Mercurial > dnsbl
annotate src/dnsbl.cpp @ 141:6256cab02248
cleanup smtp rate limit code
author | carl |
---|---|
date | Wed, 27 Sep 2006 08:11:38 -0700 |
parents | 4028de9b46dd |
children | b82e00146672 |
rev | line source |
---|---|
94 | 1 /* |
2 | |
3 Copyright (c) 2004, 2005 Carl Byington - 510 Software Group, released | |
4 under the GPL version 2 or any later version at your choice available at | |
5 http://www.fsf.org/licenses/gpl.txt | |
6 | |
7 Based on a sample milter Copyright (c) 2000-2003 Sendmail, Inc. and its | |
8 suppliers. Inspired by the DCC by Rhyolite Software | |
9 | |
10 -r port The port used to talk to our internal dns resolver processes | |
11 -p port The port through which the MTA will connect to this milter. | |
12 -t sec The timeout value. | |
13 -c Check the config, and print a copy to stdout. Don't start the | |
14 milter or do anything with the socket. | |
15 -s Stress test by loading and deleting the current config in a loop. | |
16 -d increase debug level | |
17 -e f|t Print the results of looking up from address f and to address | |
18 t in the current config | |
19 | |
20 */ | |
21 | |
22 | |
23 // from sendmail sample | |
24 #include <sys/types.h> | |
25 #include <sys/stat.h> | |
26 #include <errno.h> | |
27 #include <sysexits.h> | |
28 #include <unistd.h> | |
29 | |
30 // needed for socket io | |
31 #include <sys/ioctl.h> | |
32 #include <net/if.h> | |
33 #include <arpa/inet.h> | |
34 #include <netinet/in.h> | |
35 #include <netinet/tcp.h> | |
36 #include <netdb.h> | |
37 #include <sys/socket.h> | |
38 #include <sys/un.h> | |
39 | |
40 // needed for thread | |
41 #include <pthread.h> | |
42 | |
43 // needed for std c++ collections | |
44 #include <set> | |
45 #include <map> | |
46 #include <list> | |
47 | |
48 // for the dns resolver | |
49 #include <netinet/in.h> | |
50 #include <arpa/nameser.h> | |
51 #include <resolv.h> | |
52 | |
53 // misc stuff needed here | |
54 #include <ctype.h> | |
55 #include <syslog.h> | |
56 #include <pwd.h> | |
57 #include <sys/wait.h> /* header for waitpid() and various macros */ | |
58 #include <signal.h> /* header for signal functions */ | |
59 | |
60 #include "includes.h" | |
61 | |
62 static char* dnsbl_version="$Id$"; | |
63 | |
64 | |
65 extern "C" { | |
66 #include "libmilter/mfapi.h" | |
67 sfsistat mlfi_connect(SMFICTX *ctx, char *hostname, _SOCK_ADDR *hostaddr); | |
68 sfsistat mlfi_envfrom(SMFICTX *ctx, char **argv); | |
69 sfsistat mlfi_envrcpt(SMFICTX *ctx, char **argv); | |
70 sfsistat mlfi_body(SMFICTX *ctx, u_char *data, size_t len); | |
71 sfsistat mlfi_eom(SMFICTX *ctx); | |
72 sfsistat mlfi_abort(SMFICTX *ctx); | |
73 sfsistat mlfi_close(SMFICTX *ctx); | |
74 void sig_chld(int signo); | |
75 } | |
76 | |
77 int debug_syslog = 0; | |
78 bool syslog_opened = false; | |
79 bool use_syslog = true; // false to printf | |
80 bool loader_run = true; // used to stop the config loader thread | |
81 CONFIG *config = NULL; // protected by the config_mutex | |
82 int generation = 0; // protected by the config_mutex | |
83 const int maxlen = 1000; // used for snprintf buffers | |
84 | |
85 pthread_mutex_t config_mutex; | |
86 pthread_mutex_t syslog_mutex; | |
87 pthread_mutex_t resolve_mutex; | |
88 pthread_mutex_t fd_pool_mutex; | |
136 | 89 pthread_mutex_t rate_mutex; |
94 | 90 |
91 std::set<int> fd_pool; | |
136 | 92 int NULL_SOCKET = -1; |
93 const time_t ERROR_SOCKET_TIME = 60; // number of seconds between attempts to open a socket to the dns resolver process | |
94 char *resolver_port = NULL; // unix domain socket to talk to the dns resolver process | |
95 int resolver_socket = NULL_SOCKET; // socket used to listen for resolver requests | |
96 time_t last_error_time; | |
97 int resolver_sock_count = 0; // protected with fd_pool_mutex | |
98 int resolver_pool_size = 0; // protected with fd_pool_mutex | |
99 rcpt_rates rcpt_counts; // protected with rate_mutex | |
94 | 100 |
101 | |
102 struct ns_map { | |
103 // all the strings are owned by the keys/values in the ns_host string map | |
104 string_map ns_host; // nameserver name -> host name that uses this name server | |
105 ns_mapper ns_ip; // nameserver name -> ip address of the name server | |
106 ~ns_map(); | |
107 void add(char *name, char *refer); | |
108 }; | |
109 | |
110 | |
111 ns_map::~ns_map() { | |
112 for (string_map::iterator i=ns_host.begin(); i!=ns_host.end(); i++) { | |
113 char *x = (*i).first; | |
114 char *y = (*i).second; | |
115 free(x); | |
116 free(y); | |
117 } | |
118 ns_ip.clear(); | |
119 ns_host.clear(); | |
120 } | |
121 | |
122 | |
123 void ns_map::add(char *name, char *refer) { | |
124 string_map::iterator i = ns_host.find(name); | |
125 if (i != ns_host.end()) return; | |
126 char *x = strdup(name); | |
127 char *y = strdup(refer); | |
128 ns_ip[x] = 0; | |
129 ns_host[x] = y; | |
130 | |
131 } | |
132 | |
133 // packed structure to allow a single socket write to dump the | |
134 // length and the following answer. The packing attribute is gcc specific. | |
135 struct glommer { | |
136 int length; | |
137 #ifdef NS_PACKETSZ | |
115 | 138 u_char answer[NS_PACKETSZ*4]; // with a resolver, we return resolver answers |
94 | 139 #else |
140 int answer; // without a resolver, we return a single ip4 address, 0 == no answer | |
141 #endif | |
142 } __attribute__ ((packed)); | |
143 | |
144 | |
145 //////////////////////////////////////////////// | |
136 | 146 // helper to manipulate recipient counts |
147 // | |
148 int incr_rcpt_count(char *user); | |
149 int incr_rcpt_count(char *user) { | |
150 pthread_mutex_lock(&rate_mutex); | |
151 rcpt_rates::iterator i = rcpt_counts.find(user); | |
138 | 152 int c = 1; |
153 if (i == rcpt_counts.end()) { | |
154 user = strdup(user); | |
155 rcpt_counts[user] = c; | |
156 } | |
157 else { | |
139 | 158 c = ++((*i).second); |
138 | 159 } |
136 | 160 pthread_mutex_unlock(&rate_mutex); |
161 return c; | |
162 } | |
163 | |
164 //////////////////////////////////////////////// | |
94 | 165 // helper to discard the strings held by a context_map |
166 // | |
167 void discard(context_map &cm); | |
168 void discard(context_map &cm) { | |
169 for (context_map::iterator i=cm.begin(); i!=cm.end(); i++) { | |
170 char *x = (*i).first; | |
171 free(x); | |
172 } | |
173 cm.clear(); | |
174 } | |
175 | |
176 | |
177 //////////////////////////////////////////////// | |
178 // helper to register a string in a context_map | |
179 // | |
180 void register_string(context_map &cm, char *name, CONTEXT *con); | |
181 void register_string(context_map &cm, char *name, CONTEXT *con) { | |
182 context_map::iterator i = cm.find(name); | |
183 if (i != cm.end()) return; | |
184 char *x = strdup(name); | |
185 cm[x] = con; | |
186 } | |
187 | |
188 | |
189 //////////////////////////////////////////////// | |
190 // disconnect the fd from the dns resolver process | |
191 // | |
192 void my_disconnect(int sock, bool decrement = true); | |
193 void my_disconnect(int sock, bool decrement) { | |
194 if (sock != NULL_SOCKET) { | |
195 if (decrement) { | |
196 pthread_mutex_lock(&fd_pool_mutex); | |
197 resolver_sock_count--; | |
198 pthread_mutex_unlock(&fd_pool_mutex); | |
199 } | |
200 shutdown(sock, SHUT_RDWR); | |
201 close(sock); | |
202 } | |
203 } | |
204 | |
205 | |
206 //////////////////////////////////////////////// | |
207 // return fd connected to the dns resolver process | |
208 // | |
209 int my_connect(); | |
210 int my_connect() { | |
211 // if we have had recent errors, don't even try to open the socket | |
129
c5cd1261394d
ignore smtp connection attempts for 10 minutes when getting connection errors on verify hosts
carl
parents:
128
diff
changeset
|
212 if ((time(NULL) - last_error_time) < ERROR_SOCKET_TIME) return NULL_SOCKET; |
94 | 213 |
214 // nothing recent, maybe this time it will work | |
215 int sock = NULL_SOCKET; | |
216 sockaddr_un server; | |
217 memset(&server, '\0', sizeof(server)); | |
218 server.sun_family = AF_UNIX; | |
219 strncpy(server.sun_path, resolver_port, sizeof(server.sun_path)-1); | |
220 sock = socket(AF_UNIX, SOCK_STREAM, 0); | |
221 if (sock != NULL_SOCKET) { | |
222 bool rc = (connect(sock, (sockaddr *)&server, sizeof(server)) == 0); | |
223 if (!rc) { | |
224 my_disconnect(sock, false); | |
225 sock = NULL_SOCKET; | |
129
c5cd1261394d
ignore smtp connection attempts for 10 minutes when getting connection errors on verify hosts
carl
parents:
128
diff
changeset
|
226 last_error_time = time(NULL); |
94 | 227 } |
228 } | |
129
c5cd1261394d
ignore smtp connection attempts for 10 minutes when getting connection errors on verify hosts
carl
parents:
128
diff
changeset
|
229 else last_error_time = time(NULL); |
94 | 230 if (sock != NULL_SOCKET) { |
231 pthread_mutex_lock(&fd_pool_mutex); | |
232 resolver_sock_count++; | |
233 pthread_mutex_unlock(&fd_pool_mutex); | |
234 } | |
235 return sock; | |
236 } | |
237 | |
238 | |
239 mlfiPriv::mlfiPriv() { | |
240 pthread_mutex_lock(&config_mutex); | |
241 pc = config; | |
242 pc->reference_count++; | |
243 pthread_mutex_unlock(&config_mutex); | |
244 get_fd(); | |
245 ip = 0; | |
246 mailaddr = NULL; | |
247 queueid = NULL; | |
136 | 248 authenticated = NULL; |
94 | 249 have_whites = false; |
250 only_whites = true; | |
251 memory = NULL; | |
252 scanner = NULL; | |
253 content_suffix = NULL; | |
254 content_message = NULL; | |
119 | 255 uribl_suffix = NULL; |
256 uribl_message = NULL; | |
94 | 257 content_host_ignore = NULL; |
258 } | |
259 | |
260 mlfiPriv::~mlfiPriv() { | |
261 return_fd(); | |
262 pthread_mutex_lock(&config_mutex); | |
263 pc->reference_count--; | |
264 pthread_mutex_unlock(&config_mutex); | |
265 reset(true); | |
266 } | |
267 | |
268 void mlfiPriv::reset(bool final) { | |
136 | 269 if (mailaddr) free(mailaddr); |
270 if (queueid) free(queueid); | |
271 if (authenticated) free(authenticated); | |
94 | 272 discard(env_to); |
273 if (memory) delete memory; | |
274 if (scanner) delete scanner; | |
275 if (!final) { | |
276 mailaddr = NULL; | |
277 queueid = NULL; | |
136 | 278 authenticated = NULL; |
94 | 279 have_whites = false; |
280 only_whites = true; | |
281 memory = NULL; | |
282 scanner = NULL; | |
283 content_suffix = NULL; | |
284 content_message = NULL; | |
119 | 285 uribl_suffix = NULL; |
286 uribl_message = NULL; | |
94 | 287 content_host_ignore = NULL; |
288 } | |
289 } | |
290 | |
291 void mlfiPriv::get_fd() { | |
292 err = true; | |
293 fd = NULL_SOCKET; | |
294 int result = pthread_mutex_lock(&fd_pool_mutex); | |
295 if (!result) { | |
296 std::set<int>::iterator i; | |
297 i = fd_pool.begin(); | |
298 if (i != fd_pool.end()) { | |
299 // have at least one fd in the pool | |
300 err = false; | |
301 fd = *i; | |
302 fd_pool.erase(fd); | |
303 resolver_pool_size--; | |
304 pthread_mutex_unlock(&fd_pool_mutex); | |
305 } | |
306 else { | |
307 // pool is empty, get a new fd | |
308 pthread_mutex_unlock(&fd_pool_mutex); | |
309 fd = my_connect(); | |
310 err = (fd == NULL_SOCKET); | |
311 } | |
312 } | |
313 else { | |
314 // cannot lock the pool, just get a new fd | |
315 fd = my_connect(); | |
316 err = (fd == NULL_SOCKET); | |
317 } | |
318 } | |
319 | |
320 void mlfiPriv::return_fd() { | |
321 if (err) { | |
322 // this fd got a socket error, so close it, rather than returning it to the pool | |
323 my_disconnect(fd); | |
324 } | |
325 else { | |
326 int result = pthread_mutex_lock(&fd_pool_mutex); | |
327 if (!result) { | |
328 if ((resolver_sock_count > resolver_pool_size*5) || (resolver_pool_size < 5)) { | |
329 // return the fd to the pool | |
330 fd_pool.insert(fd); | |
331 resolver_pool_size++; | |
332 pthread_mutex_unlock(&fd_pool_mutex); | |
333 } | |
334 else { | |
335 // more than 20% of the open resolver sockets are in the pool, and the | |
336 // pool as at least 5 sockets. that is enough, so just close this one. | |
337 pthread_mutex_unlock(&fd_pool_mutex); | |
338 my_disconnect(fd); | |
339 } | |
340 } | |
341 else { | |
342 // could not lock the pool, so just close the fd | |
343 my_disconnect(fd); | |
344 } | |
345 } | |
346 } | |
347 | |
348 int mlfiPriv::my_write(char *buf, int len) { | |
349 if (err) return 0; | |
350 int rs = 0; | |
351 while (len) { | |
352 int ws = write(fd, buf, len); | |
353 if (ws > 0) { | |
354 rs += ws; | |
355 len -= ws; | |
356 buf += ws; | |
357 } | |
358 else { | |
359 // peer closed the socket! | |
360 rs = 0; | |
361 err = true; | |
362 break; | |
363 } | |
364 } | |
365 return rs; | |
366 } | |
367 | |
368 int mlfiPriv::my_read(char *buf, int len) { | |
369 if (err) return 0; | |
370 int rs = 0; | |
134 | 371 while (len) { |
94 | 372 int ws = read(fd, buf, len); |
373 if (ws > 0) { | |
374 rs += ws; | |
375 len -= ws; | |
376 buf += ws; | |
377 } | |
378 else { | |
379 // peer closed the socket! | |
380 rs = 0; | |
381 err = true; | |
382 break; | |
383 } | |
384 } | |
385 return rs; | |
386 } | |
387 | |
388 void mlfiPriv::need_content_filter(char *rcpt, CONTEXT &con) { | |
389 register_string(env_to, rcpt, &con); | |
390 if (!memory) { | |
391 // first recipient that needs content filtering sets all | |
392 // the content filtering parameters | |
117 | 393 memory = new recorder(this, con.get_html_tags(), con.get_content_tlds(), con.get_content_cctlds()); |
94 | 394 scanner = new url_scanner(memory); |
395 content_suffix = con.get_content_suffix(); | |
396 content_message = con.get_content_message(); | |
119 | 397 uribl_suffix = con.get_uribl_suffix(); |
398 uribl_message = con.get_uribl_message(); | |
94 | 399 content_host_ignore = &con.get_content_host_ignore(); |
400 } | |
401 } | |
402 | |
403 #define MLFIPRIV ((struct mlfiPriv *) smfi_getpriv(ctx)) | |
404 | |
405 | |
406 //////////////////////////////////////////////// | |
407 // syslog a message | |
408 // | |
409 void my_syslog(mlfiPriv *priv, char *text) { | |
410 char buf[maxlen]; | |
411 if (priv) { | |
412 snprintf(buf, sizeof(buf), "%s: %s", priv->queueid, text); | |
413 text = buf; | |
414 } | |
415 if (use_syslog) { | |
416 pthread_mutex_lock(&syslog_mutex); | |
417 if (!syslog_opened) { | |
418 openlog("dnsbl", LOG_PID, LOG_MAIL); | |
419 syslog_opened = true; | |
420 } | |
421 syslog(LOG_NOTICE, "%s", text); | |
422 pthread_mutex_unlock(&syslog_mutex); | |
423 } | |
424 else { | |
425 printf("%s \n", text); | |
426 } | |
427 } | |
428 | |
429 void my_syslog(char *text) { | |
430 my_syslog(NULL, text); | |
431 } | |
432 | |
433 | |
434 //////////////////////////////////////////////// | |
435 // read a resolver request from the socket, process it, and | |
436 // write the result back to the socket. | |
437 | |
438 void process_resolver_requests(int socket); | |
439 void process_resolver_requests(int socket) { | |
440 #ifdef NS_MAXDNAME | |
441 char question[NS_MAXDNAME]; | |
442 #else | |
443 char question[1000]; | |
444 #endif | |
445 glommer glom; | |
446 | |
447 int maxq = sizeof(question); | |
448 while (true) { | |
449 // read a question | |
450 int rs = 0; | |
451 while (rs < maxq) { | |
452 int ns = read(socket, question+rs, maxq-rs); | |
453 if (ns > 0) { | |
454 rs += ns; | |
455 if (question[rs-1] == '\0') { | |
456 // last byte read was the null terminator, we are done | |
457 break; | |
458 } | |
459 } | |
460 else { | |
461 // peer closed the socket | |
462 #ifdef RESOLVER_DEBUG | |
463 my_syslog("process_resolver_requests() peer closed socket while reading question"); | |
464 #endif | |
465 shutdown(socket, SHUT_RDWR); | |
466 close(socket); | |
467 return; | |
468 } | |
469 } | |
470 question[rs-1] = '\0'; // ensure null termination | |
471 | |
472 // find the answer | |
473 #ifdef NS_PACKETSZ | |
474 #ifdef RESOLVER_DEBUG | |
475 char text[1000]; | |
476 snprintf(text, sizeof(text), "process_resolver_requests() has a question %s", question); | |
477 my_syslog(text); | |
478 #endif | |
479 glom.length = res_search(question, ns_c_in, ns_t_a, glom.answer, sizeof(glom.answer)); | |
480 if (glom.length < 0) glom.length = 0; // represent all errors as zero length answers | |
481 #else | |
482 glom.length = sizeof(glom.answer); | |
483 glom.answer = 0; | |
484 struct hostent *host = gethostbyname(question); | |
485 if (host && (host->h_addrtype == AF_INET)) { | |
486 memcpy(&glom.answer, host->h_addr, sizeof(glom.answer)); | |
487 } | |
488 #endif | |
489 | |
490 // write the answer | |
491 char *buf = (char *)&glom; | |
492 int len = glom.length + sizeof(glom.length); | |
493 #ifdef RESOLVER_DEBUG | |
494 snprintf(text, sizeof(text), "process_resolver_requests() writing answer length %d for total %d", glom.length, len); | |
495 my_syslog(text); | |
496 #endif | |
497 int ws = 0; | |
498 while (len > ws) { | |
499 int ns = write(socket, buf+ws, len-ws); | |
500 if (ns > 0) { | |
501 ws += ns; | |
502 } | |
503 else { | |
504 // peer closed the socket! | |
505 #ifdef RESOLVER_DEBUG | |
506 my_syslog("process_resolver_requests() peer closed socket while writing answer"); | |
507 #endif | |
508 shutdown(socket, SHUT_RDWR); | |
509 close(socket); | |
510 return; | |
511 } | |
512 } | |
513 } | |
514 } | |
515 | |
516 | |
517 //////////////////////////////////////////////// | |
518 // ask a dns question and get an A record answer - we don't try | |
519 // very hard, just using the default resolver retry settings. | |
520 // If we cannot get an answer, we just accept the mail. | |
521 // | |
522 // | |
523 int dns_interface(mlfiPriv &priv, char *question, bool maybe_ip, ns_map *nameservers); | |
524 int dns_interface(mlfiPriv &priv, char *question, bool maybe_ip, ns_map *nameservers) { | |
525 // this part can be done without locking the resolver mutex. Each | |
526 // milter thread is talking over its own socket to a separate resolver | |
527 // process, which does the actual dns resolution. | |
528 if (priv.err) return 0; // cannot ask more questions on this socket. | |
134 | 529 if (maybe_ip) { |
530 // might be a bare ip address, try this first to avoid dns lookups that may not be needed | |
531 in_addr ip; | |
532 if (inet_aton(question, &ip)) { | |
533 return (int)ip.s_addr; | |
534 } | |
535 } | |
536 int n = strlen(question); | |
537 if (question[n-1] == '.') { | |
538 priv.my_write(question, n+1); // write the question including the null terminator | |
539 } | |
540 else { | |
541 priv.my_write(question, n); // write the question | |
542 priv.my_write(".", 2); // and the fully qualified . terminator and null string terminator | |
543 } | |
94 | 544 glommer glom; |
545 char *buf = (char *)&glom; | |
546 priv.my_read(buf, sizeof(glom.length)); | |
547 buf += sizeof(glom.length); | |
548 #ifdef RESOLVER_DEBUG | |
549 char text[1000]; | |
550 snprintf(text, sizeof(text), "dns_interface() wrote question %s and has answer length %d", question, glom.length); | |
551 my_syslog(text); | |
552 #endif | |
553 if ((glom.length < 0) || (glom.length > sizeof(glom.answer))) { | |
554 priv.err = true; | |
555 return 0; // cannot process overlarge answers | |
556 } | |
557 priv.my_read(buf, glom.length); | |
558 | |
559 #ifdef NS_PACKETSZ | |
560 // now we need to lock the resolver mutex to keep the milter threads from | |
561 // stepping on each other while parsing the dns answer. | |
562 int ret_address = 0; | |
563 pthread_mutex_lock(&resolve_mutex); | |
564 if (glom.length > 0) { | |
565 // parse the answer | |
566 ns_msg handle; | |
567 ns_rr rr; | |
568 if (ns_initparse(glom.answer, glom.length, &handle) == 0) { | |
569 // look for ns names | |
570 if (nameservers) { | |
571 ns_map &ns = *nameservers; | |
572 int rrnum = 0; | |
573 while (ns_parserr(&handle, ns_s_ns, rrnum++, &rr) == 0) { | |
574 if (ns_rr_type(rr) == ns_t_ns) { | |
575 char nam[NS_MAXDNAME+1]; | |
576 char *n = nam; | |
577 const u_char *p = ns_rr_rdata(rr); | |
578 while (((n-nam) < NS_MAXDNAME) && ((p-glom.answer) < glom.length) && *p) { | |
579 size_t s = *(p++); | |
580 if (s > 191) { | |
581 // compression pointer | |
582 s = (s-192)*256 + *(p++); | |
583 if (s >= glom.length) break; // pointer outside bounds of answer | |
584 p = glom.answer + s; | |
585 s = *(p++); | |
586 } | |
587 if (s > 0) { | |
588 if ((n-nam) >= (NS_MAXDNAME-s)) break; // destination would overflow name buffer | |
589 if ((p-glom.answer) >= (glom.length-s)) break; // source outside bounds of answer | |
590 memcpy(n, p, s); | |
591 n += s; | |
592 p += s; | |
593 *(n++) = '.'; | |
594 } | |
595 } | |
596 if (n-nam) n--; // remove trailing . | |
597 *n = '\0'; // null terminate it | |
598 ns.add(nam, question); // ns host to lookup later | |
599 } | |
600 } | |
601 rrnum = 0; | |
602 while (ns_parserr(&handle, ns_s_ar, rrnum++, &rr) == 0) { | |
603 if (ns_rr_type(rr) == ns_t_a) { | |
604 char* nam = (char*)ns_rr_name(rr); | |
605 ns_mapper::iterator i = ns.ns_ip.find(nam); | |
606 if (i != ns.ns_ip.end()) { | |
607 // we want this ip address | |
608 int address; | |
609 memcpy(&address, ns_rr_rdata(rr), sizeof(address)); | |
610 ns.ns_ip[nam] = address; | |
611 } | |
612 } | |
613 } | |
614 } | |
615 int rrnum = 0; | |
616 while (ns_parserr(&handle, ns_s_an, rrnum++, &rr) == 0) { | |
617 if (ns_rr_type(rr) == ns_t_a) { | |
618 int address; | |
619 memcpy(&address, ns_rr_rdata(rr), sizeof(address)); | |
620 ret_address = address; | |
621 } | |
622 } | |
623 } | |
624 } | |
625 pthread_mutex_unlock(&resolve_mutex); | |
626 return ret_address; | |
627 #else | |
628 return glom.answer; | |
629 #endif | |
630 } | |
631 | |
632 | |
633 //////////////////////////////////////////////// | |
634 // check a single dnsbl | |
635 // | |
636 bool check_single(mlfiPriv &priv, int ip, char *suffix); | |
637 bool check_single(mlfiPriv &priv, int ip, char *suffix) { | |
638 // make a dns question | |
639 const u_char *src = (const u_char *)&ip; | |
640 if (src[0] == 127) return false; // don't do dns lookups on localhost | |
126 | 641 if (src[0] == 10) return false; // don't do dns lookups on rfc1918 space |
642 if ((src[0] == 192) && (src[1] == 168)) return false; | |
643 if ((src[0] == 172) && (16 <= src[1]) && (src[1] <= 31)) return false; | |
94 | 644 #ifdef NS_MAXDNAME |
645 char question[NS_MAXDNAME]; | |
646 #else | |
647 char question[1000]; | |
648 #endif | |
649 snprintf(question, sizeof(question), "%u.%u.%u.%u.%s.", src[3], src[2], src[1], src[0], suffix); | |
650 // ask the question, if we get an A record it implies a blacklisted ip address | |
651 return dns_interface(priv, question, false, NULL); | |
652 } | |
653 | |
654 | |
655 //////////////////////////////////////////////// | |
656 // check a single dnsbl | |
657 // | |
658 bool check_single(mlfiPriv &priv, int ip, DNSBL &bl); | |
659 bool check_single(mlfiPriv &priv, int ip, DNSBL &bl) { | |
660 return check_single(priv, ip, bl.suffix); | |
661 } | |
662 | |
663 | |
664 //////////////////////////////////////////////// | |
665 // check the dnsbls specified for this recipient | |
666 // | |
667 bool check_dnsbl(mlfiPriv &priv, dnsblp_list &dnsbll, DNSBLP &rejectlist); | |
668 bool check_dnsbl(mlfiPriv &priv, dnsblp_list &dnsbll, DNSBLP &rejectlist) { | |
669 for (dnsblp_list::iterator i=dnsbll.begin(); i!=dnsbll.end(); i++) { | |
670 DNSBLP dp = *i; // non null by construction | |
671 bool st; | |
672 map<DNSBLP, bool>::iterator f = priv.checked.find(dp); | |
673 if (f == priv.checked.end()) { | |
674 // have not checked this list yet | |
675 st = check_single(priv, priv.ip, *dp); | |
676 rejectlist = dp; | |
677 priv.checked[dp] = st; | |
678 } | |
679 else { | |
680 st = (*f).second; | |
681 rejectlist = (*f).first; | |
682 } | |
683 if (st) return st; | |
684 } | |
685 return false; | |
686 } | |
687 | |
688 | |
689 //////////////////////////////////////////////// | |
134 | 690 // lookup the domain name part of a hostname on the uribl |
117 | 691 // |
124 | 692 // if we find part of the hostname on the uribl, return |
693 // true and point found to the part of the hostname that we found. | |
694 // otherwise, return false and preserve the value of found. | |
695 // | |
696 bool uriblookup(mlfiPriv &priv ,char *hostname, char *top, char *&found) ; | |
697 bool uriblookup(mlfiPriv &priv, char *hostname, char *top, char *&found) { | |
117 | 698 // top is pointer to '.' char at end of base domain, or null for ip address form |
699 // so for hostname of www.fred.mydomain.co.uk | |
700 // top points to-----------------------^ | |
701 // and we end up looking at only mydomain.co.uk, ignoring the www.fred stuff | |
702 char buf[maxlen]; | |
703 if (top) { | |
704 // add one more component | |
705 *top = '\0'; | |
706 char *x = strrchr(hostname, '.'); | |
707 if (x) hostname = x+1; | |
708 *top = '.'; | |
709 } | |
131
df355d117199
uribl lookups fully qualified; allow two component host names
carl
parents:
129
diff
changeset
|
710 snprintf(buf, sizeof(buf), "%s.%s.", hostname, priv.uribl_suffix); |
119 | 711 if (dns_interface(priv, buf, false, NULL)) { |
117 | 712 if (debug_syslog > 2) { |
713 char tmp[maxlen]; | |
119 | 714 snprintf(tmp, sizeof(tmp), "found %s on %s", hostname, priv.uribl_suffix); |
117 | 715 my_syslog(tmp); |
716 } | |
124 | 717 found = hostname; |
119 | 718 return true; |
117 | 719 } |
720 return false; | |
721 } | |
722 | |
723 | |
724 //////////////////////////////////////////////// | |
124 | 725 // uribl checker |
726 // ------------- | |
727 // hostname MUST not have a trailing dot | |
728 // If tld, two level lookup. | |
729 // Else, look up three level domain. | |
730 // | |
731 // if we find part of the hostname on the uribl, return | |
732 // true and point found to the part of the hostname that we found. | |
733 // otherwise, return false and preserve the value of found. | |
734 // | |
735 bool check_uribl(mlfiPriv &priv, char *hostname, char *&found) ; | |
736 bool check_uribl(mlfiPriv &priv, char *hostname, char *&found) { | |
117 | 737 in_addr ip; |
738 if (inet_aton(hostname, &ip)) { | |
120 | 739 const u_char *src = (const u_char *)&ip.s_addr; |
128 | 740 if (src[0] == 127) return false; // don't do dns lookups on localhost |
741 if (src[0] == 10) return false; // don't do dns lookups on rfc1918 space | |
742 if ((src[0] == 192) && (src[1] == 168)) return false; | |
743 if ((src[0] == 172) && (16 <= src[1]) && (src[1] <= 31)) return false; | |
124 | 744 static char adr[sizeof "255.255.255.255"]; |
120 | 745 snprintf(adr, sizeof(adr), "%u.%u.%u.%u", src[3], src[2], src[1], src[0]); |
124 | 746 return (uriblookup(priv, adr, NULL, found)); |
117 | 747 } |
748 | |
749 char *top, *top2, *top3; | |
750 top = strrchr(hostname, '.'); | |
751 if (top) { | |
752 *top = '\0'; | |
753 top2 = strrchr(hostname, '.'); | |
754 *top = '.'; | |
755 | |
756 if (top2) { | |
757 string_set::iterator i = priv.memory->get_cctlds()->find(top2+1); | |
758 string_set::iterator x = priv.memory->get_cctlds()->end(); | |
759 // if we have a 2-level-cctld, just look at top three levels of the name | |
124 | 760 if (i != x) return uriblookup(priv, hostname, top2, found); |
117 | 761 |
762 *top2 = '\0'; | |
763 top3 = strrchr(hostname, '.'); | |
764 *top2 = '.'; | |
765 | |
766 // if we have more than 3 levels in the name, look at the top three levels of the name | |
124 | 767 if (top3 && uriblookup(priv, hostname, top2, found)) return true; |
117 | 768 // if that was not found, fall thru to looking at the top two levels |
769 } | |
770 // look at the top two levels of the name | |
124 | 771 return uriblookup(priv, hostname, top, found); |
117 | 772 } |
773 return false; | |
774 } | |
775 | |
776 | |
777 //////////////////////////////////////////////// | |
119 | 778 // check the hosts from the body against the content filter and uribl dnsbls |
94 | 779 // |
124 | 780 // |
781 bool check_hosts(mlfiPriv &priv, bool random, int limit, char *&msg, char *&host, int &ip, char *&found); | |
782 bool check_hosts(mlfiPriv &priv, bool random, int limit, char *&msg, char *&host, int &ip, char *&found) { | |
783 found = NULL; // normally ip address style | |
119 | 784 if (!priv.content_suffix && !priv.uribl_suffix) return false; // nothing to check |
94 | 785 CONFIG &dc = *priv.pc; |
786 string_set &hosts = priv.memory->get_hosts(); | |
787 string_set &ignore = *priv.content_host_ignore; | |
788 | |
789 int count = 0; | |
790 int cnt = hosts.size(); // number of hosts we could look at | |
791 int_set ips; | |
792 ns_map nameservers; | |
793 for (string_set::iterator i=hosts.begin(); i!=hosts.end(); i++) { | |
794 host = *i; // a reference into hosts, which will live until this smtp transaction is closed | |
795 | |
796 // don't bother looking up hosts on the ignore list | |
797 string_set::iterator j = ignore.find(host); | |
798 if (j != ignore.end()) continue; | |
799 | |
800 // try to only look at limit/cnt fraction of the available cnt host names in random mode | |
801 if ((cnt > limit) && (limit > 0) && random) { | |
802 int r = rand() % cnt; | |
803 if (r >= limit) { | |
804 if (debug_syslog > 2) { | |
805 char buf[maxlen]; | |
806 snprintf(buf, sizeof(buf), "host %s skipped", host); | |
807 my_syslog(&priv, buf); | |
808 } | |
809 continue; | |
810 } | |
811 } | |
812 count++; | |
813 ip = dns_interface(priv, host, true, &nameservers); | |
814 if (debug_syslog > 2) { | |
815 char buf[maxlen]; | |
816 if (ip) { | |
817 char adr[sizeof "255.255.255.255"]; | |
818 adr[0] = '\0'; | |
819 inet_ntop(AF_INET, (const u_char *)&ip, adr, sizeof(adr)); | |
820 snprintf(buf, sizeof(buf), "host %s found at %s", host, adr); | |
821 } | |
822 else { | |
823 snprintf(buf, sizeof(buf), "host %s not found", host); | |
824 } | |
825 my_syslog(&priv, buf); | |
826 } | |
827 if (ip) { | |
828 int_set::iterator i = ips.find(ip); | |
829 if (i == ips.end()) { | |
117 | 830 // we haven't looked this up yet |
94 | 831 ips.insert(ip); |
124 | 832 // check dnsbl style list |
833 if (priv.content_suffix && check_single(priv, ip, priv.content_suffix)) { | |
119 | 834 msg = priv.content_message; |
835 return true; | |
836 } | |
124 | 837 // Check uribl & surbl style list |
838 if (priv.uribl_suffix && check_uribl(priv, host, found)) { | |
119 | 839 msg = priv.uribl_message; |
840 return true; | |
841 } | |
94 | 842 } |
843 } | |
844 } | |
845 limit *= 4; // allow average of 3 ns per host name | |
846 for (ns_mapper::iterator i=nameservers.ns_ip.begin(); i!=nameservers.ns_ip.end(); i++) { | |
847 count++; | |
119 | 848 if ((count > limit) && (limit > 0)) return false; // too many name servers to check them all |
94 | 849 host = (*i).first; // a transient reference that needs to be replaced before we return it |
850 ip = (*i).second; | |
851 if (!ip) ip = dns_interface(priv, host, false, NULL); | |
852 if (debug_syslog > 2) { | |
853 char buf[maxlen]; | |
854 if (ip) { | |
855 char adr[sizeof "255.255.255.255"]; | |
856 adr[0] = '\0'; | |
857 inet_ntop(AF_INET, (const u_char *)&ip, adr, sizeof(adr)); | |
858 snprintf(buf, sizeof(buf), "ns %s found at %s", host, adr); | |
859 } | |
860 else { | |
861 snprintf(buf, sizeof(buf), "ns %s not found", host); | |
862 } | |
863 my_syslog(&priv, buf); | |
864 } | |
865 if (ip) { | |
866 int_set::iterator i = ips.find(ip); | |
867 if (i == ips.end()) { | |
868 ips.insert(ip); | |
119 | 869 if (check_single(priv, ip, priv.content_suffix)) { |
870 msg = priv.content_message; | |
94 | 871 string_map::iterator j = nameservers.ns_host.find(host); |
872 if (j != nameservers.ns_host.end()) { | |
873 char *refer = (*j).second; | |
874 char buf[maxlen]; | |
875 snprintf(buf, sizeof(buf), "%s with nameserver %s", refer, host); | |
876 host = register_string(hosts, buf); // put a copy into hosts, and return that reference | |
877 } | |
878 else { | |
879 host = register_string(hosts, host); // put a copy into hosts, and return that reference | |
880 } | |
881 return true; | |
882 } | |
883 } | |
884 } | |
885 } | |
886 return false; | |
887 } | |
888 | |
127 | 889 |
94 | 890 //////////////////////////////////////////////// |
127 | 891 // |
892 // this email address is passed in from sendmail, and will normally be | |
893 // enclosed in <>. I think older versions of sendmail supplied the <> | |
894 // wrapper if the mail client did not, but the current version does not do | |
895 // that. So the <> wrapper is now optional. It may have mixed case, just | |
896 // as the mail client sent it. We dup the string and convert the duplicate | |
897 // to lower case. | |
94 | 898 // |
899 char *to_lower_string(char *email); | |
900 char *to_lower_string(char *email) { | |
127 | 901 int n = strlen(email); |
902 if (*email == '<') { | |
903 // assume it also ends with > | |
904 n -= 2; | |
905 if (n < 1) return strdup(email); // return "<>" | |
906 email++; | |
907 } | |
908 char *key = strdup(email); | |
94 | 909 key[n] = '\0'; |
910 for (int i=0; i<n; i++) key[i] = tolower(key[i]); | |
911 return key; | |
912 } | |
913 | |
914 | |
915 //////////////////////////////////////////////// | |
916 // start of sendmail milter interfaces | |
917 // | |
918 sfsistat mlfi_connect(SMFICTX *ctx, char *hostname, _SOCK_ADDR *hostaddr) | |
919 { | |
920 // allocate some private memory | |
921 mlfiPriv *priv = new mlfiPriv; | |
922 if (hostaddr->sa_family == AF_INET) { | |
923 priv->ip = ((struct sockaddr_in *)hostaddr)->sin_addr.s_addr; | |
924 } | |
925 | |
926 // save the private data | |
927 smfi_setpriv(ctx, (void*)priv); | |
928 | |
929 // continue processing | |
930 return SMFIS_CONTINUE; | |
931 } | |
932 | |
933 sfsistat mlfi_envfrom(SMFICTX *ctx, char **from) | |
934 { | |
935 mlfiPriv &priv = *MLFIPRIV; | |
936 priv.mailaddr = to_lower_string(from[0]); | |
136 | 937 priv.authenticated = smfi_getsymval(ctx, "{auth_authen}"); |
938 if (priv.authenticated) priv.authenticated = strdup(priv.authenticated); | |
94 | 939 return SMFIS_CONTINUE; |
940 } | |
941 | |
942 sfsistat mlfi_envrcpt(SMFICTX *ctx, char **rcpt) | |
943 { | |
944 DNSBLP rejectlist = NULL; // list that caused the reject | |
945 mlfiPriv &priv = *MLFIPRIV; | |
946 CONFIG &dc = *priv.pc; | |
947 if (!priv.queueid) priv.queueid = strdup(smfi_getsymval(ctx, "i")); | |
948 char *rcptaddr = rcpt[0]; | |
949 char *loto = to_lower_string(rcptaddr); | |
950 CONTEXT &con = *(dc.find_context(loto)->find_context(priv.mailaddr)); | |
951 VERIFYP ver = con.find_verify(loto); | |
952 if (debug_syslog > 1) { | |
953 char buf[maxlen]; | |
954 char msg[maxlen]; | |
955 snprintf(msg, sizeof(msg), "from <%s> to <%s> using context %s", priv.mailaddr, loto, con.get_full_name(buf,maxlen)); | |
956 my_syslog(&priv, msg); | |
957 } | |
958 free(loto); | |
959 char *fromvalue = con.find_from(priv.mailaddr); | |
960 status st; | |
961 if (priv.authenticated) { | |
136 | 962 int c = incr_rcpt_count(priv.authenticated); |
963 int l = dc.default_context->find_rate(priv.authenticated); | |
964 if (c > l) { | |
965 smfi_setreply(ctx, "550", "5.7.1", "recipient rate limit exceeded"); | |
966 return SMFIS_REJECT; | |
967 } | |
968 else { | |
969 if (debug_syslog > 1) { | |
970 char buf[maxlen]; | |
971 char msg[maxlen]; | |
972 snprintf(msg, sizeof(msg), "authenticated id %s (%d recipients, %d limit)", priv.authenticated, c, l); | |
973 my_syslog(&priv, msg); | |
974 } | |
975 st = white; | |
976 } | |
94 | 977 } |
978 else if (fromvalue == token_black) { | |
979 st = black; | |
980 } | |
981 else if (fromvalue == token_white) { | |
982 st = white; | |
983 } | |
984 else { | |
985 // check the dns based lists | |
986 st = (check_dnsbl(priv, con.get_dnsbl_list(), rejectlist)) ? reject : oksofar; | |
987 } | |
988 if (st == reject) { | |
989 // reject the recipient based on some dnsbl | |
990 char adr[sizeof "255.255.255.255"]; | |
991 adr[0] = '\0'; | |
992 inet_ntop(AF_INET, (const u_char *)&priv.ip, adr, sizeof(adr)); | |
993 char buf[maxlen]; | |
994 snprintf(buf, sizeof(buf), rejectlist->message, adr, adr); | |
995 smfi_setreply(ctx, "550", "5.7.1", buf); | |
996 return SMFIS_REJECT; | |
997 } | |
998 if (st == black) { | |
999 // reject the recipient based on blacklisting either from or to | |
1000 smfi_setreply(ctx, "550", "5.7.1", "no such user"); | |
1001 return SMFIS_REJECT; | |
1002 } | |
1003 if (ver && (st != white)) { | |
1004 // try to verify this from/to pair of addresses since it is not explicitly whitelisted | |
1005 char *loto = to_lower_string(rcptaddr); | |
1006 bool rc = ver->ok(priv.mailaddr, loto); | |
1007 free(loto); | |
1008 if (!rc) { | |
1009 smfi_setreply(ctx, "550", "5.7.1", "no such user"); | |
1010 return SMFIS_REJECT; | |
1011 } | |
1012 } | |
1013 // accept the recipient | |
1014 if (!con.get_content_filtering()) st = white; | |
1015 if (st == oksofar) { | |
1016 // but remember the non-whites | |
1017 priv.need_content_filter(rcptaddr, con); | |
1018 priv.only_whites = false; | |
1019 } | |
1020 if (st == white) { | |
1021 priv.have_whites = true; | |
1022 } | |
1023 return SMFIS_CONTINUE; | |
1024 } | |
1025 | |
1026 sfsistat mlfi_body(SMFICTX *ctx, u_char *data, size_t len) | |
1027 { | |
1028 mlfiPriv &priv = *MLFIPRIV; | |
1029 if (priv.authenticated) return SMFIS_CONTINUE; | |
1030 if (priv.only_whites) return SMFIS_CONTINUE; | |
1031 priv.scanner->scan(data, len); | |
1032 return SMFIS_CONTINUE; | |
1033 } | |
1034 | |
1035 sfsistat mlfi_eom(SMFICTX *ctx) | |
1036 { | |
1037 sfsistat rc; | |
1038 mlfiPriv &priv = *MLFIPRIV; | |
1039 CONFIG &dc = *priv.pc; | |
1040 char *host = NULL; | |
1041 int ip; | |
1042 status st; | |
1043 // process end of message | |
1044 if (priv.authenticated || priv.only_whites) rc = SMFIS_CONTINUE; | |
1045 else { | |
1046 // assert env_to not empty | |
1047 char buf[maxlen]; | |
1048 char *msg = NULL; | |
1049 string_set alive; | |
1050 bool random = false; | |
1051 int limit = 0; | |
1052 for (context_map::iterator i=priv.env_to.begin(); i!=priv.env_to.end(); i++) { | |
1053 char *rcpt = (*i).first; | |
1054 CONTEXT &con = *((*i).second); | |
1055 if (!con.acceptable_content(*priv.memory, msg)) { | |
1056 // bad html tags or excessive hosts | |
1057 smfi_delrcpt(ctx, rcpt); | |
1058 } | |
1059 else { | |
1060 alive.insert(rcpt); | |
1061 random |= con.get_host_random(); | |
1062 limit = max(limit, con.get_host_limit()); | |
1063 } | |
1064 } | |
1065 bool rejecting = alive.empty(); // if alive is empty, we must have set msg above in acceptable_content() | |
1066 if (!rejecting) { | |
124 | 1067 char *fmt, *found; |
1068 if (check_hosts(priv, random, limit, fmt, host, ip, found)) { | |
1069 if (found) { | |
1070 // uribl style | |
1071 snprintf(buf, sizeof(buf), fmt, host, found); | |
1072 } | |
1073 else { | |
1074 // dnsbl style | |
1075 char adr[sizeof "255.255.255.255"]; | |
1076 adr[0] = '\0'; | |
1077 inet_ntop(AF_INET, (const u_char *)&ip, adr, sizeof(adr)); | |
1078 snprintf(buf, sizeof(buf), fmt, host, adr); | |
1079 } | |
94 | 1080 msg = buf; |
1081 rejecting = true; | |
1082 } | |
1083 } | |
1084 if (!rejecting) { | |
1085 rc = SMFIS_CONTINUE; | |
1086 } | |
1087 else if (!priv.have_whites) { | |
1088 // can reject the entire message | |
1089 smfi_setreply(ctx, "550", "5.7.1", msg); | |
1090 rc = SMFIS_REJECT; | |
1091 } | |
1092 else { | |
1093 // need to accept it but remove the recipients that don't want it | |
1094 for (string_set::iterator i=alive.begin(); i!=alive.end(); i++) { | |
1095 char *rcpt = *i; | |
1096 smfi_delrcpt(ctx, rcpt); | |
1097 } | |
1098 rc = SMFIS_CONTINUE; | |
1099 } | |
1100 } | |
1101 // reset for a new message on the same connection | |
1102 mlfi_abort(ctx); | |
1103 return rc; | |
1104 } | |
1105 | |
1106 sfsistat mlfi_abort(SMFICTX *ctx) | |
1107 { | |
1108 mlfiPriv &priv = *MLFIPRIV; | |
1109 priv.reset(); | |
1110 return SMFIS_CONTINUE; | |
1111 } | |
1112 | |
1113 sfsistat mlfi_close(SMFICTX *ctx) | |
1114 { | |
1115 mlfiPriv *priv = MLFIPRIV; | |
1116 if (!priv) return SMFIS_CONTINUE; | |
1117 delete priv; | |
1118 smfi_setpriv(ctx, NULL); | |
1119 return SMFIS_CONTINUE; | |
1120 } | |
1121 | |
1122 struct smfiDesc smfilter = | |
1123 { | |
1124 "DNSBL", // filter name | |
1125 SMFI_VERSION, // version code -- do not change | |
1126 SMFIF_DELRCPT, // flags | |
1127 mlfi_connect, // connection info filter | |
1128 NULL, // SMTP HELO command filter | |
1129 mlfi_envfrom, // envelope sender filter | |
1130 mlfi_envrcpt, // envelope recipient filter | |
1131 NULL, // header filter | |
1132 NULL, // end of header | |
1133 mlfi_body, // body block filter | |
1134 mlfi_eom, // end of message | |
1135 mlfi_abort, // message aborted | |
1136 mlfi_close, // connection cleanup | |
1137 }; | |
1138 | |
1139 | |
1140 //////////////////////////////////////////////// | |
1141 // reload the config | |
1142 // | |
1143 CONFIG* new_conf(); | |
1144 CONFIG* new_conf() { | |
1145 CONFIG *newc = new CONFIG; | |
1146 pthread_mutex_lock(&config_mutex); | |
1147 newc->generation = generation++; | |
1148 pthread_mutex_unlock(&config_mutex); | |
1149 if (debug_syslog) { | |
1150 char buf[maxlen]; | |
1151 snprintf(buf, sizeof(buf), "loading configuration generation %d", newc->generation); | |
1152 my_syslog(buf); | |
1153 } | |
1154 if (load_conf(*newc, "dnsbl.conf")) { | |
1155 newc->load_time = time(NULL); | |
1156 return newc; | |
1157 } | |
1158 delete newc; | |
1159 return NULL; | |
1160 } | |
1161 | |
1162 | |
1163 //////////////////////////////////////////////// | |
1164 // thread to watch the old config files for changes | |
1165 // and reload when needed. we also cleanup old | |
1166 // configs whose reference count has gone to zero. | |
136 | 1167 // we also clear the SMTP AUTH recipient counts hourly |
94 | 1168 // |
1169 void* config_loader(void *arg); | |
1170 void* config_loader(void *arg) { | |
136 | 1171 int loop = 0; |
94 | 1172 typedef set<CONFIG *> configp_set; |
1173 configp_set old_configs; | |
1174 while (loader_run) { | |
1175 sleep(180); // look for modifications every 3 minutes | |
1176 if (!loader_run) break; | |
136 | 1177 loop++; |
1178 if (loop == 20) { | |
1179 // three minutes thru each loop, 20 loops per hour | |
1180 // clear the recipient counts | |
1181 pthread_mutex_lock(&rate_mutex); | |
138 | 1182 for (rcpt_rates::iterator i=rcpt_counts.begin(); i!=rcpt_counts.end(); i++) { |
140 | 1183 (*i).second = 0; |
138 | 1184 } |
136 | 1185 pthread_mutex_unlock(&rate_mutex); |
137 | 1186 loop = 0; |
136 | 1187 } |
94 | 1188 CONFIG &dc = *config; |
1189 time_t then = dc.load_time; | |
1190 struct stat st; | |
1191 bool reload = false; | |
1192 for (string_set::iterator i=dc.config_files.begin(); i!=dc.config_files.end(); i++) { | |
1193 char *fn = *i; | |
1194 if (stat(fn, &st)) reload = true; // file disappeared | |
1195 else if (st.st_mtime > then) reload = true; // file modified | |
1196 if (reload) break; | |
1197 } | |
1198 if (reload) { | |
1199 CONFIG *newc = new_conf(); | |
1200 if (newc) { | |
1201 // replace the global config pointer | |
1202 pthread_mutex_lock(&config_mutex); | |
1203 CONFIG *old = config; | |
1204 config = newc; | |
1205 pthread_mutex_unlock(&config_mutex); | |
1206 if (old) old_configs.insert(old); | |
1207 } | |
1208 else { | |
1209 // failed to load new config | |
1210 my_syslog("failed to load new configuration"); | |
1211 system("echo 'failed to load new dnsbl configuration from /etc/dnsbl' | mail -s 'error in /etc/dnsbl configuration' root"); | |
1212 // update the load time on the current config to prevent complaining every 3 minutes | |
1213 dc.load_time = time(NULL); | |
1214 } | |
1215 } | |
1216 // now look for old configs with zero ref counts | |
1217 for (configp_set::iterator i=old_configs.begin(); i!=old_configs.end(); ) { | |
1218 CONFIG *old = *i; | |
1219 if (!old->reference_count) { | |
1220 if (debug_syslog) { | |
1221 char buf[maxlen]; | |
1222 snprintf(buf, sizeof(buf), "freeing memory for old configuration generation %d", old->generation); | |
1223 my_syslog(buf); | |
1224 } | |
1225 delete old; // destructor does all the work | |
1226 old_configs.erase(i++); | |
1227 } | |
1228 else i++; | |
1229 } | |
1230 } | |
1231 return NULL; | |
1232 } | |
1233 | |
1234 | |
1235 void usage(char *prog); | |
1236 void usage(char *prog) | |
1237 { | |
1238 fprintf(stderr, "Usage: %s [-d [level]] [-c] [-s] [-e from|to] -r port -p sm-sock-addr [-t timeout]\n", prog); | |
1239 fprintf(stderr, "where port is for the connection to our own dns resolver processes\n"); | |
1240 fprintf(stderr, " and should be local-domain-socket-file-name\n"); | |
1241 fprintf(stderr, "where sm-sock-addr is for the connection to sendmail\n"); | |
1242 fprintf(stderr, " and should be one of\n"); | |
1243 fprintf(stderr, " inet:port@ip-address\n"); | |
1244 fprintf(stderr, " local:local-domain-socket-file-name\n"); | |
1245 fprintf(stderr, "-c will load and dump the config to stdout\n"); | |
1246 fprintf(stderr, "-s will stress test the config loading code by repeating the load/free cycle\n"); | |
1247 fprintf(stderr, " in an infinte loop.\n"); | |
1248 fprintf(stderr, "-d will set the syslog message level, currently 0 to 3\n"); | |
1249 fprintf(stderr, "-e will print the results of looking up the from and to addresses in the\n"); | |
1250 fprintf(stderr, " current config. The | character is used to separate the from and to\n"); | |
1251 fprintf(stderr, " addresses in the argument to the -e switch\n"); | |
1252 } | |
1253 | |
1254 | |
1255 | |
1256 void setup_socket(char *sock); | |
1257 void setup_socket(char *sock) { | |
1258 unlink(sock); | |
1259 // sockaddr_un addr; | |
1260 // memset(&addr, '\0', sizeof addr); | |
1261 // addr.sun_family = AF_UNIX; | |
1262 // strncpy(addr.sun_path, sock, sizeof(addr.sun_path)-1); | |
1263 // int s = socket(AF_UNIX, SOCK_STREAM, 0); | |
1264 // bind(s, (sockaddr*)&addr, sizeof(addr)); | |
1265 // close(s); | |
1266 } | |
1267 | |
1268 | |
1269 /* | |
1270 * The signal handler function -- only gets called when a SIGCHLD | |
1271 * is received, ie when a child terminates | |
1272 */ | |
1273 void sig_chld(int signo) | |
1274 { | |
1275 int status; | |
1276 /* Wait for any child without blocking */ | |
1277 while (waitpid(-1, &status, WNOHANG) > 0) { | |
1278 // ignore child exit status, we only do this to cleanup zombies | |
1279 } | |
1280 } | |
1281 | |
1282 | |
1283 int main(int argc, char**argv) | |
1284 { | |
1285 token_init(); | |
1286 bool check = false; | |
1287 bool stress = false; | |
1288 bool setconn = false; | |
1289 bool setreso = false; | |
1290 char *email = NULL; | |
1291 int c; | |
1292 const char *args = "r:p:t:e:d:chs"; | |
1293 extern char *optarg; | |
1294 | |
1295 // Process command line options | |
1296 while ((c = getopt(argc, argv, args)) != -1) { | |
1297 switch (c) { | |
1298 case 'r': | |
1299 if (optarg == NULL || *optarg == '\0') { | |
1300 fprintf(stderr, "Illegal resolver socket: %s\n", optarg); | |
1301 exit(EX_USAGE); | |
1302 } | |
1303 resolver_port = strdup(optarg); | |
1304 setup_socket(resolver_port); | |
1305 setreso = true; | |
1306 break; | |
1307 | |
1308 case 'p': | |
1309 if (optarg == NULL || *optarg == '\0') { | |
1310 fprintf(stderr, "Illegal sendmail socket: %s\n", optarg); | |
1311 exit(EX_USAGE); | |
1312 } | |
1313 if (smfi_setconn(optarg) == MI_FAILURE) { | |
1314 fprintf(stderr, "smfi_setconn failed\n"); | |
1315 exit(EX_SOFTWARE); | |
1316 } | |
1317 if (strncasecmp(optarg, "unix:", 5) == 0) setup_socket(optarg + 5); | |
1318 else if (strncasecmp(optarg, "local:", 6) == 0) setup_socket(optarg + 6); | |
1319 setconn = true; | |
1320 break; | |
1321 | |
1322 case 't': | |
1323 if (optarg == NULL || *optarg == '\0') { | |
1324 fprintf(stderr, "Illegal timeout: %s\n", optarg); | |
1325 exit(EX_USAGE); | |
1326 } | |
1327 if (smfi_settimeout(atoi(optarg)) == MI_FAILURE) { | |
1328 fprintf(stderr, "smfi_settimeout failed\n"); | |
1329 exit(EX_SOFTWARE); | |
1330 } | |
1331 break; | |
1332 | |
1333 case 'e': | |
1334 if (email) free(email); | |
1335 email = strdup(optarg); | |
1336 break; | |
1337 | |
1338 case 'c': | |
1339 check = true; | |
1340 break; | |
1341 | |
1342 case 's': | |
1343 stress = true; | |
1344 break; | |
1345 | |
1346 case 'd': | |
1347 if (optarg == NULL || *optarg == '\0') debug_syslog = 1; | |
1348 else debug_syslog = atoi(optarg); | |
1349 break; | |
1350 | |
1351 case 'h': | |
1352 default: | |
1353 usage(argv[0]); | |
1354 exit(EX_USAGE); | |
1355 } | |
1356 } | |
1357 | |
1358 if (check) { | |
1359 use_syslog = false; | |
1360 debug_syslog = 10; | |
1361 CONFIG *conf = new_conf(); | |
1362 if (conf) { | |
1363 conf->dump(); | |
1364 delete conf; | |
1365 return 0; | |
1366 } | |
1367 else { | |
1368 return 1; // config failed to load | |
1369 } | |
1370 } | |
1371 | |
1372 if (stress) { | |
1373 fprintf(stdout, "stress testing\n"); | |
1374 while (1) { | |
1375 for (int i=0; i<10; i++) { | |
1376 CONFIG *conf = new_conf(); | |
1377 if (conf) delete conf; | |
1378 } | |
1379 fprintf(stdout, "."); | |
1380 fflush(stdout); | |
1381 sleep(1); | |
1382 } | |
1383 } | |
1384 | |
1385 if (email) { | |
1386 char *x = strchr(email, '|'); | |
1387 if (x) { | |
1388 *x = '\0'; | |
1389 char *from = strdup(email); | |
1390 char *to = strdup(x+1); | |
1391 use_syslog = false; | |
1392 CONFIG *conf = new_conf(); | |
1393 if (conf) { | |
1394 CONTEXTP con = conf->find_context(to); | |
1395 char buf[maxlen]; | |
1396 fprintf(stdout, "envelope to <%s> finds context %s\n", to, con->get_full_name(buf,maxlen)); | |
1397 CONTEXTP fc = con->find_context(from); | |
1398 fprintf(stdout, "envelope from <%s> finds context %s\n", from, fc->get_full_name(buf,maxlen)); | |
1399 char *st = fc->find_from(from); | |
1400 fprintf(stdout, "envelope from <%s> finds status %s\n", from, st); | |
1401 delete conf; | |
1402 } | |
1403 } | |
1404 return 0; | |
1405 } | |
1406 | |
1407 if (!setconn) { | |
1408 fprintf(stderr, "%s: Missing required -p argument\n", argv[0]); | |
1409 usage(argv[0]); | |
1410 exit(EX_USAGE); | |
1411 } | |
1412 | |
1413 if (!setreso) { | |
1414 fprintf(stderr, "%s: Missing required -r argument\n", argv[0]); | |
1415 usage(argv[0]); | |
1416 exit(EX_USAGE); | |
1417 } | |
1418 | |
1419 if (smfi_register(smfilter) == MI_FAILURE) { | |
1420 fprintf(stderr, "smfi_register failed\n"); | |
1421 exit(EX_UNAVAILABLE); | |
1422 } | |
1423 | |
1424 // switch to background mode | |
1425 if (daemon(1,0) < 0) { | |
1426 fprintf(stderr, "daemon() call failed\n"); | |
1427 exit(EX_UNAVAILABLE); | |
1428 } | |
1429 | |
1430 // write the pid | |
1431 const char *pidpath = "/var/run/dnsbl.pid"; | |
1432 unlink(pidpath); | |
1433 FILE *f = fopen(pidpath, "w"); | |
1434 if (f) { | |
1435 #ifdef linux | |
1436 // from a comment in the DCC source code: | |
1437 // Linux threads are broken. Signals given the | |
1438 // original process are delivered to only the | |
1439 // thread that happens to have that PID. The | |
1440 // sendmail libmilter thread that needs to hear | |
1441 // SIGINT and other signals does not, and that breaks | |
1442 // scripts that need to stop milters. | |
1443 // However, signaling the process group works. | |
1444 fprintf(f, "-%d\n", (u_int)getpgrp()); | |
1445 #else | |
1446 fprintf(f, "%d\n", (u_int)getpid()); | |
1447 #endif | |
1448 fclose(f); | |
1449 } | |
1450 | |
1451 // initialize the thread sync objects | |
1452 pthread_mutex_init(&config_mutex, 0); | |
1453 pthread_mutex_init(&syslog_mutex, 0); | |
1454 pthread_mutex_init(&resolve_mutex, 0); | |
1455 pthread_mutex_init(&fd_pool_mutex, 0); | |
1456 | |
1457 // drop root privs | |
1458 struct passwd *pw = getpwnam("dnsbl"); | |
1459 if (pw) { | |
1460 if (setgid(pw->pw_gid) == -1) { | |
1461 my_syslog("failed to switch to group dnsbl"); | |
1462 } | |
1463 if (setuid(pw->pw_uid) == -1) { | |
1464 my_syslog("failed to switch to user dnsbl"); | |
1465 } | |
1466 } | |
1467 | |
1468 // load the initial config | |
1469 config = new_conf(); | |
1470 if (!config) { | |
1471 my_syslog("failed to load initial configuration, quitting"); | |
1472 exit(1); | |
1473 } | |
1474 | |
1475 // fork off the resolver listener process | |
1476 pid_t child = fork(); | |
1477 if (child < 0) { | |
1478 my_syslog("failed to create resolver listener process"); | |
1479 exit(0); | |
1480 } | |
1481 if (child == 0) { | |
1482 // we are the child - dns resolver listener process | |
1483 resolver_socket = socket(AF_UNIX, SOCK_STREAM, 0); | |
1484 if (resolver_socket < 0) { | |
1485 my_syslog("child failed to create resolver socket"); | |
1486 exit(0); // failed | |
1487 } | |
1488 sockaddr_un server; | |
1489 memset(&server, '\0', sizeof(server)); | |
1490 server.sun_family = AF_UNIX; | |
1491 strncpy(server.sun_path, resolver_port, sizeof(server.sun_path)-1); | |
1492 //try to bind the address to the socket. | |
1493 if (bind(resolver_socket, (sockaddr *)&server, sizeof(server)) < 0) { | |
1494 // bind failed | |
1495 shutdown(resolver_socket, SHUT_RDWR); | |
1496 close(resolver_socket); | |
1497 my_syslog("child failed to bind resolver socket"); | |
1498 exit(0); // failed | |
1499 } | |
1500 //listen on the socket. | |
1501 if (listen(resolver_socket, 10) < 0) { | |
1502 // listen failed | |
1503 shutdown(resolver_socket, SHUT_RDWR); | |
1504 close(resolver_socket); | |
1505 my_syslog("child failed to listen to resolver socket"); | |
1506 exit(0); // failed | |
1507 } | |
1508 // setup sigchld handler to prevent zombies | |
1509 struct sigaction act; | |
1510 act.sa_handler = sig_chld; // Assign sig_chld as our SIGCHLD handler | |
1511 sigemptyset(&act.sa_mask); // We don't want to block any other signals in this example | |
1512 act.sa_flags = SA_NOCLDSTOP; // only want children that have terminated | |
1513 if (sigaction(SIGCHLD, &act, NULL) < 0) { | |
1514 my_syslog("child failed to setup SIGCHLD handler"); | |
1515 exit(0); // failed | |
1516 } | |
1517 while (true) { | |
1518 sockaddr_un client; | |
1519 socklen_t clientlen = sizeof(client); | |
1520 int s = accept(resolver_socket, (sockaddr *)&client, &clientlen); | |
1521 if (s > 0) { | |
1522 // accept worked, it did not get cancelled before we could accept it | |
1523 // fork off a process to handle this connection | |
1524 int newchild = fork(); | |
1525 if (newchild == 0) { | |
1526 // this is the worker process | |
1527 // child does not need the listening socket | |
1528 close(resolver_socket); | |
1529 process_resolver_requests(s); | |
1530 exit(0); | |
1531 } | |
1532 else { | |
1533 // this is the parent | |
1534 // parent does not need the accepted socket | |
1535 close(s); | |
1536 } | |
1537 } | |
1538 } | |
1539 exit(0); // make sure we don't fall thru. | |
1540 } | |
1541 else { | |
1542 sleep(2); // allow child to get started | |
1543 } | |
1544 | |
1545 // only create threads after the fork() in daemon | |
1546 pthread_t tid; | |
1547 if (pthread_create(&tid, 0, config_loader, 0)) | |
1548 my_syslog("failed to create config loader thread"); | |
1549 if (pthread_detach(tid)) | |
1550 my_syslog("failed to detach config loader thread"); | |
1551 if (pthread_create(&tid, 0, verify_closer, 0)) | |
1552 my_syslog("failed to create verify closer thread"); | |
1553 if (pthread_detach(tid)) | |
1554 my_syslog("failed to detach verify closer thread"); | |
1555 | |
1556 time_t starting = time(NULL); | |
1557 int rc = smfi_main(); | |
1558 if ((rc != MI_SUCCESS) && (time(NULL) > starting+5*60)) { | |
1559 my_syslog("trying to restart after smfi_main()"); | |
1560 loader_run = false; // eventually the config loader thread will terminate | |
1561 execvp(argv[0], argv); | |
1562 } | |
1563 exit((rc == MI_SUCCESS) ? 0 : EX_UNAVAILABLE); | |
1564 } | |
1565 |