summaryrefslogtreecommitdiff
path: root/post.c
blob: 27df0dc01ea79cb283df24b2687df8661818efc2 (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
#define _XOPEN_SOURCE 700
#include <search.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "blog.h"

#define HSIZE 4 /* username, password, title, body */

static void add_data(char *buf)
{
	char *value = strchr(buf, '=');
	*value = '\0';
	value++;

	char *key = strdup(buf);
	char *data = strdup(value);

	ENTRY e = {
		.key = key,
		.data = data
	};
	hsearch(e, ENTER);
}

void read_post_data(void)
{
	char *content_length = getenv("CONTENT_LENGTH");
	if (!content_length) {
		return;
	}

	int cl = atoi(content_length);
	if (!cl) {
		return;
	}

	if (!hcreate(HSIZE)) {
		return;
	}

	char *buf = malloc(cl + 1);
	if (!buf) {
		return;
	}

	int pos = 0;
	int c;
	buf[0] = '\0';

	while (pos < cl && (c = getchar()) != EOF) {
		if (c == '&') {
			add_data(buf);
			pos = 0;
		} else if (c == '+') {
			buf[pos] = ' ';
			buf[++pos] = '\0';
		} else if (c == '%') {
			char hex[3] = { 0, 0, 0 };
			hex[0] = getchar();
			hex[1] = getchar();
			buf[pos] = strtol(hex, NULL, 16);
			buf[++pos] = '\0';
		} else {
			buf[pos] = c;
			buf[++pos] = '\0';
		}
	}

	if (pos != 0) {
		add_data(buf);
	}

	free(buf);
}

char *find_post_data(char *key)
{
	ENTRY e = {
		.key = key
	};
	ENTRY *p = hsearch(e, FIND);
	if (p && p->data) {
		return p->data;
	}

	return NULL;
}