Mercurial > dnsbl
annotate src/dnsbl.cpp @ 143:ecb40aa3eaa5 stable-5-23
require two periods for ip addresses
author | carl |
---|---|
date | Tue, 10 Oct 2006 19:12:16 -0700 |
parents | b82e00146672 |
children | 7278c9766e26 |
rev | line source |
---|---|
94 | 1 /* |
2 | |
143 | 3 Copyright (c) 2006 Carl Byington - 510 Software Group, released |
94 | 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); | |
142 | 964 if (debug_syslog > 1) { |
965 char buf[maxlen]; | |
966 char msg[maxlen]; | |
967 snprintf(msg, sizeof(msg), "authenticated id %s (%d recipients, %d limit)", priv.authenticated, c, l); | |
968 my_syslog(&priv, msg); | |
969 } | |
136 | 970 if (c > l) { |
971 smfi_setreply(ctx, "550", "5.7.1", "recipient rate limit exceeded"); | |
972 return SMFIS_REJECT; | |
973 } | |
142 | 974 st = white; |
94 | 975 } |
976 else if (fromvalue == token_black) { | |
977 st = black; | |
978 } | |
979 else if (fromvalue == token_white) { | |
980 st = white; | |
981 } | |
982 else { | |
983 // check the dns based lists | |
984 st = (check_dnsbl(priv, con.get_dnsbl_list(), rejectlist)) ? reject : oksofar; | |
985 } | |
986 if (st == reject) { | |
987 // reject the recipient based on some dnsbl | |
988 char adr[sizeof "255.255.255.255"]; | |
989 adr[0] = '\0'; | |
990 inet_ntop(AF_INET, (const u_char *)&priv.ip, adr, sizeof(adr)); | |
991 char buf[maxlen]; | |
992 snprintf(buf, sizeof(buf), rejectlist->message, adr, adr); | |
993 smfi_setreply(ctx, "550", "5.7.1", buf); | |
994 return SMFIS_REJECT; | |
995 } | |
996 if (st == black) { | |
997 // reject the recipient based on blacklisting either from or to | |
998 smfi_setreply(ctx, "550", "5.7.1", "no such user"); | |
999 return SMFIS_REJECT; | |
1000 } | |
1001 if (ver && (st != white)) { | |
1002 // try to verify this from/to pair of addresses since it is not explicitly whitelisted | |
1003 char *loto = to_lower_string(rcptaddr); | |
1004 bool rc = ver->ok(priv.mailaddr, loto); | |
1005 free(loto); | |
1006 if (!rc) { | |
1007 smfi_setreply(ctx, "550", "5.7.1", "no such user"); | |
1008 return SMFIS_REJECT; | |
1009 } | |
1010 } | |
1011 // accept the recipient | |
1012 if (!con.get_content_filtering()) st = white; | |
1013 if (st == oksofar) { | |
1014 // but remember the non-whites | |
1015 priv.need_content_filter(rcptaddr, con); | |
1016 priv.only_whites = false; | |
1017 } | |
1018 if (st == white) { | |
1019 priv.have_whites = true; | |
1020 } | |
1021 return SMFIS_CONTINUE; | |
1022 } | |
1023 | |
1024 sfsistat mlfi_body(SMFICTX *ctx, u_char *data, size_t len) | |
1025 { | |
1026 mlfiPriv &priv = *MLFIPRIV; | |
1027 if (priv.authenticated) return SMFIS_CONTINUE; | |
1028 if (priv.only_whites) return SMFIS_CONTINUE; | |
1029 priv.scanner->scan(data, len); | |
1030 return SMFIS_CONTINUE; | |
1031 } | |
1032 | |
1033 sfsistat mlfi_eom(SMFICTX *ctx) | |
1034 { | |
1035 sfsistat rc; | |
1036 mlfiPriv &priv = *MLFIPRIV; | |
1037 CONFIG &dc = *priv.pc; | |
1038 char *host = NULL; | |
1039 int ip; | |
1040 status st; | |
1041 // process end of message | |
1042 if (priv.authenticated || priv.only_whites) rc = SMFIS_CONTINUE; | |
1043 else { | |
1044 // assert env_to not empty | |
1045 char buf[maxlen]; | |
1046 char *msg = NULL; | |
1047 string_set alive; | |
1048 bool random = false; | |
1049 int limit = 0; | |
1050 for (context_map::iterator i=priv.env_to.begin(); i!=priv.env_to.end(); i++) { | |
1051 char *rcpt = (*i).first; | |
1052 CONTEXT &con = *((*i).second); | |
1053 if (!con.acceptable_content(*priv.memory, msg)) { | |
1054 // bad html tags or excessive hosts | |
1055 smfi_delrcpt(ctx, rcpt); | |
1056 } | |
1057 else { | |
1058 alive.insert(rcpt); | |
1059 random |= con.get_host_random(); | |
1060 limit = max(limit, con.get_host_limit()); | |
1061 } | |
1062 } | |
1063 bool rejecting = alive.empty(); // if alive is empty, we must have set msg above in acceptable_content() | |
1064 if (!rejecting) { | |
124 | 1065 char *fmt, *found; |
1066 if (check_hosts(priv, random, limit, fmt, host, ip, found)) { | |
1067 if (found) { | |
1068 // uribl style | |
1069 snprintf(buf, sizeof(buf), fmt, host, found); | |
1070 } | |
1071 else { | |
1072 // dnsbl style | |
1073 char adr[sizeof "255.255.255.255"]; | |
1074 adr[0] = '\0'; | |
1075 inet_ntop(AF_INET, (const u_char *)&ip, adr, sizeof(adr)); | |
1076 snprintf(buf, sizeof(buf), fmt, host, adr); | |
1077 } | |
94 | 1078 msg = buf; |
1079 rejecting = true; | |
1080 } | |
1081 } | |
1082 if (!rejecting) { | |
1083 rc = SMFIS_CONTINUE; | |
1084 } | |
1085 else if (!priv.have_whites) { | |
1086 // can reject the entire message | |
1087 smfi_setreply(ctx, "550", "5.7.1", msg); | |
1088 rc = SMFIS_REJECT; | |
1089 } | |
1090 else { | |
1091 // need to accept it but remove the recipients that don't want it | |
1092 for (string_set::iterator i=alive.begin(); i!=alive.end(); i++) { | |
1093 char *rcpt = *i; | |
1094 smfi_delrcpt(ctx, rcpt); | |
1095 } | |
1096 rc = SMFIS_CONTINUE; | |
1097 } | |
1098 } | |
1099 // reset for a new message on the same connection | |
1100 mlfi_abort(ctx); | |
1101 return rc; | |
1102 } | |
1103 | |
1104 sfsistat mlfi_abort(SMFICTX *ctx) | |
1105 { | |
1106 mlfiPriv &priv = *MLFIPRIV; | |
1107 priv.reset(); | |
1108 return SMFIS_CONTINUE; | |
1109 } | |
1110 | |
1111 sfsistat mlfi_close(SMFICTX *ctx) | |
1112 { | |
1113 mlfiPriv *priv = MLFIPRIV; | |
1114 if (!priv) return SMFIS_CONTINUE; | |
1115 delete priv; | |
1116 smfi_setpriv(ctx, NULL); | |
1117 return SMFIS_CONTINUE; | |
1118 } | |
1119 | |
1120 struct smfiDesc smfilter = | |
1121 { | |
1122 "DNSBL", // filter name | |
1123 SMFI_VERSION, // version code -- do not change | |
1124 SMFIF_DELRCPT, // flags | |
1125 mlfi_connect, // connection info filter | |
1126 NULL, // SMTP HELO command filter | |
1127 mlfi_envfrom, // envelope sender filter | |
1128 mlfi_envrcpt, // envelope recipient filter | |
1129 NULL, // header filter | |
1130 NULL, // end of header | |
1131 mlfi_body, // body block filter | |
1132 mlfi_eom, // end of message | |
1133 mlfi_abort, // message aborted | |
1134 mlfi_close, // connection cleanup | |
1135 }; | |
1136 | |
1137 | |
1138 //////////////////////////////////////////////// | |
1139 // reload the config | |
1140 // | |
1141 CONFIG* new_conf(); | |
1142 CONFIG* new_conf() { | |
1143 CONFIG *newc = new CONFIG; | |
1144 pthread_mutex_lock(&config_mutex); | |
1145 newc->generation = generation++; | |
1146 pthread_mutex_unlock(&config_mutex); | |
1147 if (debug_syslog) { | |
1148 char buf[maxlen]; | |
1149 snprintf(buf, sizeof(buf), "loading configuration generation %d", newc->generation); | |
1150 my_syslog(buf); | |
1151 } | |
1152 if (load_conf(*newc, "dnsbl.conf")) { | |
1153 newc->load_time = time(NULL); | |
1154 return newc; | |
1155 } | |
1156 delete newc; | |
1157 return NULL; | |
1158 } | |
1159 | |
1160 | |
1161 //////////////////////////////////////////////// | |
1162 // thread to watch the old config files for changes | |
1163 // and reload when needed. we also cleanup old | |
1164 // configs whose reference count has gone to zero. | |
136 | 1165 // we also clear the SMTP AUTH recipient counts hourly |
94 | 1166 // |
1167 void* config_loader(void *arg); | |
1168 void* config_loader(void *arg) { | |
136 | 1169 int loop = 0; |
94 | 1170 typedef set<CONFIG *> configp_set; |
1171 configp_set old_configs; | |
1172 while (loader_run) { | |
1173 sleep(180); // look for modifications every 3 minutes | |
1174 if (!loader_run) break; | |
136 | 1175 loop++; |
1176 if (loop == 20) { | |
1177 // three minutes thru each loop, 20 loops per hour | |
1178 // clear the recipient counts | |
1179 pthread_mutex_lock(&rate_mutex); | |
138 | 1180 for (rcpt_rates::iterator i=rcpt_counts.begin(); i!=rcpt_counts.end(); i++) { |
140 | 1181 (*i).second = 0; |
138 | 1182 } |
136 | 1183 pthread_mutex_unlock(&rate_mutex); |
137 | 1184 loop = 0; |
136 | 1185 } |
94 | 1186 CONFIG &dc = *config; |
1187 time_t then = dc.load_time; | |
1188 struct stat st; | |
1189 bool reload = false; | |
1190 for (string_set::iterator i=dc.config_files.begin(); i!=dc.config_files.end(); i++) { | |
1191 char *fn = *i; | |
1192 if (stat(fn, &st)) reload = true; // file disappeared | |
1193 else if (st.st_mtime > then) reload = true; // file modified | |
1194 if (reload) break; | |
1195 } | |
1196 if (reload) { | |
1197 CONFIG *newc = new_conf(); | |
1198 if (newc) { | |
1199 // replace the global config pointer | |
1200 pthread_mutex_lock(&config_mutex); | |
1201 CONFIG *old = config; | |
1202 config = newc; | |
1203 pthread_mutex_unlock(&config_mutex); | |
1204 if (old) old_configs.insert(old); | |
1205 } | |
1206 else { | |
1207 // failed to load new config | |
1208 my_syslog("failed to load new configuration"); | |
1209 system("echo 'failed to load new dnsbl configuration from /etc/dnsbl' | mail -s 'error in /etc/dnsbl configuration' root"); | |
1210 // update the load time on the current config to prevent complaining every 3 minutes | |
1211 dc.load_time = time(NULL); | |
1212 } | |
1213 } | |
1214 // now look for old configs with zero ref counts | |
1215 for (configp_set::iterator i=old_configs.begin(); i!=old_configs.end(); ) { | |
1216 CONFIG *old = *i; | |
1217 if (!old->reference_count) { | |
1218 if (debug_syslog) { | |
1219 char buf[maxlen]; | |
1220 snprintf(buf, sizeof(buf), "freeing memory for old configuration generation %d", old->generation); | |
1221 my_syslog(buf); | |
1222 } | |
1223 delete old; // destructor does all the work | |
1224 old_configs.erase(i++); | |
1225 } | |
1226 else i++; | |
1227 } | |
1228 } | |
1229 return NULL; | |
1230 } | |
1231 | |
1232 | |
1233 void usage(char *prog); | |
1234 void usage(char *prog) | |
1235 { | |
1236 fprintf(stderr, "Usage: %s [-d [level]] [-c] [-s] [-e from|to] -r port -p sm-sock-addr [-t timeout]\n", prog); | |
1237 fprintf(stderr, "where port is for the connection to our own dns resolver processes\n"); | |
1238 fprintf(stderr, " and should be local-domain-socket-file-name\n"); | |
1239 fprintf(stderr, "where sm-sock-addr is for the connection to sendmail\n"); | |
1240 fprintf(stderr, " and should be one of\n"); | |
1241 fprintf(stderr, " inet:port@ip-address\n"); | |
1242 fprintf(stderr, " local:local-domain-socket-file-name\n"); | |
1243 fprintf(stderr, "-c will load and dump the config to stdout\n"); | |
1244 fprintf(stderr, "-s will stress test the config loading code by repeating the load/free cycle\n"); | |
1245 fprintf(stderr, " in an infinte loop.\n"); | |
1246 fprintf(stderr, "-d will set the syslog message level, currently 0 to 3\n"); | |
1247 fprintf(stderr, "-e will print the results of looking up the from and to addresses in the\n"); | |
1248 fprintf(stderr, " current config. The | character is used to separate the from and to\n"); | |
1249 fprintf(stderr, " addresses in the argument to the -e switch\n"); | |
1250 } | |
1251 | |
1252 | |
1253 | |
1254 void setup_socket(char *sock); | |
1255 void setup_socket(char *sock) { | |
1256 unlink(sock); | |
1257 // sockaddr_un addr; | |
1258 // memset(&addr, '\0', sizeof addr); | |
1259 // addr.sun_family = AF_UNIX; | |
1260 // strncpy(addr.sun_path, sock, sizeof(addr.sun_path)-1); | |
1261 // int s = socket(AF_UNIX, SOCK_STREAM, 0); | |
1262 // bind(s, (sockaddr*)&addr, sizeof(addr)); | |
1263 // close(s); | |
1264 } | |
1265 | |
1266 | |
1267 /* | |
1268 * The signal handler function -- only gets called when a SIGCHLD | |
1269 * is received, ie when a child terminates | |
1270 */ | |
1271 void sig_chld(int signo) | |
1272 { | |
1273 int status; | |
1274 /* Wait for any child without blocking */ | |
1275 while (waitpid(-1, &status, WNOHANG) > 0) { | |
1276 // ignore child exit status, we only do this to cleanup zombies | |
1277 } | |
1278 } | |
1279 | |
1280 | |
1281 int main(int argc, char**argv) | |
1282 { | |
1283 token_init(); | |
1284 bool check = false; | |
1285 bool stress = false; | |
1286 bool setconn = false; | |
1287 bool setreso = false; | |
1288 char *email = NULL; | |
1289 int c; | |
1290 const char *args = "r:p:t:e:d:chs"; | |
1291 extern char *optarg; | |
1292 | |
1293 // Process command line options | |
1294 while ((c = getopt(argc, argv, args)) != -1) { | |
1295 switch (c) { | |
1296 case 'r': | |
1297 if (optarg == NULL || *optarg == '\0') { | |
1298 fprintf(stderr, "Illegal resolver socket: %s\n", optarg); | |
1299 exit(EX_USAGE); | |
1300 } | |
1301 resolver_port = strdup(optarg); | |
1302 setup_socket(resolver_port); | |
1303 setreso = true; | |
1304 break; | |
1305 | |
1306 case 'p': | |
1307 if (optarg == NULL || *optarg == '\0') { | |
1308 fprintf(stderr, "Illegal sendmail socket: %s\n", optarg); | |
1309 exit(EX_USAGE); | |
1310 } | |
1311 if (smfi_setconn(optarg) == MI_FAILURE) { | |
1312 fprintf(stderr, "smfi_setconn failed\n"); | |
1313 exit(EX_SOFTWARE); | |
1314 } | |
1315 if (strncasecmp(optarg, "unix:", 5) == 0) setup_socket(optarg + 5); | |
1316 else if (strncasecmp(optarg, "local:", 6) == 0) setup_socket(optarg + 6); | |
1317 setconn = true; | |
1318 break; | |
1319 | |
1320 case 't': | |
1321 if (optarg == NULL || *optarg == '\0') { | |
1322 fprintf(stderr, "Illegal timeout: %s\n", optarg); | |
1323 exit(EX_USAGE); | |
1324 } | |
1325 if (smfi_settimeout(atoi(optarg)) == MI_FAILURE) { | |
1326 fprintf(stderr, "smfi_settimeout failed\n"); | |
1327 exit(EX_SOFTWARE); | |
1328 } | |
1329 break; | |
1330 | |
1331 case 'e': | |
1332 if (email) free(email); | |
1333 email = strdup(optarg); | |
1334 break; | |
1335 | |
1336 case 'c': | |
1337 check = true; | |
1338 break; | |
1339 | |
1340 case 's': | |
1341 stress = true; | |
1342 break; | |
1343 | |
1344 case 'd': | |
1345 if (optarg == NULL || *optarg == '\0') debug_syslog = 1; | |
1346 else debug_syslog = atoi(optarg); | |
1347 break; | |
1348 | |
1349 case 'h': | |
1350 default: | |
1351 usage(argv[0]); | |
1352 exit(EX_USAGE); | |
1353 } | |
1354 } | |
1355 | |
1356 if (check) { | |
1357 use_syslog = false; | |
1358 debug_syslog = 10; | |
1359 CONFIG *conf = new_conf(); | |
1360 if (conf) { | |
1361 conf->dump(); | |
1362 delete conf; | |
1363 return 0; | |
1364 } | |
1365 else { | |
1366 return 1; // config failed to load | |
1367 } | |
1368 } | |
1369 | |
1370 if (stress) { | |
1371 fprintf(stdout, "stress testing\n"); | |
1372 while (1) { | |
1373 for (int i=0; i<10; i++) { | |
1374 CONFIG *conf = new_conf(); | |
1375 if (conf) delete conf; | |
1376 } | |
1377 fprintf(stdout, "."); | |
1378 fflush(stdout); | |
1379 sleep(1); | |
1380 } | |
1381 } | |
1382 | |
1383 if (email) { | |
1384 char *x = strchr(email, '|'); | |
1385 if (x) { | |
1386 *x = '\0'; | |
1387 char *from = strdup(email); | |
1388 char *to = strdup(x+1); | |
1389 use_syslog = false; | |
1390 CONFIG *conf = new_conf(); | |
1391 if (conf) { | |
1392 CONTEXTP con = conf->find_context(to); | |
1393 char buf[maxlen]; | |
1394 fprintf(stdout, "envelope to <%s> finds context %s\n", to, con->get_full_name(buf,maxlen)); | |
1395 CONTEXTP fc = con->find_context(from); | |
1396 fprintf(stdout, "envelope from <%s> finds context %s\n", from, fc->get_full_name(buf,maxlen)); | |
1397 char *st = fc->find_from(from); | |
1398 fprintf(stdout, "envelope from <%s> finds status %s\n", from, st); | |
1399 delete conf; | |
1400 } | |
1401 } | |
1402 return 0; | |
1403 } | |
1404 | |
1405 if (!setconn) { | |
1406 fprintf(stderr, "%s: Missing required -p argument\n", argv[0]); | |
1407 usage(argv[0]); | |
1408 exit(EX_USAGE); | |
1409 } | |
1410 | |
1411 if (!setreso) { | |
1412 fprintf(stderr, "%s: Missing required -r argument\n", argv[0]); | |
1413 usage(argv[0]); | |
1414 exit(EX_USAGE); | |
1415 } | |
1416 | |
1417 if (smfi_register(smfilter) == MI_FAILURE) { | |
1418 fprintf(stderr, "smfi_register failed\n"); | |
1419 exit(EX_UNAVAILABLE); | |
1420 } | |
1421 | |
1422 // switch to background mode | |
1423 if (daemon(1,0) < 0) { | |
1424 fprintf(stderr, "daemon() call failed\n"); | |
1425 exit(EX_UNAVAILABLE); | |
1426 } | |
1427 | |
1428 // write the pid | |
1429 const char *pidpath = "/var/run/dnsbl.pid"; | |
1430 unlink(pidpath); | |
1431 FILE *f = fopen(pidpath, "w"); | |
1432 if (f) { | |
1433 #ifdef linux | |
1434 // from a comment in the DCC source code: | |
1435 // Linux threads are broken. Signals given the | |
1436 // original process are delivered to only the | |
1437 // thread that happens to have that PID. The | |
1438 // sendmail libmilter thread that needs to hear | |
1439 // SIGINT and other signals does not, and that breaks | |
1440 // scripts that need to stop milters. | |
1441 // However, signaling the process group works. | |
1442 fprintf(f, "-%d\n", (u_int)getpgrp()); | |
1443 #else | |
1444 fprintf(f, "%d\n", (u_int)getpid()); | |
1445 #endif | |
1446 fclose(f); | |
1447 } | |
1448 | |
1449 // initialize the thread sync objects | |
1450 pthread_mutex_init(&config_mutex, 0); | |
1451 pthread_mutex_init(&syslog_mutex, 0); | |
1452 pthread_mutex_init(&resolve_mutex, 0); | |
1453 pthread_mutex_init(&fd_pool_mutex, 0); | |
1454 | |
1455 // drop root privs | |
1456 struct passwd *pw = getpwnam("dnsbl"); | |
1457 if (pw) { | |
1458 if (setgid(pw->pw_gid) == -1) { | |
1459 my_syslog("failed to switch to group dnsbl"); | |
1460 } | |
1461 if (setuid(pw->pw_uid) == -1) { | |
1462 my_syslog("failed to switch to user dnsbl"); | |
1463 } | |
1464 } | |
1465 | |
1466 // load the initial config | |
1467 config = new_conf(); | |
1468 if (!config) { | |
1469 my_syslog("failed to load initial configuration, quitting"); | |
1470 exit(1); | |
1471 } | |
1472 | |
1473 // fork off the resolver listener process | |
1474 pid_t child = fork(); | |
1475 if (child < 0) { | |
1476 my_syslog("failed to create resolver listener process"); | |
1477 exit(0); | |
1478 } | |
1479 if (child == 0) { | |
1480 // we are the child - dns resolver listener process | |
1481 resolver_socket = socket(AF_UNIX, SOCK_STREAM, 0); | |
1482 if (resolver_socket < 0) { | |
1483 my_syslog("child failed to create resolver socket"); | |
1484 exit(0); // failed | |
1485 } | |
1486 sockaddr_un server; | |
1487 memset(&server, '\0', sizeof(server)); | |
1488 server.sun_family = AF_UNIX; | |
1489 strncpy(server.sun_path, resolver_port, sizeof(server.sun_path)-1); | |
1490 //try to bind the address to the socket. | |
1491 if (bind(resolver_socket, (sockaddr *)&server, sizeof(server)) < 0) { | |
1492 // bind failed | |
1493 shutdown(resolver_socket, SHUT_RDWR); | |
1494 close(resolver_socket); | |
1495 my_syslog("child failed to bind resolver socket"); | |
1496 exit(0); // failed | |
1497 } | |
1498 //listen on the socket. | |
1499 if (listen(resolver_socket, 10) < 0) { | |
1500 // listen failed | |
1501 shutdown(resolver_socket, SHUT_RDWR); | |
1502 close(resolver_socket); | |
1503 my_syslog("child failed to listen to resolver socket"); | |
1504 exit(0); // failed | |
1505 } | |
1506 // setup sigchld handler to prevent zombies | |
1507 struct sigaction act; | |
1508 act.sa_handler = sig_chld; // Assign sig_chld as our SIGCHLD handler | |
1509 sigemptyset(&act.sa_mask); // We don't want to block any other signals in this example | |
1510 act.sa_flags = SA_NOCLDSTOP; // only want children that have terminated | |
1511 if (sigaction(SIGCHLD, &act, NULL) < 0) { | |
1512 my_syslog("child failed to setup SIGCHLD handler"); | |
1513 exit(0); // failed | |
1514 } | |
1515 while (true) { | |
1516 sockaddr_un client; | |
1517 socklen_t clientlen = sizeof(client); | |
1518 int s = accept(resolver_socket, (sockaddr *)&client, &clientlen); | |
1519 if (s > 0) { | |
1520 // accept worked, it did not get cancelled before we could accept it | |
1521 // fork off a process to handle this connection | |
1522 int newchild = fork(); | |
1523 if (newchild == 0) { | |
1524 // this is the worker process | |
1525 // child does not need the listening socket | |
1526 close(resolver_socket); | |
1527 process_resolver_requests(s); | |
1528 exit(0); | |
1529 } | |
1530 else { | |
1531 // this is the parent | |
1532 // parent does not need the accepted socket | |
1533 close(s); | |
1534 } | |
1535 } | |
1536 } | |
1537 exit(0); // make sure we don't fall thru. | |
1538 } | |
1539 else { | |
1540 sleep(2); // allow child to get started | |
1541 } | |
1542 | |
1543 // only create threads after the fork() in daemon | |
1544 pthread_t tid; | |
1545 if (pthread_create(&tid, 0, config_loader, 0)) | |
1546 my_syslog("failed to create config loader thread"); | |
1547 if (pthread_detach(tid)) | |
1548 my_syslog("failed to detach config loader thread"); | |
1549 if (pthread_create(&tid, 0, verify_closer, 0)) | |
1550 my_syslog("failed to create verify closer thread"); | |
1551 if (pthread_detach(tid)) | |
1552 my_syslog("failed to detach verify closer thread"); | |
1553 | |
1554 time_t starting = time(NULL); | |
1555 int rc = smfi_main(); | |
1556 if ((rc != MI_SUCCESS) && (time(NULL) > starting+5*60)) { | |
1557 my_syslog("trying to restart after smfi_main()"); | |
1558 loader_run = false; // eventually the config loader thread will terminate | |
1559 execvp(argv[0], argv); | |
1560 } | |
1561 exit((rc == MI_SUCCESS) ? 0 : EX_UNAVAILABLE); | |
1562 } | |
1563 |