Blame glib/gshell.c

Packit ae235b
/* gshell.c - Shell-related utilities
Packit ae235b
 *
Packit ae235b
 *  Copyright 2000 Red Hat, Inc.
Packit ae235b
 *  g_execvpe implementation based on GNU libc execvp:
Packit ae235b
 *   Copyright 1991, 92, 95, 96, 97, 98, 99 Free Software Foundation, Inc.
Packit ae235b
 *
Packit ae235b
 * This library is free software; you can redistribute it and/or
Packit ae235b
 * modify it under the terms of the GNU Lesser General Public
Packit ae235b
 * License as published by the Free Software Foundation; either
Packit ae235b
 * version 2.1 of the License, or (at your option) any later version.
Packit ae235b
 *
Packit ae235b
 * This library is distributed in the hope that it will be useful,
Packit ae235b
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit ae235b
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Packit ae235b
 * Lesser General Public License for more details.
Packit ae235b
 *
Packit ae235b
 * You should have received a copy of the GNU Lesser General Public License
Packit ae235b
 * along with this library; if not, see <http://www.gnu.org/licenses/>.
Packit ae235b
 */
Packit ae235b
Packit ae235b
#include "config.h"
Packit ae235b
Packit ae235b
#include <string.h>
Packit ae235b
Packit ae235b
#include "gshell.h"
Packit ae235b
Packit ae235b
#include "gslist.h"
Packit ae235b
#include "gstrfuncs.h"
Packit ae235b
#include "gstring.h"
Packit ae235b
#include "gtestutils.h"
Packit ae235b
#include "glibintl.h"
Packit ae235b
#include "gthread.h"
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * SECTION:shell
Packit ae235b
 * @title: Shell-related Utilities
Packit ae235b
 * @short_description: shell-like commandline handling
Packit ae235b
 *
Packit ae235b
 * GLib provides the functions g_shell_quote() and g_shell_unquote()
Packit ae235b
 * to handle shell-like quoting in strings. The function g_shell_parse_argv()
Packit ae235b
 * parses a string similar to the way a POSIX shell (/bin/sh) would.
Packit ae235b
 *
Packit ae235b
 * Note that string handling in shells has many obscure and historical
Packit ae235b
 * corner-cases which these functions do not necessarily reproduce. They
Packit ae235b
 * are good enough in practice, though.
Packit ae235b
 */
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * G_SHELL_ERROR:
Packit ae235b
 *
Packit ae235b
 * Error domain for shell functions. Errors in this domain will be from
Packit ae235b
 * the #GShellError enumeration. See #GError for information on error
Packit ae235b
 * domains.
Packit ae235b
 **/
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * GShellError:
Packit ae235b
 * @G_SHELL_ERROR_BAD_QUOTING: Mismatched or otherwise mangled quoting.
Packit ae235b
 * @G_SHELL_ERROR_EMPTY_STRING: String to be parsed was empty.
Packit ae235b
 * @G_SHELL_ERROR_FAILED: Some other error.
Packit ae235b
 *
Packit ae235b
 * Error codes returned by shell functions.
Packit ae235b
 **/
Packit ae235b
G_DEFINE_QUARK (g-shell-error-quark, g_shell_error)
Packit ae235b
Packit ae235b
/* Single quotes preserve the literal string exactly. escape
Packit ae235b
 * sequences are not allowed; not even \' - if you want a '
Packit ae235b
 * in the quoted text, you have to do something like 'foo'\''bar'
Packit ae235b
 *
Packit ae235b
 * Double quotes allow $ ` " \ and newline to be escaped with backslash.
Packit ae235b
 * Otherwise double quotes preserve things literally.
Packit ae235b
 */
Packit ae235b
Packit ae235b
static gboolean 
Packit ae235b
unquote_string_inplace (gchar* str, gchar** end, GError** err)
Packit ae235b
{
Packit ae235b
  gchar* dest;
Packit ae235b
  gchar* s;
Packit ae235b
  gchar quote_char;
Packit ae235b
  
Packit ae235b
  g_return_val_if_fail(end != NULL, FALSE);
Packit ae235b
  g_return_val_if_fail(err == NULL || *err == NULL, FALSE);
Packit ae235b
  g_return_val_if_fail(str != NULL, FALSE);
Packit ae235b
  
Packit ae235b
  dest = s = str;
Packit ae235b
Packit ae235b
  quote_char = *s;
Packit ae235b
  
Packit ae235b
  if (!(*s == '"' || *s == '\''))
Packit ae235b
    {
Packit ae235b
      g_set_error_literal (err,
Packit ae235b
                           G_SHELL_ERROR,
Packit ae235b
                           G_SHELL_ERROR_BAD_QUOTING,
Packit ae235b
                           _("Quoted text doesn’t begin with a quotation mark"));
Packit ae235b
      *end = str;
Packit ae235b
      return FALSE;
Packit ae235b
    }
Packit ae235b
Packit ae235b
  /* Skip the initial quote mark */
Packit ae235b
  ++s;
Packit ae235b
Packit ae235b
  if (quote_char == '"')
Packit ae235b
    {
Packit ae235b
      while (*s)
Packit ae235b
        {
Packit ae235b
          g_assert(s > dest); /* loop invariant */
Packit ae235b
      
Packit ae235b
          switch (*s)
Packit ae235b
            {
Packit ae235b
            case '"':
Packit ae235b
              /* End of the string, return now */
Packit ae235b
              *dest = '\0';
Packit ae235b
              ++s;
Packit ae235b
              *end = s;
Packit ae235b
              return TRUE;
Packit ae235b
              break;
Packit ae235b
Packit ae235b
            case '\\':
Packit ae235b
              /* Possible escaped quote or \ */
Packit ae235b
              ++s;
Packit ae235b
              switch (*s)
Packit ae235b
                {
Packit ae235b
                case '"':
Packit ae235b
                case '\\':
Packit ae235b
                case '`':
Packit ae235b
                case '$':
Packit ae235b
                case '\n':
Packit ae235b
                  *dest = *s;
Packit ae235b
                  ++s;
Packit ae235b
                  ++dest;
Packit ae235b
                  break;
Packit ae235b
Packit ae235b
                default:
Packit ae235b
                  /* not an escaped char */
Packit ae235b
                  *dest = '\\';
Packit ae235b
                  ++dest;
Packit ae235b
                  /* ++s already done. */
Packit ae235b
                  break;
Packit ae235b
                }
Packit ae235b
              break;
Packit ae235b
Packit ae235b
            default:
Packit ae235b
              *dest = *s;
Packit ae235b
              ++dest;
Packit ae235b
              ++s;
Packit ae235b
              break;
Packit ae235b
            }
Packit ae235b
Packit ae235b
          g_assert(s > dest); /* loop invariant */
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
  else
Packit ae235b
    {
Packit ae235b
      while (*s)
Packit ae235b
        {
Packit ae235b
          g_assert(s > dest); /* loop invariant */
Packit ae235b
          
Packit ae235b
          if (*s == '\'')
Packit ae235b
            {
Packit ae235b
              /* End of the string, return now */
Packit ae235b
              *dest = '\0';
Packit ae235b
              ++s;
Packit ae235b
              *end = s;
Packit ae235b
              return TRUE;
Packit ae235b
            }
Packit ae235b
          else
Packit ae235b
            {
Packit ae235b
              *dest = *s;
Packit ae235b
              ++dest;
Packit ae235b
              ++s;
Packit ae235b
            }
Packit ae235b
Packit ae235b
          g_assert(s > dest); /* loop invariant */
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
  
Packit ae235b
  /* If we reach here this means the close quote was never encountered */
Packit ae235b
Packit ae235b
  *dest = '\0';
Packit ae235b
  
Packit ae235b
  g_set_error_literal (err,
Packit ae235b
                       G_SHELL_ERROR,
Packit ae235b
                       G_SHELL_ERROR_BAD_QUOTING,
Packit ae235b
                       _("Unmatched quotation mark in command line or other shell-quoted text"));
Packit ae235b
  *end = s;
Packit ae235b
  return FALSE;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_shell_quote:
Packit ae235b
 * @unquoted_string: (type filename): a literal string
Packit ae235b
 * 
Packit ae235b
 * Quotes a string so that the shell (/bin/sh) will interpret the
Packit ae235b
 * quoted string to mean @unquoted_string. If you pass a filename to
Packit ae235b
 * the shell, for example, you should first quote it with this
Packit ae235b
 * function.  The return value must be freed with g_free(). The
Packit ae235b
 * quoting style used is undefined (single or double quotes may be
Packit ae235b
 * used).
Packit ae235b
 * 
Packit ae235b
 * Returns: (type filename): quoted string
Packit ae235b
 **/
Packit ae235b
gchar*
Packit ae235b
g_shell_quote (const gchar *unquoted_string)
Packit ae235b
{
Packit ae235b
  /* We always use single quotes, because the algorithm is cheesier.
Packit ae235b
   * We could use double if we felt like it, that might be more
Packit ae235b
   * human-readable.
Packit ae235b
   */
Packit ae235b
Packit ae235b
  const gchar *p;
Packit ae235b
  GString *dest;
Packit ae235b
Packit ae235b
  g_return_val_if_fail (unquoted_string != NULL, NULL);
Packit ae235b
  
Packit ae235b
  dest = g_string_new ("'");
Packit ae235b
Packit ae235b
  p = unquoted_string;
Packit ae235b
Packit ae235b
  /* could speed this up a lot by appending chunks of text at a
Packit ae235b
   * time.
Packit ae235b
   */
Packit ae235b
  while (*p)
Packit ae235b
    {
Packit ae235b
      /* Replace literal ' with a close ', a \', and a open ' */
Packit ae235b
      if (*p == '\'')
Packit ae235b
        g_string_append (dest, "'\\''");
Packit ae235b
      else
Packit ae235b
        g_string_append_c (dest, *p);
Packit ae235b
Packit ae235b
      ++p;
Packit ae235b
    }
Packit ae235b
Packit ae235b
  /* close the quote */
Packit ae235b
  g_string_append_c (dest, '\'');
Packit ae235b
  
Packit ae235b
  return g_string_free (dest, FALSE);
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_shell_unquote:
Packit ae235b
 * @quoted_string: (type filename): shell-quoted string
Packit ae235b
 * @error: error return location or NULL
Packit ae235b
 * 
Packit ae235b
 * Unquotes a string as the shell (/bin/sh) would. Only handles
Packit ae235b
 * quotes; if a string contains file globs, arithmetic operators,
Packit ae235b
 * variables, backticks, redirections, or other special-to-the-shell
Packit ae235b
 * features, the result will be different from the result a real shell
Packit ae235b
 * would produce (the variables, backticks, etc. will be passed
Packit ae235b
 * through literally instead of being expanded). This function is
Packit ae235b
 * guaranteed to succeed if applied to the result of
Packit ae235b
 * g_shell_quote(). If it fails, it returns %NULL and sets the
Packit ae235b
 * error. The @quoted_string need not actually contain quoted or
Packit ae235b
 * escaped text; g_shell_unquote() simply goes through the string and
Packit ae235b
 * unquotes/unescapes anything that the shell would. Both single and
Packit ae235b
 * double quotes are handled, as are escapes including escaped
Packit ae235b
 * newlines. The return value must be freed with g_free(). Possible
Packit ae235b
 * errors are in the #G_SHELL_ERROR domain.
Packit ae235b
 * 
Packit ae235b
 * Shell quoting rules are a bit strange. Single quotes preserve the
Packit ae235b
 * literal string exactly. escape sequences are not allowed; not even
Packit ae235b
 * \' - if you want a ' in the quoted text, you have to do something
Packit ae235b
 * like 'foo'\''bar'.  Double quotes allow $, `, ", \, and newline to
Packit ae235b
 * be escaped with backslash. Otherwise double quotes preserve things
Packit ae235b
 * literally.
Packit ae235b
 *
Packit ae235b
 * Returns: (type filename): an unquoted string
Packit ae235b
 **/
Packit ae235b
gchar*
Packit ae235b
g_shell_unquote (const gchar *quoted_string,
Packit ae235b
                 GError     **error)
Packit ae235b
{
Packit ae235b
  gchar *unquoted;
Packit ae235b
  gchar *end;
Packit ae235b
  gchar *start;
Packit ae235b
  GString *retval;
Packit ae235b
  
Packit ae235b
  g_return_val_if_fail (quoted_string != NULL, NULL);
Packit ae235b
  
Packit ae235b
  unquoted = g_strdup (quoted_string);
Packit ae235b
Packit ae235b
  start = unquoted;
Packit ae235b
  end = unquoted;
Packit ae235b
  retval = g_string_new (NULL);
Packit ae235b
Packit ae235b
  /* The loop allows cases such as
Packit ae235b
   * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
Packit ae235b
   */
Packit ae235b
  while (*start)
Packit ae235b
    {
Packit ae235b
      /* Append all non-quoted chars, honoring backslash escape
Packit ae235b
       */
Packit ae235b
      
Packit ae235b
      while (*start && !(*start == '"' || *start == '\''))
Packit ae235b
        {
Packit ae235b
          if (*start == '\\')
Packit ae235b
            {
Packit ae235b
              /* all characters can get escaped by backslash,
Packit ae235b
               * except newline, which is removed if it follows
Packit ae235b
               * a backslash outside of quotes
Packit ae235b
               */
Packit ae235b
              
Packit ae235b
              ++start;
Packit ae235b
              if (*start)
Packit ae235b
                {
Packit ae235b
                  if (*start != '\n')
Packit ae235b
                    g_string_append_c (retval, *start);
Packit ae235b
                  ++start;
Packit ae235b
                }
Packit ae235b
            }
Packit ae235b
          else
Packit ae235b
            {
Packit ae235b
              g_string_append_c (retval, *start);
Packit ae235b
              ++start;
Packit ae235b
            }
Packit ae235b
        }
Packit ae235b
Packit ae235b
      if (*start)
Packit ae235b
        {
Packit ae235b
          if (!unquote_string_inplace (start, &end, error))
Packit ae235b
            {
Packit ae235b
              goto error;
Packit ae235b
            }
Packit ae235b
          else
Packit ae235b
            {
Packit ae235b
              g_string_append (retval, start);
Packit ae235b
              start = end;
Packit ae235b
            }
Packit ae235b
        }
Packit ae235b
    }
Packit ae235b
Packit ae235b
  g_free (unquoted);
Packit ae235b
  return g_string_free (retval, FALSE);
Packit ae235b
  
Packit ae235b
 error:
Packit ae235b
  g_assert (error == NULL || *error != NULL);
Packit ae235b
  
Packit ae235b
  g_free (unquoted);
Packit ae235b
  g_string_free (retval, TRUE);
Packit ae235b
  return NULL;
Packit ae235b
}
Packit ae235b
Packit ae235b
/* g_parse_argv() does a semi-arbitrary weird subset of the way
Packit ae235b
 * the shell parses a command line. We don't do variable expansion,
Packit ae235b
 * don't understand that operators are tokens, don't do tilde expansion,
Packit ae235b
 * don't do command substitution, no arithmetic expansion, IFS gets ignored,
Packit ae235b
 * don't do filename globs, don't remove redirection stuff, etc.
Packit ae235b
 *
Packit ae235b
 * READ THE UNIX98 SPEC on "Shell Command Language" before changing
Packit ae235b
 * the behavior of this code.
Packit ae235b
 *
Packit ae235b
 * Steps to parsing the argv string:
Packit ae235b
 *
Packit ae235b
 *  - tokenize the string (but since we ignore operators,
Packit ae235b
 *    our tokenization may diverge from what the shell would do)
Packit ae235b
 *    note that tokenization ignores the internals of a quoted
Packit ae235b
 *    word and it always splits on spaces, not on IFS even
Packit ae235b
 *    if we used IFS. We also ignore "end of input indicator"
Packit ae235b
 *    (I guess this is control-D?)
Packit ae235b
 *
Packit ae235b
 *    Tokenization steps, from UNIX98 with operator stuff removed,
Packit ae235b
 *    are:
Packit ae235b
 * 
Packit ae235b
 *    1) "If the current character is backslash, single-quote or
Packit ae235b
 *        double-quote (\, ' or ") and it is not quoted, it will affect
Packit ae235b
 *        quoting for subsequent characters up to the end of the quoted
Packit ae235b
 *        text. The rules for quoting are as described in Quoting
Packit ae235b
 *        . During token recognition no substitutions will be actually
Packit ae235b
 *        performed, and the result token will contain exactly the
Packit ae235b
 *        characters that appear in the input (except for newline
Packit ae235b
 *        character joining), unmodified, including any embedded or
Packit ae235b
 *        enclosing quotes or substitution operators, between the quote
Packit ae235b
 *        mark and the end of the quoted text. The token will not be
Packit ae235b
 *        delimited by the end of the quoted field."
Packit ae235b
 *
Packit ae235b
 *    2) "If the current character is an unquoted newline character,
Packit ae235b
 *        the current token will be delimited."
Packit ae235b
 *
Packit ae235b
 *    3) "If the current character is an unquoted blank character, any
Packit ae235b
 *        token containing the previous character is delimited and the
Packit ae235b
 *        current character will be discarded."
Packit ae235b
 *
Packit ae235b
 *    4) "If the previous character was part of a word, the current
Packit ae235b
 *        character will be appended to that word."
Packit ae235b
 *
Packit ae235b
 *    5) "If the current character is a "#", it and all subsequent
Packit ae235b
 *        characters up to, but excluding, the next newline character
Packit ae235b
 *        will be discarded as a comment. The newline character that
Packit ae235b
 *        ends the line is not considered part of the comment. The
Packit ae235b
 *        "#" starts a comment only when it is at the beginning of a
Packit ae235b
 *        token. Since the search for the end-of-comment does not
Packit ae235b
 *        consider an escaped newline character specially, a comment
Packit ae235b
 *        cannot be continued to the next line."
Packit ae235b
 *
Packit ae235b
 *    6) "The current character will be used as the start of a new word."
Packit ae235b
 *
Packit ae235b
 *
Packit ae235b
 *  - for each token (word), perform portions of word expansion, namely
Packit ae235b
 *    field splitting (using default whitespace IFS) and quote
Packit ae235b
 *    removal.  Field splitting may increase the number of words.
Packit ae235b
 *    Quote removal does not increase the number of words.
Packit ae235b
 *
Packit ae235b
 *   "If the complete expansion appropriate for a word results in an
Packit ae235b
 *   empty field, that empty field will be deleted from the list of
Packit ae235b
 *   fields that form the completely expanded command, unless the
Packit ae235b
 *   original word contained single-quote or double-quote characters."
Packit ae235b
 *    - UNIX98 spec
Packit ae235b
 *
Packit ae235b
 *
Packit ae235b
 */
Packit ae235b
Packit ae235b
static inline void
Packit ae235b
ensure_token (GString **token)
Packit ae235b
{
Packit ae235b
  if (*token == NULL)
Packit ae235b
    *token = g_string_new (NULL);
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
delimit_token (GString **token,
Packit ae235b
               GSList **retval)
Packit ae235b
{
Packit ae235b
  if (*token == NULL)
Packit ae235b
    return;
Packit ae235b
Packit ae235b
  *retval = g_slist_prepend (*retval, g_string_free (*token, FALSE));
Packit ae235b
Packit ae235b
  *token = NULL;
Packit ae235b
}
Packit ae235b
Packit ae235b
static GSList*
Packit ae235b
tokenize_command_line (const gchar *command_line,
Packit ae235b
                       GError **error)
Packit ae235b
{
Packit ae235b
  gchar current_quote;
Packit ae235b
  const gchar *p;
Packit ae235b
  GString *current_token = NULL;
Packit ae235b
  GSList *retval = NULL;
Packit ae235b
  gboolean quoted;
Packit ae235b
Packit ae235b
  current_quote = '\0';
Packit ae235b
  quoted = FALSE;
Packit ae235b
  p = command_line;
Packit ae235b
 
Packit ae235b
  while (*p)
Packit ae235b
    {
Packit ae235b
      if (current_quote == '\\')
Packit ae235b
        {
Packit ae235b
          if (*p == '\n')
Packit ae235b
            {
Packit ae235b
              /* we append nothing; backslash-newline become nothing */
Packit ae235b
            }
Packit ae235b
          else
Packit ae235b
            {
Packit ae235b
              /* we append the backslash and the current char,
Packit ae235b
               * to be interpreted later after tokenization
Packit ae235b
               */
Packit ae235b
              ensure_token (&current_token);
Packit ae235b
              g_string_append_c (current_token, '\\');
Packit ae235b
              g_string_append_c (current_token, *p);
Packit ae235b
            }
Packit ae235b
Packit ae235b
          current_quote = '\0';
Packit ae235b
        }
Packit ae235b
      else if (current_quote == '#')
Packit ae235b
        {
Packit ae235b
          /* Discard up to and including next newline */
Packit ae235b
          while (*p && *p != '\n')
Packit ae235b
            ++p;
Packit ae235b
Packit ae235b
          current_quote = '\0';
Packit ae235b
          
Packit ae235b
          if (*p == '\0')
Packit ae235b
            break;
Packit ae235b
        }
Packit ae235b
      else if (current_quote)
Packit ae235b
        {
Packit ae235b
          if (*p == current_quote &&
Packit ae235b
              /* check that it isn't an escaped double quote */
Packit ae235b
              !(current_quote == '"' && quoted))
Packit ae235b
            {
Packit ae235b
              /* close the quote */
Packit ae235b
              current_quote = '\0';
Packit ae235b
            }
Packit ae235b
Packit ae235b
          /* Everything inside quotes, and the close quote,
Packit ae235b
           * gets appended literally.
Packit ae235b
           */
Packit ae235b
Packit ae235b
          ensure_token (&current_token);
Packit ae235b
          g_string_append_c (current_token, *p);
Packit ae235b
        }
Packit ae235b
      else
Packit ae235b
        {
Packit ae235b
          switch (*p)
Packit ae235b
            {
Packit ae235b
            case '\n':
Packit ae235b
              delimit_token (&current_token, &retval);
Packit ae235b
              break;
Packit ae235b
Packit ae235b
            case ' ':
Packit ae235b
            case '\t':
Packit ae235b
              /* If the current token contains the previous char, delimit
Packit ae235b
               * the current token. A nonzero length
Packit ae235b
               * token should always contain the previous char.
Packit ae235b
               */
Packit ae235b
              if (current_token &&
Packit ae235b
                  current_token->len > 0)
Packit ae235b
                {
Packit ae235b
                  delimit_token (&current_token, &retval);
Packit ae235b
                }
Packit ae235b
              
Packit ae235b
              /* discard all unquoted blanks (don't add them to a token) */
Packit ae235b
              break;
Packit ae235b
Packit ae235b
Packit ae235b
              /* single/double quotes are appended to the token,
Packit ae235b
               * escapes are maybe appended next time through the loop,
Packit ae235b
               * comment chars are never appended.
Packit ae235b
               */
Packit ae235b
              
Packit ae235b
            case '\'':
Packit ae235b
            case '"':
Packit ae235b
              ensure_token (&current_token);
Packit ae235b
              g_string_append_c (current_token, *p);
Packit ae235b
Packit ae235b
              /* FALL THRU */
Packit ae235b
            case '\\':
Packit ae235b
              current_quote = *p;
Packit ae235b
              break;
Packit ae235b
Packit ae235b
            case '#':
Packit ae235b
              if (p == command_line)
Packit ae235b
	        { /* '#' was the first char */
Packit ae235b
                  current_quote = *p;
Packit ae235b
                  break;
Packit ae235b
                }
Packit ae235b
              switch(*(p-1))
Packit ae235b
                {
Packit ae235b
                  case ' ':
Packit ae235b
                  case '\n':
Packit ae235b
                  case '\0':
Packit ae235b
                    current_quote = *p;
Packit ae235b
                    break;
Packit ae235b
                  default:
Packit ae235b
                    ensure_token (&current_token);
Packit ae235b
                    g_string_append_c (current_token, *p);
Packit ae235b
		    break;
Packit ae235b
                }
Packit ae235b
              break;
Packit ae235b
Packit ae235b
            default:
Packit ae235b
              /* Combines rules 4) and 6) - if we have a token, append to it,
Packit ae235b
               * otherwise create a new token.
Packit ae235b
               */
Packit ae235b
              ensure_token (&current_token);
Packit ae235b
              g_string_append_c (current_token, *p);
Packit ae235b
              break;
Packit ae235b
            }
Packit ae235b
        }
Packit ae235b
Packit ae235b
      /* We need to count consecutive backslashes mod 2, 
Packit ae235b
       * to detect escaped doublequotes.
Packit ae235b
       */
Packit ae235b
      if (*p != '\\')
Packit ae235b
	quoted = FALSE;
Packit ae235b
      else
Packit ae235b
	quoted = !quoted;
Packit ae235b
Packit ae235b
      ++p;
Packit ae235b
    }
Packit ae235b
Packit ae235b
  delimit_token (&current_token, &retval);
Packit ae235b
Packit ae235b
  if (current_quote)
Packit ae235b
    {
Packit ae235b
      if (current_quote == '\\')
Packit ae235b
        g_set_error (error,
Packit ae235b
                     G_SHELL_ERROR,
Packit ae235b
                     G_SHELL_ERROR_BAD_QUOTING,
Packit ae235b
                     _("Text ended just after a “\\” character."
Packit ae235b
                       " (The text was “%s”)"),
Packit ae235b
                     command_line);
Packit ae235b
      else
Packit ae235b
        g_set_error (error,
Packit ae235b
                     G_SHELL_ERROR,
Packit ae235b
                     G_SHELL_ERROR_BAD_QUOTING,
Packit ae235b
                     _("Text ended before matching quote was found for %c."
Packit ae235b
                       " (The text was “%s”)"),
Packit ae235b
                     current_quote, command_line);
Packit ae235b
      
Packit ae235b
      goto error;
Packit ae235b
    }
Packit ae235b
Packit ae235b
  if (retval == NULL)
Packit ae235b
    {
Packit ae235b
      g_set_error_literal (error,
Packit ae235b
                           G_SHELL_ERROR,
Packit ae235b
                           G_SHELL_ERROR_EMPTY_STRING,
Packit ae235b
                           _("Text was empty (or contained only whitespace)"));
Packit ae235b
Packit ae235b
      goto error;
Packit ae235b
    }
Packit ae235b
  
Packit ae235b
  /* we appended backward */
Packit ae235b
  retval = g_slist_reverse (retval);
Packit ae235b
Packit ae235b
  return retval;
Packit ae235b
Packit ae235b
 error:
Packit ae235b
  g_assert (error == NULL || *error != NULL);
Packit ae235b
Packit ae235b
  g_slist_free_full (retval, g_free);
Packit ae235b
Packit ae235b
  return NULL;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_shell_parse_argv:
Packit ae235b
 * @command_line: (type filename): command line to parse
Packit ae235b
 * @argcp: (out) (optional): return location for number of args
Packit ae235b
 * @argvp: (out) (optional) (array length=argcp zero-terminated=1) (element-type filename):
Packit ae235b
 *   return location for array of args
Packit ae235b
 * @error: (optional): return location for error
Packit ae235b
 * 
Packit ae235b
 * Parses a command line into an argument vector, in much the same way
Packit ae235b
 * the shell would, but without many of the expansions the shell would
Packit ae235b
 * perform (variable expansion, globs, operators, filename expansion,
Packit ae235b
 * etc. are not supported). The results are defined to be the same as
Packit ae235b
 * those you would get from a UNIX98 /bin/sh, as long as the input
Packit ae235b
 * contains none of the unsupported shell expansions. If the input
Packit ae235b
 * does contain such expansions, they are passed through
Packit ae235b
 * literally. Possible errors are those from the #G_SHELL_ERROR
Packit ae235b
 * domain. Free the returned vector with g_strfreev().
Packit ae235b
 * 
Packit ae235b
 * Returns: %TRUE on success, %FALSE if error set
Packit ae235b
 **/
Packit ae235b
gboolean
Packit ae235b
g_shell_parse_argv (const gchar *command_line,
Packit ae235b
                    gint        *argcp,
Packit ae235b
                    gchar     ***argvp,
Packit ae235b
                    GError     **error)
Packit ae235b
{
Packit ae235b
  /* Code based on poptParseArgvString() from libpopt */
Packit ae235b
  gint argc = 0;
Packit ae235b
  gchar **argv = NULL;
Packit ae235b
  GSList *tokens = NULL;
Packit ae235b
  gint i;
Packit ae235b
  GSList *tmp_list;
Packit ae235b
  
Packit ae235b
  g_return_val_if_fail (command_line != NULL, FALSE);
Packit ae235b
Packit ae235b
  tokens = tokenize_command_line (command_line, error);
Packit ae235b
  if (tokens == NULL)
Packit ae235b
    return FALSE;
Packit ae235b
Packit ae235b
  /* Because we can't have introduced any new blank space into the
Packit ae235b
   * tokens (we didn't do any new expansions), we don't need to
Packit ae235b
   * perform field splitting. If we were going to honor IFS or do any
Packit ae235b
   * expansions, we would have to do field splitting on each word
Packit ae235b
   * here. Also, if we were going to do any expansion we would need to
Packit ae235b
   * remove any zero-length words that didn't contain quotes
Packit ae235b
   * originally; but since there's no expansion we know all words have
Packit ae235b
   * nonzero length, unless they contain quotes.
Packit ae235b
   * 
Packit ae235b
   * So, we simply remove quotes, and don't do any field splitting or
Packit ae235b
   * empty word removal, since we know there was no way to introduce
Packit ae235b
   * such things.
Packit ae235b
   */
Packit ae235b
Packit ae235b
  argc = g_slist_length (tokens);
Packit ae235b
  argv = g_new0 (gchar*, argc + 1);
Packit ae235b
  i = 0;
Packit ae235b
  tmp_list = tokens;
Packit ae235b
  while (tmp_list)
Packit ae235b
    {
Packit ae235b
      argv[i] = g_shell_unquote (tmp_list->data, error);
Packit ae235b
Packit ae235b
      /* Since we already checked that quotes matched up in the
Packit ae235b
       * tokenizer, this shouldn't be possible to reach I guess.
Packit ae235b
       */
Packit ae235b
      if (argv[i] == NULL)
Packit ae235b
        goto failed;
Packit ae235b
Packit ae235b
      tmp_list = g_slist_next (tmp_list);
Packit ae235b
      ++i;
Packit ae235b
    }
Packit ae235b
  
Packit ae235b
  g_slist_free_full (tokens, g_free);
Packit ae235b
  
Packit ae235b
  if (argcp)
Packit ae235b
    *argcp = argc;
Packit ae235b
Packit ae235b
  if (argvp)
Packit ae235b
    *argvp = argv;
Packit ae235b
  else
Packit ae235b
    g_strfreev (argv);
Packit ae235b
Packit ae235b
  return TRUE;
Packit ae235b
Packit ae235b
 failed:
Packit ae235b
Packit ae235b
  g_assert (error == NULL || *error != NULL);
Packit ae235b
  g_strfreev (argv);
Packit ae235b
  g_slist_free_full (tokens, g_free);
Packit ae235b
  
Packit ae235b
  return FALSE;
Packit ae235b
}