]> git.donarmstrong.com Git - deb_pkgs/spamass-milter.git/blob - spamass-milter.cpp
revert to upstream versions of config.sub and config.guess; switch to autotools_dev
[deb_pkgs/spamass-milter.git] / spamass-milter.cpp
1 // 
2 //
3 //  $Id: spamass-milter.cpp,v 1.94 2011/02/14 21:50:53 dnelson Exp $
4 //
5 //  SpamAss-Milter 
6 //    - a rather trivial SpamAssassin Sendmail Milter plugin
7 //
8 //  for information about SpamAssassin please see
9 //                        http://www.spamassassin.org
10 //
11 //  for information about Sendmail please see
12 //                        http://www.sendmail.org
13 //
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
17 //
18
19 // {{{ License, Contact, Notes & Includes 
20
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.
25 //  
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.
30 //  
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
34 //
35 //   Contact:
36 //            Michael Brown <michaelb@opentext.com>
37 //
38
39 // Notes:
40 //
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
43 //  you to understand.
44 //
45 //  The code should be reasonably thread-safe. No guarantees, though.
46 //
47 //  This program roughly does the following steps:
48 //
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
58 //      them accordingly
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)
64 //
65
66 // Includes  
67 #include "config.h"
68
69 #include <arpa/inet.h>
70 #include <sys/types.h>
71 #include <sys/wait.h>
72 #include <sys/stat.h>
73 #include <netinet/in.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <stdarg.h>
77 #include <string.h>
78 #include <strings.h>
79 #include <sysexits.h>
80 #include <unistd.h>
81 #include <fcntl.h>
82 #include <syslog.h>
83 #include <signal.h>
84 #include <pthread.h>
85 #ifdef HAVE_POLL_H
86 #include <poll.h>
87 #else
88 #include "subst_poll.h"
89 #endif
90 #include <errno.h>
91
92 // C++ includes
93 #include <cstdio>
94 #include <cstddef>
95 #include <csignal>
96 #include <string>
97 #include <iostream>
98
99 #ifdef  __cplusplus
100 extern "C" {
101 #endif
102
103 #include "libmilter/mfapi.h"
104 //#include "libmilter/mfdef.h"
105
106 #if !HAVE_DECL_STRSEP
107 char *strsep(char **stringp, const char *delim);
108 #endif 
109
110 #if !HAVE_DECL_DAEMON
111 int daemon(int nochdir, int noclose);
112 #endif 
113
114 #ifdef  __cplusplus
115 }
116 #endif
117
118 #include "spamass-milter.h"
119
120 #ifdef WITH_DMALLOC
121 #include "dmalloc.h"
122 #endif
123
124 #ifndef INADDR_LOOPBACK
125 #define INADDR_LOOPBACK 0x7F000001
126 #endif
127
128 // }}} 
129
130 static const char Id[] = "$Id: spamass-milter.cpp,v 1.94 2011/02/14 21:50:53 dnelson Exp $";
131
132 struct smfiDesc smfilter =
133   {
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
147   };
148
149 const char *const debugstrings[] = {
150         "ALL", "FUNC", "POLL", "UORI", "STR", "MISC", "NET", "SPAMC", "RCPT",
151         "COPY",
152         NULL
153 };
154
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 */
163 char *spamdhost;
164 struct networklist ignorenets;
165 int spamc_argc;
166 char **spamc_argv;
167 bool flag_bucket = false;
168 bool flag_bucket_only = false;
169 char *spambucket;
170 bool flag_full_email = false;           /* pass full email address to spamc */
171 bool flag_expand = false;       /* alias/virtusertable expansion */
172 bool ignore_authenticated_senders = false;
173 bool warnedmacro = false;       /* have we logged that we couldn't fetch a macro? */
174
175 // {{{ main()
176
177 int
178 main(int argc, char* argv[])
179 {
180    int c, err = 0;
181    const char *args = "fd:mMp:P:r:u:D:i:Ib:B:e:x";
182    char *sock = NULL;
183    bool dofork = false;
184    char *pidfilename = NULL;
185    FILE *pidfile = NULL;
186
187 #ifdef HAVE_VERBOSE_TERMINATE_HANDLER
188         std::set_terminate (__gnu_cxx::__verbose_terminate_handler);
189 #endif
190
191    openlog("spamass-milter", LOG_PID, LOG_MAIL);
192
193         /* Process command line options */
194         while ((c = getopt(argc, argv, args)) != -1) {
195                 switch (c) {
196                         case 'f':
197                                 dofork = true;
198                                 break;
199                         case 'd':
200                                 parse_debuglevel(optarg);
201                                 break;
202                         case 'D':
203                                 spamdhost = strdup(optarg);
204                                 break;
205                         case 'e':
206                                 flag_full_email = true;
207                                 defaultdomain = strdup(optarg);
208                                 break;
209                         case 'i':
210                                 debug(D_MISC, "Parsing ignore list");
211                                 parse_networklist(optarg, &ignorenets);
212                                 break;
213                         case 'I':
214                                 debug(D_MISC, "Ignore authenticated senders");
215                                 ignore_authenticated_senders = true;
216                                 break;
217                         case 'm':
218                                 dontmodifyspam = true;
219                                 smfilter.xxfi_flags &= ~SMFIF_CHGBODY;
220                                 break;
221                         case 'M':
222                                 dontmodify = true;
223                                 dontmodifyspam = true;
224                                 smfilter.xxfi_flags &= ~(SMFIF_CHGBODY|SMFIF_CHGHDRS);
225                                 break;
226                         case 'p':
227                                 sock = strdup(optarg);
228                                 break;
229                         case 'P':
230                                 pidfilename = strdup(optarg);
231                                 break;
232                         case 'r':
233                                 flag_reject = true;
234                                 reject_score = atoi(optarg);
235                                 break;
236                         case 'u':
237                                 flag_sniffuser = true;
238                                 defaultuser = strdup(optarg);
239                                 break;
240                         case 'b':
241                         case 'B':
242                                 if (flag_bucket)
243                                 {
244                                         fprintf(stderr, "Can only have one -b or -B flag\n");
245                                         err = 1;
246                                         break;
247                                 }
248                                 flag_bucket = true;
249                                 if (c == 'b')
250                                 {
251                                         flag_bucket_only = true;
252                                         smfilter.xxfi_flags |= SMFIF_DELRCPT; // May delete recipients
253                                 }
254                                 // we will modify the recipient list; if spamc returns
255                                 // indicating that this mail is spam, the message will be
256                                 // sent to <optarg>@localhost
257                                 smfilter.xxfi_flags |= SMFIF_ADDRCPT; // May add recipients
258                                 // XXX we should probably verify that optarg is vaguely sane
259                                 spambucket = strdup( optarg );
260                                 break;
261                         case 'x':
262                                 flag_expand = true;
263                                 break;
264                         case '?':
265                                 err = 1;
266                                 break;
267                 }
268         }
269
270    if (flag_full_email && !flag_sniffuser)
271    {
272           fprintf(stderr, "-e flag requires -u\n");
273       err=1;
274    }
275
276    /* remember the remainer of the arguments so we can pass them to spamc */
277    spamc_argc = argc - optind;
278    spamc_argv = argv + optind;
279
280    if (!sock || err) {
281       cout << PACKAGE_NAME << " - Version " << PACKAGE_VERSION << endl;
282       cout << "SpamAssassin Sendmail Milter Plugin" << endl;
283       cout << "Usage: spamass-milter -p socket [-b|-B bucket] [-d xx[,yy...]] [-D host]" << endl;
284       cout << "                      [-e defaultdomain] [-f] [-i networks] [-I] [-m] [-M]" << endl;
285       cout << "                      [-P pidfile] [-r nn] [-u defaultuser] [-x]" << endl;
286       cout << "                      [-- spamc args ]" << endl;
287       cout << "   -p socket: path to create socket" << endl;
288       cout << "   -b bucket: redirect spam to this mail address.  The orignal" << endl;
289       cout << "          recipient(s) will not receive anything." << endl;
290       cout << "   -B bucket: add this mail address as a BCC recipient of spam." << endl;
291       cout << "   -d xx[,yy ...]: set debug flags.  Logs to syslog" << endl;
292       cout << "   -D host: connect to spamd at remote host (deprecated)" << endl;
293       cout << "   -e defaultdomain: pass full email address to spamc instead of just\n"
294               "          username.  Uses 'defaultdomain' if there was none" << endl;
295       cout << "   -f: fork into background" << endl;
296       cout << "   -i: skip (ignore) checks from these IPs or netblocks" << endl;
297       cout << "          example: -i 192.168.12.5,10.0.0.0/8,172.16.0.0/255.255.0.0" << endl;
298       cout << "   -I: skip (ignore) checks if sender is authenticated" << endl;
299       cout << "   -m: don't modify body, Content-type: or Subject:" << endl;
300       cout << "   -M: don't modify the message at all" << endl;
301       cout << "   -P pidfile: Put processid in pidfile" << endl;
302       cout << "   -r nn: reject messages with a score >= nn with an SMTP error.\n"
303               "          use -1 to reject any messages tagged by SA." << endl;
304       cout << "   -u defaultuser: pass the recipient's username to spamc.\n"
305               "          Uses 'defaultuser' if there are multiple recipients." << endl;
306       cout << "   -x: pass email address through alias and virtusertable expansion." << endl;
307       cout << "   -- spamc args: pass the remaining flags to spamc." << endl;
308               
309       exit(EX_USAGE);
310    }
311
312         if (pidfilename)
313         {
314                 unlink(pidfilename);
315                 pidfile = fopen(pidfilename,"w");
316                 if (!pidfile)
317                 {
318                         fprintf(stderr, "Could not open pidfile: %s\n", strerror(errno));
319                         exit(1);
320                 }
321                 /* leave the file open through the fork, since we don't know our pid
322                    yet
323                 */
324         }
325
326
327         if (dofork == true) 
328         {
329                 if (daemon(0, 0) == -1)
330                 {
331             fprintf(stderr, "daemon() failed: %s\n", strerror(errno));
332             exit(1);
333                 }
334         }
335         
336         if (pidfile)
337         {
338                 fprintf(pidfile, "%ld\n", (long)getpid());
339                 fclose(pidfile);
340                 pidfile = NULL;
341         }       
342         
343    {
344       struct stat junk;
345       if (stat(sock,&junk) == 0) unlink(sock);
346    }
347
348    (void) smfi_setconn(sock);
349         if (smfi_register(smfilter) == MI_FAILURE) {
350                 fprintf(stderr, "smfi_register failed\n");
351                 exit(EX_UNAVAILABLE);
352         } else {
353       debug(D_MISC, "smfi_register succeeded");
354    }
355         debug(D_ALWAYS, "spamass-milter %s starting", PACKAGE_VERSION);
356         err = smfi_main();
357         debug(D_ALWAYS, "spamass-milter %s exiting", PACKAGE_VERSION);
358         if (pidfilename)
359                 unlink(pidfilename);
360         return err;
361 }
362
363 // }}}
364
365 /* Update a header if SA changes it, or add it if it is new. */
366 void update_or_insert(SpamAssassin* assassin, SMFICTX* ctx, string oldstring, t_setter setter, const char *header )
367 {
368         string::size_type eoh1 = assassin->d().find("\n\n");
369         string::size_type eoh2 = assassin->d().find("\n\r\n");
370         string::size_type eoh = ( eoh1 < eoh2 ? eoh1 : eoh2 );
371
372         string newstring;
373         string::size_type oldsize;
374
375         debug(D_UORI, "u_or_i: looking at <%s>", header);
376         debug(D_UORI, "u_or_i: oldstring: <%s>", oldstring.c_str());
377
378         newstring = retrieve_field(assassin->d().substr(0, eoh), header);
379         debug(D_UORI, "u_or_i: newstring: <%s>", newstring.c_str());
380
381         oldsize = callsetter(*assassin,setter)(newstring);
382       
383         if (!dontmodify)
384         {
385                 if (newstring != oldstring)
386                 {
387                         /* change if old one was present, append if non-null */
388                         char* cstr = const_cast<char*>(newstring.c_str());
389                         char* hstr = const_cast<char*>(header);
390                         if (oldsize > 0)
391                         {
392                                 debug(D_UORI, "u_or_i: changing");
393                                 smfi_chgheader(ctx, hstr, 1, newstring.size() > 0 ? 
394                                         cstr : NULL );
395                         } else if (newstring.size() > 0)
396                         {
397                                 debug(D_UORI, "u_or_i: inserting");
398                                 smfi_addheader(ctx, hstr, cstr);
399                         }
400                 } else
401                 {
402                         debug(D_UORI, "u_or_i: no change");
403                 }
404         }
405 }
406
407 // {{{ Assassinate
408
409 //
410 // implement the changes suggested by SpamAssassin for the mail.  Returns
411 // the milter error code.
412 int 
413 assassinate(SMFICTX* ctx, SpamAssassin* assassin)
414 {
415   // find end of header (eol in last line of header)
416   // and beginning of body
417   string::size_type eoh1 = assassin->d().find("\n\n");
418   string::size_type eoh2 = assassin->d().find("\n\r\n");
419   string::size_type eoh = (eoh1 < eoh2) ? eoh1 : eoh2;
420   string::size_type bob = assassin->d().find_first_not_of("\r\n", eoh);
421
422   if (bob == string::npos)
423         bob = assassin->d().size();
424
425   update_or_insert(assassin, ctx, assassin->spam_flag(), &SpamAssassin::set_spam_flag, "X-Spam-Flag");
426   update_or_insert(assassin, ctx, assassin->spam_status(), &SpamAssassin::set_spam_status, "X-Spam-Status");
427
428   /* Summarily reject the message if SA tagged it, or if we have a minimum
429      score, reject if it exceeds that score. */
430   if (flag_reject)
431   {
432         bool do_reject = false;
433         if (reject_score == -1 && !assassin->spam_flag().empty())
434                 do_reject = true;
435         if (reject_score != -1)
436         {
437                 int score, rv;
438                 const char *spam_status = assassin->spam_status().c_str();
439                 /* SA 3.0 uses the keyword "score" */
440                 rv = sscanf(spam_status,"%*s score=%d", &score);
441                 if (rv != 1)
442                 {
443                         /* SA 2.x uses the keyword "hits" */
444                         rv = sscanf(spam_status,"%*s hits=%d", &score);
445                 }
446                 if (rv != 1)
447                         debug(D_ALWAYS, "Could not extract score from <%s>", spam_status);
448                 else 
449                 {
450                         debug(D_MISC, "SA score: %d", score);
451                         if (score >= reject_score)
452                                 do_reject = true;
453                 }
454         }
455         if (do_reject)
456         {
457                 debug(D_MISC, "Rejecting");
458                 smfi_setreply(ctx, "550", "5.7.1", "Blocked by SpamAssassin");
459
460
461                 if (flag_bucket)
462                 {
463                         /* If we also want a copy of the spam, shell out to sendmail and
464                            send another copy.  The milter API will not let you send the
465                            message AND return a failure code to the sender, so this is
466                            the only way to do it. */
467                         char *popen_argv[3];
468                         FILE *p;
469                         pid_t pid;
470
471                         popen_argv[0] = SENDMAIL;
472                         popen_argv[1] = spambucket;
473                         popen_argv[2] = NULL;
474                         
475                         debug(D_COPY, "calling %s %s", SENDMAIL, spambucket);
476                         p = popenv(popen_argv, "w",&pid);
477                         if (!p)
478                         {
479                                 debug(D_COPY, "popenv failed(%s).  Will not send a copy to spambucket", strerror(errno));
480                         } else
481                         {
482                                 // Send message provided by SpamAssassin
483                                 fwrite(assassin->d().c_str(), assassin->d().size(), 1, p);
484                                 fclose(p); p = NULL;
485                                 waitpid(pid,0,0);
486                         }
487                 }
488                 return SMFIS_REJECT;
489         }
490   }
491
492   /* Drop the message into the spam bucket if it's spam */
493   if ( flag_bucket ) {
494         if (!assassin->spam_flag().empty()) {
495           // first, add the spambucket address
496           if ( smfi_addrcpt( ctx, spambucket ) != MI_SUCCESS ) {
497                 throw string( "Failed to add spambucket to recipients" );
498           }
499           if (flag_bucket_only) {
500                 // Move recipients to a non-active header, one at a
501                 // time. Note, this may generate multiple X-Spam-Orig-To
502                 // headers, but that's okay.
503                 while( !assassin->recipients.empty()) {
504                   if ( smfi_addheader( ctx, "X-Spam-Orig-To", (char *)assassin->recipients.front().c_str()) != MI_SUCCESS ) {
505                         throw string( "Failed to save recipient" );
506                   }
507
508                   // It's not 100% important that this succeeds, so we'll just warn on failure rather than bailing out.
509                   if ( smfi_delrcpt( ctx, (char *)assassin->recipients.front().c_str()) != MI_SUCCESS ) {
510                         // throw_error really just logs a warning as opposed to actually throw()ing
511                         debug(D_ALWAYS, "Failed to remove recipient %s from the envelope", assassin->recipients.front().c_str() );
512                   }
513                   assassin->recipients.pop_front();
514                 }
515           }
516         }
517   }
518
519   update_or_insert(assassin, ctx, assassin->spam_report(), &SpamAssassin::set_spam_report, "X-Spam-Report");
520   update_or_insert(assassin, ctx, assassin->spam_prev_content_type(), &SpamAssassin::set_spam_prev_content_type, "X-Spam-Prev-Content-Type");
521   update_or_insert(assassin, ctx, assassin->spam_level(), &SpamAssassin::set_spam_level, "X-Spam-Level");
522   update_or_insert(assassin, ctx, assassin->spam_checker_version(), &SpamAssassin::set_spam_checker_version, "X-Spam-Checker-Version");
523
524   // 
525   // If SpamAssassin thinks it is spam, replace
526   //  Subject:
527   //  Content-Type:
528   //  <Body>
529   // 
530   //  However, only issue the header replacement calls if the content has
531   //  actually changed. If SA didn't change subject or content-type, don't
532   //  replace here unnecessarily.
533   if (!dontmodifyspam && assassin->spam_flag().size()>0)
534     {
535           update_or_insert(assassin, ctx, assassin->subject(), &SpamAssassin::set_subject, "Subject");
536           update_or_insert(assassin, ctx, assassin->content_type(), &SpamAssassin::set_content_type, "Content-Type");
537
538       // Replace body with the one SpamAssassin provided
539       string::size_type body_size = assassin->d().size() - bob;
540       string body=assassin->d().substr(bob, string::npos);
541       if ( smfi_replacebody(ctx, (unsigned char *)body.c_str(), body_size) == MI_FAILURE )
542         throw string("error. could not replace body.");
543       
544     }
545
546   return SMFIS_CONTINUE;
547 }
548
549 // retrieve the content of a specific field in the header
550 // and return it.
551 string
552 old_retrieve_field(const string& header, const string& field)
553 {
554   // look for beginning of content
555   string::size_type pos = find_nocase(header, "\n" + field + ": ");
556
557   // return empty string if not found
558   if (pos == string::npos)
559   {
560     debug(D_STR, "r_f: failed");
561     return string("");
562   }
563
564   // look for end of field name
565   pos = find_nocase(header, " ", pos) + 1;
566   
567   string::size_type pos2(pos);
568
569   // is field empty? 
570   if (pos2 == find_nocase(header, "\n", pos2))
571     return string("");
572
573   // look for end of content
574   do {
575
576     pos2 = find_nocase(header, "\n", pos2+1);
577
578   }
579   while ( pos2 < string::npos &&
580           isspace(header[pos2+1]) );
581
582   return header.substr(pos, pos2-pos);
583
584 }
585
586 // retrieve the content of a specific field in the header
587 // and return it.
588 string
589 retrieve_field(const string& header, const string& field)
590 {
591   // Find the field
592   string::size_type field_start = string::npos;
593   string::size_type field_end = string::npos;
594   string::size_type idx = 0;
595
596   while( field_start == string::npos ) {
597         idx = find_nocase( header, field + ":", idx );
598
599         // no match
600         if ( idx == string::npos ) {
601           return string( "" );
602         }
603
604         // The string we've found needs to be either at the start of the
605         // headers string, or immediately following a "\n"
606         if ( idx != 0 ) {
607           if ( header[ idx - 1 ] != '\n' ) {
608                 idx++; // so we don't get stuck in an infinite loop
609                 continue; // loop around again
610           }
611         }
612
613         field_start = idx;
614   }
615
616   // A mail field starts just after the header. Ideally, there's a
617   // space, but it's possible that there isn't.
618   field_start += field.length() + 1;
619   if ( field_start < ( header.length() - 1 ) && header[ field_start ] == ' ' ) {
620         field_start++;
621   }
622
623   // See if there's anything left, to shortcut the rest of the
624   // function.
625   if ( field_start == header.length() - 1 ) {
626         return string( "" );
627   }
628
629   // The field continues to the end of line. If the start of the next
630   // line is whitespace, then the field continues.
631   idx = field_start;
632   while( field_end == string::npos ) {
633         idx = header.find( "\n", idx );
634
635         // if we don't find a "\n", gobble everything to the end of the headers
636         if ( idx == string::npos ) {
637           field_end = header.length();
638         } else {
639           // check the next character
640           if (( idx + 1 ) < header.length() && ( isspace( header[ idx + 1 ] ))) {
641                 idx ++; // whitespace found, so wrap to the next line
642           } else {
643                 field_end = idx;
644           }
645         }
646   }
647
648   /* if the header line ends in \r\n, don't return the \r */
649   if (header[field_end-1] == '\r')
650         field_end--;
651
652   string data = header.substr( field_start, field_end - field_start );
653   
654   /* Replace all CRLF pairs with LF */
655   idx = 0;
656   while ( (idx = data.find("\r\n", idx)) != string::npos )
657   {
658         data.replace(idx,2,"\n");
659   }
660
661   return data;
662 }
663
664
665 // }}}
666
667 // {{{ MLFI callbacks
668
669 //
670 // Gets called once when a client connects to sendmail
671 //
672 // gets the originating IP address and checks it against the ignore list
673 // if it isn't in the list, store the IP in a structure and store a 
674 // pointer to it in the private data area.
675 //
676 sfsistat 
677 mlfi_connect(SMFICTX * ctx, char *hostname, _SOCK_ADDR * hostaddr)
678 {
679         struct context *sctx;
680         int rv;
681
682         debug(D_FUNC, "mlfi_connect: enter");
683
684         /* allocate a structure to store the IP address (and SA object) in */
685         sctx = (struct context *)malloc(sizeof(*sctx));
686         if (!hostaddr)
687         {
688                 /* not a socket; probably a local user calling sendmail directly */
689                 /* set to 127.0.0.1 */
690                 sctx->connect_ip.s_addr = htonl(INADDR_LOOPBACK);
691         } else
692         {
693                 sctx->connect_ip = ((struct sockaddr_in *) hostaddr)->sin_addr;
694         }
695         sctx->assassin = NULL;
696         sctx->helo = NULL;
697         
698         /* store a pointer to it with setpriv */
699         rv = smfi_setpriv(ctx, sctx);
700         if (rv != MI_SUCCESS)
701         {
702                 debug(D_ALWAYS, "smfi_setpriv failed!");
703                 return SMFIS_TEMPFAIL;
704         }
705         /* debug(D_ALWAYS, "ZZZ set private context to %p", sctx); */
706
707         if (ip_in_networklist(sctx->connect_ip, &ignorenets))
708         {
709                 debug(D_NET, "%s is in our ignore list - accepting message",
710                     inet_ntoa(sctx->connect_ip));
711                 debug(D_FUNC, "mlfi_connect: exit ignore");
712                 return SMFIS_ACCEPT;
713         }
714         
715         // Tell Milter to continue
716         debug(D_FUNC, "mlfi_connect: exit");
717
718         return SMFIS_CONTINUE;
719 }
720
721 //
722 // Gets called on every "HELO"
723 //
724 // stores the result in the context structure
725 //
726 sfsistat mlfi_helo(SMFICTX * ctx, char * helohost)
727 {
728         struct context *sctx = (struct context*)smfi_getpriv(ctx);
729         if (sctx->helo)
730                 free(sctx->helo);
731         sctx->helo = strdup(helohost);
732
733         return SMFIS_CONTINUE;
734 }
735
736 //
737 // Gets called first for all messages
738 //
739 // creates SpamAssassin object and makes pointer to it
740 // private data of this filter process
741 //
742 sfsistat
743 mlfi_envfrom(SMFICTX* ctx, char** envfrom)
744 {
745   SpamAssassin* assassin;
746   struct context *sctx = (struct context *)smfi_getpriv(ctx);
747   char *queueid;
748
749   if (sctx == NULL)
750   {
751     debug(D_ALWAYS, "smfi_getpriv failed!");
752     return SMFIS_TEMPFAIL;
753   }
754   /* debug(D_ALWAYS, "ZZZ got private context %p", sctx); */
755
756   if (ignore_authenticated_senders)
757   {
758     char *auth_authen;
759
760     auth_authen = smfi_getsymval(ctx, "{auth_authen}");
761     debug(D_MISC, "auth_authen=%s", auth_authen ?: "<unauthenticated>");
762
763     if (auth_authen)
764     {
765       debug(D_MISC, "sender authenticated (%s) - accepting message",
766             auth_authen);
767       debug(D_FUNC, "mlfi_envfrom: exit ignore");
768       return SMFIS_ACCEPT;
769     }
770   }
771
772   debug(D_FUNC, "mlfi_envfrom: enter");
773   try {
774     // launch new SpamAssassin
775     assassin=new SpamAssassin;
776   } catch (string& problem)
777     {
778       throw_error(problem);
779       return SMFIS_TEMPFAIL;
780     };
781   
782   assassin->set_connectip(string(inet_ntoa(sctx->connect_ip)));
783
784   // Store a pointer to the assassin object in our context struct
785   sctx->assassin = assassin;
786
787   // remember the MAIL FROM address
788   assassin->set_from(string(envfrom[0]));
789   
790   queueid=smfi_getsymval(ctx,"i");
791   if (!queueid)
792   {
793     queueid="unknown";
794     warnmacro("i", "ENVFROM");
795   }
796   assassin->queueid = queueid;
797
798   debug(D_MISC, "queueid=%s", queueid);
799
800   // tell Milter to continue
801   debug(D_FUNC, "mlfi_envfrom: exit");
802
803   return SMFIS_CONTINUE;
804 }
805
806 //
807 // Gets called once for each recipient
808 //
809 // stores the first recipient in the spamassassin object and
810 // stores all addresses and the number thereof (some redundancy)
811 //
812
813
814 sfsistat
815 mlfi_envrcpt(SMFICTX* ctx, char** envrcpt)
816 {
817         struct context *sctx = (struct context*)smfi_getpriv(ctx);
818         SpamAssassin* assassin = sctx->assassin;
819         FILE *p;
820
821         debug(D_FUNC, "mlfi_envrcpt: enter");
822
823         if (flag_expand)
824         {
825                 /* open a pipe to sendmail so we can do address expansion */
826
827                 char buf[1024];
828                 char *popen_argv[4];
829                 pid_t pid;
830                 
831                 popen_argv[0] = SENDMAIL;
832                 popen_argv[1] = "-bv";
833                 popen_argv[2] = envrcpt[0];
834                 popen_argv[3] = NULL;
835
836                 debug(D_RCPT, "calling %s -bv %s", SENDMAIL, envrcpt[0]);
837
838                 p = popenv(popen_argv, "r", &pid);
839                 if (!p)
840                 {
841                         debug(D_RCPT, "popenv failed(%s).  Will not expand aliases", strerror(errno));
842                         assassin->expandedrcpt.push_back(envrcpt[0]);
843                 } else
844                 {
845                         while (fgets(buf, sizeof(buf), p) != NULL)
846                         {
847                                 int i = strlen(buf);
848                                 /* strip trailing EOLs */
849                                 while (i > 0 && buf[i - 1] <= ' ')
850                                         i--;
851                                 buf[i] = '\0';
852                                 debug(D_RCPT, "sendmail output: %s", buf);
853                                 /*      From a quick scan of the sendmail source, a valid email
854                                         address gets printed via either
855                                             "deliverable: mailer %s, host %s, user %s"
856                                         or  "deliverable: mailer %s, user %s"
857                                 */
858                                 if (strstr(buf, "... deliverable: mailer "))
859                                 {
860                                         char *p=strstr(buf,", user ");
861                                         /* anything after ", user " is the email address */
862                                         debug(D_RCPT, "user: %s", p+7);
863                                         assassin->expandedrcpt.push_back(p+7);
864                                 }
865                         }
866                         fclose(p); p = NULL;
867                         waitpid(pid,0,0);
868
869                 }
870         } else
871         {
872                 assassin->expandedrcpt.push_back(envrcpt[0]);
873         }       
874         debug(D_RCPT, "Total of %d actual recipients", (int)assassin->expandedrcpt.size());
875
876         if (assassin->numrcpt() == 0)
877         {
878                 /* Send the envelope headers as X-Envelope-From: and
879                    X-Envelope-To: so that SpamAssassin can use them in its
880                    whitelist checks.  Also forge as complete a dummy
881                    Received: header as possible because SA gets a lot of
882                    info from it.
883                    
884                         HReceived: $?sfrom $s $.$?_($?s$|from $.$_)
885                                 $.$?{auth_type}(authenticated$?{auth_ssf} bits=${auth_ssf}$.)
886                                 $.by $j ($v/$Z)$?r with $r$. id $i$?{tls_version}
887                                 (version=${tls_version} cipher=${cipher} bits=${cipher_bits} verify=${verify})$.$?u
888                                 for $u; $|;
889                                 $.$b$?g
890                                 (envelope-from $g)$.
891                    
892                 */
893                 const char *macro_b, *macro_i, *macro_j, *macro_r,
894                            *macro_s, *macro_v, *macro_Z, *macro__;
895                 char date[32];
896
897                 /* RFC 822 date. */
898                 macro_b = smfi_getsymval(ctx, "b");
899                 if (!macro_b)                                  
900                 {
901                         time_t tval;
902                         time(&tval);
903                         strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %z", localtime(&tval));
904                         macro_b = date;
905                         warnmacro("b", "ENVRCPT");
906                 }
907
908                 /* queue ID */
909                 macro_i = smfi_getsymval(ctx, "i");
910                 if (!macro_i)
911                 {
912                         macro_i = "unknown";
913                         warnmacro("i", "ENVRCPT");
914                 }
915
916                 /* FQDN of this site */
917                 macro_j = smfi_getsymval(ctx, "j");
918                 if (!macro_j)
919                 {
920                         macro_j = "localhost";
921                         warnmacro("j", "ENVRCPT");
922                 }
923
924                 /* Protocol used to receive the message */
925                 macro_r = smfi_getsymval(ctx, "r");
926                 if (!macro_r)
927                 {
928                         macro_r = "SMTP";
929                         warnmacro("r", "ENVRCPT");
930                 }
931                         
932                 /* Sendmail currently cannot pass us the {s} macro, but
933                    I do not know why.  Leave this in for the day sendmail is
934                    fixed.  Until that day, use the value remembered by
935                    mlfi_helo()
936                 */
937                 macro_s = smfi_getsymval(ctx, "s");
938                 if (!macro_s)
939                         macro_s = sctx->helo;
940                 if (!macro_s)
941                         macro_s = "nohelo";
942
943                 /* Sendmail binary version */
944                 macro_v = smfi_getsymval(ctx, "v");
945                 if (!macro_v)
946                 {
947                         macro_v = "8.13.0";
948                         warnmacro("v", "ENVRCPT");
949                 }
950
951                 /* Sendmail .cf version */
952                 macro_Z = smfi_getsymval(ctx, "Z");
953                 if (!macro_Z)
954                 {
955                         macro_Z = "8.13.0";
956                         warnmacro("Z", "ENVRCPT");
957                 }
958
959                 /* Validated sending site's address */
960                 macro__ = smfi_getsymval(ctx, "_");
961                 if (!macro__)
962                 {
963                         macro__ = "unknown";
964                         warnmacro("_", "ENVRCPT");
965                 }
966
967                 assassin->output((string)"X-Envelope-From: "+assassin->from()+"\r\n");
968                 assassin->output((string)"X-Envelope-To: "+envrcpt[0]+"\r\n");
969
970                 assassin->output((string)
971                         "Received: from "+macro_s+" ("+macro__+")\r\n\t"+
972                         "by "+macro_j+" ("+macro_v+"/"+macro_Z+") with "+macro_r+" id "+macro_i+"\r\n\t"+
973                         macro_b+"\r\n\t"+
974                         "(envelope-from "+assassin->from()+")\r\n");
975
976         } else
977                 assassin->output((string)"X-Envelope-To: "+envrcpt[0]+"\r\n");
978
979         /* increment RCPT TO: count */
980         assassin->set_numrcpt();
981
982         /* If we expanded to at least one user and we haven't recorded one yet,
983            record the first one */
984         if (!assassin->expandedrcpt.empty() && (assassin->rcpt().size() == 0))
985         {
986                 debug(D_RCPT, "remembering %s for spamc", assassin->expandedrcpt.front().c_str());
987                 assassin->set_rcpt(assassin->expandedrcpt.front());
988         }
989
990         debug(D_RCPT, "remembering recipient %s", envrcpt[0]);
991         assassin->recipients.push_back( envrcpt[0] ); // XXX verify that this worked
992
993         debug(D_FUNC, "mlfi_envrcpt: exit");
994
995         return SMFIS_CONTINUE;
996 }
997
998 //
999 // Gets called repeatedly for all header fields
1000 //
1001 // assembles the headers and passes them on to the SpamAssassin client
1002 // through the pipe.
1003 //
1004 // only exception: SpamAssassin header fields (X-Spam-*) get suppressed
1005 // but are being stored in the SpamAssassin element.
1006 //
1007 // this function also starts the connection with the SPAMC program the
1008 // first time it is called.
1009 //
1010
1011 sfsistat
1012 mlfi_header(SMFICTX* ctx, char* headerf, char* headerv)
1013 {
1014   SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1015   debug(D_FUNC, "mlfi_header: enter");
1016
1017   // Check if the SPAMC program has already been run, if not we run it.
1018   if ( !(assassin->connected) )
1019      {
1020        try {
1021          assassin->connected = 1; // SPAMC is getting ready to run
1022          assassin->Connect();
1023        } 
1024        catch (string& problem) {
1025          throw_error(problem);
1026          ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1027          delete assassin;
1028          debug(D_FUNC, "mlfi_header: exit error connect");
1029          return SMFIS_TEMPFAIL;
1030        };
1031      }
1032
1033   // Is it a "X-Spam-" header field?
1034   if ( cmp_nocase_partial("X-Spam-", headerf) == 0 )
1035     {
1036       int suppress = 1;
1037       // memorize content of old fields
1038
1039       if ( cmp_nocase_partial("X-Spam-Status", headerf) == 0 )
1040         assassin->set_spam_status(headerv);
1041       else if ( cmp_nocase_partial("X-Spam-Flag", headerf) == 0 )
1042         assassin->set_spam_flag(headerv);
1043       else if ( cmp_nocase_partial("X-Spam-Report", headerf) == 0 )
1044         assassin->set_spam_report(headerv);
1045       else if ( cmp_nocase_partial("X-Spam-Prev-Content-Type", headerf) == 0 )
1046         assassin->set_spam_prev_content_type(headerv);
1047       else if ( cmp_nocase_partial("X-Spam-Level", headerf) == 0 )
1048         assassin->set_spam_level(headerv);
1049       else if ( cmp_nocase_partial("X-Spam-Checker-Version", headerf) == 0 )
1050         assassin->set_spam_checker_version(headerv);
1051       else
1052       {
1053         /* Hm. X-Spam header, but not one we recognize.  Pass it through. */
1054         suppress = 0;
1055       }
1056       
1057       if (suppress)
1058       {
1059         debug(D_FUNC, "mlfi_header: suppress");
1060         return SMFIS_CONTINUE;
1061       }
1062     }
1063
1064   // Content-Type: will be stored if present
1065   if ( cmp_nocase_partial("Content-Type", headerf) == 0 )
1066     assassin->set_content_type(headerv);
1067
1068   // Subject: should be stored
1069   if ( cmp_nocase_partial("Subject", headerf) == 0 )
1070     assassin->set_subject(headerv);
1071
1072   // assemble header to be written to SpamAssassin
1073   string header = string(headerf) + ": " + headerv + "\r\n";
1074  
1075   try {
1076     // write to SpamAssassin client
1077     assassin->output(header.c_str(),header.size());
1078   } catch (string& problem)
1079     {
1080       throw_error(problem);
1081       ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1082       delete assassin;
1083       debug(D_FUNC, "mlfi_header: exit error output");
1084       return SMFIS_TEMPFAIL;
1085     };
1086   
1087   // go on...
1088   debug(D_FUNC, "mlfi_header: exit");
1089
1090   return SMFIS_CONTINUE;
1091 }
1092
1093 // 
1094 // Gets called once when the header is finished.
1095 //
1096 // writes empty line to SpamAssassin client to separate
1097 // headers from body.
1098 //
1099 sfsistat
1100 mlfi_eoh(SMFICTX* ctx)
1101 {
1102   SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1103
1104   debug(D_FUNC, "mlfi_eoh: enter");
1105
1106   // Check if the SPAMC program has already been run, if not we run it.
1107   if ( !(assassin->connected) )
1108      {
1109        try {
1110          assassin->connected = 1; // SPAMC is getting ready to run
1111          assassin->Connect();
1112        } 
1113        catch (string& problem) {
1114          throw_error(problem);
1115          ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1116          delete assassin;
1117
1118          debug(D_FUNC, "mlfi_eoh: exit error connect");
1119          return SMFIS_TEMPFAIL;
1120        };
1121      }
1122
1123   try {
1124     // add blank line between header and body
1125     assassin->output("\r\n",2);
1126   } catch (string& problem)
1127     {
1128       throw_error(problem);
1129       ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1130       delete assassin;
1131   
1132       debug(D_FUNC, "mlfi_eoh: exit error output");
1133       return SMFIS_TEMPFAIL;
1134     };
1135   
1136   // go on...
1137
1138   debug(D_FUNC, "mlfi_eoh: exit");
1139   return SMFIS_CONTINUE;
1140 }
1141
1142 //
1143 // Gets called repeatedly to transmit the body
1144 //
1145 // writes everything directly to SpamAssassin client
1146 //
1147 sfsistat
1148 mlfi_body(SMFICTX* ctx, u_char *bodyp, size_t bodylen)
1149 {
1150   debug(D_FUNC, "mlfi_body: enter");
1151   SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1152
1153  
1154   try {
1155     assassin->output(bodyp, bodylen);
1156   } catch (string& problem)
1157     {
1158       throw_error(problem);
1159       ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1160       delete assassin;
1161       debug(D_FUNC, "mlfi_body: exit error");
1162       return SMFIS_TEMPFAIL;
1163     };
1164
1165   // go on...
1166   debug(D_FUNC, "mlfi_body: exit");
1167   return SMFIS_CONTINUE;
1168 }
1169
1170 //
1171 // Gets called once at the end of mail processing
1172 //
1173 // tells SpamAssassin client that the mail is complete
1174 // through EOF and then modifies the mail accordingly by
1175 // calling the "assassinate" function
1176 //
1177 sfsistat
1178 mlfi_eom(SMFICTX* ctx)
1179 {
1180   SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1181   int milter_status;
1182  
1183   debug(D_FUNC, "mlfi_eom: enter");
1184   try {
1185
1186     // close output pipe to signal EOF to SpamAssassin
1187     assassin->close_output();
1188
1189     // read what the Assassin is telling us
1190     assassin->input();
1191
1192     milter_status = assassinate(ctx, assassin);
1193
1194     // now cleanup the element.
1195     ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1196     delete assassin;
1197
1198   } catch (string& problem)
1199     {
1200       throw_error(problem);
1201       ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1202       delete assassin;
1203       debug(D_FUNC, "mlfi_eom: exit error");
1204       return SMFIS_TEMPFAIL;
1205     };
1206   
1207   // go on...
1208   debug(D_FUNC, "mlfi_eom: exit");
1209   return milter_status;
1210 }
1211
1212 //
1213 // Gets called on session-basis. This keeps things nice & quiet.
1214 //
1215 sfsistat
1216 mlfi_close(SMFICTX* ctx)
1217 {
1218   struct context *sctx;
1219   debug(D_FUNC, "mlfi_close");
1220   
1221   sctx = (struct context*)smfi_getpriv(ctx);
1222   if (sctx == NULL)
1223     return SMFIS_ACCEPT;
1224
1225   if (sctx->helo)
1226         free(sctx->helo);
1227   free(sctx);
1228   smfi_setpriv(ctx, NULL);
1229   
1230   return SMFIS_ACCEPT;
1231 }
1232
1233 //
1234 // Gets called when things are being aborted.
1235 //
1236 // kills the SpamAssassin object, its destructor should
1237 // take care of everything.
1238 //
1239 sfsistat
1240 mlfi_abort(SMFICTX* ctx)
1241 {
1242   SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1243
1244   debug(D_FUNC, "mlfi_abort");
1245   ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1246   delete assassin;
1247
1248   return SMFIS_ACCEPT;
1249 }
1250
1251 // }}}
1252
1253 // {{{ SpamAssassin Class
1254
1255 //
1256 // This is a new constructor for the SpamAssassin object.  It simply 
1257 // initializes two variables.  The original constructor has been
1258 // renamed to Connect().
1259 //
1260 SpamAssassin::SpamAssassin():
1261   error(false),
1262   running(false),
1263   connected(false),
1264   _numrcpt(0)
1265 {
1266 }
1267
1268
1269 SpamAssassin::~SpamAssassin()
1270
1271         if (connected) 
1272         {
1273                 // close all pipes that are still open
1274                 if (pipe_io[0][0] > -1) close(pipe_io[0][0]);
1275                 if (pipe_io[0][1] > -1) close(pipe_io[0][1]);
1276                 if (pipe_io[1][0] > -1) close(pipe_io[1][0]);
1277                 if (pipe_io[1][1] > -1) close(pipe_io[1][1]);
1278
1279                 // child still running?
1280                 if (running)
1281                 {
1282                         // make sure the pid is valid
1283                         if (pid > 0) {
1284                                 // slaughter child
1285                                 kill(pid, SIGKILL);
1286
1287                                 // wait for child to terminate
1288                                 int status;
1289                                 waitpid(pid, &status, 0);
1290                         }
1291                 }
1292     }
1293
1294         // Clean up the recip list. Might be overkill, but it's good housekeeping.
1295         while( !recipients.empty()) 
1296         {
1297                 recipients.pop_front();
1298         }
1299         // Clean up the recip list. Might be overkill, but it's good housekeeping.
1300         while( !expandedrcpt.empty()) 
1301         {
1302                 expandedrcpt.pop_front();
1303         }
1304 }
1305
1306 //
1307 // This is the old SpamAssassin constructor.  It has been renamed Connect(),
1308 // and is now called at the beginning of the mlfi_header() function.
1309 //
1310
1311 void SpamAssassin::Connect()
1312 {
1313   // set up pipes for in- and output
1314   if (pipe(pipe_io[0]))
1315     throw string(string("pipe error: ")+string(strerror(errno)));
1316   if (pipe(pipe_io[1]))
1317     throw string(string("pipe error: ")+string(strerror(errno)));
1318
1319   // now execute SpamAssassin client for contact with SpamAssassin spamd
1320
1321   // start child process
1322   switch(pid = fork())
1323     {
1324     case -1:
1325       // forking trouble. throw error.
1326       throw string(string("fork error: ")+string(strerror(errno)));
1327       break;
1328     case 0:
1329       // +++ CHILD +++
1330       
1331       // close unused pipes
1332       close(pipe_io[1][0]);
1333       close(pipe_io[0][1]);
1334
1335       // redirect stdin(0), stdout(1) and stderr(2)
1336       dup2(pipe_io[0][0],0);
1337       dup2(pipe_io[1][1],1);
1338       dup2(pipe_io[1][1],2);
1339
1340       closeall(3);
1341
1342       // execute spamc 
1343       // absolute path (determined in autoconf) 
1344       // should be a little more secure
1345       // XXX arbitrary 100-argument max
1346       int argc = 0;
1347       char** argv = (char**) malloc(100*sizeof(char*));
1348       argv[argc++] = SPAMC;
1349       if (flag_sniffuser) 
1350       {
1351         argv[argc++] = "-u";
1352         if ( expandedrcpt.size() != 1 )
1353         {
1354           // More (or less?) than one recipient, so we pass the default
1355           // username to SPAMC.  This way special rules can be defined for
1356           // multi recipient messages.
1357           debug(D_RCPT, "%d recipients; spamc gets default username %s", (int)expandedrcpt.size(), defaultuser);
1358           argv[argc++] = defaultuser; 
1359         } else
1360         { 
1361           // There is only 1 recipient so we pass the username
1362           // (converted to lowercase) to SPAMC.  Don't worry about 
1363           // freeing this memory as we're exec()ing anyhow.
1364           if (flag_full_email)
1365             argv[argc] = strlwr(strdup(full_user().c_str())); 
1366           else
1367             argv[argc] = strlwr(strdup(local_user().c_str())); 
1368
1369           debug(D_RCPT, "spamc gets %s", argv[argc]);
1370          
1371           argc++;
1372         }
1373       }
1374       if (spamdhost) 
1375       {
1376         argv[argc++] = "-d";
1377         argv[argc++] = spamdhost;
1378       }
1379       if (spamc_argc)
1380       {
1381         memcpy(argv+argc, spamc_argv, spamc_argc * sizeof(char *));
1382         argc += spamc_argc;
1383       }
1384       argv[argc++] = 0;
1385
1386       execvp(argv[0] , argv); // does not return!
1387
1388       // execution failed
1389       throw_error(string("execution error: ")+string(strerror(errno)));
1390       _exit(1);
1391       break;
1392     }
1393
1394   // +++ PARENT +++
1395
1396   // close unused pipes
1397   close(pipe_io[0][0]);
1398   close(pipe_io[1][1]);
1399   pipe_io[0][0]=-1;
1400   pipe_io[1][1]=-1;
1401
1402   // mark the pipes non-blocking
1403   if(fcntl(pipe_io[0][1], F_SETFL, O_NONBLOCK) == -1)
1404      throw string(string("Cannot set pipe01 nonblocking: ")+string(strerror(errno)));
1405 #if 0  /* don't really need to make the sink pipe nonblocking */
1406   if(fcntl(pipe_io[1][0], F_SETFL, O_NONBLOCK) == -1)
1407      throw string(string("Cannot set pipe10 nonblocking: ")+string(strerror(errno)));
1408 #endif
1409
1410   // we have to assume the client is running now.
1411   running=true;
1412
1413   /* If we have any buffered output, write it now. */
1414   if (outputbuffer.size())
1415   {
1416     output(outputbuffer);
1417     outputbuffer="";
1418   }
1419 }
1420
1421 // write to SpamAssassin
1422 void
1423 SpamAssassin::output(const void* buffer, long size)
1424 {
1425   debug(D_FUNC, "::output enter");
1426
1427   debug(D_SPAMC, "output \"%*.*s\"", (int)size, (int)size, (char *)buffer);
1428
1429   // if there are problems, fail.
1430   if (error)
1431     throw string("tried output despite problems. failed.");
1432
1433   /* If we haven't launched spamc yet, just store the data */
1434   if (!connected)
1435   {
1436         /* Silly C++ can't tell the difference between 
1437                 (const char*, string::size_type) and
1438                 (string::size_type, char), so we have to cast the parameters.
1439         */
1440         outputbuffer.append((const char *)buffer,(string::size_type)size);
1441         debug(D_FUNC, "::output exit1");
1442         return;
1443   }
1444
1445   // send to SpamAssassin
1446   long total = 0;
1447   long wsize = 0;
1448   string reason;
1449   int status;
1450   do {
1451         struct pollfd fds[2];
1452         int nfds = 2, nready;
1453         fds[0].fd = pipe_io[0][1];
1454         fds[0].events = POLLOUT;
1455         fds[1].fd = pipe_io[1][0];
1456         fds[1].events = POLLIN;
1457
1458         debug(D_POLL, "polling fds %d and %d", pipe_io[0][1], pipe_io[1][0]);
1459         nready = poll(fds, nfds, 1000);
1460         if (nready == -1)
1461                 throw("poll failed");
1462
1463         debug(D_POLL, "poll returned %d, fd0=%d, fd1=%d", nready, fds[0].revents, fds[1].revents);
1464
1465         if (fds[1].revents & (POLLERR|POLLNVAL|POLLHUP))
1466         {
1467                 throw string("poll says my read pipe is busted");
1468         }
1469
1470         if (fds[0].revents & (POLLERR|POLLNVAL|POLLHUP))
1471         {
1472                 throw string("poll says my write pipe is busted");
1473         }
1474
1475         if (fds[1].revents & POLLIN)
1476         {
1477                 debug(D_POLL, "poll says I can read");
1478                 read_pipe();
1479         }
1480
1481         if (fds[0].revents & POLLOUT)
1482         {
1483                 debug(D_POLL, "poll says I can write");
1484                 switch(wsize = write(pipe_io[0][1], (char *)buffer + total, size - total))
1485                 {
1486                   case -1:
1487                         if (errno == EAGAIN)
1488                                 continue;
1489                         reason = string(strerror(errno));
1490
1491                         // close the pipes
1492                         close(pipe_io[0][1]);
1493                         close(pipe_io[1][0]);
1494                         pipe_io[0][1]=-1;       
1495                         pipe_io[1][0]=-1;       
1496
1497                         // Slaughter child
1498                         kill(pid, SIGKILL);
1499
1500                         // set flags
1501                         error = true;
1502                         running = false;
1503         
1504                         // wait until child is dead
1505                         waitpid(pid, &status, 0);
1506
1507                         throw string(string("write error: ")+reason);   
1508                         break;
1509               default:
1510                         total += wsize;
1511                         debug(D_POLL, "wrote %ld bytes", wsize);
1512                         break;
1513                 }
1514         }
1515   } while ( total < size );
1516
1517   debug(D_FUNC, "::output exit2");
1518 }
1519
1520 void SpamAssassin::output(const void* buffer)
1521 {
1522         output(buffer, strlen((const char *)buffer));
1523 }
1524
1525 void SpamAssassin::output(string buffer)
1526 {
1527         output(buffer.c_str(), buffer.size());
1528 }
1529
1530 // close output pipe
1531 void
1532 SpamAssassin::close_output()
1533 {
1534   if(close(pipe_io[0][1]))
1535     throw string(string("close error: ")+string(strerror(errno)));
1536   pipe_io[0][1]=-1;
1537 }
1538
1539 void
1540 SpamAssassin::input()
1541 {
1542   debug(D_FUNC, "::input enter");
1543   // if the child has exited or we experienced an error, return
1544   // immediately.
1545   if (!running || error)
1546   {
1547     debug(D_FUNC, "::input exit1");
1548     return;
1549   }
1550
1551   // keep reading from input pipe until it is empty
1552   empty_and_close_pipe();
1553   
1554   // that's it, we're through
1555   running = false;
1556
1557   // wait until child is dead
1558   int status;
1559   if(waitpid(pid, &status, 0)<0)
1560     {
1561       error = true;
1562       throw string(string("waitpid error: ")+string(strerror(errno)));
1563     }; 
1564         debug(D_FUNC, "::input exit2");
1565 }
1566
1567 //
1568 // return reference to mail
1569 //
1570 string& 
1571 SpamAssassin::d()
1572 {
1573   return mail;
1574 }
1575
1576 //
1577 // get values of the different SpamAssassin fields
1578 //
1579 string& 
1580 SpamAssassin::spam_status()
1581 {
1582   return x_spam_status;
1583 }
1584
1585 string& 
1586 SpamAssassin::spam_flag()
1587 {
1588   return x_spam_flag;
1589 }
1590
1591 string& 
1592 SpamAssassin::spam_report()
1593 {
1594   return x_spam_report;
1595 }
1596
1597 string& 
1598 SpamAssassin::spam_prev_content_type()
1599 {
1600   return x_spam_prev_content_type;
1601 }
1602
1603 string& 
1604 SpamAssassin::spam_checker_version()
1605 {
1606   return x_spam_checker_version;
1607 }
1608
1609 string& 
1610 SpamAssassin::spam_level()
1611 {
1612   return x_spam_level;
1613 }
1614
1615 string& 
1616 SpamAssassin::content_type()
1617 {
1618   return _content_type;
1619 }
1620
1621 string& 
1622 SpamAssassin::subject()
1623 {
1624   return _subject;
1625 }
1626
1627 string&
1628 SpamAssassin::rcpt()
1629 {
1630   return _rcpt;
1631 }
1632
1633 string&
1634 SpamAssassin::from()
1635 {
1636   return _from;
1637 }
1638
1639 string&
1640 SpamAssassin::connectip()
1641 {
1642   return _connectip;
1643 }
1644
1645
1646 string
1647 SpamAssassin::local_user()
1648 {
1649   // assuming we have a recipient in the form: <username@somehost.somedomain>
1650   // (angle brackets optional) we return 'username'
1651   if (_rcpt[0] == '<')
1652     return _rcpt.substr(1, _rcpt.find_first_of("@+")-1);
1653   else
1654         return _rcpt.substr(0, _rcpt.find_first_of("@+"));
1655 }
1656
1657 string
1658 SpamAssassin::full_user()
1659 {
1660   string name;
1661   // assuming we have a recipient in the form: <username@somehost.somedomain>
1662   // (angle brackets optional) we return 'username@somehost.somedomain'
1663   if (_rcpt[0] == '<')
1664     name = _rcpt.substr(1, _rcpt.find('>')-1);
1665   else
1666         name = _rcpt;
1667   if(name.find('@') == string::npos)
1668   {
1669     /* if the name had no domain part (local delivery), append the default one */
1670     name = name + "@" + defaultdomain;
1671   }
1672   return name;
1673 }
1674
1675 int
1676 SpamAssassin::numrcpt()
1677 {
1678   return _numrcpt;
1679 }
1680
1681 int
1682 SpamAssassin::set_numrcpt()
1683 {
1684   _numrcpt++;
1685   return _numrcpt;
1686 }
1687
1688 int
1689 SpamAssassin::set_numrcpt(const int val)
1690 {
1691   _numrcpt = val;
1692   return _numrcpt;
1693 }
1694
1695 //
1696 // set the values of the different SpamAssassin
1697 // fields in our element. Returns former size of field
1698 //
1699 string::size_type
1700 SpamAssassin::set_spam_status(const string& val)
1701 {
1702   string::size_type old = x_spam_status.size();
1703   x_spam_status = val;
1704   return (old);
1705 }
1706
1707 string::size_type
1708 SpamAssassin::set_spam_flag(const string& val)
1709 {
1710   string::size_type old = x_spam_flag.size();
1711   x_spam_flag = val;
1712   return (old);
1713 }
1714
1715 string::size_type
1716 SpamAssassin::set_spam_report(const string& val)
1717 {
1718   string::size_type old = x_spam_report.size();
1719   x_spam_report = val;
1720   return (old);
1721 }
1722
1723 string::size_type
1724 SpamAssassin::set_spam_prev_content_type(const string& val)
1725 {
1726   string::size_type old = x_spam_prev_content_type.size();
1727   x_spam_prev_content_type = val;
1728   return (old);
1729 }
1730
1731 string::size_type
1732 SpamAssassin::set_spam_checker_version(const string& val)
1733 {
1734   string::size_type old = x_spam_checker_version.size();
1735   x_spam_checker_version = val;
1736   return (old);
1737 }
1738
1739 string::size_type
1740 SpamAssassin::set_spam_level(const string& val)
1741 {
1742   string::size_type old = x_spam_level.size();
1743   x_spam_level = val;
1744   return (old);
1745 }
1746
1747 string::size_type
1748 SpamAssassin::set_content_type(const string& val)
1749 {
1750   string::size_type old = _content_type.size();
1751   _content_type = val;
1752   return (old);
1753 }
1754
1755 string::size_type
1756 SpamAssassin::set_subject(const string& val)
1757 {
1758   string::size_type old = _subject.size();
1759   _subject = val;
1760   return (old);
1761 }
1762
1763 string::size_type
1764 SpamAssassin::set_rcpt(const string& val)
1765 {
1766   string::size_type old = _rcpt.size();
1767   _rcpt = val;
1768   return (old);  
1769 }
1770
1771 string::size_type
1772 SpamAssassin::set_from(const string& val)
1773 {
1774   string::size_type old = _from.size();
1775   _from = val;
1776   return (old);  
1777 }
1778
1779 string::size_type
1780 SpamAssassin::set_connectip(const string& val)
1781 {
1782   string::size_type old = _connectip.size();
1783   _connectip = val;
1784   return (old);  
1785 }
1786
1787 //
1788 // Read available output from SpamAssassin client
1789 //
1790 int
1791 SpamAssassin::read_pipe()
1792 {
1793         long size;
1794         int  status;
1795         char iobuff[1024];
1796         string reason;
1797
1798         debug(D_FUNC, "::read_pipe enter");
1799
1800         if (pipe_io[1][0] == -1)
1801         {
1802                 debug(D_FUNC, "::read_pipe exit - shouldn't have been called?");
1803                 return 0;
1804         }
1805
1806         size = read(pipe_io[1][0], iobuff, 1024);
1807
1808         if (size < 0)
1809     {
1810                 // Error. 
1811                 reason = string(strerror(errno));
1812                 
1813                 // Close remaining pipe.
1814                 close(pipe_io[1][0]);
1815                 pipe_io[1][0] = -1;
1816         
1817                 // Slaughter child
1818                 kill(pid, SIGKILL);
1819         
1820                 // set flags
1821                 error = true;
1822                 running = false;
1823         
1824                 // wait until child is dead
1825                 waitpid(pid, &status, 0);
1826         
1827                 // throw the error message that caused this trouble
1828                 throw string(string("read error: ")+reason);
1829         } else if ( size == 0 )
1830         {
1831
1832                 // EOF. Close the pipe
1833                 if(close(pipe_io[1][0]))
1834                         throw string(string("close error: ")+string(strerror(errno)));
1835                 pipe_io[1][0] = -1;
1836         
1837         } else
1838         { 
1839                 // append to mail buffer 
1840                 mail.append(iobuff, size);
1841                 debug(D_POLL, "read %ld bytes", size);
1842                 debug(D_SPAMC, "input  \"%*.*s\"", (int)size, (int)size, iobuff);
1843         }
1844         debug(D_FUNC, "::read_pipe exit");
1845         return size;
1846 }
1847
1848 //
1849 // Read all output from SpamAssassin client
1850 // and close the pipe
1851 //
1852 void
1853 SpamAssassin::empty_and_close_pipe()
1854 {
1855         debug(D_FUNC, "::empty_and_close_pipe enter");
1856         while (read_pipe())
1857                 ;
1858         debug(D_FUNC, "::empty_and_close_pipe exit");
1859 }
1860
1861 // }}}
1862
1863 // {{{ Some small subroutines without much relation to functionality
1864
1865 // output error message to syslog facility
1866 void
1867 throw_error(const string& errmsg)
1868 {
1869   if (errmsg.c_str())
1870     syslog(LOG_ERR, "Thrown error: %s", errmsg.c_str());
1871   else
1872     syslog(LOG_ERR, "Unknown error");
1873 }
1874
1875 /* Takes a comma or space-delimited string of debug tokens and sets the
1876    appropriate bits in flag_debug.  "all" sets all the bits.
1877 */
1878 void parse_debuglevel(char* string)
1879 {
1880         char *token;
1881
1882         /* make a copy so we don't overwrite argv[] */
1883         string = strdup(string);
1884
1885         /* handle the old numeric values too */
1886         switch(atoi(string))
1887         {
1888                 case 3:
1889                         flag_debug |= (1<<D_UORI) | (1<<D_STR);
1890                 case 2:
1891                         flag_debug |= (1<<D_POLL);
1892                 case 1:
1893                         flag_debug |= (1<<D_MISC) | (1<<D_FUNC);
1894                         debug(D_ALWAYS, "Setting debug level to 0x%0x", flag_debug);
1895                         free(string);
1896                         return;
1897                 default:
1898                         break;
1899         }
1900
1901         while ((token = strsep(&string, ", ")))
1902         {
1903                 int i;
1904                 for (i=0; debugstrings[i]; i++)
1905                 {
1906                         if(strcasecmp(token, "ALL")==0)
1907                         {
1908                                 flag_debug = (1<<D_MAX)-1;
1909                                 break;
1910                         }
1911                         if(strcasecmp(token, debugstrings[i])==0)
1912                         {
1913                                 flag_debug |= (1<<i);
1914                                 break;
1915                         }
1916                 }
1917
1918                 if (!debugstrings[i])
1919                 {
1920                         fprintf(stderr, "Invalid debug token \"%s\"\n", token);
1921                         exit(1);
1922                 }
1923         }
1924         debug(D_ALWAYS, "Setting debug level to 0x%0x", flag_debug);
1925         free(string);
1926 }
1927
1928 /*
1929    Output a line to syslog using print format, but only if the appropriate
1930    debug level is set.  The D_ALWAYS level is always enabled.
1931 */
1932 void debug(enum debuglevel level, const char* fmt, ...)
1933 {
1934         if ((1<<level) & flag_debug)
1935         {
1936 #if defined(HAVE_VSYSLOG)
1937                 va_list vl;
1938                 va_start(vl, fmt);
1939                 vsyslog(LOG_ERR, fmt, vl);
1940                 va_end(vl);
1941 #else
1942 #if defined(HAVE_VASPRINTF)
1943                 char *buf;
1944 #else
1945                 char buf[1024];
1946 #endif
1947                 va_list vl;
1948                 va_start(vl, fmt);
1949 #if defined(HAVE_VASPRINTF)
1950                 vasprintf(&buf, fmt, vl);
1951 #else
1952 #if defined(HAVE_VSNPRINTF)
1953                 vsnprintf(buf, sizeof(buf)-1, fmt, vl);
1954 #else
1955                 /* XXX possible buffer overflow here; be careful what you pass to debug() */
1956                 vsprintf(buf, fmt, vl);
1957 #endif
1958 #endif
1959                 va_end(vl);
1960                 syslog(LOG_ERR, "%s", buf);
1961 #if defined(HAVE_VASPRINTF)
1962                 free(buf);
1963 #endif 
1964 #endif /* vsyslog */
1965         }
1966 }
1967
1968 // case-insensitive search 
1969 string::size_type 
1970 find_nocase(const string& array, const string& pattern, string::size_type start)
1971 {
1972   string::size_type pos(start);
1973
1974   while (pos < array.size())
1975     {
1976       string::size_type ctr = 0;
1977
1978       while( (pos+ctr) < array.size() &&
1979              toupper(array[pos+ctr]) == toupper(pattern[ctr]) )
1980         {
1981           ++ctr;
1982           if (ctr == pattern.size())
1983           {
1984             debug(D_STR, "f_nc: <%s><%s>: hit", array.c_str(), pattern.c_str());
1985             return pos;
1986           }
1987         };
1988       
1989       ++pos;
1990     };
1991
1992   debug(D_STR, "f_nc: <%s><%s>: nohit", array.c_str(), pattern.c_str());
1993   return string::npos;
1994 }
1995
1996 // compare case-insensitive
1997 int
1998 cmp_nocase_partial(const string& s, const string& s2)
1999 {
2000   string::const_iterator p=s.begin();
2001   string::const_iterator p2=s2.begin();
2002
2003   while ( p != s.end() && p2 <= s2.end() ) {
2004     if (toupper(*p) != toupper(*p2))
2005     {
2006       debug(D_STR, "c_nc_p: <%s><%s> : miss", s.c_str(), s2.c_str());
2007       return (toupper(*p) < toupper(*p2)) ? -1 : 1;
2008     }
2009     ++p;
2010     ++p2;
2011   };
2012
2013   debug(D_STR, "c_nc_p: <%s><%s> : hit", s.c_str(), s2.c_str());
2014   return 0;
2015
2016 }
2017
2018 /* closeall() - close all FDs >= a specified value */ 
2019 void closeall(int fd) 
2020 {
2021         int fdlimit = sysconf(_SC_OPEN_MAX); 
2022         while (fd < fdlimit) 
2023                 close(fd++); 
2024 }
2025
2026 void parse_networklist(char *string, struct networklist *list)
2027 {
2028         char *token;
2029
2030         /* make a copy so we don't overwrite argv[] */
2031         string = strdup(string);
2032
2033         while ((token = strsep(&string, ", ")))
2034         {
2035                 char *tnet = strsep(&token, "/");
2036                 char *tmask = token;
2037                 struct in_addr net, mask;
2038
2039                 if (list->num_nets % 10 == 0)
2040                         list->nets = (struct net*)realloc(list->nets, sizeof(*list->nets) * (list->num_nets + 10));
2041
2042                 if (!inet_aton(tnet, &net))
2043                 {
2044                         fprintf(stderr, "Could not parse \"%s\" as a network\n", tnet);
2045                         exit(1);
2046                 }
2047
2048                 if (tmask)
2049                 {
2050                         if (strchr(tmask, '.') == NULL)
2051                         {
2052                                 /* CIDR */
2053                                 unsigned int bits;
2054                                 int ret;
2055                                 ret = sscanf(tmask, "%u", &bits);
2056                                 if (ret != 1 || bits > 32)
2057                                 {
2058                                         fprintf(stderr,"%s: bad CIDR value", tmask);
2059                                         exit(1);
2060                                 }
2061                                 mask.s_addr = htonl(~((1L << (32 - bits)) - 1) & 0xffffffff);
2062                         } else if (!inet_aton(tmask, &mask))
2063                         {
2064                                 fprintf(stderr, "Could not parse \"%s\" as a netmask\n", tmask);
2065                                 exit(1);
2066                         }
2067                 } else
2068                         mask.s_addr = 0xffffffff;
2069
2070                 {
2071                         char *snet = strdup(inet_ntoa(net));
2072                         debug(D_MISC, "Adding %s/%s to network list", snet, inet_ntoa(mask));
2073                         free(snet);
2074                 }
2075
2076                 net.s_addr = net.s_addr & mask.s_addr;
2077                 list->nets[list->num_nets].network = net;
2078                 list->nets[list->num_nets].netmask = mask;
2079                 list->num_nets++;
2080         }
2081         free(string);
2082 }
2083
2084 int ip_in_networklist(struct in_addr ip, struct networklist *list)
2085 {
2086         int i;
2087
2088         if (list->num_nets == 0)
2089                 return 0;
2090                 
2091         debug(D_NET, "Checking %s against:", inet_ntoa(ip));
2092         for (i = 0; i < list->num_nets; i++)
2093         {
2094                 debug(D_NET, "%s", inet_ntoa(list->nets[i].network));
2095                 debug(D_NET, "/%s", inet_ntoa(list->nets[i].netmask));
2096                 if ((ip.s_addr & list->nets[i].netmask.s_addr) == list->nets[i].network.s_addr)
2097         {
2098                 debug(D_NET, "Hit!");
2099                         return 1;
2100                 }
2101         }
2102
2103         return 0;
2104 }
2105
2106 char *strlwr(char *str)
2107 {
2108     char *s = str;
2109     while (*s)
2110     {
2111         *s = tolower(*s);
2112         s++;
2113     }
2114     return str;
2115 }
2116
2117 /* Log a message about missing milter macros, but only the first time */
2118 void warnmacro(char *macro, char *scope)
2119 {
2120         if (warnedmacro)
2121                 return;
2122         debug(D_ALWAYS, "Could not retrieve sendmail macro \"%s\"!.  Please add it to confMILTER_MACROS_%s for better spamassassin results",
2123                 macro, scope);
2124         warnedmacro = true;
2125 }
2126
2127 /*
2128    untrusted-argument-safe popen function - only supports "r" and "w" modes
2129    for simplicity, and always reads stdout and stderr in "r" mode.  Call
2130    fclose to close the FILE.
2131 */
2132 FILE *popenv(char *const argv[], const char *type, pid_t *pid)
2133 {
2134         FILE *iop;
2135         int pdes[2];
2136         int save_errno;
2137
2138         if ((*type != 'r' && *type != 'w') || type[1])
2139         {
2140                 errno = EINVAL;
2141                 return (NULL);
2142         }
2143         if (pipe(pdes) < 0)
2144                 return (NULL);
2145         
2146         *pid = fork();
2147         switch (*pid) {
2148         
2149         case -1:                        /* Error. */
2150                 save_errno = errno;
2151                 (void)close(pdes[0]);
2152                 (void)close(pdes[1]);
2153                 errno = save_errno;
2154                 return (NULL);
2155                 /* NOTREACHED */
2156         case 0:                         /* Child. */
2157                 if (*type == 'r') {
2158                         /*
2159                          * The dup2() to STDIN_FILENO is repeated to avoid
2160                          * writing to pdes[1], which might corrupt the
2161                          * parent's copy.  This isn't good enough in
2162                          * general, since the exit() is no return, so
2163                          * the compiler is free to corrupt all the local
2164                          * variables.
2165                          */
2166                         (void)close(pdes[0]);
2167                         (void)dup2(pdes[1], STDOUT_FILENO);
2168                         (void)dup2(pdes[1], STDERR_FILENO);
2169                         if (pdes[1] != STDOUT_FILENO && pdes[1] != STDERR_FILENO) {
2170                                 (void)close(pdes[1]);
2171                         } 
2172                 } else {
2173                         if (pdes[0] != STDIN_FILENO) {
2174                                 (void)dup2(pdes[0], STDIN_FILENO);
2175                                 (void)close(pdes[0]);
2176                         }
2177                         (void)close(pdes[1]);
2178                 }
2179                 execv(argv[0], argv);
2180                 exit(127);
2181                 /* NOTREACHED */
2182         }
2183
2184         /* Parent; assume fdopen can't fail. */
2185         if (*type == 'r') {
2186                 iop = fdopen(pdes[0], type);
2187                 (void)close(pdes[1]);
2188         } else {
2189                 iop = fdopen(pdes[1], type);
2190                 (void)close(pdes[0]);
2191         }
2192
2193         return (iop);
2194 }
2195
2196 // }}}
2197 // vim6:ai:noexpandtab