1 /***********************************************************************
3 * This software is part of the ast package *
4 * Copyright (c) 1985-2010 AT&T Intellectual Property *
5 * and is licensed under the *
6 * Common Public License, Version 1.0 *
7 * by AT&T Intellectual Property *
9 * A copy of the License is available at *
10 * http://www.opensource.org/licenses/cpl1.0.txt *
11 * (with md5 checksum 059e8cd6165cb4c31e351f2b69388fd9) *
13 * Information and Software Systems Research *
17 * Glenn Fowler <gsf@research.att.com> *
18 * David Korn <dgk@research.att.com> *
19 * Phong Vo <kpv@research.att.com> *
21 ***********************************************************************/
27 * return string with expanded escape chars
35 * quote string as of length n with qb...qe
36 * (flags&FMT_ALWAYS) always quotes, otherwise quote output only if necessary
37 * qe and the usual suspects are \... escaped
38 * (flags&FMT_WIDE) doesn't escape 8 bit chars
39 * (flags&FMT_ESCAPED) doesn't \... escape the usual suspects
40 * (flags&FMT_SHELL) escape $`"#;~&|()<>[]*?
44 fmtquote(const char* as
, const char* qb
, const char* qe
, size_t n
, int flags
)
46 register unsigned char* s
= (unsigned char*)as
;
47 register unsigned char* e
= s
+ n
;
52 register int doublequote
;
53 register int singlequote
;
60 c
+= strlen((char*)qb
);
62 c
+= strlen((char*)qe
);
69 if (qb
[0] == '$' && qb
[1] == '\'' && qb
[2] == 0)
71 else if ((flags
& FMT_SHELL
) && qb
[1] == 0)
75 else if (qb
[0] == '\'')
81 else if (flags
& FMT_SHELL
)
84 escaped
= spaced
= !!(flags
& FMT_ALWAYS
);
87 if ((c
= mbsize(s
)) > 1)
95 if (!(flags
& FMT_ESCAPED
) && (iscntrl(c
) || !isprint(c
) || c
== '\\'))
128 if (!(flags
& FMT_WIDE
) || !(c
& 0200))
130 *b
++ = '0' + ((c
>> 6) & 07);
131 *b
++ = '0' + ((c
>> 3) & 07);
146 else if (qe
&& strchr(qe
, c
))
148 if (singlequote
&& c
== '\'')
162 else if (c
== '$' || c
== '`')
164 if (c
== '$' && (flags
& FMT_PARAM
) && (*s
== '{' || *s
== '('))
166 if (singlequote
|| shell
)
186 else if (doublequote
)
188 else if (singlequote
|| (flags
& FMT_SHELL
))
191 else if (!spaced
&& !escaped
&& (isspace(c
) || ((flags
& FMT_SHELL
) || shell
) && (strchr("\";~&|()<>[]*?", c
) || c
== '#' && (b
== f
|| isspace(*(b
- 1))))))
199 buf
+= shell
+ !spaced
;
200 if (qe
&& (escaped
|| spaced
))
209 * escape the usual suspects and quote chars in qs
210 * in length n string as
214 fmtnesq(const char* as
, const char* qs
, size_t n
)
216 return fmtquote(as
, NiL
, qs
, n
, 0);
220 * escape the usual suspects and quote chars in qs
224 fmtesq(const char* as
, const char* qs
)
226 return fmtquote(as
, NiL
, qs
, strlen((char*)as
), 0);
230 * escape the usual suspects
234 fmtesc(const char* as
)
236 return fmtquote(as
, NiL
, NiL
, strlen((char*)as
), 0);