xref: /lighttpd1.4/src/buffer.c (revision ee9352b1)
1 #include "first.h"
2 
3 #include "buffer.h"
4 
5 #include <stdlib.h>
6 #include <string.h>
7 #include "sys-time.h"   /* strftime() */
8 
9 static const char hex_chars_lc[] = "0123456789abcdef";
10 static const char hex_chars_uc[] = "0123456789ABCDEF";
11 
12 /**
13  * init the buffer
14  *
15  */
16 
17 __attribute_noinline__
18 buffer* buffer_init(void) {
19 	buffer * const b = calloc(1, sizeof(*b));
20 	force_assert(b);
21 	return b;
22 }
23 
24 buffer *buffer_init_buffer(const buffer *src) {
25 	buffer * const b = buffer_init();
26 	buffer_copy_string_len(b, BUF_PTR_LEN(src));
27 	return b;
28 }
29 
30 buffer *buffer_init_string(const char *str) {
31 	buffer * const b = buffer_init();
32 	buffer_copy_string(b, str);
33 	return b;
34 }
35 
36 void buffer_free(buffer *b) {
37 	if (NULL == b) return;
38 
39 	free(b->ptr);
40 	free(b);
41 }
42 
43 void buffer_free_ptr(buffer *b) {
44 	free(b->ptr);
45 	b->ptr = NULL;
46 	b->used = 0;
47 	b->size = 0;
48 }
49 
50 void buffer_move(buffer * restrict b, buffer * restrict src) {
51 	buffer tmp;
52 	buffer_clear(b);
53 	tmp = *src; *src = *b; *b = tmp;
54 }
55 
56 /* make sure buffer is at least "size" big + 1 for '\0'. keep old data */
57 __attribute_cold__
58 __attribute_noinline__
59 __attribute_nonnull__
60 __attribute_returns_nonnull__
61 static char* buffer_realloc(buffer * const restrict b, const size_t len) {
62     #define BUFFER_PIECE_SIZE 64uL  /*(must be power-of-2)*/
63     size_t sz = (len + 1 + BUFFER_PIECE_SIZE-1) & ~(BUFFER_PIECE_SIZE-1);
64     force_assert(sz > len);
65     if ((sz & (sz-1)) && sz < INT_MAX) {/* not power-2; huge val not expected */
66         /*(optimizer should recognize this and use ffs or clz or equivalent)*/
67         const size_t psz = sz;
68         for (sz = 256; sz < psz; sz <<= 1) ;
69     }
70     sz |= 1; /*(extra +1 for '\0' when needed buffer size is exact power-2)*/
71 
72     b->size = sz;
73     b->ptr = realloc(b->ptr, sz);
74 
75     force_assert(NULL != b->ptr);
76     return b->ptr;
77 }
78 
79 __attribute_cold__
80 __attribute_noinline__
81 __attribute_nonnull__
82 __attribute_returns_nonnull__
83 static char* buffer_alloc_replace(buffer * const restrict b, const size_t size) {
84     /*(discard old data so realloc() does not copy)*/
85     if (NULL != b->ptr) {
86         free(b->ptr);
87         b->ptr = NULL;
88     }
89     /*(note: if size larger than one lshift, use size instead of power-2)*/
90     const size_t bsize2x = (b->size & ~1uL) << 1;
91     return buffer_realloc(b, bsize2x > size ? bsize2x-1 : size);
92 }
93 
94 char* buffer_string_prepare_copy(buffer * const b, const size_t size) {
95     b->used = 0;
96     return (size < b->size)
97       ? b->ptr
98       : buffer_alloc_replace(b, size);
99 }
100 
101 __attribute_cold__
102 __attribute_noinline__
103 __attribute_nonnull__
104 __attribute_returns_nonnull__
105 static char* buffer_string_prepare_append_resize(buffer * const restrict b, const size_t size) {
106     if (b->used < 2) {  /* buffer_is_blank(b) */
107         char * const s = buffer_string_prepare_copy(b, size);
108         *s = '\0'; /*(for case (1 == b->used))*/
109         return s;
110     }
111 
112     /* not empty, b->used already includes a terminating 0 */
113     /*(note: if size larger than one lshift, use size instead of power-2)*/
114     const size_t bsize2x = (b->size & ~1uL) << 1;
115     const size_t req_size = (bsize2x - b->used > size)
116       ? bsize2x-1
117       : b->used + size;
118 
119     /* check for overflow: unsigned overflow is defined to wrap around */
120     force_assert(req_size >= b->used);
121 
122     return buffer_realloc(b, req_size) + b->used - 1;
123 }
124 
125 char* buffer_string_prepare_append(buffer * const b, const size_t size) {
126     const uint32_t len = b->used ? b->used-1 : 0;
127     return (b->size - len >= size + 1)
128       ? b->ptr + len
129       : buffer_string_prepare_append_resize(b, size);
130 }
131 
132 /*(prefer smaller code than inlining buffer_extend in many places in buffer.c)*/
133 __attribute_noinline__
134 char*
135 buffer_extend (buffer * const b, const size_t x)
136 {
137     /* extend buffer to append x (reallocate by power-2 (or larger), if needed)
138      * (combine buffer_string_prepare_append() and buffer_commit())
139      * (future: might make buffer.h static inline func for HTTP/1.1 performance)
140      * pre-sets '\0' byte and b->used (unlike buffer_string_prepare_append())*/
141   #if 0
142     char * const s = buffer_string_prepare_append(b, x);
143     b->used += x + (0 == b->used);
144   #else
145     const uint32_t len = b->used ? b->used-1 : 0;
146     char * const s = (b->size - len >= x + 1)
147       ? b->ptr + len
148       : buffer_string_prepare_append_resize(b, x);
149     b->used = len+x+1;
150   #endif
151     s[x] = '\0';
152     return s;
153 }
154 
155 void buffer_commit(buffer *b, size_t size)
156 {
157 	size_t sz = b->used;
158 	if (0 == sz) sz = 1;
159 
160 	if (size > 0) {
161 		/* check for overflow: unsigned overflow is defined to wrap around */
162 		sz += size;
163 		force_assert(sz > size);
164 	}
165 
166 	b->used = sz;
167 	b->ptr[sz - 1] = '\0';
168 }
169 
170 void buffer_copy_string(buffer * restrict b, const char * restrict s) {
171 	buffer_copy_string_len(b, s, NULL != s ? strlen(s) : 0);
172 }
173 
174 void buffer_copy_string_len(buffer * const restrict b, const char * const restrict s, const size_t len) {
175     b->used = len + 1;
176     char * const restrict d = (len < b->size)
177       ? b->ptr
178       : buffer_alloc_replace(b, len);
179     d[len] = '\0';
180     memcpy(d, s, len);
181 }
182 
183 void buffer_append_string(buffer * restrict b, const char * restrict s) {
184 	buffer_append_string_len(b, s, NULL != s ? strlen(s) : 0);
185 }
186 
187 /**
188  * append a string to the end of the buffer
189  *
190  * the resulting buffer is terminated with a '\0'
191  * s is treated as a un-terminated string (a \0 is handled a normal character)
192  *
193  * @param b a buffer
194  * @param s the string
195  * @param s_len size of the string (without the terminating \0)
196  */
197 
198 void buffer_append_string_len(buffer * const restrict b, const char * const restrict s, const size_t len) {
199     memcpy(buffer_extend(b, len), s, len);
200 }
201 
202 void buffer_append_str2(buffer * const restrict b, const char * const s1, const size_t len1, const char * const s2, const size_t len2) {
203     char * const restrict s = buffer_extend(b, len1+len2);
204   #ifdef HAVE_MEMPCPY
205     mempcpy(mempcpy(s, s1, len1), s2, len2);
206   #else
207     memcpy(s,      s1, len1);
208     memcpy(s+len1, s2, len2);
209   #endif
210 }
211 
212 void buffer_append_str3(buffer * const restrict b, const char * const s1, const size_t len1, const char * const s2, const size_t len2, const char * const s3, const size_t len3) {
213     char * restrict s = buffer_extend(b, len1+len2+len3);
214   #ifdef HAVE_MEMPCPY
215     mempcpy(mempcpy(mempcpy(s, s1, len1), s2, len2), s3, len3);
216   #else
217     memcpy(s,         s1, len1);
218     memcpy((s+=len1), s2, len2);
219     memcpy((s+=len2), s3, len3);
220   #endif
221 }
222 
223 void buffer_append_iovec(buffer * const restrict b, const struct const_iovec * const iov, const size_t n) {
224     size_t len = 0;
225     for (size_t i = 0; i < n; ++i)
226         len += iov[i].iov_len;
227     char *s = buffer_extend(b, len);
228     for (size_t i = 0; i < n; ++i) {
229         if (0 == iov[i].iov_len) continue;
230       #ifdef HAVE_MEMPCPY
231         s = mempcpy(s, iov[i].iov_base, iov[i].iov_len);
232       #else
233         memcpy(s, iov[i].iov_base, iov[i].iov_len);
234         s += iov[i].iov_len;
235       #endif
236     }
237 }
238 
239 void buffer_append_path_len(buffer * restrict b, const char * restrict a, size_t alen) {
240     char * restrict s = buffer_string_prepare_append(b, alen+1);
241     const int aslash = (alen && a[0] == '/');
242     if (b->used > 1 && s[-1] == '/') {
243         if (aslash) {
244             ++a;
245             --alen;
246         }
247     }
248     else {
249         if (0 == b->used) b->used = 1;
250         if (!aslash) {
251             *s++ = '/';
252             ++b->used;
253         }
254     }
255     b->used += alen;
256     s[alen] = '\0';
257     memcpy(s, a, alen);
258 }
259 
260 void
261 buffer_copy_path_len2 (buffer * const restrict b, const char * const restrict s1, size_t len1, const char * const restrict s2, size_t len2)
262 {
263     /*(similar to buffer_copy_string_len(b, s1, len1) but combined allocation)*/
264     memcpy(buffer_string_prepare_copy(b, len1+len2+1), s1, len1);
265     b->used = len1 + 1;                    /*('\0' byte will be written below)*/
266 
267     buffer_append_path_len(b, s2, len2);/*(choice: not inlined, special-cased)*/
268 }
269 
270 void
271 buffer_copy_string_len_lc (buffer * const restrict b, const char * const restrict s, const size_t len)
272 {
273     char * const restrict d = buffer_string_prepare_copy(b, len);
274     b->used = len+1;
275     d[len] = '\0';
276     for (size_t i = 0; i < len; ++i)
277         d[i] = (!light_isupper(s[i])) ? s[i] : s[i] | 0x20;
278 }
279 
280 void buffer_append_uint_hex_lc(buffer *b, uintmax_t value) {
281 	char *buf;
282 	unsigned int shift = 0;
283 
284 	{
285 		uintmax_t copy = value;
286 		do {
287 			copy >>= 8;
288 			shift += 8; /* counting bits */
289 		} while (0 != copy);
290 	}
291 
292 	buf = buffer_extend(b, shift >> 2); /*nibbles (4 bits)*/
293 
294 	while (shift > 0) {
295 		shift -= 4;
296 		*(buf++) = hex_chars_lc[(value >> shift) & 0x0F];
297 	}
298 }
299 
300 __attribute_nonnull__
301 __attribute_returns_nonnull__
302 static char* utostr(char buf[LI_ITOSTRING_LENGTH], uintmax_t val) {
303 	char *cur = buf+LI_ITOSTRING_LENGTH;
304 	do {
305 		int mod = val % 10;
306 		val /= 10;
307 		/* prepend digit mod */
308 		*(--cur) = (char) ('0' + mod);
309 	} while (0 != val);
310 	return cur;
311 }
312 
313 __attribute_nonnull__
314 __attribute_returns_nonnull__
315 static char* itostr(char buf[LI_ITOSTRING_LENGTH], intmax_t val) {
316 	/* absolute value not defined for INTMAX_MIN, but can take absolute
317 	 * value of any negative number via twos complement cast to unsigned.
318 	 * negative sign is prepended after (now unsigned) value is converted
319 	 * to string */
320 	uintmax_t uval = val >= 0 ? (uintmax_t)val : ((uintmax_t)~val) + 1;
321 	char *cur = utostr(buf, uval);
322 	if (val < 0) *(--cur) = '-';
323 
324 	return cur;
325 }
326 
327 void buffer_append_int(buffer *b, intmax_t val) {
328 	char buf[LI_ITOSTRING_LENGTH];
329 	const char * const str = itostr(buf, val);
330 	buffer_append_string_len(b, str, buf+sizeof(buf) - str);
331 }
332 
333 void buffer_append_strftime(buffer * const restrict b, const char * const restrict format, const struct tm * const restrict tm) {
334     force_assert(NULL != format);
335     /*(localtime_r() or gmtime_r() producing tm should not have failed)*/
336     if (__builtin_expect( (NULL == tm), 0)) return;
337 
338     /*(expecting typical format strings to result in < 64 bytes needed;
339      * skipping buffer_string_space() calculation and providing fixed size)*/
340     size_t rv = strftime(buffer_string_prepare_append(b, 63), 64, format, tm);
341 
342     /* 0 (in some apis) signals the string may have been too small;
343      * but the format could also just have lead to an empty string */
344     if (__builtin_expect( (0 == rv), 0) || __builtin_expect( (rv > 63), 0)) {
345         /* unexpected; give it a second try with a larger string */
346         rv = strftime(buffer_string_prepare_append(b, 4095), 4096, format, tm);
347         if (__builtin_expect( (rv > 4095), 0))/*(input format was ridiculous)*/
348             return;
349     }
350 
351     /*buffer_commit(b, rv);*/
352     b->used += (uint32_t)rv + (0 == b->used);
353 }
354 
355 
356 size_t li_itostrn(char *buf, size_t buf_len, intmax_t val) {
357 	char p_buf[LI_ITOSTRING_LENGTH];
358 	char* const str = itostr(p_buf, val);
359 	size_t len = (size_t)(p_buf+sizeof(p_buf)-str);
360 	force_assert(len <= buf_len);
361 	memcpy(buf, str, len);
362 	return len;
363 }
364 
365 size_t li_utostrn(char *buf, size_t buf_len, uintmax_t val) {
366 	char p_buf[LI_ITOSTRING_LENGTH];
367 	char* const str = utostr(p_buf, val);
368 	size_t len = (size_t)(p_buf+sizeof(p_buf)-str);
369 	force_assert(len <= buf_len);
370 	memcpy(buf, str, len);
371 	return len;
372 }
373 
374 #define li_ntox_lc(n) ((n) <= 9 ? (n) + '0' : (n) + 'a' - 10)
375 
376 /* c (char) and n (nibble) MUST be unsigned integer types */
377 #define li_cton(c,n) \
378   (((n) = (c) - '0') <= 9 || (((n) = ((c)&0xdf) - 'A') <= 5 ? ((n) += 10) : 0))
379 
380 /* converts hex char (0-9, A-Z, a-z) to decimal.
381  * returns 0xFF on invalid input.
382  */
383 char hex2int(unsigned char hex) {
384 	unsigned char n;
385 	return li_cton(hex,n) ? (char)n : 0xFF;
386 }
387 
388 int li_hex2bin (unsigned char * const bin, const size_t binlen, const char * const hexstr, const size_t len)
389 {
390     /* validate and transform 32-byte MD5 hex string to 16-byte binary MD5,
391      * or 64-byte SHA-256 or SHA-512-256 hex string to 32-byte binary digest */
392     if (len > (binlen << 1)) return -1;
393     for (int i = 0, ilen = (int)len; i < ilen; i+=2) {
394         int hi = hexstr[i];
395         int lo = hexstr[i+1];
396         if ('0' <= hi && hi <= '9')                    hi -= '0';
397         else if ((uint32_t)(hi |= 0x20)-'a' <= 'f'-'a')hi += -'a' + 10;
398         else                                           return -1;
399         if ('0' <= lo && lo <= '9')                    lo -= '0';
400         else if ((uint32_t)(lo |= 0x20)-'a' <= 'f'-'a')lo += -'a' + 10;
401         else                                           return -1;
402         bin[(i >> 1)] = (unsigned char)((hi << 4) | lo);
403     }
404     return 0;
405 }
406 
407 
408 __attribute_noinline__
409 int buffer_eq_icase_ssn(const char * const a, const char * const b, const size_t len) {
410     for (size_t i = 0; i < len; ++i) {
411         unsigned int ca = ((unsigned char *)a)[i];
412         unsigned int cb = ((unsigned char *)b)[i];
413         if (ca != cb) {
414             ca |= 0x20;
415             cb |= 0x20;
416             if (ca != cb) return 0;
417             if (!light_islower(ca)) return 0;
418             if (!light_islower(cb)) return 0;
419         }
420     }
421     return 1;
422 }
423 
424 int buffer_eq_icase_ss(const char * const a, const size_t alen, const char * const b, const size_t blen) {
425     /* 1 = equal; 0 = not equal */ /* short string sizes expected (< INT_MAX) */
426     return (alen == blen) ? buffer_eq_icase_ssn(a, b, blen) : 0;
427 }
428 
429 int buffer_eq_icase_slen(const buffer * const b, const char * const s, const size_t slen) {
430     /* Note: b must be initialized, i.e. 0 != b->used; uninitialized is not eq*/
431     /* 1 = equal; 0 = not equal */ /* short string sizes expected (< INT_MAX) */
432     return (b->used == slen + 1) ? buffer_eq_icase_ssn(b->ptr, s, slen) : 0;
433 }
434 
435 int buffer_eq_slen(const buffer * const b, const char * const s, const size_t slen) {
436     /* Note: b must be initialized, i.e. 0 != b->used; uninitialized is not eq*/
437     /* 1 = equal; 0 = not equal */ /* short string sizes expected (< INT_MAX) */
438     return (b->used == slen + 1 && 0 == memcmp(b->ptr, s, slen));
439 }
440 
441 
442 /**
443  * check if two buffer contain the same data
444  */
445 
446 int buffer_is_equal(const buffer *a, const buffer *b) {
447 	/* 1 = equal; 0 = not equal */
448 	return (a->used == b->used && 0 == memcmp(a->ptr, b->ptr, a->used));
449 }
450 
451 
452 void li_tohex_lc(char * const restrict buf, size_t buf_len, const char * const restrict s, size_t s_len) {
453 	force_assert(2 * s_len > s_len);
454 	force_assert(2 * s_len < buf_len);
455 
456 	for (size_t i = 0; i < s_len; ++i) {
457 		buf[2*i]   = hex_chars_lc[(s[i] >> 4) & 0x0F];
458 		buf[2*i+1] = hex_chars_lc[s[i] & 0x0F];
459 	}
460 	buf[2*s_len] = '\0';
461 }
462 
463 void li_tohex_uc(char * const restrict buf, size_t buf_len, const char * const restrict s, size_t s_len) {
464 	force_assert(2 * s_len > s_len);
465 	force_assert(2 * s_len < buf_len);
466 
467 	for (size_t i = 0; i < s_len; ++i) {
468 		buf[2*i]   = hex_chars_uc[(s[i] >> 4) & 0x0F];
469 		buf[2*i+1] = hex_chars_uc[s[i] & 0x0F];
470 	}
471 	buf[2*s_len] = '\0';
472 }
473 
474 
475 void buffer_substr_replace (buffer * const restrict b, const size_t offset,
476                             const size_t len, const buffer * const restrict replace)
477 {
478     const size_t blen = buffer_clen(b);
479     const size_t rlen = buffer_clen(replace);
480 
481     if (rlen > len) {
482         buffer_extend(b, blen-len+rlen);
483         memmove(b->ptr+offset+rlen, b->ptr+offset+len, blen-offset-len);
484     }
485 
486     memcpy(b->ptr+offset, replace->ptr, rlen);
487 
488     if (rlen < len) {
489         memmove(b->ptr+offset+rlen, b->ptr+offset+len, blen-offset-len);
490         buffer_truncate(b, blen-len+rlen);
491     }
492 }
493 
494 
495 void buffer_append_string_encoded_hex_lc(buffer * const restrict b, const char * const restrict s, size_t len) {
496     unsigned char * const p = (unsigned char *)buffer_extend(b, len*2);
497     for (size_t i = 0; i < len; ++i) {
498         p[(i<<1)]   = hex_chars_lc[(s[i] >> 4) & 0x0F];
499         p[(i<<1)+1] = hex_chars_lc[(s[i])      & 0x0F];
500     }
501 }
502 
503 void buffer_append_string_encoded_hex_uc(buffer * const restrict b, const char * const restrict s, size_t len) {
504     unsigned char * const p = (unsigned char *)buffer_extend(b, len*2);
505     for (size_t i = 0; i < len; ++i) {
506         p[(i<<1)]   = hex_chars_uc[(s[i] >> 4) & 0x0F];
507         p[(i<<1)+1] = hex_chars_uc[(s[i])      & 0x0F];
508     }
509 }
510 
511 
512 /* everything except: ! ( ) * - . 0-9 A-Z _ a-z */
513 static const char encoded_chars_rel_uri_part[] = {
514 	/*
515 	0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
516 	*/
517 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  00 -  0F control chars */
518 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  10 -  1F */
519 	1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1,  /*  20 -  2F space " # $ % & ' + , / */
520 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,  /*  30 -  3F : ; < = > ? */
521 	1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  40 -  4F @ */
522 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,  /*  50 -  5F [ \ ] ^ */
523 	1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  60 -  6F ` */
524 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1,  /*  70 -  7F { | } DEL */
525 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  80 -  8F */
526 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  90 -  9F */
527 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  A0 -  AF */
528 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  B0 -  BF */
529 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  C0 -  CF */
530 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  D0 -  DF */
531 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  E0 -  EF */
532 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  F0 -  FF */
533 };
534 
535 /* everything except: ! ( ) * - . / 0-9 A-Z _ a-z */
536 static const char encoded_chars_rel_uri[] = {
537 	/*
538 	0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
539 	*/
540 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  00 -  0F control chars */
541 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  10 -  1F */
542 	1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0,  /*  20 -  2F space " # $ % & ' + , */
543 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,  /*  30 -  3F : ; < = > ? */
544 	1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  40 -  4F @ */
545 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,  /*  50 -  5F [ \ ] ^ */
546 	1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  60 -  6F ` */
547 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1,  /*  70 -  7F { | } DEL */
548 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  80 -  8F */
549 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  90 -  9F */
550 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  A0 -  AF */
551 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  B0 -  BF */
552 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  C0 -  CF */
553 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  D0 -  DF */
554 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  E0 -  EF */
555 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  F0 -  FF */
556 };
557 
558 static const char encoded_chars_html[] = {
559 	/*
560 	0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
561 	*/
562 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  00 -  0F control chars */
563 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  10 -  1F */
564 	0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,  /*  20 -  2F " & ' */
565 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0,  /*  30 -  3F < > */
566 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  40 -  4F */
567 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  50 -  5F */
568 	1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  60 -  6F ` */
569 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,  /*  70 -  7F DEL */
570 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  80 -  8F */
571 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  90 -  9F */
572 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  A0 -  AF */
573 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  B0 -  BF */
574 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  C0 -  CF */
575 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  D0 -  DF */
576 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  E0 -  EF */
577 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  F0 -  FF */
578 };
579 
580 static const char encoded_chars_minimal_xml[] = {
581 	/*
582 	0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
583 	*/
584 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  00 -  0F control chars */
585 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /*  10 -  1F */
586 	0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,  /*  20 -  2F " & ' */
587 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0,  /*  30 -  3F < > */
588 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  40 -  4F */
589 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  50 -  5F */
590 	1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  60 -  6F ` */
591 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,  /*  70 -  7F DEL */
592 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  80 -  8F */
593 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  90 -  9F */
594 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  A0 -  AF */
595 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  B0 -  BF */
596 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  C0 -  CF */
597 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  D0 -  DF */
598 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  E0 -  EF */
599 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /*  F0 -  FF */
600 };
601 
602 
603 
604 void buffer_append_string_encoded(buffer * const restrict b, const char * const restrict s, size_t s_len, buffer_encoding_t encoding) {
605 	unsigned char *ds, *d;
606 	size_t d_len, ndx;
607 	const char *map = NULL;
608 
609 	if (0 == s_len) return;
610 
611 	force_assert(NULL != s);
612 
613 	switch(encoding) {
614 	case ENCODING_REL_URI:
615 		map = encoded_chars_rel_uri;
616 		break;
617 	case ENCODING_REL_URI_PART:
618 		map = encoded_chars_rel_uri_part;
619 		break;
620 	case ENCODING_HTML:
621 		map = encoded_chars_html;
622 		break;
623 	case ENCODING_MINIMAL_XML:
624 		map = encoded_chars_minimal_xml;
625 		break;
626 	}
627 
628 	force_assert(NULL != map);
629 
630 	/* count to-be-encoded-characters */
631 	for (ds = (unsigned char *)s, d_len = 0, ndx = 0; ndx < s_len; ds++, ndx++) {
632 		if (map[*ds & 0xFF]) {
633 			switch(encoding) {
634 			case ENCODING_REL_URI:
635 			case ENCODING_REL_URI_PART:
636 				d_len += 3;
637 				break;
638 			case ENCODING_HTML:
639 			case ENCODING_MINIMAL_XML:
640 				d_len += 6;
641 				break;
642 			}
643 		} else {
644 			d_len++;
645 		}
646 	}
647 
648 	d = (unsigned char*) buffer_extend(b, d_len);
649 
650 	if (d_len == s_len) { /*(short-circuit; nothing to encoded)*/
651 		memcpy(d, s, s_len);
652 		return;
653 	}
654 
655 	for (ds = (unsigned char *)s, d_len = 0, ndx = 0; ndx < s_len; ds++, ndx++) {
656 		if (map[*ds & 0xFF]) {
657 			switch(encoding) {
658 			case ENCODING_REL_URI:
659 			case ENCODING_REL_URI_PART:
660 				d[d_len++] = '%';
661 				d[d_len++] = hex_chars_uc[((*ds) >> 4) & 0x0F];
662 				d[d_len++] = hex_chars_uc[(*ds) & 0x0F];
663 				break;
664 			case ENCODING_HTML:
665 			case ENCODING_MINIMAL_XML:
666 				d[d_len++] = '&';
667 				d[d_len++] = '#';
668 				d[d_len++] = 'x';
669 				d[d_len++] = hex_chars_uc[((*ds) >> 4) & 0x0F];
670 				d[d_len++] = hex_chars_uc[(*ds) & 0x0F];
671 				d[d_len++] = ';';
672 				break;
673 			}
674 		} else {
675 			d[d_len++] = *ds;
676 		}
677 	}
678 }
679 
680 void buffer_append_string_c_escaped(buffer * const restrict b, const char * const restrict s, size_t s_len) {
681 	unsigned char *ds, *d;
682 	size_t d_len, ndx;
683 
684 	if (0 == s_len) return;
685 
686 	/* count to-be-encoded-characters */
687 	for (ds = (unsigned char *)s, d_len = 0, ndx = 0; ndx < s_len; ds++, ndx++) {
688 		if ((*ds < 0x20) /* control character */
689 				|| (*ds >= 0x7f)) { /* DEL + non-ASCII characters */
690 			switch (*ds) {
691 			case '\t':
692 			case '\r':
693 			case '\n':
694 				d_len += 2;
695 				break;
696 			default:
697 				d_len += 4; /* \xCC */
698 				break;
699 			}
700 		} else {
701 			d_len++;
702 		}
703 	}
704 
705 	d = (unsigned char*) buffer_extend(b, d_len);
706 
707 	if (d_len == s_len) { /*(short-circuit; nothing to encoded)*/
708 		memcpy(d, s, s_len);
709 		return;
710 	}
711 
712 	for (ds = (unsigned char *)s, d_len = 0, ndx = 0; ndx < s_len; ds++, ndx++) {
713 		if ((*ds < 0x20) /* control character */
714 				|| (*ds >= 0x7f)) { /* DEL + non-ASCII characters */
715 			d[d_len++] = '\\';
716 			switch (*ds) {
717 			case '\t':
718 				d[d_len++] = 't';
719 				break;
720 			case '\r':
721 				d[d_len++] = 'r';
722 				break;
723 			case '\n':
724 				d[d_len++] = 'n';
725 				break;
726 			default:
727 				d[d_len++] = 'x';
728 				d[d_len++] = hex_chars_lc[((*ds) >> 4) & 0x0F];
729 				d[d_len++] = hex_chars_lc[(*ds) & 0x0F];
730 				break;
731 			}
732 		} else {
733 			d[d_len++] = *ds;
734 		}
735 	}
736 }
737 
738 
739 /* decodes url-special-chars inplace.
740  * replaces non-printable characters with '_'
741  * (If this is used on a portion of query string, then query string should be
742  *  split on '&', and '+' replaced with ' ' before calling this routine)
743  */
744 
745 void buffer_urldecode_path(buffer * const b) {
746     const size_t len = buffer_clen(b);
747     char *src = len ? memchr(b->ptr, '%', len) : NULL;
748     if (NULL == src) return;
749 
750     char *dst = src;
751     do {
752         /* *src == '%' */
753         unsigned char high = hex2int(*(src + 1));
754         unsigned char low = hex2int(*(src + 2));
755         if (0xFF != high && 0xFF != low) {
756             high = (high << 4) | low;   /* map ctrls to '_' */
757             *dst = (high >= 32 && high != 127) ? high : '_';
758             src += 2;
759         } /* else ignore this '%'; leave as-is and move on */
760 
761         while ((*++dst = *++src) != '%' && *src) ;
762     } while (*src);
763     b->used = (dst - b->ptr) + 1;
764 }
765 
766 int buffer_is_valid_UTF8(const buffer *b) {
767     /* https://www.w3.org/International/questions/qa-forms-utf-8 */
768     const unsigned char *c = (unsigned char *)b->ptr;
769     while (*c) {
770 
771         /*(note: includes ctrls)*/
772         if (                         c[0] <  0x80 ) { ++c;  continue; }
773 
774         if (         0xc2 <= c[0] && c[0] <= 0xdf
775             &&       0x80 <= c[1] && c[1] <= 0xbf ) { c+=2; continue; }
776 
777         if ( (   (   0xe0 == c[0]
778                   && 0xa0 <= c[1] && c[1] <= 0xbf)
779               || (   0xe1 <= c[0] && c[0] <= 0xef && c[0] != 0xed
780                   && 0x80 <= c[1] && c[1] <= 0xbf)
781               || (   0xed == c[0]
782                   && 0x80 <= c[1] && c[1] <= 0x9f)   )
783             &&       0x80 <= c[2] && c[2] <= 0xbf ) { c+=3; continue; }
784 
785         if ( (   (   0xf0 == c[0]
786                   && 0x90 <= c[1] && c[1] <= 0xbf)
787               || (   0xf1 <= c[0] && c[0] <= 0xf3
788                   && 0x80 <= c[1] && c[1] <= 0xbf)
789               || (   0xf4 == c[0]
790                   && 0x80 <= c[1] && c[1] <= 0x8f)   )
791             &&       0x80 <= c[2] && c[2] <= 0xbf
792             &&       0x80 <= c[3] && c[3] <= 0xbf ) { c+=4; continue; }
793 
794         return 0; /* invalid */
795     }
796     return 1; /* valid */
797 }
798 
799 /* - special case: empty string returns empty string
800  * - on windows or cygwin: replace \ with /
801  * - strip leading spaces
802  * - prepends "/" if not present already
803  * - resolve "/../", "//" and "/./" the usual way:
804  *   the first one removes a preceding component, the other two
805  *   get compressed to "/".
806  * - "/." and "/.." at the end are similar, but always leave a trailing
807  *   "/"
808  *
809  * /blah/..         gets  /
810  * /blah/../foo     gets  /foo
811  * /abc/./xyz       gets  /abc/xyz
812  * /abc//xyz        gets  /abc/xyz
813  */
814 
815 void buffer_path_simplify(buffer *b)
816 {
817     char *out = b->ptr;
818     char * const end = b->ptr + b->used - 1;
819 
820     if (__builtin_expect( (buffer_is_blank(b)), 0)) {
821         buffer_blank(b);
822         return;
823     }
824 
825   #if defined(__WIN32) || defined(__CYGWIN__)
826     /* cygwin is treating \ and / the same, so we have to that too */
827     for (char *p = b->ptr; *p; p++) {
828         if (*p == '\\') *p = '/';
829     }
830   #endif
831 
832     *end = '/'; /*(end of path modified to avoid need to check '\0')*/
833 
834     char *walk = out;
835     if (__builtin_expect( (*walk == '/'), 1)) {
836         /* scan to detect (potential) need for path simplification
837          * (repeated '/' or "/.") */
838         do {
839             if (*++walk == '.' || *walk == '/')
840                 break;
841             do { ++walk; } while (*walk != '/');
842         } while (walk != end);
843         if (__builtin_expect( (walk == end), 1)) {
844             /* common case: no repeated '/' or "/." */
845             *end = '\0'; /* overwrite extra '/' added to end of path */
846             return;
847         }
848         out = walk-1;
849     }
850     else {
851         if (walk[0] == '.' && walk[1] == '/')
852             *out = *++walk;
853         else if (walk[0] == '.' && walk[1] == '.' && walk[2] == '/')
854             *out = *(walk += 2);
855         else {
856             while (*++walk != '/') ;
857             out = walk;
858         }
859         ++walk;
860     }
861 
862     while (walk <= end) {
863         /* previous char is '/' at this point (or start of string w/o '/') */
864         if (__builtin_expect( (walk[0] == '/'), 0)) {
865             /* skip repeated '/' (e.g. "///" -> "/") */
866             if (++walk < end)
867                 continue;
868             else {
869                 ++out;
870                 break;
871             }
872         }
873         else if (__builtin_expect( (walk[0] == '.'), 0)) {
874             /* handle "./" and "../" */
875             if (walk[1] == '.' && walk[2] == '/') {
876                 /* handle "../" */
877                 while (out > b->ptr && *--out != '/') ;
878                 *out = '/'; /*(in case path had not started with '/')*/
879                 if ((walk += 3) >= end) {
880                     ++out;
881                     break;
882                 }
883                 else
884                 continue;
885             }
886             else if (walk[1] == '/') {
887                 /* handle "./" */
888                 if ((walk += 2) >= end) {
889                     ++out;
890                     break;
891                 }
892                 continue;
893             }
894             else {
895                 /* accept "." if not part of "../" or "./" */
896                 *++out = '.';
897                 ++walk;
898             }
899         }
900 
901         while ((*++out = *walk++) != '/') ;
902     }
903     *out = *end = '\0'; /* overwrite extra '/' added to end of path */
904     b->used = (out - b->ptr) + 1;
905     /*buffer_truncate(b, out - b->ptr);*/
906 }
907 
908 void buffer_to_lower(buffer * const b) {
909     unsigned char * const restrict s = (unsigned char *)b->ptr;
910     for (uint32_t i = 0; i < b->used; ++i) {
911         if (light_isupper(s[i])) s[i] |= 0x20;
912     }
913 }
914 
915 
916 void buffer_to_upper(buffer * const b) {
917     unsigned char * const restrict s = (unsigned char *)b->ptr;
918     for (uint32_t i = 0; i < b->used; ++i) {
919         if (light_islower(s[i])) s[i] &= 0xdf;
920     }
921 }
922