aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/surbl.c
blob: 0fe64ba2fa09f13ac26feddfd2a242dfb496b324 (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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
/*
 * Copyright (c) 2009, Rambler media
 * 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 BY Rambler media ''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 Rambler 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.
 */

/***MODULE:surbl
 * rspamd module that implements SURBL url checking
 */

#include "../config.h"
#include "../util.h"
#include <evdns.h>

#include "surbl.h"

static char *hash_fill = "1";
struct surbl_ctx *surbl_module_ctx;
GRegex *extract_hoster_regexp, *extract_normal_regexp, *extract_numeric_regexp;

static int surbl_test_url (struct worker_task *task);
static void dns_callback (int result, char type, int count, int ttl, void *addresses, void *data);

int
surbl_module_init (struct config_file *cfg, struct module_ctx **ctx)
{
	GError *err = NULL;

	surbl_module_ctx = g_malloc (sizeof (struct surbl_ctx));

	surbl_module_ctx->header_filter = NULL;
	surbl_module_ctx->mime_filter = NULL;
	surbl_module_ctx->message_filter = NULL;
	surbl_module_ctx->url_filter = surbl_test_url;
	surbl_module_ctx->use_redirector = 0;
	surbl_module_ctx->suffixes = NULL;
	surbl_module_ctx->bits = NULL;
	surbl_module_ctx->surbl_pool = memory_pool_new (1024);
	
	surbl_module_ctx->hosters = g_hash_table_new (g_str_hash, g_str_equal);
	/* Register destructors */
	memory_pool_add_destructor (surbl_module_ctx->surbl_pool, (pool_destruct_func)g_hash_table_remove_all, surbl_module_ctx->hosters);

	surbl_module_ctx->whitelist = g_hash_table_new (g_str_hash, g_str_equal);
	/* Register destructors */
	memory_pool_add_destructor (surbl_module_ctx->surbl_pool, (pool_destruct_func)g_hash_table_remove_all, surbl_module_ctx->whitelist);
	memory_pool_add_destructor (surbl_module_ctx->surbl_pool, (pool_destruct_func)g_list_free, surbl_module_ctx->suffixes);
	memory_pool_add_destructor (surbl_module_ctx->surbl_pool, (pool_destruct_func)g_list_free, surbl_module_ctx->bits);
		
	/* Init matching regexps */
	extract_hoster_regexp = g_regex_new ("([^.]+)\\.([^.]+)\\.([^.]+)$", G_REGEX_RAW, 0, &err);
	extract_normal_regexp = g_regex_new ("([^.]+)\\.([^.]+)$", G_REGEX_RAW, 0, &err);
	extract_numeric_regexp = g_regex_new ("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$", G_REGEX_RAW, 0, &err);

	*ctx = (struct module_ctx *)surbl_module_ctx;

	return 0;
}

int
surbl_module_config (struct config_file *cfg)
{
	struct hostent *hent;
	LIST_HEAD (moduleoptq, module_opt) *opt = NULL;
	struct module_opt *cur;
	struct suffix_item *new_suffix;
	struct surbl_bit_item *new_bit;

	char *value, *cur_tok, *str;
	uint32_t bit;

	evdns_init ();

	if ((value = get_module_opt (cfg, "surbl", "redirector")) != NULL) {
		str = memory_pool_strdup (surbl_module_ctx->surbl_pool, value);
		cur_tok = strsep (&str, ":");
		if (!inet_aton (cur_tok, &surbl_module_ctx->redirector_addr)) {
			/* Try to call gethostbyname */
			hent = gethostbyname (cur_tok);
			if (hent != NULL) {
				memcpy((char *)&surbl_module_ctx->redirector_addr, hent->h_addr, sizeof(struct in_addr));
				if (str != NULL) {
					surbl_module_ctx->redirector_port = (uint16_t)strtoul (str, NULL, 10);
				}
				else {
					surbl_module_ctx->redirector_port = DEFAULT_REDIRECTOR_PORT;
				}
				surbl_module_ctx->use_redirector = 1;
			}
		}
	}
	if ((value = get_module_opt (cfg, "surbl", "weight")) != NULL) {
		surbl_module_ctx->weight = atoi (value);
	}
	else {
		surbl_module_ctx->weight = DEFAULT_SURBL_WEIGHT;
	}
	if ((value = get_module_opt (cfg, "surbl", "url_expire")) != NULL) {
		surbl_module_ctx->url_expire = atoi (value);
	}
	else {
		surbl_module_ctx->url_expire = DEFAULT_SURBL_URL_EXPIRE;
	}
	if ((value = get_module_opt (cfg, "surbl", "redirector_connect_timeout")) != NULL) {
		surbl_module_ctx->connect_timeout = parse_seconds (value);
	}
	else {
		surbl_module_ctx->connect_timeout = DEFAULT_REDIRECTOR_CONNECT_TIMEOUT;
	}
	if ((value = get_module_opt (cfg, "surbl", "redirector_read_timeout")) != NULL) {
		surbl_module_ctx->read_timeout = parse_seconds (value);
	}
	else {
		surbl_module_ctx->read_timeout = DEFAULT_REDIRECTOR_READ_TIMEOUT;
	}
	if ((value = get_module_opt (cfg, "surbl", "max_urls")) != NULL) {
		surbl_module_ctx->max_urls = atoi (value);
	}
	else {
		surbl_module_ctx->max_urls = DEFAULT_SURBL_MAX_URLS;
	}
	if ((value = get_module_opt (cfg, "surbl", "metric")) != NULL) {
		surbl_module_ctx->metric = memory_pool_strdup (surbl_module_ctx->surbl_pool, value);
	}
	else {
		surbl_module_ctx->metric = DEFAULT_METRIC;
	}
	if ((value = get_module_opt (cfg, "surbl", "hostings")) != NULL) {
		char comment_flag = 0;
		str = value;
		while (*value ++) {
			if (*value == '#') {
				comment_flag = 1;
			}
			if (*value == '\r' || *value == '\n' || *value == ',') {
				if (!comment_flag && str != value) {
					g_hash_table_insert (surbl_module_ctx->hosters, g_strstrip(str), hash_fill);
					str = value + 1;
				}
				else if (*value != ',') {
					comment_flag = 0;
					str = value + 1;
				}
			}
		}
	}
	if ((value = get_module_opt (cfg, "surbl", "whitelist")) != NULL) {
		char comment_flag = 0;
		str = value;
		while (*value ++) {
			if (*value == '#') {
				comment_flag = 1;
			}
			if (*value == '\r' || *value == '\n' || *value == ',') {
				if (!comment_flag && str != value) {
					g_hash_table_insert (surbl_module_ctx->whitelist, g_strstrip(str), hash_fill);
					str = value + 1;
				}
				else if (*value != ',') {
					comment_flag = 0;
					str = value + 1;
				}
			}
		}
	}
	
	opt = g_hash_table_lookup (cfg->modules_opts, "surbl");
	if (opt) {
		LIST_FOREACH (cur, opt, next) {
			if (!g_strncasecmp (cur->param, "suffix", sizeof ("suffix") - 1)) {
				if ((str = strchr (cur->param, '_')) != NULL) {
					new_suffix = memory_pool_alloc (surbl_module_ctx->surbl_pool, sizeof (struct suffix_item));
					*str = '\0';
					new_suffix->symbol = memory_pool_strdup (surbl_module_ctx->surbl_pool, str + 1);
					new_suffix->suffix = memory_pool_strdup (surbl_module_ctx->surbl_pool, cur->value);
					msg_debug ("surbl_module_config: add new surbl suffix: %s with symbol: %s", 
								new_suffix->suffix, new_suffix->symbol);
					*str = '_';
					surbl_module_ctx->suffixes = g_list_prepend (surbl_module_ctx->suffixes, new_suffix);
				}
			}
			if (!g_strncasecmp (cur->param, "bit", sizeof ("bit") - 1)) {
				if ((str = strchr (cur->param, '_')) != NULL) {
					bit = strtoul (str + 1, NULL, 10);
					if (bit != 0) {
						new_bit = memory_pool_alloc (surbl_module_ctx->surbl_pool, sizeof (struct surbl_bit_item));
						new_bit->bit = bit;
						new_bit->symbol = memory_pool_strdup (surbl_module_ctx->surbl_pool, cur->value);
						msg_debug ("surbl_module_config: add new bit suffix: %d with symbol: %s", 
									(int)new_bit->bit, new_bit->symbol);
						surbl_module_ctx->bits = g_list_prepend (surbl_module_ctx->bits, new_bit);
					}
				}
			}
		}
	}
	/* Add default suffix */
	if (surbl_module_ctx->suffixes == NULL) {
		new_suffix = memory_pool_alloc (surbl_module_ctx->surbl_pool, sizeof (struct suffix_item));
		new_suffix->suffix = memory_pool_strdup (surbl_module_ctx->surbl_pool, DEFAULT_SURBL_SUFFIX);
		new_suffix->symbol = memory_pool_strdup (surbl_module_ctx->surbl_pool, DEFAULT_SURBL_SYMBOL);
		msg_debug ("surbl_module_config: add default surbl suffix: %s with symbol: %s", 
								new_suffix->suffix, new_suffix->symbol);
		surbl_module_ctx->suffixes = g_list_prepend (surbl_module_ctx->suffixes, new_suffix);
	}

	return 0;
}

int
surbl_module_reconfig (struct config_file *cfg)
{
	memory_pool_delete (surbl_module_ctx->surbl_pool);
	surbl_module_ctx->surbl_pool = memory_pool_new (1024);

	return surbl_module_config (cfg);
}

static char *
format_surbl_request (memory_pool_t *pool, f_str_t *hostname, struct suffix_item *suffix) 
{
	GMatchInfo *info;
	char *result = NULL;
    int len;
    
    len = hostname->len + strlen (suffix->suffix) + 2;

	/* First try to match numeric expression */
	if (g_regex_match_full (extract_numeric_regexp, hostname->begin, hostname->len, 0, 0, &info, NULL) == TRUE) {
		gchar *octet1, *octet2, *octet3, *octet4;
		octet1 = g_match_info_fetch (info, 1);
		octet2 = g_match_info_fetch (info, 2);
		octet3 = g_match_info_fetch (info, 3);
		octet4 = g_match_info_fetch (info, 4);
		result = memory_pool_alloc (pool, len); 
		msg_debug ("format_surbl_request: got numeric host for check: %s.%s.%s.%s", octet1, octet2, octet3, octet4);
		snprintf (result, len, "%s.%s.%s.%s.%s", octet4, octet3, octet2, octet1, suffix->suffix);
		g_free (octet1);
		g_free (octet2);
		g_free (octet3);
		g_free (octet4);
		g_match_info_free (info);
		return result;
	}
	g_match_info_free (info);
	/* Try to match normal domain */
	if (g_regex_match_full (extract_normal_regexp, hostname->begin, hostname->len, 0, 0, &info, NULL) == TRUE) {
		gchar *part1, *part2;
		part1 = g_match_info_fetch (info, 1);
		part2 = g_match_info_fetch (info, 2);
		g_match_info_free (info);
		result = memory_pool_alloc (pool, len); 
		snprintf (result, len, "%s.%s", part1, part2);
		if (g_hash_table_lookup (surbl_module_ctx->hosters, result) != NULL) {
			/* Match additional part for hosters */
			g_free (part1);
			g_free (part2);
			g_match_info_free (info);
			if (g_regex_match_full (extract_hoster_regexp, hostname->begin, hostname->len, 0, 0, &info, NULL) == TRUE) {
				gchar *hpart1, *hpart2, *hpart3;
				hpart1 = g_match_info_fetch (info, 1);
				hpart2 = g_match_info_fetch (info, 2);
				hpart3 = g_match_info_fetch (info, 3);
				msg_debug ("format_surbl_request: got hoster 3-d level domain %s.%s.%s", hpart1, hpart2, hpart3);
				snprintf (result, len, "%s.%s.%s.%s", hpart1, hpart2, hpart3, suffix->suffix);
				g_free (hpart1);
				g_free (hpart2);
				g_free (hpart3);
				g_match_info_free (info);
				return result;
			}
			g_match_info_free (info);
			return NULL;
		}
		else {
			snprintf (result, len, "%s.%s.%s", part1, part2, suffix->suffix);
			msg_debug ("format_surbl_request: got normal 2-d level domain %s.%s", part1, part2);
		}
		g_free (part1);
		g_free (part2);
		return result;
	}

	g_match_info_free (info);
	return NULL;
}

static void 
make_surbl_requests (struct uri* url, struct worker_task *task, GTree *tree)
{	
	char *surbl_req;
	f_str_t f;
	GList *cur;
	struct dns_param *param;

	cur = g_list_first (surbl_module_ctx->suffixes);
	f.begin = url->host;
	f.len = url->hostlen;

	while (cur) {
		param = memory_pool_alloc (task->task_pool, sizeof (struct dns_param));
		param->url = url;
		param->task = task;
		param->suffix = (struct suffix_item *)cur->data;
		if ((surbl_req = format_surbl_request (task->task_pool, &f, (struct suffix_item *)cur->data)) != NULL) {
			if (g_tree_lookup (tree, surbl_req) == NULL) {
				g_tree_insert (tree, surbl_req, surbl_req);
				msg_debug ("surbl_test_url: send surbl dns request %s", surbl_req);
				evdns_resolve_ipv4 (surbl_req, DNS_QUERY_NO_SEARCH, dns_callback, (void *)param);
				param->task->save.saved ++;
			}
			else {
				msg_debug ("make_surbl_requests: request %s is already sent", surbl_req);
			}
		}
		else {
			msg_info ("surbl_test_url: cannot format url string for surbl %s", struri (url));
			return;
		}
		cur = g_list_next (cur);
	}
}

static void
process_dns_results (struct worker_task *task, struct suffix_item *suffix, char *url, uint32_t addr)
{
	char *c, *symbol;
	GList *cur;
	struct surbl_bit_item *bit;
	int len, found = 0;

	if ((c = strchr (suffix->symbol, '%')) != NULL && *(c + 1) == 'b') {
		cur = g_list_first (surbl_module_ctx->bits);

		while (cur) {
			bit = (struct surbl_bit_item *)cur->data;
			msg_debug ("process_dns_results: got result(%d) AND bit(%d): %d", (int)addr, (int)ntohl(bit->bit), 
							(int)bit->bit & (int)ntohl (addr));
			if (((int)bit->bit & (int)ntohl (addr)) != 0) {
				len = strlen (suffix->symbol) - 2 + strlen (bit->symbol) + 1;
				*c = '\0';
				symbol = memory_pool_alloc (task->task_pool, len);
				snprintf (symbol, len, "%s%s%s", suffix->symbol, bit->symbol, c + 2);
				*c = '%';
				insert_result (task, surbl_module_ctx->metric, symbol, 1, 
							g_list_prepend (NULL, memory_pool_strdup (task->task_pool, url)));
				found = 1;
			}
			cur = g_list_next (cur);
		}

		if (!found) {
			insert_result (task, surbl_module_ctx->metric, suffix->symbol, 1, 
							g_list_prepend (NULL, memory_pool_strdup (task->task_pool, url)));
		}
	}
	else {
		insert_result (task, surbl_module_ctx->metric, suffix->symbol, 1, 
							g_list_prepend (NULL, memory_pool_strdup (task->task_pool, url)));
	}
}

static void 
dns_callback (int result, char type, int count, int ttl, void *addresses, void *data)
{
	struct dns_param *param = (struct dns_param *)data;
	char c;
	
	msg_debug ("dns_callback: in surbl request callback");
	c = *(param->url->host + param->url->hostlen);
	*(param->url->host + param->url->hostlen) = 0;
	/* If we have result from DNS server, this url exists in SURBL, so increase score */
	if (result == DNS_ERR_NONE && type == DNS_IPv4_A) {
		msg_info ("surbl_check: <%s> url %s is in surbl %s", 
					param->task->message_id, param->url->host, param->suffix->suffix);
		process_dns_results (param->task, param->suffix, param->url->host, (uint32_t)(((in_addr_t *)addresses)[0]));
	}
	else {
		msg_debug ("surbl_check: <%s> url %s is not in surbl %s", 
					param->task->message_id, param->url->host, param->suffix->suffix);
	}
	*(param->url->host + param->url->hostlen) = c;
	
	param->task->save.saved --;
	if (param->task->save.saved == 0) {
		/* Call other filters */
		param->task->save.saved = 1;
		process_filters (param->task);
	}

}

static void 
memcached_callback (memcached_ctx_t *ctx, memc_error_t error, void *data)
{
	struct memcached_param *param = (struct memcached_param *)data;
	int *url_count;

	switch (ctx->op) {
		case CMD_CONNECT:
			if (error != OK) {
				msg_info ("memcached_callback: memcached returned error %s on CONNECT stage", memc_strerror (error));
				memc_close_ctx (param->ctx);
				param->task->save.saved --;
				if (param->task->save.saved == 0) {
					/* Call other filters */
					param->task->save.saved = 1;
					process_filters (param->task);
				}
			}
			else {
				memc_get (param->ctx, param->ctx->param);
			}
			break;
		case CMD_READ:
			if (error != OK) {
				msg_info ("memcached_callback: memcached returned error %s on READ stage", memc_strerror (error));
				memc_close_ctx (param->ctx);
				param->task->save.saved --;
				if (param->task->save.saved == 0) {
					/* Call other filters */
					param->task->save.saved = 1;
					process_filters (param->task);
				}
			}
			else {
				url_count = (int *)param->ctx->param->buf;
				/* Do not check DNS for urls that have count more than max_urls */
				if (*url_count > surbl_module_ctx->max_urls) {
					msg_info ("memcached_callback: url '%s' has count %d, max: %d", struri (param->url), *url_count, surbl_module_ctx->max_urls);
					/* 
					 * XXX: try to understand why we should use memcached here
					 * insert_result (param->task, surbl_module_ctx->metric, surbl_module_ctx->symbol, 1);
					 */
				}
				(*url_count) ++;
				memc_set (param->ctx, param->ctx->param, surbl_module_ctx->url_expire);
			}
			break;
		case CMD_WRITE:
			if (error != OK) {
				msg_info ("memcached_callback: memcached returned error %s on WRITE stage", memc_strerror (error));
			}
			memc_close_ctx (param->ctx);
			param->task->save.saved --;
			if (param->task->save.saved == 0) {
				/* Call other filters */
				param->task->save.saved = 1;
				process_filters (param->task);
			}
			make_surbl_requests (param->url, param->task, param->tree);
			break;
		default:
			return;
	}
}

static void
register_memcached_call (struct uri *url, struct worker_task *task, GTree *url_tree) 
{
	struct memcached_param *param;
	struct memcached_server *selected;
	memcached_param_t *cur_param;
	gchar *sum_str;
	int *url_count;

	param = memory_pool_alloc (task->task_pool, sizeof (struct memcached_param));
	cur_param = memory_pool_alloc0 (task->task_pool, sizeof (memcached_param_t));
	url_count = memory_pool_alloc (task->task_pool, sizeof (int));

	param->url = url;
	param->task = task;
	param->tree = url_tree;

	param->ctx = memory_pool_alloc0 (task->task_pool, sizeof (memcached_ctx_t));

	cur_param->buf = (u_char *)url_count;
	cur_param->bufsize = sizeof (int);

	sum_str = g_compute_checksum_for_string (G_CHECKSUM_MD5, struri (url), -1);
	g_strlcpy (cur_param->key, sum_str, sizeof (cur_param->key));
	g_free (sum_str);

	selected = (struct memcached_server *) get_upstream_by_hash ((void *)task->cfg->memcached_servers,
											task->cfg->memcached_servers_num, sizeof (struct memcached_server),
											time (NULL), task->cfg->memcached_error_time, task->cfg->memcached_dead_time, task->cfg->memcached_maxerrors,
											cur_param->key, strlen(cur_param->key));
	if (selected == NULL) {
		msg_err ("surbl_register_memcached_call: no memcached servers can be selected");
		return;
	}
	param->ctx->callback = memcached_callback;
	param->ctx->callback_data = (void *)param;
	param->ctx->protocol = task->cfg->memcached_protocol;
	memcpy(&param->ctx->addr, &selected->addr, sizeof (struct in_addr));
	param->ctx->port = selected->port;
	param->ctx->timeout.tv_sec = task->cfg->memcached_connect_timeout / 1000;
	param->ctx->timeout.tv_sec = task->cfg->memcached_connect_timeout - param->ctx->timeout.tv_sec * 1000;
	param->ctx->sock = -1;
#ifdef WITH_DEBUG
	param->ctx->options = MEMC_OPT_DEBUG;
#else
	param->ctx->options = 0;
#endif
	param->ctx->param = cur_param;
	memc_init_ctx (param->ctx);
}

static void
redirector_callback (int fd, short what, void *arg)
{
	struct redirector_param *param = (struct redirector_param *)arg;
	char url_buf[1024];
	int r;
	struct timeval timeout;
	char *p, *c;

	switch (param->state) {
		case STATE_CONNECT:
			/* We have write readiness after connect call, so reinit event */
			if (what == EV_WRITE) {
				timeout.tv_sec = surbl_module_ctx->read_timeout / 1000;
				timeout.tv_usec = surbl_module_ctx->read_timeout - timeout.tv_sec * 1000;
				event_del (&param->ev);
				event_set (&param->ev, param->sock, EV_READ | EV_PERSIST, redirector_callback, (void *)param);
				event_add (&param->ev, &timeout);
				r = snprintf (url_buf, sizeof (url_buf), "GET %s HTTP/1.0\r\n\r\n", struri (param->url));
				if (write (param->sock, url_buf, r) == -1) {
					msg_err ("redirector_callback: write failed %s", strerror (errno));
					event_del (&param->ev);
					close (fd);
					param->task->save.saved --;
					make_surbl_requests (param->url, param->task, param->tree);
					if (param->task->save.saved == 0) {
						/* Call other filters */
						param->task->save.saved = 1;
						process_filters (param->task);
					}
					return;
				}
				param->state = STATE_READ;
			}
			else {
				event_del (&param->ev);
				close (fd);
				msg_info ("redirector_callback: <%s> connection to redirector timed out while waiting for write",
							param->task->message_id);
				param->task->save.saved --;
				make_surbl_requests (param->url, param->task, param->tree);

				if (param->task->save.saved == 0) {
					/* Call other filters */
					param->task->save.saved = 1;
					process_filters (param->task);
				}
			}
			break;
		case STATE_READ:
			if (what == EV_READ) {
				r = read (param->sock, url_buf, sizeof (url_buf));
				if ((p = strstr (url_buf, "Uri: ")) != NULL) {
					p += sizeof ("Uri: ") - 1;
					c = p;
					while (p++ < url_buf + sizeof (url_buf) - 1) {
						if (*p == '\r' || *p == '\n') {
							*p = '\0';
							break;
						}
					}
					if (*p == '\0') {
						msg_debug ("redirector_callback: <%s> got reply from redirector: '%s' -> '%s'", 
									param->task->message_id, struri (param->url), c);
						parse_uri (param->url, c, param->task->task_pool);
					}
				}
				event_del (&param->ev);
				close (fd);
				param->task->save.saved --;
				make_surbl_requests (param->url, param->task, param->tree);
				if (param->task->save.saved == 0) {
					/* Call other filters */
					param->task->save.saved = 1;
					process_filters (param->task);
				}
			}
			else {
				event_del (&param->ev);
				close (fd);
				msg_info ("redirector_callback: <%s> reading redirector timed out, while waiting for read",
							param->task->message_id);
				param->task->save.saved --;
				make_surbl_requests (param->url, param->task, param->tree);
				if (param->task->save.saved == 0) {
					/* Call other filters */
					param->task->save.saved = 1;
					process_filters (param->task);
				}
			}
			break;
	}
}


static void
register_redirector_call (struct uri *url, struct worker_task *task, GTree *url_tree) 
{
	int s;
	struct redirector_param *param;
	struct timeval timeout;

	s = make_tcp_socket (&surbl_module_ctx->redirector_addr, surbl_module_ctx->redirector_port, FALSE);

	if (s == -1) {
		msg_info ("register_redirector_call: <%s> cannot create tcp socket failed: %s", 
					task->message_id, strerror (errno));
		task->save.saved --;
		make_surbl_requests (url, task, url_tree);
		return; 
	}

	param = memory_pool_alloc (task->task_pool, sizeof (struct redirector_param));
	param->url = url;
	param->task = task;
	param->state = STATE_CONNECT;
	param->sock = s;
	param->tree = url_tree;
	timeout.tv_sec = surbl_module_ctx->connect_timeout / 1000;
	timeout.tv_usec = surbl_module_ctx->connect_timeout - timeout.tv_sec * 1000;
	event_set (&param->ev, s, EV_WRITE, redirector_callback, (void *)param);
	event_add (&param->ev, &timeout);
}

static int 
surbl_test_url (struct worker_task *task)
{
	struct uri *url;
	GTree *url_tree;

	url_tree = g_tree_new ((GCompareFunc)g_ascii_strcasecmp);

	TAILQ_FOREACH (url, &task->urls, next) {
		msg_debug ("surbl_test_url: check url %s", struri (url));
		if (surbl_module_ctx->use_redirector) {
			register_redirector_call (url, task, url_tree);
			task->save.saved++;
		}
		else {
			if (task->worker->srv->cfg->memcached_servers_num > 0) {
				register_memcached_call (url, task, url_tree);
				task->save.saved++;
			}
			else {
				make_surbl_requests (url, task, url_tree);
			}
		}
	}

	memory_pool_add_destructor (task->task_pool, (pool_destruct_func)g_tree_destroy, url_tree);
	return 0;
}

/*
 * vi:ts=4 
 */