/* Shell command argument quoting.1Copyright (C) 1994, 1995, 1997 Free Software Foundation, Inc.23This program is free software; you can redistribute it and/or modify4it under the terms of the GNU General Public License as published by5the Free Software Foundation; either version 2, or (at your option)6any later version.78This program is distributed in the hope that it will be useful,9but WITHOUT ANY WARRANTY; without even the implied warranty of10MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the11GNU General Public License for more details.1213You should have received a copy of the GNU General Public License14along with this program; see the file COPYING.15If not, write to the Free Software Foundation,1659 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */1718/* Written by Paul Eggert <[email protected]> */1920#if HAVE_CONFIG_H21# include <config.h>22#endif2324#include <sys/types.h>25#include <quotesys.h>2627/* Place into QUOTED a quoted version of ARG suitable for `system'.28Return the length of the resulting string (which is not null-terminated).29If QUOTED is null, return the length without any side effects. */3031size_t32quote_system_arg (quoted, arg)33char *quoted;34char const *arg;35{36char const *a;37size_t len = 0;3839/* Scan ARG, copying it to QUOTED if QUOTED is not null,40looking for shell metacharacters. */4142for (a = arg; ; a++)43{44char c = *a;45switch (c)46{47case 0:48/* ARG has no shell metacharacters. */49return len;5051case '=':52if (*arg == '-')53break;54/* Fall through. */55case '\t': case '\n': case ' ':56case '!': case '"': case '#': case '$': case '%': case '&': case '\'':57case '(': case ')': case '*': case ';':58case '<': case '>': case '?': case '[': case '\\':59case '^': case '`': case '|': case '~':60{61/* ARG has a shell metacharacter.62Start over, quoting it this time. */6364len = 0;65c = *arg++;6667/* If ARG is an option, quote just its argument.68This is not necessary, but it looks nicer. */69if (c == '-' && arg < a)70{71c = *arg++;7273if (quoted)74{75quoted[len] = '-';76quoted[len + 1] = c;77}78len += 2;7980if (c == '-')81while (arg < a)82{83c = *arg++;84if (quoted)85quoted[len] = c;86len++;87if (c == '=')88break;89}90c = *arg++;91}9293if (quoted)94quoted[len] = '\'';95len++;9697for (; c; c = *arg++)98{99if (c == '\'')100{101if (quoted)102{103quoted[len] = '\'';104quoted[len + 1] = '\\';105quoted[len + 2] = '\'';106}107len += 3;108}109if (quoted)110quoted[len] = c;111len++;112}113114if (quoted)115quoted[len] = '\'';116return len + 1;117}118}119120if (quoted)121quoted[len] = c;122len++;123}124}125126127