aboutsummaryrefslogtreecommitdiff
path: root/src/clog.c
blob: 077fba47a9ebcf62bda24482b9ed46bdfb6eefaf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
#include <ctype.h>

#include <kore/kore.h>
#include <kore/http.h>
#include <kore/pgsql.h>
#include <kore/seccomp.h>

#include "../lib/md4c/src/entity.h"
#include "../lib/md4c/src/entity.c"
#include "../lib/md4c/src/md4c.h"
#include "../lib/md4c/src/md4c.c"
#include "../lib/md4c/src/md4c-html.h"
#include "../lib/md4c/src/md4c-html.c"

#include "assets.h"
// FIXME: Why does compilation fail if this is a .c file?
#include "queries.h"

KORE_SECCOMP_FILTER("clog",
    KORE_SYSCALL_ALLOW(bind),
    KORE_SYSCALL_ALLOW(getdents64),
    KORE_SYSCALL_ALLOW(newfstatat),
    KORE_SYSCALL_ALLOW(sendmmsg),
    KORE_SYSCALL_ALLOW(uname)
)

enum content_type { JSON, HTML };

enum query_status { QUERY_STATUS_OK, QUERY_STATUS_ERROR, QUERY_STATUS_NOT_FOUND };

struct post_query {
	const char *id;
	enum content_type type;

	int status;
	struct kore_buf *result;
};

static const char *accept_json = "application/json";
static const char *database = "db";

static const char * const error_msg[] = {
	[HTTP_STATUS_BAD_REQUEST] = "There was an error processing the request data.",
	[HTTP_STATUS_NOT_FOUND] = "Resource not found.",
	[HTTP_STATUS_INTERNAL_ERROR] = "There was an error processing the request.",
};

void post_query_init(struct post_query *pq);
void post_query_cleanup(struct post_query *pq);

int validate_uuid(const char *uuid);

enum content_type get_content_type(struct http_request *req);

int http_ok_resp(
	struct http_request *req,
	enum content_type type,
	enum http_status_code status,
	struct kore_buf *result
);

int http_err_resp(
	struct http_request *req,
	enum content_type type,
	enum http_status_code status
);

int redirect(struct http_request *req);

int get_posts(struct http_request *req);
int get_posts_resource(struct http_request *req);
int post_posts(struct http_request *req);

int sql_select_posts(struct post_query *pq);
int sql_insert_posts(
	const char *id,
	const char *title,
	const char *body
);
int sql_render_posts(struct kore_pgsql *sql, struct post_query *pq);

static void process_md_output(const MD_CHAR *, MD_SIZE size, void *);
static int render_md(const char *, struct kore_buf *);

void
post_query_init(struct post_query *pq) {
	pq->id = NULL;
	pq->type = JSON;

	pq->status = QUERY_STATUS_OK;
	pq->result = kore_buf_alloc(0);
}

void
post_query_cleanup(struct post_query *pq) {
	if (pq->result != NULL)
		kore_buf_free(pq->result);
	pq->result = NULL;
}

int
validate_uuid(const char *uuid) {
	int i = 0;

	if (strlen(uuid) != 36)
		return KORE_RESULT_ERROR;

	for (i = 0; i <= 36; i++) {
		if ((i == 8) || (i == 13) || (i == 18) || (i == 23)) {
			if (uuid[i] != '-')
				return KORE_RESULT_ERROR;
			continue;
		}
		if (i == 36) {
			if (uuid[i] != '\0')
				return KORE_RESULT_ERROR;
			continue;
		}
		if (!isxdigit(uuid[i]))
			return KORE_RESULT_ERROR;
	}

	return KORE_RESULT_OK;
}

enum content_type
get_content_type(struct http_request *req) {
	int err = 0;

	const char *accept = NULL;

	err = http_request_header(req, "accept", &accept);
	if (err == KORE_RESULT_OK) {
		kore_log(LOG_DEBUG, "Accept: %s", accept);
		if (strncmp(accept, accept_json, sizeof(*accept_json)) == 0)
			return JSON;
	}

	return HTML;
}

int http_ok_resp(
	struct http_request *req,
	enum content_type type,
	enum http_status_code status,
	struct kore_buf *result
) {
	struct kore_buf *resp_buf = kore_buf_alloc(0);
	const char *body = kore_buf_stringify(result, NULL);

	if (type == JSON) {
		http_response_header(req, "content-type", "application/json; charset=utf-8");
		kore_buf_append(
			resp_buf,
			body,
			strlen(body)
		);
	} else {
		http_response_header(req, "content-type", "text/html; charset=utf-8");
		kore_buf_append(resp_buf, asset_index_begin_html, asset_len_index_begin_html);
		kore_buf_append(
			resp_buf,
			body,
			strlen(body)
		);
		kore_buf_append(resp_buf, asset_index_end_html, asset_len_index_end_html);
	}

	http_response(
		req,
		status,
		resp_buf->data,
		resp_buf->offset
	);

	kore_buf_free(resp_buf);

	return KORE_RESULT_OK;
}

int http_err_resp(
	struct http_request *req,
	enum content_type type,
	enum http_status_code status
) {
	struct kore_buf *resp_buf = kore_buf_alloc(0);

	if (type == JSON) {
		http_response_header(req, "content-type", "application/json; charset=utf-8");
		kore_buf_appendf(
			resp_buf,
			(const char *) asset_error_json,
			error_msg[status]
		);
	} else {
		http_response_header(req, "content-type", "text/html; charset=utf-8");
		kore_buf_append(resp_buf, asset_index_begin_html, asset_len_index_begin_html);
		kore_buf_appendf(
			resp_buf,
			(const char *) asset_error_html,
			error_msg[status]
		);
		kore_buf_append(resp_buf, asset_index_end_html, asset_len_index_end_html);
	}

	http_response(
		req,
		status,
		resp_buf->data,
		resp_buf->offset
	);

	kore_buf_free(resp_buf);

	return KORE_RESULT_OK;
}


int
redirect(struct http_request *req) {
	http_response_header(req, "Location", "/");
	http_response(req, HTTP_STATUS_MOVED_PERMANENTLY, NULL, 0);

	return KORE_RESULT_OK;
}

int
get_posts(struct http_request *req) {
	struct post_query pq;

	post_query_init(&pq);
	pq.type = get_content_type(req);

	(void) sql_select_posts(&pq);
	if (pq.status != QUERY_STATUS_OK)
		http_err_resp(req, pq.type, HTTP_STATUS_INTERNAL_ERROR);
	else
		http_ok_resp(req, pq.type, HTTP_STATUS_OK, pq.result);

	post_query_cleanup(&pq);

	return KORE_RESULT_OK;
}

int
get_posts_resource(struct http_request *req) {
	int err = 0;

	struct post_query pq;

	post_query_init(&pq);
	pq.id = req->path + strlen("/posts/");
	pq.type = get_content_type(req);

	// Check for valid resource UUID
	kore_log(LOG_DEBUG, "Resource id /posts/%s.", pq.id);
	err = validate_uuid(pq.id);
	if (err == KORE_RESULT_ERROR) {
		kore_log(LOG_ERR, "Invalid post id %s.", pq.id);
		http_err_resp(req, pq.type, HTTP_STATUS_NOT_FOUND);
		goto out;
	}

	(void) sql_select_posts(&pq);
	if (pq.status == QUERY_STATUS_NOT_FOUND)
		http_err_resp(req, pq.type, HTTP_STATUS_NOT_FOUND);
	else if (pq.status == QUERY_STATUS_ERROR)
		http_err_resp(req, pq.type, HTTP_STATUS_INTERNAL_ERROR);
	else
		http_ok_resp(req, pq.type, HTTP_STATUS_OK, pq.result);

out: ;

	post_query_cleanup(&pq);

	return KORE_RESULT_OK;
}

int
post_posts(struct http_request *req) {
	int err = 0;

	int status = HTTP_STATUS_CREATED;

	enum content_type type = get_content_type(req);

	const char *id = NULL;
	const char *title = NULL;
	const char *body = NULL;

	struct post_query pq;

	struct kore_json_item *item = NULL;
	struct kore_json json;
	kore_json_init(&json, req->http_body->data, req->http_body->length);

	if (!kore_json_parse(&json)) {
		status = HTTP_STATUS_BAD_REQUEST;
		kore_log(LOG_ERR, "error parsing json: %s\n", kore_json_strerror());
		goto out;
	}

	item = kore_json_find_string(json.root, "id");
	if (item != NULL) {
		id = item->data.string;
		kore_log(LOG_INFO, "id = '%s'\n", id);
	} else {
		status = HTTP_STATUS_BAD_REQUEST;
		kore_log(LOG_ERR, "error parsing id: %s\n", kore_json_strerror());
		goto out;
	}

	// Check for valid resource ID/UUID
	err = validate_uuid(id);
	if (err == KORE_RESULT_ERROR) {
		status = HTTP_STATUS_BAD_REQUEST;
		kore_log(LOG_ERR, "Invalid post UUID %s.", id);
		goto out;
	}

	item = kore_json_find_string(json.root, "title");
	if (item != NULL) {
		title = item->data.string;
		kore_log(LOG_INFO, "title = '%s'\n", title);
	} else {
		status = HTTP_STATUS_BAD_REQUEST;
		kore_log(LOG_ERR, "error parsing title: %s\n", kore_json_strerror());
		goto out;
	}

	item = kore_json_find_string(json.root, "body");
	if (item != NULL) {
		body = item->data.string;
		kore_log(LOG_INFO, "body = '%s'\n", body);
	} else {
		status = HTTP_STATUS_BAD_REQUEST;
		kore_log(LOG_ERR, "error parsing body: %s\n", kore_json_strerror());
		goto out;
	}

	err = sql_insert_posts(id, title, body);

	if (err == KORE_RESULT_ERROR) {
		status = HTTP_STATUS_INTERNAL_ERROR;
		goto out;
	}

out: ;

	if (status == HTTP_STATUS_CREATED) {

		post_query_init(&pq);
		pq.id = id;
		pq.type = type;

		(void) sql_select_posts(&pq);
		if (pq.status == QUERY_STATUS_NOT_FOUND)
			http_err_resp(req, pq.type, HTTP_STATUS_NOT_FOUND);
		else if (pq.status == QUERY_STATUS_ERROR)
			http_err_resp(req, pq.type, HTTP_STATUS_INTERNAL_ERROR);
		else
			http_ok_resp(req, pq.type, HTTP_STATUS_OK, pq.result);

		post_query_cleanup(&pq);
	}
	else
		http_err_resp(req, type, status);

	kore_json_cleanup(&json);

	return KORE_RESULT_OK;
}


int
sql_select_posts(struct post_query *pq) {
	int err = 0;

	struct kore_pgsql sql;

	kore_pgsql_init(&sql);

	pq->status = QUERY_STATUS_OK;

	// Set up synchronous database handle.
	err = kore_pgsql_setup(&sql, database, KORE_PGSQL_SYNC);
	if (err == KORE_RESULT_ERROR) {
		pq->status = QUERY_STATUS_ERROR;
		kore_pgsql_logerror(&sql);
		goto out;
	}

	// Query for posts, check for error.
	if (pq->id != NULL) {
		// Query a post.
		err = kore_pgsql_query_params(
			&sql,
			pq->type == HTML ? query_html_post : query_json_post,
			0,  // return string data
			1,  // param count
			KORE_PGSQL_PARAM_TEXT(pq->id)
		);
	} else {
		// Query all posts.
		err = kore_pgsql_query(
			&sql,
			pq->type == HTML ? query_html_posts : query_json_posts
		);
	}

	if (err == KORE_RESULT_ERROR) {
		pq->status = QUERY_STATUS_ERROR;
		kore_pgsql_logerror(&sql);
		goto out;
	}

	// XXX Always tuples from the above Postgres queries, need to check the length for results.
	if (pq->type == JSON && kore_pgsql_getlength(&sql, 0, 0) == 0) {
		pq->status = QUERY_STATUS_NOT_FOUND;
		goto out;
	}

	// TODO: Add test for this; When database is empty, don't return 404 for base request.
	if (pq->id != NULL && kore_pgsql_ntuples(&sql) == 0) {
		pq->status = QUERY_STATUS_NOT_FOUND;
		goto out;
	}

	(void) sql_render_posts(&sql, pq);

out: ;

	kore_pgsql_cleanup(&sql);

	return KORE_RESULT_OK;
}

int sql_render_posts(struct kore_pgsql *sql, struct post_query *pq) {
	int err = 0;

	int row = 0, rows = 0;

	struct kore_buf *html_buf = NULL;

	const char *id = NULL;
	const char *title = NULL;
	const char *created_at = NULL;
	const char *body = NULL;

	if (pq->type == JSON) {
		kore_buf_append(
			pq->result,
			kore_pgsql_getvalue(sql, 0, 0),
			kore_pgsql_getlength(sql, 0, 0)
		);
		return KORE_RESULT_OK;
	}

	// Allocate a buffer to render the markdown as HTML into.
	html_buf = kore_buf_alloc(0);

	// pg->type == HTML
	// Iterate over posts and render them.
	rows = kore_pgsql_ntuples(sql);
	for (row = 0; row < rows; row++) {
		// Reset buffer.
		kore_buf_cleanup(html_buf);

		// Fetch data.
		id = kore_pgsql_getvalue(sql, row, 0);
		title = kore_pgsql_getvalue(sql, row, 1);
		created_at = kore_pgsql_getvalue(sql, row, 2);
		body = kore_pgsql_getvalue(sql, row, 3);
		kore_log(LOG_DEBUG, "id: '%s'; title '%s'", id, title);

		// Render MD.
		err = render_md(body, html_buf);
		if (err == KORE_RESULT_ERROR) {
			kore_log(LOG_ERR, "Error rendering markdown for entry %s.", id);
			continue;
		}

		// Append rendered MD post.
		kore_buf_appendf(
			pq->result,
			(const char *) asset_post_html,
			title,
			created_at,
			kore_buf_stringify(html_buf, NULL)
		);

	}

	kore_buf_free(html_buf);

	return KORE_RESULT_OK;
}

int
sql_insert_posts(
	const char *id,
	const char *title,
	const char *body
) {
	int err = KORE_RESULT_OK;

	struct kore_pgsql sql;
	kore_pgsql_init(&sql);

	err = kore_pgsql_setup(&sql, database, KORE_PGSQL_SYNC);
	if (err == KORE_RESULT_ERROR) {
		kore_pgsql_logerror(&sql);
		goto out;
	}

	err = kore_pgsql_query_params(
		&sql,
		"INSERT INTO posts (id, title, body) "
		"VALUES ($1, $2, $3) RETURNING id;",
		0,
		3,
		KORE_PGSQL_PARAM_TEXT(id),
		KORE_PGSQL_PARAM_TEXT(title),
		KORE_PGSQL_PARAM_TEXT(body)
	);
	if (err == KORE_RESULT_ERROR) {
		kore_pgsql_logerror(&sql);
		goto out;
	}

out: ;

	kore_pgsql_cleanup(&sql);

	return err;
}

static int
render_md(const char *in, struct kore_buf *out) {
	int err = 0;

	static unsigned parser_flags = 0;
	static unsigned renderer_flags = MD_HTML_FLAG_DEBUG;

	err = md_html(
		in,
		(MD_SIZE) strlen(in),
		process_md_output,
		(void*) out,
		parser_flags,
		renderer_flags
	);

	if(err != 0) {
		kore_log(LOG_ERR, "Parsing Markdown failed.");
		return KORE_RESULT_ERROR;
	}

	return KORE_RESULT_OK;
}

static void
process_md_output(const MD_CHAR *html, MD_SIZE size, void *buf) {
	kore_buf_append(
		(struct kore_buf *) buf,
		(const void *) html,
		(size_t) size
	);
}