1 /* Shell quoting. 2 Copyright (C) 2001-2004, 2006 Free Software Foundation, Inc. 3 Written by Bruno Haible <haible@clisp.cons.org>, 2001. 4 5 This program is free software; you can redistribute it and/or modify 6 it under the terms of the GNU General Public License as published by 7 the Free Software Foundation; either version 2, or (at your option) 8 any later version. 9 10 This program is distributed in the hope that it will be useful, 11 but WITHOUT ANY WARRANTY; without even the implied warranty of 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 GNU General Public License for more details. 14 15 You should have received a copy of the GNU General Public License 16 along with this program; if not, write to the Free Software Foundation, 17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ 18 19 #include <config.h> 20 21 /* Specification. */ 22 #include "sh-quote.h" 23 24 #include <string.h> 25 26 #include "quotearg.h" 27 #include "xalloc.h" 28 29 /* Describes quoting for sh compatible shells. */ 30 static struct quoting_options *sh_quoting_options; 31 32 /* Initializes the sh_quoting_options variable. */ 33 static void 34 init_sh_quoting_options () 35 { 36 sh_quoting_options = clone_quoting_options (NULL); 37 set_quoting_style (sh_quoting_options, shell_quoting_style); 38 } 39 40 /* Returns the number of bytes needed for the quoted string. */ 41 size_t 42 shell_quote_length (const char *string) 43 { 44 if (sh_quoting_options == NULL) 45 init_sh_quoting_options (); 46 return quotearg_buffer (NULL, 0, string, strlen (string), 47 sh_quoting_options); 48 } 49 50 /* Copies the quoted string to p and returns the incremented p. 51 There must be room for shell_quote_length (string) + 1 bytes at p. */ 52 char * 53 shell_quote_copy (char *p, const char *string) 54 { 55 if (sh_quoting_options == NULL) 56 init_sh_quoting_options (); 57 return p + quotearg_buffer (p, (size_t)(-1), string, strlen (string), 58 sh_quoting_options); 59 } 60 61 /* Returns the freshly allocated quoted string. */ 62 char * 63 shell_quote (const char *string) 64 { 65 if (sh_quoting_options == NULL) 66 init_sh_quoting_options (); 67 return quotearg_alloc (string, strlen (string), sh_quoting_options); 68 } 69 70 /* Returns a freshly allocated string containing all argument strings, quoted, 71 separated through spaces. */ 72 char * 73 shell_quote_argv (char **argv) 74 { 75 if (*argv != NULL) 76 { 77 char **argp; 78 size_t length; 79 char *command; 80 char *p; 81 82 length = 0; 83 for (argp = argv; ; ) 84 { 85 length += shell_quote_length (*argp) + 1; 86 argp++; 87 if (*argp == NULL) 88 break; 89 } 90 91 command = (char *) xmalloc (length); 92 93 p = command; 94 for (argp = argv; ; ) 95 { 96 p = shell_quote_copy (p, *argp); 97 argp++; 98 if (*argp == NULL) 99 break; 100 *p++ = ' '; 101 } 102 *p = '\0'; 103 104 return command; 105 } 106 else 107 return xstrdup (""); 108 } 109