Mercurial > dnsbl
annotate src/dnsbl.cpp @ 130:e316f6fd9c39
uribl lookups fully qualified; allow two component host names
author | carl |
---|---|
date | Tue, 01 Aug 2006 10:44:55 -0700 |
parents | c5cd1261394d |
children | df355d117199 |
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; | |
129
c5cd1261394d
ignore smtp connection attempts for 10 minutes when getting connection errors on verify hosts
carl
parents:
128
diff
changeset
|
91 const int NULL_SOCKET = -1; |
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; | |
349 while (len > 1) { | |
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. | |
507 priv.my_write(question, strlen(question)+1); // write the question including the null terminator | |
508 glommer glom; | |
509 char *buf = (char *)&glom; | |
510 priv.my_read(buf, sizeof(glom.length)); | |
511 buf += sizeof(glom.length); | |
512 #ifdef RESOLVER_DEBUG | |
513 char text[1000]; | |
514 snprintf(text, sizeof(text), "dns_interface() wrote question %s and has answer length %d", question, glom.length); | |
515 my_syslog(text); | |
516 #endif | |
517 if ((glom.length < 0) || (glom.length > sizeof(glom.answer))) { | |
518 priv.err = true; | |
519 return 0; // cannot process overlarge answers | |
520 } | |
521 priv.my_read(buf, glom.length); | |
522 | |
523 #ifdef NS_PACKETSZ | |
524 // now we need to lock the resolver mutex to keep the milter threads from | |
525 // stepping on each other while parsing the dns answer. | |
526 int ret_address = 0; | |
527 pthread_mutex_lock(&resolve_mutex); | |
528 if (glom.length > 0) { | |
529 // parse the answer | |
530 ns_msg handle; | |
531 ns_rr rr; | |
532 if (ns_initparse(glom.answer, glom.length, &handle) == 0) { | |
533 // look for ns names | |
534 if (nameservers) { | |
535 ns_map &ns = *nameservers; | |
536 int rrnum = 0; | |
537 while (ns_parserr(&handle, ns_s_ns, rrnum++, &rr) == 0) { | |
538 if (ns_rr_type(rr) == ns_t_ns) { | |
539 char nam[NS_MAXDNAME+1]; | |
540 char *n = nam; | |
541 const u_char *p = ns_rr_rdata(rr); | |
542 while (((n-nam) < NS_MAXDNAME) && ((p-glom.answer) < glom.length) && *p) { | |
543 size_t s = *(p++); | |
544 if (s > 191) { | |
545 // compression pointer | |
546 s = (s-192)*256 + *(p++); | |
547 if (s >= glom.length) break; // pointer outside bounds of answer | |
548 p = glom.answer + s; | |
549 s = *(p++); | |
550 } | |
551 if (s > 0) { | |
552 if ((n-nam) >= (NS_MAXDNAME-s)) break; // destination would overflow name buffer | |
553 if ((p-glom.answer) >= (glom.length-s)) break; // source outside bounds of answer | |
554 memcpy(n, p, s); | |
555 n += s; | |
556 p += s; | |
557 *(n++) = '.'; | |
558 } | |
559 } | |
560 if (n-nam) n--; // remove trailing . | |
561 *n = '\0'; // null terminate it | |
562 ns.add(nam, question); // ns host to lookup later | |
563 } | |
564 } | |
565 rrnum = 0; | |
566 while (ns_parserr(&handle, ns_s_ar, rrnum++, &rr) == 0) { | |
567 if (ns_rr_type(rr) == ns_t_a) { | |
568 char* nam = (char*)ns_rr_name(rr); | |
569 ns_mapper::iterator i = ns.ns_ip.find(nam); | |
570 if (i != ns.ns_ip.end()) { | |
571 // we want this ip address | |
572 int address; | |
573 memcpy(&address, ns_rr_rdata(rr), sizeof(address)); | |
574 ns.ns_ip[nam] = address; | |
575 } | |
576 } | |
577 } | |
578 } | |
579 int rrnum = 0; | |
580 while (ns_parserr(&handle, ns_s_an, rrnum++, &rr) == 0) { | |
581 if (ns_rr_type(rr) == ns_t_a) { | |
582 int address; | |
583 memcpy(&address, ns_rr_rdata(rr), sizeof(address)); | |
584 ret_address = address; | |
585 } | |
586 } | |
587 } | |
588 } | |
589 if (maybe_ip && !ret_address) { | |
590 // might be a bare ip address | |
591 in_addr ip; | |
592 if (inet_aton(question, &ip)) { | |
593 ret_address = ip.s_addr; | |
594 } | |
595 } | |
596 pthread_mutex_unlock(&resolve_mutex); | |
597 return ret_address; | |
598 #else | |
599 return glom.answer; | |
600 #endif | |
601 } | |
602 | |
603 | |
604 //////////////////////////////////////////////// | |
605 // check a single dnsbl | |
606 // | |
607 bool check_single(mlfiPriv &priv, int ip, char *suffix); | |
608 bool check_single(mlfiPriv &priv, int ip, char *suffix) { | |
609 // make a dns question | |
610 const u_char *src = (const u_char *)&ip; | |
611 if (src[0] == 127) return false; // don't do dns lookups on localhost | |
126 | 612 if (src[0] == 10) return false; // don't do dns lookups on rfc1918 space |
613 if ((src[0] == 192) && (src[1] == 168)) return false; | |
614 if ((src[0] == 172) && (16 <= src[1]) && (src[1] <= 31)) return false; | |
94 | 615 #ifdef NS_MAXDNAME |
616 char question[NS_MAXDNAME]; | |
617 #else | |
618 char question[1000]; | |
619 #endif | |
620 snprintf(question, sizeof(question), "%u.%u.%u.%u.%s.", src[3], src[2], src[1], src[0], suffix); | |
621 // ask the question, if we get an A record it implies a blacklisted ip address | |
622 return dns_interface(priv, question, false, NULL); | |
623 } | |
624 | |
625 | |
626 //////////////////////////////////////////////// | |
627 // check a single dnsbl | |
628 // | |
629 bool check_single(mlfiPriv &priv, int ip, DNSBL &bl); | |
630 bool check_single(mlfiPriv &priv, int ip, DNSBL &bl) { | |
631 return check_single(priv, ip, bl.suffix); | |
632 } | |
633 | |
634 | |
635 //////////////////////////////////////////////// | |
636 // check the dnsbls specified for this recipient | |
637 // | |
638 bool check_dnsbl(mlfiPriv &priv, dnsblp_list &dnsbll, DNSBLP &rejectlist); | |
639 bool check_dnsbl(mlfiPriv &priv, dnsblp_list &dnsbll, DNSBLP &rejectlist) { | |
640 for (dnsblp_list::iterator i=dnsbll.begin(); i!=dnsbll.end(); i++) { | |
641 DNSBLP dp = *i; // non null by construction | |
642 bool st; | |
643 map<DNSBLP, bool>::iterator f = priv.checked.find(dp); | |
644 if (f == priv.checked.end()) { | |
645 // have not checked this list yet | |
646 st = check_single(priv, priv.ip, *dp); | |
647 rejectlist = dp; | |
648 priv.checked[dp] = st; | |
649 } | |
650 else { | |
651 st = (*f).second; | |
652 rejectlist = (*f).first; | |
653 } | |
654 if (st) return st; | |
655 } | |
656 return false; | |
657 } | |
658 | |
659 | |
660 //////////////////////////////////////////////// | |
117 | 661 // lookup the domain name part of a hostname on two lists |
662 // | |
124 | 663 // if we find part of the hostname on the uribl, return |
664 // true and point found to the part of the hostname that we found. | |
665 // otherwise, return false and preserve the value of found. | |
666 // | |
667 bool uriblookup(mlfiPriv &priv ,char *hostname, char *top, char *&found) ; | |
668 bool uriblookup(mlfiPriv &priv, char *hostname, char *top, char *&found) { | |
117 | 669 // top is pointer to '.' char at end of base domain, or null for ip address form |
670 // so for hostname of www.fred.mydomain.co.uk | |
671 // top points to-----------------------^ | |
672 // and we end up looking at only mydomain.co.uk, ignoring the www.fred stuff | |
673 char buf[maxlen]; | |
674 if (top) { | |
675 // add one more component | |
676 *top = '\0'; | |
677 char *x = strrchr(hostname, '.'); | |
678 if (x) hostname = x+1; | |
679 *top = '.'; | |
680 } | |
119 | 681 snprintf(buf, sizeof(buf), "%s.%s", hostname, priv.uribl_suffix); |
682 if (dns_interface(priv, buf, false, NULL)) { | |
117 | 683 if (debug_syslog > 2) { |
684 char tmp[maxlen]; | |
119 | 685 snprintf(tmp, sizeof(tmp), "found %s on %s", hostname, priv.uribl_suffix); |
117 | 686 my_syslog(tmp); |
687 } | |
124 | 688 found = hostname; |
119 | 689 return true; |
117 | 690 } |
691 return false; | |
692 } | |
693 | |
694 | |
695 //////////////////////////////////////////////// | |
124 | 696 // uribl checker |
697 // ------------- | |
698 // hostname MUST not have a trailing dot | |
699 // If tld, two level lookup. | |
700 // Else, look up three level domain. | |
701 // | |
702 // if we find part of the hostname on the uribl, return | |
703 // true and point found to the part of the hostname that we found. | |
704 // otherwise, return false and preserve the value of found. | |
705 // | |
706 bool check_uribl(mlfiPriv &priv, char *hostname, char *&found) ; | |
707 bool check_uribl(mlfiPriv &priv, char *hostname, char *&found) { | |
117 | 708 in_addr ip; |
709 if (inet_aton(hostname, &ip)) { | |
120 | 710 const u_char *src = (const u_char *)&ip.s_addr; |
128 | 711 if (src[0] == 127) return false; // don't do dns lookups on localhost |
712 if (src[0] == 10) return false; // don't do dns lookups on rfc1918 space | |
713 if ((src[0] == 192) && (src[1] == 168)) return false; | |
714 if ((src[0] == 172) && (16 <= src[1]) && (src[1] <= 31)) return false; | |
124 | 715 static char adr[sizeof "255.255.255.255"]; |
120 | 716 snprintf(adr, sizeof(adr), "%u.%u.%u.%u", src[3], src[2], src[1], src[0]); |
124 | 717 return (uriblookup(priv, adr, NULL, found)); |
117 | 718 } |
719 | |
720 char *top, *top2, *top3; | |
721 top = strrchr(hostname, '.'); | |
722 if (top) { | |
723 *top = '\0'; | |
724 top2 = strrchr(hostname, '.'); | |
725 *top = '.'; | |
726 | |
727 if (top2) { | |
728 string_set::iterator i = priv.memory->get_cctlds()->find(top2+1); | |
729 string_set::iterator x = priv.memory->get_cctlds()->end(); | |
730 // if we have a 2-level-cctld, just look at top three levels of the name | |
124 | 731 if (i != x) return uriblookup(priv, hostname, top2, found); |
117 | 732 |
733 *top2 = '\0'; | |
734 top3 = strrchr(hostname, '.'); | |
735 *top2 = '.'; | |
736 | |
737 // if we have more than 3 levels in the name, look at the top three levels of the name | |
124 | 738 if (top3 && uriblookup(priv, hostname, top2, found)) return true; |
117 | 739 // if that was not found, fall thru to looking at the top two levels |
740 } | |
741 // look at the top two levels of the name | |
124 | 742 return uriblookup(priv, hostname, top, found); |
117 | 743 } |
744 return false; | |
745 } | |
746 | |
747 | |
748 //////////////////////////////////////////////// | |
119 | 749 // check the hosts from the body against the content filter and uribl dnsbls |
94 | 750 // |
124 | 751 // |
752 bool check_hosts(mlfiPriv &priv, bool random, int limit, char *&msg, char *&host, int &ip, char *&found); | |
753 bool check_hosts(mlfiPriv &priv, bool random, int limit, char *&msg, char *&host, int &ip, char *&found) { | |
754 found = NULL; // normally ip address style | |
119 | 755 if (!priv.content_suffix && !priv.uribl_suffix) return false; // nothing to check |
94 | 756 CONFIG &dc = *priv.pc; |
757 string_set &hosts = priv.memory->get_hosts(); | |
758 string_set &ignore = *priv.content_host_ignore; | |
759 | |
760 int count = 0; | |
761 int cnt = hosts.size(); // number of hosts we could look at | |
762 int_set ips; | |
763 ns_map nameservers; | |
764 for (string_set::iterator i=hosts.begin(); i!=hosts.end(); i++) { | |
765 host = *i; // a reference into hosts, which will live until this smtp transaction is closed | |
766 | |
767 // don't bother looking up hosts on the ignore list | |
768 string_set::iterator j = ignore.find(host); | |
769 if (j != ignore.end()) continue; | |
770 | |
771 // try to only look at limit/cnt fraction of the available cnt host names in random mode | |
772 if ((cnt > limit) && (limit > 0) && random) { | |
773 int r = rand() % cnt; | |
774 if (r >= limit) { | |
775 if (debug_syslog > 2) { | |
776 char buf[maxlen]; | |
777 snprintf(buf, sizeof(buf), "host %s skipped", host); | |
778 my_syslog(&priv, buf); | |
779 } | |
780 continue; | |
781 } | |
782 } | |
783 count++; | |
784 ip = dns_interface(priv, host, true, &nameservers); | |
785 if (debug_syslog > 2) { | |
786 char buf[maxlen]; | |
787 if (ip) { | |
788 char adr[sizeof "255.255.255.255"]; | |
789 adr[0] = '\0'; | |
790 inet_ntop(AF_INET, (const u_char *)&ip, adr, sizeof(adr)); | |
791 snprintf(buf, sizeof(buf), "host %s found at %s", host, adr); | |
792 } | |
793 else { | |
794 snprintf(buf, sizeof(buf), "host %s not found", host); | |
795 } | |
796 my_syslog(&priv, buf); | |
797 } | |
798 if (ip) { | |
799 int_set::iterator i = ips.find(ip); | |
800 if (i == ips.end()) { | |
117 | 801 // we haven't looked this up yet |
94 | 802 ips.insert(ip); |
124 | 803 // check dnsbl style list |
804 if (priv.content_suffix && check_single(priv, ip, priv.content_suffix)) { | |
119 | 805 msg = priv.content_message; |
806 return true; | |
807 } | |
124 | 808 // Check uribl & surbl style list |
809 if (priv.uribl_suffix && check_uribl(priv, host, found)) { | |
119 | 810 msg = priv.uribl_message; |
811 return true; | |
812 } | |
94 | 813 } |
814 } | |
815 } | |
816 limit *= 4; // allow average of 3 ns per host name | |
817 for (ns_mapper::iterator i=nameservers.ns_ip.begin(); i!=nameservers.ns_ip.end(); i++) { | |
818 count++; | |
119 | 819 if ((count > limit) && (limit > 0)) return false; // too many name servers to check them all |
94 | 820 host = (*i).first; // a transient reference that needs to be replaced before we return it |
821 ip = (*i).second; | |
822 if (!ip) ip = dns_interface(priv, host, false, NULL); | |
823 if (debug_syslog > 2) { | |
824 char buf[maxlen]; | |
825 if (ip) { | |
826 char adr[sizeof "255.255.255.255"]; | |
827 adr[0] = '\0'; | |
828 inet_ntop(AF_INET, (const u_char *)&ip, adr, sizeof(adr)); | |
829 snprintf(buf, sizeof(buf), "ns %s found at %s", host, adr); | |
830 } | |
831 else { | |
832 snprintf(buf, sizeof(buf), "ns %s not found", host); | |
833 } | |
834 my_syslog(&priv, buf); | |
835 } | |
836 if (ip) { | |
837 int_set::iterator i = ips.find(ip); | |
838 if (i == ips.end()) { | |
839 ips.insert(ip); | |
119 | 840 if (check_single(priv, ip, priv.content_suffix)) { |
841 msg = priv.content_message; | |
94 | 842 string_map::iterator j = nameservers.ns_host.find(host); |
843 if (j != nameservers.ns_host.end()) { | |
844 char *refer = (*j).second; | |
845 char buf[maxlen]; | |
846 snprintf(buf, sizeof(buf), "%s with nameserver %s", refer, host); | |
847 host = register_string(hosts, buf); // put a copy into hosts, and return that reference | |
848 } | |
849 else { | |
850 host = register_string(hosts, host); // put a copy into hosts, and return that reference | |
851 } | |
852 return true; | |
853 } | |
854 } | |
855 } | |
856 } | |
857 return false; | |
858 } | |
859 | |
127 | 860 |
94 | 861 //////////////////////////////////////////////// |
127 | 862 // |
863 // this email address is passed in from sendmail, and will normally be | |
864 // enclosed in <>. I think older versions of sendmail supplied the <> | |
865 // wrapper if the mail client did not, but the current version does not do | |
866 // that. So the <> wrapper is now optional. It may have mixed case, just | |
867 // as the mail client sent it. We dup the string and convert the duplicate | |
868 // to lower case. | |
94 | 869 // |
870 char *to_lower_string(char *email); | |
871 char *to_lower_string(char *email) { | |
127 | 872 int n = strlen(email); |
873 if (*email == '<') { | |
874 // assume it also ends with > | |
875 n -= 2; | |
876 if (n < 1) return strdup(email); // return "<>" | |
877 email++; | |
878 } | |
879 char *key = strdup(email); | |
94 | 880 key[n] = '\0'; |
881 for (int i=0; i<n; i++) key[i] = tolower(key[i]); | |
882 return key; | |
883 } | |
884 | |
885 | |
886 //////////////////////////////////////////////// | |
887 // start of sendmail milter interfaces | |
888 // | |
889 sfsistat mlfi_connect(SMFICTX *ctx, char *hostname, _SOCK_ADDR *hostaddr) | |
890 { | |
891 // allocate some private memory | |
892 mlfiPriv *priv = new mlfiPriv; | |
893 if (hostaddr->sa_family == AF_INET) { | |
894 priv->ip = ((struct sockaddr_in *)hostaddr)->sin_addr.s_addr; | |
895 } | |
896 | |
897 // save the private data | |
898 smfi_setpriv(ctx, (void*)priv); | |
899 | |
900 // continue processing | |
901 return SMFIS_CONTINUE; | |
902 } | |
903 | |
904 sfsistat mlfi_envfrom(SMFICTX *ctx, char **from) | |
905 { | |
906 mlfiPriv &priv = *MLFIPRIV; | |
907 priv.mailaddr = to_lower_string(from[0]); | |
908 priv.authenticated = (smfi_getsymval(ctx, "{auth_authen}") != NULL); | |
909 return SMFIS_CONTINUE; | |
910 } | |
911 | |
912 sfsistat mlfi_envrcpt(SMFICTX *ctx, char **rcpt) | |
913 { | |
914 DNSBLP rejectlist = NULL; // list that caused the reject | |
915 mlfiPriv &priv = *MLFIPRIV; | |
916 CONFIG &dc = *priv.pc; | |
917 if (!priv.queueid) priv.queueid = strdup(smfi_getsymval(ctx, "i")); | |
918 char *rcptaddr = rcpt[0]; | |
919 char *loto = to_lower_string(rcptaddr); | |
920 CONTEXT &con = *(dc.find_context(loto)->find_context(priv.mailaddr)); | |
921 VERIFYP ver = con.find_verify(loto); | |
922 if (debug_syslog > 1) { | |
923 char buf[maxlen]; | |
924 char msg[maxlen]; | |
925 snprintf(msg, sizeof(msg), "from <%s> to <%s> using context %s", priv.mailaddr, loto, con.get_full_name(buf,maxlen)); | |
926 my_syslog(&priv, msg); | |
927 } | |
928 free(loto); | |
929 char *fromvalue = con.find_from(priv.mailaddr); | |
930 status st; | |
931 if (priv.authenticated) { | |
932 st = white; | |
933 } | |
934 else if (fromvalue == token_black) { | |
935 st = black; | |
936 } | |
937 else if (fromvalue == token_white) { | |
938 st = white; | |
939 } | |
940 else { | |
941 // check the dns based lists | |
942 st = (check_dnsbl(priv, con.get_dnsbl_list(), rejectlist)) ? reject : oksofar; | |
943 } | |
944 if (st == reject) { | |
945 // reject the recipient based on some dnsbl | |
946 char adr[sizeof "255.255.255.255"]; | |
947 adr[0] = '\0'; | |
948 inet_ntop(AF_INET, (const u_char *)&priv.ip, adr, sizeof(adr)); | |
949 char buf[maxlen]; | |
950 snprintf(buf, sizeof(buf), rejectlist->message, adr, adr); | |
951 smfi_setreply(ctx, "550", "5.7.1", buf); | |
952 return SMFIS_REJECT; | |
953 } | |
954 if (st == black) { | |
955 // reject the recipient based on blacklisting either from or to | |
956 smfi_setreply(ctx, "550", "5.7.1", "no such user"); | |
957 return SMFIS_REJECT; | |
958 } | |
959 if (ver && (st != white)) { | |
960 // try to verify this from/to pair of addresses since it is not explicitly whitelisted | |
961 char *loto = to_lower_string(rcptaddr); | |
962 bool rc = ver->ok(priv.mailaddr, loto); | |
963 free(loto); | |
964 if (!rc) { | |
965 smfi_setreply(ctx, "550", "5.7.1", "no such user"); | |
966 return SMFIS_REJECT; | |
967 } | |
968 } | |
969 // accept the recipient | |
970 if (!con.get_content_filtering()) st = white; | |
971 if (st == oksofar) { | |
972 // but remember the non-whites | |
973 priv.need_content_filter(rcptaddr, con); | |
974 priv.only_whites = false; | |
975 } | |
976 if (st == white) { | |
977 priv.have_whites = true; | |
978 } | |
979 return SMFIS_CONTINUE; | |
980 } | |
981 | |
982 sfsistat mlfi_body(SMFICTX *ctx, u_char *data, size_t len) | |
983 { | |
984 mlfiPriv &priv = *MLFIPRIV; | |
985 if (priv.authenticated) return SMFIS_CONTINUE; | |
986 if (priv.only_whites) return SMFIS_CONTINUE; | |
987 priv.scanner->scan(data, len); | |
988 return SMFIS_CONTINUE; | |
989 } | |
990 | |
991 sfsistat mlfi_eom(SMFICTX *ctx) | |
992 { | |
993 sfsistat rc; | |
994 mlfiPriv &priv = *MLFIPRIV; | |
995 CONFIG &dc = *priv.pc; | |
996 char *host = NULL; | |
997 int ip; | |
998 status st; | |
999 // process end of message | |
1000 if (priv.authenticated || priv.only_whites) rc = SMFIS_CONTINUE; | |
1001 else { | |
1002 // assert env_to not empty | |
1003 char buf[maxlen]; | |
1004 char *msg = NULL; | |
1005 string_set alive; | |
1006 bool random = false; | |
1007 int limit = 0; | |
1008 for (context_map::iterator i=priv.env_to.begin(); i!=priv.env_to.end(); i++) { | |
1009 char *rcpt = (*i).first; | |
1010 CONTEXT &con = *((*i).second); | |
1011 if (!con.acceptable_content(*priv.memory, msg)) { | |
1012 // bad html tags or excessive hosts | |
1013 smfi_delrcpt(ctx, rcpt); | |
1014 } | |
1015 else { | |
1016 alive.insert(rcpt); | |
1017 random |= con.get_host_random(); | |
1018 limit = max(limit, con.get_host_limit()); | |
1019 } | |
1020 } | |
1021 bool rejecting = alive.empty(); // if alive is empty, we must have set msg above in acceptable_content() | |
1022 if (!rejecting) { | |
124 | 1023 char *fmt, *found; |
1024 if (check_hosts(priv, random, limit, fmt, host, ip, found)) { | |
1025 if (found) { | |
1026 // uribl style | |
1027 snprintf(buf, sizeof(buf), fmt, host, found); | |
1028 } | |
1029 else { | |
1030 // dnsbl style | |
1031 char adr[sizeof "255.255.255.255"]; | |
1032 adr[0] = '\0'; | |
1033 inet_ntop(AF_INET, (const u_char *)&ip, adr, sizeof(adr)); | |
1034 snprintf(buf, sizeof(buf), fmt, host, adr); | |
1035 } | |
94 | 1036 msg = buf; |
1037 rejecting = true; | |
1038 } | |
1039 } | |
1040 if (!rejecting) { | |
1041 rc = SMFIS_CONTINUE; | |
1042 } | |
1043 else if (!priv.have_whites) { | |
1044 // can reject the entire message | |
1045 smfi_setreply(ctx, "550", "5.7.1", msg); | |
1046 rc = SMFIS_REJECT; | |
1047 } | |
1048 else { | |
1049 // need to accept it but remove the recipients that don't want it | |
1050 for (string_set::iterator i=alive.begin(); i!=alive.end(); i++) { | |
1051 char *rcpt = *i; | |
1052 smfi_delrcpt(ctx, rcpt); | |
1053 } | |
1054 rc = SMFIS_CONTINUE; | |
1055 } | |
1056 } | |
1057 // reset for a new message on the same connection | |
1058 mlfi_abort(ctx); | |
1059 return rc; | |
1060 } | |
1061 | |
1062 sfsistat mlfi_abort(SMFICTX *ctx) | |
1063 { | |
1064 mlfiPriv &priv = *MLFIPRIV; | |
1065 priv.reset(); | |
1066 return SMFIS_CONTINUE; | |
1067 } | |
1068 | |
1069 sfsistat mlfi_close(SMFICTX *ctx) | |
1070 { | |
1071 mlfiPriv *priv = MLFIPRIV; | |
1072 if (!priv) return SMFIS_CONTINUE; | |
1073 delete priv; | |
1074 smfi_setpriv(ctx, NULL); | |
1075 return SMFIS_CONTINUE; | |
1076 } | |
1077 | |
1078 struct smfiDesc smfilter = | |
1079 { | |
1080 "DNSBL", // filter name | |
1081 SMFI_VERSION, // version code -- do not change | |
1082 SMFIF_DELRCPT, // flags | |
1083 mlfi_connect, // connection info filter | |
1084 NULL, // SMTP HELO command filter | |
1085 mlfi_envfrom, // envelope sender filter | |
1086 mlfi_envrcpt, // envelope recipient filter | |
1087 NULL, // header filter | |
1088 NULL, // end of header | |
1089 mlfi_body, // body block filter | |
1090 mlfi_eom, // end of message | |
1091 mlfi_abort, // message aborted | |
1092 mlfi_close, // connection cleanup | |
1093 }; | |
1094 | |
1095 | |
1096 //////////////////////////////////////////////// | |
1097 // reload the config | |
1098 // | |
1099 CONFIG* new_conf(); | |
1100 CONFIG* new_conf() { | |
1101 CONFIG *newc = new CONFIG; | |
1102 pthread_mutex_lock(&config_mutex); | |
1103 newc->generation = generation++; | |
1104 pthread_mutex_unlock(&config_mutex); | |
1105 if (debug_syslog) { | |
1106 char buf[maxlen]; | |
1107 snprintf(buf, sizeof(buf), "loading configuration generation %d", newc->generation); | |
1108 my_syslog(buf); | |
1109 } | |
1110 if (load_conf(*newc, "dnsbl.conf")) { | |
1111 newc->load_time = time(NULL); | |
1112 return newc; | |
1113 } | |
1114 delete newc; | |
1115 return NULL; | |
1116 } | |
1117 | |
1118 | |
1119 //////////////////////////////////////////////// | |
1120 // thread to watch the old config files for changes | |
1121 // and reload when needed. we also cleanup old | |
1122 // configs whose reference count has gone to zero. | |
1123 // | |
1124 void* config_loader(void *arg); | |
1125 void* config_loader(void *arg) { | |
1126 typedef set<CONFIG *> configp_set; | |
1127 configp_set old_configs; | |
1128 while (loader_run) { | |
1129 sleep(180); // look for modifications every 3 minutes | |
1130 if (!loader_run) break; | |
1131 CONFIG &dc = *config; | |
1132 time_t then = dc.load_time; | |
1133 struct stat st; | |
1134 bool reload = false; | |
1135 for (string_set::iterator i=dc.config_files.begin(); i!=dc.config_files.end(); i++) { | |
1136 char *fn = *i; | |
1137 if (stat(fn, &st)) reload = true; // file disappeared | |
1138 else if (st.st_mtime > then) reload = true; // file modified | |
1139 if (reload) break; | |
1140 } | |
1141 if (reload) { | |
1142 CONFIG *newc = new_conf(); | |
1143 if (newc) { | |
1144 // replace the global config pointer | |
1145 pthread_mutex_lock(&config_mutex); | |
1146 CONFIG *old = config; | |
1147 config = newc; | |
1148 pthread_mutex_unlock(&config_mutex); | |
1149 if (old) old_configs.insert(old); | |
1150 } | |
1151 else { | |
1152 // failed to load new config | |
1153 my_syslog("failed to load new configuration"); | |
1154 system("echo 'failed to load new dnsbl configuration from /etc/dnsbl' | mail -s 'error in /etc/dnsbl configuration' root"); | |
1155 // update the load time on the current config to prevent complaining every 3 minutes | |
1156 dc.load_time = time(NULL); | |
1157 } | |
1158 } | |
1159 // now look for old configs with zero ref counts | |
1160 for (configp_set::iterator i=old_configs.begin(); i!=old_configs.end(); ) { | |
1161 CONFIG *old = *i; | |
1162 if (!old->reference_count) { | |
1163 if (debug_syslog) { | |
1164 char buf[maxlen]; | |
1165 snprintf(buf, sizeof(buf), "freeing memory for old configuration generation %d", old->generation); | |
1166 my_syslog(buf); | |
1167 } | |
1168 delete old; // destructor does all the work | |
1169 old_configs.erase(i++); | |
1170 } | |
1171 else i++; | |
1172 } | |
1173 } | |
1174 return NULL; | |
1175 } | |
1176 | |
1177 | |
1178 void usage(char *prog); | |
1179 void usage(char *prog) | |
1180 { | |
1181 fprintf(stderr, "Usage: %s [-d [level]] [-c] [-s] [-e from|to] -r port -p sm-sock-addr [-t timeout]\n", prog); | |
1182 fprintf(stderr, "where port is for the connection to our own dns resolver processes\n"); | |
1183 fprintf(stderr, " and should be local-domain-socket-file-name\n"); | |
1184 fprintf(stderr, "where sm-sock-addr is for the connection to sendmail\n"); | |
1185 fprintf(stderr, " and should be one of\n"); | |
1186 fprintf(stderr, " inet:port@ip-address\n"); | |
1187 fprintf(stderr, " local:local-domain-socket-file-name\n"); | |
1188 fprintf(stderr, "-c will load and dump the config to stdout\n"); | |
1189 fprintf(stderr, "-s will stress test the config loading code by repeating the load/free cycle\n"); | |
1190 fprintf(stderr, " in an infinte loop.\n"); | |
1191 fprintf(stderr, "-d will set the syslog message level, currently 0 to 3\n"); | |
1192 fprintf(stderr, "-e will print the results of looking up the from and to addresses in the\n"); | |
1193 fprintf(stderr, " current config. The | character is used to separate the from and to\n"); | |
1194 fprintf(stderr, " addresses in the argument to the -e switch\n"); | |
1195 } | |
1196 | |
1197 | |
1198 | |
1199 void setup_socket(char *sock); | |
1200 void setup_socket(char *sock) { | |
1201 unlink(sock); | |
1202 // sockaddr_un addr; | |
1203 // memset(&addr, '\0', sizeof addr); | |
1204 // addr.sun_family = AF_UNIX; | |
1205 // strncpy(addr.sun_path, sock, sizeof(addr.sun_path)-1); | |
1206 // int s = socket(AF_UNIX, SOCK_STREAM, 0); | |
1207 // bind(s, (sockaddr*)&addr, sizeof(addr)); | |
1208 // close(s); | |
1209 } | |
1210 | |
1211 | |
1212 /* | |
1213 * The signal handler function -- only gets called when a SIGCHLD | |
1214 * is received, ie when a child terminates | |
1215 */ | |
1216 void sig_chld(int signo) | |
1217 { | |
1218 int status; | |
1219 /* Wait for any child without blocking */ | |
1220 while (waitpid(-1, &status, WNOHANG) > 0) { | |
1221 // ignore child exit status, we only do this to cleanup zombies | |
1222 } | |
1223 } | |
1224 | |
1225 | |
1226 int main(int argc, char**argv) | |
1227 { | |
1228 token_init(); | |
1229 bool check = false; | |
1230 bool stress = false; | |
1231 bool setconn = false; | |
1232 bool setreso = false; | |
1233 char *email = NULL; | |
1234 int c; | |
1235 const char *args = "r:p:t:e:d:chs"; | |
1236 extern char *optarg; | |
1237 | |
1238 // Process command line options | |
1239 while ((c = getopt(argc, argv, args)) != -1) { | |
1240 switch (c) { | |
1241 case 'r': | |
1242 if (optarg == NULL || *optarg == '\0') { | |
1243 fprintf(stderr, "Illegal resolver socket: %s\n", optarg); | |
1244 exit(EX_USAGE); | |
1245 } | |
1246 resolver_port = strdup(optarg); | |
1247 setup_socket(resolver_port); | |
1248 setreso = true; | |
1249 break; | |
1250 | |
1251 case 'p': | |
1252 if (optarg == NULL || *optarg == '\0') { | |
1253 fprintf(stderr, "Illegal sendmail socket: %s\n", optarg); | |
1254 exit(EX_USAGE); | |
1255 } | |
1256 if (smfi_setconn(optarg) == MI_FAILURE) { | |
1257 fprintf(stderr, "smfi_setconn failed\n"); | |
1258 exit(EX_SOFTWARE); | |
1259 } | |
1260 if (strncasecmp(optarg, "unix:", 5) == 0) setup_socket(optarg + 5); | |
1261 else if (strncasecmp(optarg, "local:", 6) == 0) setup_socket(optarg + 6); | |
1262 setconn = true; | |
1263 break; | |
1264 | |
1265 case 't': | |
1266 if (optarg == NULL || *optarg == '\0') { | |
1267 fprintf(stderr, "Illegal timeout: %s\n", optarg); | |
1268 exit(EX_USAGE); | |
1269 } | |
1270 if (smfi_settimeout(atoi(optarg)) == MI_FAILURE) { | |
1271 fprintf(stderr, "smfi_settimeout failed\n"); | |
1272 exit(EX_SOFTWARE); | |
1273 } | |
1274 break; | |
1275 | |
1276 case 'e': | |
1277 if (email) free(email); | |
1278 email = strdup(optarg); | |
1279 break; | |
1280 | |
1281 case 'c': | |
1282 check = true; | |
1283 break; | |
1284 | |
1285 case 's': | |
1286 stress = true; | |
1287 break; | |
1288 | |
1289 case 'd': | |
1290 if (optarg == NULL || *optarg == '\0') debug_syslog = 1; | |
1291 else debug_syslog = atoi(optarg); | |
1292 break; | |
1293 | |
1294 case 'h': | |
1295 default: | |
1296 usage(argv[0]); | |
1297 exit(EX_USAGE); | |
1298 } | |
1299 } | |
1300 | |
1301 if (check) { | |
1302 use_syslog = false; | |
1303 debug_syslog = 10; | |
1304 CONFIG *conf = new_conf(); | |
1305 if (conf) { | |
1306 conf->dump(); | |
1307 delete conf; | |
1308 return 0; | |
1309 } | |
1310 else { | |
1311 return 1; // config failed to load | |
1312 } | |
1313 } | |
1314 | |
1315 if (stress) { | |
1316 fprintf(stdout, "stress testing\n"); | |
1317 while (1) { | |
1318 for (int i=0; i<10; i++) { | |
1319 CONFIG *conf = new_conf(); | |
1320 if (conf) delete conf; | |
1321 } | |
1322 fprintf(stdout, "."); | |
1323 fflush(stdout); | |
1324 sleep(1); | |
1325 } | |
1326 } | |
1327 | |
1328 if (email) { | |
1329 char *x = strchr(email, '|'); | |
1330 if (x) { | |
1331 *x = '\0'; | |
1332 char *from = strdup(email); | |
1333 char *to = strdup(x+1); | |
1334 use_syslog = false; | |
1335 CONFIG *conf = new_conf(); | |
1336 if (conf) { | |
1337 CONTEXTP con = conf->find_context(to); | |
1338 char buf[maxlen]; | |
1339 fprintf(stdout, "envelope to <%s> finds context %s\n", to, con->get_full_name(buf,maxlen)); | |
1340 CONTEXTP fc = con->find_context(from); | |
1341 fprintf(stdout, "envelope from <%s> finds context %s\n", from, fc->get_full_name(buf,maxlen)); | |
1342 char *st = fc->find_from(from); | |
1343 fprintf(stdout, "envelope from <%s> finds status %s\n", from, st); | |
1344 delete conf; | |
1345 } | |
1346 } | |
1347 return 0; | |
1348 } | |
1349 | |
1350 if (!setconn) { | |
1351 fprintf(stderr, "%s: Missing required -p argument\n", argv[0]); | |
1352 usage(argv[0]); | |
1353 exit(EX_USAGE); | |
1354 } | |
1355 | |
1356 if (!setreso) { | |
1357 fprintf(stderr, "%s: Missing required -r argument\n", argv[0]); | |
1358 usage(argv[0]); | |
1359 exit(EX_USAGE); | |
1360 } | |
1361 | |
1362 if (smfi_register(smfilter) == MI_FAILURE) { | |
1363 fprintf(stderr, "smfi_register failed\n"); | |
1364 exit(EX_UNAVAILABLE); | |
1365 } | |
1366 | |
1367 // switch to background mode | |
1368 if (daemon(1,0) < 0) { | |
1369 fprintf(stderr, "daemon() call failed\n"); | |
1370 exit(EX_UNAVAILABLE); | |
1371 } | |
1372 | |
1373 // write the pid | |
1374 const char *pidpath = "/var/run/dnsbl.pid"; | |
1375 unlink(pidpath); | |
1376 FILE *f = fopen(pidpath, "w"); | |
1377 if (f) { | |
1378 #ifdef linux | |
1379 // from a comment in the DCC source code: | |
1380 // Linux threads are broken. Signals given the | |
1381 // original process are delivered to only the | |
1382 // thread that happens to have that PID. The | |
1383 // sendmail libmilter thread that needs to hear | |
1384 // SIGINT and other signals does not, and that breaks | |
1385 // scripts that need to stop milters. | |
1386 // However, signaling the process group works. | |
1387 fprintf(f, "-%d\n", (u_int)getpgrp()); | |
1388 #else | |
1389 fprintf(f, "%d\n", (u_int)getpid()); | |
1390 #endif | |
1391 fclose(f); | |
1392 } | |
1393 | |
1394 // initialize the thread sync objects | |
1395 pthread_mutex_init(&config_mutex, 0); | |
1396 pthread_mutex_init(&syslog_mutex, 0); | |
1397 pthread_mutex_init(&resolve_mutex, 0); | |
1398 pthread_mutex_init(&fd_pool_mutex, 0); | |
1399 | |
1400 // drop root privs | |
1401 struct passwd *pw = getpwnam("dnsbl"); | |
1402 if (pw) { | |
1403 if (setgid(pw->pw_gid) == -1) { | |
1404 my_syslog("failed to switch to group dnsbl"); | |
1405 } | |
1406 if (setuid(pw->pw_uid) == -1) { | |
1407 my_syslog("failed to switch to user dnsbl"); | |
1408 } | |
1409 } | |
1410 | |
1411 // load the initial config | |
1412 config = new_conf(); | |
1413 if (!config) { | |
1414 my_syslog("failed to load initial configuration, quitting"); | |
1415 exit(1); | |
1416 } | |
1417 | |
1418 // fork off the resolver listener process | |
1419 pid_t child = fork(); | |
1420 if (child < 0) { | |
1421 my_syslog("failed to create resolver listener process"); | |
1422 exit(0); | |
1423 } | |
1424 if (child == 0) { | |
1425 // we are the child - dns resolver listener process | |
1426 resolver_socket = socket(AF_UNIX, SOCK_STREAM, 0); | |
1427 if (resolver_socket < 0) { | |
1428 my_syslog("child failed to create resolver socket"); | |
1429 exit(0); // failed | |
1430 } | |
1431 sockaddr_un server; | |
1432 memset(&server, '\0', sizeof(server)); | |
1433 server.sun_family = AF_UNIX; | |
1434 strncpy(server.sun_path, resolver_port, sizeof(server.sun_path)-1); | |
1435 //try to bind the address to the socket. | |
1436 if (bind(resolver_socket, (sockaddr *)&server, sizeof(server)) < 0) { | |
1437 // bind failed | |
1438 shutdown(resolver_socket, SHUT_RDWR); | |
1439 close(resolver_socket); | |
1440 my_syslog("child failed to bind resolver socket"); | |
1441 exit(0); // failed | |
1442 } | |
1443 //listen on the socket. | |
1444 if (listen(resolver_socket, 10) < 0) { | |
1445 // listen failed | |
1446 shutdown(resolver_socket, SHUT_RDWR); | |
1447 close(resolver_socket); | |
1448 my_syslog("child failed to listen to resolver socket"); | |
1449 exit(0); // failed | |
1450 } | |
1451 // setup sigchld handler to prevent zombies | |
1452 struct sigaction act; | |
1453 act.sa_handler = sig_chld; // Assign sig_chld as our SIGCHLD handler | |
1454 sigemptyset(&act.sa_mask); // We don't want to block any other signals in this example | |
1455 act.sa_flags = SA_NOCLDSTOP; // only want children that have terminated | |
1456 if (sigaction(SIGCHLD, &act, NULL) < 0) { | |
1457 my_syslog("child failed to setup SIGCHLD handler"); | |
1458 exit(0); // failed | |
1459 } | |
1460 while (true) { | |
1461 sockaddr_un client; | |
1462 socklen_t clientlen = sizeof(client); | |
1463 int s = accept(resolver_socket, (sockaddr *)&client, &clientlen); | |
1464 if (s > 0) { | |
1465 // accept worked, it did not get cancelled before we could accept it | |
1466 // fork off a process to handle this connection | |
1467 int newchild = fork(); | |
1468 if (newchild == 0) { | |
1469 // this is the worker process | |
1470 // child does not need the listening socket | |
1471 close(resolver_socket); | |
1472 process_resolver_requests(s); | |
1473 exit(0); | |
1474 } | |
1475 else { | |
1476 // this is the parent | |
1477 // parent does not need the accepted socket | |
1478 close(s); | |
1479 } | |
1480 } | |
1481 } | |
1482 exit(0); // make sure we don't fall thru. | |
1483 } | |
1484 else { | |
1485 sleep(2); // allow child to get started | |
1486 } | |
1487 | |
1488 // only create threads after the fork() in daemon | |
1489 pthread_t tid; | |
1490 if (pthread_create(&tid, 0, config_loader, 0)) | |
1491 my_syslog("failed to create config loader thread"); | |
1492 if (pthread_detach(tid)) | |
1493 my_syslog("failed to detach config loader thread"); | |
1494 if (pthread_create(&tid, 0, verify_closer, 0)) | |
1495 my_syslog("failed to create verify closer thread"); | |
1496 if (pthread_detach(tid)) | |
1497 my_syslog("failed to detach verify closer thread"); | |
1498 | |
1499 time_t starting = time(NULL); | |
1500 int rc = smfi_main(); | |
1501 if ((rc != MI_SUCCESS) && (time(NULL) > starting+5*60)) { | |
1502 my_syslog("trying to restart after smfi_main()"); | |
1503 loader_run = false; // eventually the config loader thread will terminate | |
1504 execvp(argv[0], argv); | |
1505 } | |
1506 exit((rc == MI_SUCCESS) ? 0 : EX_UNAVAILABLE); | |
1507 } | |
1508 |