summaryrefslogtreecommitdiffstats
path: root/squark-filter.c
blob: c0d66d96debb9059df67a7dbf6f638058313a206 (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
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <cmph.h>

#include "squarkdb.h"
#include "blob.h"

static int running = 1;
static uint64_t banned_categories = 0;
static const blob_t space = BLOB_STR_INIT(" ");
static const blob_t lf = BLOB_STR_INIT("\n");
static blob_t redirect_page;

struct url_info {
	blob_t protocol;
	blob_t username;
	blob_t password;
	blob_t host;
	blob_t path;
	blob_t query;
	blob_t fragment;
	int port;
};

/* URI is generalized as:
 * [proto://][user[:password]@]domain.name[:port][/[path/to][?p=a&q=b;r=c][#fragment]]
 * Character literals used as separators are:
 *  : / @ ? & ; #
 * Also URI escaping says to treat %XX as encoded hex value.
 */

static int url_parse(blob_t uri, struct url_info *nfo)
{
	blob_t before_colon;
	blob_t word;

	memset(nfo, 0, sizeof(*nfo));

	/* parse protocol, username/password and domain name/port */
	do {
		word = blob_pull_cspn(&uri, BLOB_STR(":@/?"));
		switch (uri.len ? uri.ptr[0] : '/') {
		case ':':
			blob_pull_skip(&uri, 1);
			if (blob_is_null(nfo->protocol) &&
			    blob_pull_matching(&uri, BLOB_STR("//")))
				nfo->protocol = word;
			else
				before_colon = word;
			break;
		case '@':
			blob_pull_skip(&uri, 1);
			if (!blob_is_null(nfo->username) ||
			    !blob_is_null(nfo->password))
				goto error;
			if (!blob_is_null(before_colon)) {
				nfo->username = before_colon;
				nfo->password = word;
			} else
				nfo->username = word;
			before_colon = BLOB_NULL;
			break;
		case '/':
		case '?':
			if (!blob_is_null(before_colon)) {
				nfo->host = before_colon;
				nfo->port = blob_pull_uint(&word, 10);
			} else
				nfo->host = word;
			break;
		}
	} while (blob_is_null(nfo->host) && !blob_is_null(uri));

	/* rest of the components */
	nfo->path = blob_pull_cspn(&uri, BLOB_STR("?&;#"));
	nfo->query = blob_pull_cspn(&uri, BLOB_STR("#"));
	nfo->fragment = uri;

	/* fill in defaults if needed */
	if (blob_is_null(nfo->protocol)) {
		if (nfo->port == 443)
			nfo->protocol = BLOB_STR("https");
		else
			nfo->protocol = BLOB_STR("http");
		if (nfo->port == 0)
			nfo->port = 80;
	} else if (nfo->port == 0) {
		if (blob_cmp(nfo->protocol, BLOB_STR("https")) == 0)
			nfo->port = 443;
		else
			nfo->port = 80;
	}
	if (blob_is_null(nfo->path))
		nfo->path = BLOB_STR("/");

	return 1;
error:
	return 0;
}

static void url_print(struct url_info *nfo)
{
#define print_field(nfo, x) if (!blob_is_null(nfo->x)) printf(" %s{%.*s}", #x, nfo->x.len, nfo->x.ptr)
	print_field(nfo, protocol);
	print_field(nfo, username);
	print_field(nfo, password);
	print_field(nfo, host);
	printf(" port{%d}", nfo->port);
	print_field(nfo, path);
	print_field(nfo, query);
	print_field(nfo, fragment);
#undef print_field
}

static int url_classify(struct url_info *url, struct sqdb *db)
{
	unsigned char buffer[1024];
	blob_t b, key, got, tld, mkey;
	void *cmph;
	struct sqdb_index_entry *indx;
	cmph_uint32 i = -1, previ;

	cmph = sqdb_section_get(db, SQDB_SECTION_INDEX_MPH, NULL);
	indx = sqdb_section_get(db, SQDB_SECTION_INDEX, NULL);

	/* search for most qualified domain match; do first lookup
	 * with two domain components */
	key = BLOB_PTR_LEN(url->host.ptr + url->host.len, 0);
	tld = blob_expand_head(&key, url->host, '.');

	do {
		/* add one more domain component */
		got = blob_expand_head(&key, url->host, '.');
		if (blob_is_null(got))
			break;

		previ = i;
		i = cmph_search_packed(cmph, key.ptr, key.len);
		if (blob_cmp(got, sqdb_get_string_literal(db, indx[i].component)) != 0) {
			/* the subdomain did no longer match, use 
			 * parents classification */
			i = previ;
			goto parent_dns_match;
		}
		if (!blob_is_null(tld)) {
			if (blob_cmp(tld, sqdb_get_string_literal(db, indx[indx[i].parent].component)) != 0) {
				/* top level domain did not match */
				i = -1;
				goto parent_dns_match;
			}
			tld = BLOB_NULL;
		}
		mkey = key;
	} while (indx[i].has_subdomains);

	if (key.ptr != url->host.ptr || !indx[i].has_paths) {
		/* the full dns part did not match, or there's no more
		 * specific paths in db -- skip the path name search */
		goto parent_dns_match;
	}

	/* and then search for path matches -- construct hashing
	 * string of url decoded path */
	b = BLOB_BUF(buffer);
	blob_push(&b, key);
	key = blob_pushed(BLOB_BUF(buffer), b);
	blob_push_urldecode(&b, url->path);
	b = blob_pushed(BLOB_BUF(buffer), b);

	while (indx[i].has_paths) {
		/* add one more path component */
		got = blob_expand_tail(&key, b, '/');
		if (blob_is_null(got))
			break;
		previ = i;
		i = cmph_search_packed(cmph, key.ptr, key.len);
		tld = sqdb_get_string_literal(db, indx[i].component);
		if (blob_cmp(got, sqdb_get_string_literal(db, indx[i].component)) != 0) {
			/* the subdomain did no longer match, use 
			* parents classification */
			i = previ;
			goto parent_dns_match;
		}
		mkey = key;
	}

parent_dns_match:
	if (i == -1)
		return 0; /* no category */

	return indx[i].category;
}

static blob_t get_category_name(struct sqdb *db, int id)
{
	uint32_t *c, clen;

	c = sqdb_section_get(db, SQDB_SECTION_CATEGORIES, &clen);
	if (c == NULL || id < 0 || id * sizeof(uint32_t) >= clen)
		return BLOB_NULL;

	return sqdb_get_string_literal(db, c[id]);
}

static int find_category_id(struct sqdb *db, blob_t cat)
{
	uint32_t size, *ptr;
	int i;

	ptr = sqdb_section_get(db, SQDB_SECTION_CATEGORIES, &size);
	if (ptr == NULL)
		return -1;

	size /= sizeof(uint32_t);
	for (i = 0; i < size; i++)
		if (blob_cmp(cat, sqdb_get_string_literal(db, ptr[i])) == 0)
			return i;

	return -1;
}

static void send_ok(blob_t tag)
{
	static char buffer[64];
	blob_t b = BLOB_BUF(buffer);

	blob_push(&b, tag);
	blob_push(&b, lf);
	b = blob_pushed(BLOB_BUF(buffer), b);

	write(STDOUT_FILENO, b.ptr, b.len);
}

static void send_redirect(struct sqdb *db, blob_t tag, blob_t url, int categ, blob_t username)
{
	static char buffer[8*1024];
	blob_t b = BLOB_BUF(buffer);

	blob_push(&b, tag);
	blob_push(&b, BLOB_STR(" 302:"));
	blob_push(&b, redirect_page);
	blob_push(&b, BLOB_STR("?REASON="));
	blob_push(&b, get_category_name(db, categ));
	blob_push(&b, BLOB_STR("&USER="));
	blob_push(&b, username);
	blob_push(&b, lf);
	b = blob_pushed(BLOB_BUF(buffer), b);

	write(STDOUT_FILENO, b.ptr, b.len);
}

static void read_input(struct sqdb *db)
{
	static char buffer[8 * 1024];
	static blob_t left;

	blob_t b, line, id, url, username;
	struct url_info nfo;
	int r, category;

	if (blob_is_null(left))
		left = BLOB_BUF(buffer);

	r = read(STDIN_FILENO, left.ptr, left.len);
	if (r < 0)
		return;
	if (r == 0) {
		running = 0;
		return;
	}
	left.ptr += r;
	left.len -= r;

	b = blob_pushed(BLOB_BUF(buffer), left);
	do {
		line = blob_pull_cspn(&b, lf);
		if (!blob_pull_matching(&b, lf))
			return;

		id = blob_pull_cspn(&line, space);
		blob_pull_spn(&line, space);
		url = blob_pull_cspn(&line, space);
		blob_pull_spn(&line, space);
		blob_pull_cspn(&line, space); /* client addr / fqdn */
		blob_pull_spn(&line, space);
		username = blob_pull_cspn(&line, space);
		/* http method */
		/* urlgroup */
		/* myaddr=xxx myport=xxx etc */

		if (!blob_is_null(username)) {
			/* valid request, handle it */
			if (url_parse(url, &nfo))
				category = url_classify(&nfo, db);
			else
				category = 0;

			if ((1ULL << category) & banned_categories)
				send_redirect(db, id, url, category, username);
			else
				send_ok(id);
		}

		if (b.len) {
			memcpy(buffer, b.ptr, b.len);
			b.ptr = buffer;
		}
		left = BLOB_PTR_LEN(buffer + b.len, sizeof(buffer) - b.len);
	} while (b.len);
}

static void ban_category(struct sqdb *db, blob_t c)
{
	int category;

	category = find_category_id(db, c);
	if (category >= 0)
		banned_categories |= 1ULL << category;
	else
		fprintf(stderr, "WARNING: unknown category '%.*s'\n",
			c.len, c.ptr);
}

int main(int argc, char **argv)
{
	struct sqdb db;
	int opt;

	sqdb_open(&db, "squark.db");

	while ((opt = getopt(argc, argv, "r:b:")) != -1) {
		switch (opt) {
		case 'r':
			redirect_page = BLOB_STRLEN(optarg);
			break;
		case 'b':
			ban_category(&db, BLOB_STRLEN(optarg));
			break;
		}
	}

	while (running)
		read_input(&db);

	sqdb_close(&db);
}