aboutsummaryrefslogtreecommitdiffstats
path: root/src/rcl/rcl_util.c
blob: acf8bcd6d19f03ad0c665427691251b4f551e9f9 (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
/* Copyright (c) 2013, Vsevolod Stakhov
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *       * Redistributions of source code must retain the above copyright
 *         notice, this list of conditions and the following disclaimer.
 *       * Redistributions in binary form must reproduce the above copyright
 *         notice, this list of conditions and the following disclaimer in the
 *         documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "rcl.h"
#include "rcl_internal.h"
#include "util.h"

#ifdef HAVE_OPENSSL
#include <openssl/err.h>
#include <openssl/sha.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <openssl/evp.h>
#endif

/**
 * @file rcl_util.c
 * Utilities for rcl parsing
 */


static void
rspamd_cl_obj_free_internal (rspamd_cl_object_t *obj, gboolean allow_rec)
{
	rspamd_cl_object_t *sub, *tmp;

	while (obj != NULL) {
		if (obj->key != NULL) {
			g_free (obj->key);
		}

		if (obj->type == RSPAMD_CL_STRING) {
			g_free (obj->value.sv);
		}
		else if (obj->type == RSPAMD_CL_ARRAY) {
			sub = obj->value.ov;
			while (sub != NULL) {
				tmp = sub->next;
				rspamd_cl_obj_free_internal (sub, FALSE);
				sub = tmp;
			}
		}
		else if (obj->type == RSPAMD_CL_OBJECT) {
			HASH_ITER (hh, obj->value.ov, sub, tmp) {
				HASH_DELETE (hh, obj->value.ov, sub);
				rspamd_cl_obj_free_internal (sub, TRUE);
			}
		}
		tmp = obj->next;
		g_slice_free1 (sizeof (rspamd_cl_object_t), obj);
		obj = tmp;

		if (!allow_rec) {
			break;
		}
	}
}

void
rspamd_cl_obj_free (rspamd_cl_object_t *obj)
{
	rspamd_cl_obj_free_internal (obj, TRUE);
}

void
rspamd_cl_unescape_json_string (gchar *str)
{
	gchar *t = str, *h = str;
	gint i, uval;

	/* t is target (tortoise), h is source (hare) */

	while (*h != '\0') {
		if (*h == '\\') {
			h ++;
			switch (*h) {
			case 'n':
				*t++ = '\n';
				break;
			case 'r':
				*t++ = '\r';
				break;
			case 'b':
				*t++ = '\b';
				break;
			case 't':
				*t++ = '\t';
				break;
			case 'f':
				*t++ = '\f';
				break;
			case '\\':
				*t++ = '\\';
				break;
			case '"':
				*t++ = '"';
				break;
			case 'u':
				/* Unicode escape */
				uval = 0;
				for (i = 0; i < 4; i++) {
					uval <<= 4;
					if (g_ascii_isdigit (h[i])) {
						uval += h[i] - '0';
					}
					else if (h[i] >= 'a' && h[i] <= 'f') {
						uval += h[i] - 'a' + 10;
					}
					else if (h[i] >= 'A' && h[i] <= 'F') {
						uval += h[i] - 'A' + 10;
					}
				}
				h += 3;
				/* Encode */
				if(uval < 0x80) {
					t[0] = (char)uval;
					t ++;
				}
				else if(uval < 0x800) {
					t[0] = 0xC0 + ((uval & 0x7C0) >> 6);
					t[1] = 0x80 + ((uval & 0x03F));
					t += 2;
				}
				else if(uval < 0x10000) {
					t[0] = 0xE0 + ((uval & 0xF000) >> 12);
					t[1] = 0x80 + ((uval & 0x0FC0) >> 6);
					t[2] = 0x80 + ((uval & 0x003F));
					t += 3;
				}
				else if(uval <= 0x10FFFF) {
					t[0] = 0xF0 + ((uval & 0x1C0000) >> 18);
					t[1] = 0x80 + ((uval & 0x03F000) >> 12);
					t[2] = 0x80 + ((uval & 0x000FC0) >> 6);
					t[3] = 0x80 + ((uval & 0x00003F));
					t += 4;
				}
				else {
					*t++ = '?';
				}
				break;
			default:
				*t++ = '?';
				break;
			}
			h ++;
		}
		else {
			*t++ = *h++;
		}
	}
}

rspamd_cl_object_t*
rspamd_cl_parser_get_object (struct rspamd_cl_parser *parser, GError **err)
{
	if (parser->state != RSPAMD_RCL_STATE_INIT && parser->state != RSPAMD_RCL_STATE_ERROR) {
		return parser->top_obj;
	}

	return NULL;
}

void
rspamd_cl_parser_free (struct rspamd_cl_parser *parser)
{
	struct rspamd_cl_stack *stack, *stmp;
	struct rspamd_cl_macro *macro, *mtmp;
	struct rspamd_cl_chunk *chunk, *ctmp;
	struct rspamd_cl_pubkey *key, *ktmp;

	if (parser->top_obj != NULL) {
		rspamd_cl_obj_free (parser->top_obj);
	}

	LL_FOREACH_SAFE (parser->stack, stack, stmp) {
		g_slice_free1 (sizeof (struct rspamd_cl_stack), stack);
	}
	HASH_ITER (hh, parser->macroes, macro, mtmp) {
		g_slice_free1 (sizeof (struct rspamd_cl_macro), macro);
	}
	LL_FOREACH_SAFE (parser->chunks, chunk, ctmp) {
		g_slice_free1 (sizeof (struct rspamd_cl_chunk), chunk);
	}
	LL_FOREACH_SAFE (parser->keys, key, ktmp) {
		g_slice_free1 (sizeof (struct rspamd_cl_pubkey), key);
	}

	g_slice_free1 (sizeof (struct rspamd_cl_parser), parser);
}

gboolean
rspamd_cl_pubkey_add (struct rspamd_cl_parser *parser, const guchar *key, gsize len, GError **err)
{
	struct rspamd_cl_pubkey *nkey;
#ifndef HAVE_OPENSSL
	g_set_error (err, RCL_ERROR, RSPAMD_CL_EINTERNAL, "cannot check signatures without openssl");
	return FALSE;
#else
	BIO *mem;

	mem = BIO_new_mem_buf ((void *)key, len);
	nkey = g_slice_alloc0 (sizeof (struct rspamd_cl_pubkey));
	nkey->key = PEM_read_bio_PUBKEY (mem, &nkey->key, NULL, NULL);
	BIO_free (mem);
	if (nkey->key == NULL) {
		g_slice_free1 (sizeof (struct rspamd_cl_pubkey), nkey);
		g_set_error (err, RCL_ERROR, RSPAMD_CL_ESSL, "%s",
				ERR_error_string (ERR_get_error (), NULL));
		return FALSE;
	}
	LL_PREPEND (parser->keys, nkey);
#endif
	return TRUE;
}

#ifdef CURL_FOUND
struct rspamd_cl_curl_cbdata {
	guchar *buf;
	gsize buflen;
};

static gsize
rspamd_cl_curl_write_callback (gpointer contents, gsize size, gsize nmemb, gpointer ud)
{
	struct rspamd_cl_curl_cbdata *cbdata = ud;
	gsize realsize = size * nmemb;

	cbdata->buf = g_realloc (cbdata->buf, cbdata->buflen + realsize + 1);
	if (cbdata->buf == NULL) {
		return 0;
	}

	memcpy (&(cbdata->buf[cbdata->buflen]), contents, realsize);
	cbdata->buflen += realsize;
	cbdata->buf[cbdata->buflen] = 0;

	return realsize;
}
#endif

/**
 * Fetch a url and save results to the memory buffer
 * @param url url to fetch
 * @param len length of url
 * @param buf target buffer
 * @param buflen target length
 * @return
 */
static gboolean
rspamd_cl_fetch_url (const guchar *url, gsize len, guchar **buf, gsize *buflen, GError **err)
{
	char urlbuf[PATH_MAX];

	rspamd_snprintf (urlbuf, sizeof (urlbuf), "%*s", len, url);

#ifdef HAVE_FETCH_H
	struct url *fetch_url;
	struct url_stat us;
	FILE *in;
	guchar *buf;

	fetch_url = fetchParseURL (urlbuf);
	if (fetch_url == NULL) {
		g_set_error (err, RCL_ERROR, RSPAMD_CL_EIO, "invalid URL %s: %s",
				urlbuf, strerror (errno));
		return FALSE;
	}
	if ((in = fetchXGet (fetch_url, &us, "")) == NULL) {
		g_set_error (err, RCL_ERROR, RSPAMD_CL_EIO, "cannot fetch URL %s: %s",
				urlbuf, strerror (errno));
		fetchFreeURL (fetch_url);
		return FALSE;
	}

	*buflen = us.size;
	*buf = g_malloc (*buflen);
	if (buf == NULL) {
		g_set_error (err, RCL_ERROR, RSPAMD_CL_EIO, "cannot allocate buffer for URL %s: %s",
				urlbuf, strerror (errno));
		fclose (in);
		fetchFreeURL (fetch_url);
		return FALSE;
	}

	if (fread (*buf, *buflen, 1, in) != 1) {
		g_set_error (err, RCL_ERROR, RSPAMD_CL_EIO, "cannot read URL %s: %s",
				urlbuf, strerror (errno));
		fclose (in);
		fetchFreeURL (fetch_url);
		return FALSE;
	}

	fetchFreeURL (fetch_url);
	return TRUE;
#elif defined(CURL_FOUND)
	CURL *curl;
	gint r;
	struct rspamd_cl_curl_cbdata cbdata;

	curl = curl_easy_init ();
	if (curl == NULL) {
		g_set_error (err, RCL_ERROR, RSPAMD_CL_EINTERNAL, "CURL interface is broken");
		return FALSE;
	}
	if ((r = curl_easy_setopt (curl, CURLOPT_URL, urlbuf)) != CURLE_OK) {
		g_set_error (err, RCL_ERROR, RSPAMD_CL_EIO, "invalid URL %s: %s",
						urlbuf, curl_easy_strerror (r));
		curl_easy_cleanup (curl);
		return FALSE;
	}
	curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, rspamd_cl_curl_write_callback);
	cbdata.buf = *buf;
	cbdata.buflen = *buflen;
	curl_easy_setopt (curl, CURLOPT_WRITEDATA, &cbdata);

	if ((r = curl_easy_perform (curl)) != CURLE_OK) {
		g_set_error (err, RCL_ERROR, RSPAMD_CL_EIO, "error fetching URL %s: %s",
				urlbuf, curl_easy_strerror (r));
		curl_easy_cleanup (curl);
		if (buf != NULL) {
			g_free (buf);
		}
		return FALSE;
	}
	*buf = cbdata.buf;
	*buflen = cbdata.buflen;

	return TRUE;
#else
	g_set_error (err, RCL_ERROR, RSPAMD_CL_EINTERNAL, "URL support is disabled");
	return FALSE;
#endif
}

/**
 * Fetch a file and save results to the memory buffer
 * @param filename filename to fetch
 * @param len length of filename
 * @param buf target buffer
 * @param buflen target length
 * @return
 */
static gboolean
rspamd_cl_fetch_file (const guchar *filename, gsize len, guchar **buf, gsize *buflen, GError **err)
{
	gint fd;
	struct stat st;
	char filebuf[PATH_MAX];

	rspamd_snprintf (filebuf, sizeof (filebuf), "%*s", len, filename);
	if (stat (filebuf, &st) == -1) {
		g_set_error (err, RCL_ERROR, RSPAMD_CL_EIO, "cannot stat file %s: %s",
				filebuf, strerror (errno));
		return FALSE;
	}
	if ((fd = open (filebuf, O_RDONLY)) == -1) {
		g_set_error (err, RCL_ERROR, RSPAMD_CL_EIO, "cannot open file %s: %s",
				filebuf, strerror (errno));
		return FALSE;
	}
	if ((*buf = mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
		close (fd);
		g_set_error (err, RCL_ERROR, RSPAMD_CL_EIO, "cannot mmap file %s: %s",
				filebuf, strerror (errno));
		return FALSE;
	}
	*buflen = st.st_size;
	close (fd);

	return TRUE;
}

/**
 * Include an url to configuration
 * @param data
 * @param len
 * @param parser
 * @param err
 * @return
 */
static gboolean
rspamd_cl_include_url (const guchar *data, gsize len, struct rspamd_cl_parser *parser, GError **err)
{

	gboolean res;
	guchar *buf = NULL;
	gsize buflen = 0;
	struct rspamd_cl_chunk *chunk;


	if (!rspamd_cl_fetch_url (data, len, &buf, &buflen, err)) {
		return FALSE;
	}

	res = rspamd_cl_parser_add_chunk (parser, buf, buflen, err);
	if (res == TRUE) {
		/* Remove chunk from the stack */
		chunk = parser->chunks;
		if (chunk != NULL) {
			parser->chunks = chunk->next;
			g_slice_free1 (sizeof (struct rspamd_cl_chunk), chunk);
		}
	}
	g_free (buf);

	return res;
}

/**
 * Include a file to configuration
 * @param data
 * @param len
 * @param parser
 * @param err
 * @return
 */
static gboolean
rspamd_cl_include_file (const guchar *data, gsize len, struct rspamd_cl_parser *parser, GError **err)
{
	gboolean res;
	struct rspamd_cl_chunk *chunk;
	guchar *buf = NULL;
	gsize buflen;

	if (!rspamd_cl_fetch_file (data, len, &buf, &buflen, err)) {
		return FALSE;
	}

	res = rspamd_cl_parser_add_chunk (parser, buf, buflen, err);
	if (res == TRUE) {
		/* Remove chunk from the stack */
		chunk = parser->chunks;
		if (chunk != NULL) {
			parser->chunks = chunk->next;
			g_slice_free1 (sizeof (struct rspamd_cl_chunk), chunk);
		}
	}
	munmap (buf, buflen);

	return res;
}

/**
 * Handle include macro
 * @param data include data
 * @param len length of data
 * @param ud user data
 * @param err error ptr
 * @return
 */
gboolean
rspamd_cl_include_handler (const guchar *data, gsize len, gpointer ud, GError **err)
{
	struct rspamd_cl_parser *parser = ud;

	if (*data == '/') {
		/* Try to load a file */
		return rspamd_cl_include_file (data, len, parser, err);
	}

	return rspamd_cl_include_url (data, len, parser, err);
}

/**
 * Handle includes macro
 * @param data include data
 * @param len length of data
 * @param ud user data
 * @param err error ptr
 * @return
 */
gboolean
rspamd_cl_includes_handler (const guchar *data, gsize len, gpointer ud, GError **err)
{
	struct rspamd_cl_parser *parser = ud;

	return TRUE;
}