summaryrefslogtreecommitdiff
path: root/src/string.c
blob: e4680632a14d965e35930e6c43fc390f1a1fd543 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
/*
 *	C-string functions
 *	Copyright Jan Engelhardt, 1999-2010
 *
 *	This file is part of libHX. libHX is free software; you can
 *	redistribute it and/or modify it under the terms of the GNU Lesser
 *	General Public License as published by the Free Software Foundation;
 *	either version 2.1 or (at your option) any later version.
 */
#include <errno.h>
#include <limits.h>
#include <math.h> /* nextafter */
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libHX/ctype_helper.h>
#include <libHX/string.h>
#include "internal.h"

/**
 * %HXQUOTE_ACCEPT:	the listed characters are passed through,
 * 			all others need to be quoted
 * %HXQUOTE_REJECT:	the listed characters need to be quoted,
 * 			all others pass through
 */
enum HX_quote_selector {
	HXQUOTE_ALWAYS,
	HXQUOTE_ACCEPT,
	HXQUOTE_REJECT,
};

/**
 * @selector:	whether this rule is accept- or reject-based
 * @qchars:	characters that need (no) quoting
 */
struct HX_quote_rule {
	char selector;
	const char *chars;
};

static const char HX_hexenc[16] = "0123456789ABCDEF";

EXPORT_SYMBOL char *HX_basename(const char *s)
{
	const char *p;
	/* ignore trailing slashes */
	for (p = s + strlen(s) - 1; p >= s && *p == '/'; --p)
		;
	if (p < s)
		/*
		 * String contained only slashes - this must be the root
		 * directory. Since we have the opportunity, rather than
		 * returning "////", just give the cleaned-up "/".
		 */
		return const_cast1(char *, s + strlen(s) - 1);
	if ((p = HX_strbchr(s, p, '/')) != NULL)
		return const_cast1(char *, p + 1);
	return const_cast1(char *, s);
}

EXPORT_SYMBOL char *HX_basename_exact(const char *s)
{
	const char *start, *end;
	char *ret;
	int len;

	if (*s == '\0')
		return HX_strdup(".");
	/* ignore trailing slashes */
	for (end = s + strlen(s) - 1; end >= s && *end == '/'; --end)
		;
	if (end < s)
		/* string consisted of only slashes */
		return HX_strdup("/");

	start = HX_strbchr(s, end, '/');
	if (start == NULL) {
		len = end - s + 1;
		ret = HX_memdup(s, len + 1);
	} else {
		++start;
		len = end - start + 1;
		ret = HX_memdup(start, len + 1);
	}
	if (ret == NULL)
		return NULL;
	ret[len] = '\0';
	return ret;
}

EXPORT_SYMBOL char *HX_chomp(char *s)
{
	char *p = s + strlen(s) - 1;
	while (p >= s) {
		if (*p != '\n' && *p != '\r')
			break;
		*p-- = '\0';
	}
	return s;
}

EXPORT_SYMBOL char *HX_dirname(const char *s)
{
	const char *last, *stop;
	char *p;

	if (*s == '\0')
		return HX_strdup(".");

	for (last = s + strlen(s) - 1; last > s && *last == '/'; --last)
		;

	if ((stop = HX_strbchr(s, last, '/')) == NULL)
		return HX_strdup(".");

	for (; stop > s && *stop == '/'; --stop)
		;

	p = HX_memdup(s, stop - s + 2);
	p[stop-s+1] = '\0';
	return p;
}

EXPORT_SYMBOL hxmc_t *HX_getl(hxmc_t **ptr, FILE *fp)
{
	/* Read a whole line into a dynamic buffer. */
	char temp[MAXLNLEN];

	if (fgets(temp, sizeof(temp), fp) == NULL)
		return NULL;

	if (*ptr == NULL) {
		*ptr = HXmc_meminit(NULL, 0);
		if (*ptr == NULL)
			return NULL;
	} else {
		HXmc_trunc(ptr, 0);
	}

	do {
		if (HXmc_strcat(ptr, temp) == NULL)
			return *ptr;
		if (strchr(temp, '\n') != NULL)
			break;
	} while (fgets(temp, sizeof(temp), fp) != NULL);

	return *ptr;
}

EXPORT_SYMBOL void *HX_memmem(const void *vspace, size_t spacesize,
    const void *vpoint, size_t pointsize)
{
	const char *space = vspace, *point = vpoint;
	const char *head, *end;
	size_t tailsize;
	char *tail;

	if (pointsize == 0)
		return const_cast1(void *, vspace);
	if (pointsize > spacesize)
		return NULL;

	/* Do a BM-style trailer search and reduce calls to memcmp */
	head = space + (pointsize - 1);
	tail = memchr(head, point[pointsize-1], spacesize - (pointsize - 1));
	if (tail == NULL || pointsize == 1)
		return tail;
	end = space + spacesize;
	do {
		head = tail - pointsize + 1;
		if (memcmp(head, point, pointsize) == 0)
			return const_cast(char *, head);
		++tail;
		tailsize = end - tail;
		tail = memchr(tail, point[pointsize-1], tailsize);
	} while (tail != NULL);
	return NULL;
}

EXPORT_SYMBOL char **HX_split(const char *str, const char *delim,
    int *cp, int max)
{
	/*
	 * @countp can be NULL in case you are not interested in the number of
	 * fields. In either case, you can find out the number of fields by
	 * scanning through the resulting vector.
	 */
	int count = 0;
	char **ret;

	if (cp == NULL)
		cp = &count;
	*cp = 1;

	{
		const char *wp = str;
		while ((wp = strpbrk(wp, delim)) != NULL) {
			if (++*cp >= max && max > 0) {
				*cp = max;
				break;
			}
			++wp;
		}
	}

	if (max == 0 || *cp < max)
		max = *cp;
	else if (*cp > max)
		*cp = max;

	ret = malloc(sizeof(char *) * (*cp + 1));
	if (ret == nullptr)
		return nullptr;
	ret[*cp] = NULL;

	{
		char *seg, *wp = HX_strdup(str), *bg = wp;
		size_t i = 0;

		while (--max > 0) {
			seg      = HX_strsep(&wp, delim);
			ret[i++] = HX_strdup(seg);
		}

		ret[i++] = HX_strdup(wp);
		free(bg);
	}

	return ret;
}

EXPORT_SYMBOL char **HX_split_inplace(char *s, const char *delim, int *fld, int max)
{
	char **stk;
	const char *p = s;
	int count = 1;

	for (p = strpbrk(p, delim); p != NULL; p = strpbrk(++p, delim))
		if (++count >= max && max > 0) {
			count = max;
			break;
		}

	stk = malloc(sizeof(char *) * (count + 1));
	if (stk == NULL)
		return NULL;
	stk[count] = NULL;
	count = HX_split_fixed(s, delim, count, stk);
	if (fld != NULL)
		*fld = count;
	return stk;
}

EXPORT_SYMBOL int HX_split_fixed(char *s, const char *delim, int max, char **stk)
{
	/*
	 * HX_split_fixed - the "stack split" (we try to avoid using the heap):
	 * Split @s (modifies it, so must be writable!) at @delim with at most
	 * @max fields and putting the results into @stk[0..@max-1].
	 *
	 * Example on @max:
	 *	char *stk[max];
	 *	HX_split_fixed(s, delim, max, stk);
	 */
	int i = 0;
	char *p;

	while (--max > 0) {
		if ((p = strpbrk(s, delim)) == NULL)
			break;
		stk[i++] = s;
		*p = '\0';
		s  = p + 1;
	}

	stk[i++] = s;
	return i;
}

EXPORT_SYMBOL char *HX_strbchr(const char *start, const char *now, char d)
{
	/* Find the last occurrence of @d within @start and (including) @now. */
	while (now >= start)
		if (*now-- == d)
			return const_cast1(char *, ++now);
	return NULL;
}

/**
 * This is the counterpart to strpbrk(). Returns a pointer to the first
 * character not in @accept, or otherwise %NULL.
 */
EXPORT_SYMBOL char *HX_strchr2(const char *s, const char *accept)
{
	size_t seg = strspn(s, accept);

	if (s[seg] == '\0')
		return NULL;
	return const_cast1(char *, s + seg);
}

EXPORT_SYMBOL char *HX_strclone(char **pa, const char *pb)
{
	if (*pa == pb)
		return *pa;
	if (*pa != NULL) {
		free(*pa);
		*pa = NULL;
	}
	if (pb == NULL)
		return NULL;
	if ((*pa = malloc(strlen(pb) + 1)) == NULL)
		return NULL;
	strcpy(*pa, pb);
	return *pa;
}

EXPORT_SYMBOL char *HX_strdup(const char *src)
{
	if (src == NULL)
		return NULL;
	/* return HX_strndup(src, SIZE_MAX); */
	return HX_memdup(src, strlen(src) + 1);
}

EXPORT_SYMBOL char *HX_strlcat(char *dest, const char *src, size_t len)
{
	ssize_t x = len - strlen(dest) - 1;
	if (x <= 0)
		return dest;
	return strncat(dest, src, x);
}

EXPORT_SYMBOL char *HX_strlcpy(char *dest, const char *src, size_t n)
{
	if (n == 0)
		return dest;
	strncpy(dest, src, n);
	dest[n-1] = '\0';
	return dest;
}

EXPORT_SYMBOL char *HX_strlncat(char *dest, const char *src, size_t dlen,
    size_t slen)
{
	ssize_t x = dlen - strlen(dest) - 1;
	if (x <= 0)
		return dest;
	x = ((ssize_t)slen < x) ? (ssize_t)slen : x;
	return strncat(dest, src, x);
}

EXPORT_SYMBOL char *HX_strlower(char *orig)
{
	char *expr;
	for (expr = orig; *expr != '\0'; ++expr)
		*expr = HX_tolower(*expr);
	return orig;
}

EXPORT_SYMBOL size_t HX_strltrim(char *expr)
{
	char *travp;
	size_t diff = 0;
	travp = expr;

	while (HX_isspace(*travp))
		++travp;
	if ((diff = travp - expr) > 0)
		memmove(expr, travp, strlen(travp) + 1);
	return diff;
}

EXPORT_SYMBOL char *HX_stpltrim(const char *p)
{
	while (HX_isspace(*p))
		++p;
	return const_cast1(char *, p);
}

/**
 * Helper for substr() function for dealing with negative off/len values
 * @z:		total length of string
 * @offset:	n>=0 specifies offset from the start,
 * 		n<0 specifies offset from the end
 * @len:	"length"; n>=0 specifies length to copy (from @offset),
 * 		n<0 specifies the byte relative to the end at which to stop
 *
 * @abstart:	(result) absolute start
 * @retval:	(result) absolute length to copy (from *@abstart)
 */
size_t HX_substr_helper(size_t z, long offset, long len, size_t *start)
{
	if (offset >= 0)
		*start = offset;
	else if (offset == LONG_MIN)
		*start = z + -static_cast(size_t, LONG_MIN);
	else
		*start = z >= static_cast(unsigned long, -offset) ? z + offset : z;

	size_t end;
	if (len >= 0)
		end = *start < SIZE_MAX - len ? *start + len : SIZE_MAX;
	else if (len == LONG_MIN)
		end = z + -static_cast(unsigned long, LONG_MIN);
	else
		end = z >= static_cast(unsigned long, -len) ? z + len : 0;
	if (end > z)
		end = z;
	return end > *start ? end - *start : 0;
}

/* supports negative offsets like scripting languages */
EXPORT_SYMBOL char *HX_strmid(const char *expr, long offset, long length)
{
	size_t start = 0, tocopy = HX_substr_helper(strlen(expr), offset, length, &start);
	char *buffer = malloc(tocopy + 1);
	if (buffer == nullptr)
		return NULL;
	memcpy(buffer, &expr[start], tocopy);
	buffer[tocopy] = '\0';
	return buffer;
}

EXPORT_SYMBOL char *HX_strndup(const char *src, size_t size)
{
	char *ret;
	size_t z;

	if (src == NULL)
		return NULL;
	z = strlen(src);
	if (z < size)
		size = z;
	if ((ret = malloc(size + 1)) == NULL)
		return NULL;
	memcpy(ret, src, size);
	ret[size] = '\0';
	return ret;
}

EXPORT_SYMBOL size_t HX_strnlen(const char *src, size_t size)
{
	const char *ptr = src;
	for (; *ptr != '\0' && size > 0; --size, ++ptr)
		;
	return ptr - src;
}

EXPORT_SYMBOL size_t HX_strrcspn(const char *s, const char *rej)
{
	size_t n = strlen(s);
	const char *p = s + n;
	while (--p >= s)
		if (strchr(rej, *p) != NULL)
			return p - s;
	return n;
}

EXPORT_SYMBOL char *HX_strrev(char *s)
{
	size_t i, z = strlen(s)-1, z2 = z / 2;

	for (i = 0; i < z2; ++i) {
		char temp;
		temp = s[i];
		s[i] = s[z-i];
		s[z-i] = temp;
	}

	return s;
}

EXPORT_SYMBOL size_t HX_strrtrim(char *expr)
{
	size_t i = strlen(expr), s = 0;
	while (i-- && HX_isspace(expr[i]))
		++s;
	expr[++i] = '\0';
	return s;
}

EXPORT_SYMBOL char *HX_strsep(char **sp, const char *d)
{
	char *begin, *end;

	if (*sp == NULL || **sp == '\0')
		return NULL;
	begin = *sp;

	if (d[0] == '\0' || d[1] == '\0') {
		if (*begin == *d)
			end = begin;
		else if (*begin == '\0')
			end = NULL;
		else
			end = strchr(begin + 1, *d);
	} else {
		end = strpbrk(begin, d);
	}

	if (end == NULL) {
		*sp = NULL;
	} else {
		*end++ = '\0';
		*sp = end;
	}

	return begin;
}

EXPORT_SYMBOL char *HX_strsep2(char **wp, const char *str)
{
	char *ptr, *ret;
	if (*wp == NULL)
		return NULL;
	ret = *wp;
	if ((ptr = strstr(*wp, str)) == NULL) {
		*wp = NULL;
		return ret;
	}
	*ptr = '\0';
	*wp  = ptr + strlen(str);
	return ret;
}

static const struct HX_quote_rule HX_quote_rules[] = {
	[HXQUOTE_SQUOTE]  = {HXQUOTE_REJECT, "'\\"},
	[HXQUOTE_DQUOTE]  = {HXQUOTE_REJECT, "\"\\"},
	[HXQUOTE_HTML]    = {HXQUOTE_REJECT, "\"&<>"},
	[HXQUOTE_LDAPFLT] = {HXQUOTE_REJECT, "\n*()\\"},
	[HXQUOTE_LDAPRDN] = {HXQUOTE_REJECT, "\n \"#+,;<=>\\"},
	[HXQUOTE_URIENC]  = {HXQUOTE_ACCEPT, "-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~"},
	[HXQUOTE_SQLSQUOTE] = {HXQUOTE_REJECT, "'"},
	[HXQUOTE_SQLBQUOTE] = {HXQUOTE_REJECT, "`"},
};

/**
 * HX_qsize_bsa - calculate length of statically expanded string (for accepts)
 * @s:		input string
 * @qchars:	characters that need quoting
 * @cost:	quoting cost per quoted character
 *
 * The cost depends on the quote format. Typical values:
 * 	1	when "&" becomes "\&" (programming language-like)
 * 	2	when "&" becomes "\26" (LDAPRDN/HTTPURI-like hex encoding)
 * 	3	when "&" becomes "\x26" (hex encoding for programming)
 */
static size_t
HX_qsize_bsa(const char *s, const char *qchars, unsigned int cost)
{
	const char *p = s;
	size_t n = strlen(s);

	while ((p = HX_strchr2(p, qchars)) != NULL) {
		n += cost;
		++p;
	}
	return n;
}

/**
 * HX_qsize_bsr - calculate length of statically expanded string (for rejects)
 * @s:		input string
 * @qchars:	characters that need quoting
 * @cost:	quoting cost per quoted character
 *
 * Same as for HX_qsize_bsa, but for HXQUOTE_REJECT-type rules.
 */
static size_t
HX_qsize_bsr(const char *s, const char *qchars, unsigned int cost)
{
	const char *p = s;
	size_t n = strlen(s);

	while ((p = strpbrk(p, qchars)) != NULL) {
		n += cost;
		++p;
	}
	return n;
}

static char *HX_quote_backslash(char *dest, const char *src, const char *qc)
{
	char *ret = dest;
	size_t len;

	while (*src != '\0') {
		len = strcspn(src, qc);
		if (len > 0) {
			memcpy(dest, src, len);
			dest += len;
			src  += len;
			if (*src == '\0')
				break;
		}
		*dest++ = '\\';
		*dest++ = *src++;
	}

	*dest = '\0';
	return ret;
}

static char *
HX_quote_sqlbackslash(char *dest, const char *src, const char *trm)
{
	char *ret = dest;
	size_t len;

	while (*src != '\0') {
		len = strcspn(src, trm);
		if (len > 0) {
			memcpy(dest, src, len);
			dest += len;
			src  += len;
			if (*src == '\0')
				break;
		}
		*dest++ = *trm;
		*dest++ = *trm;
		++src;
	}

	*dest = '\0';
	return ret;
}

/**
 * Encode @src into BASE-64 according to RFC 4648 and write result to @dest,
 * which must be of appropriate size, plus one for a trailing NUL.
 */
static char *HX_quote_base64(char *d, const char *s, char x1, char x2)
{
	char a[] =
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		"abcdefghijklmnopqrstuvwxyz0123456789??";
	size_t len = strlen(s);
	char *ret = d;

	a[62] = x1;
	a[63] = x2;
	while (len > 0) {
		if (len >= 3) {
			len -= 3;
			d[0] = a[(s[0] & 0xFC) >> 2];
			d[1] = a[((s[0] & 0x03) << 4) | ((s[1] & 0xF0) >> 4)];
			d[2] = a[((s[1] & 0x0F) << 2) | ((s[2] & 0xC0) >> 6)];
			d[3] = a[s[2] & 0x3F];
		} else if (len == 2) {
			len = 0;
			d[0] = a[(s[0] & 0xFC) >> 2];
			d[1] = a[((s[0] & 0x03) << 4) | ((s[1] & 0xF0) >> 4)];
			d[2] = a[(s[1] & 0x0F) << 2];
			d[3] = '=';
		} else if (len == 1) {
			len = 0;
			d[0] = a[(s[0] & 0xFC) >> 2];
			d[1] = a[(s[0] & 0x03) << 4];
			d[2] = '=';
			d[3] = '=';
		}
		s += 3;
		d += 4;
	}
	*d = '\0';
	return ret;
}

static size_t HX_qsize_html(const char *s)
{
	const char *p = s;
	size_t n = strlen(s);

	while ((p = strpbrk(p, HX_quote_rules[HXQUOTE_HTML].chars)) != NULL) {
		switch (*p) {
		/* minus 2: \0 and the original char */
		case '"':
			n += sizeof("&quot;") - 2;
			break;
		case '&':
			n += sizeof("&amp;") - 2;
			break;
		case '<':
		case '>':
			n += sizeof("&lt;") - 2;
			break;
		}
		++p;
	}
	return n;
}

static char *HX_quote_html(char *dest, const char *src)
{
#define put(s) do { \
	memcpy(dest, (s), sizeof(s) - 1); \
	dest += sizeof(s) - 1; \
} while (false);

	char *ret = dest;

	while (*src != '\0') {
		size_t len = strcspn(src, HX_quote_rules[HXQUOTE_HTML].chars);
		if (len > 0) {
			memcpy(dest, src, len);
			dest += len;
			src  += len;
			if (*src == '\0')
				break;
		}
		switch (*src++) {
		case '"': put("&quot;"); break;
		case '&': put("&amp;"); break;
		case '<': put("&lt;"); break;
		case '>': put("&gt;"); break;
		}
	}
	*dest = '\0';
	return ret;
#undef put
}

static char *HX_quote_ldap(char *dest, const char *src, const char *qc)
{
	char *ret = dest;
	size_t len;

	while (*src != '\0') {
		len = strcspn(src, qc);
		if (len > 0) {
			memcpy(dest, src, len);
			dest += len;
			src  += len;
			if (*src == '\0')
				break;
		}
		*dest++ = '\\';
		*dest++ = HX_hexenc[(*src >> 4) & 0x0F];
		*dest++ = HX_hexenc[*src++ & 0x0F];
	}

	*dest = '\0';
	return ret;
}

static char *HX_quote_urlenc(char *dest, const char *src)
{
	char *ret = dest;
	size_t len;

	while (*src != '\0') {
		len = strspn(src, HX_quote_rules[HXQUOTE_URIENC].chars);
		if (len > 0) {
			memcpy(dest, src, len);
			dest += len;
			src  += len;
			if (*src == '\0')
				break;
		}
		*dest++ = '%';
		*dest++ = HX_hexenc[(*src >> 4) & 0x0F];
		*dest++ = HX_hexenc[*src++ & 0x0F];
	}

	*dest = '\0';
	return ret;
}

/**
 * HX_quoted_size -
 * @s:		string to analyze
 * @type:	quoting method
 *
 * Returns the size of the string @s when quoted.
 */
static size_t HX_quoted_size(const char *s, unsigned int type)
{
	switch (type) {
	case HXQUOTE_SQUOTE:
	case HXQUOTE_DQUOTE:
	case HXQUOTE_SQLSQUOTE:
	case HXQUOTE_SQLBQUOTE:
		return HX_qsize_bsr(s, HX_quote_rules[type].chars, 1);
	case HXQUOTE_HTML:
		return HX_qsize_html(s);
	case HXQUOTE_LDAPFLT:
	case HXQUOTE_LDAPRDN:
		return HX_qsize_bsr(s, HX_quote_rules[type].chars, 2);
	case HXQUOTE_BASE64:
	case HXQUOTE_BASE64URL:
	case HXQUOTE_BASE64IMAP:
		return (strlen(s) + 2) / 3 * 4;
	case HXQUOTE_URIENC:
		return HX_qsize_bsa(s, HX_quote_rules[type].chars, 2);
	default:
		return strlen(s);
	}
}

EXPORT_SYMBOL char *HX_strquote(const char *src, unsigned int type,
    char **free_me)
{
	const struct HX_quote_rule *rule = nullptr;
	bool do_quote;
	char *tmp;

	if (type >= _HXQUOTE_MAX) {
		errno = EINVAL;
		return NULL;
	}
	/* If quote_chars is NULL, it is clear all chars are to be encoded. */
	if (type >= ARRAY_SIZE(HX_quote_rules)) {
		do_quote = true;
	} else {
		rule = &HX_quote_rules[type];
		if (rule->selector == HXQUOTE_ALWAYS)
			do_quote = true;
		else if (rule->selector == HXQUOTE_REJECT)
			do_quote = strpbrk(src, rule->chars) != NULL;
		else if (rule->selector == HXQUOTE_ACCEPT)
			do_quote = HX_strchr2(src, rule->chars) != NULL;
		else
			do_quote = false;
	}
	/*
	 * free_me == NULL implies that we always allocate, even if
	 * there is nothing to quote.
	 */
	if (free_me != NULL) {
		free(*free_me);
		*free_me = NULL;
		if (!do_quote)
			return const_cast1(char *, src);
	} else {
		if (!do_quote)
			return HX_strdup(src);
		free_me = &tmp;
	}

	*free_me = malloc(HX_quoted_size(src, type) + 1);
	if (*free_me == NULL)
		return NULL;

	switch (type) {
	case HXQUOTE_SQUOTE:
	case HXQUOTE_DQUOTE:
		return HX_quote_backslash(*free_me, src, rule->chars);
	case HXQUOTE_HTML:
		return HX_quote_html(*free_me, src);
	case HXQUOTE_LDAPFLT:
	case HXQUOTE_LDAPRDN:
		return HX_quote_ldap(*free_me, src, rule->chars);
	case HXQUOTE_BASE64:
		return HX_quote_base64(*free_me, src, '+', '/');
	case HXQUOTE_BASE64URL:
		return HX_quote_base64(*free_me, src, '-', '_');
	case HXQUOTE_BASE64IMAP:
		return HX_quote_base64(*free_me, src, '+', ',');
	case HXQUOTE_URIENC:
		return HX_quote_urlenc(*free_me, src);
	case HXQUOTE_SQLSQUOTE:
	case HXQUOTE_SQLBQUOTE:
		return HX_quote_sqlbackslash(*free_me, src, rule->chars);
	}
	return NULL;
}

EXPORT_SYMBOL char *HX_strupper(char *orig)
{
	char *expr;
	for (expr = orig; *expr != '\0'; ++expr)
		*expr = HX_toupper(*expr);
	return orig;
}

EXPORT_SYMBOL char *HX_unit_size(char *buf, size_t bufsize,
    unsigned long long size, unsigned int divisor, unsigned int cutoff)
{
	static const char unit_names[] = "\0kMGTPEZYRQ";
	unsigned int unit_idx = 0;
	if (divisor == 0)
		divisor = 1000;
	if (cutoff == 0) {
		cutoff = 10000;
		if (cutoff < divisor)
			cutoff = divisor;
	}
	while (unit_idx < ARRAY_SIZE(unit_names) - 1 && size >= cutoff) {
		++unit_idx;
		size /= divisor;
	}
	snprintf(buf, bufsize, "%llu%.1s", size, &unit_names[unit_idx]);
	return buf;
}

static inline unsigned long long p_90(unsigned long long x)
{
	/* Perform x*9/10, but without the risk of overflow. */
	return x - x / 10 - !!(x % 10);
}

EXPORT_SYMBOL char *HX_unit_size_cu(char *buf, size_t bufsize,
    unsigned long long orig_size, unsigned int divisor)
{
	/* No floating point. Take that, coreutils! */
	static const char unit_names[] = "\0kMGTPEZYRQ";
	unsigned int unit_idx = 0, last_rem = 0;
	unsigned long long size = orig_size, gpow = 1, grand_rem;
	if (divisor == 0)
		divisor = 1000;

	while (unit_idx < ARRAY_SIZE(unit_names) - 1 && size >= divisor) {
		++unit_idx;
		last_rem = size % divisor;
		size /= divisor;
		gpow *= divisor;
	}
	if (unit_idx == 0) {
		snprintf(buf, bufsize, "%llu%.1s", size, &unit_names[unit_idx]);
		return buf;
	}
	grand_rem = orig_size - size * gpow;
	if (grand_rem != 0) {
		if (grand_rem > p_90(gpow)) {
			++size;
			last_rem = 0;
		} else {
			last_rem *= 10;
			last_rem /= divisor;
			++last_rem;
			if (last_rem == 10 || (size >= 10 && last_rem > 0)) {
				++size;
				last_rem = 0;
			}
		}
		if (unit_idx < ARRAY_SIZE(unit_names) - 1 && size == divisor) {
			/* ++size from above may brought size to @divisor again */
			++unit_idx;
			size /= divisor;
		}
	}
	if (size >= 10 && last_rem == 0)
		snprintf(buf, bufsize, "%llu%.1s", size, &unit_names[unit_idx]);
	else
		snprintf(buf, bufsize, "%llu.%01u%.1s", size, last_rem, &unit_names[unit_idx]);
	return buf;
}

static unsigned int suffix_power(char u)
{
	switch (HX_toupper(u)) {
	case 'K': return 1;
	case 'M': return 2;
	case 'G': return 3;
	case 'T': return 4;
	case 'P': return 5;
	case 'E': return 6;
	case 'Z': return 7;
	case 'Y': return 8;
	case 'R': return 9;
	case 'Q': return 10;
	default: return 0;
	}
}

EXPORT_SYMBOL double HX_strtod_unit(const char *s, char **out_end, unsigned int exponent)
{
	char *end;
	double q;

	while (HX_isspace(*s))
		++s;
	q = strtod(s, &end);
	if (exponent == 0)
		exponent = 1000;
	if (end == s) {
		if (out_end != nullptr)
			*out_end = end;
		errno = 0;
		return q;
	}
	while (HX_isspace(*end))
		++end;
	unsigned int pwr = suffix_power(*end);
	if (pwr == 0) {
		if (out_end != nullptr)
			*out_end = const_cast(char *, end);
		errno = 0;
		return q;
	}
	if (out_end != nullptr)
		*out_end = const_cast(char *, end + 1);
	errno = 0;
	return q * pow(exponent, pwr);
}

EXPORT_SYMBOL unsigned long long HX_strtoull_unit(const char *s,
    char **out_end, unsigned int exponent)
{
	char *end;
	unsigned long long ipart;
	unsigned int pwr = 0;
	bool neg = false;

	while (HX_isspace(*s))
		++s;
	if (*s == '-') {
		/*
		 * "-5k": While (-5ULL) * 1000 is the same as (-5000ULL) under
		 * modulo arithmetic, the expression `ipart >= ULLONG_MAX /
		 * exponent` depends on seeing the true value (5 rather than
		 * (-5ULL).)
		 */
		neg = true;
		++s;
	}
	errno = 0;
	ipart = strtoull(s, &end, 10);
	if (ipart == ULLONG_MAX && errno == ERANGE)
		return ipart;
	if (*end == '.') {
		double q = HX_strtod_unit(s, out_end, exponent);
		bool lo_ok = q >= nextafter(-static_cast(double, ULLONG_MAX), 0);
		bool hi_ok = q <= nextafter(static_cast(double, ULLONG_MAX), 0);
		if (!hi_ok || !lo_ok) {
			errno = ERANGE;
			return ULLONG_MAX;
		}
		/*
		 * https://eel.is/c++draft/conv.fpint: values unrepresentable
		 * in the target type (such as forcing -5.2f into a uint) is
		 * UB. Thus check for range and apply the negation after the
		 * conversion to ULL.
		 */
		if (q >= static_cast(double, ULLONG_MAX)) {
			errno = ERANGE;
			return ULLONG_MAX;
		}
		unsigned long long r = q;
		errno = 0;
		return neg ? -r : r;
	}
	if (exponent == 0)
		exponent = 1000;
	while (HX_isspace(*end))
		++end;
	pwr = suffix_power(*end);
	if (pwr == 0) {
		if (out_end != nullptr)
			*out_end = end;
		errno = 0;
		return neg ? -ipart: ipart;
	}
	if (out_end != nullptr)
		*out_end = const_cast(char *, end + 1);
	while (pwr-- > 0) {
		if (ipart >= ULLONG_MAX / exponent) {
			errno = ERANGE;
			return ULLONG_MAX;
		}
		ipart *= exponent;
	}
	errno = 0;
	return neg ? -ipart : ipart;
}

/* Numbers also used by systemd — the focus is on longterm averages */
#define SECONDS_PER_YEAR 31557600 /* 365.25 days */
#define SECONDS_PER_MONTH 2629800 /* 1/12th of that year = 30.4375 days */
#define NSEC_PER_SECOND 1000000000ULL

static const struct {
	const char name[8];
	unsigned int len;
	uint32_t s_mult;
	uint64_t ns_mult;
} time_multiplier[] = {
	{"seconds", 7, 1, 1 * NSEC_PER_SECOND},
	{"second",  6, 1, 1 * NSEC_PER_SECOND},
	{"sec",     3, 1, 1 * NSEC_PER_SECOND},
	{"s",       1, 1, 1 * NSEC_PER_SECOND},
	{"minutes", 7, 60, 60 * NSEC_PER_SECOND},
	{"minute",  6, 60, 60 * NSEC_PER_SECOND},
	{"min",     3, 60, 60 * NSEC_PER_SECOND},
	{"hours",   5, 3600, 3600 * NSEC_PER_SECOND},
	{"hour",    4, 3600, 3600 * NSEC_PER_SECOND},
	{"h",       1, 3600, 3600 * NSEC_PER_SECOND},
	{"days",    4, 86400, 86400 * NSEC_PER_SECOND},
	{"day",     3, 86400, 86400 * NSEC_PER_SECOND},
	{"d",       1, 86400, 86400 * NSEC_PER_SECOND},
	{"weeks",   5, 604800, 604800 * NSEC_PER_SECOND},
	{"week",    4, 604800, 604800 * NSEC_PER_SECOND},
	{"months",  6, SECONDS_PER_MONTH, SECONDS_PER_MONTH * NSEC_PER_SECOND},
	{"month",   5, SECONDS_PER_MONTH, SECONDS_PER_MONTH * NSEC_PER_SECOND},
	{"years",   5, SECONDS_PER_YEAR, SECONDS_PER_YEAR * NSEC_PER_SECOND},
	{"year",    4, SECONDS_PER_YEAR, SECONDS_PER_YEAR * NSEC_PER_SECOND},
	{"y",       1, SECONDS_PER_YEAR, SECONDS_PER_YEAR * NSEC_PER_SECOND},
	{"msec",    4, 0, 1000000},
	{"ms",      2, 0, 1000000},
	{"µsec",    5, 0, 1000},
	{"µs",      3, 0, 1000},
	{"nsec",    4, 0, 1},
	{"ns",      2, 0, 1},
};

static unsigned long long HX_strtoull_time(const char *s, char **out_end, bool nsec)
{
	unsigned long long quant = 0;

	while (*s != '\0') {
		while (HX_isspace(*s))
			++s;
		const char *numbegin = s;
		if (*s == '-')
			break;
		char *end = nullptr;
		unsigned long long num = strtoull(s, &end, 10);
		if (num == ULLONG_MAX && errno == ERANGE)
			return num;
		double frac = 0;
		bool have_frac = *end == '.';
		if (have_frac)
			frac = strtod(s, &end);
		if (end == s)
			break;
		s = end;
		while (HX_isspace(*s))
			++s;
		unsigned int i;
		for (i = 0; i < ARRAY_SIZE(time_multiplier); ++i)
			if (strncmp(s, time_multiplier[i].name,
			    time_multiplier[i].len) == 0 &&
			    !HX_isalpha(s[time_multiplier[i].len]))
				break;
		if (i == ARRAY_SIZE(time_multiplier)) {
			if ((!have_frac && num == 0) || (have_frac && frac == 0))
				/* 0 is the same no matter what unit, take it */
				continue;
			s = numbegin;
			break;
		}
		unsigned long long mult = nsec ? time_multiplier[i].ns_mult : time_multiplier[i].s_mult;
		if (have_frac) {
			quant += frac * mult;
		} else {
			if (mult > 0 && num >= ULLONG_MAX / mult) {
				if (out_end != nullptr)
					*out_end = const_cast(char *, numbegin);
				errno = ERANGE;
				return ULLONG_MAX;
			}
			quant += num * mult;
		}
		s += time_multiplier[i].len;
	}
	if (out_end != nullptr)
		*out_end = const_cast(char *, s);
	return quant;
}

EXPORT_SYMBOL unsigned long long HX_strtoull_sec(const char *s, char **out_end)
{
	return HX_strtoull_time(s, out_end, false);
}

EXPORT_SYMBOL unsigned long long HX_strtoull_nsec(const char *s, char **out_end)
{
	return HX_strtoull_time(s, out_end, true);
}

EXPORT_SYMBOL char *HX_unit_seconds(char *out, size_t outsize,
    unsigned long long secs, unsigned int flags)
{
	unsigned long years = 0, months = 0, weeks = 0, days, hours, mins;
	char buf[HXSIZEOF_Z64+4];
	if (flags & HXUNIT_YEARS) {
		years = secs / SECONDS_PER_YEAR;
		secs %= SECONDS_PER_YEAR;
	}
	if (flags & HXUNIT_MONTHS) {
		months = secs / SECONDS_PER_MONTH;
		secs %= SECONDS_PER_MONTH;
	}
	if (flags & HXUNIT_WEEKS) {
		weeks = secs / 604800;
		secs %= 604800;
	}
	days = secs / 86400;
	secs %= 86400;
	hours = secs / 3600;
	secs %= 3600;
	mins = secs / 60;
	secs %= 60;
	*out = '\0';
	if (years > 0) {
		snprintf(buf, ARRAY_SIZE(buf), "%luy", years);
		HX_strlcat(out, buf, outsize);
	}
	if (months == 1) {
		HX_strlcat(out, "1month", outsize);
	} else if (months > 0) {
		snprintf(buf, ARRAY_SIZE(buf), "%lumonths", months);
		HX_strlcat(out, buf, outsize);
	}
	if (weeks == 1) {
		HX_strlcat(out, "1week", outsize);
	} else if (weeks > 0) {
		snprintf(buf, ARRAY_SIZE(buf), "%luweeks", weeks);
		HX_strlcat(out, buf, outsize);
	}
	if (days > 0) {
		snprintf(buf, ARRAY_SIZE(buf), "%lud", days);
		HX_strlcat(out, buf, outsize);
	}
	if (hours > 0) {
		snprintf(buf, ARRAY_SIZE(buf), "%luh", hours);
		HX_strlcat(out, buf, outsize);
	}
	if (mins > 0) {
		snprintf(buf, ARRAY_SIZE(buf), "%lumin", mins);
		HX_strlcat(out, buf, outsize);
	}
	if (secs > 0 ||
	    (years == 0 && months == 0 && weeks == 0 &&
	    days == 0 && hours == 0 && mins == 0)) {
		snprintf(buf, ARRAY_SIZE(buf), "%llus", secs);
		HX_strlcat(out, buf, outsize);
	}
	return out;
}