1/* POSIX.2 wordexp implementation.
2 Copyright (C) 1997-2020 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Tim Waugh <tim@cyberelk.demon.co.uk>.
5
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
10
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <https://www.gnu.org/licenses/>. */
19
20#include <ctype.h>
21#include <errno.h>
22#include <fcntl.h>
23#include <fnmatch.h>
24#include <glob.h>
25#include <libintl.h>
26#include <paths.h>
27#include <pwd.h>
28#include <stdbool.h>
29#include <stdio.h>
30#include <string.h>
31#include <sys/param.h>
32#include <sys/wait.h>
33#include <unistd.h>
34#include <wordexp.h>
35#include <spawn.h>
36#include <scratch_buffer.h>
37#include <_itoa.h>
38#include <assert.h>
39
40/*
41 * This is a recursive-descent-style word expansion routine.
42 */
43
44/* These variables are defined and initialized in the startup code. */
45extern int __libc_argc attribute_hidden;
46extern char **__libc_argv attribute_hidden;
47
48/* Some forward declarations */
49static int parse_dollars (char **word, size_t *word_length, size_t *max_length,
50 const char *words, size_t *offset, int flags,
51 wordexp_t *pwordexp, const char *ifs,
52 const char *ifs_white, int quoted);
53static int parse_backtick (char **word, size_t *word_length,
54 size_t *max_length, const char *words,
55 size_t *offset, int flags, wordexp_t *pwordexp,
56 const char *ifs, const char *ifs_white);
57static int parse_dquote (char **word, size_t *word_length, size_t *max_length,
58 const char *words, size_t *offset, int flags,
59 wordexp_t *pwordexp, const char *ifs,
60 const char *ifs_white);
61static int eval_expr (char *expr, long int *result);
62
63/* The w_*() functions manipulate word lists. */
64
65#define W_CHUNK (100)
66
67/* Result of w_newword will be ignored if it's the last word. */
68static inline char *
69w_newword (size_t *actlen, size_t *maxlen)
70{
71 *actlen = *maxlen = 0;
72 return NULL;
73}
74
75static char *
76w_addchar (char *buffer, size_t *actlen, size_t *maxlen, char ch)
77 /* (lengths exclude trailing zero) */
78{
79 /* Add a character to the buffer, allocating room for it if needed. */
80
81 if (*actlen == *maxlen)
82 {
83 char *old_buffer = buffer;
84 assert (buffer == NULL || *maxlen != 0);
85 *maxlen += W_CHUNK;
86 buffer = (char *) realloc (buffer, 1 + *maxlen);
87
88 if (buffer == NULL)
89 free (old_buffer);
90 }
91
92 if (buffer != NULL)
93 {
94 buffer[*actlen] = ch;
95 buffer[++(*actlen)] = '\0';
96 }
97
98 return buffer;
99}
100
101static char *
102w_addmem (char *buffer, size_t *actlen, size_t *maxlen, const char *str,
103 size_t len)
104{
105 /* Add a string to the buffer, allocating room for it if needed.
106 */
107 if (*actlen + len > *maxlen)
108 {
109 char *old_buffer = buffer;
110 assert (buffer == NULL || *maxlen != 0);
111 *maxlen += MAX (2 * len, W_CHUNK);
112 buffer = realloc (old_buffer, 1 + *maxlen);
113
114 if (buffer == NULL)
115 free (old_buffer);
116 }
117
118 if (buffer != NULL)
119 {
120 *((char *) __mempcpy (&buffer[*actlen], str, len)) = '\0';
121 *actlen += len;
122 }
123
124 return buffer;
125}
126
127static char *
128w_addstr (char *buffer, size_t *actlen, size_t *maxlen, const char *str)
129 /* (lengths exclude trailing zero) */
130{
131 /* Add a string to the buffer, allocating room for it if needed.
132 */
133 size_t len;
134
135 assert (str != NULL); /* w_addstr only called from this file */
136 len = strlen (str);
137
138 return w_addmem (buffer, actlen, maxlen, str, len);
139}
140
141static int
142w_addword (wordexp_t *pwordexp, char *word)
143{
144 /* Add a word to the wordlist */
145 size_t num_p;
146 char **new_wordv;
147 bool allocated = false;
148
149 /* Internally, NULL acts like "". Convert NULLs to "" before
150 * the caller sees them.
151 */
152 if (word == NULL)
153 {
154 word = __strdup ("");
155 if (word == NULL)
156 goto no_space;
157 allocated = true;
158 }
159
160 num_p = 2 + pwordexp->we_wordc + pwordexp->we_offs;
161 new_wordv = realloc (pwordexp->we_wordv, sizeof (char *) * num_p);
162 if (new_wordv != NULL)
163 {
164 pwordexp->we_wordv = new_wordv;
165 pwordexp->we_wordv[pwordexp->we_offs + pwordexp->we_wordc++] = word;
166 pwordexp->we_wordv[pwordexp->we_offs + pwordexp->we_wordc] = NULL;
167 return 0;
168 }
169
170 if (allocated)
171 free (word);
172
173no_space:
174 return WRDE_NOSPACE;
175}
176
177/* The parse_*() functions should leave *offset being the offset in 'words'
178 * to the last character processed.
179 */
180
181static int
182parse_backslash (char **word, size_t *word_length, size_t *max_length,
183 const char *words, size_t *offset)
184{
185 /* We are poised _at_ a backslash, not in quotes */
186
187 switch (words[1 + *offset])
188 {
189 case 0:
190 /* Backslash is last character of input words */
191 return WRDE_SYNTAX;
192
193 case '\n':
194 ++(*offset);
195 break;
196
197 default:
198 *word = w_addchar (*word, word_length, max_length, words[1 + *offset]);
199 if (*word == NULL)
200 return WRDE_NOSPACE;
201
202 ++(*offset);
203 break;
204 }
205
206 return 0;
207}
208
209static int
210parse_qtd_backslash (char **word, size_t *word_length, size_t *max_length,
211 const char *words, size_t *offset)
212{
213 /* We are poised _at_ a backslash, inside quotes */
214
215 switch (words[1 + *offset])
216 {
217 case 0:
218 /* Backslash is last character of input words */
219 return WRDE_SYNTAX;
220
221 case '\n':
222 ++(*offset);
223 break;
224
225 case '$':
226 case '`':
227 case '"':
228 case '\\':
229 *word = w_addchar (*word, word_length, max_length, words[1 + *offset]);
230 if (*word == NULL)
231 return WRDE_NOSPACE;
232
233 ++(*offset);
234 break;
235
236 default:
237 *word = w_addchar (*word, word_length, max_length, words[*offset]);
238 if (*word != NULL)
239 *word = w_addchar (*word, word_length, max_length, words[1 + *offset]);
240
241 if (*word == NULL)
242 return WRDE_NOSPACE;
243
244 ++(*offset);
245 break;
246 }
247
248 return 0;
249}
250
251static int
252parse_tilde (char **word, size_t *word_length, size_t *max_length,
253 const char *words, size_t *offset, size_t wordc)
254{
255 /* We are poised _at_ a tilde */
256 size_t i;
257
258 if (*word_length != 0)
259 {
260 if (!((*word)[*word_length - 1] == '=' && wordc == 0))
261 {
262 if (!((*word)[*word_length - 1] == ':'
263 && strchr (*word, '=') && wordc == 0))
264 {
265 *word = w_addchar (*word, word_length, max_length, '~');
266 return *word ? 0 : WRDE_NOSPACE;
267 }
268 }
269 }
270
271 for (i = 1 + *offset; words[i]; i++)
272 {
273 if (words[i] == ':' || words[i] == '/' || words[i] == ' '
274 || words[i] == '\t' || words[i] == 0 )
275 break;
276
277 if (words[i] == '\\')
278 {
279 *word = w_addchar (*word, word_length, max_length, '~');
280 return *word ? 0 : WRDE_NOSPACE;
281 }
282 }
283
284 if (i == 1 + *offset)
285 {
286 /* Tilde appears on its own */
287 char* home;
288
289 /* POSIX.2 says ~ expands to $HOME and if HOME is unset the
290 results are unspecified. We do a lookup on the uid if
291 HOME is unset. */
292
293 home = getenv ("HOME");
294 if (home != NULL)
295 {
296 *word = w_addstr (*word, word_length, max_length, home);
297 if (*word == NULL)
298 return WRDE_NOSPACE;
299 }
300 else
301 {
302 struct passwd pwd, *tpwd;
303 uid_t uid = __getuid ();
304 int result;
305 struct scratch_buffer tmpbuf;
306 scratch_buffer_init (&tmpbuf);
307
308 while ((result = __getpwuid_r (uid, &pwd,
309 tmpbuf.data, tmpbuf.length,
310 &tpwd)) != 0
311 && errno == ERANGE)
312 if (!scratch_buffer_grow (&tmpbuf))
313 return WRDE_NOSPACE;
314
315 if (result == 0 && tpwd != NULL && pwd.pw_dir != NULL)
316 {
317 *word = w_addstr (*word, word_length, max_length, pwd.pw_dir);
318 if (*word == NULL)
319 {
320 scratch_buffer_free (&tmpbuf);
321 return WRDE_NOSPACE;
322 }
323 }
324 else
325 {
326 *word = w_addchar (*word, word_length, max_length, '~');
327 if (*word == NULL)
328 {
329 scratch_buffer_free (&tmpbuf);
330 return WRDE_NOSPACE;
331 }
332 }
333 scratch_buffer_free (&tmpbuf);
334 }
335 }
336 else
337 {
338 /* Look up user name in database to get home directory */
339 char *user = strndupa (&words[1 + *offset], i - (1 + *offset));
340 struct passwd pwd, *tpwd;
341 int result;
342 struct scratch_buffer tmpbuf;
343 scratch_buffer_init (&tmpbuf);
344
345 while ((result = __getpwnam_r (user, &pwd, tmpbuf.data, tmpbuf.length,
346 &tpwd)) != 0
347 && errno == ERANGE)
348 if (!scratch_buffer_grow (&tmpbuf))
349 return WRDE_NOSPACE;
350
351 if (result == 0 && tpwd != NULL && pwd.pw_dir)
352 *word = w_addstr (*word, word_length, max_length, pwd.pw_dir);
353 else
354 {
355 /* (invalid login name) */
356 *word = w_addchar (*word, word_length, max_length, '~');
357 if (*word != NULL)
358 *word = w_addstr (*word, word_length, max_length, user);
359 }
360
361 scratch_buffer_free (&tmpbuf);
362
363 *offset = i - 1;
364 }
365 return *word ? 0 : WRDE_NOSPACE;
366}
367
368
369static int
370do_parse_glob (const char *glob_word, char **word, size_t *word_length,
371 size_t *max_length, wordexp_t *pwordexp, const char *ifs,
372 const char *ifs_white)
373{
374 int error;
375 unsigned int match;
376 glob_t globbuf;
377
378 error = glob (glob_word, GLOB_NOCHECK, NULL, &globbuf);
379
380 if (error != 0)
381 {
382 /* We can only run into memory problems. */
383 assert (error == GLOB_NOSPACE);
384 return WRDE_NOSPACE;
385 }
386
387 if (ifs && !*ifs)
388 {
389 /* No field splitting allowed. */
390 assert (globbuf.gl_pathv[0] != NULL);
391 *word = w_addstr (*word, word_length, max_length, globbuf.gl_pathv[0]);
392 for (match = 1; match < globbuf.gl_pathc && *word != NULL; ++match)
393 {
394 *word = w_addchar (*word, word_length, max_length, ' ');
395 if (*word != NULL)
396 *word = w_addstr (*word, word_length, max_length,
397 globbuf.gl_pathv[match]);
398 }
399
400 globfree (&globbuf);
401 return *word ? 0 : WRDE_NOSPACE;
402 }
403
404 assert (ifs == NULL || *ifs != '\0');
405 if (*word != NULL)
406 {
407 free (*word);
408 *word = w_newword (word_length, max_length);
409 }
410
411 for (match = 0; match < globbuf.gl_pathc; ++match)
412 {
413 char *matching_word = __strdup (globbuf.gl_pathv[match]);
414 if (matching_word == NULL || w_addword (pwordexp, matching_word))
415 {
416 globfree (&globbuf);
417 return WRDE_NOSPACE;
418 }
419 }
420
421 globfree (&globbuf);
422 return 0;
423}
424
425static int
426parse_glob (char **word, size_t *word_length, size_t *max_length,
427 const char *words, size_t *offset, int flags,
428 wordexp_t *pwordexp, const char *ifs, const char *ifs_white)
429{
430 /* We are poised just after a '*', a '[' or a '?'. */
431 int error = WRDE_NOSPACE;
432 int quoted = 0; /* 1 if singly-quoted, 2 if doubly */
433 size_t i;
434 wordexp_t glob_list; /* List of words to glob */
435
436 glob_list.we_wordc = 0;
437 glob_list.we_wordv = NULL;
438 glob_list.we_offs = 0;
439 for (; words[*offset] != '\0'; ++*offset)
440 {
441 if (strchr (ifs, words[*offset]) != NULL)
442 /* Reached IFS */
443 break;
444
445 /* Sort out quoting */
446 if (words[*offset] == '\'')
447 {
448 if (quoted == 0)
449 {
450 quoted = 1;
451 continue;
452 }
453 else if (quoted == 1)
454 {
455 quoted = 0;
456 continue;
457 }
458 }
459 else if (words[*offset] == '"')
460 {
461 if (quoted == 0)
462 {
463 quoted = 2;
464 continue;
465 }
466 else if (quoted == 2)
467 {
468 quoted = 0;
469 continue;
470 }
471 }
472
473 /* Sort out other special characters */
474 if (quoted != 1 && words[*offset] == '$')
475 {
476 error = parse_dollars (word, word_length, max_length, words,
477 offset, flags, &glob_list, ifs, ifs_white,
478 quoted == 2);
479 if (error)
480 goto tidy_up;
481
482 continue;
483 }
484 else if (words[*offset] == '\\')
485 {
486 if (quoted)
487 error = parse_qtd_backslash (word, word_length, max_length,
488 words, offset);
489 else
490 error = parse_backslash (word, word_length, max_length,
491 words, offset);
492
493 if (error)
494 goto tidy_up;
495
496 continue;
497 }
498
499 *word = w_addchar (*word, word_length, max_length, words[*offset]);
500 if (*word == NULL)
501 goto tidy_up;
502 }
503
504 /* Don't forget to re-parse the character we stopped at. */
505 --*offset;
506
507 /* Glob the words */
508 error = w_addword (&glob_list, *word);
509 *word = w_newword (word_length, max_length);
510 for (i = 0; error == 0 && i < glob_list.we_wordc; i++)
511 error = do_parse_glob (glob_list.we_wordv[i], word, word_length,
512 max_length, pwordexp, ifs, ifs_white);
513
514 /* Now tidy up */
515tidy_up:
516 wordfree (&glob_list);
517 return error;
518}
519
520static int
521parse_squote (char **word, size_t *word_length, size_t *max_length,
522 const char *words, size_t *offset)
523{
524 /* We are poised just after a single quote */
525 for (; words[*offset]; ++(*offset))
526 {
527 if (words[*offset] != '\'')
528 {
529 *word = w_addchar (*word, word_length, max_length, words[*offset]);
530 if (*word == NULL)
531 return WRDE_NOSPACE;
532 }
533 else return 0;
534 }
535
536 /* Unterminated string */
537 return WRDE_SYNTAX;
538}
539
540/* Functions to evaluate an arithmetic expression */
541static int
542eval_expr_val (char **expr, long int *result)
543{
544 char *digit;
545
546 /* Skip white space */
547 for (digit = *expr; digit && *digit && isspace (*digit); ++digit);
548
549 if (*digit == '(')
550 {
551 /* Scan for closing paren */
552 for (++digit; **expr && **expr != ')'; ++(*expr));
553
554 /* Is there one? */
555 if (!**expr)
556 return WRDE_SYNTAX;
557
558 *(*expr)++ = 0;
559
560 if (eval_expr (digit, result))
561 return WRDE_SYNTAX;
562
563 return 0;
564 }
565
566 /* POSIX requires that decimal, octal, and hexadecimal constants are
567 recognized. Therefore we pass 0 as the third parameter to strtol. */
568 *result = strtol (digit, expr, 0);
569 if (digit == *expr)
570 return WRDE_SYNTAX;
571
572 return 0;
573}
574
575static int
576eval_expr_multdiv (char **expr, long int *result)
577{
578 long int arg;
579
580 /* Read a Value */
581 if (eval_expr_val (expr, result) != 0)
582 return WRDE_SYNTAX;
583
584 while (**expr)
585 {
586 /* Skip white space */
587 for (; *expr && **expr && isspace (**expr); ++(*expr));
588
589 if (**expr == '*')
590 {
591 ++(*expr);
592 if (eval_expr_val (expr, &arg) != 0)
593 return WRDE_SYNTAX;
594
595 *result *= arg;
596 }
597 else if (**expr == '/')
598 {
599 ++(*expr);
600 if (eval_expr_val (expr, &arg) != 0)
601 return WRDE_SYNTAX;
602
603 /* Division by zero or integer overflow. */
604 if (arg == 0 || (arg == -1 && *result == LONG_MIN))
605 return WRDE_SYNTAX;
606
607 *result /= arg;
608 }
609 else break;
610 }
611
612 return 0;
613}
614
615static int
616eval_expr (char *expr, long int *result)
617{
618 long int arg;
619
620 /* Read a Multdiv */
621 if (eval_expr_multdiv (&expr, result) != 0)
622 return WRDE_SYNTAX;
623
624 while (*expr)
625 {
626 /* Skip white space */
627 for (; expr && *expr && isspace (*expr); ++expr);
628
629 if (*expr == '+')
630 {
631 ++expr;
632 if (eval_expr_multdiv (&expr, &arg) != 0)
633 return WRDE_SYNTAX;
634
635 *result += arg;
636 }
637 else if (*expr == '-')
638 {
639 ++expr;
640 if (eval_expr_multdiv (&expr, &arg) != 0)
641 return WRDE_SYNTAX;
642
643 *result -= arg;
644 }
645 else break;
646 }
647
648 return 0;
649}
650
651static int
652parse_arith (char **word, size_t *word_length, size_t *max_length,
653 const char *words, size_t *offset, int flags, int bracket)
654{
655 /* We are poised just after "$((" or "$[" */
656 int error;
657 int paren_depth = 1;
658 size_t expr_length;
659 size_t expr_maxlen;
660 char *expr;
661
662 expr = w_newword (&expr_length, &expr_maxlen);
663 for (; words[*offset]; ++(*offset))
664 {
665 switch (words[*offset])
666 {
667 case '$':
668 error = parse_dollars (&expr, &expr_length, &expr_maxlen,
669 words, offset, flags, NULL, NULL, NULL, 1);
670 /* The ``1'' here is to tell parse_dollars not to
671 * split the fields.
672 */
673 if (error)
674 {
675 free (expr);
676 return error;
677 }
678 break;
679
680 case '`':
681 (*offset)++;
682 error = parse_backtick (&expr, &expr_length, &expr_maxlen,
683 words, offset, flags, NULL, NULL, NULL);
684 /* The first NULL here is to tell parse_backtick not to
685 * split the fields.
686 */
687 if (error)
688 {
689 free (expr);
690 return error;
691 }
692 break;
693
694 case '\\':
695 error = parse_qtd_backslash (&expr, &expr_length, &expr_maxlen,
696 words, offset);
697 if (error)
698 {
699 free (expr);
700 return error;
701 }
702 /* I think that a backslash within an
703 * arithmetic expansion is bound to
704 * cause an error sooner or later anyway though.
705 */
706 break;
707
708 case ')':
709 if (--paren_depth == 0)
710 {
711 char result[21]; /* 21 = ceil(log10(2^64)) + 1 */
712 long int numresult = 0;
713 long long int convertme;
714
715 if (bracket || words[1 + *offset] != ')')
716 {
717 free (expr);
718 return WRDE_SYNTAX;
719 }
720
721 ++(*offset);
722
723 /* Go - evaluate. */
724 if (*expr && eval_expr (expr, &numresult) != 0)
725 {
726 free (expr);
727 return WRDE_SYNTAX;
728 }
729
730 if (numresult < 0)
731 {
732 convertme = -numresult;
733 *word = w_addchar (*word, word_length, max_length, '-');
734 if (!*word)
735 {
736 free (expr);
737 return WRDE_NOSPACE;
738 }
739 }
740 else
741 convertme = numresult;
742
743 result[20] = '\0';
744 *word = w_addstr (*word, word_length, max_length,
745 _itoa (convertme, &result[20], 10, 0));
746 free (expr);
747 return *word ? 0 : WRDE_NOSPACE;
748 }
749 expr = w_addchar (expr, &expr_length, &expr_maxlen, words[*offset]);
750 if (expr == NULL)
751 return WRDE_NOSPACE;
752
753 break;
754
755 case ']':
756 if (bracket && paren_depth == 1)
757 {
758 char result[21]; /* 21 = ceil(log10(2^64)) + 1 */
759 long int numresult = 0;
760
761 /* Go - evaluate. */
762 if (*expr && eval_expr (expr, &numresult) != 0)
763 {
764 free (expr);
765 return WRDE_SYNTAX;
766 }
767
768 result[20] = '\0';
769 *word = w_addstr (*word, word_length, max_length,
770 _itoa_word (numresult, &result[20], 10, 0));
771 free (expr);
772 return *word ? 0 : WRDE_NOSPACE;
773 }
774
775 free (expr);
776 return WRDE_SYNTAX;
777
778 case '\n':
779 case ';':
780 case '{':
781 case '}':
782 free (expr);
783 return WRDE_BADCHAR;
784
785 case '(':
786 ++paren_depth;
787 /* Fall through. */
788 default:
789 expr = w_addchar (expr, &expr_length, &expr_maxlen, words[*offset]);
790 if (expr == NULL)
791 return WRDE_NOSPACE;
792 }
793 }
794
795 /* Premature end */
796 free (expr);
797 return WRDE_SYNTAX;
798}
799
800#define DYNARRAY_STRUCT strlist
801#define DYNARRAY_ELEMENT char *
802#define DYNARRAY_PREFIX strlist_
803/* Allocates about 512/1024 (32/64 bit) on stack. */
804#define DYNARRAY_INITIAL_SIZE 128
805#include <malloc/dynarray-skeleton.c>
806
807/* Function called by child process in exec_comm() */
808static pid_t
809exec_comm_child (char *comm, int *fildes, bool showerr, bool noexec)
810{
811 pid_t pid = -1;
812
813 /* Execute the command, or just check syntax? */
814 const char *args[] = { _PATH_BSHELL, noexec ? "-nc" : "-c", comm, NULL };
815
816 posix_spawn_file_actions_t fa;
817 /* posix_spawn_file_actions_init does not fail. */
818 __posix_spawn_file_actions_init (&fa);
819
820 /* Redirect output. For check syntax only (noexec being true), exec_comm
821 explicits sets fildes[1] to -1, so check its value to avoid a failure in
822 __posix_spawn_file_actions_adddup2. */
823 if (fildes[1] != -1)
824 {
825 if (__glibc_likely (fildes[1] != STDOUT_FILENO))
826 {
827 if (__posix_spawn_file_actions_adddup2 (&fa, fildes[1],
828 STDOUT_FILENO) != 0
829 || __posix_spawn_file_actions_addclose (&fa, fildes[1]) != 0)
830 goto out;
831 }
832 else
833 /* Reset the close-on-exec flag (if necessary). */
834 if (__posix_spawn_file_actions_adddup2 (&fa, fildes[1], fildes[1])
835 != 0)
836 goto out;
837 }
838
839 /* Redirect stderr to /dev/null if we have to. */
840 if (!showerr)
841 if (__posix_spawn_file_actions_addopen (&fa, STDERR_FILENO, _PATH_DEVNULL,
842 O_WRONLY, 0) != 0)
843 goto out;
844
845 struct strlist newenv;
846 strlist_init (&newenv);
847
848 bool recreate_env = getenv ("IFS") != NULL;
849 if (recreate_env)
850 {
851 for (char **ep = __environ; *ep != NULL; ep++)
852 if (strncmp (*ep, "IFS=", strlen ("IFS=")) != 0)
853 strlist_add (&newenv, *ep);
854 strlist_add (&newenv, NULL);
855 if (strlist_has_failed (&newenv))
856 goto out;
857 }
858
859 /* pid is not set if posix_spawn fails, so it keep the original value
860 of -1. */
861 __posix_spawn (&pid, _PATH_BSHELL, &fa, NULL, (char *const *) args,
862 recreate_env ? strlist_begin (&newenv) : __environ);
863
864 strlist_free (&newenv);
865
866out:
867 __posix_spawn_file_actions_destroy (&fa);
868
869 return pid;
870}
871
872/* Function to execute a command and retrieve the results */
873/* pwordexp contains NULL if field-splitting is forbidden */
874static int
875exec_comm (char *comm, char **word, size_t *word_length, size_t *max_length,
876 int flags, wordexp_t *pwordexp, const char *ifs,
877 const char *ifs_white)
878{
879 int fildes[2];
880#define bufsize 128
881 int buflen;
882 int i;
883 int status = 0;
884 size_t maxnewlines = 0;
885 char buffer[bufsize];
886 pid_t pid;
887 bool noexec = false;
888
889 /* Do nothing if command substitution should not succeed. */
890 if (flags & WRDE_NOCMD)
891 return WRDE_CMDSUB;
892
893 /* Don't posix_spawn unless necessary */
894 if (!comm || !*comm)
895 return 0;
896
897 if (__pipe2 (fildes, O_CLOEXEC) < 0)
898 return WRDE_NOSPACE;
899
900 again:
901 pid = exec_comm_child (comm, fildes, noexec ? false : flags & WRDE_SHOWERR,
902 noexec);
903 if (pid < 0)
904 {
905 __close (fildes[0]);
906 __close (fildes[1]);
907 return WRDE_NOSPACE;
908 }
909
910 /* If we are just testing the syntax, only wait. */
911 if (noexec)
912 return (TEMP_FAILURE_RETRY (__waitpid (pid, &status, 0)) == pid
913 && status != 0) ? WRDE_SYNTAX : 0;
914
915 __close (fildes[1]);
916 fildes[1] = -1;
917
918 if (!pwordexp)
919 /* Quoted - no field splitting */
920 {
921 while (1)
922 {
923 if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
924 bufsize))) < 1)
925 {
926 /* If read returned 0 then the process has closed its
927 stdout. Don't use WNOHANG in that case to avoid busy
928 looping until the process eventually exits. */
929 if (TEMP_FAILURE_RETRY (__waitpid (pid, &status,
930 buflen == 0 ? 0 : WNOHANG))
931 == 0)
932 continue;
933 if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
934 bufsize))) < 1)
935 break;
936 }
937
938 maxnewlines += buflen;
939
940 *word = w_addmem (*word, word_length, max_length, buffer, buflen);
941 if (*word == NULL)
942 goto no_space;
943 }
944 }
945 else
946 /* Not quoted - split fields */
947 {
948 int copying = 0;
949 /* 'copying' is:
950 * 0 when searching for first character in a field not IFS white space
951 * 1 when copying the text of a field
952 * 2 when searching for possible non-whitespace IFS
953 * 3 when searching for non-newline after copying field
954 */
955
956 while (1)
957 {
958 if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
959 bufsize))) < 1)
960 {
961 /* If read returned 0 then the process has closed its
962 stdout. Don't use WNOHANG in that case to avoid busy
963 looping until the process eventually exits. */
964 if (TEMP_FAILURE_RETRY (__waitpid (pid, &status,
965 buflen == 0 ? 0 : WNOHANG))
966 == 0)
967 continue;
968 if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
969 bufsize))) < 1)
970 break;
971 }
972
973 for (i = 0; i < buflen; ++i)
974 {
975 if (strchr (ifs, buffer[i]) != NULL)
976 {
977 /* Current character is IFS */
978 if (strchr (ifs_white, buffer[i]) == NULL)
979 {
980 /* Current character is IFS but not whitespace */
981 if (copying == 2)
982 {
983 /* current character
984 * |
985 * V
986 * eg: text<space><comma><space>moretext
987 *
988 * So, strip whitespace IFS (like at the start)
989 */
990 copying = 0;
991 continue;
992 }
993
994 copying = 0;
995 /* fall through and delimit field.. */
996 }
997 else
998 {
999 if (buffer[i] == '\n')
1000 {
1001 /* Current character is (IFS) newline */
1002
1003 /* If copying a field, this is the end of it,
1004 but maybe all that's left is trailing newlines.
1005 So start searching for a non-newline. */
1006 if (copying == 1)
1007 copying = 3;
1008
1009 continue;
1010 }
1011 else
1012 {
1013 /* Current character is IFS white space, but
1014 not a newline */
1015
1016 /* If not either copying a field or searching
1017 for non-newline after a field, ignore it */
1018 if (copying != 1 && copying != 3)
1019 continue;
1020
1021 /* End of field (search for non-ws IFS afterwards) */
1022 copying = 2;
1023 }
1024 }
1025
1026 /* First IFS white space (non-newline), or IFS non-whitespace.
1027 * Delimit the field. Nulls are converted by w_addword. */
1028 if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
1029 goto no_space;
1030
1031 *word = w_newword (word_length, max_length);
1032
1033 maxnewlines = 0;
1034 /* fall back round the loop.. */
1035 }
1036 else
1037 {
1038 /* Not IFS character */
1039
1040 if (copying == 3)
1041 {
1042 /* Nothing but (IFS) newlines since the last field,
1043 so delimit it here before starting new word */
1044 if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
1045 goto no_space;
1046
1047 *word = w_newword (word_length, max_length);
1048 }
1049
1050 copying = 1;
1051
1052 if (buffer[i] == '\n') /* happens if newline not in IFS */
1053 maxnewlines++;
1054 else
1055 maxnewlines = 0;
1056
1057 *word = w_addchar (*word, word_length, max_length,
1058 buffer[i]);
1059 if (*word == NULL)
1060 goto no_space;
1061 }
1062 }
1063 }
1064 }
1065
1066 /* Chop off trailing newlines (required by POSIX.2) */
1067 /* Ensure we don't go back further than the beginning of the
1068 substitution (i.e. remove maxnewlines bytes at most) */
1069 while (maxnewlines-- != 0
1070 && *word_length > 0 && (*word)[*word_length - 1] == '\n')
1071 {
1072 (*word)[--*word_length] = '\0';
1073
1074 /* If the last word was entirely newlines, turn it into a new word
1075 * which can be ignored if there's nothing following it. */
1076 if (*word_length == 0)
1077 {
1078 free (*word);
1079 *word = w_newword (word_length, max_length);
1080 break;
1081 }
1082 }
1083
1084 __close (fildes[0]);
1085 fildes[0] = -1;
1086
1087 /* Check for syntax error (re-execute but with "-n" flag) */
1088 if (buflen < 1 && status != 0)
1089 {
1090 noexec = true;
1091 goto again;
1092 }
1093
1094 return 0;
1095
1096no_space:
1097 __kill (pid, SIGKILL);
1098 TEMP_FAILURE_RETRY (__waitpid (pid, NULL, 0));
1099 __close (fildes[0]);
1100 return WRDE_NOSPACE;
1101}
1102
1103static int
1104parse_comm (char **word, size_t *word_length, size_t *max_length,
1105 const char *words, size_t *offset, int flags, wordexp_t *pwordexp,
1106 const char *ifs, const char *ifs_white)
1107{
1108 /* We are poised just after "$(" */
1109 int paren_depth = 1;
1110 int error = 0;
1111 int quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1112 size_t comm_length;
1113 size_t comm_maxlen;
1114 char *comm = w_newword (&comm_length, &comm_maxlen);
1115
1116 for (; words[*offset]; ++(*offset))
1117 {
1118 switch (words[*offset])
1119 {
1120 case '\'':
1121 if (quoted == 0)
1122 quoted = 1;
1123 else if (quoted == 1)
1124 quoted = 0;
1125
1126 break;
1127
1128 case '"':
1129 if (quoted == 0)
1130 quoted = 2;
1131 else if (quoted == 2)
1132 quoted = 0;
1133
1134 break;
1135
1136 case ')':
1137 if (!quoted && --paren_depth == 0)
1138 {
1139 /* Go -- give script to the shell */
1140 if (comm)
1141 {
1142 /* posix_spawn already handles thread cancellation. */
1143 error = exec_comm (comm, word, word_length, max_length,
1144 flags, pwordexp, ifs, ifs_white);
1145 free (comm);
1146 }
1147
1148 return error;
1149 }
1150
1151 /* This is just part of the script */
1152 break;
1153
1154 case '(':
1155 if (!quoted)
1156 ++paren_depth;
1157 }
1158
1159 comm = w_addchar (comm, &comm_length, &comm_maxlen, words[*offset]);
1160 if (comm == NULL)
1161 return WRDE_NOSPACE;
1162 }
1163
1164 /* Premature end. */
1165 free (comm);
1166
1167 return WRDE_SYNTAX;
1168}
1169
1170#define CHAR_IN_SET(ch, char_set) \
1171 (memchr (char_set "", ch, sizeof (char_set) - 1) != NULL)
1172
1173static int
1174parse_param (char **word, size_t *word_length, size_t *max_length,
1175 const char *words, size_t *offset, int flags, wordexp_t *pwordexp,
1176 const char *ifs, const char *ifs_white, int quoted)
1177{
1178 /* We are poised just after "$" */
1179 enum action
1180 {
1181 ACT_NONE,
1182 ACT_RP_SHORT_LEFT = '#',
1183 ACT_RP_LONG_LEFT = 'L',
1184 ACT_RP_SHORT_RIGHT = '%',
1185 ACT_RP_LONG_RIGHT = 'R',
1186 ACT_NULL_ERROR = '?',
1187 ACT_NULL_SUBST = '-',
1188 ACT_NONNULL_SUBST = '+',
1189 ACT_NULL_ASSIGN = '='
1190 };
1191 size_t env_length;
1192 size_t env_maxlen;
1193 size_t pat_length;
1194 size_t pat_maxlen;
1195 size_t start = *offset;
1196 char *env;
1197 char *pattern;
1198 char *value = NULL;
1199 enum action action = ACT_NONE;
1200 int depth = 0;
1201 int colon_seen = 0;
1202 int seen_hash = 0;
1203 int free_value = 0;
1204 int pattern_is_quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1205 int error;
1206 int special = 0;
1207 char buffer[21];
1208 int brace = words[*offset] == '{';
1209
1210 env = w_newword (&env_length, &env_maxlen);
1211 pattern = w_newword (&pat_length, &pat_maxlen);
1212
1213 if (brace)
1214 ++*offset;
1215
1216 /* First collect the parameter name. */
1217
1218 if (words[*offset] == '#')
1219 {
1220 seen_hash = 1;
1221 if (!brace)
1222 goto envsubst;
1223 ++*offset;
1224 }
1225
1226 if (isalpha (words[*offset]) || words[*offset] == '_')
1227 {
1228 /* Normal parameter name. */
1229 do
1230 {
1231 env = w_addchar (env, &env_length, &env_maxlen,
1232 words[*offset]);
1233 if (env == NULL)
1234 goto no_space;
1235 }
1236 while (isalnum (words[++*offset]) || words[*offset] == '_');
1237 }
1238 else if (isdigit (words[*offset]))
1239 {
1240 /* Numeric parameter name. */
1241 special = 1;
1242 do
1243 {
1244 env = w_addchar (env, &env_length, &env_maxlen,
1245 words[*offset]);
1246 if (env == NULL)
1247 goto no_space;
1248 if (!brace)
1249 goto envsubst;
1250 }
1251 while (isdigit(words[++*offset]));
1252 }
1253 else if (CHAR_IN_SET (words[*offset], "*@$"))
1254 {
1255 /* Special parameter. */
1256 special = 1;
1257 env = w_addchar (env, &env_length, &env_maxlen,
1258 words[*offset]);
1259 if (env == NULL)
1260 goto no_space;
1261 ++*offset;
1262 }
1263 else
1264 {
1265 if (brace)
1266 goto syntax;
1267 }
1268
1269 if (brace)
1270 {
1271 /* Check for special action to be applied to the value. */
1272 switch (words[*offset])
1273 {
1274 case '}':
1275 /* Evaluate. */
1276 goto envsubst;
1277
1278 case '#':
1279 action = ACT_RP_SHORT_LEFT;
1280 if (words[1 + *offset] == '#')
1281 {
1282 ++*offset;
1283 action = ACT_RP_LONG_LEFT;
1284 }
1285 break;
1286
1287 case '%':
1288 action = ACT_RP_SHORT_RIGHT;
1289 if (words[1 + *offset] == '%')
1290 {
1291 ++*offset;
1292 action = ACT_RP_LONG_RIGHT;
1293 }
1294 break;
1295
1296 case ':':
1297 if (!CHAR_IN_SET (words[1 + *offset], "-=?+"))
1298 goto syntax;
1299
1300 colon_seen = 1;
1301 action = words[++*offset];
1302 break;
1303
1304 case '-':
1305 case '=':
1306 case '?':
1307 case '+':
1308 action = words[*offset];
1309 break;
1310
1311 default:
1312 goto syntax;
1313 }
1314
1315 /* Now collect the pattern, but don't expand it yet. */
1316 ++*offset;
1317 for (; words[*offset]; ++(*offset))
1318 {
1319 switch (words[*offset])
1320 {
1321 case '{':
1322 if (!pattern_is_quoted)
1323 ++depth;
1324 break;
1325
1326 case '}':
1327 if (!pattern_is_quoted)
1328 {
1329 if (depth == 0)
1330 goto envsubst;
1331 --depth;
1332 }
1333 break;
1334
1335 case '\\':
1336 if (pattern_is_quoted)
1337 /* Quoted; treat as normal character. */
1338 break;
1339
1340 /* Otherwise, it's an escape: next character is literal. */
1341 if (words[++*offset] == '\0')
1342 goto syntax;
1343
1344 pattern = w_addchar (pattern, &pat_length, &pat_maxlen, '\\');
1345 if (pattern == NULL)
1346 goto no_space;
1347
1348 break;
1349
1350 case '\'':
1351 if (pattern_is_quoted == 0)
1352 pattern_is_quoted = 1;
1353 else if (pattern_is_quoted == 1)
1354 pattern_is_quoted = 0;
1355
1356 break;
1357
1358 case '"':
1359 if (pattern_is_quoted == 0)
1360 pattern_is_quoted = 2;
1361 else if (pattern_is_quoted == 2)
1362 pattern_is_quoted = 0;
1363
1364 break;
1365 }
1366
1367 pattern = w_addchar (pattern, &pat_length, &pat_maxlen,
1368 words[*offset]);
1369 if (pattern == NULL)
1370 goto no_space;
1371 }
1372 }
1373
1374 /* End of input string -- remember to reparse the character that we
1375 * stopped at. */
1376 --(*offset);
1377
1378envsubst:
1379 if (words[start] == '{' && words[*offset] != '}')
1380 goto syntax;
1381
1382 if (env == NULL)
1383 {
1384 if (seen_hash)
1385 {
1386 /* $# expands to the number of positional parameters */
1387 buffer[20] = '\0';
1388 value = _itoa_word (__libc_argc - 1, &buffer[20], 10, 0);
1389 seen_hash = 0;
1390 }
1391 else
1392 {
1393 /* Just $ on its own */
1394 *offset = start - 1;
1395 *word = w_addchar (*word, word_length, max_length, '$');
1396 return *word ? 0 : WRDE_NOSPACE;
1397 }
1398 }
1399 /* Is it a numeric parameter? */
1400 else if (isdigit (env[0]))
1401 {
1402 int n = atoi (env);
1403
1404 if (n >= __libc_argc)
1405 /* Substitute NULL. */
1406 value = NULL;
1407 else
1408 /* Replace with appropriate positional parameter. */
1409 value = __libc_argv[n];
1410 }
1411 /* Is it a special parameter? */
1412 else if (special)
1413 {
1414 /* Is it `$$'? */
1415 if (*env == '$')
1416 {
1417 buffer[20] = '\0';
1418 value = _itoa_word (__getpid (), &buffer[20], 10, 0);
1419 }
1420 /* Is it `${#*}' or `${#@}'? */
1421 else if ((*env == '*' || *env == '@') && seen_hash)
1422 {
1423 buffer[20] = '\0';
1424 value = _itoa_word (__libc_argc > 0 ? __libc_argc - 1 : 0,
1425 &buffer[20], 10, 0);
1426 *word = w_addstr (*word, word_length, max_length, value);
1427 free (env);
1428 free (pattern);
1429 return *word ? 0 : WRDE_NOSPACE;
1430 }
1431 /* Is it `$*' or `$@' (unquoted) ? */
1432 else if (*env == '*' || (*env == '@' && !quoted))
1433 {
1434 size_t plist_len = 0;
1435 int p;
1436 char *end;
1437
1438 /* Build up value parameter by parameter (copy them) */
1439 for (p = 1; __libc_argv[p]; ++p)
1440 plist_len += strlen (__libc_argv[p]) + 1; /* for space */
1441 value = malloc (plist_len);
1442 if (value == NULL)
1443 goto no_space;
1444 end = value;
1445 *end = 0;
1446 for (p = 1; __libc_argv[p]; ++p)
1447 {
1448 if (p > 1)
1449 *end++ = ' ';
1450 end = __stpcpy (end, __libc_argv[p]);
1451 }
1452
1453 free_value = 1;
1454 }
1455 else
1456 {
1457 /* Must be a quoted `$@' */
1458 assert (*env == '@' && quoted);
1459
1460 /* Each parameter is a separate word ("$@") */
1461 if (__libc_argc == 2)
1462 value = __libc_argv[1];
1463 else if (__libc_argc > 2)
1464 {
1465 int p;
1466
1467 /* Append first parameter to current word. */
1468 value = w_addstr (*word, word_length, max_length,
1469 __libc_argv[1]);
1470 if (value == NULL || w_addword (pwordexp, value))
1471 goto no_space;
1472
1473 for (p = 2; __libc_argv[p + 1]; p++)
1474 {
1475 char *newword = __strdup (__libc_argv[p]);
1476 if (newword == NULL || w_addword (pwordexp, newword))
1477 goto no_space;
1478 }
1479
1480 /* Start a new word with the last parameter. */
1481 *word = w_newword (word_length, max_length);
1482 value = __libc_argv[p];
1483 }
1484 else
1485 {
1486 free (env);
1487 free (pattern);
1488 return 0;
1489 }
1490 }
1491 }
1492 else
1493 value = getenv (env);
1494
1495 if (value == NULL && (flags & WRDE_UNDEF))
1496 {
1497 /* Variable not defined. */
1498 error = WRDE_BADVAL;
1499 goto do_error;
1500 }
1501
1502 if (action != ACT_NONE)
1503 {
1504 int expand_pattern = 0;
1505
1506 /* First, find out if we need to expand pattern (i.e. if we will
1507 * use it). */
1508 switch (action)
1509 {
1510 case ACT_RP_SHORT_LEFT:
1511 case ACT_RP_LONG_LEFT:
1512 case ACT_RP_SHORT_RIGHT:
1513 case ACT_RP_LONG_RIGHT:
1514 /* Always expand for these. */
1515 expand_pattern = 1;
1516 break;
1517
1518 case ACT_NULL_ERROR:
1519 case ACT_NULL_SUBST:
1520 case ACT_NULL_ASSIGN:
1521 if (!value || (!*value && colon_seen))
1522 /* If param is unset, or set but null and a colon has been seen,
1523 the expansion of the pattern will be needed. */
1524 expand_pattern = 1;
1525
1526 break;
1527
1528 case ACT_NONNULL_SUBST:
1529 /* Expansion of word will be needed if parameter is set and not null,
1530 or set null but no colon has been seen. */
1531 if (value && (*value || !colon_seen))
1532 expand_pattern = 1;
1533
1534 break;
1535
1536 default:
1537 assert (! "Unrecognised action!");
1538 }
1539
1540 if (expand_pattern)
1541 {
1542 /* We need to perform tilde expansion, parameter expansion,
1543 command substitution, and arithmetic expansion. We also
1544 have to be a bit careful with wildcard characters, as
1545 pattern might be given to fnmatch soon. To do this, we
1546 convert quotes to escapes. */
1547
1548 char *expanded;
1549 size_t exp_len;
1550 size_t exp_maxl;
1551 char *p;
1552 int quoted = 0; /* 1: single quotes; 2: double */
1553
1554 expanded = w_newword (&exp_len, &exp_maxl);
1555 for (p = pattern; p && *p; p++)
1556 {
1557 size_t offset;
1558
1559 switch (*p)
1560 {
1561 case '"':
1562 if (quoted == 2)
1563 quoted = 0;
1564 else if (quoted == 0)
1565 quoted = 2;
1566 else break;
1567
1568 continue;
1569
1570 case '\'':
1571 if (quoted == 1)
1572 quoted = 0;
1573 else if (quoted == 0)
1574 quoted = 1;
1575 else break;
1576
1577 continue;
1578
1579 case '*':
1580 case '?':
1581 if (quoted)
1582 {
1583 /* Convert quoted wildchar to escaped wildchar. */
1584 expanded = w_addchar (expanded, &exp_len,
1585 &exp_maxl, '\\');
1586
1587 if (expanded == NULL)
1588 goto no_space;
1589 }
1590 break;
1591
1592 case '$':
1593 offset = 0;
1594 error = parse_dollars (&expanded, &exp_len, &exp_maxl, p,
1595 &offset, flags, NULL, NULL, NULL, 1);
1596 if (error)
1597 {
1598 if (free_value)
1599 free (value);
1600
1601 free (expanded);
1602
1603 goto do_error;
1604 }
1605
1606 p += offset;
1607 continue;
1608
1609 case '~':
1610 if (quoted || exp_len)
1611 break;
1612
1613 offset = 0;
1614 error = parse_tilde (&expanded, &exp_len, &exp_maxl, p,
1615 &offset, 0);
1616 if (error)
1617 {
1618 if (free_value)
1619 free (value);
1620
1621 free (expanded);
1622
1623 goto do_error;
1624 }
1625
1626 p += offset;
1627 continue;
1628
1629 case '\\':
1630 expanded = w_addchar (expanded, &exp_len, &exp_maxl, '\\');
1631 ++p;
1632 assert (*p); /* checked when extracted initially */
1633 if (expanded == NULL)
1634 goto no_space;
1635 }
1636
1637 expanded = w_addchar (expanded, &exp_len, &exp_maxl, *p);
1638
1639 if (expanded == NULL)
1640 goto no_space;
1641 }
1642
1643 free (pattern);
1644
1645 pattern = expanded;
1646 }
1647
1648 switch (action)
1649 {
1650 case ACT_RP_SHORT_LEFT:
1651 case ACT_RP_LONG_LEFT:
1652 case ACT_RP_SHORT_RIGHT:
1653 case ACT_RP_LONG_RIGHT:
1654 {
1655 char *p;
1656 char c;
1657 char *end;
1658
1659 if (value == NULL || pattern == NULL || *pattern == '\0')
1660 break;
1661
1662 end = value + strlen (value);
1663
1664 switch (action)
1665 {
1666 case ACT_RP_SHORT_LEFT:
1667 for (p = value; p <= end; ++p)
1668 {
1669 c = *p;
1670 *p = '\0';
1671 if (fnmatch (pattern, value, 0) != FNM_NOMATCH)
1672 {
1673 *p = c;
1674 if (free_value)
1675 {
1676 char *newval = __strdup (p);
1677 if (newval == NULL)
1678 {
1679 free (value);
1680 goto no_space;
1681 }
1682 free (value);
1683 value = newval;
1684 }
1685 else
1686 value = p;
1687 break;
1688 }
1689 *p = c;
1690 }
1691
1692 break;
1693
1694 case ACT_RP_LONG_LEFT:
1695 for (p = end; p >= value; --p)
1696 {
1697 c = *p;
1698 *p = '\0';
1699 if (fnmatch (pattern, value, 0) != FNM_NOMATCH)
1700 {
1701 *p = c;
1702 if (free_value)
1703 {
1704 char *newval = __strdup (p);
1705 if (newval == NULL)
1706 {
1707 free (value);
1708 goto no_space;
1709 }
1710 free (value);
1711 value = newval;
1712 }
1713 else
1714 value = p;
1715 break;
1716 }
1717 *p = c;
1718 }
1719
1720 break;
1721
1722 case ACT_RP_SHORT_RIGHT:
1723 for (p = end; p >= value; --p)
1724 {
1725 if (fnmatch (pattern, p, 0) != FNM_NOMATCH)
1726 {
1727 char *newval;
1728 newval = malloc (p - value + 1);
1729
1730 if (newval == NULL)
1731 {
1732 if (free_value)
1733 free (value);
1734 goto no_space;
1735 }
1736
1737 *(char *) __mempcpy (newval, value, p - value) = '\0';
1738 if (free_value)
1739 free (value);
1740 value = newval;
1741 free_value = 1;
1742 break;
1743 }
1744 }
1745
1746 break;
1747
1748 case ACT_RP_LONG_RIGHT:
1749 for (p = value; p <= end; ++p)
1750 {
1751 if (fnmatch (pattern, p, 0) != FNM_NOMATCH)
1752 {
1753 char *newval;
1754 newval = malloc (p - value + 1);
1755
1756 if (newval == NULL)
1757 {
1758 if (free_value)
1759 free (value);
1760 goto no_space;
1761 }
1762
1763 *(char *) __mempcpy (newval, value, p - value) = '\0';
1764 if (free_value)
1765 free (value);
1766 value = newval;
1767 free_value = 1;
1768 break;
1769 }
1770 }
1771
1772 break;
1773
1774 default:
1775 break;
1776 }
1777
1778 break;
1779 }
1780
1781 case ACT_NULL_ERROR:
1782 if (value && *value)
1783 /* Substitute parameter */
1784 break;
1785
1786 error = 0;
1787 if (!colon_seen && value)
1788 /* Substitute NULL */
1789 ;
1790 else
1791 {
1792 const char *str = pattern;
1793
1794 if (str[0] == '\0')
1795 str = _("parameter null or not set");
1796
1797 __fxprintf (NULL, "%s: %s\n", env, str);
1798 }
1799
1800 if (free_value)
1801 free (value);
1802 goto do_error;
1803
1804 case ACT_NULL_SUBST:
1805 if (value && *value)
1806 /* Substitute parameter */
1807 break;
1808
1809 if (free_value)
1810 free (value);
1811
1812 if (!colon_seen && value)
1813 /* Substitute NULL */
1814 goto success;
1815
1816 value = pattern ? __strdup (pattern) : pattern;
1817 free_value = 1;
1818
1819 if (pattern && !value)
1820 goto no_space;
1821
1822 break;
1823
1824 case ACT_NONNULL_SUBST:
1825 if (value && (*value || !colon_seen))
1826 {
1827 if (free_value)
1828 free (value);
1829
1830 value = pattern ? __strdup (pattern) : pattern;
1831 free_value = 1;
1832
1833 if (pattern && !value)
1834 goto no_space;
1835
1836 break;
1837 }
1838
1839 /* Substitute NULL */
1840 if (free_value)
1841 free (value);
1842 goto success;
1843
1844 case ACT_NULL_ASSIGN:
1845 if (value && *value)
1846 /* Substitute parameter */
1847 break;
1848
1849 if (!colon_seen && value)
1850 {
1851 /* Substitute NULL */
1852 if (free_value)
1853 free (value);
1854 goto success;
1855 }
1856
1857 if (free_value)
1858 free (value);
1859
1860 value = pattern ? __strdup (pattern) : pattern;
1861 free_value = 1;
1862
1863 if (pattern && !value)
1864 goto no_space;
1865
1866 __setenv (env, value ?: "", 1);
1867 break;
1868
1869 default:
1870 assert (! "Unrecognised action!");
1871 }
1872 }
1873
1874 free (env);
1875 env = NULL;
1876 free (pattern);
1877 pattern = NULL;
1878
1879 if (seen_hash)
1880 {
1881 char param_length[21];
1882 param_length[20] = '\0';
1883 *word = w_addstr (*word, word_length, max_length,
1884 _itoa_word (value ? strlen (value) : 0,
1885 &param_length[20], 10, 0));
1886 if (free_value)
1887 {
1888 assert (value != NULL);
1889 free (value);
1890 }
1891
1892 return *word ? 0 : WRDE_NOSPACE;
1893 }
1894
1895 if (value == NULL)
1896 return 0;
1897
1898 if (quoted || !pwordexp)
1899 {
1900 /* Quoted - no field split */
1901 *word = w_addstr (*word, word_length, max_length, value);
1902 if (free_value)
1903 free (value);
1904
1905 return *word ? 0 : WRDE_NOSPACE;
1906 }
1907 else
1908 {
1909 /* Need to field-split */
1910 char *value_copy = __strdup (value); /* Don't modify value */
1911 char *field_begin = value_copy;
1912 int seen_nonws_ifs = 0;
1913
1914 if (free_value)
1915 free (value);
1916
1917 if (value_copy == NULL)
1918 goto no_space;
1919
1920 do
1921 {
1922 char *field_end = field_begin;
1923 char *next_field;
1924
1925 /* If this isn't the first field, start a new word */
1926 if (field_begin != value_copy)
1927 {
1928 if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
1929 {
1930 free (value_copy);
1931 goto no_space;
1932 }
1933
1934 *word = w_newword (word_length, max_length);
1935 }
1936
1937 /* Skip IFS whitespace before the field */
1938 field_begin += strspn (field_begin, ifs_white);
1939
1940 if (!seen_nonws_ifs && *field_begin == 0)
1941 /* Nothing but whitespace */
1942 break;
1943
1944 /* Search for the end of the field */
1945 field_end = field_begin + strcspn (field_begin, ifs);
1946
1947 /* Set up pointer to the character after end of field and
1948 skip whitespace IFS after it. */
1949 next_field = field_end + strspn (field_end, ifs_white);
1950
1951 /* Skip at most one non-whitespace IFS character after the field */
1952 seen_nonws_ifs = 0;
1953 if (*next_field && strchr (ifs, *next_field))
1954 {
1955 seen_nonws_ifs = 1;
1956 next_field++;
1957 }
1958
1959 /* Null-terminate it */
1960 *field_end = 0;
1961
1962 /* Tag a copy onto the current word */
1963 *word = w_addstr (*word, word_length, max_length, field_begin);
1964
1965 if (*word == NULL && *field_begin != '\0')
1966 {
1967 free (value_copy);
1968 goto no_space;
1969 }
1970
1971 field_begin = next_field;
1972 }
1973 while (seen_nonws_ifs || *field_begin);
1974
1975 free (value_copy);
1976 }
1977
1978 return 0;
1979
1980success:
1981 error = 0;
1982 goto do_error;
1983
1984no_space:
1985 error = WRDE_NOSPACE;
1986 goto do_error;
1987
1988syntax:
1989 error = WRDE_SYNTAX;
1990
1991do_error:
1992 free (env);
1993
1994 free (pattern);
1995
1996 return error;
1997}
1998
1999#undef CHAR_IN_SET
2000
2001static int
2002parse_dollars (char **word, size_t *word_length, size_t *max_length,
2003 const char *words, size_t *offset, int flags,
2004 wordexp_t *pwordexp, const char *ifs, const char *ifs_white,
2005 int quoted)
2006{
2007 /* We are poised _at_ "$" */
2008 switch (words[1 + *offset])
2009 {
2010 case '"':
2011 case '\'':
2012 case 0:
2013 *word = w_addchar (*word, word_length, max_length, '$');
2014 return *word ? 0 : WRDE_NOSPACE;
2015
2016 case '(':
2017 if (words[2 + *offset] == '(')
2018 {
2019 /* Differentiate between $((1+3)) and $((echo);(ls)) */
2020 int i = 3 + *offset;
2021 int depth = 0;
2022 while (words[i] && !(depth == 0 && words[i] == ')'))
2023 {
2024 if (words[i] == '(')
2025 ++depth;
2026 else if (words[i] == ')')
2027 --depth;
2028
2029 ++i;
2030 }
2031
2032 if (words[i] == ')' && words[i + 1] == ')')
2033 {
2034 (*offset) += 3;
2035 /* Call parse_arith -- 0 is for "no brackets" */
2036 return parse_arith (word, word_length, max_length, words, offset,
2037 flags, 0);
2038 }
2039 }
2040
2041 (*offset) += 2;
2042 return parse_comm (word, word_length, max_length, words, offset, flags,
2043 quoted? NULL : pwordexp, ifs, ifs_white);
2044
2045 case '[':
2046 (*offset) += 2;
2047 /* Call parse_arith -- 1 is for "brackets" */
2048 return parse_arith (word, word_length, max_length, words, offset, flags,
2049 1);
2050
2051 case '{':
2052 default:
2053 ++(*offset); /* parse_param needs to know if "{" is there */
2054 return parse_param (word, word_length, max_length, words, offset, flags,
2055 pwordexp, ifs, ifs_white, quoted);
2056 }
2057}
2058
2059static int
2060parse_backtick (char **word, size_t *word_length, size_t *max_length,
2061 const char *words, size_t *offset, int flags,
2062 wordexp_t *pwordexp, const char *ifs, const char *ifs_white)
2063{
2064 /* We are poised just after "`" */
2065 int error;
2066 int squoting = 0;
2067 size_t comm_length;
2068 size_t comm_maxlen;
2069 char *comm = w_newword (&comm_length, &comm_maxlen);
2070
2071 for (; words[*offset]; ++(*offset))
2072 {
2073 switch (words[*offset])
2074 {
2075 case '`':
2076 /* Go -- give the script to the shell */
2077 error = exec_comm (comm, word, word_length, max_length, flags,
2078 pwordexp, ifs, ifs_white);
2079 free (comm);
2080 return error;
2081
2082 case '\\':
2083 if (squoting)
2084 {
2085 error = parse_qtd_backslash (&comm, &comm_length, &comm_maxlen,
2086 words, offset);
2087
2088 if (error)
2089 {
2090 free (comm);
2091 return error;
2092 }
2093
2094 break;
2095 }
2096
2097 error = parse_backslash (&comm, &comm_length, &comm_maxlen, words,
2098 offset);
2099
2100 if (error)
2101 {
2102 free (comm);
2103 return error;
2104 }
2105
2106 break;
2107
2108 case '\'':
2109 squoting = 1 - squoting;
2110 /* Fall through. */
2111 default:
2112 comm = w_addchar (comm, &comm_length, &comm_maxlen, words[*offset]);
2113 if (comm == NULL)
2114 return WRDE_NOSPACE;
2115 }
2116 }
2117
2118 /* Premature end */
2119 free (comm);
2120 return WRDE_SYNTAX;
2121}
2122
2123static int
2124parse_dquote (char **word, size_t *word_length, size_t *max_length,
2125 const char *words, size_t *offset, int flags,
2126 wordexp_t *pwordexp, const char * ifs, const char * ifs_white)
2127{
2128 /* We are poised just after a double-quote */
2129 int error;
2130
2131 for (; words[*offset]; ++(*offset))
2132 {
2133 switch (words[*offset])
2134 {
2135 case '"':
2136 return 0;
2137
2138 case '$':
2139 error = parse_dollars (word, word_length, max_length, words, offset,
2140 flags, pwordexp, ifs, ifs_white, 1);
2141 /* The ``1'' here is to tell parse_dollars not to
2142 * split the fields. It may need to, however ("$@").
2143 */
2144 if (error)
2145 return error;
2146
2147 break;
2148
2149 case '`':
2150 ++(*offset);
2151 error = parse_backtick (word, word_length, max_length, words,
2152 offset, flags, NULL, NULL, NULL);
2153 /* The first NULL here is to tell parse_backtick not to
2154 * split the fields.
2155 */
2156 if (error)
2157 return error;
2158
2159 break;
2160
2161 case '\\':
2162 error = parse_qtd_backslash (word, word_length, max_length, words,
2163 offset);
2164
2165 if (error)
2166 return error;
2167
2168 break;
2169
2170 default:
2171 *word = w_addchar (*word, word_length, max_length, words[*offset]);
2172 if (*word == NULL)
2173 return WRDE_NOSPACE;
2174 }
2175 }
2176
2177 /* Unterminated string */
2178 return WRDE_SYNTAX;
2179}
2180
2181/*
2182 * wordfree() is to be called after pwordexp is finished with.
2183 */
2184
2185void
2186wordfree (wordexp_t *pwordexp)
2187{
2188
2189 /* wordexp can set pwordexp to NULL */
2190 if (pwordexp && pwordexp->we_wordv)
2191 {
2192 char **wordv = pwordexp->we_wordv;
2193
2194 for (wordv += pwordexp->we_offs; *wordv; ++wordv)
2195 free (*wordv);
2196
2197 free (pwordexp->we_wordv);
2198 pwordexp->we_wordv = NULL;
2199 }
2200}
2201libc_hidden_def (wordfree)
2202
2203/*
2204 * wordexp()
2205 */
2206
2207int
2208wordexp (const char *words, wordexp_t *pwordexp, int flags)
2209{
2210 size_t words_offset;
2211 size_t word_length;
2212 size_t max_length;
2213 char *word = w_newword (&word_length, &max_length);
2214 int error;
2215 char *ifs;
2216 char ifs_white[4];
2217 wordexp_t old_word = *pwordexp;
2218
2219 if (flags & WRDE_REUSE)
2220 {
2221 /* Minimal implementation of WRDE_REUSE for now */
2222 wordfree (pwordexp);
2223 old_word.we_wordv = NULL;
2224 }
2225
2226 if ((flags & WRDE_APPEND) == 0)
2227 {
2228 pwordexp->we_wordc = 0;
2229
2230 if (flags & WRDE_DOOFFS)
2231 {
2232 pwordexp->we_wordv = calloc (1 + pwordexp->we_offs, sizeof (char *));
2233 if (pwordexp->we_wordv == NULL)
2234 {
2235 error = WRDE_NOSPACE;
2236 goto do_error;
2237 }
2238 }
2239 else
2240 {
2241 pwordexp->we_wordv = calloc (1, sizeof (char *));
2242 if (pwordexp->we_wordv == NULL)
2243 {
2244 error = WRDE_NOSPACE;
2245 goto do_error;
2246 }
2247
2248 pwordexp->we_offs = 0;
2249 }
2250 }
2251
2252 /* Find out what the field separators are.
2253 * There are two types: whitespace and non-whitespace.
2254 */
2255 ifs = getenv ("IFS");
2256
2257 if (ifs == NULL)
2258 /* IFS unset - use <space><tab><newline>. */
2259 ifs = strcpy (ifs_white, " \t\n");
2260 else
2261 {
2262 char *ifsch = ifs;
2263 char *whch = ifs_white;
2264
2265 while (*ifsch != '\0')
2266 {
2267 if (*ifsch == ' ' || *ifsch == '\t' || *ifsch == '\n')
2268 {
2269 /* Whitespace IFS. See first whether it is already in our
2270 collection. */
2271 char *runp = ifs_white;
2272
2273 while (runp < whch && *runp != *ifsch)
2274 ++runp;
2275
2276 if (runp == whch)
2277 *whch++ = *ifsch;
2278 }
2279
2280 ++ifsch;
2281 }
2282 *whch = '\0';
2283 }
2284
2285 for (words_offset = 0 ; words[words_offset] ; ++words_offset)
2286 switch (words[words_offset])
2287 {
2288 case '\\':
2289 error = parse_backslash (&word, &word_length, &max_length, words,
2290 &words_offset);
2291
2292 if (error)
2293 goto do_error;
2294
2295 break;
2296
2297 case '$':
2298 error = parse_dollars (&word, &word_length, &max_length, words,
2299 &words_offset, flags, pwordexp, ifs, ifs_white,
2300 0);
2301
2302 if (error)
2303 goto do_error;
2304
2305 break;
2306
2307 case '`':
2308 ++words_offset;
2309 error = parse_backtick (&word, &word_length, &max_length, words,
2310 &words_offset, flags, pwordexp, ifs,
2311 ifs_white);
2312
2313 if (error)
2314 goto do_error;
2315
2316 break;
2317
2318 case '"':
2319 ++words_offset;
2320 error = parse_dquote (&word, &word_length, &max_length, words,
2321 &words_offset, flags, pwordexp, ifs, ifs_white);
2322
2323 if (error)
2324 goto do_error;
2325
2326 if (!word_length)
2327 {
2328 error = w_addword (pwordexp, NULL);
2329
2330 if (error)
2331 return error;
2332 }
2333
2334 break;
2335
2336 case '\'':
2337 ++words_offset;
2338 error = parse_squote (&word, &word_length, &max_length, words,
2339 &words_offset);
2340
2341 if (error)
2342 goto do_error;
2343
2344 if (!word_length)
2345 {
2346 error = w_addword (pwordexp, NULL);
2347
2348 if (error)
2349 return error;
2350 }
2351
2352 break;
2353
2354 case '~':
2355 error = parse_tilde (&word, &word_length, &max_length, words,
2356 &words_offset, pwordexp->we_wordc);
2357
2358 if (error)
2359 goto do_error;
2360
2361 break;
2362
2363 case '*':
2364 case '[':
2365 case '?':
2366 error = parse_glob (&word, &word_length, &max_length, words,
2367 &words_offset, flags, pwordexp, ifs, ifs_white);
2368
2369 if (error)
2370 goto do_error;
2371
2372 break;
2373
2374 default:
2375 /* Is it a word separator? */
2376 if (strchr (" \t", words[words_offset]) == NULL)
2377 {
2378 char ch = words[words_offset];
2379
2380 /* Not a word separator -- but is it a valid word char? */
2381 if (strchr ("\n|&;<>(){}", ch))
2382 {
2383 /* Fail */
2384 error = WRDE_BADCHAR;
2385 goto do_error;
2386 }
2387
2388 /* "Ordinary" character -- add it to word */
2389 word = w_addchar (word, &word_length, &max_length,
2390 ch);
2391 if (word == NULL)
2392 {
2393 error = WRDE_NOSPACE;
2394 goto do_error;
2395 }
2396
2397 break;
2398 }
2399
2400 /* If a word has been delimited, add it to the list. */
2401 if (word != NULL)
2402 {
2403 error = w_addword (pwordexp, word);
2404 if (error)
2405 goto do_error;
2406 }
2407
2408 word = w_newword (&word_length, &max_length);
2409 }
2410
2411 /* End of string */
2412
2413 /* There was a word separator at the end */
2414 if (word == NULL) /* i.e. w_newword */
2415 return 0;
2416
2417 /* There was no field separator at the end */
2418 return w_addword (pwordexp, word);
2419
2420do_error:
2421 /* Error:
2422 * free memory used (unless error is WRDE_NOSPACE), and
2423 * set pwordexp members back to what they were.
2424 */
2425
2426 free (word);
2427
2428 if (error == WRDE_NOSPACE)
2429 return WRDE_NOSPACE;
2430
2431 if ((flags & WRDE_APPEND) == 0)
2432 wordfree (pwordexp);
2433
2434 *pwordexp = old_word;
2435 return error;
2436}
2437