diff --git a/configure.ac b/configure.ac index bce0293c..f36bafc0 100644 --- a/configure.ac +++ b/configure.ac @@ -802,6 +802,7 @@ util/tradcpp/Makefile lib/Makefile lib/McdeSys/Makefile lib/McdeSound/Makefile +lib/libDtChat/Makefile lib/DtXinerama/Makefile diff --git a/include/DtChat/DtChat.h b/include/DtChat/DtChat.h new file mode 100644 index 00000000..08e23645 --- /dev/null +++ b/include/DtChat/DtChat.h @@ -0,0 +1,108 @@ +/* + * DtChat.h -- dtchat's public core API + * + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * The UI and the headless tests use only this header. No Xt, no protocol + * library, no audio/video type appears here. The core owns the event queue; + * the caller drains it with dtchat_event_next() and frees each event. + */ +#ifndef _DtChat_DtChat_h +#define _DtChat_DtChat_h + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct DtChat DtChat; + +typedef enum { + DTCHAT_EV_STATE, /* an account or a local peer changed state */ + DTCHAT_EV_CONV, /* a conversation was added, changed or removed */ + DTCHAT_EV_MESSAGE, /* a message, incoming or echoed */ + DTCHAT_EV_PRESENCE, /* a buddy or a local peer changed presence */ + DTCHAT_EV_TYPING, /* someone started or stopped typing */ + DTCHAT_EV_REQUEST, /* the adapter needs an answer: code, password, QR */ + DTCHAT_EV_CALL, /* call state changed */ + DTCHAT_EV_ERROR /* an account or the local peer failed */ +} DtChatEventType; + +/* DtChatEvent.flags for DTCHAT_EV_MESSAGE */ +#define DTCHAT_MSG_SELF 0x01 /* our own message, echoed */ +#define DTCHAT_MSG_ACTION 0x02 /* /me */ +#define DTCHAT_MSG_SYSTEM 0x04 /* join, part, topic, ... */ +#define DTCHAT_MSG_NOTICE 0x08 + +/* dtchat_call() media bits */ +#define DTCHAT_MEDIA_AUDIO 0x01 +#define DTCHAT_MEDIA_VIDEO 0x02 + +/* + * One event. The strings are owned by the event; dtchat_event_free() + * releases them. "account" is NULL for a local peer, "conv" is the + * conversation id inside that account, "from" is the sender's display + * name, "text" is UTF-8. request_id is only set for DTCHAT_EV_REQUEST; + * data is reserved for the event-specific payload (a call object, later). + */ +typedef struct { + DtChatEventType type; + char *account; + char *conv; + char *from; + char *text; + long long ts; /* seconds since the epoch, 0 if unknown */ + int flags; + int request_id; + void *data; +} DtChatEvent; + +/* + * Open the core with its state directory. NULL means ~/.dt/dtchat. + * The call does not create the directory; the store does that when the + * first account is saved (T1.3). Returns NULL on out of memory. + */ +DtChat *dtchat_open(const char *config_dir); + +/* Stop adapters, close the local listener and free the core. */ +void dtchat_close(DtChat *chat); + +/* + * A file descriptor that becomes readable when events are queued, for + * XtAppAddInput() or poll(). Returns -1 when the core has no wakeup pipe + * yet (the T1.1 stub). + */ +int dtchat_fd(const DtChat *chat); + +/* + * Run the core's event loop once. timeout_ms < 0 waits without a timeout, + * 0 returns immediately. Returns the number of ready descriptors, 0 on a + * timeout, -1 on error. + */ +int dtchat_poll(DtChat *chat, int timeout_ms); + +/* Return the next queued event, or NULL when the queue is empty. */ +DtChatEvent *dtchat_event_next(DtChat *chat); + +/* Free one event returned by dtchat_event_next(). NULL is allowed. */ +void dtchat_event_free(DtChatEvent *event); + +/* Send UTF-8 text to CONV. Returns 0 when it was queued, -1 on error. */ +int dtchat_send(DtChat *chat, const char *conv, const char *text); + +/* Join a channel/room; the adapter decides what that means. */ +int dtchat_join(DtChat *chat, const char *account, const char *conv); + +/* Answer a DTCHAT_EV_REQUEST; VALUE may be NULL for "cancel". */ +int dtchat_answer(DtChat *chat, const char *account, int request_id, + const char *value); + +/* Start a call to a local peer; MEDIA is DTCHAT_MEDIA_AUDIO/VIDEO. */ +int dtchat_call(DtChat *chat, const char *peer, int media); + +#ifdef __cplusplus +} +#endif + +#endif /* _DtChat_DtChat_h */ diff --git a/include/DtChat/Ipc.h b/include/DtChat/Ipc.h new file mode 100644 index 00000000..116f9fa3 --- /dev/null +++ b/include/DtChat/Ipc.h @@ -0,0 +1,137 @@ +/* + * Ipc.h -- dtchat's adapter contract: JSON lines, at most 1 MiB each + * + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * This header is also the contract for adapters written outside this tree. + * The rules are in docs/reference/dtchat-adapter-protocol.txt: + * - one JSON object per line, UTF-8, '\n' terminated + * - at most DC_IPC_MAX_LINE bytes per line (without the '\n') + * - no NUL byte, no pretty-printing, no multiple objects per line + * - unknown fields are ignored; a breaking change raises DC_IPC_VERSION + */ +#ifndef _DtChat_Ipc_h +#define _DtChat_Ipc_h + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define DC_IPC_VERSION 1 +#define DC_IPC_MAX_LINE (1024 * 1024) +#define DC_JSON_MAX_DEPTH 32 + +/* + * UTF-8 validation. Returns 1 for a valid sequence, 0 otherwise (overlong + * forms, surrogates, values above U+10FFFF and truncated sequences are + * invalid). N may be 0; S may be NULL only when N is 0. + */ +int dc_utf8_valid(const char *s, size_t n); + +/* + * A parsed or built JSON value. Opaque; the accessors below are the API. + */ +typedef struct DcJson DcJson; + +typedef enum { + DC_JSON_NULL, + DC_JSON_BOOL, + DC_JSON_INT, + DC_JSON_DOUBLE, + DC_JSON_STRING, + DC_JSON_ARRAY, + DC_JSON_OBJECT +} DcJsonType; + +/* + * Parse one JSON value from LEN bytes. On error returns NULL and writes a + * short message (including the byte offset) into ERR when ERR is not NULL. + * The parser is strict: it rejects trailing data, duplicate object keys, + * unescaped control characters, invalid UTF-8, invalid escapes, a depth + * above DC_JSON_MAX_DEPTH, and input larger than DC_IPC_MAX_LINE. + */ +DcJson *dc_json_parse(const char *text, size_t len, char *err, size_t errlen); + +void dc_json_free(DcJson *json); + +DcJsonType dc_json_type(const DcJson *json); +const char *dc_json_type_name(DcJsonType type); + +/* Constructors; NULL on out of memory. */ +DcJson *dc_json_new_null(void); +DcJson *dc_json_new_bool(int value); +DcJson *dc_json_new_int(long long value); +DcJson *dc_json_new_double(double value); +DcJson *dc_json_new_string(const char *value); /* value is UTF-8 */ +DcJson *dc_json_new_array(void); +DcJson *dc_json_new_object(void); + +/* + * Object/array builders. Both take ownership of VALUE: on success it is + * stored, on failure it is freed and -1 is returned. Setting an existing + * object key replaces the old value. + */ +int dc_json_object_set(DcJson *object, const char *key, DcJson *value); +int dc_json_array_append(DcJson *array, DcJson *value); + +/* + * Accessors. They return NULL/0/-1 when JSON is NULL or the wrong type. + * dc_json_string() returns a pointer into JSON, valid until it is freed. + */ +DcJson *dc_json_get(const DcJson *object, const char *key); +const char *dc_json_string(const DcJson *json); +long long dc_json_int(const DcJson *json); +double dc_json_double(const DcJson *json); +int dc_json_bool(const DcJson *json); + +size_t dc_json_array_size(const DcJson *array); +DcJson *dc_json_array_get(const DcJson *array, size_t index); + +/* + * Serialize to a newly allocated, NUL-terminated UTF-8 string without a + * trailing newline. LEN, when not NULL, receives the string length. The + * caller frees the result with free(3). NULL on out of memory. + */ +char *dc_json_write(const DcJson *json, size_t *len); + +/* + * Line framing for a non-blocking adapter pipe. The buffer owns its + * memory; dc_frame_next() returns a newly allocated line (without '\n' + * and without a trailing '\r') that the caller frees with free(3), or + * NULL when no complete line is buffered. + */ +typedef struct { + char *buf; + size_t len; + size_t cap; +} DcFrameBuf; + +void dc_frame_init(DcFrameBuf *frame); +void dc_frame_reset(DcFrameBuf *frame); +void dc_frame_free(DcFrameBuf *frame); + +/* + * Append N bytes. Returns 0 on success, -1 when the data contains a NUL + * byte or the buffered line would exceed DC_IPC_MAX_LINE. On -1 the + * buffer content is undefined; the caller closes the connection. + */ +int dc_frame_feed(DcFrameBuf *frame, const void *data, size_t n); + +/* + * Return the next complete line (without '\n' and without a trailing + * '\r') or NULL when no line is buffered. The result is newly allocated; + * the caller frees it with free(3). LEN, when not NULL, receives its + * length. + */ +char *dc_frame_next(DcFrameBuf *frame, size_t *len); + +/* Write LINE plus '\n' to FD, handling short writes and EINTR. 0/-1. */ +int dc_frame_send(int fd, const char *line, size_t len); + +#ifdef __cplusplus +} +#endif + +#endif /* _DtChat_Ipc_h */ diff --git a/include/Makefile.am b/include/Makefile.am index daace385..5c5161a0 100644 --- a/include/Makefile.am +++ b/include/Makefile.am @@ -8,6 +8,8 @@ nobase_include_HEADERS = Mcde/GlobalMenu.h \ Mcde/Thumb.h \ Mcde/McdeSys.h \ Mcde/Sound.h \ + DtChat/DtChat.h \ + DtChat/Ipc.h \ Dt/Editor.h \ Dt/TermPrim.h \ Dt/Term.h \ diff --git a/lib/Makefile.am b/lib/Makefile.am index 6ccbac71..1d1bf8d7 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -1,4 +1,4 @@ MAINTAINERCLEANFILES = Makefile.in -SUBDIRS = McdeSys McdeSound DtXinerama tt DtSvc DtSearch DtWidget DtHelp DtPrint DtTerm \ +SUBDIRS = McdeSys McdeSound libDtChat DtXinerama tt DtSvc DtSearch DtWidget DtHelp DtPrint DtTerm \ DtMrm csa DtMmdb diff --git a/lib/libDtChat/Makefile.am b/lib/libDtChat/Makefile.am new file mode 100644 index 00000000..781f578a --- /dev/null +++ b/lib/libDtChat/Makefile.am @@ -0,0 +1,25 @@ +MAINTAINERCLEANFILES = Makefile.in + +# libDtChatIpc: JSON and line framing for adapters (no X, no TLS, no codec). +# libDtChat: the core, which links the IPC part and adds the event loop, +# storage, adapters and the local peer in the later tasks. +lib_LTLIBRARIES = libDtChatIpc.la libDtChat.la + +libDtChatIpc_la_CPPFLAGS = -I$(top_srcdir)/include +libDtChatIpc_la_SOURCES = json.c +libDtChatIpc_la_LDFLAGS = -version-info 1:0:0 + +libDtChat_la_CPPFLAGS = -I$(top_srcdir)/include +libDtChat_la_SOURCES = core.c dc_internal.h +libDtChat_la_LIBADD = libDtChatIpc.la +libDtChat_la_LDFLAGS = -version-info 1:0:0 + +# make check, and tools/mcde-tests.sh from a native build +check_PROGRAMS = test_json test_frame +test_json_SOURCES = test_json.c +test_json_CPPFLAGS = -I$(top_srcdir)/include +test_json_LDADD = libDtChatIpc.la +test_frame_SOURCES = test_frame.c +test_frame_CPPFLAGS = -I$(top_srcdir)/include +test_frame_LDADD = libDtChatIpc.la +TESTS = test_json test_frame diff --git a/lib/libDtChat/core.c b/lib/libDtChat/core.c new file mode 100644 index 00000000..33308cde --- /dev/null +++ b/lib/libDtChat/core.c @@ -0,0 +1,113 @@ +/* + * core.c -- dtchat's core lifecycle (T1.1 stub) + * + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * T1.1 only needs the public API to exist and link. The event loop (T1.2), + * storage (T1.3), conversations (T1.4) and adapters (T1.5) replace the + * stubs below; the signatures are already the ones the UI compiles against. + */ +#include "DtChat/DtChat.h" + +#include +#include + +struct DtChat { + char *dir; +}; + +DtChat * +dtchat_open(const char *config_dir) +{ + DtChat *chat = calloc(1, sizeof(*chat)); + + if (chat == NULL) + return NULL; + chat->dir = strdup(config_dir ? config_dir : ""); + if (chat->dir == NULL) { + free(chat); + return NULL; + } + return chat; +} + +void +dtchat_close(DtChat *chat) +{ + if (chat == NULL) + return; + free(chat->dir); + free(chat); +} + +int +dtchat_fd(const DtChat *chat) +{ + (void)chat; + return -1; +} + +int +dtchat_poll(DtChat *chat, int timeout_ms) +{ + (void)chat; + (void)timeout_ms; + return 0; +} + +DtChatEvent * +dtchat_event_next(DtChat *chat) +{ + (void)chat; + return NULL; +} + +void +dtchat_event_free(DtChatEvent *event) +{ + if (event == NULL) + return; + free(event->account); + free(event->conv); + free(event->from); + free(event->text); + free(event); +} + +int +dtchat_send(DtChat *chat, const char *conv, const char *text) +{ + (void)chat; + (void)conv; + (void)text; + return -1; +} + +int +dtchat_join(DtChat *chat, const char *account, const char *conv) +{ + (void)chat; + (void)account; + (void)conv; + return -1; +} + +int +dtchat_answer(DtChat *chat, const char *account, int request_id, + const char *value) +{ + (void)chat; + (void)account; + (void)request_id; + (void)value; + return -1; +} + +int +dtchat_call(DtChat *chat, const char *peer, int media) +{ + (void)chat; + (void)peer; + (void)media; + return -1; +} diff --git a/lib/libDtChat/dc_internal.h b/lib/libDtChat/dc_internal.h new file mode 100644 index 00000000..5e751c0d --- /dev/null +++ b/lib/libDtChat/dc_internal.h @@ -0,0 +1,14 @@ +/* + * dc_internal.h -- private types of libDtChat + * + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * Nothing here is installed. The public surface is include/DtChat/*.h. + */ +#ifndef _DtChat_dc_internal_h +#define _DtChat_dc_internal_h + +#include "DtChat/DtChat.h" +#include "DtChat/Ipc.h" + +#endif /* _DtChat_dc_internal_h */ diff --git a/lib/libDtChat/json.c b/lib/libDtChat/json.c new file mode 100644 index 00000000..5a41323d --- /dev/null +++ b/lib/libDtChat/json.c @@ -0,0 +1,1271 @@ +/* + * json.c -- the small, strict JSON reader/writer of dtchat's IPC + * + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * The parser is deliberately strict: adapters are other programs, and a + * malformed line must be rejected, not guessed around. The writer builds + * the same subset (null, bool, int, double, string, array, object). + */ +#include "DtChat/Ipc.h" + +#include +#include +#include +#include +#include +#include +#include + +struct DcJson { + DcJsonType type; + union { + int boolean; + long long integer; + double dbl; + char *string; + struct { + DcJson **items; + size_t n, cap; + } array; + struct { + char **keys; + DcJson **values; + size_t n, cap; + } object; + } u; +}; + +/* ------------------------------------------------------------------ */ +/* UTF-8 */ + +/* + * Decode one UTF-8 sequence. Returns 0 on success (and sets *CP and + * *USED), -1 on an invalid, overlong, surrogate or truncated sequence. + */ +static int +utf8_decode_one(const unsigned char *s, size_t n, unsigned *cp, size_t *used) +{ + unsigned c, v, min; + size_t need, i; + + if (n == 0) + return -1; + c = s[0]; + if (c < 0x80) { + *cp = c; + *used = 1; + return 0; + } + if (c >= 0xC2 && c <= 0xDF) { + need = 1; + v = c & 0x1F; + min = 0x80; + } else if (c >= 0xE0 && c <= 0xEF) { + need = 2; + v = c & 0x0F; + min = 0x800; + } else if (c >= 0xF0 && c <= 0xF4) { + need = 3; + v = c & 0x07; + min = 0x10000; + } else { + return -1; + } + if (1 + need > n) + return -1; + for (i = 1; i <= need; i++) { + if ((s[i] & 0xC0) != 0x80) + return -1; + v = (v << 6) | (s[i] & 0x3F); + } + if (v < min || v > 0x10FFFF || (v >= 0xD800 && v <= 0xDFFF)) + return -1; + *cp = v; + *used = 1 + need; + return 0; +} + +int +dc_utf8_valid(const char *s, size_t n) +{ + const unsigned char *p = (const unsigned char *)s; + size_t used; + unsigned cp; + + if (s == NULL) + return n == 0; + while (n > 0) { + if (utf8_decode_one(p, n, &cp, &used) != 0) + return 0; + p += used; + n -= used; + } + return 1; +} + +static int +utf8_encode(unsigned cp, char out[4]) +{ + if (cp < 0x80) { + out[0] = (char)cp; + return 1; + } + if (cp < 0x800) { + out[0] = (char)(0xC0 | (cp >> 6)); + out[1] = (char)(0x80 | (cp & 0x3F)); + return 2; + } + if (cp < 0x10000) { + if (cp >= 0xD800 && cp <= 0xDFFF) + return -1; + out[0] = (char)(0xE0 | (cp >> 12)); + out[1] = (char)(0x80 | ((cp >> 6) & 0x3F)); + out[2] = (char)(0x80 | (cp & 0x3F)); + return 3; + } + if (cp <= 0x10FFFF) { + out[0] = (char)(0xF0 | (cp >> 18)); + out[1] = (char)(0x80 | ((cp >> 12) & 0x3F)); + out[2] = (char)(0x80 | ((cp >> 6) & 0x3F)); + out[3] = (char)(0x80 | (cp & 0x3F)); + return 4; + } + return -1; +} + +/* ------------------------------------------------------------------ */ +/* growable string buffer */ + +typedef struct { + char *p; + size_t len, cap; +} StrBuf; + +static void +sb_init(StrBuf *sb) +{ + sb->p = NULL; + sb->len = 0; + sb->cap = 0; +} + +static void +sb_free(StrBuf *sb) +{ + free(sb->p); + sb->p = NULL; + sb->len = sb->cap = 0; +} + +static int +sb_reserve(StrBuf *sb, size_t extra) +{ + size_t need, cap; + char *np; + + if (extra > SIZE_MAX - sb->len - 1) + return -1; + need = sb->len + extra + 1; + if (need <= sb->cap) + return 0; + cap = sb->cap ? sb->cap : 64; + while (cap < need) { + if (cap > SIZE_MAX / 2) + return -1; + cap *= 2; + } + np = realloc(sb->p, cap); + if (np == NULL) + return -1; + sb->p = np; + sb->cap = cap; + return 0; +} + +static int +sb_putc(StrBuf *sb, char c) +{ + if (sb_reserve(sb, 1) != 0) + return -1; + sb->p[sb->len++] = c; + sb->p[sb->len] = '\0'; + return 0; +} + +static int +sb_putn(StrBuf *sb, const char *s, size_t n) +{ + if (sb_reserve(sb, n) != 0) + return -1; + memcpy(sb->p + sb->len, s, n); + sb->len += n; + sb->p[sb->len] = '\0'; + return 0; +} + +/* ------------------------------------------------------------------ */ +/* constructors and accessors */ + +static DcJson * +json_new(DcJsonType type) +{ + DcJson *j = calloc(1, sizeof(*j)); + if (j != NULL) + j->type = type; + return j; +} + +DcJson * +dc_json_new_null(void) +{ + return json_new(DC_JSON_NULL); +} + +DcJson * +dc_json_new_bool(int value) +{ + DcJson *j = json_new(DC_JSON_BOOL); + if (j != NULL) + j->u.boolean = value != 0; + return j; +} + +DcJson * +dc_json_new_int(long long value) +{ + DcJson *j = json_new(DC_JSON_INT); + if (j != NULL) + j->u.integer = value; + return j; +} + +DcJson * +dc_json_new_double(double value) +{ + DcJson *j; + + if (!isfinite(value)) + return NULL; + j = json_new(DC_JSON_DOUBLE); + if (j != NULL) + j->u.dbl = value; + return j; +} + +DcJson * +dc_json_new_string(const char *value) +{ + DcJson *j; + + if (value == NULL || !dc_utf8_valid(value, strlen(value))) + return NULL; + j = json_new(DC_JSON_STRING); + if (j == NULL) + return NULL; + j->u.string = strdup(value); + if (j->u.string == NULL) { + free(j); + return NULL; + } + return j; +} + +DcJson * +dc_json_new_array(void) +{ + return json_new(DC_JSON_ARRAY); +} + +DcJson * +dc_json_new_object(void) +{ + return json_new(DC_JSON_OBJECT); +} + +DcJsonType +dc_json_type(const DcJson *json) +{ + return json ? json->type : DC_JSON_NULL; +} + +const char * +dc_json_type_name(DcJsonType type) +{ + switch (type) { + case DC_JSON_NULL: return "null"; + case DC_JSON_BOOL: return "bool"; + case DC_JSON_INT: return "int"; + case DC_JSON_DOUBLE: return "double"; + case DC_JSON_STRING: return "string"; + case DC_JSON_ARRAY: return "array"; + case DC_JSON_OBJECT: return "object"; + } + return "?"; +} + +void +dc_json_free(DcJson *json) +{ + size_t i; + + if (json == NULL) + return; + switch (json->type) { + case DC_JSON_STRING: + free(json->u.string); + break; + case DC_JSON_ARRAY: + for (i = 0; i < json->u.array.n; i++) + dc_json_free(json->u.array.items[i]); + free(json->u.array.items); + break; + case DC_JSON_OBJECT: + for (i = 0; i < json->u.object.n; i++) { + free(json->u.object.keys[i]); + dc_json_free(json->u.object.values[i]); + } + free(json->u.object.keys); + free(json->u.object.values); + break; + default: + break; + } + free(json); +} + +DcJson * +dc_json_get(const DcJson *json, const char *key) +{ + size_t i; + + if (json == NULL || json->type != DC_JSON_OBJECT || key == NULL) + return NULL; + for (i = 0; i < json->u.object.n; i++) + if (strcmp(json->u.object.keys[i], key) == 0) + return json->u.object.values[i]; + return NULL; +} + +const char * +dc_json_string(const DcJson *json) +{ + if (json == NULL || json->type != DC_JSON_STRING) + return NULL; + return json->u.string; +} + +long long +dc_json_int(const DcJson *json) +{ + return (json && json->type == DC_JSON_INT) ? json->u.integer : 0; +} + +double +dc_json_double(const DcJson *json) +{ + if (json == NULL) + return 0.0; + if (json->type == DC_JSON_DOUBLE) + return json->u.dbl; + if (json->type == DC_JSON_INT) + return (double)json->u.integer; + return 0.0; +} + +int +dc_json_bool(const DcJson *json) +{ + return (json && json->type == DC_JSON_BOOL) ? json->u.boolean : 0; +} + +size_t +dc_json_array_size(const DcJson *json) +{ + return (json && json->type == DC_JSON_ARRAY) ? json->u.array.n : 0; +} + +DcJson * +dc_json_array_get(const DcJson *json, size_t index) +{ + if (json == NULL || json->type != DC_JSON_ARRAY || + index >= json->u.array.n) + return NULL; + return json->u.array.items[index]; +} + +static int +array_grow(DcJson *array) +{ + size_t cap; + DcJson **items; + + if (array->u.array.n < array->u.array.cap) + return 0; + cap = array->u.array.cap ? array->u.array.cap * 2 : 8; + items = realloc(array->u.array.items, cap * sizeof(*items)); + if (items == NULL) + return -1; + array->u.array.items = items; + array->u.array.cap = cap; + return 0; +} + +int +dc_json_array_append(DcJson *array, DcJson *value) +{ + if (array == NULL || array->type != DC_JSON_ARRAY || value == NULL) { + dc_json_free(value); + return -1; + } + if (array_grow(array) != 0) { + dc_json_free(value); + return -1; + } + array->u.array.items[array->u.array.n++] = value; + return 0; +} + +static int +object_grow(DcJson *object) +{ + size_t cap; + char **keys; + DcJson **values; + + if (object->u.object.n < object->u.object.cap) + return 0; + cap = object->u.object.cap ? object->u.object.cap * 2 : 8; + keys = realloc(object->u.object.keys, cap * sizeof(*keys)); + if (keys == NULL) + return -1; + object->u.object.keys = keys; + values = realloc(object->u.object.values, cap * sizeof(*values)); + if (values == NULL) + return -1; + object->u.object.values = values; + object->u.object.cap = cap; + return 0; +} + +int +dc_json_object_set(DcJson *object, const char *key, DcJson *value) +{ + size_t i; + char *dup; + + if (object == NULL || object->type != DC_JSON_OBJECT || key == NULL || + value == NULL || !dc_utf8_valid(key, strlen(key))) { + dc_json_free(value); + return -1; + } + for (i = 0; i < object->u.object.n; i++) { + if (strcmp(object->u.object.keys[i], key) == 0) { + dc_json_free(object->u.object.values[i]); + object->u.object.values[i] = value; + return 0; + } + } + if (object_grow(object) != 0) { + dc_json_free(value); + return -1; + } + dup = strdup(key); + if (dup == NULL) { + dc_json_free(value); + return -1; + } + object->u.object.keys[object->u.object.n] = dup; + object->u.object.values[object->u.object.n] = value; + object->u.object.n++; + return 0; +} + +/* ------------------------------------------------------------------ */ +/* parser */ + +typedef struct { + const char *start; + const char *p; + const char *end; + int depth; + int failed; + char *err; + size_t errlen; +} Parser; + +static void +perr(Parser *ps, const char *msg) +{ + if (ps->failed) + return; + ps->failed = 1; + if (ps->err != NULL && ps->errlen > 0) + snprintf(ps->err, ps->errlen, "%s at byte %zu", msg, + (size_t)(ps->p - ps->start)); +} + +static void +skip_ws(Parser *ps) +{ + while (ps->p < ps->end) { + char c = *ps->p; + if (c != ' ' && c != '\t' && c != '\n' && c != '\r') + break; + ps->p++; + } +} + +static DcJson *parse_value(Parser *ps); + +static int +hexval(char c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + return -1; +} + +static int +parse_hex4(Parser *ps, unsigned *out) +{ + unsigned v = 0; + int i, h; + + if ((size_t)(ps->end - ps->p) < 4) { + perr(ps, "short \\u escape"); + return -1; + } + for (i = 0; i < 4; i++) { + h = hexval(ps->p[i]); + if (h < 0) { + perr(ps, "bad hex digit"); + return -1; + } + v = (v << 4) | (unsigned)h; + } + ps->p += 4; + *out = v; + return 0; +} + +static char * +parse_string_raw(Parser *ps) +{ + StrBuf sb; + unsigned cp, low; + char utf8[4]; + int n; + + sb_init(&sb); + if (ps->p >= ps->end || *ps->p != '"') { + perr(ps, "expected string"); + return NULL; + } + ps->p++; + while (ps->p < ps->end) { + unsigned char c = (unsigned char)*ps->p; + + if (c == '"') { + ps->p++; + if (sb.p == NULL) + return strdup(""); + return sb.p; + } + if (c == '\\') { + ps->p++; + if (ps->p >= ps->end) { + perr(ps, "short escape"); + goto bad; + } + switch (*ps->p++) { + case '"': c = '"'; break; + case '\\': c = '\\'; break; + case '/': c = '/'; break; + case 'b': c = '\b'; break; + case 'f': c = '\f'; break; + case 'n': c = '\n'; break; + case 'r': c = '\r'; break; + case 't': c = '\t'; break; + case 'u': + if (parse_hex4(ps, &cp) != 0) + goto bad; + if (cp >= 0xD800 && cp <= 0xDBFF) { + if ((size_t)(ps->end - ps->p) < 6 || + ps->p[0] != '\\' || ps->p[1] != 'u') { + perr(ps, "missing low surrogate"); + goto bad; + } + ps->p += 2; + if (parse_hex4(ps, &low) != 0) + goto bad; + if (low < 0xDC00 || low > 0xDFFF) { + perr(ps, "bad low surrogate"); + goto bad; + } + cp = 0x10000 + ((cp - 0xD800) << 10) + + (low - 0xDC00); + } else if (cp >= 0xDC00 && cp <= 0xDFFF) { + perr(ps, "lone low surrogate"); + goto bad; + } + if (cp == 0) { + perr(ps, "NUL in string"); + goto bad; + } + n = utf8_encode(cp, utf8); + if (n < 0 || sb_putn(&sb, utf8, (size_t)n) != 0) { + perr(ps, "bad code point"); + goto bad; + } + continue; + default: + perr(ps, "bad escape"); + goto bad; + } + if (sb_putc(&sb, (char)c) != 0) { + perr(ps, "out of memory"); + goto bad; + } + continue; + } + if (c < 0x20) { + perr(ps, "control character in string"); + goto bad; + } + if (c < 0x80) { + if (sb_putc(&sb, (char)c) != 0) { + perr(ps, "out of memory"); + goto bad; + } + ps->p++; + continue; + } + { + size_t used; + const char *q = ps->p; + + if (utf8_decode_one((const unsigned char *)q, + (size_t)(ps->end - q), &cp, &used) != 0) { + perr(ps, "invalid UTF-8"); + goto bad; + } + if (sb_putn(&sb, q, used) != 0) { + perr(ps, "out of memory"); + goto bad; + } + ps->p += used; + } + } + perr(ps, "unterminated string"); +bad: + sb_free(&sb); + return NULL; +} + +static DcJson * +parse_number(Parser *ps) +{ + const char *start = ps->p; + char *tmp; + char *endptr; + DcJson *j; + int is_int = 1; + + if (ps->p < ps->end && *ps->p == '-') + ps->p++; + if (ps->p >= ps->end) { + perr(ps, "short number"); + return NULL; + } + if (*ps->p == '0') { + ps->p++; + if (ps->p < ps->end && *ps->p >= '0' && *ps->p <= '9') { + perr(ps, "leading zero"); + return NULL; + } + } else if (*ps->p >= '1' && *ps->p <= '9') { + while (ps->p < ps->end && *ps->p >= '0' && *ps->p <= '9') + ps->p++; + } else { + perr(ps, "bad number"); + return NULL; + } + if (ps->p < ps->end && *ps->p == '.') { + is_int = 0; + ps->p++; + if (ps->p >= ps->end || *ps->p < '0' || *ps->p > '9') { + perr(ps, "bad fraction"); + return NULL; + } + while (ps->p < ps->end && *ps->p >= '0' && *ps->p <= '9') + ps->p++; + } + if (ps->p < ps->end && (*ps->p == 'e' || *ps->p == 'E')) { + is_int = 0; + ps->p++; + if (ps->p < ps->end && (*ps->p == '+' || *ps->p == '-')) + ps->p++; + if (ps->p >= ps->end || *ps->p < '0' || *ps->p > '9') { + perr(ps, "bad exponent"); + return NULL; + } + while (ps->p < ps->end && *ps->p >= '0' && *ps->p <= '9') + ps->p++; + } + + tmp = malloc((size_t)(ps->p - start) + 1); + if (tmp == NULL) { + perr(ps, "out of memory"); + return NULL; + } + memcpy(tmp, start, (size_t)(ps->p - start)); + tmp[ps->p - start] = '\0'; + errno = 0; + if (is_int) { + long long v = strtoll(tmp, &endptr, 10); + if (errno == 0 && endptr != tmp && *endptr == '\0') { + free(tmp); + return dc_json_new_int(v); + } + } + errno = 0; + j = dc_json_new_double(strtod(tmp, &endptr)); + if (errno != 0 || endptr == tmp || *endptr != '\0' || + j == NULL) { + perr(ps, "bad number"); + free(tmp); + dc_json_free(j); + return NULL; + } + free(tmp); + return j; +} + +static DcJson * +parse_array(Parser *ps) +{ + DcJson *array; + + if (ps->depth >= DC_JSON_MAX_DEPTH) { + perr(ps, "depth limit"); + return NULL; + } + ps->depth++; + ps->p++; /* '[' */ + array = dc_json_new_array(); + if (array == NULL) { + perr(ps, "out of memory"); + ps->depth--; + return NULL; + } + skip_ws(ps); + if (ps->p < ps->end && *ps->p == ']') { + ps->p++; + ps->depth--; + return array; + } + for (;;) { + DcJson *item; + + skip_ws(ps); + item = parse_value(ps); + if (item == NULL || dc_json_array_append(array, item) != 0) { + if (item == NULL) + perr(ps, "bad array item"); + dc_json_free(array); + ps->depth--; + return NULL; + } + skip_ws(ps); + if (ps->p >= ps->end) { + perr(ps, "unterminated array"); + dc_json_free(array); + ps->depth--; + return NULL; + } + if (*ps->p == ',') { + ps->p++; + skip_ws(ps); + if (ps->p < ps->end && *ps->p == ']') { + perr(ps, "trailing comma"); + dc_json_free(array); + ps->depth--; + return NULL; + } + continue; + } + if (*ps->p == ']') { + ps->p++; + ps->depth--; + return array; + } + perr(ps, "expected ',' or ']'"); + dc_json_free(array); + ps->depth--; + return NULL; + } +} + +static DcJson * +parse_object(Parser *ps) +{ + DcJson *object; + + if (ps->depth >= DC_JSON_MAX_DEPTH) { + perr(ps, "depth limit"); + return NULL; + } + ps->depth++; + ps->p++; /* '{' */ + object = dc_json_new_object(); + if (object == NULL) { + perr(ps, "out of memory"); + ps->depth--; + return NULL; + } + skip_ws(ps); + if (ps->p < ps->end && *ps->p == '}') { + ps->p++; + ps->depth--; + return object; + } + for (;;) { + char *key; + DcJson *value; + + skip_ws(ps); + key = parse_string_raw(ps); + if (key == NULL) { + perr(ps, "bad object key"); + dc_json_free(object); + ps->depth--; + return NULL; + } + skip_ws(ps); + if (ps->p >= ps->end || *ps->p != ':') { + perr(ps, "expected ':'"); + free(key); + dc_json_free(object); + ps->depth--; + return NULL; + } + ps->p++; + skip_ws(ps); + value = parse_value(ps); + if (value == NULL) { + perr(ps, "bad object value"); + free(key); + dc_json_free(object); + ps->depth--; + return NULL; + } + if (dc_json_get(object, key) != NULL) { + perr(ps, "duplicate object key"); + free(key); + dc_json_free(value); + dc_json_free(object); + ps->depth--; + return NULL; + } + if (dc_json_object_set(object, key, value) != 0) { + perr(ps, "out of memory"); + free(key); + dc_json_free(object); + ps->depth--; + return NULL; + } + free(key); + skip_ws(ps); + if (ps->p >= ps->end) { + perr(ps, "unterminated object"); + dc_json_free(object); + ps->depth--; + return NULL; + } + if (*ps->p == ',') { + ps->p++; + skip_ws(ps); + if (ps->p < ps->end && *ps->p == '}') { + perr(ps, "trailing comma"); + dc_json_free(object); + ps->depth--; + return NULL; + } + continue; + } + if (*ps->p == '}') { + ps->p++; + ps->depth--; + return object; + } + perr(ps, "expected ',' or '}'"); + dc_json_free(object); + ps->depth--; + return NULL; + } +} + +static DcJson * +parse_value(Parser *ps) +{ + skip_ws(ps); + if (ps->p >= ps->end) { + perr(ps, "unexpected end"); + return NULL; + } + switch (*ps->p) { + case '{': + return parse_object(ps); + case '[': + return parse_array(ps); + case '"': { + char *s = parse_string_raw(ps); + DcJson *j; + if (s == NULL) + return NULL; + j = dc_json_new_string(s); + free(s); + if (j == NULL) + perr(ps, "out of memory or invalid UTF-8"); + return j; + } + case 't': + if ((size_t)(ps->end - ps->p) >= 4 && + memcmp(ps->p, "true", 4) == 0) { + ps->p += 4; + return dc_json_new_bool(1); + } + break; + case 'f': + if ((size_t)(ps->end - ps->p) >= 5 && + memcmp(ps->p, "false", 5) == 0) { + ps->p += 5; + return dc_json_new_bool(0); + } + break; + case 'n': + if ((size_t)(ps->end - ps->p) >= 4 && + memcmp(ps->p, "null", 4) == 0) { + ps->p += 4; + return dc_json_new_null(); + } + break; + default: + if (*ps->p == '-' || (*ps->p >= '0' && *ps->p <= '9')) + return parse_number(ps); + break; + } + perr(ps, "unexpected token"); + return NULL; +} + +DcJson * +dc_json_parse(const char *text, size_t len, char *err, size_t errlen) +{ + Parser ps; + DcJson *j; + + if (err != NULL && errlen > 0) + err[0] = '\0'; + if (text == NULL) + return NULL; + if (len > DC_IPC_MAX_LINE) { + if (err != NULL && errlen > 0) + snprintf(err, errlen, "line too long (%zu bytes)", len); + return NULL; + } + memset(&ps, 0, sizeof(ps)); + ps.start = text; + ps.p = text; + ps.end = text + len; + ps.err = err; + ps.errlen = errlen; + j = parse_value(&ps); + if (j == NULL) + return NULL; + skip_ws(&ps); + if (ps.p != ps.end) { + perr(&ps, "trailing data"); + dc_json_free(j); + return NULL; + } + return j; +} + +/* ------------------------------------------------------------------ */ +/* writer */ + +static int +write_string(StrBuf *sb, const char *s) +{ + const unsigned char *p = (const unsigned char *)s; + size_t n = strlen(s); + size_t used; + unsigned cp; + char esc[8]; + + if (!dc_utf8_valid(s, n)) + return -1; + if (sb_putc(sb, '"') != 0) + return -1; + while (n > 0) { + unsigned char c = *p; + if (c == '"' || c == '\\') { + if (sb_putc(sb, '\\') != 0 || + sb_putc(sb, (char)c) != 0) + return -1; + p++; + n--; + continue; + } + if (c == '\b') { + if (sb_putn(sb, "\\b", 2) != 0) return -1; + p++; n--; continue; + } + if (c == '\f') { + if (sb_putn(sb, "\\f", 2) != 0) return -1; + p++; n--; continue; + } + if (c == '\n') { + if (sb_putn(sb, "\\n", 2) != 0) return -1; + p++; n--; continue; + } + if (c == '\r') { + if (sb_putn(sb, "\\r", 2) != 0) return -1; + p++; n--; continue; + } + if (c == '\t') { + if (sb_putn(sb, "\\t", 2) != 0) return -1; + p++; n--; continue; + } + if (c < 0x20) { + snprintf(esc, sizeof(esc), "\\u%04x", c); + if (sb_putn(sb, esc, 6) != 0) + return -1; + p++; n--; continue; + } + if (c >= 0x80) { + if (utf8_decode_one(p, n, &cp, &used) != 0) + return -1; + if (sb_putn(sb, (const char *)p, used) != 0) + return -1; + p += used; + n -= used; + continue; + } + if (sb_putc(sb, (char)c) != 0) + return -1; + p++; + n--; + } + return sb_putc(sb, '"'); +} + +static int +write_value(StrBuf *sb, const DcJson *json, int depth) +{ + char num[64]; + size_t i; + + if (json == NULL || depth > DC_JSON_MAX_DEPTH) + return -1; + switch (json->type) { + case DC_JSON_NULL: + return sb_putn(sb, "null", 4); + case DC_JSON_BOOL: + return sb_putn(sb, json->u.boolean ? "true" : "false", + json->u.boolean ? 4 : 5); + case DC_JSON_INT: + snprintf(num, sizeof(num), "%lld", json->u.integer); + return sb_putn(sb, num, strlen(num)); + case DC_JSON_DOUBLE: + if (!isfinite(json->u.dbl)) + return -1; + snprintf(num, sizeof(num), "%.17g", json->u.dbl); + return sb_putn(sb, num, strlen(num)); + case DC_JSON_STRING: + return write_string(sb, json->u.string); + case DC_JSON_ARRAY: + if (sb_putc(sb, '[') != 0) + return -1; + for (i = 0; i < json->u.array.n; i++) { + if (i > 0 && sb_putc(sb, ',') != 0) + return -1; + if (write_value(sb, json->u.array.items[i], + depth + 1) != 0) + return -1; + } + return sb_putc(sb, ']'); + case DC_JSON_OBJECT: + if (sb_putc(sb, '{') != 0) + return -1; + for (i = 0; i < json->u.object.n; i++) { + if (i > 0 && sb_putc(sb, ',') != 0) + return -1; + if (write_string(sb, json->u.object.keys[i]) != 0) + return -1; + if (sb_putc(sb, ':') != 0) + return -1; + if (write_value(sb, json->u.object.values[i], + depth + 1) != 0) + return -1; + } + return sb_putc(sb, '}'); + } + return -1; +} + +char * +dc_json_write(const DcJson *json, size_t *len) +{ + StrBuf sb; + + sb_init(&sb); + if (write_value(&sb, json, 0) != 0) { + sb_free(&sb); + return NULL; + } + if (len != NULL) + *len = sb.len; + return sb.p; +} + +/* ------------------------------------------------------------------ */ +/* line framing */ + +void +dc_frame_init(DcFrameBuf *frame) +{ + frame->buf = NULL; + frame->len = 0; + frame->cap = 0; +} + +void +dc_frame_reset(DcFrameBuf *frame) +{ + frame->len = 0; + if (frame->buf != NULL) + frame->buf[0] = '\0'; +} + +void +dc_frame_free(DcFrameBuf *frame) +{ + free(frame->buf); + frame->buf = NULL; + frame->len = 0; + frame->cap = 0; +} + +static int +frame_reserve(DcFrameBuf *frame, size_t extra) +{ + size_t need, cap; + char *np; + + if (extra > SIZE_MAX - frame->len - 1) + return -1; + need = frame->len + extra + 1; + if (need <= frame->cap) + return 0; + cap = frame->cap ? frame->cap : 1024; + while (cap < need) { + if (cap > SIZE_MAX / 2) + return -1; + cap *= 2; + } + np = realloc(frame->buf, cap); + if (np == NULL) + return -1; + frame->buf = np; + frame->cap = cap; + return 0; +} + +int +dc_frame_feed(DcFrameBuf *frame, const void *data, size_t n) +{ + const char *p = data; + const char *nl; + size_t first; + + if (n == 0) + return 0; + if (memchr(p, '\0', n) != NULL) + return -1; + if (frame_reserve(frame, n) != 0) + return -1; + memcpy(frame->buf + frame->len, p, n); + frame->len += n; + frame->buf[frame->len] = '\0'; + + /* + * A newline may only appear within the first DC_IPC_MAX_LINE bytes. + * If there is none yet, the buffered line must still fit. + */ + nl = memchr(frame->buf, '\n', frame->len); + first = nl != NULL ? (size_t)(nl - frame->buf) : frame->len; + if (first > DC_IPC_MAX_LINE) + return -1; + return 0; +} + +char * +dc_frame_next(DcFrameBuf *frame, size_t *len) +{ + char *nl; + size_t line_len, consume; + char *line; + + if (frame->len == 0) + return NULL; + nl = memchr(frame->buf, '\n', frame->len); + if (nl == NULL) + return NULL; + line_len = (size_t)(nl - frame->buf); + if (line_len > 0 && frame->buf[line_len - 1] == '\r') + line_len--; + line = malloc(line_len + 1); + if (line == NULL) + return NULL; + memcpy(line, frame->buf, line_len); + line[line_len] = '\0'; + + consume = (size_t)(nl - frame->buf) + 1; + memmove(frame->buf, frame->buf + consume, frame->len - consume); + frame->len -= consume; + frame->buf[frame->len] = '\0'; + if (len != NULL) + *len = line_len; + return line; +} + +int +dc_frame_send(int fd, const char *line, size_t len) +{ + size_t off = 0; + ssize_t w; + + if (line == NULL) + return -1; + while (off < len) { + w = write(fd, line + off, len - off); + if (w < 0) { + if (errno == EINTR) + continue; + return -1; + } + off += (size_t)w; + } + while (write(fd, "\n", 1) < 0) { + if (errno != EINTR) + return -1; + } + return 0; +} diff --git a/lib/libDtChat/test_frame.c b/lib/libDtChat/test_frame.c new file mode 100644 index 00000000..77e65e30 --- /dev/null +++ b/lib/libDtChat/test_frame.c @@ -0,0 +1,145 @@ +/* + * test_frame.c -- unit tests for libDtChatIpc's line framing + * + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#include "DtChat/Ipc.h" + +#include +#include +#include +#include + +static int fails; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \ + #cond); \ + fails++; \ + } \ +} while (0) + +static void +feed(DcFrameBuf *frame, const char *s) +{ + CHECK(dc_frame_feed(frame, s, strlen(s)) == 0); +} + +static void +test_lines(void) +{ + DcFrameBuf frame; + char *line; + size_t len; + + dc_frame_init(&frame); + feed(&frame, "hello\n"); + line = dc_frame_next(&frame, &len); + CHECK(line != NULL); + if (line != NULL) { + CHECK(strcmp(line, "hello") == 0); + CHECK(len == 5); + free(line); + } + CHECK(dc_frame_next(&frame, &len) == NULL); + + feed(&frame, "par"); + feed(&frame, "tial\n"); + line = dc_frame_next(&frame, &len); + CHECK(line != NULL && strcmp(line, "partial") == 0); + free(line); + + feed(&frame, "a\nb\n"); + line = dc_frame_next(&frame, &len); + CHECK(line != NULL && strcmp(line, "a") == 0); + free(line); + line = dc_frame_next(&frame, &len); + CHECK(line != NULL && strcmp(line, "b") == 0); + free(line); + CHECK(dc_frame_next(&frame, &len) == NULL); + + feed(&frame, "x\r\n"); + line = dc_frame_next(&frame, &len); + CHECK(line != NULL && strcmp(line, "x") == 0); + CHECK(len == 1); + free(line); + + feed(&frame, "\n"); + line = dc_frame_next(&frame, &len); + CHECK(line != NULL && strcmp(line, "") == 0); + CHECK(len == 0); + free(line); + + dc_frame_free(&frame); +} + +static void +test_bad(void) +{ + DcFrameBuf frame; + char *big; + size_t n; + + dc_frame_init(&frame); + CHECK(dc_frame_feed(&frame, "a\0b", 3) == -1); + dc_frame_free(&frame); + + dc_frame_init(&frame); + n = DC_IPC_MAX_LINE + 2; + big = malloc(n); + if (big == NULL) + return; + memset(big, 'a', n); + CHECK(dc_frame_feed(&frame, big, n) == -1); + dc_frame_free(&frame); + + /* exactly the maximum line length is allowed */ + dc_frame_init(&frame); + big[DC_IPC_MAX_LINE] = '\n'; + CHECK(dc_frame_feed(&frame, big, DC_IPC_MAX_LINE + 1) == 0); + { + char *line = dc_frame_next(&frame, NULL); + CHECK(line != NULL); + if (line != NULL) { + CHECK(strlen(line) == DC_IPC_MAX_LINE); + free(line); + } + } + dc_frame_free(&frame); + free(big); +} + +static void +test_send(void) +{ + int fds[2]; + char buf[32]; + ssize_t n; + + if (pipe(fds) != 0) { + perror("pipe"); + fails++; + return; + } + CHECK(dc_frame_send(fds[1], "abc", 3) == 0); + n = read(fds[0], buf, sizeof(buf)); + CHECK(n == 4); + CHECK(n == 4 && memcmp(buf, "abc\n", 4) == 0); + close(fds[0]); + close(fds[1]); +} + +int +main(void) +{ + test_lines(); + test_bad(); + test_send(); + if (fails != 0) { + fprintf(stderr, "%d test(s) failed\n", fails); + return 1; + } + printf("test_frame: all ok\n"); + return 0; +} diff --git a/lib/libDtChat/test_json.c b/lib/libDtChat/test_json.c new file mode 100644 index 00000000..a7683543 --- /dev/null +++ b/lib/libDtChat/test_json.c @@ -0,0 +1,292 @@ +/* + * test_json.c -- unit tests for libDtChatIpc's JSON reader/writer + * + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#include "DtChat/Ipc.h" + +#include +#include +#include +#include + +static int fails; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \ + #cond); \ + fails++; \ + } \ +} while (0) + +static DcJson * +parse_ok(const char *text) +{ + char err[256]; + DcJson *json = dc_json_parse(text, strlen(text), err, sizeof(err)); + + if (json == NULL) + fprintf(stderr, "parse failed for [%s]: %s\n", text, err); + return json; +} + +static void +expect_bad(const char *text) +{ + char err[256]; + DcJson *json = dc_json_parse(text, strlen(text), err, sizeof(err)); + + if (json != NULL) { + fprintf(stderr, "expected failure for [%s]\n", text); + fails++; + dc_json_free(json); + } +} + +static void +test_basic(void) +{ + DcJson *json = parse_ok("{\"a\":1,\"b\":\"x\",\"c\":true," + "\"d\":false,\"e\":null,\"f\":[1,2,3]}"); + + if (json == NULL) + return; + CHECK(dc_json_type(json) == DC_JSON_OBJECT); + CHECK(dc_json_int(dc_json_get(json, "a")) == 1); + CHECK(strcmp(dc_json_string(dc_json_get(json, "b")), "x") == 0); + CHECK(dc_json_bool(dc_json_get(json, "c")) == 1); + CHECK(dc_json_bool(dc_json_get(json, "d")) == 0); + CHECK(dc_json_type(dc_json_get(json, "e")) == DC_JSON_NULL); + CHECK(dc_json_array_size(dc_json_get(json, "f")) == 3); + CHECK(dc_json_int(dc_json_array_get(dc_json_get(json, "f"), 2)) == 3); + CHECK(dc_json_array_get(dc_json_get(json, "f"), 3) == NULL); + CHECK(dc_json_get(json, "missing") == NULL); + CHECK(dc_json_string(json) == NULL); + dc_json_free(json); +} + +static void +test_strings(void) +{ + DcJson *json = parse_ok("\"\\u00e4 \\u20ac \\ud83d\\ude00\""); + const char *s; + + if (json == NULL) + return; + s = dc_json_string(json); + CHECK(s != NULL); + if (s != NULL) { + CHECK(strcmp(s, "\xc3\xa4 \xe2\x82\xac \xf0\x9f\x98\x80") == 0); + CHECK(dc_utf8_valid(s, strlen(s))); + } + dc_json_free(json); + + json = parse_ok("\"a\\\"b\\\\c\\/d\\b\\f\\n\\r\\t\""); + if (json != NULL) { + CHECK(strcmp(dc_json_string(json), "a\"b\\c/d\b\f\n\r\t") == 0); + dc_json_free(json); + } +} + +static void +test_numbers(void) +{ + DcJson *json = parse_ok("[-9223372036854775808,1.5,1e3,-0]"); + + if (json == NULL) + return; + CHECK(dc_json_type(dc_json_array_get(json, 0)) == DC_JSON_INT); + CHECK(dc_json_int(dc_json_array_get(json, 0)) == (-9223372036854775807LL - 1)); + CHECK(dc_json_double(dc_json_array_get(json, 1)) == 1.5); + CHECK(dc_json_double(dc_json_array_get(json, 2)) == 1000.0); + CHECK(dc_json_type(dc_json_array_get(json, 3)) == DC_JSON_INT); + dc_json_free(json); +} + +static void +test_invalid(void) +{ + expect_bad(""); + expect_bad("{"); + expect_bad("}"); + expect_bad("[]x"); + expect_bad("{\"a\":1,}"); + expect_bad("[1,]"); + expect_bad("{\"a\":1,\"a\":2}"); + expect_bad("\"\\u0000\""); + expect_bad("\"\\ud800\""); + expect_bad("\"\\udc00\""); + expect_bad("\"\\ud800\\ud800\""); + expect_bad("\"\\u12\""); + expect_bad("\"\\q\""); + expect_bad("\"a\nb\""); + expect_bad("01"); + expect_bad("-"); + expect_bad("1."); + expect_bad("1e"); + expect_bad("tru"); + expect_bad("nul"); + expect_bad("{\"a\" 1}"); + expect_bad("{\"a\":}"); +} + +static void +test_utf8(void) +{ + const char bad1[] = "\"\xc0\xaf\""; + const char bad2[] = "\"\xed\xa0\x80\""; + const char good[] = "\"\xc3\xa4\""; + char err[256]; + DcJson *json; + + CHECK(dc_utf8_valid("hello", 5)); + CHECK(dc_utf8_valid("\xc3\xa4", 2)); + CHECK(!dc_utf8_valid("\xc0\xaf", 2)); + CHECK(!dc_utf8_valid("\xed\xa0\x80", 3)); + CHECK(!dc_utf8_valid("\xf4\x90\x80\x80", 4)); + CHECK(!dc_utf8_valid("\xc3", 1)); + + json = dc_json_parse(bad1, sizeof(bad1) - 1, err, sizeof(err)); + CHECK(json == NULL); + json = dc_json_parse(bad2, sizeof(bad2) - 1, err, sizeof(err)); + CHECK(json == NULL); + json = dc_json_parse(good, sizeof(good) - 1, err, sizeof(err)); + CHECK(json != NULL); + dc_json_free(json); +} + +static void +test_depth(void) +{ + char buf[128]; + size_t i; + char err[256]; + DcJson *json; + + for (i = 0; i < 33; i++) + buf[i] = '['; + for (i = 0; i < 33; i++) + buf[33 + i] = ']'; + buf[66] = '\0'; + json = dc_json_parse(buf, 66, err, sizeof(err)); + CHECK(json == NULL); + if (json != NULL) + dc_json_free(json); + + buf[32] = '\0'; + for (i = 0; i < 32; i++) + buf[32 + i] = ']'; + buf[64] = '\0'; + json = dc_json_parse(buf, 64, err, sizeof(err)); + CHECK(json != NULL); + dc_json_free(json); +} + +static void +test_too_long(void) +{ + char *buf = malloc(DC_IPC_MAX_LINE + 1); + char err[256]; + DcJson *json; + + if (buf == NULL) + return; + memset(buf, 'a', DC_IPC_MAX_LINE + 1); + json = dc_json_parse(buf, DC_IPC_MAX_LINE + 1, err, sizeof(err)); + CHECK(json == NULL); + free(buf); +} + +static void +test_writer(void) +{ + DcJson *obj = dc_json_new_object(); + DcJson *arr = dc_json_new_array(); + DcJson *nested = dc_json_new_object(); + char *text; + size_t len; + DcJson *again; + + CHECK(obj != NULL && arr != NULL && nested != NULL); + CHECK(dc_json_object_set(obj, "a", dc_json_new_int(1)) == 0); + CHECK(dc_json_object_set(obj, "b", dc_json_new_string("x")) == 0); + CHECK(dc_json_array_append(arr, dc_json_new_bool(1)) == 0); + CHECK(dc_json_array_append(arr, dc_json_new_null()) == 0); + CHECK(dc_json_object_set(obj, "c", arr) == 0); + CHECK(dc_json_object_set(nested, "e", dc_json_new_int(2)) == 0); + CHECK(dc_json_object_set(obj, "d", nested) == 0); + + text = dc_json_write(obj, &len); + CHECK(text != NULL); + if (text != NULL) { + again = dc_json_parse(text, len, NULL, 0); + CHECK(again != NULL); + if (again != NULL) { + CHECK(dc_json_int(dc_json_get(again, "a")) == 1); + CHECK(strcmp(dc_json_string(dc_json_get(again, "b")), + "x") == 0); + CHECK(dc_json_array_size(dc_json_get(again, "c")) == 2); + CHECK(dc_json_int(dc_json_get( + dc_json_get(again, "d"), "e")) == 2); + dc_json_free(again); + } + free(text); + } + + /* replace an existing key */ + CHECK(dc_json_object_set(obj, "a", dc_json_new_int(3)) == 0); + text = dc_json_write(obj, &len); + CHECK(text != NULL); + if (text != NULL) { + again = dc_json_parse(text, len, NULL, 0); + CHECK(again != NULL); + if (again != NULL) { + CHECK(dc_json_int(dc_json_get(again, "a")) == 3); + dc_json_free(again); + } + free(text); + } + dc_json_free(obj); + + /* escaping round-trip */ + obj = dc_json_new_object(); + CHECK(dc_json_object_set(obj, "s", + dc_json_new_string("a\"b\\c\n\t\xc3\xa4")) == 0); + text = dc_json_write(obj, &len); + CHECK(text != NULL); + if (text != NULL) { + again = dc_json_parse(text, len, NULL, 0); + CHECK(again != NULL); + if (again != NULL) { + CHECK(strcmp(dc_json_string(dc_json_get(again, "s")), + "a\"b\\c\n\t\xc3\xa4") == 0); + dc_json_free(again); + } + free(text); + } + dc_json_free(obj); + + CHECK(dc_json_new_string("\xc0\xaf") == NULL); + CHECK(dc_json_new_double(NAN) == NULL); + CHECK(dc_json_new_double(INFINITY) == NULL); +} + +int +main(void) +{ + test_basic(); + test_strings(); + test_numbers(); + test_invalid(); + test_utf8(); + test_depth(); + test_too_long(); + test_writer(); + if (fails != 0) { + fprintf(stderr, "%d test(s) failed\n", fails); + return 1; + } + printf("test_json: all ok\n"); + return 0; +}