3 // $Id: spamass-milter.cpp,v 1.86 2005/02/05 07:03:22 dnelson Exp $
6 // - a rather trivial SpamAssassin Sendmail Milter plugin
8 // for information about SpamAssassin please see
9 // http://www.spamassassin.org
11 // for information about Sendmail please see
12 // http://www.sendmail.org
14 // Copyright (c) 2002 Georg C. F. Greve <greve@gnu.org>,
15 // all rights maintained by FSF Europe e.V.,
16 // Villa Vogelsang, Antonienallee 1, 45279 Essen, Germany
19 // {{{ License, Contact, Notes & Includes
21 // This program is free software; you can redistribute it and/or modify
22 // it under the terms of the GNU General Public License as published by
23 // the Free Software Foundation; either version 2 of the License, or
24 // (at your option) any later version.
26 // This program is distributed in the hope that it will be useful,
27 // but WITHOUT ANY WARRANTY; without even the implied warranty of
28 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 // GNU General Public License for more details.
31 // You should have received a copy of the GNU General Public License
32 // along with this program; if not, write to the Free Software
33 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
36 // Michael Brown <michaelb@opentext.com>
41 // The libmilter for sendmail works callback-oriented, so if you have no
42 // experience with event-driven programming, the following may be hard for
45 // The code should be reasonably thread-safe. No guarantees, though.
47 // This program roughly does the following steps:
49 // 1. register filter with libmilter & set up socket
50 // 2. register the callback functions defined in this file
51 // -- wait for mail to show up --
52 // 3. start spamc client
53 // 4. assemble mail since libmilter passes it in pieces and put
54 // these parts in the output pipe to spamc.
55 // 5. when the mail is complete, close the pipe.
56 // 6. read output from spamc, close input pipe and clean up PID
57 // 7. check for the flags affected by SpamAssassin and set/change
59 // 8. replace the body with the one provided by SpamAssassin if the
60 // mail was rated spam, unless -m is specified
61 // 9. free all temporary data
62 // 10. tell sendmail to let the mail to go on (default) or be discarded
63 // -- wait for mail to show up -- (restart at 3)
69 #include <arpa/inet.h>
70 #include <sys/types.h>
73 #include <netinet/in.h>
88 #include "subst_poll.h"
103 #include "libmilter/mfapi.h"
104 //#include "libmilter/mfdef.h"
106 #if !HAVE_DECL_STRSEP
107 char *strsep(char **stringp, const char *delim);
110 #if !HAVE_DECL_DAEMON
111 int daemon(int nochdir, int noclose);
118 #include "spamass-milter.h"
124 #ifndef INADDR_LOOPBACK
125 #define INADDR_LOOPBACK 0x7F000001
130 static const char Id[] = "$Id: spamass-milter.cpp,v 1.86 2005/02/05 07:03:22 dnelson Exp $";
132 struct smfiDesc smfilter =
134 "SpamAssassin", // filter name
135 SMFI_VERSION, // version code -- leave untouched
136 SMFIF_ADDHDRS|SMFIF_CHGHDRS|SMFIF_CHGBODY, // flags
137 mlfi_connect, // info filter callback
138 mlfi_helo, // HELO filter callback
139 mlfi_envfrom, // envelope sender filter callback
140 mlfi_envrcpt, // envelope recipient filter callback
141 mlfi_header, // header filter callback
142 mlfi_eoh, // end of header callback
143 mlfi_body, // body filter callback
144 mlfi_eom, // end of message callback
145 mlfi_abort, // message aborted callback
146 mlfi_close, // connection cleanup callback
149 const char *const debugstrings[] = {
150 "ALL", "FUNC", "POLL", "UORI", "STR", "MISC", "NET", "SPAMC", "RCPT",
155 int flag_debug = (1<<D_ALWAYS);
156 bool flag_reject = false;
157 int reject_score = -1;
158 bool dontmodifyspam = false; // Don't modify/add body or spam results headers
159 bool dontmodify = false; // Don't add SA headers, ever.
160 bool flag_sniffuser = false;
161 char *defaultuser; /* Username to send to spamc if there are multiple recipients */
162 char *defaultdomain; /* Domain to append if incoming address has none */
164 struct networklist ignorenets;
167 bool flag_bucket = false;
168 bool flag_bucket_only = false;
170 bool flag_full_email = false; /* pass full email address to spamc */
171 bool flag_expand = false; /* alias/virtusertable expansion */
173 #if defined(__FreeBSD__) /* popen bug - see PR bin/50770 */
174 static pthread_mutex_t popen_mutex = PTHREAD_MUTEX_INITIALIZER;
180 main(int argc, char* argv[])
183 const char *args = "fd:mMp:P:r:u:D:i:b:B:e:x";
186 char *pidfilename = NULL;
187 FILE *pidfile = NULL;
189 #ifdef HAVE_VERBOSE_TERMINATE_HANDLER
190 std::set_terminate (__gnu_cxx::__verbose_terminate_handler);
193 openlog("spamass-milter", LOG_PID, LOG_MAIL);
195 /* Process command line options */
196 while ((c = getopt(argc, argv, args)) != -1) {
202 parse_debuglevel(optarg);
205 spamdhost = strdup(optarg);
208 flag_full_email = true;
209 defaultdomain = strdup(optarg);
212 debug(D_MISC, "Parsing ignore list");
213 parse_networklist(optarg, &ignorenets);
216 dontmodifyspam = true;
217 smfilter.xxfi_flags &= ~SMFIF_CHGBODY;
221 dontmodifyspam = true;
222 smfilter.xxfi_flags &= ~(SMFIF_CHGBODY|SMFIF_CHGHDRS);
225 sock = strdup(optarg);
228 pidfilename = strdup(optarg);
232 reject_score = atoi(optarg);
235 flag_sniffuser = true;
236 defaultuser = strdup(optarg);
242 fprintf(stderr, "Can only have one -b or -B flag\n");
249 flag_bucket_only = true;
250 smfilter.xxfi_flags |= SMFIF_DELRCPT; // May delete recipients
252 // we will modify the recipient list; if spamc returns
253 // indicating that this mail is spam, the message will be
254 // sent to <optarg>@localhost
255 smfilter.xxfi_flags |= SMFIF_ADDRCPT; // May add recipients
256 // XXX we should probably verify that optarg is vaguely sane
257 spambucket = strdup( optarg );
268 if (flag_full_email && !flag_sniffuser)
270 fprintf(stderr, "-e flag requires -u\n");
274 /* remember the remainer of the arguments so we can pass them to spamc */
275 spamc_argc = argc - optind;
276 spamc_argv = argv + optind;
279 cout << PACKAGE_NAME << " - Version " << PACKAGE_VERSION << endl;
280 cout << "SpamAssassin Sendmail Milter Plugin" << endl;
281 cout << "Usage: spamass-milter -p socket [-b|-B bucket] [-d xx[,yy...]] [-D host]" << endl;
282 cout << " [-e defaultdomain] [-f] [-i networks] [-m] [-M]" << endl;
283 cout << " [-P pidfile] [-r nn] [-u defaultuser] [-x]" << endl;
284 cout << " [-- spamc args ]" << endl;
285 cout << " -p socket: path to create socket" << endl;
286 cout << " -b bucket: redirect spam to this mail address. The orignal" << endl;
287 cout << " recipient(s) will not receive anything." << endl;
288 cout << " -B bucket: add this mail address as a BCC recipient of spam." << endl;
289 cout << " -d xx[,yy ...]: set debug flags. Logs to syslog" << endl;
290 cout << " -D host: connect to spamd at remote host (deprecated)" << endl;
291 cout << " -e defaultdomain: pass full email address to spamc instead of just\n"
292 " username. Uses 'defaultdomain' if there was none" << endl;
293 cout << " -f: fork into background" << endl;
294 cout << " -i: skip (ignore) checks from these IPs or netblocks" << endl;
295 cout << " example: -i 192.168.12.5,10.0.0.0/8,172.16/255.255.0.0" << endl;
296 cout << " -m: don't modify body, Content-type: or Subject:" << endl;
297 cout << " -M: don't modify the message at all" << endl;
298 cout << " -P pidfile: Put processid in pidfile" << endl;
299 cout << " -r nn: reject messages with a score >= nn with an SMTP error.\n"
300 " use -1 to reject any messages tagged by SA." << endl;
301 cout << " -u defaultuser: pass the recipient's username to spamc.\n"
302 " Uses 'defaultuser' if there are multiple recipients." << endl;
303 cout << " -x: pass email address through alias and virtusertable expansion." << endl;
304 cout << " -- spamc args: pass the remaining flags to spamc." << endl;
312 pidfile = fopen(pidfilename,"w");
315 fprintf(stderr, "Could not open pidfile: %s\n", strerror(errno));
318 /* leave the file open through the fork, since we don't know our pid
326 if (daemon(0, 0) == -1)
328 fprintf(stderr, "daemon() failed: %s\n", strerror(errno));
335 fprintf(pidfile, "%ld\n", (long)getpid());
342 if (stat(sock,&junk) == 0) unlink(sock);
345 (void) smfi_setconn(sock);
346 if (smfi_register(smfilter) == MI_FAILURE) {
347 fprintf(stderr, "smfi_register failed\n");
348 exit(EX_UNAVAILABLE);
350 debug(D_MISC, "smfi_register succeeded");
352 debug(D_ALWAYS, "spamass-milter %s starting", PACKAGE_VERSION);
354 debug(D_ALWAYS, "spamass-milter %s exiting", PACKAGE_VERSION);
362 /* Update a header if SA changes it, or add it if it is new. */
363 void update_or_insert(SpamAssassin* assassin, SMFICTX* ctx, string oldstring, t_setter setter, char *header )
365 string::size_type eoh1 = assassin->d().find("\n\n");
366 string::size_type eoh2 = assassin->d().find("\n\r\n");
367 string::size_type eoh = ( eoh1 < eoh2 ? eoh1 : eoh2 );
370 string::size_type oldsize;
372 debug(D_UORI, "u_or_i: looking at <%s>", header);
373 debug(D_UORI, "u_or_i: oldstring: <%s>", oldstring.c_str());
375 newstring = retrieve_field(assassin->d().substr(0, eoh), header);
376 debug(D_UORI, "u_or_i: newstring: <%s>", newstring.c_str());
378 oldsize = callsetter(*assassin,setter)(newstring);
382 if (newstring != oldstring)
384 /* change if old one was present, append if non-null */
385 char* cstr = const_cast<char*>(newstring.c_str());
388 debug(D_UORI, "u_or_i: changing");
389 smfi_chgheader(ctx, header, 1, newstring.size() > 0 ?
391 } else if (newstring.size() > 0)
393 debug(D_UORI, "u_or_i: inserting");
394 smfi_addheader(ctx, header, cstr);
398 debug(D_UORI, "u_or_i: no change");
406 // implement the changes suggested by SpamAssassin for the mail. Returns
407 // the milter error code.
409 assassinate(SMFICTX* ctx, SpamAssassin* assassin)
411 // find end of header (eol in last line of header)
412 // and beginning of body
413 string::size_type eoh1 = assassin->d().find("\n\n");
414 string::size_type eoh2 = assassin->d().find("\n\r\n");
415 string::size_type eoh = (eoh1 < eoh2) ? eoh1 : eoh2;
416 string::size_type bob = assassin->d().find_first_not_of("\r\n", eoh);
418 if (bob == string::npos)
419 bob = assassin->d().size();
421 update_or_insert(assassin, ctx, assassin->spam_flag(), &SpamAssassin::set_spam_flag, "X-Spam-Flag");
422 update_or_insert(assassin, ctx, assassin->spam_status(), &SpamAssassin::set_spam_status, "X-Spam-Status");
424 /* Summarily reject the message if SA tagged it, or if we have a minimum
425 score, reject if it exceeds that score. */
428 bool do_reject = false;
429 if (reject_score == -1 && !assassin->spam_flag().empty())
431 if (reject_score != -1)
434 const char *spam_status = assassin->spam_status().c_str();
435 /* SA 3.0 uses the keyword "score" */
436 rv = sscanf(spam_status,"%*s score=%d", &score);
439 /* SA 2.x uses the keyword "hits" */
440 rv = sscanf(spam_status,"%*s hits=%d", &score);
443 debug(D_ALWAYS, "Could not extract score from <%s>", spam_status);
446 debug(D_MISC, "SA score: %d", score);
447 if (score >= reject_score)
453 debug(D_MISC, "Rejecting");
454 smfi_setreply(ctx, "550", "5.7.1", "Blocked by SpamAssassin");
459 /* If we also want a copy of the spam, shell out to sendmail and
460 send another copy. The milter API will not let you send the
461 message AND return a failure code to the sender, so this is
462 the only way to do it. */
463 #if defined(__FreeBSD__)
467 #if defined(HAVE_ASPRINTF)
472 char *fmt="%s \"%s\"";
475 #if defined(HAVE_ASPRINTF)
476 asprintf(&buf, fmt, SENDMAIL, spambucket);
478 #if defined(HAVE_SNPRINTF)
479 snprintf(buf, sizeof(buf)-1, fmt, SENDMAIL, spambucket);
481 /* XXX possible buffer overflow here */
482 sprintf(buf, fmt, SENDMAIL, spambucket);
486 debug(D_COPY, "calling %s", buf);
487 #if defined(__FreeBSD__) /* popen bug - see PR bin/50770 */
488 rv = pthread_mutex_lock(&popen_mutex);
491 debug(D_ALWAYS, "Could not lock popen mutex: %s", strerror(rv));
498 debug(D_COPY, "popen failed(%s). Will not send a copy to spambucket", strerror(errno));
501 // Send message provided by SpamAssassin
502 fwrite(assassin->d().c_str(), assassin->d().size(), 1, p);
505 #if defined(__FreeBSD__)
506 rv = pthread_mutex_unlock(&popen_mutex);
509 debug(D_ALWAYS, "Could not unlock popen mutex: %s", strerror(rv));
513 #if defined(HAVE_ASPRINTF)
521 /* Drop the message into the spam bucket if it's spam */
523 if (!assassin->spam_flag().empty()) {
524 // first, add the spambucket address
525 if ( smfi_addrcpt( ctx, spambucket ) != MI_SUCCESS ) {
526 throw string( "Failed to add spambucket to recipients" );
528 if (flag_bucket_only) {
529 // Move recipients to a non-active header, one at a
530 // time. Note, this may generate multiple X-Spam-Orig-To
531 // headers, but that's okay.
532 while( !assassin->recipients.empty()) {
533 if ( smfi_addheader( ctx, "X-Spam-Orig-To", (char *)assassin->recipients.front().c_str()) != MI_SUCCESS ) {
534 throw string( "Failed to save recipient" );
537 // It's not 100% important that this succeeds, so we'll just warn on failure rather than bailing out.
538 if ( smfi_delrcpt( ctx, (char *)assassin->recipients.front().c_str()) != MI_SUCCESS ) {
539 // throw_error really just logs a warning as opposed to actually throw()ing
540 debug(D_ALWAYS, "Failed to remove recipient %s from the envelope", assassin->recipients.front().c_str() );
542 assassin->recipients.pop_front();
548 update_or_insert(assassin, ctx, assassin->spam_report(), &SpamAssassin::set_spam_report, "X-Spam-Report");
549 update_or_insert(assassin, ctx, assassin->spam_prev_content_type(), &SpamAssassin::set_spam_prev_content_type, "X-Spam-Prev-Content-Type");
550 update_or_insert(assassin, ctx, assassin->spam_level(), &SpamAssassin::set_spam_level, "X-Spam-Level");
551 update_or_insert(assassin, ctx, assassin->spam_checker_version(), &SpamAssassin::set_spam_checker_version, "X-Spam-Checker-Version");
554 // If SpamAssassin thinks it is spam, replace
559 // However, only issue the header replacement calls if the content has
560 // actually changed. If SA didn't change subject or content-type, don't
561 // replace here unnecessarily.
562 if (!dontmodifyspam && assassin->spam_flag().size()>0)
564 update_or_insert(assassin, ctx, assassin->subject(), &SpamAssassin::set_subject, "Subject");
565 update_or_insert(assassin, ctx, assassin->content_type(), &SpamAssassin::set_content_type, "Content-Type");
567 // Replace body with the one SpamAssassin provided
568 string::size_type body_size = assassin->d().size() - bob;
569 string body=assassin->d().substr(bob, string::npos);
570 if ( smfi_replacebody(ctx, (unsigned char *)body.c_str(), body_size) == MI_FAILURE )
571 throw string("error. could not replace body.");
575 return SMFIS_CONTINUE;
578 // retrieve the content of a specific field in the header
581 old_retrieve_field(const string& header, const string& field)
583 // look for beginning of content
584 string::size_type pos = find_nocase(header, "\n" + field + ": ");
586 // return empty string if not found
587 if (pos == string::npos)
589 debug(D_STR, "r_f: failed");
593 // look for end of field name
594 pos = find_nocase(header, " ", pos) + 1;
596 string::size_type pos2(pos);
599 if (pos2 == find_nocase(header, "\n", pos2))
602 // look for end of content
605 pos2 = find_nocase(header, "\n", pos2+1);
608 while ( pos2 < string::npos &&
609 isspace(header[pos2+1]) );
611 return header.substr(pos, pos2-pos);
615 // retrieve the content of a specific field in the header
618 retrieve_field(const string& header, const string& field)
621 string::size_type field_start = string::npos;
622 string::size_type field_end = string::npos;
623 string::size_type idx = 0;
625 while( field_start == string::npos ) {
626 idx = find_nocase( header, field + ":", idx );
629 if ( idx == string::npos ) {
633 // The string we've found needs to be either at the start of the
634 // headers string, or immediately following a "\n"
636 if ( header[ idx - 1 ] != '\n' ) {
637 idx++; // so we don't get stuck in an infinite loop
638 continue; // loop around again
645 // A mail field starts just after the header. Ideally, there's a
646 // space, but it's possible that there isn't.
647 field_start += field.length() + 1;
648 if ( field_start < ( header.length() - 1 ) && header[ field_start ] == ' ' ) {
652 // See if there's anything left, to shortcut the rest of the
654 if ( field_start == header.length() - 1 ) {
658 // The field continues to the end of line. If the start of the next
659 // line is whitespace, then the field continues.
661 while( field_end == string::npos ) {
662 idx = header.find( "\n", idx );
664 // if we don't find a "\n", gobble everything to the end of the headers
665 if ( idx == string::npos ) {
666 field_end = header.length();
668 // check the next character
669 if (( idx + 1 ) < header.length() && ( isspace( header[ idx + 1 ] ))) {
670 idx ++; // whitespace found, so wrap to the next line
677 /* if the header line ends in \r\n, don't return the \r */
678 if (header[field_end-1] == '\r')
681 // Maybe remove the whitespace picked up when a header wraps - this
682 // might actually be a requirement
683 return header.substr( field_start, field_end - field_start );
689 // {{{ MLFI callbacks
692 // Gets called once when a client connects to sendmail
694 // gets the originating IP address and checks it against the ignore list
695 // if it isn't in the list, store the IP in a structure and store a
696 // pointer to it in the private data area.
699 mlfi_connect(SMFICTX * ctx, char *hostname, _SOCK_ADDR * hostaddr)
701 struct context *sctx;
703 debug(D_FUNC, "mlfi_connect: enter");
705 /* allocate a structure to store the IP address (and SA object) in */
706 sctx = (struct context *)malloc(sizeof(*sctx));
709 /* not a socket; probably a local user calling sendmail directly */
710 /* set to 127.0.0.1 */
711 sctx->connect_ip.s_addr = htonl(INADDR_LOOPBACK);
714 sctx->connect_ip = ((struct sockaddr_in *) hostaddr)->sin_addr;
716 sctx->assassin = NULL;
719 /* store a pointer to it with setpriv */
720 smfi_setpriv(ctx, sctx);
722 if (ip_in_networklist(sctx->connect_ip, &ignorenets))
724 debug(D_NET, "%s is in our ignore list - accepting message",
725 inet_ntoa(sctx->connect_ip));
726 debug(D_FUNC, "mlfi_connect: exit ignore");
730 // Tell Milter to continue
731 debug(D_FUNC, "mlfi_connect: exit");
733 return SMFIS_CONTINUE;
737 // Gets called on every "HELO"
739 // stores the result in the context structure
741 sfsistat mlfi_helo(SMFICTX * ctx, char * helohost)
743 struct context *sctx = (struct context*)smfi_getpriv(ctx);
746 sctx->helo = strdup(helohost);
748 return SMFIS_CONTINUE;
752 // Gets called first for all messages
754 // creates SpamAssassin object and makes pointer to it
755 // private data of this filter process
758 mlfi_envfrom(SMFICTX* ctx, char** envfrom)
760 SpamAssassin* assassin;
761 struct context *sctx = (struct context *)smfi_getpriv(ctx);
764 debug(D_FUNC, "mlfi_envfrom: enter");
766 // launch new SpamAssassin
767 assassin=new SpamAssassin;
768 } catch (string& problem)
770 throw_error(problem);
771 return SMFIS_TEMPFAIL;
774 assassin->set_connectip(string(inet_ntoa(sctx->connect_ip)));
776 // Store a pointer to the assassin object in our context struct
777 sctx->assassin = assassin;
779 // remember the MAIL FROM address
780 assassin->set_from(string(envfrom[0]));
782 queueid=smfi_getsymval(ctx,"i");
785 assassin->queueid = queueid;
787 debug(D_MISC, "queueid=%s", queueid);
789 // tell Milter to continue
790 debug(D_FUNC, "mlfi_envfrom: exit");
792 return SMFIS_CONTINUE;
796 // Gets called once for each recipient
798 // stores the first recipient in the spamassassin object and
799 // stores all addresses and the number thereof (some redundancy)
804 mlfi_envrcpt(SMFICTX* ctx, char** envrcpt)
806 struct context *sctx = (struct context*)smfi_getpriv(ctx);
807 SpamAssassin* assassin = sctx->assassin;
809 #if defined(__FreeBSD__)
813 debug(D_FUNC, "mlfi_envrcpt: enter");
817 /* open a pipe to sendmail so we can do address expansion */
820 char *fmt="%s -bv \"%s\" 2>&1";
822 #if defined(HAVE_SNPRINTF)
823 snprintf(buf, sizeof(buf)-1, fmt, SENDMAIL, envrcpt[0]);
825 /* XXX possible buffer overflow here */
826 sprintf(buf, fmt, SENDMAIL, envrcpt[0]);
829 debug(D_RCPT, "calling %s", buf);
831 #if defined(__FreeBSD__) /* popen bug - see PR bin/50770 */
832 rv = pthread_mutex_lock(&popen_mutex);
835 debug(D_ALWAYS, "Could not lock popen mutex: %s", strerror(rv));
843 debug(D_RCPT, "popen failed(%s). Will not expand aliases", strerror(errno));
844 assassin->expandedrcpt.push_back(envrcpt[0]);
847 while (fgets(buf, sizeof(buf), p) != NULL)
850 /* strip trailing EOLs */
851 while (i > 0 && buf[i - 1] <= ' ')
854 debug(D_RCPT, "sendmail output: %s", buf);
855 /* From a quick scan of the sendmail source, a valid email
856 address gets printed via either
857 "deliverable: mailer %s, host %s, user %s"
858 or "deliverable: mailer %s, user %s"
860 if (strstr(buf, "... deliverable: mailer "))
862 char *p=strstr(buf,", user ");
863 /* anything after ", user " is the email address */
864 debug(D_RCPT, "user: %s", p+7);
865 assassin->expandedrcpt.push_back(p+7);
870 #if defined(__FreeBSD__)
871 rv = pthread_mutex_unlock(&popen_mutex);
874 debug(D_ALWAYS, "Could not unlock popen mutex: %s", strerror(rv));
880 assassin->expandedrcpt.push_back(envrcpt[0]);
882 debug(D_RCPT, "Total of %d actual recipients", (int)assassin->expandedrcpt.size());
884 if (assassin->numrcpt() == 0)
886 /* Send the envelope headers as X-Envelope-From: and
887 X-Envelope-To: so that SpamAssassin can use them in its
888 whitelist checks. Also forge as complete a dummy
889 Received: header as possible because SA gets a lot of
892 HReceived: $?sfrom $s $.$?_($?s$|from $.$_)
893 $.$?{auth_type}(authenticated$?{auth_ssf} bits=${auth_ssf}$.)
894 $.by $j ($v/$Z)$?r with $r$. id $i$?{tls_version}
895 (version=${tls_version} cipher=${cipher} bits=${cipher_bits} verify=${verify})$.$?u
901 const char *macro_b, *macro_s, *macro_j, *macro__;
903 /* Failure to fetch {b} is not fatal. Without this date SA can't do
904 future/past validation on the Date: header, but sendmail doesn't
905 default to allow milters to see it.
907 macro_b = smfi_getsymval(ctx, "b");
909 /* Sendmail currently cannot pass us the {s} macro, but
910 I do not know why. Leave this in for the day sendmail is
911 fixed. Until that day, use the value remembered by
914 macro_s = smfi_getsymval(ctx, "s");
916 macro_s = sctx->helo;
920 /* FQDN of this site */
921 macro_j = smfi_getsymval(ctx, "j");
923 macro_j = "localhost";
925 /* Sending site's address */
926 macro__ = smfi_getsymval(ctx, "_");
930 assassin->output((string)"X-Envelope-From: "+assassin->from()+"\r\n");
931 assassin->output((string)"X-Envelope-To: "+envrcpt[0]+"\r\n");
934 assassin->output((string)"Received: from "+macro_s+" ("+macro__+") by "+macro_j+";\r\n");
936 assassin->output((string)"Received: from "+macro_s+" ("+macro__+") by "+macro_j+"; "+macro_b+"\r\n");
939 assassin->output((string)"X-Envelope-To: "+envrcpt[0]+"\r\n");
941 /* increment RCPT TO: count */
942 assassin->set_numrcpt();
944 /* If we expanded to at least one user and we haven't recorded one yet,
945 record the first one */
946 if (!assassin->expandedrcpt.empty() && (assassin->rcpt().size() == 0))
948 debug(D_RCPT, "remembering %s for spamc", assassin->expandedrcpt.front().c_str());
949 assassin->set_rcpt(assassin->expandedrcpt.front());
952 debug(D_RCPT, "remembering recipient %s", envrcpt[0]);
953 assassin->recipients.push_back( envrcpt[0] ); // XXX verify that this worked
955 debug(D_FUNC, "mlfi_envrcpt: exit");
957 return SMFIS_CONTINUE;
961 // Gets called repeatedly for all header fields
963 // assembles the headers and passes them on to the SpamAssassin client
966 // only exception: SpamAssassin header fields (X-Spam-*) get suppressed
967 // but are being stored in the SpamAssassin element.
969 // this function also starts the connection with the SPAMC program the
970 // first time it is called.
974 mlfi_header(SMFICTX* ctx, char* headerf, char* headerv)
976 SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
977 debug(D_FUNC, "mlfi_header: enter");
979 // Check if the SPAMC program has already been run, if not we run it.
980 if ( !(assassin->connected) )
983 assassin->connected = 1; // SPAMC is getting ready to run
986 catch (string& problem) {
987 throw_error(problem);
988 ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
990 debug(D_FUNC, "mlfi_header: exit error connect");
991 return SMFIS_TEMPFAIL;
995 // Is it a "X-Spam-" header field?
996 if ( cmp_nocase_partial("X-Spam-", headerf) == 0 )
999 // memorize content of old fields
1001 if ( cmp_nocase_partial("X-Spam-Status", headerf) == 0 )
1002 assassin->set_spam_status(headerv);
1003 else if ( cmp_nocase_partial("X-Spam-Flag", headerf) == 0 )
1004 assassin->set_spam_flag(headerv);
1005 else if ( cmp_nocase_partial("X-Spam-Report", headerf) == 0 )
1006 assassin->set_spam_report(headerv);
1007 else if ( cmp_nocase_partial("X-Spam-Prev-Content-Type", headerf) == 0 )
1008 assassin->set_spam_prev_content_type(headerv);
1009 else if ( cmp_nocase_partial("X-Spam-Level", headerf) == 0 )
1010 assassin->set_spam_level(headerv);
1011 else if ( cmp_nocase_partial("X-Spam-Checker-Version", headerf) == 0 )
1012 assassin->set_spam_checker_version(headerv);
1015 /* Hm. X-Spam header, but not one we recognize. Pass it through. */
1021 debug(D_FUNC, "mlfi_header: suppress");
1022 return SMFIS_CONTINUE;
1026 // Content-Type: will be stored if present
1027 if ( cmp_nocase_partial("Content-Type", headerf) == 0 )
1028 assassin->set_content_type(headerv);
1030 // Subject: should be stored
1031 if ( cmp_nocase_partial("Subject", headerf) == 0 )
1032 assassin->set_subject(headerv);
1034 // assemble header to be written to SpamAssassin
1035 string header = string(headerf) + ": " + headerv + "\r\n";
1038 // write to SpamAssassin client
1039 assassin->output(header.c_str(),header.size());
1040 } catch (string& problem)
1042 throw_error(problem);
1043 ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1045 debug(D_FUNC, "mlfi_header: exit error output");
1046 return SMFIS_TEMPFAIL;
1050 debug(D_FUNC, "mlfi_header: exit");
1052 return SMFIS_CONTINUE;
1056 // Gets called once when the header is finished.
1058 // writes empty line to SpamAssassin client to separate
1059 // headers from body.
1062 mlfi_eoh(SMFICTX* ctx)
1064 SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1066 debug(D_FUNC, "mlfi_eoh: enter");
1068 // Check if the SPAMC program has already been run, if not we run it.
1069 if ( !(assassin->connected) )
1072 assassin->connected = 1; // SPAMC is getting ready to run
1073 assassin->Connect();
1075 catch (string& problem) {
1076 throw_error(problem);
1077 ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1080 debug(D_FUNC, "mlfi_eoh: exit error connect");
1081 return SMFIS_TEMPFAIL;
1086 // add blank line between header and body
1087 assassin->output("\r\n",2);
1088 } catch (string& problem)
1090 throw_error(problem);
1091 ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1094 debug(D_FUNC, "mlfi_eoh: exit error output");
1095 return SMFIS_TEMPFAIL;
1100 debug(D_FUNC, "mlfi_eoh: exit");
1101 return SMFIS_CONTINUE;
1105 // Gets called repeatedly to transmit the body
1107 // writes everything directly to SpamAssassin client
1110 mlfi_body(SMFICTX* ctx, u_char *bodyp, size_t bodylen)
1112 debug(D_FUNC, "mlfi_body: enter");
1113 SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1117 assassin->output(bodyp, bodylen);
1118 } catch (string& problem)
1120 throw_error(problem);
1121 ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1123 debug(D_FUNC, "mlfi_body: exit error");
1124 return SMFIS_TEMPFAIL;
1128 debug(D_FUNC, "mlfi_body: exit");
1129 return SMFIS_CONTINUE;
1133 // Gets called once at the end of mail processing
1135 // tells SpamAssassin client that the mail is complete
1136 // through EOF and then modifies the mail accordingly by
1137 // calling the "assassinate" function
1140 mlfi_eom(SMFICTX* ctx)
1142 SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1145 debug(D_FUNC, "mlfi_eom: enter");
1148 // close output pipe to signal EOF to SpamAssassin
1149 assassin->close_output();
1151 // read what the Assassin is telling us
1154 milter_status = assassinate(ctx, assassin);
1156 // now cleanup the element.
1157 ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1160 } catch (string& problem)
1162 throw_error(problem);
1163 ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1165 debug(D_FUNC, "mlfi_eom: exit error");
1166 return SMFIS_TEMPFAIL;
1170 debug(D_FUNC, "mlfi_eom: exit");
1171 return milter_status;
1175 // Gets called on session-basis. This keeps things nice & quiet.
1178 mlfi_close(SMFICTX* ctx)
1180 struct context *sctx;
1181 debug(D_FUNC, "mlfi_close");
1183 sctx = (struct context*)smfi_getpriv(ctx);
1186 /* the context should have been set in mlfi_connect */
1187 debug(D_ALWAYS, "NULL context in mlfi_close! Should not happen!");
1188 return SMFIS_ACCEPT;
1193 smfi_setpriv(ctx, NULL);
1195 return SMFIS_ACCEPT;
1199 // Gets called when things are being aborted.
1201 // kills the SpamAssassin object, its destructor should
1202 // take care of everything.
1205 mlfi_abort(SMFICTX* ctx)
1207 SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1209 debug(D_FUNC, "mlfi_abort");
1210 ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1213 return SMFIS_ACCEPT;
1218 // {{{ SpamAssassin Class
1221 // This is a new constructor for the SpamAssassin object. It simply
1222 // initializes two variables. The original constructor has been
1223 // renamed to Connect().
1225 SpamAssassin::SpamAssassin():
1234 SpamAssassin::~SpamAssassin()
1238 // close all pipes that are still open
1239 if (pipe_io[0][0] > -1) close(pipe_io[0][0]);
1240 if (pipe_io[0][1] > -1) close(pipe_io[0][1]);
1241 if (pipe_io[1][0] > -1) close(pipe_io[1][0]);
1242 if (pipe_io[1][1] > -1) close(pipe_io[1][1]);
1244 // child still running?
1247 // make sure the pid is valid
1252 // wait for child to terminate
1254 waitpid(pid, &status, 0);
1259 // Clean up the recip list. Might be overkill, but it's good housekeeping.
1260 while( !recipients.empty())
1262 recipients.pop_front();
1264 // Clean up the recip list. Might be overkill, but it's good housekeeping.
1265 while( !expandedrcpt.empty())
1267 expandedrcpt.pop_front();
1272 // This is the old SpamAssassin constructor. It has been renamed Connect(),
1273 // and is now called at the beginning of the mlfi_header() function.
1276 void SpamAssassin::Connect()
1278 // set up pipes for in- and output
1279 if (pipe(pipe_io[0]))
1280 throw string(string("pipe error: ")+string(strerror(errno)));
1281 if (pipe(pipe_io[1]))
1282 throw string(string("pipe error: ")+string(strerror(errno)));
1284 // now execute SpamAssassin client for contact with SpamAssassin spamd
1286 // start child process
1287 switch(pid = fork())
1290 // forking trouble. throw error.
1291 throw string(string("fork error: ")+string(strerror(errno)));
1296 // close unused pipes
1297 close(pipe_io[1][0]);
1298 close(pipe_io[0][1]);
1300 // redirect stdin(0), stdout(1) and stderr(2)
1301 dup2(pipe_io[0][0],0);
1302 dup2(pipe_io[1][1],1);
1303 dup2(pipe_io[1][1],2);
1308 // absolute path (determined in autoconf)
1309 // should be a little more secure
1310 // XXX arbitrary 100-argument max
1312 char** argv = (char**) malloc(100*sizeof(char*));
1313 argv[argc++] = SPAMC;
1316 argv[argc++] = "-u";
1317 if ( expandedrcpt.size() != 1 )
1319 // More (or less?) than one recipient, so we pass the default
1320 // username to SPAMC. This way special rules can be defined for
1321 // multi recipient messages.
1322 debug(D_RCPT, "%d recipients; spamc gets default username %s", (int)expandedrcpt.size(), defaultuser);
1323 argv[argc++] = defaultuser;
1326 // There is only 1 recipient so we pass the username
1327 // (converted to lowercase) to SPAMC. Don't worry about
1328 // freeing this memory as we're exec()ing anyhow.
1329 if (flag_full_email)
1330 argv[argc] = strlwr(strdup(full_user().c_str()));
1332 argv[argc] = strlwr(strdup(local_user().c_str()));
1334 debug(D_RCPT, "spamc gets %s", argv[argc]);
1341 argv[argc++] = "-d";
1342 argv[argc++] = spamdhost;
1346 memcpy(argv+argc, spamc_argv, spamc_argc * sizeof(char *));
1351 execvp(argv[0] , argv); // does not return!
1354 throw_error(string("execution error: ")+string(strerror(errno)));
1361 // close unused pipes
1362 close(pipe_io[0][0]);
1363 close(pipe_io[1][1]);
1367 // mark the pipes non-blocking
1368 if(fcntl(pipe_io[0][1], F_SETFL, O_NONBLOCK) == -1)
1369 throw string(string("Cannot set pipe01 nonblocking: ")+string(strerror(errno)));
1370 #if 0 /* don't really need to make the sink pipe nonblocking */
1371 if(fcntl(pipe_io[1][0], F_SETFL, O_NONBLOCK) == -1)
1372 throw string(string("Cannot set pipe10 nonblocking: ")+string(strerror(errno)));
1375 // we have to assume the client is running now.
1378 /* If we have any buffered output, write it now. */
1379 if (outputbuffer.size())
1381 output(outputbuffer);
1386 // write to SpamAssassin
1388 SpamAssassin::output(const void* buffer, long size)
1390 debug(D_FUNC, "::output enter");
1392 debug(D_SPAMC, "output \"%*.*s\"", (int)size, (int)size, (char *)buffer);
1394 // if there are problems, fail.
1396 throw string("tried output despite problems. failed.");
1398 /* If we haven't launched spamc yet, just store the data */
1401 /* Silly C++ can't tell the difference between
1402 (const char*, string::size_type) and
1403 (string::size_type, char), so we have to cast the parameters.
1405 outputbuffer.append((const char *)buffer,(string::size_type)size);
1406 debug(D_FUNC, "::output exit1");
1410 // send to SpamAssassin
1416 struct pollfd fds[2];
1417 int nfds = 2, nready;
1418 fds[0].fd = pipe_io[0][1];
1419 fds[0].events = POLLOUT;
1420 fds[1].fd = pipe_io[1][0];
1421 fds[1].events = POLLIN;
1423 debug(D_POLL, "polling fds %d and %d", pipe_io[0][1], pipe_io[1][0]);
1424 nready = poll(fds, nfds, 1000);
1426 throw("poll failed");
1428 debug(D_POLL, "poll returned %d, fd0=%d, fd1=%d", nready, fds[0].revents, fds[1].revents);
1430 if (fds[1].revents & (POLLERR|POLLNVAL|POLLHUP))
1432 throw string("poll says my read pipe is busted");
1435 if (fds[0].revents & (POLLERR|POLLNVAL|POLLHUP))
1437 throw string("poll says my write pipe is busted");
1440 if (fds[1].revents & POLLIN)
1442 debug(D_POLL, "poll says I can read");
1446 if (fds[0].revents & POLLOUT)
1448 debug(D_POLL, "poll says I can write");
1449 switch(wsize = write(pipe_io[0][1], (char *)buffer + total, size - total))
1452 if (errno == EAGAIN)
1454 reason = string(strerror(errno));
1457 close(pipe_io[0][1]);
1458 close(pipe_io[1][0]);
1469 // wait until child is dead
1470 waitpid(pid, &status, 0);
1472 throw string(string("write error: ")+reason);
1476 debug(D_POLL, "wrote %ld bytes", wsize);
1480 } while ( total < size );
1482 debug(D_FUNC, "::output exit2");
1485 void SpamAssassin::output(const void* buffer)
1487 output(buffer, strlen((const char *)buffer));
1490 void SpamAssassin::output(string buffer)
1492 output(buffer.c_str(), buffer.size());
1495 // close output pipe
1497 SpamAssassin::close_output()
1499 if(close(pipe_io[0][1]))
1500 throw string(string("close error: ")+string(strerror(errno)));
1505 SpamAssassin::input()
1507 debug(D_FUNC, "::input enter");
1508 // if the child has exited or we experienced an error, return
1510 if (!running || error)
1512 debug(D_FUNC, "::input exit1");
1516 // keep reading from input pipe until it is empty
1517 empty_and_close_pipe();
1519 // that's it, we're through
1522 // wait until child is dead
1524 if(waitpid(pid, &status, 0)<0)
1527 throw string(string("waitpid error: ")+string(strerror(errno)));
1529 debug(D_FUNC, "::input exit2");
1533 // return reference to mail
1542 // get values of the different SpamAssassin fields
1545 SpamAssassin::spam_status()
1547 return x_spam_status;
1551 SpamAssassin::spam_flag()
1557 SpamAssassin::spam_report()
1559 return x_spam_report;
1563 SpamAssassin::spam_prev_content_type()
1565 return x_spam_prev_content_type;
1569 SpamAssassin::spam_checker_version()
1571 return x_spam_checker_version;
1575 SpamAssassin::spam_level()
1577 return x_spam_level;
1581 SpamAssassin::content_type()
1583 return _content_type;
1587 SpamAssassin::subject()
1593 SpamAssassin::rcpt()
1599 SpamAssassin::from()
1605 SpamAssassin::connectip()
1612 SpamAssassin::local_user()
1614 // assuming we have a recipient in the form: <username@somehost.somedomain>
1615 // (angle brackets optional) we return 'username'
1616 if (_rcpt[0] == '<')
1617 return _rcpt.substr(1, _rcpt.find_first_of("@+")-1);
1619 return _rcpt.substr(0, _rcpt.find_first_of("@+"));
1623 SpamAssassin::full_user()
1626 // assuming we have a recipient in the form: <username@somehost.somedomain>
1627 // (angle brackets optional) we return 'username@somehost.somedomain'
1628 if (_rcpt[0] == '<')
1629 name = _rcpt.substr(1, _rcpt.find('>')-1);
1632 if(name.find('@') == string::npos)
1634 /* if the name had no domain part (local delivery), append the default one */
1635 name = name + "@" + defaultdomain;
1641 SpamAssassin::numrcpt()
1647 SpamAssassin::set_numrcpt()
1654 SpamAssassin::set_numrcpt(const int val)
1661 // set the values of the different SpamAssassin
1662 // fields in our element. Returns former size of field
1665 SpamAssassin::set_spam_status(const string& val)
1667 string::size_type old = x_spam_status.size();
1668 x_spam_status = val;
1673 SpamAssassin::set_spam_flag(const string& val)
1675 string::size_type old = x_spam_flag.size();
1681 SpamAssassin::set_spam_report(const string& val)
1683 string::size_type old = x_spam_report.size();
1684 x_spam_report = val;
1689 SpamAssassin::set_spam_prev_content_type(const string& val)
1691 string::size_type old = x_spam_prev_content_type.size();
1692 x_spam_prev_content_type = val;
1697 SpamAssassin::set_spam_checker_version(const string& val)
1699 string::size_type old = x_spam_checker_version.size();
1700 x_spam_checker_version = val;
1705 SpamAssassin::set_spam_level(const string& val)
1707 string::size_type old = x_spam_level.size();
1713 SpamAssassin::set_content_type(const string& val)
1715 string::size_type old = _content_type.size();
1716 _content_type = val;
1721 SpamAssassin::set_subject(const string& val)
1723 string::size_type old = _subject.size();
1729 SpamAssassin::set_rcpt(const string& val)
1731 string::size_type old = _rcpt.size();
1737 SpamAssassin::set_from(const string& val)
1739 string::size_type old = _from.size();
1745 SpamAssassin::set_connectip(const string& val)
1747 string::size_type old = _connectip.size();
1753 // Read available output from SpamAssassin client
1756 SpamAssassin::read_pipe()
1763 debug(D_FUNC, "::read_pipe enter");
1765 if (pipe_io[1][0] == -1)
1767 debug(D_FUNC, "::read_pipe exit - shouldn't have been called?");
1771 size = read(pipe_io[1][0], iobuff, 1024);
1776 reason = string(strerror(errno));
1778 // Close remaining pipe.
1779 close(pipe_io[1][0]);
1789 // wait until child is dead
1790 waitpid(pid, &status, 0);
1792 // throw the error message that caused this trouble
1793 throw string(string("read error: ")+reason);
1794 } else if ( size == 0 )
1797 // EOF. Close the pipe
1798 if(close(pipe_io[1][0]))
1799 throw string(string("close error: ")+string(strerror(errno)));
1804 // append to mail buffer
1805 mail.append(iobuff, size);
1806 debug(D_POLL, "read %ld bytes", size);
1807 debug(D_SPAMC, "input \"%*.*s\"", (int)size, (int)size, iobuff);
1809 debug(D_FUNC, "::read_pipe exit");
1814 // Read all output from SpamAssassin client
1815 // and close the pipe
1818 SpamAssassin::empty_and_close_pipe()
1820 debug(D_FUNC, "::empty_and_close_pipe enter");
1823 debug(D_FUNC, "::empty_and_close_pipe exit");
1828 // {{{ Some small subroutines without much relation to functionality
1830 // output error message to syslog facility
1832 throw_error(const string& errmsg)
1835 syslog(LOG_ERR, "Thrown error: %s", errmsg.c_str());
1837 syslog(LOG_ERR, "Unknown error");
1840 /* Takes a comma or space-delimited string of debug tokens and sets the
1841 appropriate bits in flag_debug. "all" sets all the bits.
1843 void parse_debuglevel(char* string)
1847 /* make a copy so we don't overwrite argv[] */
1848 string = strdup(string);
1850 /* handle the old numeric values too */
1851 switch(atoi(string))
1854 flag_debug |= (1<<D_UORI) | (1<<D_STR);
1856 flag_debug |= (1<<D_POLL);
1858 flag_debug |= (1<<D_MISC) | (1<<D_FUNC);
1859 debug(D_ALWAYS, "Setting debug level to 0x%0x", flag_debug);
1866 while ((token = strsep(&string, ", ")))
1869 for (i=0; debugstrings[i]; i++)
1871 if(strcasecmp(token, "ALL")==0)
1873 flag_debug = (1<<D_MAX)-1;
1876 if(strcasecmp(token, debugstrings[i])==0)
1878 flag_debug |= (1<<i);
1883 if (!debugstrings[i])
1885 fprintf(stderr, "Invalid debug token \"%s\"\n", token);
1889 debug(D_ALWAYS, "Setting debug level to 0x%0x", flag_debug);
1894 Output a line to syslog using print format, but only if the appropriate
1895 debug level is set. The D_ALWAYS level is always enabled.
1897 void debug(enum debuglevel level, const char* fmt, ...)
1899 if ((1<<level) & flag_debug)
1901 #if defined(HAVE_VSYSLOG)
1904 vsyslog(LOG_ERR, fmt, vl);
1907 #if defined(HAVE_VASPRINTF)
1914 #if defined(HAVE_VASPRINTF)
1915 vasprintf(&buf, fmt, vl);
1917 #if defined(HAVE_VSNPRINTF)
1918 vsnprintf(buf, sizeof(buf)-1, fmt, vl);
1920 /* XXX possible buffer overflow here; be careful what you pass to debug() */
1921 vsprintf(buf, fmt, vl);
1925 syslog(LOG_ERR, "%s", buf);
1926 #if defined(HAVE_VASPRINTF)
1929 #endif /* vsyslog */
1933 // case-insensitive search
1935 find_nocase(const string& array, const string& pattern, string::size_type start)
1937 string::size_type pos(start);
1939 while (pos < array.size())
1941 string::size_type ctr = 0;
1943 while( (pos+ctr) < array.size() &&
1944 toupper(array[pos+ctr]) == toupper(pattern[ctr]) )
1947 if (ctr == pattern.size())
1949 debug(D_STR, "f_nc: <%s><%s>: hit", array.c_str(), pattern.c_str());
1957 debug(D_STR, "f_nc: <%s><%s>: nohit", array.c_str(), pattern.c_str());
1958 return string::npos;
1961 // compare case-insensitive
1963 cmp_nocase_partial(const string& s, const string& s2)
1965 string::const_iterator p=s.begin();
1966 string::const_iterator p2=s2.begin();
1968 while ( p != s.end() && p2 != s2.end() ) {
1969 if (toupper(*p) != toupper(*p2))
1971 debug(D_STR, "c_nc_p: <%s><%s> : miss", s.c_str(), s2.c_str());
1972 return (toupper(*p) < toupper(*p2)) ? -1 : 1;
1978 debug(D_STR, "c_nc_p: <%s><%s> : hit", s.c_str(), s2.c_str());
1983 /* closeall() - close all FDs >= a specified value */
1984 void closeall(int fd)
1986 int fdlimit = sysconf(_SC_OPEN_MAX);
1987 while (fd < fdlimit)
1991 void parse_networklist(char *string, struct networklist *list)
1995 /* make a copy so we don't overwrite argv[] */
1996 string = strdup(string);
1998 while ((token = strsep(&string, ", ")))
2000 char *tnet = strsep(&token, "/");
2001 char *tmask = token;
2002 struct in_addr net, mask;
2004 if (list->num_nets % 10 == 0)
2005 list->nets = (struct net*)realloc(list->nets, sizeof(*list->nets) * (list->num_nets + 10));
2007 if (!inet_aton(tnet, &net))
2009 fprintf(stderr, "Could not parse \"%s\" as a network\n", tnet);
2015 if (strchr(tmask, '.') == NULL)
2020 ret = sscanf(tmask, "%u", &bits);
2021 if (ret != 1 || bits > 32)
2023 fprintf(stderr,"%s: bad CIDR value", tmask);
2026 mask.s_addr = htonl(~((1L << (32 - bits)) - 1) & 0xffffffff);
2027 } else if (!inet_aton(tmask, &mask))
2029 fprintf(stderr, "Could not parse \"%s\" as a netmask\n", tmask);
2033 mask.s_addr = 0xffffffff;
2036 char *snet = strdup(inet_ntoa(net));
2037 debug(D_MISC, "Adding %s/%s to network list", snet, inet_ntoa(mask));
2041 net.s_addr = net.s_addr & mask.s_addr;
2042 list->nets[list->num_nets].network = net;
2043 list->nets[list->num_nets].netmask = mask;
2049 int ip_in_networklist(struct in_addr ip, struct networklist *list)
2053 if (list->num_nets == 0)
2056 debug(D_NET, "Checking %s against:", inet_ntoa(ip));
2057 for (i = 0; i < list->num_nets; i++)
2059 debug(D_NET, "%s", inet_ntoa(list->nets[i].network));
2060 debug(D_NET, "/%s", inet_ntoa(list->nets[i].netmask));
2061 if ((ip.s_addr & list->nets[i].netmask.s_addr) == list->nets[i].network.s_addr)
2063 debug(D_NET, "Hit!");
2071 char *strlwr(char *str)
2083 // vim6:ai:noexpandtab