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