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