kore

An easy to use, scalable and secure web application framework for writing web APIs in C.
Commits | Files | Refs | README | LICENSE | git clone https://git.kore.io/kore.git

utils.c (14032B)



      1 /*
      2  * Copyright (c) 2013-2022 Joris Vink <joris@coders.se>
      3  *
      4  * Permission to use, copy, modify, and distribute this software for any
      5  * purpose with or without fee is hereby granted, provided that the above
      6  * copyright notice and this permission notice appear in all copies.
      7  *
      8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     15  */
     16 
     17 #include <sys/types.h>
     18 #include <sys/time.h>
     19 
     20 #include <ctype.h>
     21 #include <stdio.h>
     22 #include <stdarg.h>
     23 #include <string.h>
     24 #include <stdlib.h>
     25 #include <time.h>
     26 #include <limits.h>
     27 
     28 #include "kore.h"
     29 
     30 static struct {
     31 	char		*name;
     32 	int		value;
     33 } month_names[] = {
     34 	{ "Jan",	0 },
     35 	{ "Feb",	1 },
     36 	{ "Mar",	2 },
     37 	{ "Apr",	3 },
     38 	{ "May",	4 },
     39 	{ "Jun",	5 },
     40 	{ "Jul",	6 },
     41 	{ "Aug",	7 },
     42 	{ "Sep",	8 },
     43 	{ "Oct",	9 },
     44 	{ "Nov",	10 },
     45 	{ "Dec",	11 },
     46 	{ NULL,		0 },
     47 };
     48 
     49 static void	fatal_log(const char *, va_list);
     50 static int	utils_base64_encode(const void *, size_t, char **,
     51 		    const char *, int);
     52 static int	utils_base64_decode(const char *, u_int8_t **,
     53 		    size_t *, const char *, int);
     54 static int	utils_x509name_tobuf(void *, int, int, const char *,
     55 		    const void *, size_t, int);
     56 
     57 static char b64_table[] = 	\
     58     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
     59 
     60 static char b64url_table[] = 	\
     61     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
     62 
     63 /* b64_table and b64url_table are the same size. */
     64 #define B64_TABLE_LEN		(sizeof(b64_table))
     65 
     66 size_t
     67 kore_strlcpy(char *dst, const char *src, const size_t len)
     68 {
     69 	char		*d = dst;
     70 	const char	*s = src;
     71 	const char	*end = dst + len - 1;
     72 
     73 	if (len == 0)
     74 		fatal("kore_strlcpy: len == 0");
     75 
     76 	while ((*d = *s) != '\0') {
     77 		if (d == end) {
     78 			*d = '\0';
     79 			break;
     80 		}
     81 
     82 		d++;
     83 		s++;
     84 	}
     85 
     86 	while (*s != '\0')
     87 		s++;
     88 
     89 	return (s - src);
     90 }
     91 
     92 int
     93 kore_snprintf(char *str, size_t size, int *len, const char *fmt, ...)
     94 {
     95 	int		l;
     96 	va_list		args;
     97 
     98 	va_start(args, fmt);
     99 	l = vsnprintf(str, size, fmt, args);
    100 	va_end(args);
    101 
    102 	if (l == -1 || (size_t)l >= size)
    103 		return (KORE_RESULT_ERROR);
    104 
    105 	if (len != NULL)
    106 		*len = l;
    107 
    108 	return (KORE_RESULT_OK);
    109 }
    110 
    111 long long
    112 kore_strtonum(const char *str, int base, long long min, long long max, int *err)
    113 {
    114 	long long	l;
    115 	char		*ep;
    116 
    117 	if (min > max) {
    118 		*err = KORE_RESULT_ERROR;
    119 		return (0);
    120 	}
    121 
    122 	errno = 0;
    123 	l = strtoll(str, &ep, base);
    124 	if (errno != 0 || str == ep || *ep != '\0') {
    125 		*err = KORE_RESULT_ERROR;
    126 		return (0);
    127 	}
    128 
    129 	if (l < min) {
    130 		*err = KORE_RESULT_ERROR;
    131 		return (0);
    132 	}
    133 
    134 	if (l > max) {
    135 		*err = KORE_RESULT_ERROR;
    136 		return (0);
    137 	}
    138 
    139 	*err = KORE_RESULT_OK;
    140 	return (l);
    141 }
    142 
    143 u_int64_t
    144 kore_strtonum64(const char *str, int sign, int *err)
    145 {
    146 	u_int64_t	l;
    147 	long long	ll;
    148 	char		*ep;
    149 	int		check;
    150 
    151 	l = 0;
    152 	check = 1;
    153 
    154 	ll = strtoll(str, &ep, 10);
    155 	if ((errno == EINVAL || errno == ERANGE) &&
    156 	    (ll == LLONG_MIN || ll == LLONG_MAX)) {
    157 		if (sign) {
    158 			*err = KORE_RESULT_ERROR;
    159 			return (0);
    160 		}
    161 
    162 		check = 0;
    163 	}
    164 
    165 	if (!sign) {
    166 		l = strtoull(str, &ep, 10);
    167 		if ((errno == EINVAL || errno == ERANGE) && l == ULONG_MAX) {
    168 			*err = KORE_RESULT_ERROR;
    169 			return (0);
    170 		}
    171 
    172 		if (check && ll < 0) {
    173 			*err = KORE_RESULT_ERROR;
    174 			return (0);
    175 		}
    176 	}
    177 
    178 	if (str == ep || *ep != '\0') {
    179 		*err = KORE_RESULT_ERROR;
    180 		return (0);
    181 	}
    182 
    183 	*err = KORE_RESULT_OK;
    184 	return ((sign) ? (u_int64_t)ll : l);
    185 }
    186 
    187 double
    188 kore_strtodouble(const char *str, long double min, long double max, int *err)
    189 {
    190 	double		d;
    191 	char		*ep;
    192 
    193 	if (min > max) {
    194 		*err = KORE_RESULT_ERROR;
    195 		return (0);
    196 	}
    197 
    198 	errno = 0;
    199 	d = strtod(str, &ep);
    200 	if (errno == ERANGE || str == ep || *ep != '\0') {
    201 		*err = KORE_RESULT_ERROR;
    202 		return (0);
    203 	}
    204 
    205 	if (d < min) {
    206 		*err = KORE_RESULT_ERROR;
    207 		return (0);
    208 	}
    209 
    210 	if (d > max) {
    211 		*err = KORE_RESULT_ERROR;
    212 		return (0);
    213 	}
    214 
    215 	*err = KORE_RESULT_OK;
    216 	return (d);
    217 }
    218 
    219 int
    220 kore_split_string(char *input, const char *delim, char **out, size_t ele)
    221 {
    222 	int		count;
    223 	char		**ap;
    224 
    225 	if (ele == 0)
    226 		return (0);
    227 
    228 	count = 0;
    229 	for (ap = out; ap < &out[ele - 1] &&
    230 	    (*ap = strsep(&input, delim)) != NULL;) {
    231 		if (**ap != '\0') {
    232 			ap++;
    233 			count++;
    234 		}
    235 	}
    236 
    237 	*ap = NULL;
    238 	return (count);
    239 }
    240 
    241 void
    242 kore_strip_chars(char *in, const char strip, char **out)
    243 {
    244 	u_int32_t	len;
    245 	char		*s, *p;
    246 
    247 	len = strlen(in);
    248 	*out = kore_malloc(len + 1);
    249 	p = *out;
    250 
    251 	for (s = in; s < (in + len); s++) {
    252 		if (*s == strip)
    253 			continue;
    254 
    255 		*p++ = *s;
    256 	}
    257 
    258 	*p = '\0';
    259 }
    260 
    261 time_t
    262 kore_date_to_time(const char *http_date)
    263 {
    264 	time_t			t;
    265 	int			err, i;
    266 	struct tm		tm, *ltm;
    267 	char			*args[7], *tbuf[5], *sdup;
    268 
    269 	time(&t);
    270 	ltm = localtime(&t);
    271 	sdup = kore_strdup(http_date);
    272 
    273 	t = KORE_RESULT_ERROR;
    274 
    275 	if (kore_split_string(sdup, " ", args, 7) != 6) {
    276 		kore_log(LOG_WARNING, "misformed http-date: '%s'", http_date);
    277 		goto out;
    278 	}
    279 
    280 	memset(&tm, 0, sizeof(tm));
    281 
    282 	tm.tm_year = kore_strtonum(args[3], 10, 1900, 2068, &err) - 1900;
    283 	if (err == KORE_RESULT_ERROR) {
    284 		kore_log(LOG_WARNING, "misformed year in http-date: '%s'",
    285 		    http_date);
    286 		goto out;
    287 	}
    288 
    289 	for (i = 0; month_names[i].name != NULL; i++) {
    290 		if (!strcmp(month_names[i].name, args[2])) {
    291 			tm.tm_mon = month_names[i].value;
    292 			break;
    293 		}
    294 	}
    295 
    296 	if (month_names[i].name == NULL) {
    297 		kore_log(LOG_WARNING, "misformed month in http-date: '%s'",
    298 		    http_date);
    299 		goto out;
    300 	}
    301 
    302 	tm.tm_mday = kore_strtonum(args[1], 10, 1, 31, &err);
    303 	if (err == KORE_RESULT_ERROR) {
    304 		kore_log(LOG_WARNING, "misformed mday in http-date: '%s'",
    305 		    http_date);
    306 		goto out;
    307 	}
    308 
    309 	if (kore_split_string(args[4], ":", tbuf, 5) != 3) {
    310 		kore_log(LOG_WARNING, "misformed HH:MM:SS in http-date: '%s'",
    311 		    http_date);
    312 		goto out;
    313 	}
    314 
    315 	tm.tm_hour = kore_strtonum(tbuf[0], 10, 0, 23, &err);
    316 	if (err == KORE_RESULT_ERROR) {
    317 		kore_log(LOG_WARNING, "misformed hour in http-date: '%s'",
    318 		    http_date);
    319 		goto out;
    320 	}
    321 
    322 	tm.tm_min = kore_strtonum(tbuf[1], 10, 0, 59, &err);
    323 	if (err == KORE_RESULT_ERROR) {
    324 		kore_log(LOG_WARNING, "misformed minutes in http-date: '%s'",
    325 		    http_date);
    326 		goto out;
    327 	}
    328 
    329 	tm.tm_sec = kore_strtonum(tbuf[2], 10, 0, 60, &err);
    330 	if (err == KORE_RESULT_ERROR) {
    331 		kore_log(LOG_WARNING, "misformed seconds in http-date: '%s'",
    332 		    http_date);
    333 		goto out;
    334 	}
    335 
    336 	tm.tm_isdst = ltm->tm_isdst;
    337 	t = mktime(&tm) + ltm->tm_gmtoff;
    338 	if (t == -1) {
    339 		t = 0;
    340 		kore_log(LOG_WARNING, "mktime() on '%s' failed", http_date);
    341 	}
    342 
    343 out:
    344 	kore_free(sdup);
    345 	return (t);
    346 }
    347 
    348 char *
    349 kore_time_to_date(time_t now)
    350 {
    351 	struct tm		*tm;
    352 	static time_t		last = 0;
    353 	static char		tbuf[32];
    354 
    355 	if (now != last) {
    356 		last = now;
    357 
    358 		tm = gmtime(&now);
    359 		if (!strftime(tbuf, sizeof(tbuf), "%a, %d %b %Y %T GMT", tm))
    360 			return (NULL);
    361 	}
    362 
    363 	return (tbuf);
    364 }
    365 
    366 u_int64_t
    367 kore_time_ms(void)
    368 {
    369 	struct timespec		ts;
    370 
    371 	(void)clock_gettime(CLOCK_MONOTONIC, &ts);
    372 
    373 	return ((u_int64_t)(ts.tv_sec * 1000 + (ts.tv_nsec / 1000000)));
    374 }
    375 
    376 int
    377 kore_base64url_encode(const void *data, size_t len, char **out, int flags)
    378 {
    379 	return (utils_base64_encode(data, len, out, b64url_table, flags));
    380 }
    381 
    382 int
    383 kore_base64_encode(const void *data, size_t len, char **out)
    384 {
    385 	return (utils_base64_encode(data, len, out, b64_table, 0));
    386 }
    387 
    388 int
    389 kore_base64url_decode(const char *in, u_int8_t **out, size_t *olen, int flags)
    390 {
    391 	return (utils_base64_decode(in, out, olen, b64url_table, flags));
    392 }
    393 
    394 int
    395 kore_base64_decode(const char *in, u_int8_t **out, size_t *olen)
    396 {
    397 	return (utils_base64_decode(in, out, olen, b64_table, 0));
    398 }
    399 
    400 void *
    401 kore_mem_find(void *src, size_t slen, const void *needle, size_t len)
    402 {
    403 	size_t		pos;
    404 
    405 	for (pos = 0; pos < slen; pos++) {
    406 		if ( *((u_int8_t *)src + pos) != *(const u_int8_t *)needle)
    407 			continue;
    408 
    409 		if ((slen - pos) < len)
    410 			return (NULL);
    411 
    412 		if (!memcmp((u_int8_t *)src + pos, needle, len))
    413 			return ((u_int8_t *)src + pos);
    414 	}
    415 
    416 	return (NULL);
    417 }
    418 
    419 char *
    420 kore_text_trim(char *string, size_t len)
    421 {
    422 	char		*end;
    423 
    424 	if (len == 0)
    425 		return (string);
    426 
    427 	end = (string + len) - 1;
    428 	while (isspace(*(unsigned char *)string) && string < end)
    429 		string++;
    430 
    431 	while (isspace(*(unsigned char *)end) && end > string)
    432 		*(end)-- = '\0';
    433 
    434 	return (string);
    435 }
    436 
    437 char *
    438 kore_read_line(FILE *fp, char *in, size_t len)
    439 {
    440 	char	*p, *t;
    441 
    442 	if (fgets(in, len, fp) == NULL)
    443 		return (NULL);
    444 
    445 	p = in;
    446 	in[strcspn(in, "\n")] = '\0';
    447 
    448 	while (isspace(*(unsigned char *)p))
    449 		p++;
    450 
    451 	if (p[0] == '#' || p[0] == '\0') {
    452 		p[0] = '\0';
    453 		return (p);
    454 	}
    455 
    456 	for (t = p; *t != '\0'; t++) {
    457 		if (*t == '\t')
    458 			*t = ' ';
    459 	}
    460 
    461 	return (p);
    462 }
    463 
    464 const char *
    465 kore_worker_name(int id)
    466 {
    467 	static char	buf[64];
    468 
    469 	switch (id) {
    470 	case KORE_WORKER_KEYMGR:
    471 		(void)snprintf(buf, sizeof(buf), "[keymgr]");
    472 		break;
    473 	case KORE_WORKER_ACME:
    474 		(void)snprintf(buf, sizeof(buf), "[acme]");
    475 		break;
    476 	default:
    477 		(void)snprintf(buf, sizeof(buf), "[wrk %d]", id);
    478 		break;
    479 	}
    480 
    481 	return (buf);
    482 }
    483 
    484 int
    485 kore_x509_issuer_name(struct connection *c, char **out, int flags)
    486 {
    487 	struct kore_buf		buf;
    488 	KORE_X509_NAMES		*name;
    489 
    490 	if ((name = kore_tls_x509_issuer_name(c)) == NULL)
    491 		return (KORE_RESULT_ERROR);
    492 
    493 	kore_buf_init(&buf, 1024);
    494 
    495 	if (!kore_tls_x509name_foreach(name, flags, &buf,
    496 	    utils_x509name_tobuf)) {
    497 		kore_buf_cleanup(&buf);
    498 		return (KORE_RESULT_ERROR);
    499 	}
    500 
    501 	*out = kore_buf_stringify(&buf, NULL);
    502 
    503 	buf.offset = 0;
    504 	buf.data = NULL;
    505 
    506 	return (KORE_RESULT_OK);
    507 }
    508 
    509 int
    510 kore_x509_subject_name(struct connection *c, char **out, int flags)
    511 {
    512 	struct kore_buf		buf;
    513 	KORE_X509_NAMES		*name;
    514 
    515 	if ((name = kore_tls_x509_subject_name(c)) == NULL)
    516 		return (KORE_RESULT_ERROR);
    517 
    518 	kore_buf_init(&buf, 1024);
    519 
    520 	if (!kore_tls_x509name_foreach(name, flags, &buf,
    521 	    utils_x509name_tobuf)) {
    522 		kore_buf_cleanup(&buf);
    523 		return (KORE_RESULT_ERROR);
    524 	}
    525 
    526 	*out = kore_buf_stringify(&buf, NULL);
    527 
    528 	buf.offset = 0;
    529 	buf.data = NULL;
    530 
    531 	return (KORE_RESULT_OK);
    532 }
    533 
    534 void
    535 fatal(const char *fmt, ...)
    536 {
    537 	va_list		args;
    538 
    539 	va_start(args, fmt);
    540 	fatal_log(fmt, args);
    541 	va_end(args);
    542 
    543 	exit(1);
    544 }
    545 
    546 void
    547 fatalx(const char *fmt, ...)
    548 {
    549 	va_list		args;
    550 
    551 	/* In case people call fatalx() from the parent context. */
    552 	if (worker != NULL)
    553 		kore_msg_send(KORE_MSG_PARENT, KORE_MSG_FATALX, NULL, 0);
    554 
    555 	va_start(args, fmt);
    556 	fatal_log(fmt, args);
    557 	va_end(args);
    558 
    559 	exit(1);
    560 }
    561 
    562 static void
    563 fatal_log(const char *fmt, va_list args)
    564 {
    565 	char			buf[2048];
    566 
    567 	(void)vsnprintf(buf, sizeof(buf), fmt, args);
    568 	kore_log(LOG_ERR, "fatal: %s", buf);
    569 
    570 	if (worker != NULL && worker->id == KORE_WORKER_KEYMGR)
    571 		kore_keymgr_cleanup(1);
    572 }
    573 
    574 static int
    575 utils_x509name_tobuf(void *udata, int islast, int nid, const char *field,
    576     const void *data, size_t len, int flags)
    577 {
    578 	struct kore_buf		*buf = udata;
    579 
    580 	if (flags & KORE_X509_COMMON_NAME_ONLY) {
    581 		if (nid == KORE_X509_NAME_COMMON_NAME)
    582 			kore_buf_append(buf, data, len);
    583 	} else {
    584 		kore_buf_appendf(buf, "%s=", field);
    585 		kore_buf_append(buf, data, len);
    586 		if (!islast)
    587 			kore_buf_appendf(buf, " ");
    588 	}
    589 
    590 	return (KORE_RESULT_OK);
    591 }
    592 
    593 static int
    594 utils_base64_encode(const void *data, size_t len, char **out,
    595     const char *table, int flags)
    596 {
    597 	u_int8_t		n;
    598 	size_t			nb;
    599 	const u_int8_t		*ptr;
    600 	u_int32_t		bytes;
    601 	struct kore_buf		result;
    602 
    603 	nb = 0;
    604 	ptr = data;
    605 	kore_buf_init(&result, (len / 3) * 4);
    606 
    607 	while (len > 0) {
    608 		if (len > 2) {
    609 			nb = 3;
    610 			bytes = *ptr++ << 16;
    611 			bytes |= *ptr++ << 8;
    612 			bytes |= *ptr++;
    613 		} else if (len > 1) {
    614 			nb = 2;
    615 			bytes = *ptr++ << 16;
    616 			bytes |= *ptr++ << 8;
    617 		} else if (len == 1) {
    618 			nb = 1;
    619 			bytes = *ptr++ << 16;
    620 		} else {
    621 			kore_buf_cleanup(&result);
    622 			return (KORE_RESULT_ERROR);
    623 		}
    624 
    625 		n = (bytes >> 18) & 0x3f;
    626 		kore_buf_append(&result, &(table[n]), 1);
    627 		n = (bytes >> 12) & 0x3f;
    628 		kore_buf_append(&result, &(table[n]), 1);
    629 		if (nb > 1) {
    630 			n = (bytes >> 6) & 0x3f;
    631 			kore_buf_append(&result, &(table[n]), 1);
    632 			if (nb > 2) {
    633 				n = bytes & 0x3f;
    634 				kore_buf_append(&result, &(table[n]), 1);
    635 			}
    636 		}
    637 
    638 		len -= nb;
    639 	}
    640 
    641 	if (!(flags & KORE_BASE64_RAW)) {
    642 		switch (nb) {
    643 		case 1:
    644 			kore_buf_appendf(&result, "==");
    645 			break;
    646 		case 2:
    647 			kore_buf_appendf(&result, "=");
    648 			break;
    649 		case 3:
    650 			break;
    651 		default:
    652 			kore_buf_cleanup(&result);
    653 			return (KORE_RESULT_ERROR);
    654 		}
    655 	}
    656 
    657 	/* result.data gets taken over so no need to cleanup result. */
    658 	*out = kore_buf_stringify(&result, NULL);
    659 
    660 	return (KORE_RESULT_OK);
    661 }
    662 
    663 static int
    664 utils_base64_decode(const char *in, u_int8_t **out, size_t *olen,
    665     const char *table, int flags)
    666 {
    667 	int			i, c;
    668 	u_int8_t		d, n, o;
    669 	struct kore_buf		*res, buf;
    670 	const char		*ptr, *pad;
    671 	u_int32_t		b, len, plen, idx;
    672 
    673 	i = 4;
    674 	b = 0;
    675 	d = 0;
    676 	c = 0;
    677 	len = strlen(in);
    678 	memset(&buf, 0, sizeof(buf));
    679 
    680 	if (flags & KORE_BASE64_RAW) {
    681 		switch (len % 4) {
    682 		case 2:
    683 			plen = 2;
    684 			pad = "==";
    685 			break;
    686 		case 3:
    687 			plen = 1;
    688 			pad = "=";
    689 			break;
    690 		default:
    691 			return (KORE_RESULT_ERROR);
    692 		}
    693 
    694 		kore_buf_init(&buf, len + plen);
    695 		kore_buf_append(&buf, in, len);
    696 		kore_buf_append(&buf, pad, plen);
    697 
    698 		len = len + plen;
    699 		ptr = (const char *)buf.data;
    700 	} else {
    701 		ptr = in;
    702 	}
    703 
    704 	res = kore_buf_alloc(len);
    705 
    706 	for (idx = 0; idx < len; idx++) {
    707 		c = ptr[idx];
    708 		if (c == '=')
    709 			break;
    710 
    711 		for (o = 0; o < B64_TABLE_LEN; o++) {
    712 			if (table[o] == c) {
    713 				d = o;
    714 				break;
    715 			}
    716 		}
    717 
    718 		if (o == B64_TABLE_LEN) {
    719 			*out = NULL;
    720 			kore_buf_free(res);
    721 			kore_buf_cleanup(&buf);
    722 			return (KORE_RESULT_ERROR);
    723 		}
    724 
    725 		b |= (d & 0x3f) << ((i - 1) * 6);
    726 		i--;
    727 		if (i == 0) {
    728 			for (i = 2; i >= 0; i--) {
    729 				n = (b >> (8 * i));
    730 				kore_buf_append(res, &n, 1);
    731 			}
    732 
    733 			b = 0;
    734 			i = 4;
    735 		}
    736 	}
    737 
    738 	if (c == '=') {
    739 		if (i > 2) {
    740 			*out = NULL;
    741 			kore_buf_free(res);
    742 			kore_buf_cleanup(&buf);
    743 			return (KORE_RESULT_ERROR);
    744 		}
    745 
    746 		o = i;
    747 		for (i = 2; i >= o; i--) {
    748 			n = (b >> (8 * i));
    749 			kore_buf_append(res, &n, 1);
    750 		}
    751 	}
    752 
    753 	kore_buf_cleanup(&buf);
    754 	*out = kore_buf_release(res, olen);
    755 
    756 	return (KORE_RESULT_OK);
    757 }