Imported xs.

This commit is contained in:
default 2022-09-19 20:41:11 +02:00
parent ef03035ef0
commit 67288a763b
8 changed files with 2096 additions and 0 deletions

714
xs.h Normal file
View File

@ -0,0 +1,714 @@
/* copyright (c) 2022 grunfink - MIT license */
#ifndef _XS_H
#define _XS_H
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <stdarg.h>
#include <signal.h>
#include <errno.h>
typedef enum {
XSTYPE_NULL = 0x18,
XSTYPE_TRUE = 0x06,
XSTYPE_FALSE = 0x15,
XSTYPE_SOL = 0x11,
XSTYPE_LITEM = 0x1f,
XSTYPE_EOL = 0x12,
XSTYPE_SOD = 0x13,
XSTYPE_DITEM = 0x1e,
XSTYPE_EOD = 0x14,
XSTYPE_NUMBER = 0x17,
XSTYPE_STRING = 0x02
} xstype;
/* dynamic strings */
typedef char d_char;
/* auto-destroyable strings */
#define xs __attribute__ ((__cleanup__ (_xs_destroy))) d_char
#define _XS_BLK_SIZE 16
#define _xs_blk_size(sz) ((((sz) + _XS_BLK_SIZE) / _XS_BLK_SIZE) * _XS_BLK_SIZE)
#define xs_debug() kill(getpid(), 5)
xstype xs_type(const char *data);
int xs_size(const char *data);
d_char *xs_dup(const char *data);
d_char *xs_expand(d_char *data, int offset, int size);
d_char *xs_collapse(d_char *data, int offset, int size);
d_char *xs_insert_m(d_char *data, int offset, const char *mem, int size);
#define xs_insert(data, offset, data2) xs_insert_m(data, offset, data2, xs_size(data2))
#define xs_append_m(data, mem, size) xs_insert_m(data, xs_size(data) - 1, mem, size)
d_char *xs_str_new(const char *str);
#define xs_str_cat(str1, str2) xs_insert(str1, xs_size(str1) - 1, str2)
d_char *xs_replace(const char *str, const char *sfrom, const char *sto);
d_char *xs_fmt(const char *fmt, ...);
int xs_str_in(char *haystack, char *needle);
int xs_startswith(char *str, char *prefix);
int xs_endswith(char *str, char *postfix);
d_char *xs_crop(d_char *str, int start, int end);
d_char *xs_strip(d_char *str);
d_char *xs_tolower(d_char *str);
d_char *xs_list_new(void);
d_char *xs_list_append_m(d_char *list, const char *mem, int dsz);
#define xs_list_append(list, data) xs_list_append_m(list, data, xs_size(data))
int xs_list_iter(char **list, char **value);
int xs_list_len(char *list);
char *xs_list_get(char *list, int num);
int xs_list_in(char *list, char *val);
d_char *xs_join(char *list, const char *sep);
d_char *xs_splitn(const char *str, const char *sep, int times);
#define xs_split(str, sep) xs_splitn(str, sep, 0xfffffff)
d_char *xs_dict_new(void);
d_char *xs_dict_append_m(d_char *dict, const char *key, const char *mem, int dsz);
#define xs_dict_append(dict, key, data) xs_dict_append_m(dict, key, data, xs_size(data))
int xs_dict_iter(char **dict, char **key, char **value);
char *xs_dict_get(char *dict, const char *key);
d_char *xs_dict_del(d_char *dict, const char *key);
d_char *xs_dict_set(d_char *dict, const char *key, const char *data);
d_char *xs_val_new(xstype t);
d_char *xs_number_new(float f);
float xs_get_number(char *v);
extern int _xs_debug;
#ifdef XS_IMPLEMENTATION
int _xs_debug = 0;
void _xs_destroy(char **var)
{
if (_xs_debug)
printf("_xs_destroy %p\n", var);
free(*var);
}
xstype xs_type(const char *data)
/* return the type of data */
{
xstype t;
switch (data[0]) {
case XSTYPE_NULL:
case XSTYPE_TRUE:
case XSTYPE_FALSE:
case XSTYPE_SOL:
case XSTYPE_EOL:
case XSTYPE_SOD:
case XSTYPE_EOD:
case XSTYPE_LITEM:
case XSTYPE_DITEM:
case XSTYPE_NUMBER:
t = data[0];
break;
default:
t = XSTYPE_STRING;
break;
}
return t;
}
int xs_size(const char *data)
/* returns the size of data in bytes */
{
int len = 0;
int c = 0;
const char *p;
if (data == NULL)
return 0;
switch (xs_type(data)) {
case XSTYPE_STRING:
len = strlen(data) + 1;
break;
case XSTYPE_SOL:
/* look for a balanced EOL */
do {
c += data[len] == XSTYPE_SOL ? 1 : data[len] == XSTYPE_EOL ? -1 : 0;
len++;
} while (c);
break;
case XSTYPE_SOD:
/* look for a balanced EOD */
do {
c += data[len] == XSTYPE_SOD ? 1 : data[len] == XSTYPE_EOD ? -1 : 0;
len++;
} while (c);
break;
case XSTYPE_DITEM:
/* calculate the size of the key and the value */
p = data + 1;
p += xs_size(p);
p += xs_size(p);
len = p - data;
break;
case XSTYPE_LITEM:
/* it's the size of the item + 1 */
p = data + 1;
p += xs_size(p);
len = p - data;
break;
case XSTYPE_NUMBER:
len = sizeof(float) + 1;
break;
default:
len = 1;
}
return len;
}
d_char *xs_dup(const char *data)
/* creates a duplicate of data */
{
int sz = xs_size(data);
d_char *s = malloc(_xs_blk_size(sz));
memcpy(s, data, sz);
return s;
}
d_char *xs_expand(d_char *data, int offset, int size)
/* opens a hole in data */
{
int sz = xs_size(data);
int n;
/* open room */
if (sz == 0 || _xs_blk_size(sz) != _xs_blk_size(sz + size))
data = realloc(data, _xs_blk_size(sz + size));
/* move up the rest of the data */
for (n = sz + size - 1; n >= offset + size; n--)
data[n] = data[n - size];
return data;
}
d_char *xs_collapse(d_char *data, int offset, int size)
/* shrinks data */
{
int sz = xs_size(data);
int n;
/* don't try to delete beyond the limit */
if (offset + size > sz)
size = sz - offset;
/* shrink total size */
sz -= size;
for (n = offset; n < sz; n++)
data[n] = data[n + size];
return realloc(data, _xs_blk_size(sz));
}
d_char *xs_insert_m(d_char *data, int offset, const char *mem, int size)
/* inserts a memory block */
{
data = xs_expand(data, offset, size);
memcpy(data + offset, mem, size);
return data;
}
/** strings **/
d_char *xs_str_new(const char *str)
/* creates a new string */
{
return xs_insert(NULL, 0, str ? str : "");
}
d_char *xs_replace(const char *str, const char *sfrom, const char *sto)
/* replaces all occurrences of sfrom with sto in str */
{
d_char *s;
char *ss;
int sfsz;
/* cache the sizes */
sfsz = strlen(sfrom);
/* create the new string */
s = xs_str_new(NULL);
while ((ss = strstr(str, sfrom)) != NULL) {
/* copy the first part */
s = xs_append_m(s, str, ss - str);
/* copy sto */
s = xs_str_cat(s, sto);
/* move forward */
str = ss + sfsz;
}
/* copy the rest */
s = xs_str_cat(s, str);
return s;
}
d_char *xs_fmt(const char *fmt, ...)
/* formats a string with printf()-like marks */
{
int n;
d_char *s = NULL;
va_list ap;
va_start(ap, fmt);
n = vsnprintf(s, 0, fmt, ap);
va_end(ap);
if (n > 0) {
n = _xs_blk_size(n + 1);
s = calloc(n, 1);
va_start(ap, fmt);
n = vsnprintf(s, n, fmt, ap);
va_end(ap);
}
return s;
}
int xs_str_in(char *haystack, char *needle)
/* finds needle in haystack and returns the offset or -1 */
{
char *s;
int r = -1;
if ((s = strstr(haystack, needle)) != NULL)
r = s - haystack;
return r;
}
int xs_startswith(char *str, char *prefix)
/* returns true if str starts with prefix */
{
return !!(xs_str_in(str, prefix) == 0);
}
int xs_endswith(char *str, char *postfix)
/* returns true if str ends with postfix */
{
int ssz = strlen(str);
int psz = strlen(postfix);
return !!(ssz >= psz && memcmp(postfix, str + ssz - psz, psz) == 0);
}
d_char *xs_crop(d_char *str, int start, int end)
/* crops the d_char to be only from start to end */
{
int sz = strlen(str);
if (end <= 0)
end = sz + end;
/* crop from the top */
str[end] = '\0';
/* crop from the bottom */
str = xs_collapse(str, 0, start);
return str;
}
d_char *xs_strip(d_char *str)
/* strips the string of blanks from the start and the end */
{
int s, e;
for (s = 0; isspace(str[s]); s++);
for (e = strlen(str); e > 0 && isspace(str[e - 1]); e--);
return xs_crop(str, s, e);
}
d_char *xs_tolower(d_char *str)
/* convert to lowercase */
{
int n;
for (n = 0; str[n]; n++)
str[n] = tolower(str[n]);
return str;
}
/** lists **/
d_char *xs_list_new(void)
/* creates a new list */
{
d_char *list;
list = malloc(_xs_blk_size(2));
list[0] = XSTYPE_SOL;
list[1] = XSTYPE_EOL;
return list;
}
d_char *xs_list_append_m(d_char *list, const char *mem, int dsz)
/* adds a memory block to the list */
{
char c = XSTYPE_LITEM;
int lsz = xs_size(list);
list = xs_insert_m(list, lsz - 1, &c, 1);
list = xs_insert_m(list, lsz, mem, dsz);
return list;
}
int xs_list_iter(char **list, char **value)
/* iterates a list value */
{
int goon = 1;
char *p;
if (list == NULL || *list == NULL)
return 0;
p = *list;
/* skip a possible start of the list */
if (*p == XSTYPE_SOL)
p++;
/* an element? */
if (*p == XSTYPE_LITEM) {
p++;
*value = p;
p += xs_size(*value);
}
else {
/* end of list */
p++;
goon = 0;
}
/* store back the pointer */
*list = p;
return goon;
}
int xs_list_len(char *list)
/* returns the number of elements in the list */
{
int c = 0;
char *v;
while (xs_list_iter(&list, &v))
c++;
return c;
}
char *xs_list_get(char *list, int num)
/* returns the element #num */
{
char *v, *r = NULL;
int c = 0;
if (num < 0)
num = xs_list_len(list) + num;
while (xs_list_iter(&list, &v)) {
if (c == num) {
r = v;
break;
}
c++;
}
return r;
}
int xs_list_in(char *list, char *val)
/* returns the position of val in list or -1 */
{
int n = 0;
int r = -1;
char *v;
int sz = xs_size(val);
while (r == -1 && xs_list_iter(&list, &v)) {
int vsz = xs_size(v);
if (sz == vsz && memcmp(val, v, sz) == 0)
r = n;
n++;
}
return r;
}
d_char *xs_join(char *list, const char *sep)
/* joins a list into a string */
{
d_char *s;
char *v;
int c = 0;
s = xs_str_new(NULL);
while (xs_list_iter(&list, &v)) {
/* refuse to join non-string values */
if (xs_type(v) == XSTYPE_STRING) {
/* add the separator */
if (c != 0)
s = xs_str_cat(s, sep);
/* add the element */
s = xs_str_cat(s, v);
c++;
}
}
return s;
}
d_char *xs_splitn(const char *str, const char *sep, int times)
/* splits a string into a list upto n times */
{
int sz = strlen(sep);
char *ss;
d_char *list;
list = xs_list_new();
while (times > 0 && (ss = strstr(str, sep)) != NULL) {
/* add the first part (without the asciiz) */
list = xs_list_append_m(list, str, ss - str);
/* add the asciiz */
list = xs_str_cat(list, "");
/* skip past the separator */
str = ss + sz;
times--;
}
/* add the rest of the string */
list = xs_list_append(list, str);
return list;
}
/** dicts **/
d_char *xs_dict_new(void)
/* creates a new dict */
{
d_char *dict;
dict = malloc(_xs_blk_size(2));
dict[0] = XSTYPE_SOD;
dict[1] = XSTYPE_EOD;
return dict;
}
d_char *xs_dict_append_m(d_char *dict, const char *key, const char *mem, int dsz)
/* adds a memory block to the dict */
{
char c = XSTYPE_DITEM;
int sz = xs_size(dict);
int ksz = xs_size(key);
dict = xs_insert_m(dict, sz - 1, &c, 1);
dict = xs_insert_m(dict, sz, key, ksz);
dict = xs_insert_m(dict, sz + ksz, mem, dsz);
return dict;
}
int xs_dict_iter(char **dict, char **key, char **value)
/* iterates a dict value */
{
int goon = 1;
char *p;
if (dict == NULL || *dict == NULL)
return 0;
p = *dict;
/* skip a possible start of the list */
if (*p == XSTYPE_SOD)
p++;
/* an element? */
if (*p == XSTYPE_DITEM) {
p++;
*key = p;
p += xs_size(*key);
*value = p;
p += xs_size(*value);
}
else {
/* end of list */
p++;
goon = 0;
}
/* store back the pointer */
*dict = p;
return goon;
}
char *xs_dict_get(char *dict, const char *key)
/* returns the value directed by key */
{
char *k, *v, *r = NULL;
while (xs_dict_iter(&dict, &k, &v)) {
if (strcmp(k, key) == 0) {
r = v;
break;
}
}
return r;
}
d_char *xs_dict_del(d_char *dict, const char *key)
/* deletes a key */
{
char *k, *v;
char *p = dict;
while (xs_dict_iter(&p, &k, &v)) {
if (strcmp(k, key) == 0) {
/* the address of the item is just behind the key */
char *i = k - 1;
dict = xs_collapse(dict, i - dict, xs_size(i));
break;
}
}
return dict;
}
d_char *xs_dict_set(d_char *dict, const char *key, const char *data)
/* sets (replaces) a key */
{
/* delete the possibly existing key */
dict = xs_dict_del(dict, key);
/* append the data */
dict = xs_dict_append(dict, key, data);
return dict;
}
/** other values **/
d_char *xs_val_new(xstype t)
/* adds a new special value */
{
d_char *v = malloc(_xs_blk_size(1));
v[0] = t;
return v;
}
d_char *xs_number_new(float f)
/* adds a new number value */
{
d_char *v = malloc(_xs_blk_size(1 + sizeof(float)));
v[0] = XSTYPE_NUMBER;
memcpy(&v[1], &f, sizeof(float));
return v;
}
float xs_get_number(char *v)
/* gets the number as a float */
{
float f = 0.0;
if (v[0] == XSTYPE_NUMBER)
memcpy(&f, &v[1], sizeof(float));
return f;
}
#endif /* XS_IMPLEMENTATION */
#endif /* _XS_H */

177
xs_curl.h Normal file
View File

@ -0,0 +1,177 @@
/* copyright (c) 2022 grunfink - MIT license */
#ifndef _XS_CURL_H
#define _XS_CURL_H
d_char *xs_http_request(char *method, char *url, d_char *headers,
d_char *body, int b_size,
int *status, d_char **payload, int *p_size);
#ifdef XS_IMPLEMENTATION
#include <curl/curl.h>
static size_t _header_callback(char *buffer, size_t size,
size_t nitems, d_char **userdata)
{
d_char *headers = *userdata;
xs *l;
/* get the line */
l = xs_str_new(NULL);
l = xs_append_m(l, buffer, size * nitems);
l = xs_strip(l);
/* only the HTTP/x 200 line and the last one doesn't have ': ' */
if (xs_str_in(l, ": ") != -1) {
xs *knv = xs_splitn(l, ": ", 1);
headers = xs_dict_append(headers, xs_list_get(knv, 0), xs_list_get(knv, 1));
}
else
if (xs_startswith(l, "HTTP/"))
headers = xs_dict_append(headers, "_proto", l);
*userdata = headers;
return nitems * size;
}
struct _payload_data {
char *data;
int size;
int offset;
};
static int _data_callback(void *buffer, size_t size,
size_t nitems, struct _payload_data *pd)
{
int sz = size * nitems;
/* open space */
pd->size += sz;
pd->data = realloc(pd->data, pd->size + 1);
/* copy data */
memcpy(pd->data + pd->offset, buffer, sz);
pd->offset += sz;
return sz;
}
static int _post_callback(char *buffer, size_t size,
size_t nitems, struct _payload_data *pd)
{
/* size of data left */
int sz = pd->size - pd->offset;
/* if it's still bigger than the provided space, trim */
if (sz > size * nitems)
sz = size * nitems;
memcpy(buffer, pd->data + pd->offset, sz);
/* skip sent data */
pd->offset += sz;
return sz;
}
d_char *xs_http_request(char *method, char *url, d_char *headers,
d_char *body, int b_size,
int *status, d_char **payload, int *p_size)
/* does an HTTP request */
{
d_char *response;
CURL *curl;
struct curl_slist *list = NULL;
char *k, *v, *p;
long lstatus;
response = xs_dict_new();
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L);
/* force HTTP/1.1 */
curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
/* obey redirections */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
/* store response headers here */
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &response);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, _header_callback);
struct _payload_data ipd = { NULL, 0, 0 };
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ipd);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _data_callback);
if (strcmp(method, "POST") == 0) {
curl_easy_setopt(curl, CURLOPT_POST, 1L);
if (body != NULL) {
if (b_size <= 0)
b_size = xs_size(body);
/* add the content-length header */
char tmp[32];
sprintf(tmp, "content-length: %d", b_size);
list = curl_slist_append(list, tmp);
struct _payload_data pd = { body, b_size, 0 };
curl_easy_setopt(curl, CURLOPT_READDATA, &pd);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, _post_callback);
}
}
/* fill the request headers */
p = headers;
while (xs_dict_iter(&p, &k, &v)) {
xs *h;
const char *args[] = { k, v, NULL };
h = xs_fmt("%s: %s", args);
list = curl_slist_append(list, h);
}
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
/* do it */
curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &lstatus);
curl_easy_cleanup(curl);
if (status != NULL)
*status = (int) lstatus;
if (p_size != NULL)
*p_size = ipd.size;
if (payload != NULL) {
*payload = ipd.data;
/* add an asciiz just in case (but not touching p_size) */
if (ipd.data != NULL)
ipd.data[ipd.size] = '\0';
}
else
free(ipd.data);
return response;
}
#endif /* XS_IMPLEMENTATION */
#endif /* _XS_CURL_H */

180
xs_encdec.h Normal file
View File

@ -0,0 +1,180 @@
/* copyright (c) 2022 grunfink - MIT license */
#ifndef _XS_ENCDEC_H
#define _XS_ENCDEC_H
d_char *xs_hex_enc(const char *data, int size);
d_char *xs_hex_dec(const char *hex);
d_char *xs_base64_enc(const char *data, int sz);
d_char *xs_base64_dec(const char *data, int *size);
d_char *xs_utf8_enc(d_char *str, unsigned int cpoint);
#ifdef XS_IMPLEMENTATION
d_char *xs_hex_enc(const char *data, int size)
/* returns an hexdump of data */
{
d_char *s;
char *p;
int n;
p = s = calloc(size * 2 + 1, 1);
for (n = 0; n < size; n++) {
sprintf(p, "%02x", (unsigned char)data[n]);
p += 2;
}
return s;
}
d_char *xs_hex_dec(const char *hex)
/* decodes an hexdump into data */
{
int sz = strlen(hex);
d_char *s;
char *p;
int n;
p = s = calloc(sz / 2, 1);
for (n = 0; n < sz; n += 2) {
int i;
if (sscanf(&hex[n], "%02x", &i) == 0) {
/* decoding error */
free(s);
s = NULL;
}
else
*p = i;
p++;
}
return s;
}
d_char *xs_base64_enc(const char *data, int sz)
/* encodes data to base64 */
{
d_char *s;
unsigned char *p;
int n;
static char *b64_tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
s = xs_str_new(NULL);
p = (unsigned char *)data;
for (n = 0; n < sz; n += 3) {
int l = sz - n;
if (l == 1) {
s = xs_append_m(s, &b64_tbl[(p[n] >> 2) & 0x3f], 1);
s = xs_append_m(s, &b64_tbl[(p[n] << 4) & 0x3f], 1);
s = xs_append_m(s, "==", 2);
}
else
if (l == 2) {
s = xs_append_m(s, &b64_tbl[(p[n] >> 2) & 0x3f], 1);
s = xs_append_m(s, &b64_tbl[(p[n] << 4 | p[n + 1] >> 4) & 0x3f], 1);
s = xs_append_m(s, &b64_tbl[(p[n + 1] << 2) & 0x3f], 1);
s = xs_append_m(s, "=", 1);
}
else {
s = xs_append_m(s, &b64_tbl[(p[n] >> 2) & 0x3f], 1);
s = xs_append_m(s, &b64_tbl[(p[n] << 4 | p[n + 1] >> 4) & 0x3f], 1);
s = xs_append_m(s, &b64_tbl[(p[n + 1] << 2 | p[n + 2] >> 6) & 0x3f], 1);
s = xs_append_m(s, &b64_tbl[(p[n + 2]) & 0x3f], 1);
}
}
return s;
}
d_char *xs_base64_dec(const char *data, int *size)
/* decodes data from base64 */
{
d_char *s = NULL;
int sz = 0;
char *p;
static char *b64_tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/=";
p = (char *)data;
for (p = (char *)data; *p; p += 4) {
int cs[4];
int n;
unsigned char tmp[3];
for (n = 0; n < 4; n++) {
char *ss = strchr(b64_tbl, p[n]);
if (ss == NULL) {
/* not a base64 char */
free(s);
return NULL;
}
cs[n] = ss - b64_tbl;
}
n = 0;
/* first byte */
tmp[n++] = cs[0] << 2 | ((cs[1] >> 4) & 0x0f);
/* second byte */
if (cs[2] != 64)
tmp[n++] = cs[1] << 4 | ((cs[2] >> 2) & 0x3f);
/* third byte */
if (cs[3] != 64)
tmp[n++] = cs[2] << 6 | (cs[3] & 0x3f);
/* must be done manually because data can be pure binary */
s = realloc(s, sz + n);
memcpy(s + sz, tmp, n);
sz += n;
}
*size = sz;
return s;
}
d_char *xs_utf8_enc(d_char *str, unsigned int cpoint)
/* encodes an Unicode codepoint to utf8 */
{
unsigned char tmp[4];
int n = 0;
if (cpoint < 0x80)
tmp[n++] = cpoint & 0xff;
else
if (cpoint < 0x800) {
tmp[n++] = 0xc0 | (cpoint >> 6);
tmp[n++] = 0x80 | (cpoint & 0x3f);
}
else
if (cpoint < 0x10000) {
tmp[n++] = 0xe0 | (cpoint >> 12);
tmp[n++] = 0x80 | ((cpoint >> 6) & 0x3f);
tmp[n++] = 0x80 | (cpoint & 0x3f);
}
return xs_append_m(str, (char *)tmp, n);
}
#endif /* XS_IMPLEMENTATION */
#endif /* _XS_ENCDEC_H */

184
xs_httpd.h Normal file
View File

@ -0,0 +1,184 @@
/* copyright (c) 2022 grunfink - MIT license */
#ifndef _XS_HTTPD_H
#define _XS_HTTPD_H
d_char *xs_url_dec(char *str);
d_char *xs_url_vars(char *str);
d_char *xs_httpd_request(FILE *f);
void xs_httpd_response(FILE *f, int status, d_char *headers, char *body, int b_size);
#ifdef XS_IMPLEMENTATION
d_char *xs_url_dec(char *str)
/* decodes an URL */
{
d_char *s = xs_str_new(NULL);
while (*str) {
if (*str == '%') {
int i;
if (sscanf(str + 1, "%02x", &i) == 1) {
unsigned char uc = i;
s = xs_append_m(s, (char *)&uc, 1);
str += 2;
}
}
else
if (*str == '+')
s = xs_append_m(s, " ", 1);
else
s = xs_append_m(s, str, 1);
str++;
}
return s;
}
d_char *xs_url_vars(char *str)
/* parse url variables */
{
d_char *vars;
vars = xs_dict_new();
if (str != NULL) {
char *v, *l;
xs *args;
/* split by arguments */
args = xs_split(str, "&");
l = args;
while (xs_list_iter(&l, &v)) {
xs *kv = xs_splitn(v, "=", 2);
if (xs_list_len(kv) == 2)
vars = xs_dict_append(vars,
xs_list_get(kv, 0), xs_list_get(kv, 1));
}
}
return vars;
}
d_char *xs_httpd_request(FILE *f)
/* processes an httpd connection */
{
xs *headers = NULL;
xs *q_vars = NULL;
xs *p_vars = NULL;
d_char *req = NULL;
xs *l1, *l2;
char *v;
xs_socket_timeout(fileno(f), 2.0, 0.0);
/* read the first line and split it */
l1 = xs_strip(xs_readline(f));
l2 = xs_split(l1, " ");
if (xs_list_len(l2) != 3) {
/* error or timeout */
return NULL;
}
headers = xs_dict_new();
headers = xs_dict_append(headers, "method", xs_list_get(l2, 0));
headers = xs_dict_append(headers, "proto", xs_list_get(l2, 2));
{
/* split the path with its optional variables */
xs *udp = xs_url_dec(xs_list_get(l2, 1));
xs *pnv = xs_splitn(udp, "?", 1);
/* store the path */
headers = xs_dict_append(headers, "path", xs_list_get(pnv, 0));
/* get the variables */
q_vars = xs_url_vars(xs_list_get(pnv, 1));
}
/* read the headers */
for (;;) {
xs *l, *p = NULL;
l = xs_strip(xs_readline(f));
/* done with the header? */
if (strcmp(l, "") == 0)
break;
/* split header and content */
p = xs_splitn(l, ": ", 1);
if (xs_list_len(p) == 2)
headers = xs_dict_append(headers,
xs_tolower(xs_list_get(p, 0)), xs_list_get(p, 1));
}
xs_socket_timeout(fileno(f), 5.0, 0.0);
/* does it have a payload with form urlencoded variables? */
v = xs_dict_get(headers, "content-type");
if (v && strcmp(v, "application/x-www-form-urlencoded") == 0) {
if ((v = xs_dict_get(headers, "content-length")) != NULL) {
int cl = atoi(v);
xs *payload;
if ((payload = xs_read(f, cl)) != NULL) {
xs *upl = xs_url_dec(payload);
p_vars = xs_url_vars(upl);
}
}
}
else
p_vars = xs_dict_new();
if (errno == 0) {
req = xs_dict_new();
req = xs_dict_append(req, "headers", headers);
req = xs_dict_append(req, "q_vars", q_vars);
req = xs_dict_append(req, "p_vars", p_vars);
}
return req;
}
void xs_httpd_response(FILE *f, int status, d_char *headers, char *body, int b_size)
/* sends an httpd response */
{
xs *proto;
char *p, *k, *v;
proto = xs_fmt("HTTP/1.1 %d", status);
fprintf(f, "%s\r\n", proto);
p = headers;
while (xs_dict_iter(&p, &k, &v)) {
fprintf(f, "%s: %s\r\n", k, v);
}
if (b_size != 0)
fprintf(f, "content-length: %d\r\n", b_size);
fprintf(f, "\r\n");
if (body != NULL && b_size != 0)
fwrite(body, b_size, 1, f);
}
#endif /* XS_IMPLEMENTATION */
#endif /* XS_HTTPD_H */

86
xs_io.h Normal file
View File

@ -0,0 +1,86 @@
/* copyright (c) 2022 grunfink - MIT license */
#ifndef _XS_IO_H
#define _XS_IO_H
d_char *xs_readall(FILE *f);
d_char *xs_readline(FILE *f);
d_char *xs_read(FILE *f, int size);
#ifdef XS_IMPLEMENTATION
d_char *xs_readall(FILE *f)
/* reads the rest of the file into a string */
{
d_char *s;
char tmp[1024];
errno = 0;
/* create the new string */
s = xs_str_new(NULL);
while (fgets(tmp, sizeof(tmp), f))
s = xs_str_cat(s, tmp);
return s;
}
d_char *xs_readline(FILE *f)
/* reads a line from a file */
{
d_char *s = NULL;
errno = 0;
/* don't even try on eof */
if (!feof(f)) {
int c;
s = xs_str_new(NULL);
while ((c = fgetc(f)) != EOF) {
unsigned char rc = c;
s = xs_append_m(s, (char *)&rc, 1);
if (c == '\n')
break;
}
}
return s;
}
d_char *xs_read(FILE *f, int size)
/* reads up to size bytes from f */
{
d_char *s;
errno = 0;
s = xs_str_new(NULL);
while (size != 0 && !feof(f)) {
char tmp[2048];
int n, r;
if ((n = sizeof(tmp)) > size)
n = size;
r = fread(tmp, 1, n, f);
s = xs_append_m(s, tmp, r);
size -= r;
}
return s;
}
#endif /* XS_IMPLEMENTATION */
#endif /* _XS_IO_H */

501
xs_json.h Normal file
View File

@ -0,0 +1,501 @@
/* copyright (c) 2022 grunfink - MIT license */
#ifndef _XS_JSON_H
#define _XS_JSON_H
d_char *xs_json_dumps_pp(char *data, int indent);
#define xs_json_dumps(data) xs_json_dumps_pp(data, 0)
d_char *xs_json_loads(const char *json);
#ifdef XS_IMPLEMENTATION
/** IMPLEMENTATION **/
/** JSON dumps **/
d_char *_xs_json_dumps_str(d_char *s, char *data)
/* dumps a string in JSON format */
{
unsigned char c;
s = xs_str_cat(s, "\"");
while ((c = *data)) {
if (c == '\n')
s = xs_str_cat(s, "\\n");
else
if (c == '\r')
s = xs_str_cat(s, "\\r");
else
if (c == '\t')
s = xs_str_cat(s, "\\t");
else
if (c == '\\')
s = xs_str_cat(s, "\\\\");
else
if (c == '"')
s = xs_str_cat(s, "\\\"");
else
if (c < 32) {
char tmp[10];
sprintf(tmp, "\\u%04x", (unsigned int) c);
s = xs_str_cat(s, tmp);
}
else
s = xs_append_m(s, data, 1);
data++;
}
s = xs_str_cat(s, "\"");
return s;
}
d_char *_xs_json_indent(d_char *s, int level, int indent)
/* adds indentation */
{
if (indent) {
int n;
s = xs_str_cat(s, "\n");
for (n = 0; n < level * indent; n++)
s = xs_str_cat(s, " ");
}
return s;
}
d_char *_xs_json_dumps(d_char *s, char *data, int level, int indent)
/* dumps partial data as JSON */
{
char *k, *v;
int c = 0;
switch (xs_type(data)) {
case XSTYPE_NULL:
s = xs_str_cat(s, "null");
break;
case XSTYPE_TRUE:
s = xs_str_cat(s, "true");
break;
case XSTYPE_FALSE:
s = xs_str_cat(s, "false");
break;
case XSTYPE_NUMBER:
{
char tmp[32];
snprintf(tmp, sizeof(tmp), "%g", xs_get_number(data));
s = xs_str_cat(s, tmp);
}
break;
case XSTYPE_SOL:
s = xs_str_cat(s, "[");
while (xs_list_iter(&data, &v)) {
if (c != 0)
s = xs_str_cat(s, ",");
s = _xs_json_indent(s, level + 1, indent);
s = _xs_json_dumps(s, v, level + 1, indent);
c++;
}
s = _xs_json_indent(s, level, indent);
s = xs_str_cat(s, "]");
break;
case XSTYPE_SOD:
s = xs_str_cat(s, "{");
while (xs_dict_iter(&data, &k, &v)) {
if (c != 0)
s = xs_str_cat(s, ",");
s = _xs_json_indent(s, level + 1, indent);
s = _xs_json_dumps_str(s, k);
s = xs_str_cat(s, ":");
if (indent)
s = xs_str_cat(s, " ");
s = _xs_json_dumps(s, v, level + 1, indent);
c++;
}
s = _xs_json_indent(s, level, indent);
s = xs_str_cat(s, "}");
break;
case XSTYPE_STRING:
s = _xs_json_dumps_str(s, data);
break;
default:
break;
}
return s;
}
d_char *xs_json_dumps_pp(char *data, int indent)
/* dumps a piece of data as JSON */
{
xstype t = xs_type(data);
d_char *s = NULL;
if (t == XSTYPE_SOL || t == XSTYPE_SOD) {
s = xs_str_new(NULL);
s = _xs_json_dumps(s, data, 0, indent);
}
return s;
}
/** JSON loads **/
/* this code comes mostly from the Minimum Profit Text Editor (MPDM) */
typedef enum {
JS_ERROR = -1,
JS_INCOMPLETE,
JS_OCURLY,
JS_OBRACK,
JS_CCURLY,
JS_CBRACK,
JS_COMMA,
JS_COLON,
JS_VALUE,
JS_STRING,
JS_INTEGER,
JS_REAL,
JS_TRUE,
JS_FALSE,
JS_NULL,
JS_ARRAY,
JS_OBJECT
} js_type;
d_char *_xs_json_loads_lexer(const char **json, js_type *t)
{
char c;
const char *s = *json;
d_char *v = NULL;
/* skip blanks */
while (*s == L' ' || *s == L'\t' || *s == L'\n' || *s == L'\r')
s++;
c = *s++;
if (c == '{')
*t = JS_OCURLY;
else
if (c == '}')
*t = JS_CCURLY;
else
if (c == '[')
*t = JS_OBRACK;
else
if (c == ']')
*t = JS_CBRACK;
else
if (c == ',')
*t = JS_COMMA;
else
if (c == ':')
*t = JS_COLON;
else
if (c == '"') {
*t = JS_STRING;
v = xs_str_new(NULL);
while ((c = *s) != '"' && c != '\0') {
char tmp[5];
int i;
if (c == '\\') {
s++;
c = *s;
switch (c) {
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
case 'u': /* Unicode codepoint as an hex char */
s++;
tmp[0] = (char)*s; s++;
tmp[1] = (char)*s; s++;
tmp[2] = (char)*s; s++;
tmp[3] = (char)*s;
tmp[4] = '\0';
sscanf(tmp, "%04x", &i);
v = xs_utf8_enc(v, i);
c = '\0';
break;
}
}
if (c)
v = xs_append_m(v, &c, 1);
s++;
}
if (c != '\0')
s++;
}
else
if (c == '-' || (c >= '0' && c <= '9') || c == '.') {
xs *vn = NULL;
*t = JS_INTEGER;
vn = xs_str_new(NULL);
vn = xs_append_m(vn, &c, 1);
while (((c = *s) >= '0' && c <= '9') || c == '.') {
if (c == '.')
*t = JS_REAL;
vn = xs_append_m(vn, &c, 1);
s++;
}
/* convert to XSTYPE_NUMBER */
v = xs_number_new(atof(vn));
}
else
if (c == 't' && strncmp(s, "rue", 3) == 0) {
s += 3;
*t = JS_TRUE;
v = xs_val_new(XSTYPE_TRUE);
}
else
if (c == 'f' && strncmp(s, "alse", 4) == 0) {
s += 4;
*t = JS_FALSE;
v = xs_val_new(XSTYPE_FALSE);
}
else
if (c == 'n' && strncmp(s, "ull", 3) == 0) {
s += 3;
*t = JS_NULL;
v = xs_val_new(XSTYPE_NULL);
}
else
*t = JS_ERROR;
*json = s;
return v;
}
d_char *_xs_json_loads_array(const char **json, js_type *t);
d_char *_xs_json_loads_object(const char **json, js_type *t);
d_char *_xs_json_loads_value(const char **json, js_type *t, d_char *v)
/* parses a JSON value */
{
if (*t == JS_OBRACK)
v = _xs_json_loads_array(json, t);
else
if (*t == JS_OCURLY)
v = _xs_json_loads_object(json, t);
if (*t >= JS_VALUE)
*t = JS_VALUE;
else
*t = JS_ERROR;
return v;
}
d_char *_xs_json_loads_array(const char **json, js_type *t)
/* parses a JSON array */
{
const char *s = *json;
xs *v;
d_char *l;
js_type tt;
l = xs_list_new();
*t = JS_INCOMPLETE;
v = _xs_json_loads_lexer(&s, &tt);
if (tt == JS_CBRACK)
*t = JS_ARRAY;
else {
v = _xs_json_loads_value(&s, &tt, v);
if (tt == JS_VALUE) {
l = xs_list_append(l, v);
while (*t == JS_INCOMPLETE) {
_xs_json_loads_lexer(&s, &tt);
if (tt == JS_CBRACK)
*t = JS_ARRAY;
else
if (tt == JS_COMMA) {
xs *v2;
v2 = _xs_json_loads_lexer(&s, &tt);
v2 = _xs_json_loads_value(&s, &tt, v2);
if (tt == JS_VALUE)
l = xs_list_append(l, v2);
else
*t = JS_ERROR;
}
else
*t = JS_ERROR;
}
}
else
*t = JS_ERROR;
}
if (*t == JS_ERROR) {
free(l);
l = NULL;
}
*json = s;
return l;
}
d_char *_xs_json_loads_object(const char **json, js_type *t)
/* parses a JSON object */
{
const char *s = *json;
xs *k1;
d_char *d;
js_type tt;
d = xs_dict_new();
*t = JS_INCOMPLETE;
k1 = _xs_json_loads_lexer(&s, &tt);
if (tt == JS_CCURLY)
*t = JS_OBJECT;
else
if (tt == JS_STRING) {
_xs_json_loads_lexer(&s, &tt);
if (tt == JS_COLON) {
xs *v1;
v1 = _xs_json_loads_lexer(&s, &tt);
v1 = _xs_json_loads_value(&s, &tt, v1);
if (tt == JS_VALUE) {
d = xs_dict_append(d, k1, v1);
while (*t == JS_INCOMPLETE) {
_xs_json_loads_lexer(&s, &tt);
if (tt == JS_CCURLY)
*t = JS_OBJECT;
else
if (tt == JS_COMMA) {
xs *k;
k = _xs_json_loads_lexer(&s, &tt);
if (tt == JS_STRING) {
_xs_json_loads_lexer(&s, &tt);
if (tt == JS_COLON) {
xs *v;
v = _xs_json_loads_lexer(&s, &tt);
v = _xs_json_loads_value(&s, &tt, v);
if (tt == JS_VALUE)
d = xs_dict_append(d, k, v);
else
*t = JS_ERROR;
}
else
*t = JS_ERROR;
}
else
*t = JS_ERROR;
}
else
*t = JS_ERROR;
}
}
else
*t = JS_ERROR;
}
else
*t = JS_ERROR;
}
else
*t = JS_ERROR;
if (*t == JS_ERROR) {
free(d);
d = NULL;
}
*json = s;
return d;
}
d_char *xs_json_loads(const char *json)
/* loads a string in JSON format and converts to a multiple data */
{
d_char *v = NULL;
js_type t;
_xs_json_loads_lexer(&json, &t);
if (t == JS_OBRACK)
v = _xs_json_loads_array(&json, &t);
else
if (t == JS_OCURLY)
v = _xs_json_loads_object(&json, &t);
else
t = JS_ERROR;
return v;
}
#endif /* XS_IMPLEMENTATION */
#endif /* _XS_JSON_H */

159
xs_openssl.h Normal file
View File

@ -0,0 +1,159 @@
/* copyright (c) 2022 grunfink - MIT license */
#ifndef _XS_OPENSSL_H
#define _XS_OPENSSL_H
d_char *xs_md5_hex(const void *input, int size);
d_char *xs_sha1_hex(const void *input, int size);
d_char *xs_sha256_hex(const void *input, int size);
d_char *xs_rsa_genkey(int bits);
d_char *xs_rsa_sign(char *secret, char *mem, int size);
int xs_rsa_verify(char *pubkey, char *mem, int size, char *b64sig);
#ifdef XS_IMPLEMENTATION
#include "openssl/md5.h"
#include "openssl/sha.h"
#include "openssl/rsa.h"
#include "openssl/pem.h"
d_char *xs_md5_hex(const void *input, int size)
{
unsigned char md5[16];
MD5_CTX ctx;
MD5_Init(&ctx);
MD5_Update(&ctx, input, size);
MD5_Final(md5, &ctx);
return xs_hex_enc((char *)md5, sizeof(md5));
}
d_char *xs_sha1_hex(const void *input, int size)
{
unsigned char sha1[20];
SHA_CTX ctx;
SHA1_Init(&ctx);
SHA1_Update(&ctx, input, size);
SHA1_Final(sha1, &ctx);
return xs_hex_enc((char *)sha1, sizeof(sha1));
}
d_char *xs_sha256_hex(const void *input, int size)
{
unsigned char sha256[32];
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, input, size);
SHA256_Final(sha256, &ctx);
return xs_hex_enc((char *)sha256, sizeof(sha256));
}
d_char *xs_rsa_genkey(int bits)
/* generates an RSA keypair */
{
BIGNUM *bne;
RSA *rsa;
d_char *keypair = NULL;
if ((bne = BN_new()) != NULL) {
if (BN_set_word(bne, RSA_F4) == 1) {
if ((rsa = RSA_new()) != NULL) {
if (RSA_generate_key_ex(rsa, bits, bne, NULL) == 1) {
BIO *bs = BIO_new(BIO_s_mem());
BIO *bp = BIO_new(BIO_s_mem());
BUF_MEM *sptr;
BUF_MEM *pptr;
PEM_write_bio_RSAPrivateKey(bs, rsa, NULL, NULL, 0, 0, NULL);
BIO_get_mem_ptr(bs, &sptr);
PEM_write_bio_RSA_PUBKEY(bp, rsa);
BIO_get_mem_ptr(bp, &pptr);
keypair = xs_dict_new();
keypair = xs_dict_append(keypair, "secret", sptr->data);
keypair = xs_dict_append(keypair, "public", pptr->data);
BIO_free(bs);
BIO_free(bp);
}
}
}
}
return keypair;
}
d_char *xs_rsa_sign(char *secret, char *mem, int size)
/* signs a memory block (secret is in PEM format) */
{
d_char *signature = NULL;
BIO *b;
RSA *rsa;
unsigned char *sig;
unsigned int sig_len;
/* un-PEM the key */
b = BIO_new_mem_buf(secret, strlen(secret));
rsa = PEM_read_bio_RSAPrivateKey(b, NULL, NULL, NULL);
/* alloc space */
sig = malloc(RSA_size(rsa));
if (RSA_sign(NID_sha256, (unsigned char *)mem, size, sig, &sig_len, rsa) == 1)
signature = xs_base64_enc((char *)sig, sig_len);
BIO_free(b);
RSA_free(rsa);
free(sig);
return signature;
}
int xs_rsa_verify(char *pubkey, char *mem, int size, char *b64sig)
/* verifies a base64 block, returns non-zero on ok */
{
int r = 0;
BIO *b;
RSA *rsa;
/* un-PEM the key */
b = BIO_new_mem_buf(pubkey, strlen(pubkey));
rsa = PEM_read_bio_RSA_PUBKEY(b, NULL, NULL, NULL);
if (rsa != NULL) {
d_char *sig = NULL;
int s_size;
/* de-base64 */
sig = xs_base64_dec(b64sig, &s_size);
if (sig != NULL)
r = RSA_verify(NID_sha256, (unsigned char *)mem, size,
(unsigned char *)sig, s_size, rsa);
free(sig);
}
BIO_free(b);
RSA_free(rsa);
return r;
}
#endif /* XS_IMPLEMENTATION */
#endif /* _XS_OPENSSL_H */

95
xs_socket.h Normal file
View File

@ -0,0 +1,95 @@
/* copyright (c) 2022 grunfink - MIT license */
#ifndef _XS_SOCKET_H
#define _XS_SOCKET_H
int xs_socket_timeout(int s, float rto, float sto);
int xs_socket_server(char *addr, int port);
FILE *xs_socket_accept(int rs);
#ifdef XS_IMPLEMENTATION
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
int xs_socket_timeout(int s, float rto, float sto)
/* sets the socket timeout in seconds */
{
struct timeval tv;
int ret = 0;
if (rto > 0.0) {
tv.tv_sec = (int)rto;
tv.tv_usec = (int)((rto - (float)(int)rto) * 1000000.0);
ret = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
}
if (sto > 0.0) {
tv.tv_sec = (int)sto;
tv.tv_usec = (int)((sto - (float)(int)sto) * 1000000.0);
ret = setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
}
return ret;
}
int xs_socket_server(char *addr, int port)
/* opens a server socket */
{
int rs = -1;
struct sockaddr_in host;
memset(&host, '\0', sizeof(host));
if (addr != NULL) {
struct hostent *he;
if ((he = gethostbyname(addr)) != NULL)
memcpy(&host.sin_addr, he->h_addr_list[0], he->h_length);
else
goto end;
}
host.sin_family = AF_INET;
host.sin_port = htons(port);
if ((rs = socket(AF_INET, SOCK_STREAM, 0)) != -1) {
/* reuse addr */
int i = 1;
setsockopt(rs, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i));
if (bind(rs, (struct sockaddr *)&host, sizeof(host)) == -1) {
close(rs);
rs = -1;
}
else
listen(rs, SOMAXCONN);
}
end:
return rs;
}
FILE *xs_socket_accept(int rs)
/* accepts an incoming connection */
{
int cs = -1;
struct sockaddr_in host;
socklen_t l = sizeof(host);
cs = accept(rs, (struct sockaddr *)&host, &l);
return cs == -1 ? NULL : fdopen(cs, "r+");
}
#endif /* XS_IMPLEMENTATION */
#endif /* _XS_SOCKET_H */