Add n_idec_{buf,cp}()
[s-mailx.git] / shexp.c
bloba9d8bcc411953b094d4b684c493c848a8b970d00
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Shell "word", file- and other name expansions, incl. file globbing.
3 *@ TODO v15: peek signal states while opendir/readdir/etc.
5 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
6 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
7 */
8 /*
9 * Copyright (c) 1980, 1993
10 * The Regents of the University of California. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
36 #undef n_FILE
37 #define n_FILE shexp
39 #ifndef HAVE_AMALGAMATION
40 # include "nail.h"
41 #endif
43 #include <sys/wait.h>
45 #include <pwd.h>
47 #ifdef HAVE_FNMATCH
48 # include <dirent.h>
49 # include <fnmatch.h>
50 #endif
52 /* POSIX says
53 * Environment variable names used by the utilities in the Shell and
54 * Utilities volume of POSIX.1-2008 consist solely of uppercase
55 * letters, digits, and the <underscore> ('_') from the characters
56 * defined in Portable Character Set and do not begin with a digit.
57 * Other characters may be permitted by an implementation;
58 * applications shall tolerate the presence of such names.
59 * We do support the hyphen "-" because it is common for mailx.
60 * We support some special parameter names for one-letter variable names;
61 * note these have counterparts in the code that manages internal variables! */
62 #define a_SHEXP_ISVARC(C) (alnumchar(C) || (C) == '_' || (C) == '-')
63 #define a_SHEXP_ISVARC_SPECIAL1(C) \
64 ((C) == '*' || (C) == '@' || (C) == '#' || (C) == '?')
66 enum a_shexp_quote_flags{
67 a_SHEXP_QUOTE_NONE,
68 a_SHEXP_QUOTE_ROUNDTRIP = 1u<<0, /* Result won't be consumed immediately */
70 a_SHEXP_QUOTE_T_REVSOL = 1u<<8, /* Type: by reverse solidus */
71 a_SHEXP_QUOTE_T_SINGLE = 1u<<9, /* Type: single-quotes */
72 a_SHEXP_QUOTE_T_DOUBLE = 1u<<10, /* Type: double-quotes */
73 a_SHEXP_QUOTE_T_DOLLAR = 1u<<11, /* Type: dollar-single-quotes */
74 a_SHEXP_QUOTE_T_MASK = a_SHEXP_QUOTE_T_REVSOL | a_SHEXP_QUOTE_T_SINGLE |
75 a_SHEXP_QUOTE_T_DOUBLE | a_SHEXP_QUOTE_T_DOLLAR,
77 a_SHEXP_QUOTE__FREESHIFT = 16u
80 #ifdef HAVE_FNMATCH
81 struct a_shexp_glob_ctx{
82 char const *sgc_patdat; /* Remaining pattern (at and below level) */
83 size_t sgc_patlen;
84 struct n_string *sgc_outer; /* Resolved path up to this level */
85 ui32_t sgc_flags;
86 ui8_t sgc__dummy[4];
88 #endif
90 struct a_shexp_quote_ctx{
91 struct n_string *sqc_store; /* Result storage */
92 struct str sqc_input; /* Input data, topmost level */
93 ui32_t sqc_cnt_revso;
94 ui32_t sqc_cnt_single;
95 ui32_t sqc_cnt_double;
96 ui32_t sqc_cnt_dollar;
97 enum a_shexp_quote_flags sqc_flags;
98 ui8_t sqc__dummy[4];
101 struct a_shexp_quote_lvl{
102 struct a_shexp_quote_lvl *sql_link; /* Outer level */
103 struct str sql_dat; /* This level (has to) handle(d) */
104 enum a_shexp_quote_flags sql_flags;
105 ui8_t sql__dummy[4];
108 /* Locate the user's mailbox file (where new, unread mail is queued) */
109 static char *a_shexp_findmail(char const *user, bool_t force);
111 /* Expand ^~/? and ^~USER/? constructs.
112 * Returns the completely resolved (maybe empty or identical to input)
113 * salloc()ed string */
114 static char *a_shexp_tilde(char const *s);
116 /* Perform fnmatch(3). May return NULL on error */
117 static char *a_shexp_globname(char const *name, enum fexp_mode fexpm);
118 #ifdef HAVE_FNMATCH
119 static bool_t a_shexp__glob(struct a_shexp_glob_ctx *sgcp,
120 struct n_strlist **slpp);
121 static int a_shexp__globsort(void const *cvpa, void const *cvpb);
122 #endif
124 /* Parse an input string and create a sh(1)ell-quoted result */
125 static void a_shexp__quote(struct a_shexp_quote_ctx *sqcp,
126 struct a_shexp_quote_lvl *sqlp);
128 static char *
129 a_shexp_findmail(char const *user, bool_t force){
130 char *rv;
131 char const *cp;
132 NYD2_ENTER;
134 if(!force){
135 if((cp = ok_vlook(inbox)) != NULL && *cp != '\0'){
136 /* Folder extra introduced to avoid % recursion loops */
137 if((rv = fexpand(cp, FEXP_NSPECIAL | FEXP_NFOLDER | FEXP_NSHELL)
138 ) != NULL)
139 goto jleave;
140 n_err(_("*inbox* expansion failed, using $MAIL / builtin: %s\n"), cp);
143 if((cp = ok_vlook(MAIL)) != NULL){
144 rv = savestr(cp);
145 goto jleave;
149 /* C99 */{
150 size_t ul, i;
152 ul = strlen(user) +1;
153 i = sizeof(VAL_MAIL) -1 + 1 + ul;
155 rv = salloc(i);
156 memcpy(rv, VAL_MAIL, (i = sizeof(VAL_MAIL) -1));
157 rv[i] = '/';
158 memcpy(&rv[++i], user, ul);
160 jleave:
161 NYD2_LEAVE;
162 return rv;
165 static char *
166 a_shexp_tilde(char const *s){
167 struct passwd *pwp;
168 size_t nl, rl;
169 char const *rp, *np;
170 char *rv;
171 NYD2_ENTER;
173 if(*(rp = &s[1]) == '/' || *rp == '\0'){
174 np = ok_vlook(HOME);
175 rl = strlen(rp);
176 }else{
177 if((rp = strchr(np = rp, '/')) != NULL){
178 nl = PTR2SIZE(rp - np);
179 np = savestrbuf(np, nl);
180 rl = strlen(rp);
181 }else
182 rl = 0;
184 if((pwp = getpwnam(np)) == NULL){
185 rv = savestr(s);
186 goto jleave;
188 np = pwp->pw_dir;
191 nl = strlen(np);
192 rv = salloc(nl + 1 + rl +1);
193 memcpy(rv, np, nl);
194 if(rl > 0){
195 memcpy(rv + nl, rp, rl);
196 nl += rl;
198 rv[nl] = '\0';
199 jleave:
200 NYD2_LEAVE;
201 return rv;
204 static char *
205 a_shexp_globname(char const *name, enum fexp_mode fexpm){
206 #ifdef HAVE_FNMATCH
207 struct a_shexp_glob_ctx sgc;
208 struct n_string outer;
209 struct n_strlist *slp;
210 char *cp;
211 NYD_ENTER;
213 memset(&sgc, 0, sizeof sgc);
214 sgc.sgc_patlen = strlen(name);
215 sgc.sgc_patdat = savestrbuf(name, sgc.sgc_patlen);
216 sgc.sgc_outer = n_string_reserve(n_string_creat(&outer), sgc.sgc_patlen);
217 sgc.sgc_flags = ((fexpm & FEXP_SILENT) != 0);
218 slp = NULL;
219 if(a_shexp__glob(&sgc, &slp))
220 cp = (char*)1;
221 else
222 cp = NULL;
223 n_string_gut(&outer);
225 if(cp == NULL)
226 goto jleave;
228 if(slp == NULL){
229 cp = n_UNCONST(N_("File pattern does not match"));
230 goto jerr;
231 }else if(slp->sl_next == NULL)
232 cp = savestrbuf(slp->sl_dat, slp->sl_len);
233 else if(fexpm & FEXP_MULTIOK){
234 struct n_strlist **sorta, *xslp;
235 size_t i, no, l;
237 no = l = 0;
238 for(xslp = slp; xslp != NULL; xslp = xslp->sl_next){
239 ++no;
240 l += xslp->sl_len + 1;
243 sorta = smalloc(sizeof(*sorta) * no);
244 no = 0;
245 for(xslp = slp; xslp != NULL; xslp = xslp->sl_next)
246 sorta[no++] = xslp;
247 qsort(sorta, no, sizeof *sorta, &a_shexp__globsort);
249 cp = salloc(++l);
250 l = 0;
251 for(i = 0; i < no; ++i){
252 xslp = sorta[i];
253 memcpy(&cp[l], xslp->sl_dat, xslp->sl_len);
254 l += xslp->sl_len;
255 cp[l++] = '\0';
257 cp[l] = '\0';
259 free(sorta);
260 n_pstate |= n_PS_EXPAND_MULTIRESULT;
261 }else{
262 cp = n_UNCONST(N_("File pattern matches multiple results"));
263 goto jerr;
266 jleave:
267 while(slp != NULL){
268 struct n_strlist *tmp = slp;
270 slp = slp->sl_next;
271 free(tmp);
273 NYD_LEAVE;
274 return cp;
276 jerr:
277 if(!(fexpm & FEXP_SILENT)){
278 name = n_shexp_quote_cp(name, FAL0);
279 n_err("%s: %s\n", V_(cp), name);
281 cp = NULL;
282 goto jleave;
284 #else /* HAVE_FNMATCH */
285 n_UNUSED(fexpm);
287 if(!(fexpm & FEXP_SILENT))
288 n_err(_("No filename pattern (fnmatch(3)) support compiled in\n"));
289 return savestr(name);
290 #endif
293 #ifdef HAVE_FNMATCH
294 static bool_t
295 a_shexp__glob(struct a_shexp_glob_ctx *sgcp, struct n_strlist **slpp){
296 enum{a_SILENT = 1<<0, a_DEEP=1<<1, a_SALLOC=1<<2};
298 struct a_shexp_glob_ctx nsgc;
299 struct dirent *dep;
300 DIR *dp;
301 size_t old_outerlen;
302 char const *ccp, *myp;
303 NYD2_ENTER;
305 /* We need some special treatment for the outermost level */
306 if(!(sgcp->sgc_flags & a_DEEP)){
307 if(sgcp->sgc_patlen > 0 && sgcp->sgc_patdat[0] == '/'){
308 myp = n_string_cp(n_string_push_c(sgcp->sgc_outer, '/'));
309 ++sgcp->sgc_patdat;
310 --sgcp->sgc_patlen;
311 }else
312 myp = "./";
313 }else
314 myp = n_string_cp(sgcp->sgc_outer);
315 old_outerlen = sgcp->sgc_outer->s_len;
317 /* Separate current directory/pattern level from any possible remaining
318 * pattern in order to be able to use it for fnmatch(3) */
319 if((ccp = memchr(sgcp->sgc_patdat, '/', sgcp->sgc_patlen)) == NULL)
320 nsgc.sgc_patlen = 0;
321 else{
322 nsgc = *sgcp;
323 nsgc.sgc_flags |= a_DEEP;
324 sgcp->sgc_patlen = PTR2SIZE((nsgc.sgc_patdat = &ccp[1]) -
325 &sgcp->sgc_patdat[0]);
326 nsgc.sgc_patlen -= sgcp->sgc_patlen;
327 /* Trim solidus */
328 if(sgcp->sgc_patlen > 0){
329 assert(sgcp->sgc_patdat[sgcp->sgc_patlen -1] == '/');
330 ((char*)n_UNCONST(sgcp->sgc_patdat))[--sgcp->sgc_patlen] = '\0';
334 /* Our current directory level */
335 /* xxx Plenty of room for optimizations, like quickshot lstat(2) which may
336 * xxx be the (sole) result depending on pattern surroundings, etc. */
337 if((dp = opendir(myp)) == NULL){
338 int err;
340 switch((err = errno)){
341 case ENOTDIR:
342 ccp = N_("cannot access paths under non-directory");
343 goto jerr;
344 case ENOENT:
345 ccp = N_("path component of (sub)pattern non-existent");
346 goto jerr;
347 case EACCES:
348 ccp = N_("file permission for file (sub)pattern denied");
349 goto jerr;
350 default:
351 ccp = N_("cannot handle file (sub)pattern");
352 goto jerr;
356 /* As necessary, quote bytes in the current pattern */
357 /* C99 */{
358 char *ncp;
359 size_t i;
360 bool_t need;
362 for(need = FAL0, i = 0, myp = sgcp->sgc_patdat; *myp != '\0'; ++myp)
363 switch(*myp){
364 case '\'': case '"': case '\\': case '$':
365 case ' ': case '\t':
366 need = TRU1;
367 ++i;
368 /* FALLTHRU */
369 default:
370 ++i;
371 break;
374 if(need){
375 ncp = salloc(i +1);
376 for(i = 0, myp = sgcp->sgc_patdat; *myp != '\0'; ++myp)
377 switch(*myp){
378 case '\'': case '"': case '\\': case '$':
379 case ' ': case '\t':
380 ncp[i++] = '\\';
381 /* FALLTHRU */
382 default:
383 ncp[i++] = *myp;
384 break;
386 ncp[i] = '\0';
387 myp = ncp;
388 }else
389 myp = sgcp->sgc_patdat;
392 while((dep = readdir(dp)) != NULL){
393 switch(fnmatch(myp, dep->d_name, FNM_PATHNAME | FNM_PERIOD)){
394 case 0:{
395 /* A match expresses the desire to recurse if there is more pattern */
396 if(nsgc.sgc_patlen > 0){
397 bool_t isdir;
399 n_string_push_cp((sgcp->sgc_outer->s_len > 1
400 ? n_string_push_c(sgcp->sgc_outer, '/') : sgcp->sgc_outer),
401 dep->d_name);
403 isdir = FAL0;
404 #ifdef HAVE_DIRENT_TYPE
405 if(dep->d_type == DT_DIR)
406 isdir = TRU1;
407 else if(dep->d_type == DT_LNK || dep->d_type == DT_UNKNOWN)
408 #endif
410 struct stat sb;
412 if(stat(n_string_cp(sgcp->sgc_outer), &sb)){
413 ccp = N_("I/O error when querying file status");
414 goto jerr;
415 }else if(S_ISDIR(sb.st_mode))
416 isdir = TRU1;
419 /* TODO We recurse with current dir FD open, which could E[MN]FILE!
420 * TODO Instead save away a list of such n_string's for later */
421 if(isdir && !a_shexp__glob(&nsgc, slpp)){
422 ccp = (char*)1;
423 goto jleave;
426 n_string_trunc(sgcp->sgc_outer, old_outerlen);
427 }else{
428 struct n_strlist *slp;
429 size_t i, j;
431 i = strlen(dep->d_name);
432 j = (old_outerlen > 0) ? old_outerlen + 1 + i : i;
433 slp = n_STRLIST_MALLOC(j);
434 *slpp = slp;
435 slpp = &slp->sl_next;
436 slp->sl_next = NULL;
437 if((j = old_outerlen) > 0){
438 memcpy(&slp->sl_dat[0], sgcp->sgc_outer->s_dat, j);
439 if(slp->sl_dat[j -1] != '/')
440 slp->sl_dat[j++] = '/';
442 memcpy(&slp->sl_dat[j], dep->d_name, i);
443 slp->sl_dat[j += i] = '\0';
444 slp->sl_len = j;
446 } break;
447 case FNM_NOMATCH:
448 break;
449 default:
450 ccp = N_("fnmatch(3) cannot handle file (sub)pattern");
451 goto jerr;
455 ccp = NULL;
456 jleave:
457 if(dp != NULL)
458 closedir(dp);
459 NYD2_LEAVE;
460 return (ccp == NULL);
462 jerr:
463 if(!(sgcp->sgc_flags & a_SILENT)){
464 char const *s2, *s3;
466 if(sgcp->sgc_outer->s_len > 0){
467 s2 = n_shexp_quote_cp(n_string_cp(sgcp->sgc_outer), FAL0);
468 s3 = "/";
469 }else
470 s2 = s3 = n_empty;
472 n_err("%s: %s%s%s\n", V_(ccp), s2, s3,
473 n_shexp_quote_cp(sgcp->sgc_patdat, FAL0));
475 goto jleave;
478 static int
479 a_shexp__globsort(void const *cvpa, void const *cvpb){
480 int rv;
481 struct n_strlist const * const *slpa, * const *slpb;
482 NYD2_ENTER;
484 slpa = cvpa;
485 slpb = cvpb;
486 rv = asccasecmp((*slpa)->sl_dat, (*slpb)->sl_dat);
487 NYD2_LEAVE;
488 return rv;
490 #endif /* HAVE_FNMATCH */
492 static void
493 a_shexp__quote(struct a_shexp_quote_ctx *sqcp, struct a_shexp_quote_lvl *sqlp){
494 /* XXX Because of the problems caused by ISO C multibyte interface we cannot
495 * XXX use the recursive implementation because of stateful encodings.
496 * XXX I.e., if a quoted substring cannot be self-contained - the data after
497 * XXX the quote relies on "the former state", then this doesn't make sense.
498 * XXX Therefore this is not fully programmed out but instead only detects
499 * XXX the "most fancy" quoting necessary, and directly does that.
500 * XXX As a result of this, T_REVSOL and T_DOUBLE are not even considered.
501 * XXX Otherwise we rather have to convert to wide first and act on that,
502 * XXX e.g., call visual_info(n_VISUAL_INFO_WOUT_CREATE) on entire input */
503 #undef a_SHEXP_QUOTE_RECURSE /* XXX (Needs complete revisit, then) */
504 #ifdef a_SHEXP_QUOTE_RECURSE
505 # define jrecurse jrecurse
506 struct a_shexp_quote_lvl sql;
507 #else
508 # define jrecurse jstep
509 #endif
510 struct n_visual_info_ctx vic;
511 union {struct a_shexp_quote_lvl *head; struct n_string *store;} u;
512 ui32_t flags;
513 size_t il;
514 char const *ib;
515 NYD2_ENTER;
517 ib = sqlp->sql_dat.s;
518 il = sqlp->sql_dat.l;
519 flags = sqlp->sql_flags;
521 /* Iterate over the entire input, classify characters and type of quotes
522 * along the way. Whenever a quote change has to be applied, adjust flags
523 * for the new situation -, setup sql.* and recurse- */
524 while(il > 0){
525 char c;
527 c = *ib;
528 if(cntrlchar(c)){
529 if(flags & a_SHEXP_QUOTE_T_DOLLAR)
530 goto jstep;
531 if(c == '\t' && (flags & (a_SHEXP_QUOTE_T_REVSOL |
532 a_SHEXP_QUOTE_T_SINGLE | a_SHEXP_QUOTE_T_DOUBLE)))
533 goto jstep;
534 #ifdef a_SHEXP_QUOTE_RECURSE
535 ++sqcp->sqc_cnt_dollar;
536 #endif
537 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_DOLLAR;
538 goto jrecurse;
539 }else if(blankspacechar(c) || c == '"' || c == '$'){
540 if(flags & a_SHEXP_QUOTE_T_MASK)
541 goto jstep;
542 #ifdef a_SHEXP_QUOTE_RECURSE
543 ++sqcp->sqc_cnt_single;
544 #endif
545 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_SINGLE;
546 goto jrecurse;
547 }else if(c == '\''){
548 if(flags & (a_SHEXP_QUOTE_T_MASK & ~a_SHEXP_QUOTE_T_SINGLE))
549 goto jstep;
550 #ifdef a_SHEXP_QUOTE_RECURSE
551 ++sqcp->sqc_cnt_dollar;
552 #endif
553 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_DOLLAR;
554 goto jrecurse;
555 }else if(c == '\\'){
556 if(flags & a_SHEXP_QUOTE_T_MASK)
557 goto jstep;
558 #ifdef a_SHEXP_QUOTE_RECURSE
559 ++sqcp->sqc_cnt_single;
560 #endif
561 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_SINGLE;
562 goto jrecurse;
563 }else if(!asciichar(c)){
564 /* Need to keep together multibytes */
565 #ifdef a_SHEXP_QUOTE_RECURSE
566 memset(&vic, 0, sizeof vic);
567 vic.vic_indat = ib;
568 vic.vic_inlen = il;
569 n_visual_info(&vic,
570 n_VISUAL_INFO_ONE_CHAR | n_VISUAL_INFO_SKIP_ERRORS);
571 #endif
572 /* xxx check whether resulting \u would be ASCII */
573 if(!(flags & a_SHEXP_QUOTE_ROUNDTRIP) ||
574 (flags & a_SHEXP_QUOTE_T_DOLLAR)){
575 #ifdef a_SHEXP_QUOTE_RECURSE
576 ib = vic.vic_oudat;
577 il = vic.vic_oulen;
578 continue;
579 #else
580 goto jstep;
581 #endif
583 #ifdef a_SHEXP_QUOTE_RECURSE
584 ++sqcp->sqc_cnt_dollar;
585 #endif
586 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_DOLLAR;
587 goto jrecurse;
588 }else
589 jstep:
590 ++ib, --il;
592 sqlp->sql_flags = flags;
594 /* Level made the great and completed processing input. Reverse the list of
595 * levels, detect the "most fancy" quote type needed along this way */
596 /* XXX Due to restriction as above very crude */
597 for(flags = 0, il = 0, u.head = NULL; sqlp != NULL;){
598 struct a_shexp_quote_lvl *tmp;
600 tmp = sqlp->sql_link;
601 sqlp->sql_link = u.head;
602 u.head = sqlp;
603 il += sqlp->sql_dat.l;
604 if(sqlp->sql_flags & a_SHEXP_QUOTE_T_MASK)
605 il += (sqlp->sql_dat.l >> 1);
606 flags |= sqlp->sql_flags;
607 sqlp = tmp;
609 sqlp = u.head;
611 /* Finally work the substrings in the correct order, adjusting quotes along
612 * the way as necessary. Start off with the "most fancy" quote, so that
613 * the user sees an overall boundary she can orientate herself on.
614 * We do it like that to be able to give the user some "encapsulation
615 * experience", to address what strikes me is a problem of sh(1)ell quoting:
616 * different to, e.g., perl(1), where you see at a glance where a string
617 * starts and ends, sh(1) quoting occurs at the "top level", disrupting the
618 * visual appearance of "a string" as such */
619 u.store = n_string_reserve(sqcp->sqc_store, il);
621 if(flags & a_SHEXP_QUOTE_T_DOLLAR){
622 u.store = n_string_push_buf(u.store, "$'", sizeof("$'") -1);
623 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_DOLLAR;
624 }else if(flags & a_SHEXP_QUOTE_T_DOUBLE){
625 u.store = n_string_push_c(u.store, '"');
626 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_DOUBLE;
627 }else if(flags & a_SHEXP_QUOTE_T_SINGLE){
628 u.store = n_string_push_c(u.store, '\'');
629 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_SINGLE;
630 }else /*if(flags & a_SHEXP_QUOTE_T_REVSOL)*/
631 flags &= ~a_SHEXP_QUOTE_T_MASK;
633 /* Work all the levels */
634 for(; sqlp != NULL; sqlp = sqlp->sql_link){
635 /* As necessary update our mode of quoting */
636 #ifdef a_SHEXP_QUOTE_RECURSE
637 il = 0;
639 switch(sqlp->sql_flags & a_SHEXP_QUOTE_T_MASK){
640 case a_SHEXP_QUOTE_T_DOLLAR:
641 if(!(flags & a_SHEXP_QUOTE_T_DOLLAR))
642 il = a_SHEXP_QUOTE_T_DOLLAR;
643 break;
644 case a_SHEXP_QUOTE_T_DOUBLE:
645 if(!(flags & (a_SHEXP_QUOTE_T_DOUBLE | a_SHEXP_QUOTE_T_DOLLAR)))
646 il = a_SHEXP_QUOTE_T_DOLLAR;
647 break;
648 case a_SHEXP_QUOTE_T_SINGLE:
649 if(!(flags & (a_SHEXP_QUOTE_T_REVSOL | a_SHEXP_QUOTE_T_SINGLE |
650 a_SHEXP_QUOTE_T_DOUBLE | a_SHEXP_QUOTE_T_DOLLAR)))
651 il = a_SHEXP_QUOTE_T_SINGLE;
652 break;
653 default:
654 case a_SHEXP_QUOTE_T_REVSOL:
655 if(!(flags & (a_SHEXP_QUOTE_T_REVSOL | a_SHEXP_QUOTE_T_SINGLE |
656 a_SHEXP_QUOTE_T_DOUBLE | a_SHEXP_QUOTE_T_DOLLAR)))
657 il = a_SHEXP_QUOTE_T_REVSOL;
658 break;
661 if(il != 0){
662 if(flags & (a_SHEXP_QUOTE_T_SINGLE | a_SHEXP_QUOTE_T_DOLLAR))
663 u.store = n_string_push_c(u.store, '\'');
664 else if(flags & a_SHEXP_QUOTE_T_DOUBLE)
665 u.store = n_string_push_c(u.store, '"');
666 flags &= ~a_SHEXP_QUOTE_T_MASK;
668 flags |= (ui32_t)il;
669 if(flags & a_SHEXP_QUOTE_T_DOLLAR)
670 u.store = n_string_push_buf(u.store, "$'", sizeof("$'") -1);
671 else if(flags & a_SHEXP_QUOTE_T_DOUBLE)
672 u.store = n_string_push_c(u.store, '"');
673 else if(flags & a_SHEXP_QUOTE_T_SINGLE)
674 u.store = n_string_push_c(u.store, '\'');
676 #endif /* a_SHEXP_QUOTE_RECURSE */
678 /* Work the level's substring */
679 ib = sqlp->sql_dat.s;
680 il = sqlp->sql_dat.l;
682 while(il > 0){
683 char c2, c;
685 c = *ib;
687 if(cntrlchar(c)){
688 assert(c == '\t' || (flags & a_SHEXP_QUOTE_T_DOLLAR));
689 assert((flags & (a_SHEXP_QUOTE_T_REVSOL | a_SHEXP_QUOTE_T_SINGLE |
690 a_SHEXP_QUOTE_T_DOUBLE | a_SHEXP_QUOTE_T_DOLLAR)));
691 switch((c2 = c)){
692 case 0x07: c = 'a'; break;
693 case 0x08: c = 'b'; break;
694 case 0x0A: c = 'n'; break;
695 case 0x0B: c = 'v'; break;
696 case 0x0C: c = 'f'; break;
697 case 0x0D: c = 'r'; break;
698 case 0x1B: c = 'E'; break;
699 default: break;
700 case 0x09:
701 if(flags & a_SHEXP_QUOTE_T_DOLLAR){
702 c = 't';
703 break;
705 if(flags & a_SHEXP_QUOTE_T_REVSOL)
706 u.store = n_string_push_c(u.store, '\\');
707 goto jpush;
709 u.store = n_string_push_c(u.store, '\\');
710 if(c == c2){
711 u.store = n_string_push_c(u.store, 'c');
712 c ^= 0x40;
714 goto jpush;
715 }else if(blankspacechar(c) || c == '"' || c == '$'){
716 if(flags & (a_SHEXP_QUOTE_T_SINGLE | a_SHEXP_QUOTE_T_DOLLAR))
717 goto jpush;
718 assert(flags & (a_SHEXP_QUOTE_T_REVSOL | a_SHEXP_QUOTE_T_DOUBLE));
719 u.store = n_string_push_c(u.store, '\\');
720 goto jpush;
721 }else if(c == '\''){
722 if(flags & a_SHEXP_QUOTE_T_DOUBLE)
723 goto jpush;
724 assert(!(flags & a_SHEXP_QUOTE_T_SINGLE));
725 u.store = n_string_push_c(u.store, '\\');
726 goto jpush;
727 }else if(c == '\\'){
728 if(flags & a_SHEXP_QUOTE_T_SINGLE)
729 goto jpush;
730 assert(flags & (a_SHEXP_QUOTE_T_REVSOL | a_SHEXP_QUOTE_T_DOUBLE |
731 a_SHEXP_QUOTE_T_DOLLAR));
732 u.store = n_string_push_c(u.store, '\\');
733 goto jpush;
734 }else if(asciichar(c)){
735 /* Shorthand: we can simply push that thing out */
736 jpush:
737 u.store = n_string_push_c(u.store, c);
738 ++ib, --il;
739 }else{
740 /* Not an ASCII character, take care not to split up multibyte
741 * sequences etc. For the sake of compile testing, don't enwrap in
742 * HAVE_ALWAYS_UNICODE_LOCALE || HAVE_NATCH_CHAR */
743 if(n_psonce & n_PSO_UNICODE){
744 ui32_t uc;
745 char const *ib2;
746 size_t il2, il3;
748 ib2 = ib;
749 il3 = il2 = il;
750 if((uc = n_utf8_to_utf32(&ib2, &il2)) != UI32_MAX){
751 char itoa[32];
752 char const *cp;
754 il2 = PTR2SIZE(&ib2[0] - &ib[0]);
755 if((flags & a_SHEXP_QUOTE_ROUNDTRIP) || uc == 0xFFFDu){
756 /* Use padding to make ambiguities impossible */
757 il3 = snprintf(itoa, sizeof itoa, "\\%c%0*X",
758 (uc > 0xFFFFu ? 'U' : 'u'),
759 (int)(uc > 0xFFFFu ? 8 : 4), uc);
760 cp = itoa;
761 }else{
762 il3 = il2;
763 cp = &ib[0];
765 u.store = n_string_push_buf(u.store, cp, il3);
766 ib += il2, il -= il2;
767 continue;
771 memset(&vic, 0, sizeof vic);
772 vic.vic_indat = ib;
773 vic.vic_inlen = il;
774 n_visual_info(&vic,
775 n_VISUAL_INFO_ONE_CHAR | n_VISUAL_INFO_SKIP_ERRORS);
777 /* Work this substring as sensitive as possible */
778 il -= vic.vic_oulen;
779 if(!(flags & a_SHEXP_QUOTE_ROUNDTRIP))
780 u.store = n_string_push_buf(u.store, ib, il);
781 #ifdef HAVE_ICONV
782 else if((vic.vic_indat = n_iconv_onetime_cp(n_ICONV_NONE,
783 "utf-8", ok_vlook(ttycharset), savestrbuf(ib, il))) != NULL){
784 ui32_t uc;
785 char const *ib2;
786 size_t il2, il3;
788 il3 = il2 = strlen(ib2 = vic.vic_indat);
789 if((uc = n_utf8_to_utf32(&ib2, &il2)) != UI32_MAX){
790 char itoa[32];
792 il2 = PTR2SIZE(&ib2[0] - &vic.vic_indat[0]);
793 /* Use padding to make ambiguities impossible */
794 il3 = snprintf(itoa, sizeof itoa, "\\%c%0*X",
795 (uc > 0xFFFFu ? 'U' : 'u'),
796 (int)(uc > 0xFFFFu ? 8 : 4), uc);
797 u.store = n_string_push_buf(u.store, itoa, il3);
798 }else
799 goto Jxseq;
801 #endif
802 else
803 #ifdef HAVE_ICONV
804 Jxseq:
805 #endif
806 while(il-- > 0){
807 u.store = n_string_push_buf(u.store, "\\xFF",
808 sizeof("\\xFF") -1);
809 n_c_to_hex_base16(&u.store->s_dat[u.store->s_len - 2], *ib++);
812 ib = vic.vic_oudat;
813 il = vic.vic_oulen;
818 /* Close an open quote */
819 if(flags & (a_SHEXP_QUOTE_T_SINGLE | a_SHEXP_QUOTE_T_DOLLAR))
820 u.store = n_string_push_c(u.store, '\'');
821 else if(flags & a_SHEXP_QUOTE_T_DOUBLE)
822 u.store = n_string_push_c(u.store, '"');
823 #ifdef a_SHEXP_QUOTE_RECURSE
824 jleave:
825 #endif
826 NYD2_LEAVE;
827 return;
829 #ifdef a_SHEXP_QUOTE_RECURSE
830 jrecurse:
831 sqlp->sql_dat.l -= il;
833 sql.sql_link = sqlp;
834 sql.sql_dat.s = n_UNCONST(ib);
835 sql.sql_dat.l = il;
836 sql.sql_flags = flags;
837 a_shexp__quote(sqcp, &sql);
838 goto jleave;
839 #endif
841 #undef jrecurse
842 #undef a_SHEXP_QUOTE_RECURSE
845 FL char *
846 fexpand(char const *name, enum fexp_mode fexpm)
848 struct str s;
849 char const *cp, *res;
850 bool_t dyn;
851 NYD_ENTER;
853 n_pstate &= ~n_PS_EXPAND_MULTIRESULT;
855 /* The order of evaluation is "%" and "#" expand into constants.
856 * "&" can expand into "+". "+" can expand into shell meta characters.
857 * Shell meta characters expand into constants.
858 * This way, we make no recursive expansion */
859 if ((fexpm & FEXP_NSHORTCUT) || (res = shortcut_expand(name)) == NULL)
860 res = n_UNCONST(name);
862 if(!(fexpm & FEXP_NSPECIAL)){
863 jnext:
864 dyn = FAL0;
865 switch (*res) {
866 case '%':
867 if(res[1] == ':' && res[2] != '\0')
868 res = &res[2];
869 else{
870 bool_t force;
872 force = (res[1] != '\0');
873 res = a_shexp_findmail((force ? &res[1] : ok_vlook(LOGNAME)),
874 force);
875 if(force)
876 goto jislocal;
878 goto jnext;
879 case '#':
880 if (res[1] != '\0')
881 break;
882 if (prevfile[0] == '\0') {
883 n_err(_("No previous file\n"));
884 res = NULL;
885 goto jleave;
887 res = prevfile;
888 goto jislocal;
889 case '&':
890 if (res[1] == '\0')
891 res = ok_vlook(MBOX);
892 break;
896 /* POSIX: if *folder* unset or null, "+" shall be retained */
897 if (!(fexpm & FEXP_NFOLDER) && *res == '+' &&
898 *(cp = folder_query()) != '\0') {
899 res = str_concat_csvl(&s, cp, &res[1], NULL)->s;
900 dyn = TRU1;
902 /* TODO *folder* can't start with %[:], can it!?! */
903 if (res[0] == '%' && res[1] == ':') {
904 res += 2;
905 goto jnext;
909 /* Do some meta expansions */
910 if((fexpm & (FEXP_NSHELL | FEXP_NVAR)) != FEXP_NVAR &&
911 ((fexpm & FEXP_NSHELL) ? (strchr(res, '$') != NULL)
912 : anyof(res, "{}[]*?$"))){
913 bool_t doexp;
915 if(fexpm & FEXP_NOPROTO)
916 doexp = TRU1;
917 else switch(which_protocol(res)){
918 case PROTO_FILE:
919 case PROTO_MAILDIR:
920 doexp = TRU1;
921 break;
922 default:
923 doexp = FAL0;
924 break;
927 if(doexp){
928 struct str shin;
929 struct n_string shou, *shoup;
931 shin.s = n_UNCONST(res);
932 shin.l = UIZ_MAX;
933 shoup = n_string_creat_auto(&shou);
934 for(;;){
935 enum n_shexp_state shs;
937 /* TODO shexp: take care to not include backtick eval once avail! */
938 shs = n_shexp_parse_token(shoup, &shin, n_SHEXP_PARSE_LOG_D_V |
939 n_SHEXP_PARSE_QUOTE_AUTO_FIXED | n_SHEXP_PARSE_QUOTE_AUTO_DQ |
940 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE);
941 if(shs & n_SHEXP_STATE_STOP)
942 break;
944 res = n_string_cp(shoup);
945 shoup = n_string_drop_ownership(shoup);
946 dyn = TRU1;
948 if(res[0] == '~')
949 res = a_shexp_tilde(res);
951 if(!(fexpm & FEXP_NSHELL) &&
952 (res = a_shexp_globname(res, fexpm)) == NULL)
953 goto jleave;
954 dyn = TRU1;
955 }/* else no tilde */
956 }else if(res[0] == '~'){
957 res = a_shexp_tilde(res);
958 dyn = TRU1;
961 jislocal:
962 if (fexpm & FEXP_LOCAL)
963 switch (which_protocol(res)) {
964 case PROTO_FILE:
965 case PROTO_MAILDIR:
966 break;
967 default:
968 n_err(_("Not a local file or directory: %s\n"),
969 n_shexp_quote_cp(name, FAL0));
970 res = NULL;
971 break;
974 jleave:
975 if(res != NULL && !dyn)
976 res = savestr(res);
977 NYD_LEAVE;
978 return n_UNCONST(res);
981 FL enum n_shexp_state
982 n_shexp_parse_token(struct n_string *store, struct str *input, /* TODO WCHAR */
983 enum n_shexp_parse_flags flags){
984 char utf[8];
985 char c2, c, quotec;
986 enum{
987 a_NONE = 0,
988 a_SKIPQ = 1<<0, /* Skip rest of this quote (\c0 ..) */
989 a_SURPLUS = 1<<1, /* Extended sequence interpretation */
990 a_NTOKEN = 1<<2 /* "New token": e.g., comments are possible */
991 } state;
992 enum n_shexp_state rv;
993 size_t i, il;
994 char const *ib_save, *ib;
995 NYD2_ENTER;
996 n_UNINIT(c, '\0');
998 assert((flags & n_SHEXP_PARSE_DRYRUN) || store != NULL);
999 assert(input != NULL);
1000 assert(input->l == 0 || input->s != NULL);
1001 assert(!(flags & n_SHEXP_PARSE_LOG) || !(flags & n_SHEXP_PARSE_LOG_D_V));
1002 assert(!(flags & n_SHEXP_PARSE_IFS_ADD_COMMA) ||
1003 !(flags & n_SHEXP_PARSE_IFS_IS_COMMA));
1004 assert(!(flags & n_SHEXP_PARSE_QUOTE_AUTO_FIXED) ||
1005 (flags & n__SHEXP_PARSE_QUOTE_AUTO_MASK));
1007 if((flags & n_SHEXP_PARSE_LOG_D_V) && (n_poption & n_PO_D_V))
1008 flags |= n_SHEXP_PARSE_LOG;
1009 if(flags & n_SHEXP_PARSE_QUOTE_AUTO_FIXED)
1010 flags |= n_SHEXP_PARSE_QUOTE_AUTO_CLOSE;
1012 if((flags & n_SHEXP_PARSE_TRUNC) && store != NULL)
1013 store = n_string_trunc(store, 0);
1015 ib = input->s;
1016 if((il = input->l) == UIZ_MAX)
1017 il = strlen(ib);
1019 jrestart_empty:
1020 if(flags & n_SHEXP_PARSE_TRIMSPACE){
1021 for(; il > 0; ++ib, --il)
1022 if(!blankspacechar(*ib))
1023 break;
1025 input->s = n_UNCONST(ib);
1026 input->l = il;
1028 if(il == 0){
1029 rv = n_SHEXP_STATE_STOP;
1030 goto jleave;
1033 if(store != NULL)
1034 store = n_string_reserve(store, n_MIN(il, 32)); /* XXX */
1036 rv = n_SHEXP_STATE_NONE;
1037 switch(flags & n__SHEXP_PARSE_QUOTE_AUTO_MASK){
1038 case n_SHEXP_PARSE_QUOTE_AUTO_SQ:
1039 quotec = '\'';
1040 state = a_NONE;
1041 break;
1042 case n_SHEXP_PARSE_QUOTE_AUTO_DQ:
1043 quotec = '"';
1044 if(0){
1045 case n_SHEXP_PARSE_QUOTE_AUTO_DSQ:
1046 quotec = '\'';
1048 state = a_SURPLUS;
1049 break;
1050 default:
1051 quotec = '\0';
1052 state = a_NTOKEN;
1053 break;
1056 while(il > 0){
1057 --il, c = *ib++;
1059 /* If no quote-mode active.. */
1060 if(quotec == '\0'){
1061 if(c == '"' || c == '\''){
1062 quotec = c;
1063 if(c == '"')
1064 state |= a_SURPLUS;
1065 else
1066 state &= ~a_SURPLUS;
1067 state &= ~a_NTOKEN;
1068 continue;
1069 }else if(c == '$'){
1070 if(il > 0){
1071 state &= ~a_NTOKEN;
1072 if(*ib == '\''){
1073 --il, ++ib;
1074 quotec = '\'';
1075 state |= a_SURPLUS;
1076 continue;
1077 }else
1078 goto J_var_expand;
1080 }else if(c == '\\'){
1081 /* Outside of quotes this just escapes any next character, but a sole
1082 * <backslash> at EOS is left unchanged */
1083 if(il > 0)
1084 --il, c = *ib++;
1085 state &= ~a_NTOKEN;
1086 }else if(c == '#' && (state & a_NTOKEN)){
1087 rv |= n_SHEXP_STATE_STOP;
1088 goto jleave;
1089 }else if(c == ',' && (flags &
1090 (n_SHEXP_PARSE_IFS_ADD_COMMA | n_SHEXP_PARSE_IFS_IS_COMMA)))
1091 break;
1092 else if(blankchar(c)){
1093 if(!(flags & n_SHEXP_PARSE_IFS_IS_COMMA)){
1094 ++il, --ib;
1095 break;
1097 state |= a_NTOKEN;
1098 }else
1099 state &= ~a_NTOKEN;
1100 }else{
1101 /* Quote-mode */
1102 assert(!(state & a_NTOKEN));
1103 if(c == quotec && !(flags & n_SHEXP_PARSE_QUOTE_AUTO_FIXED)){
1104 state = a_NONE;
1105 quotec = '\0';
1106 /* Users may need to recognize the presence of empty quotes */
1107 rv |= n_SHEXP_STATE_OUTPUT;
1108 continue;
1109 }else if(c == '\\' && (state & a_SURPLUS)){
1110 ib_save = ib - 1;
1111 /* A sole <backslash> at EOS is treated as-is! This is ok since
1112 * the "closing quote" error will occur next, anyway */
1113 if(il == 0)
1114 break;
1115 else if((c2 = *ib) == quotec){
1116 --il, ++ib;
1117 c = quotec;
1118 }else if(quotec == '"'){
1119 /* Double quotes:
1120 * The <backslash> shall retain its special meaning as an
1121 * escape character (see Section 2.2.1) only when followed
1122 * by one of the following characters when considered
1123 * special: $ ` " \ <newline> */
1124 switch(c2){
1125 case '$':
1126 case '`':
1127 /* case '"': already handled via c2 == quotec */
1128 case '\\':
1129 --il, ++ib;
1130 c = c2;
1131 /* FALLTHRU */
1132 default:
1133 break;
1135 }else{
1136 /* Dollar-single-quote */
1137 --il, ++ib;
1138 switch(c2){
1139 case '"':
1140 /* case '\'': already handled via c2 == quotec */
1141 case '\\':
1142 c = c2;
1143 break;
1145 case 'b': c = '\b'; break;
1146 case 'f': c = '\f'; break;
1147 case 'n': c = '\n'; break;
1148 case 'r': c = '\r'; break;
1149 case 't': c = '\t'; break;
1150 case 'v': c = '\v'; break;
1152 case 'E':
1153 case 'e': c = '\033'; break;
1155 /* Control character */
1156 case 'c':
1157 if(il == 0)
1158 goto j_dollar_ungetc;
1159 --il, c2 = *ib++;
1160 if(state & a_SKIPQ)
1161 continue;
1162 c = upperconv(c2) ^ 0x40;
1163 if((ui8_t)c > 0x1F && c != 0x7F){ /* ASCII C0: 0..1F, 7F */
1164 if(flags & n_SHEXP_PARSE_LOG)
1165 n_err(_("Invalid \\c notation: %.*s\n"),
1166 (int)input->l, input->s);
1167 rv |= n_SHEXP_STATE_ERR_CONTROL;
1169 /* As an implementation-defined extension, support \c@
1170 * EQ printf(1) alike \c */
1171 if(c == '\0'){
1172 rv |= n_SHEXP_STATE_STOP;
1173 goto jleave;
1175 break;
1177 /* Octal sequence: 1 to 3 octal bytes */
1178 case '0':
1179 /* As an extension (dependent on where you look, echo(1), or
1180 * awk(1)/tr(1) etc.), allow leading "0" octal indicator */
1181 if(il > 0 && (c = *ib) >= '0' && c <= '7'){
1182 c2 = c;
1183 --il, ++ib;
1185 /* FALLTHRU */
1186 case '1': case '2': case '3':
1187 case '4': case '5': case '6': case '7':
1188 c2 -= '0';
1189 if(il > 0 && (c = *ib) >= '0' && c <= '7'){
1190 c2 = (c2 << 3) | (c - '0');
1191 --il, ++ib;
1193 if(il > 0 && (c = *ib) >= '0' && c <= '7'){
1194 if((ui8_t)c2 > 0x1F){
1195 if(flags & n_SHEXP_PARSE_LOG)
1196 n_err(_("\\0 argument exceeds a byte: %.*s\n"),
1197 (int)input->l, input->s);
1198 rv |= n_SHEXP_STATE_ERR_NUMBER;
1199 --il, ++ib;
1200 /* Write unchanged */
1201 je_ib_save:
1202 rv |= n_SHEXP_STATE_OUTPUT;
1203 if(!(flags & n_SHEXP_PARSE_DRYRUN))
1204 store = n_string_push_buf(store, ib_save,
1205 PTR2SIZE(ib - ib_save));
1206 continue;
1208 c2 = (c2 << 3) | (c -= '0');
1209 --il, ++ib;
1211 if((c = c2) == '\0')
1212 state |= a_SKIPQ;
1213 if(state & a_SKIPQ)
1214 continue;
1215 break;
1217 /* ISO 10646 / Unicode sequence, 8 or 4 hexadecimal bytes */
1218 case 'U':
1219 i = 8;
1220 if(0){
1221 /* FALLTHRU */
1222 case 'u':
1223 i = 4;
1225 if(il == 0)
1226 goto j_dollar_ungetc;
1227 if(0){
1228 /* FALLTHRU */
1230 /* Hexadecimal sequence, 1 or 2 hexadecimal bytes */
1231 case 'X':
1232 case 'x':
1233 if(il == 0)
1234 goto j_dollar_ungetc;
1235 i = 2;
1237 /* C99 */{
1238 static ui8_t const hexatoi[] = { /* XXX uses ASCII */
1239 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
1241 size_t no, j;
1243 i = n_MIN(il, i);
1244 for(no = j = 0; i-- > 0; --il, ++ib, ++j){
1245 c = *ib;
1246 if(hexchar(c)){
1247 no <<= 4;
1248 no += hexatoi[(ui8_t)((c) - ((c) <= '9' ? 48
1249 : ((c) <= 'F' ? 55 : 87)))];
1250 }else if(j == 0){
1251 if(state & a_SKIPQ)
1252 break;
1253 c2 = (c2 == 'U' || c2 == 'u') ? 'u' : 'x';
1254 if(flags & n_SHEXP_PARSE_LOG)
1255 n_err(_("Invalid \\%c notation: %.*s\n"),
1256 c2, (int)input->l, input->s);
1257 rv |= n_SHEXP_STATE_ERR_NUMBER;
1258 goto je_ib_save;
1259 }else
1260 break;
1263 /* Unicode massage */
1264 if((c2 != 'U' && c2 != 'u') || n_uasciichar(no)){
1265 if((c = (char)no) == '\0')
1266 state |= a_SKIPQ;
1267 }else if(no == 0)
1268 state |= a_SKIPQ;
1269 else if(!(state & a_SKIPQ)){
1270 if(!(flags & n_SHEXP_PARSE_DRYRUN))
1271 store = n_string_reserve(store, n_MAX(j, 4));
1273 c2 = FAL0;
1274 if(no > 0x10FFFF){ /* XXX magic; CText */
1275 if(flags & n_SHEXP_PARSE_LOG)
1276 n_err(_("\\U argument exceeds 0x10FFFF: %.*s\n"),
1277 (int)input->l, input->s);
1278 rv |= n_SHEXP_STATE_ERR_NUMBER;
1279 /* But normalize the output anyway */
1280 goto Je_uni_norm;
1283 j = n_utf32_to_utf8(no, utf);
1285 if(n_psonce & n_PSO_UNICODE){
1286 rv |= n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_UNICODE;
1287 if(!(flags & n_SHEXP_PARSE_DRYRUN))
1288 store = n_string_push_buf(store, utf, j);
1289 continue;
1291 #ifdef HAVE_ICONV
1292 else{
1293 char *icp;
1295 icp = n_iconv_onetime_cp(n_ICONV_NONE,
1296 NULL, NULL, utf);
1297 if(icp != NULL){
1298 rv |= n_SHEXP_STATE_OUTPUT;
1299 if(!(flags & n_SHEXP_PARSE_DRYRUN))
1300 store = n_string_push_cp(store, icp);
1301 continue;
1304 #endif
1305 if(!(flags & n_SHEXP_PARSE_DRYRUN)) Je_uni_norm:{
1306 char itoa[32];
1308 rv |= n_SHEXP_STATE_OUTPUT |
1309 n_SHEXP_STATE_ERR_UNICODE;
1310 i = snprintf(itoa, sizeof itoa, "\\%c%0*X",
1311 (no > 0xFFFFu ? 'U' : 'u'),
1312 (int)(no > 0xFFFFu ? 8 : 4), (ui32_t)no);
1313 store = n_string_push_buf(store, itoa, i);
1315 continue;
1317 if(state & a_SKIPQ)
1318 continue;
1320 break;
1322 /* Extension: \$ can be used to expand a variable.
1323 * Bug|ad effect: if conversion fails, not written "as-is" */
1324 case '$':
1325 if(il == 0)
1326 goto j_dollar_ungetc;
1327 goto J_var_expand;
1329 default:
1330 j_dollar_ungetc:
1331 /* Follow bash behaviour, print sequence unchanged */
1332 ++il, --ib;
1333 break;
1336 }else if(c == '$' && quotec == '"' && il > 0) J_var_expand:{
1337 bool_t brace;
1339 if(!(brace = (*ib == '{')) || il > 1){
1340 char const *cp, *vp;
1342 ib_save = ib - 1;
1343 il -= brace;
1344 vp = (ib += brace);
1346 for(i = 0; il > 0; --il, ++ib, ++i){
1347 /* We have some special cases regarding macro-local special
1348 * parameters, so ensure these don't cause failure */
1349 c = *ib;
1350 if(!a_SHEXP_ISVARC(c)){
1351 if(i == 0 && a_SHEXP_ISVARC_SPECIAL1(c)){
1352 --il, ++ib;
1353 ++i;
1355 break;
1359 if(state & a_SKIPQ){
1360 if(brace && il > 0 && *ib == '}')
1361 --il, ++ib;
1362 continue;
1365 if(i == 0){
1366 if(brace){
1367 if(flags & n_SHEXP_PARSE_LOG)
1368 n_err(_("Bad substitution (${}): %.*s\n Near %.*s\n"),
1369 (int)input->l, input->s, (int)il, ib);
1370 rv |= n_SHEXP_STATE_ERR_BADSUB;
1371 goto je_ib_save;
1373 c = '$';
1374 }else{
1375 if(brace){
1376 if(il == 0 || *ib != '}'){
1377 if(flags & n_SHEXP_PARSE_LOG)
1378 n_err(_("Missing closing brace for ${VAR}: %.*s\n"
1379 " Near: %.*s\n"),
1380 (int)input->l, input->s, (int)il, ib);
1381 rv |= n_SHEXP_STATE_ERR_QUOTEOPEN |
1382 n_SHEXP_STATE_ERR_BRACE;
1383 goto je_ib_save;
1385 --il, ++ib;
1388 if(flags & n_SHEXP_PARSE_DRYRUN)
1389 continue;
1391 /* Check getenv(3) shall no internal variable exist! */
1392 /* TODO Expansion of $-* and $-@ not shell compatible, if
1393 * TODO that occurs within double quotes.
1394 * TODO Same notes on that in accmacvar.c, shexp.c */
1395 vp = savestrbuf(vp, i);
1396 if((cp = n_var_vlook(vp, TRU1)) != NULL){
1397 rv |= n_SHEXP_STATE_OUTPUT;
1398 store = n_string_push_cp(store, cp);
1399 for(; (c = *cp) != '\0'; ++cp)
1400 if(cntrlchar(c)){
1401 rv |= n_SHEXP_STATE_CONTROL;
1402 break;
1405 continue;
1408 }else if(c == '`' && quotec == '"' && il > 0){ /* TODO shell command */
1409 continue;
1413 if(!(state & a_SKIPQ)){
1414 rv |= n_SHEXP_STATE_OUTPUT;
1415 if(cntrlchar(c))
1416 rv |= n_SHEXP_STATE_CONTROL;
1417 if(!(flags & n_SHEXP_PARSE_DRYRUN))
1418 store = n_string_push_c(store, c);
1422 if(quotec != '\0' && !(flags & n_SHEXP_PARSE_QUOTE_AUTO_CLOSE)){
1423 if(flags & n_SHEXP_PARSE_LOG)
1424 n_err(_("no closing quote: %.*s\n"), (int)input->l, input->s);
1425 rv |= n_SHEXP_STATE_ERR_QUOTEOPEN;
1428 jleave:
1429 if((flags & n_SHEXP_PARSE_DRYRUN) && store != NULL){
1430 store = n_string_push_buf(store, input->s, PTR2SIZE(ib - input->s));
1431 rv |= n_SHEXP_STATE_OUTPUT;
1434 if(flags & n_SHEXP_PARSE_TRIMSPACE){
1435 for(; il > 0; ++ib, --il)
1436 if(!blankchar(*ib))
1437 break;
1439 input->l = il;
1440 input->s = n_UNCONST(ib);
1442 if(!(rv & n_SHEXP_STATE_STOP)){
1443 if(il > 0 && !(rv & n_SHEXP_STATE_OUTPUT) &&
1444 (flags & n_SHEXP_PARSE_IGNORE_EMPTY))
1445 goto jrestart_empty;
1446 if(/*!(rv & n_SHEXP_STATE_OUTPUT) &&*/ il == 0)
1447 rv |= n_SHEXP_STATE_STOP;
1449 assert((rv & n_SHEXP_STATE_OUTPUT) || !(rv & n_SHEXP_STATE_UNICODE));
1450 assert((rv & n_SHEXP_STATE_OUTPUT) || !(rv & n_SHEXP_STATE_CONTROL));
1451 NYD2_LEAVE;
1452 return rv;
1455 FL enum n_shexp_state
1456 n_shexp_parse_token_buf(char **store, char const *indat, size_t inlen,
1457 enum n_shexp_parse_flags flags){
1458 struct n_string ss;
1459 struct str is;
1460 enum n_shexp_state shs;
1461 NYD2_ENTER;
1463 assert(store != NULL);
1464 assert(inlen == 0 || indat != NULL);
1466 n_string_creat_auto(&ss);
1467 is.s = n_UNCONST(indat);
1468 is.l = inlen;
1470 shs = n_shexp_parse_token(&ss, &is, flags);
1471 if(is.l > 0)
1472 shs &= ~n_SHEXP_STATE_STOP;
1473 else
1474 shs |= n_SHEXP_STATE_STOP;
1475 *store = n_string_cp(&ss);
1476 n_string_drop_ownership(&ss);
1478 n_string_gut(&ss);
1479 NYD2_LEAVE;
1480 return shs;
1483 FL struct n_string *
1484 n_shexp_quote(struct n_string *store, struct str const *input, bool_t rndtrip){
1485 struct a_shexp_quote_lvl sql;
1486 struct a_shexp_quote_ctx sqc;
1487 NYD2_ENTER;
1489 assert(store != NULL);
1490 assert(input != NULL);
1491 assert(input->l == 0 || input->s != NULL);
1493 memset(&sqc, 0, sizeof sqc);
1494 sqc.sqc_store = store;
1495 sqc.sqc_input.s = input->s;
1496 if((sqc.sqc_input.l = input->l) == UIZ_MAX)
1497 sqc.sqc_input.l = strlen(input->s);
1498 sqc.sqc_flags = rndtrip ? a_SHEXP_QUOTE_ROUNDTRIP : a_SHEXP_QUOTE_NONE;
1500 if(sqc.sqc_input.l == 0)
1501 store = n_string_push_buf(store, "''", sizeof("''") -1);
1502 else{
1503 memset(&sql, 0, sizeof sql);
1504 sql.sql_dat = sqc.sqc_input;
1505 sql.sql_flags = sqc.sqc_flags;
1506 a_shexp__quote(&sqc, &sql);
1508 NYD2_LEAVE;
1509 return store;
1512 FL char *
1513 n_shexp_quote_cp(char const *cp, bool_t rndtrip){
1514 struct n_string store;
1515 struct str input;
1516 char *rv;
1517 NYD2_ENTER;
1519 assert(cp != NULL);
1521 input.s = n_UNCONST(cp);
1522 input.l = UIZ_MAX;
1523 rv = n_string_cp(n_shexp_quote(n_string_creat_auto(&store), &input,
1524 rndtrip));
1525 n_string_gut(n_string_drop_ownership(&store));
1526 NYD2_LEAVE;
1527 return rv;
1530 FL bool_t
1531 n_shexp_is_valid_varname(char const *name){
1532 char c;
1533 bool_t rv;
1534 NYD2_ENTER;
1536 for(rv = TRU1; (c = *name++) != '\0';)
1537 if(!a_SHEXP_ISVARC(c)){
1538 rv = FAL0;
1539 break;
1541 NYD2_LEAVE;
1542 return rv;
1545 /* s-it-mode */