forked from MirBSD/mksh
-
Notifications
You must be signed in to change notification settings - Fork 2
/
misc.c
2964 lines (2745 loc) · 64.8 KB
/
misc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $OpenBSD: misc.c,v 1.41 2015/09/10 22:48:58 nicm Exp $ */
/* $OpenBSD: path.c,v 1.13 2015/09/05 09:47:08 jsg Exp $ */
/*-
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
* 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019,
* 2020, 2021, 2022, 2023
* mirabilos <[email protected]>
* Copyright (c) 2015
* Daniel Richard G. <[email protected]>
*
* Provided that these terms and disclaimer and all copyright notices
* are retained or reproduced in an accompanying document, permission
* is granted to deal in this work without restriction, including un-
* limited rights to use, publicly perform, distribute, sell, modify,
* merge, give away, or sublicence.
*
* This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
* the utmost extent permitted by applicable law, neither express nor
* implied; without malicious intent or gross negligence. In no event
* may a licensor, author or contributor be held liable for indirect,
* direct, other damage, loss, or other issues arising in any way out
* of dealing in the work, even if advised of the possibility of such
* damage or existence of a defect, except proven that it results out
* of said person's immediate fault when using the work as intended.
*/
#include "sh.h"
__RCSID("$MirOS: src/bin/mksh/misc.c,v 1.359 2023/09/17 01:54:04 tg Exp $");
static const unsigned char *pat_scan(const unsigned char *,
const unsigned char *, Wahr);
static int do_gmatch(const unsigned char *, const unsigned char *,
const unsigned char *, const unsigned char *,
const unsigned char *);
static const unsigned char *gmatch_cclass(const unsigned char *, unsigned char);
static void chvt(const Getopt *);
static unsigned int dollarqU(struct shf *, const unsigned char *);
#ifndef MKSH_SMALL
static void dollarq8(struct shf *, const unsigned char *);
#else
#define dollarq8 dollarqU
#endif
/*XXX this should go away */
static int make_path(const char *, const char *, char **, XString *, int *);
#ifdef SETUID_CAN_FAIL_WITH_EAGAIN
/* we don't need to check for other codes, EPERM won't happen */
#define DO_SETUID(func,argvec) do { \
if ((func argvec) && errno == EAGAIN) \
kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | \
KWF_TWOMSG, #func, "failed, probably due to a" \
" too low process limit; aborting"); \
} while (/* CONSTCOND */ 0)
#else
#define DO_SETUID(func,argvec) func argvec
#endif
/* called from XcheckN() to grow buffer */
char *
Xcheck_grow(XString *xsp, const char *xp, size_t more)
{
size_t old_ofs = xp - xsp->beg;
if (more < xsp->len)
more = xsp->len;
/* (xsp->len + X_EXTRA) never overflows */
checkoktoadd(more, xsp->len + X_EXTRA);
xsp->beg = aresize(xsp->beg, (xsp->len += more) + X_EXTRA, xsp->areap);
xsp->end = xsp->beg + xsp->len;
return (xsp->beg + old_ofs);
}
#define SHFLAGS_DEFNS
#define FN(sname,cname,flags,ochar) \
static const struct shoptionS_ ## cname { \
/* character flag (if any) */ \
char c; \
/* OF_* */ \
unsigned char optflags; \
/* long name of option */ \
char name[sizeof(sname)]; \
} shoptione_ ## cname = { \
ochar, flags, sname \
};
#include "sh_flags.gen"
mbCTA_BEG(sh_flags_gen);
#define FN(sname,cname,flags,ochar) mbccCTA(o_ ## cname, ( \
offsetof(struct shoptionS_ ## cname, optflags) == 1 && \
offsetof(struct shoptionS_ ## cname, name) == 2));
#include "sh_flags.gen"
mbCTA_END(sh_flags_gen);
#define OFC(i) (options[i][-2])
#define OFF(i) (((const unsigned char *)options[i])[-1])
#define OFN(i) (options[i])
const char * const options[] = {
#define SHFLAGS_ITEMS
#include "sh_flags.gen"
};
/*
* translate -o option into F* constant (also used for test -o option)
*/
size_t
option(const char *n)
{
size_t i = 0;
if (ctype(n[0], C_MINUS | C_PLUS) && n[1] && !n[2])
while (i < NELEM(options)) {
if (OFC(i) == n[1])
return (i);
++i;
}
else
while (i < NELEM(options)) {
if (!strcmp(OFN(i), n))
return (i);
++i;
}
return ((size_t)-1);
}
struct options_info {
int opt_width;
int opts[NELEM(options)];
};
static void options_fmt_entry(char *, size_t, unsigned int, const void *);
static int printoptions(Wahr);
static int printoption(size_t);
/* format a single select menu item */
static void
options_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
{
const struct options_info *oi = (const struct options_info *)arg;
shf_snprintf(buf, buflen, "%-*s %s",
oi->opt_width, OFN(oi->opts[i]),
Flag(oi->opts[i]) ? "on" : "off");
}
static int
printoption(size_t i)
{
if (Flag(i) == baseline_flags[i])
return (0);
if (!OFN(i)[0]) {
#if !defined(MKSH_SMALL) || defined(DEBUG)
bi_errorf(Tf_sd, "change in unnamed option", (int)i);
#endif
return (1);
}
if (Flag(i) != 0 && Flag(i) != 1) {
#if !defined(MKSH_SMALL) || defined(DEBUG)
bi_errorf(Tf_s_sD_s, Tdo, OFN(i), "not 0 or 1");
#endif
return (1);
}
shprintf(Tf__s_s, Flag(i) ? Tdo : Tpo, OFN(i));
return (0);
}
static int
printoptions(Wahr verbose)
{
size_t i = 0;
int rv = 0;
if (verbose) {
size_t n = 0, len, octs = 0;
struct options_info oi;
struct columnise_opts co;
/* verbose version */
shf_puts("Current option settings\n", shl_stdout);
oi.opt_width = 0;
while (i < NELEM(options)) {
if ((len = strlen(OFN(i)))) {
oi.opts[n++] = i;
if (len > octs)
octs = len;
len = utf_mbswidth(OFN(i));
if ((int)len > oi.opt_width)
oi.opt_width = (int)len;
}
++i;
}
co.shf = shl_stdout;
co.linesep = '\n';
co.prefcol = co.do_last = Ja;
print_columns(&co, n, options_fmt_entry, &oi,
octs + 4, oi.opt_width + 4);
} else {
/* short version like AT&T ksh93 */
shf_puts(Tset, shl_stdout);
shf_puts(To_o_reset, shl_stdout);
printoption(FSH);
printoption(FPOSIX);
while (i < FNFLAGS) {
if (i != FSH && i != FPOSIX)
rv |= printoption(i);
++i;
}
shf_putc('\n', shl_stdout);
}
return (rv);
}
char *
getoptions(void)
{
size_t i = 0;
char c, m[(int)FNFLAGS + 1];
char *cp = m;
while (i < NELEM(options)) {
if ((c = OFC(i)) && Flag(i))
*cp++ = c;
++i;
}
strndupx(cp, m, cp - m, ATEMP);
return (cp);
}
/* change a Flag(*) value; takes care of special actions */
void
change_flag(enum sh_flag f,
/* OF_INTERNAL, OF_FIRSTTIME, OF_CMDLINE, or OF_SET */
unsigned int what,
Wahr newset)
{
unsigned char oldval = Flag(f);
unsigned char newval = (newset ? 1 : 0);
if (f == FXTRACE) {
change_xtrace(newval, Ja);
return;
} else if (f == FPRIVILEGED) {
if (!oldval)
/* no getting back dropped privs */
return;
else if (!newval) {
/* turning off -p */
kshegid = kshgid;
ksheuid = kshuid;
} else if (oldval != 3)
/* nor going full sugid */
goto change_flag;
/* +++ set group IDs +++ */
#if HAVE_SETRESUGID
DO_SETUID(setresgid, (kshegid, kshegid, kshgid));
#else /* !HAVE_SETRESUGID */
/* setgid, setegid don't EAGAIN on Linux */
setgid(kshegid);
#ifndef MKSH__NO_SETEUGID
setegid(kshegid);
#endif /* !MKSH__NO_SETEUGID */
#endif /* !HAVE_SETRESUGID */
/* +++ wipe groups vector +++ */
#if HAVE_SETGROUPS
/* setgroups doesn't EAGAIN on Linux */
setgroups(0, NULL);
#endif /* HAVE_SETGROUPS */
/* +++ set user IDs +++ */
#if HAVE_SETRESUGID
DO_SETUID(setresuid, (ksheuid, ksheuid, kshuid));
#else /* !HAVE_SETRESUGID */
/* seteuid doesn't EAGAIN on Linux */
DO_SETUID(setuid, (ksheuid));
#ifndef MKSH__NO_SETEUGID
seteuid(ksheuid);
#endif /* !MKSH__NO_SETEUGID */
#endif /* !HAVE_SETRESUGID */
/* +++ privs changed +++ */
} else if ((f == FPOSIX || f == FSH) && newval) {
/* Turning on -o posix or -o sh? */
Flag(FBRACEEXPAND) = 0;
#ifndef MKSH_NO_CMDLINE_EDITING
} else if ((f == FEMACS ||
#if !MKSH_S_NOVI
f == FVI ||
#endif
f == FGMACS) && newval) {
#if !MKSH_S_NOVI
Flag(FVI) = 0;
#endif
Flag(FEMACS) = Flag(FGMACS) = 0;
#endif
}
change_flag:
Flag(f) = newval;
if (f == FTALKING) {
/* Changing interactive flag? */
if (what == OF_CMDLINE && procpid == kshpid)
Flag(FTALKING_I) = newval;
#ifndef MKSH_UNEMPLOYED
} else if (f == FMONITOR) {
if (what != OF_CMDLINE && newval != oldval)
j_change();
#endif
}
}
void
change_xtrace(unsigned char newval, Wahr dosnapshot)
{
static Wahr in_xtrace;
if (in_xtrace)
return;
if (!dosnapshot && newval == Flag(FXTRACE))
return;
if (Flag(FXTRACE) == 2) {
shf_putc('\n', shl_xtrace);
Flag(FXTRACE) = 1;
shf_flush(shl_xtrace);
}
if (!dosnapshot && Flag(FXTRACE) == 1)
switch (newval) {
case 1:
return;
case 2:
goto changed_xtrace;
}
shf_flush(shl_xtrace);
if (shl_xtrace->fd != 2)
close(shl_xtrace->fd);
if (!newval || (shl_xtrace->fd = savefd(2)) == -1)
shl_xtrace->fd = 2;
changed_xtrace:
if ((Flag(FXTRACE) = newval) == 2) {
in_xtrace = Ja;
Flag(FXTRACE) = 0;
shf_putsv(substitute(str_val(global("PS4")), 0), shl_xtrace);
Flag(FXTRACE) = 2;
in_xtrace = Nee;
}
}
/*
* Parse command line and set command arguments. Returns the index of
* non-option arguments, -1 if there is an error.
*/
int
parse_args(const char **argv,
/* OF_FIRSTTIME, OF_CMDLINE, or OF_SET */
unsigned int what,
Wahr *setargsp)
{
static const char cmd_opts[] =
#define SHFLAGS_NOT_SET
#define SHFLAGS_OPTCS
#include "sh_flags.gen"
#undef SHFLAGS_NOT_SET
;
static const char set_opts[] =
#define SHFLAGS_NOT_CMD
#define SHFLAGS_OPTCS
#include "sh_flags.gen"
#undef SHFLAGS_NOT_CMD
;
Wahr set;
const char * const opts = what == OF_SET ? set_opts : cmd_opts;
const char *array = NULL;
Getopt go;
size_t i;
int optc, arrayset = 0;
Wahr sortargs = Nee;
Wahr fcompatseen = Nee;
ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
while ((optc = ksh_getopt(argv, &go, opts)) != -1) {
set = isWahr(!(go.info & GI_PLUS));
switch (optc) {
case 'A':
if (what == OF_FIRSTTIME)
break;
arrayset = set ? 1 : -1;
array = go.optarg;
break;
case 'o':
if (what == OF_FIRSTTIME)
break;
if (go.optarg == NULL) {
/*
* lone -o: print options
*
* Note that on the command line, -o requires
* an option (i.e. can't get here if what is
* not OF_SET).
*/
#if !defined(MKSH_SMALL) || defined(DEBUG)
if (!set && !baseline_flags[(int)FNFLAGS]) {
bi_errorf(Ttooearly, T_set_po);
return (-1);
}
#endif
if (printoptions(set))
return (-1);
break;
}
i = option(go.optarg);
if ((i == FPOSIX || i == FSH) && set && !fcompatseen) {
/*
* If running 'set -o posix' or
* 'set -o sh', turn off the other;
* if running 'set -o posix -o sh'
* allow both to be set though.
*/
Flag(FPOSIX) = 0;
Flag(FSH) = 0;
fcompatseen = Ja;
}
if ((i != (size_t)-1) && (set ? 1U : 0U) == Flag(i))
/*
* Don't check the context if the flag
* isn't changing - makes "set -o interactive"
* work if you're already interactive. Needed
* if the output of "set +o" is to be used.
*/
;
else if ((i != (size_t)-1) && (OFF(i) & what))
change_flag((enum sh_flag)i, what, set);
else if (!strcmp(go.optarg, To_reset)) {
#if !defined(MKSH_SMALL) || defined(DEBUG)
if (!baseline_flags[(int)FNFLAGS]) {
bi_errorf(Ttooearly, To_o_reset);
return (-1);
}
#endif
/*
* ordering, with respect to side effects,
* was ensured above by printoptions
*/
for (i = 0; i < FNFLAGS; ++i)
if (Flag(i) != baseline_flags[i])
change_flag((enum sh_flag)i,
what, baseline_flags[i]);
} else {
bi_errorf(Tf_sD_s, go.optarg,
Tunknown_option);
return (-1);
}
break;
case 'T':
if (what != OF_FIRSTTIME)
break;
chvt(&go);
break;
case '?':
return (-1);
default:
if (what == OF_FIRSTTIME)
break;
/* -s: sort positional params (via AT&T ksh) */
if (what == OF_SET && isch(optc, 's')) {
sortargs = Ja;
break;
}
for (i = 0; i < NELEM(options); i++)
if (optc == OFC(i) &&
(what & OFF(i))) {
change_flag((enum sh_flag)i, what, set);
break;
}
if (i == NELEM(options))
kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
"parse_args: '%c'", optc);
}
}
/* lone ‘-’ (or ‘+’)? */
if (argv[go.optind] &&
ctype(argv[go.optind][0], C_MINUS | C_PLUS) &&
argv[go.optind][1] == '\0' &&
!(go.info & GI_MINUSMINUS)) {
/* POSIX: lone hyphen-minus sh first arg ignored */
if (what == OF_SET && isch(argv[go.optind][0], '-')) {
/* set; lone dash clears -v and -x flags (obsolete) */
Flag(FVERBOSE) = 0;
change_xtrace(0, Nee);
}
/* either way, skip it (POSIX only dash but… meh) */
go.optind++;
}
if (setargsp)
/* -- means set $#/$* even if there are no arguments */
*setargsp = !arrayset && ((go.info & GI_MINUSMINUS) ||
argv[go.optind]);
if (arrayset) {
const char *ccp = NULL;
if (array && *array)
ccp = skip_varname(array, Nee);
if (!ccp || !(!ccp[0] || (ccp[0] == '+' && !ccp[1]))) {
bi_errorf(Tf_sD_s, array, Tnot_ident);
return (-1);
}
}
if (sortargs) {
for (i = go.optind; argv[i]; i++)
;
qsort(&argv[go.optind], i - go.optind, sizeof(void *),
ascpstrcmp);
}
if (arrayset)
go.optind += set_array(array, isWahr(arrayset > 0),
argv + go.optind);
return (go.optind);
}
/* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
int
getn(const char *s, int *ai)
{
if (!getpn(&s, ai))
return (0);
if (!*s)
return (1);
errno = EINVAL;
return (0);
}
int
getnh(const char *s, mbiHUGE_U *ai)
{
if (!getpnh(&s, ai))
return (0);
if (!*s)
return (1);
errno = EINVAL;
return (0);
}
/*
* parse a decimal number
* on success, returns 1 and *ai contains it and *sp points past it
* on overflow, returns 0, *ai is 0, *sp points behind the parsed number
* on parse error (not numeric) returns 0, *ai is 0, *sp is not changed
*/
int
getpn(const char **sp, int *ai)
{
char c;
const char *s;
mksh_uari_t num = 0;
kby state = 0;
Wahr neg = Nee;
s = *sp;
do {
c = *s++;
} while (ctype(c, C_SPACE));
switch (c) {
case '-':
neg = Ja;
/* FALLTHROUGH */
case '+':
c = *s++;
break;
}
while (ctype(c, C_DIGIT)) {
/*XXX this supposed to return int? */
if (num > 214748364U) {
/* overflow on multiplication */
state = 2;
errno = EOVERFLOW;
}
if (state < 2) {
state = 1;
num = num * 10U + (unsigned int)ksh_numdig(c);
}
/* now: num <= 2147483649U */
c = *s++;
}
--s;
if (num > (neg ? 2147483648U : 2147483647U)) {
/* overflow for signed 32-bit int */
state = 2;
errno = EOVERFLOW;
}
if (state)
*sp = s;
else
errno = EINVAL;
if (state != 1) {
*ai = 0;
return (0);
}
/*XXX this supposed to return int?!?!?!?! */
*ai = (neg && num > 0) ?
(mksh_ari_t)(-(mksh_ari_t)((num - 1U) & 0x7FFFFFFF) - 1) :
(mksh_ari_t)num;
return (1);
}
int
getpnh(const char **sp, mbiHUGE_U *ai)
{
char c;
const char *s;
mbiHUGE_U num = 0;
kby state = 0;
Wahr neg = Nee;
s = *sp;
do {
c = *s++;
} while (ctype(c, C_SPACE));
switch (c) {
case '-':
neg = Ja;
/* FALLTHROUGH */
case '+':
c = *s++;
break;
}
while (ctype(c, C_DIGIT)) {
if (num > (mbiHUGE_U_MAX / 10U)) {
/* overflow on multiplication */
state = 2;
errno = EOVERFLOW;
}
num *= 10U;
if (num > (mbiHUGE_U_MAX - (unsigned int)ksh_numdig(c))) {
/* overflow on addition */
state = 2;
errno = EOVERFLOW;
}
if (state < 2) {
num += (unsigned int)ksh_numdig(c);
state = 1;
}
c = *s++;
}
--s;
if (state)
*sp = s;
else
errno = EINVAL;
if (state != 1) {
*ai = 0;
return (0);
}
*ai = neg ? (mbiHUGE_U)-(mbiHUGE_U)num : num;
return (1);
}
/**
* pattern simplifications:
* - @(x) -> x (not @(x|y) though)
* - ** -> *
*/
static void *
simplify_gmatch_pattern(const unsigned char *sp)
{
kby c;
unsigned char *cp, *dp;
const unsigned char *ps, *se;
cp = alloc(strlen((const void *)sp) + 1, ATEMP);
goto simplify_gmatch_pat1a;
/* foo@(b@(a)r)b@(a|a)z -> foobarb@(a|a)z */
simplify_gmatch_pat1:
sp = cp;
simplify_gmatch_pat1a:
dp = cp;
se = strnul(sp);
while ((c = *sp++)) {
if (!ISMAGIC(c)) {
*dp++ = c;
continue;
}
switch (ord((c = *sp++))) {
case ORD(0x80|'@'):
/* simile for @ */
case ORD(0x80|' '):
/* check whether it has only one clause */
ps = pat_scan(sp, se, Ja);
if (!ps || ps[-1] != /*(*/ ')')
/* nope */
break;
/* copy inner clause until matching close */
ps -= 2;
while ((const unsigned char *)sp < ps)
*dp++ = *sp++;
/* skip MAGIC and closing parenthesis */
sp += 2;
/* copy the rest of the pattern */
memmove(dp, sp, strlen((const void *)sp) + 1);
/* redo from start */
goto simplify_gmatch_pat1;
}
*dp++ = MAGIC;
*dp++ = c;
}
*dp = '\0';
/* collapse adjacent asterisk wildcards */
sp = dp = cp;
while ((c = *sp++)) {
if (!ISMAGIC(c)) {
*dp++ = c;
continue;
}
switch ((c = *sp++)) {
case '*':
while (ISMAGIC(sp[0]) && sp[1] == c)
sp += 2;
break;
}
*dp++ = MAGIC;
*dp++ = c;
}
*dp = '\0';
/* return the result, allocated from ATEMP */
return (cp);
}
/* -------- gmatch.c -------- */
/*
* int gmatch(string, pattern)
* char *string, *pattern;
*
* Match a pattern as in sh(1).
* pattern character are prefixed with MAGIC by expand.
*/
int
gmatchx(const char *s, const char *p, Wahr isfile)
{
const char *se, *pe;
char *pnew;
int rv;
if (s == NULL || p == NULL)
return (0);
pe = strnul(p);
/*
* isfile is Nee iff no syntax check has been done on the pattern.
* If check fails just do a strcmp().
*/
if (!isfile && !has_globbing(p)) {
size_t len = pe - p + 1;
char tbuf[64];
char *t = len <= sizeof(tbuf) ? tbuf : alloc(len, ATEMP);
debunk(t, p, len);
return (!strcmp(t, s));
}
se = strnul(s);
/*
* since the do_gmatch() engine sucks so much, we must do some
* pattern simplifications
*/
pnew = simplify_gmatch_pattern((const unsigned char *)p);
pe = strnul(pnew);
rv = do_gmatch((const unsigned char *)s, (const unsigned char *)se,
(const unsigned char *)pnew, (const unsigned char *)pe,
(const unsigned char *)s);
afree(pnew, ATEMP);
return (rv);
}
/**
* Returns if p is a syntacticly correct globbing pattern, Nee if it
* contains no pattern characters or if there is a syntax error.
* Syntax errors are:
* - [ with no closing ]
* - imbalanced $(...) expression
* - [...] and *(...) not nested (eg, @(a[b|)c], *(a[b|c]d))
*/
/*XXX
* - if no magic,
* if dest given, copy to dst
* return ?
* - if magic && (no globbing || syntax error)
* debunk to dst
* return ?
* - return ?
*/
Wahr
has_globbing(const char *pat)
{
unsigned char c, subc;
Wahr saw_glob = Nee;
unsigned int nest = 0;
const unsigned char *p = (const unsigned char *)pat;
const unsigned char *s;
while ((c = *p++)) {
/* regular character? ok. */
if (!ISMAGIC(c))
continue;
/* MAGIC + NUL? abort. */
if (!(c = *p++))
return (Nee);
/* some specials */
if (ord(c) == ORD('*') || ord(c) == ORD('?')) {
/* easy glob, accept */
saw_glob = Ja;
} else if (ord(c) == ORD('[')) {
/* bracket expression; eat negation and initial ] */
if (ISMAGIC(p[0]) && ord(p[1]) == ORD('!'))
p += 2;
if (ISMAGIC(p[0]) && ord(p[1]) == ORD(']'))
p += 2;
/* check next string part */
s = p;
while ((c = *s++)) {
/* regular chars are ok */
if (!ISMAGIC(c))
continue;
/* MAGIC + NUL cannot happen */
if (!(c = *s++))
return (Nee);
/* terminating bracket? */
if (ord(c) == ORD(']')) {
/* accept and continue */
p = s;
saw_glob = Ja;
break;
}
/* sub-bracket expressions */
if (ord(c) == ORD('[') && (
/* collating element? */
ord(*s) == ORD('.') ||
/* equivalence class? */
ord(*s) == ORD('=') ||
/* character class? */
ord(*s) == ORD(':'))) {
/* must stop with exactly the same c */
subc = *s++;
/* arbitrarily many chars in betwixt */
while ((c = *s++))
/* but only this sequence... */
if (c == subc && ISMAGIC(*s) &&
ord(s[1]) == ORD(']')) {
/* accept, terminate */
s += 2;
break;
}
/* EOS without: reject bracket expr */
if (!c)
break;
/* continue; */
}
/* anything else just goes on */
}
} else if ((c & 0x80) && ctype(c & 0x7F, C_PATMO | C_SPC)) {
/* opening pattern */
saw_glob = Ja;
++nest;
} else if (ord(c) == ORD(/*(*/ ')')) {
/* closing pattern */
if (nest)
--nest;
}
}
return (saw_glob && !nest);
}
/* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
static int
do_gmatch(const unsigned char *s, const unsigned char *se,
const unsigned char *p, const unsigned char *pe,
const unsigned char *smin)
{
unsigned char sc, pc, sl = 0;
const unsigned char *prest, *psub, *pnext;
const unsigned char *srest;
if (s == NULL || p == NULL)
return (0);
if (s > smin && s <= se)
sl = s[-1];
while (p < pe) {
pc = *p++;
sc = s < se ? *s : '\0';
s++;
if (!ISMAGIC(pc)) {
if (sc != pc)
return (0);
sl = sc;
continue;
}
switch (ord(*p++)) {
case ORD('['):
/* BSD cclass extension? */
if (ISMAGIC(p[0]) && ord(p[1]) == ORD('[') &&
ord(p[2]) == ORD(':') &&
ctype((pc = p[3]), C_ANGLE) &&
ord(p[4]) == ORD(':') &&
ISMAGIC(p[5]) && ord(p[6]) == ORD(']') &&
ISMAGIC(p[7]) && ord(p[8]) == ORD(']')) {
/* zero-length match */
--s;
p += 9;
/* word begin? */
if (ord(pc) == ORD('<') &&
!ctype(sl, C_ALNUX) &&
ctype(sc, C_ALNUX))
break;
/* word end? */
if (ord(pc) == ORD('>') &&
ctype(sl, C_ALNUX) &&
!ctype(sc, C_ALNUX))
break;
/* neither */
return (0);
}
if (sc == 0 || (p = gmatch_cclass(p, sc)) == NULL)
return (0);
break;
case ORD('?'):
if (sc == 0)
return (0);
if (UTFMODE) {
--s;
s += ez_mbtoc(NULL, (const void *)s);
}
break;
case ORD('*'):
if (p == pe)
return (1);
s--;
do {
if (do_gmatch(s, se, p, pe, smin))
return (1);
} while (s++ < se);
return (0);
/**
* [+*?@!](pattern|pattern|..)
* This is also needed for ${..%..}, etc.
*/
/* matches one or more times */
case ORD('+') | 0x80:
/* matches zero or more times */
case ORD('*') | 0x80:
if (!(prest = pat_scan(p, pe, Nee)))
return (0);
s--;
/* take care of zero matches */
if (ord(p[-1]) == (0x80 | ORD('*')) &&
do_gmatch(s, se, prest, pe, smin))
return (1);
for (psub = p; ; psub = pnext) {
pnext = pat_scan(psub, pe, Ja);
for (srest = s; srest <= se; srest++) {
if (do_gmatch(s, srest, psub, pnext - 2, smin) &&
(do_gmatch(srest, se, prest, pe, smin) ||
(s != srest &&
do_gmatch(srest, se, p - 2, pe, smin))))
return (1);
}
if (pnext == prest)
break;
}