summaryrefslogtreecommitdiffstats
path: root/src/bfstd.c
blob: 15e86672f051cf9022fe1524dbb84e192858bda4 (plain)
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
// Copyright © Tavian Barnes <tavianator@tavianator.com>
// SPDX-License-Identifier: 0BSD

#include "bfstd.h"
#include "bit.h"
#include "config.h"
#include "diag.h"
#include "sanity.h"
#include "thread.h"
#include "xregex.h"
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <langinfo.h>
#include <locale.h>
#include <nl_types.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <wchar.h>
#include <wctype.h>

#if BFS_USE_SYS_SYSMACROS_H
#  include <sys/sysmacros.h>
#elif BFS_USE_SYS_MKDEV_H
#  include <sys/mkdev.h>
#endif

#if BFS_USE_UTIL_H
#  include <util.h>
#endif

bool error_is_like(int error, int category) {
	if (error == category) {
		return true;
	}

	switch (category) {
	case ENOENT:
		return error == ENOTDIR;

#if __DragonFly__
	// https://twitter.com/tavianator/status/1742991411203485713
	case ENAMETOOLONG:
		return error == EFAULT;
#endif
	}

	return false;
}

bool errno_is_like(int category) {
	return error_is_like(errno, category);
}

char *xdirname(const char *path) {
	size_t i = xbaseoff(path);

	// Skip trailing slashes
	while (i > 0 && path[i - 1] == '/') {
		--i;
	}

	if (i > 0) {
		return strndup(path, i);
	} else if (path[i] == '/') {
		return strdup("/");
	} else {
		return strdup(".");
	}
}

char *xbasename(const char *path) {
	size_t i = xbaseoff(path);
	size_t len = strcspn(path + i, "/");
	if (len > 0) {
		return strndup(path + i, len);
	} else if (path[i] == '/') {
		return strdup("/");
	} else {
		return strdup(".");
	}
}

size_t xbaseoff(const char *path) {
	size_t i = strlen(path);

	// Skip trailing slashes
	while (i > 0 && path[i - 1] == '/') {
		--i;
	}

	// Find the beginning of the name
	while (i > 0 && path[i - 1] != '/') {
		--i;
	}

	// Skip leading slashes
	while (path[i] == '/' && path[i + 1]) {
		++i;
	}

	return i;
}

FILE *xfopen(const char *path, int flags) {
	char mode[4];

	switch (flags & O_ACCMODE) {
	case O_RDONLY:
		strcpy(mode, "rb");
		break;
	case O_WRONLY:
		strcpy(mode, "wb");
		break;
	case O_RDWR:
		strcpy(mode, "r+b");
		break;
	default:
		bfs_bug("Invalid access mode");
		errno = EINVAL;
		return NULL;
	}

	if (flags & O_APPEND) {
		mode[0] = 'a';
	}

	int fd;
	if (flags & O_CREAT) {
		fd = open(path, flags, 0666);
	} else {
		fd = open(path, flags);
	}

	if (fd < 0) {
		return NULL;
	}

	FILE *ret = fdopen(fd, mode);
	if (!ret) {
		close_quietly(fd);
		return NULL;
	}

	return ret;
}

char *xgetdelim(FILE *file, char delim) {
	char *chunk = NULL;
	size_t n = 0;
	ssize_t len = getdelim(&chunk, &n, delim, file);
	if (len >= 0) {
		if (chunk[len] == delim) {
			chunk[len] = '\0';
		}
		return chunk;
	} else {
		free(chunk);
		if (!ferror(file)) {
			errno = 0;
		}
		return NULL;
	}
}

const char *xgetprogname(void) {
	const char *cmd = NULL;
#if __GLIBC__
	cmd = program_invocation_short_name;
#elif BSD
	cmd = getprogname();
#endif

	if (!cmd) {
		cmd = BFS_COMMAND;
	}

	return cmd;
}

/** Compile and execute a regular expression for xrpmatch(). */
static int xrpregex(nl_item item, const char *response) {
	const char *pattern = nl_langinfo(item);
	if (!pattern) {
		return -1;
	}

	struct bfs_regex *regex;
	int ret = bfs_regcomp(&regex, pattern, BFS_REGEX_POSIX_EXTENDED, 0);
	if (ret == 0) {
		ret = bfs_regexec(regex, response, 0);
	}

	bfs_regfree(regex);
	return ret;
}

/** Check if a response is affirmative or negative. */
static int xrpmatch(const char *response) {
	int ret = xrpregex(NOEXPR, response);
	if (ret > 0) {
		return 0;
	} else if (ret < 0) {
		return -1;
	}

	ret = xrpregex(YESEXPR, response);
	if (ret > 0) {
		return 1;
	} else if (ret < 0) {
		return -1;
	}

	// Failsafe: always handle y/n
	char c = response[0];
	if (c == 'n' || c == 'N') {
		return 0;
	} else if (c == 'y' || c == 'Y') {
		return 1;
	} else {
		return -1;
	}
}

int ynprompt(void) {
	fflush(stderr);

	char *line = xgetdelim(stdin, '\n');
	int ret = line ? xrpmatch(line) : -1;
	free(line);
	return ret;
}

/** Get the single character describing the given file type. */
static char type_char(mode_t mode) {
	switch (mode & S_IFMT) {
	case S_IFREG:
		return '-';
	case S_IFBLK:
		return 'b';
	case S_IFCHR:
		return 'c';
	case S_IFDIR:
		return 'd';
	case S_IFLNK:
		return 'l';
	case S_IFIFO:
		return 'p';
	case S_IFSOCK:
		return 's';
#ifdef S_IFDOOR
	case S_IFDOOR:
		return 'D';
#endif
#ifdef S_IFPORT
	case S_IFPORT:
		return 'P';
#endif
#ifdef S_IFWHT
	case S_IFWHT:
		return 'w';
#endif
	}

	return '?';
}

void *xmemdup(const void *src, size_t size) {
	void *ret = malloc(size);
	if (ret) {
		memcpy(ret, src, size);
	}
	return ret;
}

char *xstpecpy(char *dest, char *end, const char *src) {
	return xstpencpy(dest, end, src, SIZE_MAX);
}

char *xstpencpy(char *dest, char *end, const char *src, size_t n) {
	size_t space = end - dest;
	n = space < n ? space : n;
	n = strnlen(src, n);
	memcpy(dest, src, n);
	if (n < space) {
		dest[n] = '\0';
		return dest + n;
	} else {
		end[-1] = '\0';
		return end;
	}
}

const char *xstrerror(int errnum) {
	int saved = errno;
	const char *ret = NULL;
	static thread_local char buf[256];

	// - __APPLE__
	// - __COSMOPOLITAN__
	//     - No strerror_l()
	// - __FreeBSD__ && SANITIZE_MEMORY
	//     - duplocale() triggers https://github.com/llvm/llvm-project/issues/65532
#if __APPLE__ || __COSMOPOLITAN__ || (__FreeBSD__ && SANITIZE_MEMORY)
	if (strerror_r(errnum, buf, sizeof(buf)) == 0) {
		ret = buf;
	}
#else
#  if __NetBSD__
	// NetBSD has no thread-specific locales
	locale_t loc = LC_GLOBAL_LOCALE;
#  else
	locale_t loc = uselocale((locale_t)0);
#  endif

	locale_t copy = loc;
	if (copy == LC_GLOBAL_LOCALE) {
		copy = duplocale(copy);
	}

	if (copy != (locale_t)0) {
		ret = strerror_l(errnum, copy);

		if (loc == LC_GLOBAL_LOCALE) {
			freelocale(copy);
		}
	}
#endif

	if (!ret) {
		// Fallback for strerror_[lr]() or duplocale() failures
		snprintf(buf, sizeof(buf), "Unknown error %d", errnum);
		ret = buf;
	}

	errno = saved;
	return ret;
}

void xstrmode(mode_t mode, char str[11]) {
	strcpy(str, "----------");

	str[0] = type_char(mode);

	if (mode & 00400) {
		str[1] = 'r';
	}
	if (mode & 00200) {
		str[2] = 'w';
	}
	if ((mode & 04100) == 04000) {
		str[3] = 'S';
	} else if (mode & 04000) {
		str[3] = 's';
	} else if (mode & 00100) {
		str[3] = 'x';
	}

	if (mode & 00040) {
		str[4] = 'r';
	}
	if (mode & 00020) {
		str[5] = 'w';
	}
	if ((mode & 02010) == 02000) {
		str[6] = 'S';
	} else if (mode & 02000) {
		str[6] = 's';
	} else if (mode & 00010) {
		str[6] = 'x';
	}

	if (mode & 00004) {
		str[7] = 'r';
	}
	if (mode & 00002) {
		str[8] = 'w';
	}
	if ((mode & 01001) == 01000) {
		str[9] = 'T';
	} else if (mode & 01000) {
		str[9] = 't';
	} else if (mode & 00001) {
		str[9] = 'x';
	}
}

/** Check if an rlimit value is infinite. */
static bool rlim_isinf(rlim_t r) {
	// Consider RLIM_{INFINITY,SAVED_{CUR,MAX}} all equally infinite
	if (r == RLIM_INFINITY) {
		return true;
	}

#ifdef RLIM_SAVED_CUR
	if (r == RLIM_SAVED_CUR) {
		return true;
	}
#endif

#ifdef RLIM_SAVED_MAX
	if (r == RLIM_SAVED_MAX) {
		return true;
	}
#endif

	return false;
}

int rlim_cmp(rlim_t a, rlim_t b) {
	bool a_inf = rlim_isinf(a);
	bool b_inf = rlim_isinf(b);
	if (a_inf || b_inf) {
		return a_inf - b_inf;
	}

	return (a > b) - (a < b);
}

dev_t xmakedev(int ma, int mi) {
#ifdef makedev
	return makedev(ma, mi);
#else
	return (ma << 8) | mi;
#endif
}

int xmajor(dev_t dev) {
#ifdef major
	return major(dev);
#else
	return dev >> 8;
#endif
}

int xminor(dev_t dev) {
#ifdef minor
	return minor(dev);
#else
	return dev & 0xFF;
#endif
}

pid_t xwaitpid(pid_t pid, int *status, int flags) {
	pid_t ret;
	do {
		ret = waitpid(pid, status, flags);
	} while (ret < 0 && errno == EINTR);
	return ret;
}

int dup_cloexec(int fd) {
#ifdef F_DUPFD_CLOEXEC
	return fcntl(fd, F_DUPFD_CLOEXEC, 0);
#else
	int ret = dup(fd);
	if (ret < 0) {
		return -1;
	}

	if (fcntl(ret, F_SETFD, FD_CLOEXEC) == -1) {
		close_quietly(ret);
		return -1;
	}

	return ret;
#endif
}

int pipe_cloexec(int pipefd[2]) {
#if __linux__ || (BSD && !__APPLE__)
	return pipe2(pipefd, O_CLOEXEC);
#else
	if (pipe(pipefd) != 0) {
		return -1;
	}

	if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) == -1 || fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) == -1) {
		close_quietly(pipefd[1]);
		close_quietly(pipefd[0]);
		return -1;
	}

	return 0;
#endif
}

size_t xread(int fd, void *buf, size_t nbytes) {
	size_t count = 0;

	while (count < nbytes) {
		ssize_t ret = read(fd, (char *)buf + count, nbytes - count);
		if (ret < 0) {
			if (errno == EINTR) {
				continue;
			} else {
				break;
			}
		} else if (ret == 0) {
			// EOF
			errno = 0;
			break;
		} else {
			count += ret;
		}
	}

	return count;
}

size_t xwrite(int fd, const void *buf, size_t nbytes) {
	size_t count = 0;

	while (count < nbytes) {
		ssize_t ret = write(fd, (const char *)buf + count, nbytes - count);
		if (ret < 0) {
			if (errno == EINTR) {
				continue;
			} else {
				break;
			}
		} else if (ret == 0) {
			// EOF?
			errno = 0;
			break;
		} else {
			count += ret;
		}
	}

	return count;
}

void close_quietly(int fd) {
	int error = errno;
	xclose(fd);
	errno = error;
}

int xclose(int fd) {
	int ret = close(fd);
	if (ret != 0) {
		bfs_verify(errno != EBADF);
	}
	return ret;
}

int xfaccessat(int fd, const char *path, int amode) {
	int ret = faccessat(fd, path, amode, 0);

#ifdef AT_EACCESS
	// Some platforms, like Hurd, only support AT_EACCESS.  Other platforms,
	// like Android, don't support AT_EACCESS at all.
	if (ret != 0 && (errno == EINVAL || errno == ENOTSUP)) {
		ret = faccessat(fd, path, amode, AT_EACCESS);
	}
#endif

	return ret;
}

char *xconfstr(int name) {
#if __ANDROID__
	errno = ENOTSUP;
	return NULL;
#else
	size_t len = confstr(name, NULL, 0);
	if (len == 0) {
		return NULL;
	}

	char *str = malloc(len);
	if (!str) {
		return NULL;
	}

	if (confstr(name, str, len) != len) {
		free(str);
		return NULL;
	}

	return str;
#endif // !__ANDROID__
}

char *xreadlinkat(int fd, const char *path, size_t size) {
	ssize_t len;
	char *name = NULL;

	if (size == 0) {
		size = 64;
	} else {
		++size; // NUL terminator
	}

	while (true) {
		char *new_name = realloc(name, size);
		if (!new_name) {
			goto error;
		}
		name = new_name;

		len = readlinkat(fd, path, name, size);
		if (len < 0) {
			goto error;
		} else if ((size_t)len >= size) {
			size *= 2;
		} else {
			break;
		}
	}

	name[len] = '\0';
	return name;

error:
	free(name);
	return NULL;
}

int xstrtofflags(const char **str, unsigned long long *set, unsigned long long *clear) {
#if BSD && !__GNU__
	char *str_arg = (char *)*str;

#if __OpenBSD__
	typedef uint32_t fflags_t;
#else
	typedef unsigned long fflags_t;
#endif
	fflags_t set_arg = 0;
	fflags_t clear_arg = 0;

#if __NetBSD__
	int ret = string_to_flags(&str_arg, &set_arg, &clear_arg);
#else
	int ret = strtofflags(&str_arg, &set_arg, &clear_arg);
#endif

	*str = str_arg;
	*set = set_arg;
	*clear = clear_arg;

	if (ret != 0) {
		errno = EINVAL;
	}
	return ret;
#else // !BSD
	errno = ENOTSUP;
	return -1;
#endif
}

wint_t xmbrtowc(const char *str, size_t *i, size_t len, mbstate_t *mb) {
	wchar_t wc;
	size_t mblen = mbrtowc(&wc, str + *i, len - *i, mb);
	switch (mblen) {
	case -1: // Invalid byte sequence
	case -2: // Incomplete byte sequence
		*i += 1;
		*mb = (mbstate_t){0};
		return WEOF;
	default:
		*i += mblen;
		return wc;
	}
}

size_t xstrwidth(const char *str) {
	size_t len = strlen(str);
	size_t ret = 0;

	mbstate_t mb = {0};
	for (size_t i = 0; i < len;) {
		wint_t wc = xmbrtowc(str, &i, len, &mb);
		if (wc == WEOF) {
			// Assume a single-width '?'
			++ret;
		} else {
			ret += xwcwidth(wc);
		}
	}

	return ret;
}

/**
 * Character type flags.
 */
enum ctype {
	IS_PRINT = 1 << 0,
	IS_SPACE = 1 << 1,
};

/** Cached ctypes. */
static unsigned char ctype_cache[UCHAR_MAX + 1];

/** Initialize the ctype cache. */
static void char_cache_init(void) {
	for (size_t c = 0; c <= UCHAR_MAX; ++c) {
		if (xisprint(c)) {
			ctype_cache[c] |= IS_PRINT;
		}
		if (xisspace(c)) {
			ctype_cache[c] |= IS_SPACE;
		}
	}
}

/** Check if a character is printable. */
static bool wesc_isprint(unsigned char c, enum wesc_flags flags) {
	if (ctype_cache[c] & IS_PRINT) {
		return true;
	}

	// Technically a literal newline is safe inside single quotes, but $'\n'
	// is much nicer than '
	// '
	if (!(flags & WESC_SHELL) && (ctype_cache[c] & IS_SPACE)) {
		return true;
	}

	return false;
}

/** Check if a wide character is printable. */
static bool wesc_iswprint(wchar_t c, enum wesc_flags flags) {
	if (xiswprint(c)) {
		return true;
	}

	if (!(flags & WESC_SHELL) && xiswspace(c)) {
		return true;
	}

	return false;
}

/** Get the length of the longest printable prefix of a string. */
static size_t printable_len(const char *str, size_t len, enum wesc_flags flags) {
	static pthread_once_t once = PTHREAD_ONCE_INIT;
	invoke_once(&once, char_cache_init);

	// Fast path: avoid multibyte checks
	size_t i, word;
	for (i = 0; i + sizeof(word) <= len;) {
		// Word-at-a-time isascii()
		memcpy(&word, str + i, sizeof(word));
		// 0xFFFF... / 0xFF == 0x10101...
		size_t mask = (SIZE_MAX / 0xFF) << 7;
		if (word & mask) {
			goto multibyte;
		}

		for (size_t j = 0; j < sizeof(word); ++i, ++j) {
			if (!wesc_isprint(str[i], flags)) {
				return i;
			}
		}
	}

	for (; i < len; ++i) {
		char c = str[i];
		if (!xisascii(c)) {
			goto multibyte;
		}
		if (!wesc_isprint(c, flags)) {
			return i;
		}
	}

multibyte:;
	mbstate_t mb = {0};

	for (size_t j = i; i < len; i = j) {
		wint_t wc = xmbrtowc(str, &j, len, &mb);
		if (wc == WEOF) {
			break;
		}
		if (!wesc_iswprint(wc, flags)) {
			break;
		}
	}

	return i;
}

/** Convert a special char into a well-known escape sequence like "\n". */
static const char *dollar_esc(char c) {
	// https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html
	switch (c) {
	case '\a':
		return "\\a";
	case '\b':
		return "\\b";
	case '\033':
		return "\\e";
	case '\f':
		return "\\f";
	case '\n':
		return "\\n";
	case '\r':
		return "\\r";
	case '\t':
		return "\\t";
	case '\v':
		return "\\v";
	case '\'':
		return "\\'";
	case '\\':
		return "\\\\";
	default:
		return NULL;
	}
}

/** $'Quote' a string for the shell. */
static char *dollar_quote(char *dest, char *end, const char *str, size_t len, enum wesc_flags flags) {
	dest = xstpecpy(dest, end, "$'");

	mbstate_t mb = {0};
	for (size_t i = 0; i < len;) {
		size_t start = i;
		bool safe = false;

		wint_t wc = xmbrtowc(str, &i, len, &mb);
		if (wc != WEOF) {
			safe = wesc_iswprint(wc, flags);
		}

		for (size_t j = start; safe && j < i; ++j) {
			if (str[j] == '\'' || str[j] == '\\') {
				safe = false;
			}
		}

		if (safe) {
			dest = xstpencpy(dest, end, str + start, i - start);
		} else {
			for (size_t j = start; j < i; ++j) {
				unsigned char byte = str[j];
				const char *esc = dollar_esc(byte);
				if (esc) {
					dest = xstpecpy(dest, end, esc);
				} else {
					static const char *hex[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
					dest = xstpecpy(dest, end, "\\x");
					dest = xstpecpy(dest, end, hex[byte / 0x10]);
					dest = xstpecpy(dest, end, hex[byte % 0x10]);
				}
			}
		}
	}

	return xstpecpy(dest, end, "'");
}

/** How much of this string is safe as a bare word? */
static size_t bare_len(const char *str, size_t len) {
	// https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_02
	size_t ret = strcspn(str, "|&;<>()$`\\\"' *?[#˜=%!{}");
	return ret < len ? ret : len;
}

/** How much of this string is safe to double-quote? */
static size_t quotable_len(const char *str, size_t len) {
	// https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_02_03
	size_t ret = strcspn(str, "`$\\\"!");
	return ret < len ? ret : len;
}

/** "Quote" a string for the shell. */
static char *double_quote(char *dest, char *end, const char *str, size_t len) {
	dest = xstpecpy(dest, end, "\"");
	dest = xstpencpy(dest, end, str, len);
	return xstpecpy(dest, end, "\"");
}

/** 'Quote' a string for the shell. */
static char *single_quote(char *dest, char *end, const char *str, size_t len) {
	bool open = false;

	while (len > 0) {
		size_t chunk = strcspn(str, "'");
		chunk = chunk < len ? chunk : len;
		if (chunk > 0) {
			if (!open) {
				dest = xstpecpy(dest, end, "'");
				open = true;
			}
			dest = xstpencpy(dest, end, str, chunk);
			str += chunk;
			len -= chunk;
		}

		while (len > 0 && *str == '\'') {
			if (open) {
				dest = xstpecpy(dest, end, "'");
				open = false;
			}
			dest = xstpecpy(dest, end, "\\'");
			++str;
			--len;
		}
	}

	if (open) {
		dest = xstpecpy(dest, end, "'");
	}

	return dest;
}

char *wordesc(char *dest, char *end, const char *str, enum wesc_flags flags) {
	return wordnesc(dest, end, str, SIZE_MAX, flags);
}

char *wordnesc(char *dest, char *end, const char *str, size_t n, enum wesc_flags flags) {
	size_t len = strnlen(str, n);
	char *start = dest;

	if (printable_len(str, len, flags) < len) {
		// String contains unprintable chars, use $'this\x7Fsyntax'
		dest = dollar_quote(dest, end, str, len, flags);
	} else if (!(flags & WESC_SHELL) || bare_len(str, len) == len) {
		// Whole string is safe as a bare word
		dest = xstpencpy(dest, end, str, len);
	} else if (quotable_len(str, len) == len) {
		// Whole string is safe to double-quote
		dest = double_quote(dest, end, str, len);
	} else {
		// Single-quote the whole string
		dest = single_quote(dest, end, str, len);
	}

	if (dest == start) {
		dest = xstpecpy(dest, end, "\"\"");
	}

	return dest;
}