a_head_addrspec_check(): do not treat high-bit bytes as _T_SPECIAL..
[s-mailx.git] / shexp.c
blob9da491d3aefffc4bc4ea3fd61af41717018dc204
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 <pwd.h>
45 #ifdef HAVE_FNMATCH
46 # include <dirent.h>
47 # include <fnmatch.h>
48 #endif
50 /* POSIX says
51 * Environment variable names used by the utilities in the Shell and
52 * Utilities volume of POSIX.1-2008 consist solely of uppercase
53 * letters, digits, and the <underscore> ('_') from the characters
54 * defined in Portable Character Set and do not begin with a digit.
55 * Other characters may be permitted by an implementation;
56 * applications shall tolerate the presence of such names.
57 * We do support the hyphen-minus "-" (except in last position for ${x[:]-y}).
58 * We support some special parameter names for one-letter(++) variable names;
59 * these have counterparts in the code that manages internal variables,
60 * and some more special treatment below! */
61 #define a_SHEXP_ISVARC(C) (alnumchar(C) || (C) == '_' || (C) == '-')
62 #define a_SHEXP_ISVARC_BAD1ST(C) (digitchar(C)) /* (Actually assumed below!) */
63 #define a_SHEXP_ISVARC_BADNST(C) ((C) == '-')
65 enum a_shexp_quote_flags{
66 a_SHEXP_QUOTE_NONE,
67 a_SHEXP_QUOTE_ROUNDTRIP = 1u<<0, /* Result won't be consumed immediately */
69 a_SHEXP_QUOTE_T_REVSOL = 1u<<8, /* Type: by reverse solidus */
70 a_SHEXP_QUOTE_T_SINGLE = 1u<<9, /* Type: single-quotes */
71 a_SHEXP_QUOTE_T_DOUBLE = 1u<<10, /* Type: double-quotes */
72 a_SHEXP_QUOTE_T_DOLLAR = 1u<<11, /* Type: dollar-single-quotes */
73 a_SHEXP_QUOTE_T_MASK = a_SHEXP_QUOTE_T_REVSOL | a_SHEXP_QUOTE_T_SINGLE |
74 a_SHEXP_QUOTE_T_DOUBLE | a_SHEXP_QUOTE_T_DOLLAR,
76 a_SHEXP_QUOTE__FREESHIFT = 16u
79 #ifdef HAVE_FNMATCH
80 struct a_shexp_glob_ctx{
81 char const *sgc_patdat; /* Remaining pattern (at and below level) */
82 size_t sgc_patlen;
83 struct n_string *sgc_outer; /* Resolved path up to this level */
84 ui32_t sgc_flags;
85 ui8_t sgc__dummy[4];
87 #endif
89 struct a_shexp_quote_ctx{
90 struct n_string *sqc_store; /* Result storage */
91 struct str sqc_input; /* Input data, topmost level */
92 ui32_t sqc_cnt_revso;
93 ui32_t sqc_cnt_single;
94 ui32_t sqc_cnt_double;
95 ui32_t sqc_cnt_dollar;
96 enum a_shexp_quote_flags sqc_flags;
97 ui8_t sqc__dummy[4];
100 struct a_shexp_quote_lvl{
101 struct a_shexp_quote_lvl *sql_link; /* Outer level */
102 struct str sql_dat; /* This level (has to) handle(d) */
103 enum a_shexp_quote_flags sql_flags;
104 ui8_t sql__dummy[4];
107 /* Locate the user's mailbox file (where new, unread mail is queued) */
108 static char *a_shexp_findmail(char const *user, bool_t force);
110 /* Expand ^~/? and ^~USER/? constructs.
111 * Returns the completely resolved (maybe empty or identical to input)
112 * salloc()ed string */
113 static char *a_shexp_tilde(char const *s);
115 /* Perform fnmatch(3). May return NULL on error */
116 static char *a_shexp_globname(char const *name, enum fexp_mode fexpm);
117 #ifdef HAVE_FNMATCH
118 static bool_t a_shexp__glob(struct a_shexp_glob_ctx *sgcp,
119 struct n_strlist **slpp);
120 static int a_shexp__globsort(void const *cvpa, void const *cvpb);
121 #endif
123 /* Parse an input string and create a sh(1)ell-quoted result */
124 static void a_shexp__quote(struct a_shexp_quote_ctx *sqcp,
125 struct a_shexp_quote_lvl *sqlp);
127 static char *
128 a_shexp_findmail(char const *user, bool_t force){
129 char *rv;
130 char const *cp;
131 NYD2_ENTER;
133 if(!force){
134 if((cp = ok_vlook(inbox)) != NULL && *cp != '\0'){
135 /* _NFOLDER extra introduced to avoid % recursion loops */
136 if((rv = fexpand(cp, FEXP_NSPECIAL | FEXP_NFOLDER | FEXP_NSHELL)
137 ) != NULL)
138 goto jleave;
139 n_err(_("*inbox* expansion failed, using $MAIL / built-in: %s\n"), cp);
141 /* Heirloom compatibility: an IMAP *folder* becomes "%" */
142 #ifdef HAVE_IMAP
143 else if(cp == NULL && !strcmp(user, ok_vlook(LOGNAME)) &&
144 which_protocol(cp = n_folder_query(), FAL0, FAL0, NULL)
145 == PROTO_IMAP){
146 /* TODO Compat handling of *folder* with IMAP! */
147 n_OBSOLETE("no more expansion of *folder* in \"%\": "
148 "please set *inbox*");
149 rv = savestr(cp);
150 goto jleave;
152 #endif
154 if((cp = ok_vlook(MAIL)) != NULL){
155 rv = savestr(cp);
156 goto jleave;
160 /* C99 */{
161 size_t ul, i;
163 ul = strlen(user) +1;
164 i = sizeof(VAL_MAIL) -1 + 1 + ul;
166 rv = salloc(i);
167 memcpy(rv, VAL_MAIL, (i = sizeof(VAL_MAIL) -1));
168 rv[i] = '/';
169 memcpy(&rv[++i], user, ul);
171 jleave:
172 NYD2_LEAVE;
173 return rv;
176 static char *
177 a_shexp_tilde(char const *s){
178 struct passwd *pwp;
179 size_t nl, rl;
180 char const *rp, *np;
181 char *rv;
182 NYD2_ENTER;
184 if(*(rp = &s[1]) == '/' || *rp == '\0'){
185 np = ok_vlook(HOME);
186 rl = strlen(rp);
187 }else{
188 if((rp = strchr(np = rp, '/')) != NULL){
189 nl = PTR2SIZE(rp - np);
190 np = savestrbuf(np, nl);
191 rl = strlen(rp);
192 }else
193 rl = 0;
195 if((pwp = getpwnam(np)) == NULL){
196 rv = savestr(s);
197 goto jleave;
199 np = pwp->pw_dir;
202 nl = strlen(np);
203 rv = salloc(nl + 1 + rl +1);
204 memcpy(rv, np, nl);
205 if(rl > 0){
206 memcpy(rv + nl, rp, rl);
207 nl += rl;
209 rv[nl] = '\0';
210 jleave:
211 NYD2_LEAVE;
212 return rv;
215 static char *
216 a_shexp_globname(char const *name, enum fexp_mode fexpm){
217 #ifdef HAVE_FNMATCH
218 struct a_shexp_glob_ctx sgc;
219 struct n_string outer;
220 struct n_strlist *slp;
221 char *cp;
222 NYD_ENTER;
224 memset(&sgc, 0, sizeof sgc);
225 sgc.sgc_patlen = strlen(name);
226 sgc.sgc_patdat = savestrbuf(name, sgc.sgc_patlen);
227 sgc.sgc_outer = n_string_reserve(n_string_creat(&outer), sgc.sgc_patlen);
228 sgc.sgc_flags = ((fexpm & FEXP_SILENT) != 0);
229 slp = NULL;
230 if(a_shexp__glob(&sgc, &slp))
231 cp = (char*)1;
232 else
233 cp = NULL;
234 n_string_gut(&outer);
236 if(cp == NULL)
237 goto jleave;
239 if(slp == NULL){
240 cp = n_UNCONST(N_("File pattern does not match"));
241 goto jerr;
242 }else if(slp->sl_next == NULL)
243 cp = savestrbuf(slp->sl_dat, slp->sl_len);
244 else if(fexpm & FEXP_MULTIOK){
245 struct n_strlist **sorta, *xslp;
246 size_t i, no, l;
248 no = l = 0;
249 for(xslp = slp; xslp != NULL; xslp = xslp->sl_next){
250 ++no;
251 l += xslp->sl_len + 1;
254 sorta = smalloc(sizeof(*sorta) * no);
255 no = 0;
256 for(xslp = slp; xslp != NULL; xslp = xslp->sl_next)
257 sorta[no++] = xslp;
258 qsort(sorta, no, sizeof *sorta, &a_shexp__globsort);
260 cp = salloc(++l);
261 l = 0;
262 for(i = 0; i < no; ++i){
263 xslp = sorta[i];
264 memcpy(&cp[l], xslp->sl_dat, xslp->sl_len);
265 l += xslp->sl_len;
266 cp[l++] = '\0';
268 cp[l] = '\0';
270 free(sorta);
271 n_pstate |= n_PS_EXPAND_MULTIRESULT;
272 }else{
273 cp = n_UNCONST(N_("File pattern matches multiple results"));
274 goto jerr;
277 jleave:
278 while(slp != NULL){
279 struct n_strlist *tmp = slp;
281 slp = slp->sl_next;
282 free(tmp);
284 NYD_LEAVE;
285 return cp;
287 jerr:
288 if(!(fexpm & FEXP_SILENT)){
289 name = n_shexp_quote_cp(name, FAL0);
290 n_err("%s: %s\n", V_(cp), name);
292 cp = NULL;
293 goto jleave;
295 #else /* HAVE_FNMATCH */
296 n_UNUSED(fexpm);
298 if(!(fexpm & FEXP_SILENT))
299 n_err(_("No filename pattern (fnmatch(3)) support compiled in\n"));
300 return savestr(name);
301 #endif
304 #ifdef HAVE_FNMATCH
305 static bool_t
306 a_shexp__glob(struct a_shexp_glob_ctx *sgcp, struct n_strlist **slpp){
307 enum{a_SILENT = 1<<0, a_DEEP=1<<1, a_SALLOC=1<<2};
309 struct a_shexp_glob_ctx nsgc;
310 struct dirent *dep;
311 DIR *dp;
312 size_t old_outerlen;
313 char const *ccp, *myp;
314 NYD2_ENTER;
316 /* We need some special treatment for the outermost level */
317 if(!(sgcp->sgc_flags & a_DEEP)){
318 if(sgcp->sgc_patlen > 0 && sgcp->sgc_patdat[0] == '/'){
319 myp = n_string_cp(n_string_push_c(sgcp->sgc_outer, '/'));
320 ++sgcp->sgc_patdat;
321 --sgcp->sgc_patlen;
322 }else
323 myp = "./";
324 }else
325 myp = n_string_cp(sgcp->sgc_outer);
326 old_outerlen = sgcp->sgc_outer->s_len;
328 /* Separate current directory/pattern level from any possible remaining
329 * pattern in order to be able to use it for fnmatch(3) */
330 if((ccp = memchr(sgcp->sgc_patdat, '/', sgcp->sgc_patlen)) == NULL)
331 nsgc.sgc_patlen = 0;
332 else{
333 nsgc = *sgcp;
334 nsgc.sgc_flags |= a_DEEP;
335 sgcp->sgc_patlen = PTR2SIZE((nsgc.sgc_patdat = &ccp[1]) -
336 &sgcp->sgc_patdat[0]);
337 nsgc.sgc_patlen -= sgcp->sgc_patlen;
338 /* Trim solidus */
339 if(sgcp->sgc_patlen > 0){
340 assert(sgcp->sgc_patdat[sgcp->sgc_patlen -1] == '/');
341 ((char*)n_UNCONST(sgcp->sgc_patdat))[--sgcp->sgc_patlen] = '\0';
345 /* Our current directory level */
346 /* xxx Plenty of room for optimizations, like quickshot lstat(2) which may
347 * xxx be the (sole) result depending on pattern surroundings, etc. */
348 if((dp = opendir(myp)) == NULL){
349 int err;
351 switch((err = n_err_no)){
352 case n_ERR_NOTDIR:
353 ccp = N_("cannot access paths under non-directory");
354 goto jerr;
355 case n_ERR_NOENT:
356 ccp = N_("path component of (sub)pattern non-existent");
357 goto jerr;
358 case n_ERR_ACCES:
359 ccp = N_("file permission for file (sub)pattern denied");
360 goto jerr;
361 default:
362 ccp = N_("cannot handle file (sub)pattern");
363 goto jerr;
367 /* As necessary, quote bytes in the current pattern */
368 /* C99 */{
369 char *ncp;
370 size_t i;
371 bool_t need;
373 for(need = FAL0, i = 0, myp = sgcp->sgc_patdat; *myp != '\0'; ++myp)
374 switch(*myp){
375 case '\'': case '"': case '\\': case '$':
376 case ' ': case '\t':
377 need = TRU1;
378 ++i;
379 /* FALLTHRU */
380 default:
381 ++i;
382 break;
385 if(need){
386 ncp = salloc(i +1);
387 for(i = 0, myp = sgcp->sgc_patdat; *myp != '\0'; ++myp)
388 switch(*myp){
389 case '\'': case '"': case '\\': case '$':
390 case ' ': case '\t':
391 ncp[i++] = '\\';
392 /* FALLTHRU */
393 default:
394 ncp[i++] = *myp;
395 break;
397 ncp[i] = '\0';
398 myp = ncp;
399 }else
400 myp = sgcp->sgc_patdat;
403 while((dep = readdir(dp)) != NULL){
404 switch(fnmatch(myp, dep->d_name, FNM_PATHNAME | FNM_PERIOD)){
405 case 0:{
406 /* A match expresses the desire to recurse if there is more pattern */
407 if(nsgc.sgc_patlen > 0){
408 bool_t isdir;
410 n_string_push_cp((sgcp->sgc_outer->s_len > 1
411 ? n_string_push_c(sgcp->sgc_outer, '/') : sgcp->sgc_outer),
412 dep->d_name);
414 isdir = FAL0;
415 #ifdef HAVE_DIRENT_TYPE
416 if(dep->d_type == DT_DIR)
417 isdir = TRU1;
418 else if(dep->d_type == DT_LNK || dep->d_type == DT_UNKNOWN)
419 #endif
421 struct stat sb;
423 if(stat(n_string_cp(sgcp->sgc_outer), &sb)){
424 ccp = N_("I/O error when querying file status");
425 goto jerr;
426 }else if(S_ISDIR(sb.st_mode))
427 isdir = TRU1;
430 /* TODO We recurse with current dir FD open, which could E[MN]FILE!
431 * TODO Instead save away a list of such n_string's for later */
432 if(isdir && !a_shexp__glob(&nsgc, slpp)){
433 ccp = (char*)1;
434 goto jleave;
437 n_string_trunc(sgcp->sgc_outer, old_outerlen);
438 }else{
439 struct n_strlist *slp;
440 size_t i, j;
442 i = strlen(dep->d_name);
443 j = (old_outerlen > 0) ? old_outerlen + 1 + i : i;
444 slp = n_STRLIST_ALLOC(j);
445 *slpp = slp;
446 slpp = &slp->sl_next;
447 slp->sl_next = NULL;
448 if((j = old_outerlen) > 0){
449 memcpy(&slp->sl_dat[0], sgcp->sgc_outer->s_dat, j);
450 if(slp->sl_dat[j -1] != '/')
451 slp->sl_dat[j++] = '/';
453 memcpy(&slp->sl_dat[j], dep->d_name, i);
454 slp->sl_dat[j += i] = '\0';
455 slp->sl_len = j;
457 } break;
458 case FNM_NOMATCH:
459 break;
460 default:
461 ccp = N_("fnmatch(3) cannot handle file (sub)pattern");
462 goto jerr;
466 ccp = NULL;
467 jleave:
468 if(dp != NULL)
469 closedir(dp);
470 NYD2_LEAVE;
471 return (ccp == NULL);
473 jerr:
474 if(!(sgcp->sgc_flags & a_SILENT)){
475 char const *s2, *s3;
477 if(sgcp->sgc_outer->s_len > 0){
478 s2 = n_shexp_quote_cp(n_string_cp(sgcp->sgc_outer), FAL0);
479 s3 = "/";
480 }else
481 s2 = s3 = n_empty;
483 n_err("%s: %s%s%s\n", V_(ccp), s2, s3,
484 n_shexp_quote_cp(sgcp->sgc_patdat, FAL0));
486 goto jleave;
489 static int
490 a_shexp__globsort(void const *cvpa, void const *cvpb){
491 int rv;
492 struct n_strlist const * const *slpa, * const *slpb;
493 NYD2_ENTER;
495 slpa = cvpa;
496 slpb = cvpb;
497 rv = asccasecmp((*slpa)->sl_dat, (*slpb)->sl_dat);
498 NYD2_LEAVE;
499 return rv;
501 #endif /* HAVE_FNMATCH */
503 static void
504 a_shexp__quote(struct a_shexp_quote_ctx *sqcp, struct a_shexp_quote_lvl *sqlp){
505 /* XXX Because of the problems caused by ISO C multibyte interface we cannot
506 * XXX use the recursive implementation because of stateful encodings.
507 * XXX I.e., if a quoted substring cannot be self-contained - the data after
508 * XXX the quote relies on "the former state", then this doesn't make sense.
509 * XXX Therefore this is not fully programmed out but instead only detects
510 * XXX the "most fancy" quoting necessary, and directly does that.
511 * XXX As a result of this, T_REVSOL and T_DOUBLE are not even considered.
512 * XXX Otherwise we rather have to convert to wide first and act on that,
513 * XXX e.g., call visual_info(n_VISUAL_INFO_WOUT_CREATE) on entire input */
514 #undef a_SHEXP_QUOTE_RECURSE /* XXX (Needs complete revisit, then) */
515 #ifdef a_SHEXP_QUOTE_RECURSE
516 # define jrecurse jrecurse
517 struct a_shexp_quote_lvl sql;
518 #else
519 # define jrecurse jstep
520 #endif
521 struct n_visual_info_ctx vic;
522 union {struct a_shexp_quote_lvl *head; struct n_string *store;} u;
523 ui32_t flags;
524 size_t il;
525 char const *ib, *ib_base;
526 NYD2_ENTER;
528 ib_base = ib = sqlp->sql_dat.s;
529 il = sqlp->sql_dat.l;
530 flags = sqlp->sql_flags;
532 /* Iterate over the entire input, classify characters and type of quotes
533 * along the way. Whenever a quote change has to be applied, adjust flags
534 * for the new situation -, setup sql.* and recurse- */
535 while(il > 0){
536 char c;
538 c = *ib;
539 if(cntrlchar(c)){
540 if(flags & a_SHEXP_QUOTE_T_DOLLAR)
541 goto jstep;
542 if(c == '\t' && (flags & (a_SHEXP_QUOTE_T_REVSOL |
543 a_SHEXP_QUOTE_T_SINGLE | a_SHEXP_QUOTE_T_DOUBLE)))
544 goto jstep;
545 #ifdef a_SHEXP_QUOTE_RECURSE
546 ++sqcp->sqc_cnt_dollar;
547 #endif
548 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_DOLLAR;
549 goto jrecurse;
550 }else if(blankspacechar(c) || c == '|' || c == '&' || c == ';' ||
551 /* Whereas we don't support those, quote them for the sh(1)ell */
552 c == '(' || c == ')' || c == '<' || c == '>' ||
553 c == '"' || c == '$'){
554 if(flags & a_SHEXP_QUOTE_T_MASK)
555 goto jstep;
556 #ifdef a_SHEXP_QUOTE_RECURSE
557 ++sqcp->sqc_cnt_single;
558 #endif
559 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_SINGLE;
560 goto jrecurse;
561 }else if(c == '\''){
562 if(flags & (a_SHEXP_QUOTE_T_MASK & ~a_SHEXP_QUOTE_T_SINGLE))
563 goto jstep;
564 #ifdef a_SHEXP_QUOTE_RECURSE
565 ++sqcp->sqc_cnt_dollar;
566 #endif
567 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_DOLLAR;
568 goto jrecurse;
569 }else if(c == '\\' || (c == '#' && ib == ib_base)){
570 if(flags & a_SHEXP_QUOTE_T_MASK)
571 goto jstep;
572 #ifdef a_SHEXP_QUOTE_RECURSE
573 ++sqcp->sqc_cnt_single;
574 #endif
575 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_SINGLE;
576 goto jrecurse;
577 }else if(!asciichar(c)){
578 /* Need to keep together multibytes */
579 #ifdef a_SHEXP_QUOTE_RECURSE
580 memset(&vic, 0, sizeof vic);
581 vic.vic_indat = ib;
582 vic.vic_inlen = il;
583 n_visual_info(&vic,
584 n_VISUAL_INFO_ONE_CHAR | n_VISUAL_INFO_SKIP_ERRORS);
585 #endif
586 /* xxx check whether resulting \u would be ASCII */
587 if(!(flags & a_SHEXP_QUOTE_ROUNDTRIP) ||
588 (flags & a_SHEXP_QUOTE_T_DOLLAR)){
589 #ifdef a_SHEXP_QUOTE_RECURSE
590 ib = vic.vic_oudat;
591 il = vic.vic_oulen;
592 continue;
593 #else
594 goto jstep;
595 #endif
597 #ifdef a_SHEXP_QUOTE_RECURSE
598 ++sqcp->sqc_cnt_dollar;
599 #endif
600 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_DOLLAR;
601 goto jrecurse;
602 }else
603 jstep:
604 ++ib, --il;
606 sqlp->sql_flags = flags;
608 /* Level made the great and completed processing input. Reverse the list of
609 * levels, detect the "most fancy" quote type needed along this way */
610 /* XXX Due to restriction as above very crude */
611 for(flags = 0, il = 0, u.head = NULL; sqlp != NULL;){
612 struct a_shexp_quote_lvl *tmp;
614 tmp = sqlp->sql_link;
615 sqlp->sql_link = u.head;
616 u.head = sqlp;
617 il += sqlp->sql_dat.l;
618 if(sqlp->sql_flags & a_SHEXP_QUOTE_T_MASK)
619 il += (sqlp->sql_dat.l >> 1);
620 flags |= sqlp->sql_flags;
621 sqlp = tmp;
623 sqlp = u.head;
625 /* Finally work the substrings in the correct order, adjusting quotes along
626 * the way as necessary. Start off with the "most fancy" quote, so that
627 * the user sees an overall boundary she can orientate herself on.
628 * We do it like that to be able to give the user some "encapsulation
629 * experience", to address what strikes me is a problem of sh(1)ell quoting:
630 * different to, e.g., perl(1), where you see at a glance where a string
631 * starts and ends, sh(1) quoting occurs at the "top level", disrupting the
632 * visual appearance of "a string" as such */
633 u.store = n_string_reserve(sqcp->sqc_store, il);
635 if(flags & a_SHEXP_QUOTE_T_DOLLAR){
636 u.store = n_string_push_buf(u.store, "$'", sizeof("$'") -1);
637 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_DOLLAR;
638 }else if(flags & a_SHEXP_QUOTE_T_DOUBLE){
639 u.store = n_string_push_c(u.store, '"');
640 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_DOUBLE;
641 }else if(flags & a_SHEXP_QUOTE_T_SINGLE){
642 u.store = n_string_push_c(u.store, '\'');
643 flags = (flags & ~a_SHEXP_QUOTE_T_MASK) | a_SHEXP_QUOTE_T_SINGLE;
644 }else /*if(flags & a_SHEXP_QUOTE_T_REVSOL)*/
645 flags &= ~a_SHEXP_QUOTE_T_MASK;
647 /* Work all the levels */
648 for(; sqlp != NULL; sqlp = sqlp->sql_link){
649 /* As necessary update our mode of quoting */
650 #ifdef a_SHEXP_QUOTE_RECURSE
651 il = 0;
653 switch(sqlp->sql_flags & a_SHEXP_QUOTE_T_MASK){
654 case a_SHEXP_QUOTE_T_DOLLAR:
655 if(!(flags & a_SHEXP_QUOTE_T_DOLLAR))
656 il = a_SHEXP_QUOTE_T_DOLLAR;
657 break;
658 case a_SHEXP_QUOTE_T_DOUBLE:
659 if(!(flags & (a_SHEXP_QUOTE_T_DOUBLE | a_SHEXP_QUOTE_T_DOLLAR)))
660 il = a_SHEXP_QUOTE_T_DOLLAR;
661 break;
662 case a_SHEXP_QUOTE_T_SINGLE:
663 if(!(flags & (a_SHEXP_QUOTE_T_REVSOL | a_SHEXP_QUOTE_T_SINGLE |
664 a_SHEXP_QUOTE_T_DOUBLE | a_SHEXP_QUOTE_T_DOLLAR)))
665 il = a_SHEXP_QUOTE_T_SINGLE;
666 break;
667 default:
668 case a_SHEXP_QUOTE_T_REVSOL:
669 if(!(flags & (a_SHEXP_QUOTE_T_REVSOL | a_SHEXP_QUOTE_T_SINGLE |
670 a_SHEXP_QUOTE_T_DOUBLE | a_SHEXP_QUOTE_T_DOLLAR)))
671 il = a_SHEXP_QUOTE_T_REVSOL;
672 break;
675 if(il != 0){
676 if(flags & (a_SHEXP_QUOTE_T_SINGLE | a_SHEXP_QUOTE_T_DOLLAR))
677 u.store = n_string_push_c(u.store, '\'');
678 else if(flags & a_SHEXP_QUOTE_T_DOUBLE)
679 u.store = n_string_push_c(u.store, '"');
680 flags &= ~a_SHEXP_QUOTE_T_MASK;
682 flags |= (ui32_t)il;
683 if(flags & a_SHEXP_QUOTE_T_DOLLAR)
684 u.store = n_string_push_buf(u.store, "$'", sizeof("$'") -1);
685 else if(flags & a_SHEXP_QUOTE_T_DOUBLE)
686 u.store = n_string_push_c(u.store, '"');
687 else if(flags & a_SHEXP_QUOTE_T_SINGLE)
688 u.store = n_string_push_c(u.store, '\'');
690 #endif /* a_SHEXP_QUOTE_RECURSE */
692 /* Work the level's substring */
693 ib = sqlp->sql_dat.s;
694 il = sqlp->sql_dat.l;
696 while(il > 0){
697 char c2, c;
699 c = *ib;
701 if(cntrlchar(c)){
702 assert(c == '\t' || (flags & a_SHEXP_QUOTE_T_DOLLAR));
703 assert((flags & (a_SHEXP_QUOTE_T_REVSOL | a_SHEXP_QUOTE_T_SINGLE |
704 a_SHEXP_QUOTE_T_DOUBLE | a_SHEXP_QUOTE_T_DOLLAR)));
705 switch((c2 = c)){
706 case 0x07: c = 'a'; break;
707 case 0x08: c = 'b'; break;
708 case 0x0A: c = 'n'; break;
709 case 0x0B: c = 'v'; break;
710 case 0x0C: c = 'f'; break;
711 case 0x0D: c = 'r'; break;
712 case 0x1B: c = 'E'; break;
713 default: break;
714 case 0x09:
715 if(flags & a_SHEXP_QUOTE_T_DOLLAR){
716 c = 't';
717 break;
719 if(flags & a_SHEXP_QUOTE_T_REVSOL)
720 u.store = n_string_push_c(u.store, '\\');
721 goto jpush;
723 u.store = n_string_push_c(u.store, '\\');
724 if(c == c2){
725 u.store = n_string_push_c(u.store, 'c');
726 c ^= 0x40;
728 goto jpush;
729 }else if(blankspacechar(c) || c == '|' || c == '&' || c == ';' ||
730 /* Whereas we don't support those, quote them for the sh(1)ell */
731 c == '(' || c == ')' || c == '<' || c == '>' ||
732 c == '"' || c == '$'){
733 if(flags & (a_SHEXP_QUOTE_T_SINGLE | a_SHEXP_QUOTE_T_DOLLAR))
734 goto jpush;
735 assert(flags & (a_SHEXP_QUOTE_T_REVSOL | a_SHEXP_QUOTE_T_DOUBLE));
736 u.store = n_string_push_c(u.store, '\\');
737 goto jpush;
738 }else if(c == '\''){
739 if(flags & a_SHEXP_QUOTE_T_DOUBLE)
740 goto jpush;
741 assert(!(flags & a_SHEXP_QUOTE_T_SINGLE));
742 u.store = n_string_push_c(u.store, '\\');
743 goto jpush;
744 }else if(c == '\\' || (c == '#' && ib == ib_base)){
745 if(flags & a_SHEXP_QUOTE_T_SINGLE)
746 goto jpush;
747 assert(flags & (a_SHEXP_QUOTE_T_REVSOL | a_SHEXP_QUOTE_T_DOUBLE |
748 a_SHEXP_QUOTE_T_DOLLAR));
749 u.store = n_string_push_c(u.store, '\\');
750 goto jpush;
751 }else if(asciichar(c)){
752 /* Shorthand: we can simply push that thing out */
753 jpush:
754 u.store = n_string_push_c(u.store, c);
755 ++ib, --il;
756 }else{
757 /* Not an ASCII character, take care not to split up multibyte
758 * sequences etc. For the sake of compile testing, don't enwrap in
759 * HAVE_ALWAYS_UNICODE_LOCALE || HAVE_NATCH_CHAR */
760 if(n_psonce & n_PSO_UNICODE){
761 ui32_t uc;
762 char const *ib2;
763 size_t il2, il3;
765 ib2 = ib;
766 il2 = il;
767 if((uc = n_utf8_to_utf32(&ib2, &il2)) != UI32_MAX){
768 char itoa[32];
769 char const *cp;
771 il2 = PTR2SIZE(&ib2[0] - &ib[0]);
772 if((flags & a_SHEXP_QUOTE_ROUNDTRIP) || uc == 0xFFFDu){
773 /* Use padding to make ambiguities impossible */
774 il3 = snprintf(itoa, sizeof itoa, "\\%c%0*X",
775 (uc > 0xFFFFu ? 'U' : 'u'),
776 (int)(uc > 0xFFFFu ? 8 : 4), uc);
777 cp = itoa;
778 }else{
779 il3 = il2;
780 cp = &ib[0];
782 u.store = n_string_push_buf(u.store, cp, il3);
783 ib += il2, il -= il2;
784 continue;
788 memset(&vic, 0, sizeof vic);
789 vic.vic_indat = ib;
790 vic.vic_inlen = il;
791 n_visual_info(&vic,
792 n_VISUAL_INFO_ONE_CHAR | n_VISUAL_INFO_SKIP_ERRORS);
794 /* Work this substring as sensitive as possible */
795 il -= vic.vic_oulen;
796 if(!(flags & a_SHEXP_QUOTE_ROUNDTRIP))
797 u.store = n_string_push_buf(u.store, ib, il);
798 #ifdef HAVE_ICONV
799 else if((vic.vic_indat = n_iconv_onetime_cp(n_ICONV_NONE,
800 "utf-8", ok_vlook(ttycharset), savestrbuf(ib, il))) != NULL){
801 ui32_t uc;
802 char const *ib2;
803 size_t il2, il3;
805 il2 = strlen(ib2 = vic.vic_indat);
806 if((uc = n_utf8_to_utf32(&ib2, &il2)) != UI32_MAX){
807 char itoa[32];
809 il2 = PTR2SIZE(&ib2[0] - &vic.vic_indat[0]);
810 /* Use padding to make ambiguities impossible */
811 il3 = snprintf(itoa, sizeof itoa, "\\%c%0*X",
812 (uc > 0xFFFFu ? 'U' : 'u'),
813 (int)(uc > 0xFFFFu ? 8 : 4), uc);
814 u.store = n_string_push_buf(u.store, itoa, il3);
815 }else
816 goto Jxseq;
818 #endif
819 else
820 #ifdef HAVE_ICONV
821 Jxseq:
822 #endif
823 while(il-- > 0){
824 u.store = n_string_push_buf(u.store, "\\xFF",
825 sizeof("\\xFF") -1);
826 n_c_to_hex_base16(&u.store->s_dat[u.store->s_len - 2], *ib++);
829 ib = vic.vic_oudat;
830 il = vic.vic_oulen;
835 /* Close an open quote */
836 if(flags & (a_SHEXP_QUOTE_T_SINGLE | a_SHEXP_QUOTE_T_DOLLAR))
837 u.store = n_string_push_c(u.store, '\'');
838 else if(flags & a_SHEXP_QUOTE_T_DOUBLE)
839 u.store = n_string_push_c(u.store, '"');
840 #ifdef a_SHEXP_QUOTE_RECURSE
841 jleave:
842 #endif
843 NYD2_LEAVE;
844 return;
846 #ifdef a_SHEXP_QUOTE_RECURSE
847 jrecurse:
848 sqlp->sql_dat.l -= il;
850 sql.sql_link = sqlp;
851 sql.sql_dat.s = n_UNCONST(ib);
852 sql.sql_dat.l = il;
853 sql.sql_flags = flags;
854 a_shexp__quote(sqcp, &sql);
855 goto jleave;
856 #endif
858 #undef jrecurse
859 #undef a_SHEXP_QUOTE_RECURSE
862 FL char *
863 fexpand(char const *name, enum fexp_mode fexpm) /* TODO in parts: -> URL::!! */
865 struct str proto, s;
866 char const *res, *cp;
867 bool_t dyn, haveproto;
868 NYD_ENTER;
870 n_pstate &= ~n_PS_EXPAND_MULTIRESULT;
871 dyn = FAL0;
873 /* The order of evaluation is "%" and "#" expand into constants.
874 * "&" can expand into "+". "+" can expand into shell meta characters.
875 * Shell meta characters expand into constants.
876 * This way, we make no recursive expansion */
877 if((fexpm & FEXP_NSHORTCUT) || (res = shortcut_expand(name)) == NULL)
878 res = n_UNCONST(name);
880 jprotonext:
881 n_UNINIT(proto.s, NULL), n_UNINIT(proto.l, 0);
882 haveproto = FAL0;
883 for(cp = res; *cp && *cp != ':'; ++cp)
884 if(!alnumchar(*cp))
885 goto jnoproto;
886 if(cp[0] == ':' && cp[1] == '/' && cp[2] == '/'){
887 haveproto = TRU1;
888 proto.s = n_UNCONST(res);
889 cp += 3;
890 proto.l = PTR2SIZE(cp - res);
891 res = cp;
894 jnoproto:
895 if(!(fexpm & FEXP_NSPECIAL)){
896 jnext:
897 dyn = FAL0;
898 switch(*res){
899 case '%':
900 if(res[1] == ':' && res[2] != '\0'){
901 res = &res[2];
902 goto jprotonext;
903 }else{
904 bool_t force;
906 force = (res[1] != '\0');
907 res = a_shexp_findmail((force ? &res[1] : ok_vlook(LOGNAME)),
908 force);
909 if(force)
910 goto jislocal;
912 goto jnext;
913 case '#':
914 if (res[1] != '\0')
915 break;
916 if (prevfile[0] == '\0') {
917 n_err(_("No previous file\n"));
918 res = NULL;
919 goto jleave;
921 res = prevfile;
922 goto jislocal;
923 case '&':
924 if (res[1] == '\0')
925 res = ok_vlook(MBOX);
926 break;
927 default:
928 break;
932 #ifdef HAVE_IMAP
933 if(res[0] == '@' && which_protocol(mailname, FAL0, FAL0, NULL)
934 == PROTO_IMAP){
935 res = str_concat_csvl(&s, protbase(mailname), "/", &res[1], NULL)->s;
936 dyn = TRU1;
938 #endif
940 /* POSIX: if *folder* unset or null, "+" shall be retained */
941 if(!(fexpm & FEXP_NFOLDER) && *res == '+' &&
942 *(cp = n_folder_query()) != '\0'){
943 res = str_concat_csvl(&s, cp, &res[1], NULL)->s;
944 dyn = TRU1;
947 /* Do some meta expansions */
948 if((fexpm & (FEXP_NSHELL | FEXP_NVAR)) != FEXP_NVAR &&
949 ((fexpm & FEXP_NSHELL) ? (strchr(res, '$') != NULL)
950 : anyof(res, "{}[]*?$"))){
951 bool_t doexp;
953 if(fexpm & FEXP_NOPROTO)
954 doexp = TRU1;
955 else{
956 cp = haveproto ? savecat(savestrbuf(proto.s, proto.l), res) : res;
958 switch(which_protocol(cp, TRU1, FAL0, NULL)){
959 case PROTO_FILE:
960 case PROTO_MAILDIR:
961 doexp = TRU1;
962 break;
963 default:
964 doexp = FAL0;
965 break;
969 if(doexp){
970 struct str shin;
971 struct n_string shou, *shoup;
973 shin.s = n_UNCONST(res);
974 shin.l = UIZ_MAX;
975 shoup = n_string_creat_auto(&shou);
976 for(;;){
977 enum n_shexp_state shs;
979 /* TODO shexp: take care to not include backtick eval once avail! */
980 shs = n_shexp_parse_token((n_SHEXP_PARSE_LOG_D_V |
981 n_SHEXP_PARSE_QUOTE_AUTO_FIXED | n_SHEXP_PARSE_QUOTE_AUTO_DQ |
982 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE), shoup, &shin, NULL);
983 if(shs & n_SHEXP_STATE_STOP)
984 break;
986 res = n_string_cp(shoup);
987 /*shoup = n_string_drop_ownership(shoup);*/
988 dyn = TRU1;
990 if(res[0] == '~')
991 res = a_shexp_tilde(res);
993 if(!(fexpm & FEXP_NSHELL) &&
994 (res = a_shexp_globname(res, fexpm)) == NULL)
995 goto jleave;
996 dyn = TRU1;
997 }/* else no tilde */
998 }else if(res[0] == '~'){
999 res = a_shexp_tilde(res);
1000 dyn = TRU1;
1003 jislocal:
1004 if(res != NULL && haveproto){
1005 res = savecat(savestrbuf(proto.s, proto.l), res);
1006 dyn = TRU1;
1009 if(fexpm & FEXP_LOCAL){
1010 switch (which_protocol(res, FAL0, FAL0, NULL)) {
1011 case PROTO_FILE:
1012 case PROTO_MAILDIR: /* Cannot happen since we don't stat(2), but.. */
1013 break;
1014 default:
1015 n_err(_("Not a local file or directory: %s\n"),
1016 n_shexp_quote_cp(name, FAL0));
1017 res = NULL;
1018 break;
1022 jleave:
1023 if(res != NULL && !dyn)
1024 res = savestr(res);
1025 NYD_LEAVE;
1026 return n_UNCONST(res);
1029 FL enum n_shexp_state
1030 n_shexp_parse_token(enum n_shexp_parse_flags flags, struct n_string *store,
1031 struct str *input, void const **cookie){
1032 /* TODO shexp_parse_token: WCHAR */
1033 ui32_t last_known_meta_trim_len;
1034 char c2, c, quotec, utf[8];
1035 enum n_shexp_state rv;
1036 size_t i, il;
1037 char const *ifs, *ifs_ws, *ib_save, *ib;
1038 enum{
1039 a_NONE = 0,
1040 a_SKIPQ = 1u<<0, /* Skip rest of this quote (\u0 ..) */
1041 a_SKIPT = 1u<<1, /* Skip entire token (\c@) */
1042 a_SKIPMASK = a_SKIPQ | a_SKIPT,
1043 a_SURPLUS = 1u<<2, /* Extended sequence interpretation */
1044 a_NTOKEN = 1u<<3, /* "New token": e.g., comments are possible */
1045 a_BRACE = 1u<<4, /* Variable substitution: brace enclosed */
1046 a_DIGIT1 = 1u<<5, /* ..first character was digit */
1047 a_NONDIGIT = 1u<<6, /* ..has seen any non-digits */
1048 a_VARSUBST_MASK = n_BITENUM_MASK(4, 6),
1050 a_ROUND_MASK = a_SKIPT | (int)~n_BITENUM_MASK(0, 7),
1051 a_COOKIE = 1u<<8,
1052 a_EXPLODE = 1u<<9,
1053 a_CONSUME = 1u<<10, /* When done, "consume" remaining input */
1054 a_TMP = 1u<<30
1055 } state;
1056 NYD2_ENTER;
1058 assert((flags & n_SHEXP_PARSE_DRYRUN) || store != NULL);
1059 assert(input != NULL);
1060 assert(input->l == 0 || input->s != NULL);
1061 assert(!(flags & n_SHEXP_PARSE_LOG) || !(flags & n_SHEXP_PARSE_LOG_D_V));
1062 assert(!(flags & n_SHEXP_PARSE_IFS_ADD_COMMA) ||
1063 !(flags & n_SHEXP_PARSE_IFS_IS_COMMA));
1064 assert(!(flags & n_SHEXP_PARSE_QUOTE_AUTO_FIXED) ||
1065 (flags & n__SHEXP_PARSE_QUOTE_AUTO_MASK));
1067 if((flags & n_SHEXP_PARSE_LOG_D_V) && (n_poption & n_PO_D_V))
1068 flags |= n_SHEXP_PARSE_LOG;
1069 if(flags & n_SHEXP_PARSE_QUOTE_AUTO_FIXED)
1070 flags |= n_SHEXP_PARSE_QUOTE_AUTO_CLOSE;
1072 if((flags & n_SHEXP_PARSE_TRUNC) && store != NULL)
1073 store = n_string_trunc(store, 0);
1075 if(flags & (n_SHEXP_PARSE_IFS_VAR | n_SHEXP_PARSE_TRIM_IFSSPACE)){
1076 ifs = ok_vlook(ifs);
1077 ifs_ws = ok_vlook(ifs_ws);
1080 state = a_NONE;
1081 ib = input->s;
1082 if((il = input->l) == UIZ_MAX)
1083 input->l = il = strlen(ib);
1084 n_UNINIT(c, '\0');
1086 if(cookie != NULL && *cookie != NULL){
1087 assert(!(flags & n_SHEXP_PARSE_DRYRUN));
1088 state |= a_COOKIE;
1091 rv = n_SHEXP_STATE_NONE;
1092 jrestart_empty:
1093 rv &= n_SHEXP_STATE_WS_LEAD;
1094 state &= a_ROUND_MASK;
1096 /* In cookie mode, the next ARGV entry is the token already, unchanged,
1097 * since it has already been expanded before! */
1098 if(state & a_COOKIE){
1099 char const * const *xcookie, *cp;
1101 i = store->s_len;
1102 xcookie = *cookie;
1103 if((store = n_string_push_cp(store, *xcookie))->s_len > 0)
1104 rv |= n_SHEXP_STATE_OUTPUT;
1105 if(*++xcookie == NULL){
1106 *cookie = NULL;
1107 state &= ~a_COOKIE;
1108 flags |= n_SHEXP_PARSE_QUOTE_AUTO_DQ; /* ..why we are here! */
1109 }else
1110 *cookie = n_UNCONST(xcookie);
1112 for(cp = &n_string_cp(store)[i]; (c = *cp++) != '\0';)
1113 if(cntrlchar(c)){
1114 rv |= n_SHEXP_STATE_CONTROL;
1115 break;
1118 /* The last exploded cookie will join with the yielded input token, so
1119 * simply fall through in this case */
1120 if(state & a_COOKIE)
1121 goto jleave_quick;
1122 }else{
1123 jrestart:
1124 if(flags & n_SHEXP_PARSE_TRIM_SPACE){
1125 for(; il > 0; ++ib, --il){
1126 if(!blankspacechar(*ib))
1127 break;
1128 rv |= n_SHEXP_STATE_WS_LEAD;
1132 if(flags & n_SHEXP_PARSE_TRIM_IFSSPACE){
1133 for(; il > 0; ++ib, --il){
1134 if(strchr(ifs_ws, *ib) == NULL)
1135 break;
1136 rv |= n_SHEXP_STATE_WS_LEAD;
1140 input->s = n_UNCONST(ib);
1141 input->l = il;
1144 if(il == 0){
1145 rv |= n_SHEXP_STATE_STOP;
1146 goto jleave;
1149 if(store != NULL)
1150 store = n_string_reserve(store, n_MIN(il, 32)); /* XXX */
1152 switch(flags & n__SHEXP_PARSE_QUOTE_AUTO_MASK){
1153 case n_SHEXP_PARSE_QUOTE_AUTO_SQ:
1154 quotec = '\'';
1155 rv |= n_SHEXP_STATE_QUOTE;
1156 break;
1157 case n_SHEXP_PARSE_QUOTE_AUTO_DQ:
1158 quotec = '"';
1159 if(0){
1160 case n_SHEXP_PARSE_QUOTE_AUTO_DSQ:
1161 quotec = '\'';
1163 rv |= n_SHEXP_STATE_QUOTE;
1164 state |= a_SURPLUS;
1165 break;
1166 default:
1167 quotec = '\0';
1168 state |= a_NTOKEN;
1169 break;
1172 /* TODO n_SHEXP_PARSE_META_SEMICOLON++, well, hack: we are not the shell,
1173 * TODO we are not a language, and therefore the general *ifs-ws* and normal
1174 * TODO whitespace trimming that input lines undergo (in a_go_evaluate())
1175 * TODO has already happened, our result will be used *as is*, and therefore
1176 * TODO we need to be aware of and remove trailing unquoted WS that would
1177 * TODO otherwise remain, after we have seen a semicolon sequencer.
1178 * By sheer luck we only need to track this in non-quote-mode */
1179 last_known_meta_trim_len = UI32_MAX;
1181 while(il > 0){
1182 --il, c = *ib++;
1184 /* If no quote-mode active.. */
1185 if(quotec == '\0'){
1186 if(c == '"' || c == '\''){
1187 quotec = c;
1188 if(c == '"')
1189 state |= a_SURPLUS;
1190 else
1191 state &= ~a_SURPLUS;
1192 state &= ~a_NTOKEN;
1193 last_known_meta_trim_len = UI32_MAX;
1194 rv |= n_SHEXP_STATE_QUOTE;
1195 continue;
1196 }else if(c == '$'){
1197 if(il > 0){
1198 state &= ~a_NTOKEN;
1199 last_known_meta_trim_len = UI32_MAX;
1200 if(*ib == '\''){
1201 --il, ++ib;
1202 quotec = '\'';
1203 state |= a_SURPLUS;
1204 rv |= n_SHEXP_STATE_QUOTE;
1205 continue;
1206 }else
1207 goto J_var_expand;
1209 }else if(c == '\\'){
1210 /* Outside of quotes this just escapes any next character, but a sole
1211 * <reverse solidus> at EOS is left unchanged */
1212 if(il > 0)
1213 --il, c = *ib++;
1214 state &= ~a_NTOKEN;
1215 last_known_meta_trim_len = UI32_MAX;
1217 /* A comment may it be if no token has yet started */
1218 else if(c == '#' && (state & a_NTOKEN)){
1219 rv |= n_SHEXP_STATE_STOP;
1220 /*last_known_meta_trim_len = UI32_MAX;*/
1221 goto jleave;
1223 /* Metacharacters which separate tokens must be turned on explicitly */
1224 else if(c == '|' && (flags & n_SHEXP_PARSE_META_VERTBAR)){
1225 rv |= n_SHEXP_STATE_META_VERTBAR;
1227 /* The parsed sequence may be _the_ output, so ensure we don't
1228 * include the metacharacter, then. */
1229 if(flags & (n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_META_KEEP))
1230 ++il, --ib;
1231 /*last_known_meta_trim_len = UI32_MAX;*/
1232 break;
1233 }else if(c == '&' && (flags & n_SHEXP_PARSE_META_AMPERSAND)){
1234 rv |= n_SHEXP_STATE_META_AMPERSAND;
1236 /* The parsed sequence may be _the_ output, so ensure we don't
1237 * include the metacharacter, then. */
1238 if(flags & (n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_META_KEEP))
1239 ++il, --ib;
1240 /*last_known_meta_trim_len = UI32_MAX;*/
1241 break;
1242 }else if(c == ';' && (flags & n_SHEXP_PARSE_META_SEMICOLON)){
1243 if(il > 0)
1244 n_go_input_inject(n_GO_INPUT_INJECT_COMMIT, ib, il);
1245 rv |= n_SHEXP_STATE_META_SEMICOLON | n_SHEXP_STATE_STOP;
1246 state |= a_CONSUME;
1247 if(!(flags & n_SHEXP_PARSE_DRYRUN) && (rv & n_SHEXP_STATE_OUTPUT) &&
1248 last_known_meta_trim_len != UI32_MAX)
1249 store = n_string_trunc(store, last_known_meta_trim_len);
1251 /* The parsed sequence may be _the_ output, so ensure we don't
1252 * include the metacharacter, then. */
1253 if(flags & (n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_META_KEEP))
1254 ++il, --ib;
1255 /*last_known_meta_trim_len = UI32_MAX;*/
1256 break;
1257 }else if(c == ',' && (flags &
1258 (n_SHEXP_PARSE_IFS_ADD_COMMA | n_SHEXP_PARSE_IFS_IS_COMMA))){
1259 /* The parsed sequence may be _the_ output, so ensure we don't
1260 * include the metacharacter, then. */
1261 if(flags & (n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_META_KEEP))
1262 ++il, --ib;
1263 /*last_known_meta_trim_len = UI32_MAX;*/
1264 break;
1265 }else{
1266 ui8_t blnk;
1268 blnk = blankchar(c) ? 1 : 0;
1269 blnk |= ((flags & (n_SHEXP_PARSE_IFS_VAR |
1270 n_SHEXP_PARSE_TRIM_IFSSPACE)) &&
1271 strchr(ifs_ws, c) != NULL) ? 2 : 0;
1273 if((!(flags & n_SHEXP_PARSE_IFS_VAR) && (blnk & 1)) ||
1274 ((flags & n_SHEXP_PARSE_IFS_VAR) &&
1275 ((blnk & 2) || strchr(ifs, c) != NULL))){
1276 if(!(flags & n_SHEXP_PARSE_IFS_IS_COMMA)){
1277 /* The parsed sequence may be _the_ output, so ensure we don't
1278 * include the metacharacter, then. */
1279 if(flags & (n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_META_KEEP))
1280 ++il, --ib;
1281 /*last_known_meta_trim_len = UI32_MAX;*/
1282 break;
1284 state |= a_NTOKEN;
1285 }else
1286 state &= ~a_NTOKEN;
1288 if(blnk && store != NULL){
1289 if(last_known_meta_trim_len == UI32_MAX)
1290 last_known_meta_trim_len = store->s_len;
1291 }else
1292 last_known_meta_trim_len = UI32_MAX;
1294 }else{
1295 /* Quote-mode */
1296 assert(!(state & a_NTOKEN));
1297 if(c == quotec && !(flags & n_SHEXP_PARSE_QUOTE_AUTO_FIXED)){
1298 state &= a_ROUND_MASK;
1299 quotec = '\0';
1300 /* Users may need to recognize the presence of empty quotes */
1301 rv |= n_SHEXP_STATE_OUTPUT;
1302 continue;
1303 }else if(c == '\\' && (state & a_SURPLUS)){
1304 ib_save = ib - 1;
1305 /* A sole <reverse solidus> at EOS is treated as-is! This is ok
1306 * since the "closing quote" error will occur next, anyway */
1307 if(il == 0)
1308 break;
1309 else if((c2 = *ib) == quotec){
1310 --il, ++ib;
1311 c = quotec;
1312 }else if(quotec == '"'){
1313 /* Double quotes, POSIX says:
1314 * The <backslash> shall retain its special meaning as an
1315 * escape character (see Section 2.2.1) only when followed
1316 * by one of the following characters when considered
1317 * special: $ ` " \ <newline> */
1318 switch(c2){
1319 case '$':
1320 case '`':
1321 /* case '"': already handled via c2 == quotec */
1322 case '\\':
1323 --il, ++ib;
1324 c = c2;
1325 /* FALLTHRU */
1326 default:
1327 break;
1329 }else{
1330 /* Dollar-single-quote */
1331 --il, ++ib;
1332 switch(c2){
1333 case '"':
1334 /* case '\'': already handled via c2 == quotec */
1335 case '\\':
1336 c = c2;
1337 break;
1339 case 'b': c = '\b'; break;
1340 case 'f': c = '\f'; break;
1341 case 'n': c = '\n'; break;
1342 case 'r': c = '\r'; break;
1343 case 't': c = '\t'; break;
1344 case 'v': c = '\v'; break;
1346 case 'E':
1347 case 'e': c = '\033'; break;
1349 /* Control character */
1350 case 'c':
1351 if(il == 0)
1352 goto j_dollar_ungetc;
1353 --il, c2 = *ib++;
1354 if(state & a_SKIPMASK)
1355 continue;
1356 c = upperconv(c2) ^ 0x40;
1357 if((ui8_t)c > 0x1F && c != 0x7F){ /* ASCII C0: 0..1F, 7F */
1358 if(flags & n_SHEXP_PARSE_LOG)
1359 n_err(_("Invalid \\c notation: %.*s\n"),
1360 (int)input->l, input->s);
1361 rv |= n_SHEXP_STATE_ERR_CONTROL;
1363 /* As an implementation-defined extension, support \c@
1364 * EQ printf(1) alike \c */
1365 if(c == '\0'){
1366 state |= a_SKIPT;
1367 continue;
1369 break;
1371 /* Octal sequence: 1 to 3 octal bytes */
1372 case '0':
1373 /* As an extension (dependent on where you look, echo(1), or
1374 * awk(1)/tr(1) etc.), allow leading "0" octal indicator */
1375 if(il > 0 && (c = *ib) >= '0' && c <= '7'){
1376 c2 = c;
1377 --il, ++ib;
1379 /* FALLTHRU */
1380 case '1': case '2': case '3':
1381 case '4': case '5': case '6': case '7':
1382 c2 -= '0';
1383 if(il > 0 && (c = *ib) >= '0' && c <= '7'){
1384 c2 = (c2 << 3) | (c - '0');
1385 --il, ++ib;
1387 if(il > 0 && (c = *ib) >= '0' && c <= '7'){
1388 if(!(state & a_SKIPMASK) && (ui8_t)c2 > 0x1F){
1389 if(flags & n_SHEXP_PARSE_LOG)
1390 n_err(_("\\0 argument exceeds a byte: %.*s\n"),
1391 (int)input->l, input->s);
1392 rv |= n_SHEXP_STATE_ERR_NUMBER;
1393 --il, ++ib;
1394 /* Write unchanged */
1395 je_ib_save:
1396 rv |= n_SHEXP_STATE_OUTPUT;
1397 if(!(flags & n_SHEXP_PARSE_DRYRUN))
1398 store = n_string_push_buf(store, ib_save,
1399 PTR2SIZE(ib - ib_save));
1400 continue;
1402 c2 = (c2 << 3) | (c -= '0');
1403 --il, ++ib;
1405 if(state & a_SKIPMASK)
1406 continue;
1407 if((c = c2) == '\0'){
1408 state |= a_SKIPQ;
1409 continue;
1411 break;
1413 /* ISO 10646 / Unicode sequence, 8 or 4 hexadecimal bytes */
1414 case 'U':
1415 i = 8;
1416 if(0){
1417 /* FALLTHRU */
1418 case 'u':
1419 i = 4;
1421 if(il == 0)
1422 goto j_dollar_ungetc;
1423 if(0){
1424 /* FALLTHRU */
1426 /* Hexadecimal sequence, 1 or 2 hexadecimal bytes */
1427 case 'X':
1428 case 'x':
1429 if(il == 0)
1430 goto j_dollar_ungetc;
1431 i = 2;
1433 /* C99 */{
1434 static ui8_t const hexatoi[] = { /* XXX uses ASCII */
1435 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
1437 size_t no, j;
1439 i = n_MIN(il, i);
1440 for(no = j = 0; i-- > 0; --il, ++ib, ++j){
1441 c = *ib;
1442 if(hexchar(c)){
1443 no <<= 4;
1444 no += hexatoi[(ui8_t)((c) - ((c) <= '9' ? 48
1445 : ((c) <= 'F' ? 55 : 87)))];
1446 }else if(j == 0){
1447 if(state & a_SKIPMASK)
1448 break;
1449 c2 = (c2 == 'U' || c2 == 'u') ? 'u' : 'x';
1450 if(flags & n_SHEXP_PARSE_LOG)
1451 n_err(_("Invalid \\%c notation: %.*s\n"),
1452 c2, (int)input->l, input->s);
1453 rv |= n_SHEXP_STATE_ERR_NUMBER;
1454 goto je_ib_save;
1455 }else
1456 break;
1459 /* Unicode massage */
1460 if((c2 != 'U' && c2 != 'u') || n_uasciichar(no)){
1461 if((c = (char)no) == '\0')
1462 state |= a_SKIPQ;
1463 }else if(no == 0)
1464 state |= a_SKIPQ;
1465 else if(!(state & a_SKIPMASK)){
1466 if(!(flags & n_SHEXP_PARSE_DRYRUN))
1467 store = n_string_reserve(store, n_MAX(j, 4));
1469 if(no > 0x10FFFF){ /* XXX magic; CText */
1470 if(flags & n_SHEXP_PARSE_LOG)
1471 n_err(_("\\U argument exceeds 0x10FFFF: %.*s\n"),
1472 (int)input->l, input->s);
1473 rv |= n_SHEXP_STATE_ERR_NUMBER;
1474 /* But normalize the output anyway */
1475 goto Je_uni_norm;
1478 j = n_utf32_to_utf8(no, utf);
1480 if(n_psonce & n_PSO_UNICODE){
1481 rv |= n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_UNICODE;
1482 if(!(flags & n_SHEXP_PARSE_DRYRUN))
1483 store = n_string_push_buf(store, utf, j);
1484 continue;
1486 #ifdef HAVE_ICONV
1487 else{
1488 char *icp;
1490 icp = n_iconv_onetime_cp(n_ICONV_NONE,
1491 NULL, NULL, utf);
1492 if(icp != NULL){
1493 rv |= n_SHEXP_STATE_OUTPUT;
1494 if(!(flags & n_SHEXP_PARSE_DRYRUN))
1495 store = n_string_push_cp(store, icp);
1496 continue;
1499 #endif
1500 if(!(flags & n_SHEXP_PARSE_DRYRUN)) Je_uni_norm:{
1501 char itoa[32];
1503 rv |= n_SHEXP_STATE_OUTPUT |
1504 n_SHEXP_STATE_ERR_UNICODE;
1505 i = snprintf(itoa, sizeof itoa, "\\%c%0*X",
1506 (no > 0xFFFFu ? 'U' : 'u'),
1507 (int)(no > 0xFFFFu ? 8 : 4), (ui32_t)no);
1508 store = n_string_push_buf(store, itoa, i);
1510 continue;
1512 if(state & a_SKIPMASK)
1513 continue;
1515 break;
1517 /* Extension: \$ can be used to expand a variable.
1518 * Bug|ad effect: if conversion fails, not written "as-is" */
1519 case '$':
1520 if(il == 0)
1521 goto j_dollar_ungetc;
1522 goto J_var_expand;
1524 default:
1525 j_dollar_ungetc:
1526 /* Follow bash(1) behaviour, print sequence unchanged */
1527 ++il, --ib;
1528 break;
1531 }else if(c == '$' && quotec == '"' && il > 0) J_var_expand:{
1532 state &= ~a_VARSUBST_MASK;
1533 if(*ib == '{')
1534 state |= a_BRACE;
1536 if(!(state & a_BRACE) || il > 1){
1537 char const *cp, *vp;
1539 ib_save = ib - 1;
1540 if(state & a_BRACE)
1541 --il, ++ib;
1542 vp = ib;
1543 state &= ~a_EXPLODE;
1545 for(i = 0; il > 0; --il, ++ib, ++i){
1546 /* We have some special cases regarding special parameters,
1547 * so ensure these don't cause failure. This code has
1548 * counterparts in code that manages internal variables! */
1549 c = *ib;
1550 if(!a_SHEXP_ISVARC(c)){
1551 if(i == 0 && (c == '*' || c == '@' || c == '#' ||
1552 c == '?' || c == '!' || c == '^')){
1553 /* Skip over multiplexer */
1554 if(c == '^')
1555 continue;
1556 if(c == '@'){
1557 if(quotec == '"')
1558 state |= a_EXPLODE;
1560 --il, ++ib;
1561 ++i;
1563 break;
1564 }else if(a_SHEXP_ISVARC_BAD1ST(c)){
1565 if(i == 0)
1566 state |= a_DIGIT1;
1567 }else
1568 state |= a_NONDIGIT;
1571 if(state & a_SKIPMASK){
1572 if((state & a_BRACE) && il > 0 && *ib == '}')
1573 --il, ++ib;
1574 continue;
1577 if((state & (a_DIGIT1 | a_NONDIGIT)) == (a_DIGIT1 | a_NONDIGIT)){
1578 if(state & a_BRACE){
1579 if(il > 0 && *ib == '}')
1580 --il, ++ib;
1581 else
1582 rv |= n_SHEXP_STATE_ERR_BRACE;
1584 if(flags & n_SHEXP_PARSE_LOG)
1585 n_err(_("Invalid identifier for ${}: %.*s\n"),
1586 (int)input->l, input->s);
1587 rv |= n_SHEXP_STATE_ERR_IDENTIFIER;
1588 goto je_ib_save;
1589 }else if(i == 0){
1590 if(state & a_BRACE){
1591 if(flags & n_SHEXP_PARSE_LOG)
1592 n_err(_("Bad substitution for ${}: %.*s\n"),
1593 (int)input->l, input->s);
1594 rv |= n_SHEXP_STATE_ERR_BADSUB;
1595 if(il > 0 && *ib == '}')
1596 --il, ++ib;
1597 else
1598 rv |= n_SHEXP_STATE_ERR_BRACE;
1599 goto je_ib_save;
1601 c = '$';
1602 }else{
1603 if(state & a_BRACE){
1604 if(il == 0 || *ib != '}'){
1605 if(flags & n_SHEXP_PARSE_LOG)
1606 n_err(_("No closing brace for ${}: %.*s\n"),
1607 (int)input->l, input->s);
1608 rv |= n_SHEXP_STATE_ERR_QUOTEOPEN |
1609 n_SHEXP_STATE_ERR_BRACE;
1610 goto je_ib_save;
1612 --il, ++ib;
1615 if(flags & n_SHEXP_PARSE_DRYRUN)
1616 continue;
1618 /* We may shall explode "${@}" to a series of successive,
1619 * properly quoted tokens (instead). The first exploded
1620 * cookie will join with the current token */
1621 if((state & a_EXPLODE) && !(flags & n_SHEXP_PARSE_DRYRUN) &&
1622 cookie != NULL){
1623 if(n_var_vexplode(cookie))
1624 state |= a_COOKIE;
1625 /* On the other hand, if $@ expands to nothing and is the
1626 * sole content of this quote then act like the shell does
1627 * and throw away the entire atxplode construct */
1628 else if(!(rv & n_SHEXP_STATE_OUTPUT) &&
1629 il == 1 && *ib == '"' &&
1630 ib_save == &input->s[1] && ib_save[-1] == '"')
1631 ++ib, --il;
1632 else
1633 continue;
1634 input->s = n_UNCONST(ib);
1635 input->l = il;
1636 goto jrestart_empty;
1639 /* Check getenv(3) shall no internal variable exist!
1640 * XXX We have some common idioms, avoid memory for them
1641 * XXX Even better would be var_vlook_buf()! */
1642 if(i == 1){
1643 switch(*vp){
1644 case '?': vp = n_qm; break;
1645 case '!': vp = n_em; break;
1646 case '*': vp = n_star; break;
1647 case '@': vp = n_at; break;
1648 case '#': vp = n_ns; break;
1649 default: goto j_var_look_buf;
1651 }else
1652 j_var_look_buf:
1653 vp = savestrbuf(vp, i);
1655 if((cp = n_var_vlook(vp, TRU1)) != NULL){
1656 rv |= n_SHEXP_STATE_OUTPUT;
1657 store = n_string_push_cp(store, cp);
1658 for(; (c = *cp) != '\0'; ++cp)
1659 if(cntrlchar(c)){
1660 rv |= n_SHEXP_STATE_CONTROL;
1661 break;
1664 continue;
1667 }else if(c == '`' && quotec == '"' && il > 0){ /* TODO shell command */
1668 continue;
1672 if(!(state & a_SKIPMASK)){
1673 rv |= n_SHEXP_STATE_OUTPUT;
1674 if(cntrlchar(c))
1675 rv |= n_SHEXP_STATE_CONTROL;
1676 if(!(flags & n_SHEXP_PARSE_DRYRUN))
1677 store = n_string_push_c(store, c);
1681 if(quotec != '\0' && !(flags & n_SHEXP_PARSE_QUOTE_AUTO_CLOSE)){
1682 if(flags & n_SHEXP_PARSE_LOG)
1683 n_err(_("No closing quote: %.*s\n"), (int)input->l, input->s);
1684 rv |= n_SHEXP_STATE_ERR_QUOTEOPEN;
1687 jleave:
1688 assert(!(state & a_COOKIE));
1689 if((flags & n_SHEXP_PARSE_DRYRUN) && store != NULL){
1690 store = n_string_push_buf(store, input->s, PTR2SIZE(ib - input->s));
1691 rv |= n_SHEXP_STATE_OUTPUT;
1694 if(state & a_CONSUME){
1695 input->s = n_UNCONST(&ib[il]);
1696 input->l = 0;
1697 }else{
1698 if(flags & n_SHEXP_PARSE_TRIM_SPACE){
1699 for(; il > 0; ++ib, --il){
1700 if(!blankspacechar(*ib))
1701 break;
1702 rv |= n_SHEXP_STATE_WS_TRAIL;
1706 if(flags & n_SHEXP_PARSE_TRIM_IFSSPACE){
1707 for(; il > 0; ++ib, --il){
1708 if(strchr(ifs_ws, *ib) == NULL)
1709 break;
1710 rv |= n_SHEXP_STATE_WS_TRAIL;
1714 input->l = il;
1715 input->s = n_UNCONST(ib);
1718 if(!(rv & n_SHEXP_STATE_STOP)){
1719 if(!(rv & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_META_MASK)) &&
1720 (flags & n_SHEXP_PARSE_IGNORE_EMPTY) && il > 0)
1721 goto jrestart_empty;
1722 if(/*!(rv & n_SHEXP_STATE_OUTPUT) &&*/ il == 0)
1723 rv |= n_SHEXP_STATE_STOP;
1726 if((state & a_SKIPT) && !(rv & n_SHEXP_STATE_STOP) &&
1727 (flags & n_SHEXP_PARSE_META_MASK))
1728 goto jrestart;
1729 jleave_quick:
1730 assert((rv & n_SHEXP_STATE_OUTPUT) || !(rv & n_SHEXP_STATE_UNICODE));
1731 assert((rv & n_SHEXP_STATE_OUTPUT) || !(rv & n_SHEXP_STATE_CONTROL));
1732 NYD2_LEAVE;
1733 return rv;
1736 FL char *
1737 n_shexp_parse_token_cp(enum n_shexp_parse_flags flags, char const **cp){
1738 struct str input;
1739 struct n_string sou, *soup;
1740 char *rv;
1741 enum n_shexp_state shs;
1742 NYD2_ENTER;
1744 assert(cp != NULL);
1746 input.s = n_UNCONST(*cp);
1747 input.l = UIZ_MAX;
1748 soup = n_string_creat_auto(&sou);
1750 shs = n_shexp_parse_token(flags, soup, &input, NULL);
1751 if(shs & n_SHEXP_STATE_ERR_MASK){
1752 soup = n_string_assign_cp(soup, *cp);
1753 *cp = NULL;
1754 }else
1755 *cp = input.s;
1757 rv = n_string_cp(soup);
1758 /*n_string_gut(n_string_drop_ownership(soup));*/
1759 NYD2_LEAVE;
1760 return rv;
1763 FL struct n_string *
1764 n_shexp_quote(struct n_string *store, struct str const *input, bool_t rndtrip){
1765 struct a_shexp_quote_lvl sql;
1766 struct a_shexp_quote_ctx sqc;
1767 NYD2_ENTER;
1769 assert(store != NULL);
1770 assert(input != NULL);
1771 assert(input->l == 0 || input->s != NULL);
1773 memset(&sqc, 0, sizeof sqc);
1774 sqc.sqc_store = store;
1775 sqc.sqc_input.s = input->s;
1776 if((sqc.sqc_input.l = input->l) == UIZ_MAX)
1777 sqc.sqc_input.l = strlen(input->s);
1778 sqc.sqc_flags = rndtrip ? a_SHEXP_QUOTE_ROUNDTRIP : a_SHEXP_QUOTE_NONE;
1780 if(sqc.sqc_input.l == 0)
1781 store = n_string_push_buf(store, "''", sizeof("''") -1);
1782 else{
1783 memset(&sql, 0, sizeof sql);
1784 sql.sql_dat = sqc.sqc_input;
1785 sql.sql_flags = sqc.sqc_flags;
1786 a_shexp__quote(&sqc, &sql);
1788 NYD2_LEAVE;
1789 return store;
1792 FL char *
1793 n_shexp_quote_cp(char const *cp, bool_t rndtrip){
1794 struct n_string store;
1795 struct str input;
1796 char *rv;
1797 NYD2_ENTER;
1799 assert(cp != NULL);
1801 input.s = n_UNCONST(cp);
1802 input.l = UIZ_MAX;
1803 rv = n_string_cp(n_shexp_quote(n_string_creat_auto(&store), &input,
1804 rndtrip));
1805 n_string_gut(n_string_drop_ownership(&store));
1806 NYD2_LEAVE;
1807 return rv;
1810 FL bool_t
1811 n_shexp_is_valid_varname(char const *name){
1812 char lc, c;
1813 bool_t rv;
1814 NYD2_ENTER;
1816 rv = FAL0;
1818 for(lc = '\0'; (c = *name++) != '\0'; lc = c)
1819 if(!a_SHEXP_ISVARC(c))
1820 goto jleave;
1821 else if(lc == '\0' && a_SHEXP_ISVARC_BAD1ST(c))
1822 goto jleave;
1823 if(a_SHEXP_ISVARC_BADNST(lc))
1824 goto jleave;
1826 rv = TRU1;
1827 jleave:
1828 NYD2_LEAVE;
1829 return rv;
1832 FL int
1833 c_shcodec(void *vp){
1834 struct str in;
1835 struct n_string sou_b, *soup;
1836 si32_t nerrn;
1837 size_t alen;
1838 bool_t norndtrip;
1839 char const **argv, *varname, *act, *cp;
1841 soup = n_string_creat_auto(&sou_b);
1842 argv = vp;
1843 varname = (n_pstate & n_PS_ARGMOD_VPUT) ? *argv++ : NULL;
1845 act = *argv;
1846 for(cp = act; *cp != '\0' && !blankspacechar(*cp); ++cp)
1848 if((norndtrip = (*act == '+')))
1849 ++act;
1850 if(act == cp)
1851 goto jesynopsis;
1852 alen = PTR2SIZE(cp - act);
1853 if(*cp != '\0')
1854 ++cp;
1856 in.l = strlen(in.s = n_UNCONST(cp));
1857 nerrn = n_ERR_NONE;
1859 if(is_ascncaseprefix(act, "encode", alen))
1860 soup = n_shexp_quote(soup, &in, !norndtrip);
1861 else if(!norndtrip && is_ascncaseprefix(act, "decode", alen)){
1862 for(;;){
1863 enum n_shexp_state shs;
1865 shs = n_shexp_parse_token((n_SHEXP_PARSE_LOG |
1866 n_SHEXP_PARSE_IGNORE_EMPTY), soup, &in, NULL);
1867 if(shs & n_SHEXP_STATE_ERR_MASK){
1868 soup = n_string_assign_cp(soup, cp);
1869 nerrn = n_ERR_CANCELED;
1870 vp = NULL;
1871 break;
1873 if(shs & n_SHEXP_STATE_STOP)
1874 break;
1876 }else
1877 goto jesynopsis;
1879 if(varname != NULL){
1880 cp = n_string_cp(soup);
1881 if(!n_var_vset(varname, (uintptr_t)cp)){
1882 nerrn = n_ERR_NOTSUP;
1883 vp = NULL;
1885 }else{
1886 struct str out;
1888 in.s = n_string_cp(soup);
1889 in.l = soup->s_len;
1890 makeprint(&in, &out);
1891 if(fprintf(n_stdout, "%s\n", out.s) < 0){
1892 nerrn = n_err_no;
1893 vp = NULL;
1895 free(out.s);
1898 jleave:
1899 n_pstate_err_no = nerrn;
1900 NYD_LEAVE;
1901 return (vp != NULL ? 0 : 1);
1902 jesynopsis:
1903 n_err(_("Synopsis: shcodec: <[+]e[ncode]|d[ecode]> <rest-of-line>\n"));
1904 nerrn = n_ERR_INVAL;
1905 vp = NULL;
1906 goto jleave;
1909 /* s-it-mode */