]> git.donarmstrong.com Git - deb_pkgs/spamass-milter.git/blob - spamass-milter.cpp
switch to using waitpid instead of ignoring children in popenv
[deb_pkgs/spamass-milter.git] / spamass-milter.cpp
1 // 
2 //
3 //  $Id: spamass-milter.cpp,v 1.90 2006/03/23 21:41:36 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.90 2006/03/23 21:41:36 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    struct sigaction children_sigaction;
187
188 #ifdef HAVE_VERBOSE_TERMINATE_HANDLER
189         std::set_terminate (__gnu_cxx::__verbose_terminate_handler);
190 #endif
191
192    openlog("spamass-milter", LOG_PID, LOG_MAIL);
193
194         /* Process command line options */
195         while ((c = getopt(argc, argv, args)) != -1) {
196                 switch (c) {
197                         case 'f':
198                                 dofork = true;
199                                 break;
200                         case 'd':
201                                 parse_debuglevel(optarg);
202                                 break;
203                         case 'D':
204                                 spamdhost = strdup(optarg);
205                                 break;
206                         case 'e':
207                                 flag_full_email = true;
208                                 defaultdomain = strdup(optarg);
209                                 break;
210                         case 'i':
211                                 debug(D_MISC, "Parsing ignore list");
212                                 parse_networklist(optarg, &ignorenets);
213                                 break;
214                         case 'I':
215                                 debug(D_MISC, "Ignore authenticated senders");
216                                 ignore_authenticated_senders = true;
217                                 break;
218                         case 'm':
219                                 dontmodifyspam = true;
220                                 smfilter.xxfi_flags &= ~SMFIF_CHGBODY;
221                                 break;
222                         case 'M':
223                                 dontmodify = true;
224                                 dontmodifyspam = true;
225                                 smfilter.xxfi_flags &= ~(SMFIF_CHGBODY|SMFIF_CHGHDRS);
226                                 break;
227                         case 'p':
228                                 sock = strdup(optarg);
229                                 break;
230                         case 'P':
231                                 pidfilename = strdup(optarg);
232                                 break;
233                         case 'r':
234                                 flag_reject = true;
235                                 reject_score = atoi(optarg);
236                                 break;
237                         case 'u':
238                                 flag_sniffuser = true;
239                                 defaultuser = strdup(optarg);
240                                 break;
241                         case 'b':
242                         case 'B':
243                                 if (flag_bucket)
244                                 {
245                                         fprintf(stderr, "Can only have one -b or -B flag\n");
246                                         err = 1;
247                                         break;
248                                 }
249                                 flag_bucket = true;
250                                 if (c == 'b')
251                                 {
252                                         flag_bucket_only = true;
253                                         smfilter.xxfi_flags |= SMFIF_DELRCPT; // May delete recipients
254                                 }
255                                 // we will modify the recipient list; if spamc returns
256                                 // indicating that this mail is spam, the message will be
257                                 // sent to <optarg>@localhost
258                                 smfilter.xxfi_flags |= SMFIF_ADDRCPT; // May add recipients
259                                 // XXX we should probably verify that optarg is vaguely sane
260                                 spambucket = strdup( optarg );
261                                 break;
262                         case 'x':
263                                 flag_expand = true;
264                                 break;
265                         case '?':
266                                 err = 1;
267                                 break;
268                 }
269         }
270
271    if (flag_full_email && !flag_sniffuser)
272    {
273           fprintf(stderr, "-e flag requires -u\n");
274       err=1;
275    }
276
277    /* remember the remainer of the arguments so we can pass them to spamc */
278    spamc_argc = argc - optind;
279    spamc_argv = argv + optind;
280
281    if (!sock || err) {
282       cout << PACKAGE_NAME << " - Version " << PACKAGE_VERSION << endl;
283       cout << "SpamAssassin Sendmail Milter Plugin" << endl;
284       cout << "Usage: spamass-milter -p socket [-b|-B bucket] [-d xx[,yy...]] [-D host]" << endl;
285       cout << "                      [-e defaultdomain] [-f] [-i networks] [-I] [-m] [-M]" << endl;
286       cout << "                      [-P pidfile] [-r nn] [-u defaultuser] [-x]" << endl;
287       cout << "                      [-- spamc args ]" << endl;
288       cout << "   -p socket: path to create socket" << endl;
289       cout << "   -b bucket: redirect spam to this mail address.  The orignal" << endl;
290       cout << "          recipient(s) will not receive anything." << endl;
291       cout << "   -B bucket: add this mail address as a BCC recipient of spam." << endl;
292       cout << "   -d xx[,yy ...]: set debug flags.  Logs to syslog" << endl;
293       cout << "   -D host: connect to spamd at remote host (deprecated)" << endl;
294       cout << "   -e defaultdomain: pass full email address to spamc instead of just\n"
295               "          username.  Uses 'defaultdomain' if there was none" << endl;
296       cout << "   -f: fork into background" << endl;
297       cout << "   -i: skip (ignore) checks from these IPs or netblocks" << endl;
298       cout << "          example: -i 192.168.12.5,10.0.0.0/8,172.16.0.0/255.255.0.0" << endl;
299       cout << "   -I: skip (ignore) checks if sender is authenticated" << endl;
300       cout << "   -m: don't modify body, Content-type: or Subject:" << endl;
301       cout << "   -M: don't modify the message at all" << endl;
302       cout << "   -P pidfile: Put processid in pidfile" << endl;
303       cout << "   -r nn: reject messages with a score >= nn with an SMTP error.\n"
304               "          use -1 to reject any messages tagged by SA." << endl;
305       cout << "   -u defaultuser: pass the recipient's username to spamc.\n"
306               "          Uses 'defaultuser' if there are multiple recipients." << endl;
307       cout << "   -x: pass email address through alias and virtusertable expansion." << endl;
308       cout << "   -- spamc args: pass the remaining flags to spamc." << endl;
309               
310       exit(EX_USAGE);
311    }
312
313         if (pidfilename)
314         {
315                 unlink(pidfilename);
316                 pidfile = fopen(pidfilename,"w");
317                 if (!pidfile)
318                 {
319                         fprintf(stderr, "Could not open pidfile: %s\n", strerror(errno));
320                         exit(1);
321                 }
322                 /* leave the file open through the fork, since we don't know our pid
323                    yet
324                 */
325         }
326
327
328         if (dofork == true) 
329         {
330                 if (daemon(0, 0) == -1)
331                 {
332             fprintf(stderr, "daemon() failed: %s\n", strerror(errno));
333             exit(1);
334                 }
335         }
336         
337         if (pidfile)
338         {
339                 fprintf(pidfile, "%ld\n", (long)getpid());
340                 fclose(pidfile);
341                 pidfile = NULL;
342         }       
343         
344    {
345       struct stat junk;
346       if (stat(sock,&junk) == 0) unlink(sock);
347    }
348
349    (void) smfi_setconn(sock);
350         if (smfi_register(smfilter) == MI_FAILURE) {
351                 fprintf(stderr, "smfi_register failed\n");
352                 exit(EX_UNAVAILABLE);
353         } else {
354       debug(D_MISC, "smfi_register succeeded");
355    }
356         debug(D_ALWAYS, "spamass-milter %s starting", PACKAGE_VERSION);
357         err = smfi_main();
358         debug(D_ALWAYS, "spamass-milter %s exiting", PACKAGE_VERSION);
359         if (pidfilename)
360                 unlink(pidfilename);
361         return err;
362 }
363
364 // }}}
365
366 /* Update a header if SA changes it, or add it if it is new. */
367 void update_or_insert(SpamAssassin* assassin, SMFICTX* ctx, string oldstring, t_setter setter, char *header )
368 {
369         string::size_type eoh1 = assassin->d().find("\n\n");
370         string::size_type eoh2 = assassin->d().find("\n\r\n");
371         string::size_type eoh = ( eoh1 < eoh2 ? eoh1 : eoh2 );
372
373         string newstring;
374         string::size_type oldsize;
375
376         debug(D_UORI, "u_or_i: looking at <%s>", header);
377         debug(D_UORI, "u_or_i: oldstring: <%s>", oldstring.c_str());
378
379         newstring = retrieve_field(assassin->d().substr(0, eoh), header);
380         debug(D_UORI, "u_or_i: newstring: <%s>", newstring.c_str());
381
382         oldsize = callsetter(*assassin,setter)(newstring);
383       
384         if (!dontmodify)
385         {
386                 if (newstring != oldstring)
387                 {
388                         /* change if old one was present, append if non-null */
389                         char* cstr = const_cast<char*>(newstring.c_str());
390                         if (oldsize > 0)
391                         {
392                                 debug(D_UORI, "u_or_i: changing");
393                                 smfi_chgheader(ctx, header, 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, header, 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 #if defined(__FreeBSD__)
821         int rv;
822 #endif
823
824         debug(D_FUNC, "mlfi_envrcpt: enter");
825
826         if (flag_expand)
827         {
828                 /* open a pipe to sendmail so we can do address expansion */
829
830                 char buf[1024];
831                 char *popen_argv[4];
832                 pid_t pid;
833                 
834                 popen_argv[0] = SENDMAIL;
835                 popen_argv[1] = "-bv";
836                 popen_argv[2] = envrcpt[0];
837                 popen_argv[3] = NULL;
838
839                 debug(D_RCPT, "calling %s -bv %s", SENDMAIL, envrcpt[0]);
840
841                 p = popenv(popen_argv, "r", &pid);
842                 if (!p)
843                 {
844                         debug(D_RCPT, "popenv failed(%s).  Will not expand aliases", strerror(errno));
845                         assassin->expandedrcpt.push_back(envrcpt[0]);
846                 } else
847                 {
848                         while (fgets(buf, sizeof(buf), p) != NULL)
849                         {
850                                 int i = strlen(buf);
851                                 /* strip trailing EOLs */
852                                 while (i > 0 && buf[i - 1] <= ' ')
853                                         i--;
854                                 buf[i] = '\0';
855                                 debug(D_RCPT, "sendmail output: %s", buf);
856                                 /*      From a quick scan of the sendmail source, a valid email
857                                         address gets printed via either
858                                             "deliverable: mailer %s, host %s, user %s"
859                                         or  "deliverable: mailer %s, user %s"
860                                 */
861                                 if (strstr(buf, "... deliverable: mailer "))
862                                 {
863                                         char *p=strstr(buf,", user ");
864                                         /* anything after ", user " is the email address */
865                                         debug(D_RCPT, "user: %s", p+7);
866                                         assassin->expandedrcpt.push_back(p+7);
867                                 }
868                         }
869                         fclose(p); p = NULL;
870                         waitpid(pid,0,0);
871
872                 }
873         } else
874         {
875                 assassin->expandedrcpt.push_back(envrcpt[0]);
876         }       
877         debug(D_RCPT, "Total of %d actual recipients", (int)assassin->expandedrcpt.size());
878
879         if (assassin->numrcpt() == 0)
880         {
881                 /* Send the envelope headers as X-Envelope-From: and
882                    X-Envelope-To: so that SpamAssassin can use them in its
883                    whitelist checks.  Also forge as complete a dummy
884                    Received: header as possible because SA gets a lot of
885                    info from it.
886                    
887                         HReceived: $?sfrom $s $.$?_($?s$|from $.$_)
888                                 $.$?{auth_type}(authenticated$?{auth_ssf} bits=${auth_ssf}$.)
889                                 $.by $j ($v/$Z)$?r with $r$. id $i$?{tls_version}
890                                 (version=${tls_version} cipher=${cipher} bits=${cipher_bits} verify=${verify})$.$?u
891                                 for $u; $|;
892                                 $.$b$?g
893                                 (envelope-from $g)$.
894                    
895                 */
896                 const char *macro_b, *macro_i, *macro_j, *macro_r,
897                            *macro_s, *macro_v, *macro_Z, *macro__;
898                 char date[32];
899
900                 /* RFC 822 date. */
901                 macro_b = smfi_getsymval(ctx, "b");
902                 if (!macro_b)                                  
903                 {
904                         time_t tval;
905                         time(&tval);
906                         strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %z", localtime(&tval));
907                         macro_b = date;
908                         warnmacro("b", "ENVRCPT");
909                 }
910
911                 /* queue ID */
912                 macro_i = smfi_getsymval(ctx, "i");
913                 if (!macro_i)
914                 {
915                         macro_i = "unknown";
916                         warnmacro("i", "ENVRCPT");
917                 }
918
919                 /* FQDN of this site */
920                 macro_j = smfi_getsymval(ctx, "j");
921                 if (!macro_j)
922                 {
923                         macro_j = "localhost";
924                         warnmacro("j", "ENVRCPT");
925                 }
926
927                 /* Protocol used to receive the message */
928                 macro_r = smfi_getsymval(ctx, "r");
929                 if (!macro_r)
930                 {
931                         macro_r = "SMTP";
932                         warnmacro("r", "ENVRCPT");
933                 }
934                         
935                 /* Sendmail currently cannot pass us the {s} macro, but
936                    I do not know why.  Leave this in for the day sendmail is
937                    fixed.  Until that day, use the value remembered by
938                    mlfi_helo()
939                 */
940                 macro_s = smfi_getsymval(ctx, "s");
941                 if (!macro_s)
942                         macro_s = sctx->helo;
943                 if (!macro_s)
944                         macro_s = "nohelo";
945
946                 /* Sendmail binary version */
947                 macro_v = smfi_getsymval(ctx, "v");
948                 if (!macro_v)
949                 {
950                         macro_v = "8.13.0";
951                         warnmacro("v", "ENVRCPT");
952                 }
953
954                 /* Sendmail .cf version */
955                 macro_Z = smfi_getsymval(ctx, "Z");
956                 if (!macro_Z)
957                 {
958                         macro_Z = "8.13.0";
959                         warnmacro("Z", "ENVRCPT");
960                 }
961
962                 /* Validated sending site's address */
963                 macro__ = smfi_getsymval(ctx, "_");
964                 if (!macro__)
965                 {
966                         macro__ = "unknown";
967                         warnmacro("_", "ENVRCPT");
968                 }
969
970                 assassin->output((string)"X-Envelope-From: "+assassin->from()+"\r\n");
971                 assassin->output((string)"X-Envelope-To: "+envrcpt[0]+"\r\n");
972
973                 assassin->output((string)
974                         "Received: from "+macro_s+" ("+macro__+")\r\n\t"+
975                         "by "+macro_j+" ("+macro_v+"/"+macro_Z+") with "+macro_r+" id "+macro_i+"\r\n\t"+
976                         macro_b+"\r\n\t"+
977                         "(envelope-from "+assassin->from()+")\r\n");
978
979         } else
980                 assassin->output((string)"X-Envelope-To: "+envrcpt[0]+"\r\n");
981
982         /* increment RCPT TO: count */
983         assassin->set_numrcpt();
984
985         /* If we expanded to at least one user and we haven't recorded one yet,
986            record the first one */
987         if (!assassin->expandedrcpt.empty() && (assassin->rcpt().size() == 0))
988         {
989                 debug(D_RCPT, "remembering %s for spamc", assassin->expandedrcpt.front().c_str());
990                 assassin->set_rcpt(assassin->expandedrcpt.front());
991         }
992
993         debug(D_RCPT, "remembering recipient %s", envrcpt[0]);
994         assassin->recipients.push_back( envrcpt[0] ); // XXX verify that this worked
995
996         debug(D_FUNC, "mlfi_envrcpt: exit");
997
998         return SMFIS_CONTINUE;
999 }
1000
1001 //
1002 // Gets called repeatedly for all header fields
1003 //
1004 // assembles the headers and passes them on to the SpamAssassin client
1005 // through the pipe.
1006 //
1007 // only exception: SpamAssassin header fields (X-Spam-*) get suppressed
1008 // but are being stored in the SpamAssassin element.
1009 //
1010 // this function also starts the connection with the SPAMC program the
1011 // first time it is called.
1012 //
1013
1014 sfsistat
1015 mlfi_header(SMFICTX* ctx, char* headerf, char* headerv)
1016 {
1017   SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1018   debug(D_FUNC, "mlfi_header: enter");
1019
1020   // Check if the SPAMC program has already been run, if not we run it.
1021   if ( !(assassin->connected) )
1022      {
1023        try {
1024          assassin->connected = 1; // SPAMC is getting ready to run
1025          assassin->Connect();
1026        } 
1027        catch (string& problem) {
1028          throw_error(problem);
1029          ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1030          delete assassin;
1031          debug(D_FUNC, "mlfi_header: exit error connect");
1032          return SMFIS_TEMPFAIL;
1033        };
1034      }
1035
1036   // Is it a "X-Spam-" header field?
1037   if ( cmp_nocase_partial("X-Spam-", headerf) == 0 )
1038     {
1039       int suppress = 1;
1040       // memorize content of old fields
1041
1042       if ( cmp_nocase_partial("X-Spam-Status", headerf) == 0 )
1043         assassin->set_spam_status(headerv);
1044       else if ( cmp_nocase_partial("X-Spam-Flag", headerf) == 0 )
1045         assassin->set_spam_flag(headerv);
1046       else if ( cmp_nocase_partial("X-Spam-Report", headerf) == 0 )
1047         assassin->set_spam_report(headerv);
1048       else if ( cmp_nocase_partial("X-Spam-Prev-Content-Type", headerf) == 0 )
1049         assassin->set_spam_prev_content_type(headerv);
1050       else if ( cmp_nocase_partial("X-Spam-Level", headerf) == 0 )
1051         assassin->set_spam_level(headerv);
1052       else if ( cmp_nocase_partial("X-Spam-Checker-Version", headerf) == 0 )
1053         assassin->set_spam_checker_version(headerv);
1054       else
1055       {
1056         /* Hm. X-Spam header, but not one we recognize.  Pass it through. */
1057         suppress = 0;
1058       }
1059       
1060       if (suppress)
1061       {
1062         debug(D_FUNC, "mlfi_header: suppress");
1063         return SMFIS_CONTINUE;
1064       }
1065     }
1066
1067   // Content-Type: will be stored if present
1068   if ( cmp_nocase_partial("Content-Type", headerf) == 0 )
1069     assassin->set_content_type(headerv);
1070
1071   // Subject: should be stored
1072   if ( cmp_nocase_partial("Subject", headerf) == 0 )
1073     assassin->set_subject(headerv);
1074
1075   // assemble header to be written to SpamAssassin
1076   string header = string(headerf) + ": " + headerv + "\r\n";
1077  
1078   try {
1079     // write to SpamAssassin client
1080     assassin->output(header.c_str(),header.size());
1081   } catch (string& problem)
1082     {
1083       throw_error(problem);
1084       ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1085       delete assassin;
1086       debug(D_FUNC, "mlfi_header: exit error output");
1087       return SMFIS_TEMPFAIL;
1088     };
1089   
1090   // go on...
1091   debug(D_FUNC, "mlfi_header: exit");
1092
1093   return SMFIS_CONTINUE;
1094 }
1095
1096 // 
1097 // Gets called once when the header is finished.
1098 //
1099 // writes empty line to SpamAssassin client to separate
1100 // headers from body.
1101 //
1102 sfsistat
1103 mlfi_eoh(SMFICTX* ctx)
1104 {
1105   SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1106
1107   debug(D_FUNC, "mlfi_eoh: enter");
1108
1109   // Check if the SPAMC program has already been run, if not we run it.
1110   if ( !(assassin->connected) )
1111      {
1112        try {
1113          assassin->connected = 1; // SPAMC is getting ready to run
1114          assassin->Connect();
1115        } 
1116        catch (string& problem) {
1117          throw_error(problem);
1118          ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1119          delete assassin;
1120
1121          debug(D_FUNC, "mlfi_eoh: exit error connect");
1122          return SMFIS_TEMPFAIL;
1123        };
1124      }
1125
1126   try {
1127     // add blank line between header and body
1128     assassin->output("\r\n",2);
1129   } catch (string& problem)
1130     {
1131       throw_error(problem);
1132       ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1133       delete assassin;
1134   
1135       debug(D_FUNC, "mlfi_eoh: exit error output");
1136       return SMFIS_TEMPFAIL;
1137     };
1138   
1139   // go on...
1140
1141   debug(D_FUNC, "mlfi_eoh: exit");
1142   return SMFIS_CONTINUE;
1143 }
1144
1145 //
1146 // Gets called repeatedly to transmit the body
1147 //
1148 // writes everything directly to SpamAssassin client
1149 //
1150 sfsistat
1151 mlfi_body(SMFICTX* ctx, u_char *bodyp, size_t bodylen)
1152 {
1153   debug(D_FUNC, "mlfi_body: enter");
1154   SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1155
1156  
1157   try {
1158     assassin->output(bodyp, bodylen);
1159   } catch (string& problem)
1160     {
1161       throw_error(problem);
1162       ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1163       delete assassin;
1164       debug(D_FUNC, "mlfi_body: exit error");
1165       return SMFIS_TEMPFAIL;
1166     };
1167
1168   // go on...
1169   debug(D_FUNC, "mlfi_body: exit");
1170   return SMFIS_CONTINUE;
1171 }
1172
1173 //
1174 // Gets called once at the end of mail processing
1175 //
1176 // tells SpamAssassin client that the mail is complete
1177 // through EOF and then modifies the mail accordingly by
1178 // calling the "assassinate" function
1179 //
1180 sfsistat
1181 mlfi_eom(SMFICTX* ctx)
1182 {
1183   SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1184   int milter_status;
1185  
1186   debug(D_FUNC, "mlfi_eom: enter");
1187   try {
1188
1189     // close output pipe to signal EOF to SpamAssassin
1190     assassin->close_output();
1191
1192     // read what the Assassin is telling us
1193     assassin->input();
1194
1195     milter_status = assassinate(ctx, assassin);
1196
1197     // now cleanup the element.
1198     ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1199     delete assassin;
1200
1201   } catch (string& problem)
1202     {
1203       throw_error(problem);
1204       ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1205       delete assassin;
1206       debug(D_FUNC, "mlfi_eom: exit error");
1207       return SMFIS_TEMPFAIL;
1208     };
1209   
1210   // go on...
1211   debug(D_FUNC, "mlfi_eom: exit");
1212   return milter_status;
1213 }
1214
1215 //
1216 // Gets called on session-basis. This keeps things nice & quiet.
1217 //
1218 sfsistat
1219 mlfi_close(SMFICTX* ctx)
1220 {
1221   struct context *sctx;
1222   debug(D_FUNC, "mlfi_close");
1223   
1224   sctx = (struct context*)smfi_getpriv(ctx);
1225   if (sctx == NULL)
1226     return SMFIS_ACCEPT;
1227
1228   if (sctx->helo)
1229         free(sctx->helo);
1230   free(sctx);
1231   smfi_setpriv(ctx, NULL);
1232   
1233   return SMFIS_ACCEPT;
1234 }
1235
1236 //
1237 // Gets called when things are being aborted.
1238 //
1239 // kills the SpamAssassin object, its destructor should
1240 // take care of everything.
1241 //
1242 sfsistat
1243 mlfi_abort(SMFICTX* ctx)
1244 {
1245   SpamAssassin* assassin = ((struct context *)smfi_getpriv(ctx))->assassin;
1246
1247   debug(D_FUNC, "mlfi_abort");
1248   ((struct context *)smfi_getpriv(ctx))->assassin=NULL;
1249   delete assassin;
1250
1251   return SMFIS_ACCEPT;
1252 }
1253
1254 // }}}
1255
1256 // {{{ SpamAssassin Class
1257
1258 //
1259 // This is a new constructor for the SpamAssassin object.  It simply 
1260 // initializes two variables.  The original constructor has been
1261 // renamed to Connect().
1262 //
1263 SpamAssassin::SpamAssassin():
1264   error(false),
1265   running(false),
1266   connected(false),
1267   _numrcpt(0)
1268 {
1269 }
1270
1271
1272 SpamAssassin::~SpamAssassin()
1273
1274         if (connected) 
1275         {
1276                 // close all pipes that are still open
1277                 if (pipe_io[0][0] > -1) close(pipe_io[0][0]);
1278                 if (pipe_io[0][1] > -1) close(pipe_io[0][1]);
1279                 if (pipe_io[1][0] > -1) close(pipe_io[1][0]);
1280                 if (pipe_io[1][1] > -1) close(pipe_io[1][1]);
1281
1282                 // child still running?
1283                 if (running)
1284                 {
1285                         // make sure the pid is valid
1286                         if (pid > 0) {
1287                                 // slaughter child
1288                                 kill(pid, SIGKILL);
1289
1290                                 // wait for child to terminate
1291                                 int status;
1292                                 waitpid(pid, &status, 0);
1293                         }
1294                 }
1295     }
1296
1297         // Clean up the recip list. Might be overkill, but it's good housekeeping.
1298         while( !recipients.empty()) 
1299         {
1300                 recipients.pop_front();
1301         }
1302         // Clean up the recip list. Might be overkill, but it's good housekeeping.
1303         while( !expandedrcpt.empty()) 
1304         {
1305                 expandedrcpt.pop_front();
1306         }
1307 }
1308
1309 //
1310 // This is the old SpamAssassin constructor.  It has been renamed Connect(),
1311 // and is now called at the beginning of the mlfi_header() function.
1312 //
1313
1314 void SpamAssassin::Connect()
1315 {
1316   // set up pipes for in- and output
1317   if (pipe(pipe_io[0]))
1318     throw string(string("pipe error: ")+string(strerror(errno)));
1319   if (pipe(pipe_io[1]))
1320     throw string(string("pipe error: ")+string(strerror(errno)));
1321
1322   // now execute SpamAssassin client for contact with SpamAssassin spamd
1323
1324   // start child process
1325   switch(pid = fork())
1326     {
1327     case -1:
1328       // forking trouble. throw error.
1329       throw string(string("fork error: ")+string(strerror(errno)));
1330       break;
1331     case 0:
1332       // +++ CHILD +++
1333       
1334       // close unused pipes
1335       close(pipe_io[1][0]);
1336       close(pipe_io[0][1]);
1337
1338       // redirect stdin(0), stdout(1) and stderr(2)
1339       dup2(pipe_io[0][0],0);
1340       dup2(pipe_io[1][1],1);
1341       dup2(pipe_io[1][1],2);
1342
1343       closeall(3);
1344
1345       // execute spamc 
1346       // absolute path (determined in autoconf) 
1347       // should be a little more secure
1348       // XXX arbitrary 100-argument max
1349       int argc = 0;
1350       char** argv = (char**) malloc(100*sizeof(char*));
1351       argv[argc++] = SPAMC;
1352       if (flag_sniffuser) 
1353       {
1354         argv[argc++] = "-u";
1355         if ( expandedrcpt.size() != 1 )
1356         {
1357           // More (or less?) than one recipient, so we pass the default
1358           // username to SPAMC.  This way special rules can be defined for
1359           // multi recipient messages.
1360           debug(D_RCPT, "%d recipients; spamc gets default username %s", (int)expandedrcpt.size(), defaultuser);
1361           argv[argc++] = defaultuser; 
1362         } else
1363         { 
1364           // There is only 1 recipient so we pass the username
1365           // (converted to lowercase) to SPAMC.  Don't worry about 
1366           // freeing this memory as we're exec()ing anyhow.
1367           if (flag_full_email)
1368             argv[argc] = strlwr(strdup(full_user().c_str())); 
1369           else
1370             argv[argc] = strlwr(strdup(local_user().c_str())); 
1371
1372           debug(D_RCPT, "spamc gets %s", argv[argc]);
1373          
1374           argc++;
1375         }
1376       }
1377       if (spamdhost) 
1378       {
1379         argv[argc++] = "-d";
1380         argv[argc++] = spamdhost;
1381       }
1382       if (spamc_argc)
1383       {
1384         memcpy(argv+argc, spamc_argv, spamc_argc * sizeof(char *));
1385         argc += spamc_argc;
1386       }
1387       argv[argc++] = 0;
1388
1389       execvp(argv[0] , argv); // does not return!
1390
1391       // execution failed
1392       throw_error(string("execution error: ")+string(strerror(errno)));
1393       _exit(1);
1394       break;
1395     }
1396
1397   // +++ PARENT +++
1398
1399   // close unused pipes
1400   close(pipe_io[0][0]);
1401   close(pipe_io[1][1]);
1402   pipe_io[0][0]=-1;
1403   pipe_io[1][1]=-1;
1404
1405   // mark the pipes non-blocking
1406   if(fcntl(pipe_io[0][1], F_SETFL, O_NONBLOCK) == -1)
1407      throw string(string("Cannot set pipe01 nonblocking: ")+string(strerror(errno)));
1408 #if 0  /* don't really need to make the sink pipe nonblocking */
1409   if(fcntl(pipe_io[1][0], F_SETFL, O_NONBLOCK) == -1)
1410      throw string(string("Cannot set pipe10 nonblocking: ")+string(strerror(errno)));
1411 #endif
1412
1413   // we have to assume the client is running now.
1414   running=true;
1415
1416   /* If we have any buffered output, write it now. */
1417   if (outputbuffer.size())
1418   {
1419     output(outputbuffer);
1420     outputbuffer="";
1421   }
1422 }
1423
1424 // write to SpamAssassin
1425 void
1426 SpamAssassin::output(const void* buffer, long size)
1427 {
1428   debug(D_FUNC, "::output enter");
1429
1430   debug(D_SPAMC, "output \"%*.*s\"", (int)size, (int)size, (char *)buffer);
1431
1432   // if there are problems, fail.
1433   if (error)
1434     throw string("tried output despite problems. failed.");
1435
1436   /* If we haven't launched spamc yet, just store the data */
1437   if (!connected)
1438   {
1439         /* Silly C++ can't tell the difference between 
1440                 (const char*, string::size_type) and
1441                 (string::size_type, char), so we have to cast the parameters.
1442         */
1443         outputbuffer.append((const char *)buffer,(string::size_type)size);
1444         debug(D_FUNC, "::output exit1");
1445         return;
1446   }
1447
1448   // send to SpamAssassin
1449   long total = 0;
1450   long wsize = 0;
1451   string reason;
1452   int status;
1453   do {
1454         struct pollfd fds[2];
1455         int nfds = 2, nready;
1456         fds[0].fd = pipe_io[0][1];
1457         fds[0].events = POLLOUT;
1458         fds[1].fd = pipe_io[1][0];
1459         fds[1].events = POLLIN;
1460
1461         debug(D_POLL, "polling fds %d and %d", pipe_io[0][1], pipe_io[1][0]);
1462         nready = poll(fds, nfds, 1000);
1463         if (nready == -1)
1464                 throw("poll failed");
1465
1466         debug(D_POLL, "poll returned %d, fd0=%d, fd1=%d", nready, fds[0].revents, fds[1].revents);
1467
1468         if (fds[1].revents & (POLLERR|POLLNVAL|POLLHUP))
1469         {
1470                 throw string("poll says my read pipe is busted");
1471         }
1472
1473         if (fds[0].revents & (POLLERR|POLLNVAL|POLLHUP))
1474         {
1475                 throw string("poll says my write pipe is busted");
1476         }
1477
1478         if (fds[1].revents & POLLIN)
1479         {
1480                 debug(D_POLL, "poll says I can read");
1481                 read_pipe();
1482         }
1483
1484         if (fds[0].revents & POLLOUT)
1485         {
1486                 debug(D_POLL, "poll says I can write");
1487                 switch(wsize = write(pipe_io[0][1], (char *)buffer + total, size - total))
1488                 {
1489                   case -1:
1490                         if (errno == EAGAIN)
1491                                 continue;
1492                         reason = string(strerror(errno));
1493
1494                         // close the pipes
1495                         close(pipe_io[0][1]);
1496                         close(pipe_io[1][0]);
1497                         pipe_io[0][1]=-1;       
1498                         pipe_io[1][0]=-1;       
1499
1500                         // Slaughter child
1501                         kill(pid, SIGKILL);
1502
1503                         // set flags
1504                         error = true;
1505                         running = false;
1506         
1507                         // wait until child is dead
1508                         waitpid(pid, &status, 0);
1509
1510                         throw string(string("write error: ")+reason);   
1511                         break;
1512               default:
1513                         total += wsize;
1514                         debug(D_POLL, "wrote %ld bytes", wsize);
1515                         break;
1516                 }
1517         }
1518   } while ( total < size );
1519
1520   debug(D_FUNC, "::output exit2");
1521 }
1522
1523 void SpamAssassin::output(const void* buffer)
1524 {
1525         output(buffer, strlen((const char *)buffer));
1526 }
1527
1528 void SpamAssassin::output(string buffer)
1529 {
1530         output(buffer.c_str(), buffer.size());
1531 }
1532
1533 // close output pipe
1534 void
1535 SpamAssassin::close_output()
1536 {
1537   if(close(pipe_io[0][1]))
1538     throw string(string("close error: ")+string(strerror(errno)));
1539   pipe_io[0][1]=-1;
1540 }
1541
1542 void
1543 SpamAssassin::input()
1544 {
1545   debug(D_FUNC, "::input enter");
1546   // if the child has exited or we experienced an error, return
1547   // immediately.
1548   if (!running || error)
1549   {
1550     debug(D_FUNC, "::input exit1");
1551     return;
1552   }
1553
1554   // keep reading from input pipe until it is empty
1555   empty_and_close_pipe();
1556   
1557   // that's it, we're through
1558   running = false;
1559
1560   // wait until child is dead
1561   int status;
1562   if(waitpid(pid, &status, 0)<0)
1563     {
1564       error = true;
1565       throw string(string("waitpid error: ")+string(strerror(errno)));
1566     }; 
1567         debug(D_FUNC, "::input exit2");
1568 }
1569
1570 //
1571 // return reference to mail
1572 //
1573 string& 
1574 SpamAssassin::d()
1575 {
1576   return mail;
1577 }
1578
1579 //
1580 // get values of the different SpamAssassin fields
1581 //
1582 string& 
1583 SpamAssassin::spam_status()
1584 {
1585   return x_spam_status;
1586 }
1587
1588 string& 
1589 SpamAssassin::spam_flag()
1590 {
1591   return x_spam_flag;
1592 }
1593
1594 string& 
1595 SpamAssassin::spam_report()
1596 {
1597   return x_spam_report;
1598 }
1599
1600 string& 
1601 SpamAssassin::spam_prev_content_type()
1602 {
1603   return x_spam_prev_content_type;
1604 }
1605
1606 string& 
1607 SpamAssassin::spam_checker_version()
1608 {
1609   return x_spam_checker_version;
1610 }
1611
1612 string& 
1613 SpamAssassin::spam_level()
1614 {
1615   return x_spam_level;
1616 }
1617
1618 string& 
1619 SpamAssassin::content_type()
1620 {
1621   return _content_type;
1622 }
1623
1624 string& 
1625 SpamAssassin::subject()
1626 {
1627   return _subject;
1628 }
1629
1630 string&
1631 SpamAssassin::rcpt()
1632 {
1633   return _rcpt;
1634 }
1635
1636 string&
1637 SpamAssassin::from()
1638 {
1639   return _from;
1640 }
1641
1642 string&
1643 SpamAssassin::connectip()
1644 {
1645   return _connectip;
1646 }
1647
1648
1649 string
1650 SpamAssassin::local_user()
1651 {
1652   // assuming we have a recipient in the form: <username@somehost.somedomain>
1653   // (angle brackets optional) we return 'username'
1654   if (_rcpt[0] == '<')
1655     return _rcpt.substr(1, _rcpt.find_first_of("@+")-1);
1656   else
1657         return _rcpt.substr(0, _rcpt.find_first_of("@+"));
1658 }
1659
1660 string
1661 SpamAssassin::full_user()
1662 {
1663   string name;
1664   // assuming we have a recipient in the form: <username@somehost.somedomain>
1665   // (angle brackets optional) we return 'username@somehost.somedomain'
1666   if (_rcpt[0] == '<')
1667     name = _rcpt.substr(1, _rcpt.find('>')-1);
1668   else
1669         name = _rcpt;
1670   if(name.find('@') == string::npos)
1671   {
1672     /* if the name had no domain part (local delivery), append the default one */
1673     name = name + "@" + defaultdomain;
1674   }
1675   return name;
1676 }
1677
1678 int
1679 SpamAssassin::numrcpt()
1680 {
1681   return _numrcpt;
1682 }
1683
1684 int
1685 SpamAssassin::set_numrcpt()
1686 {
1687   _numrcpt++;
1688   return _numrcpt;
1689 }
1690
1691 int
1692 SpamAssassin::set_numrcpt(const int val)
1693 {
1694   _numrcpt = val;
1695   return _numrcpt;
1696 }
1697
1698 //
1699 // set the values of the different SpamAssassin
1700 // fields in our element. Returns former size of field
1701 //
1702 string::size_type
1703 SpamAssassin::set_spam_status(const string& val)
1704 {
1705   string::size_type old = x_spam_status.size();
1706   x_spam_status = val;
1707   return (old);
1708 }
1709
1710 string::size_type
1711 SpamAssassin::set_spam_flag(const string& val)
1712 {
1713   string::size_type old = x_spam_flag.size();
1714   x_spam_flag = val;
1715   return (old);
1716 }
1717
1718 string::size_type
1719 SpamAssassin::set_spam_report(const string& val)
1720 {
1721   string::size_type old = x_spam_report.size();
1722   x_spam_report = val;
1723   return (old);
1724 }
1725
1726 string::size_type
1727 SpamAssassin::set_spam_prev_content_type(const string& val)
1728 {
1729   string::size_type old = x_spam_prev_content_type.size();
1730   x_spam_prev_content_type = val;
1731   return (old);
1732 }
1733
1734 string::size_type
1735 SpamAssassin::set_spam_checker_version(const string& val)
1736 {
1737   string::size_type old = x_spam_checker_version.size();
1738   x_spam_checker_version = val;
1739   return (old);
1740 }
1741
1742 string::size_type
1743 SpamAssassin::set_spam_level(const string& val)
1744 {
1745   string::size_type old = x_spam_level.size();
1746   x_spam_level = val;
1747   return (old);
1748 }
1749
1750 string::size_type
1751 SpamAssassin::set_content_type(const string& val)
1752 {
1753   string::size_type old = _content_type.size();
1754   _content_type = val;
1755   return (old);
1756 }
1757
1758 string::size_type
1759 SpamAssassin::set_subject(const string& val)
1760 {
1761   string::size_type old = _subject.size();
1762   _subject = val;
1763   return (old);
1764 }
1765
1766 string::size_type
1767 SpamAssassin::set_rcpt(const string& val)
1768 {
1769   string::size_type old = _rcpt.size();
1770   _rcpt = val;
1771   return (old);  
1772 }
1773
1774 string::size_type
1775 SpamAssassin::set_from(const string& val)
1776 {
1777   string::size_type old = _from.size();
1778   _from = val;
1779   return (old);  
1780 }
1781
1782 string::size_type
1783 SpamAssassin::set_connectip(const string& val)
1784 {
1785   string::size_type old = _connectip.size();
1786   _connectip = val;
1787   return (old);  
1788 }
1789
1790 //
1791 // Read available output from SpamAssassin client
1792 //
1793 int
1794 SpamAssassin::read_pipe()
1795 {
1796         long size;
1797         int  status;
1798         char iobuff[1024];
1799         string reason;
1800
1801         debug(D_FUNC, "::read_pipe enter");
1802
1803         if (pipe_io[1][0] == -1)
1804         {
1805                 debug(D_FUNC, "::read_pipe exit - shouldn't have been called?");
1806                 return 0;
1807         }
1808
1809         size = read(pipe_io[1][0], iobuff, 1024);
1810
1811         if (size < 0)
1812     {
1813                 // Error. 
1814                 reason = string(strerror(errno));
1815                 
1816                 // Close remaining pipe.
1817                 close(pipe_io[1][0]);
1818                 pipe_io[1][0] = -1;
1819         
1820                 // Slaughter child
1821                 kill(pid, SIGKILL);
1822         
1823                 // set flags
1824                 error = true;
1825                 running = false;
1826         
1827                 // wait until child is dead
1828                 waitpid(pid, &status, 0);
1829         
1830                 // throw the error message that caused this trouble
1831                 throw string(string("read error: ")+reason);
1832         } else if ( size == 0 )
1833         {
1834
1835                 // EOF. Close the pipe
1836                 if(close(pipe_io[1][0]))
1837                         throw string(string("close error: ")+string(strerror(errno)));
1838                 pipe_io[1][0] = -1;
1839         
1840         } else
1841         { 
1842                 // append to mail buffer 
1843                 mail.append(iobuff, size);
1844                 debug(D_POLL, "read %ld bytes", size);
1845                 debug(D_SPAMC, "input  \"%*.*s\"", (int)size, (int)size, iobuff);
1846         }
1847         debug(D_FUNC, "::read_pipe exit");
1848         return size;
1849 }
1850
1851 //
1852 // Read all output from SpamAssassin client
1853 // and close the pipe
1854 //
1855 void
1856 SpamAssassin::empty_and_close_pipe()
1857 {
1858         debug(D_FUNC, "::empty_and_close_pipe enter");
1859         while (read_pipe())
1860                 ;
1861         debug(D_FUNC, "::empty_and_close_pipe exit");
1862 }
1863
1864 // }}}
1865
1866 // {{{ Some small subroutines without much relation to functionality
1867
1868 // output error message to syslog facility
1869 void
1870 throw_error(const string& errmsg)
1871 {
1872   if (errmsg.c_str())
1873     syslog(LOG_ERR, "Thrown error: %s", errmsg.c_str());
1874   else
1875     syslog(LOG_ERR, "Unknown error");
1876 }
1877
1878 /* Takes a comma or space-delimited string of debug tokens and sets the
1879    appropriate bits in flag_debug.  "all" sets all the bits.
1880 */
1881 void parse_debuglevel(char* string)
1882 {
1883         char *token;
1884
1885         /* make a copy so we don't overwrite argv[] */
1886         string = strdup(string);
1887
1888         /* handle the old numeric values too */
1889         switch(atoi(string))
1890         {
1891                 case 3:
1892                         flag_debug |= (1<<D_UORI) | (1<<D_STR);
1893                 case 2:
1894                         flag_debug |= (1<<D_POLL);
1895                 case 1:
1896                         flag_debug |= (1<<D_MISC) | (1<<D_FUNC);
1897                         debug(D_ALWAYS, "Setting debug level to 0x%0x", flag_debug);
1898                         free(string);
1899                         return;
1900                 default:
1901                         break;
1902         }
1903
1904         while ((token = strsep(&string, ", ")))
1905         {
1906                 int i;
1907                 for (i=0; debugstrings[i]; i++)
1908                 {
1909                         if(strcasecmp(token, "ALL")==0)
1910                         {
1911                                 flag_debug = (1<<D_MAX)-1;
1912                                 break;
1913                         }
1914                         if(strcasecmp(token, debugstrings[i])==0)
1915                         {
1916                                 flag_debug |= (1<<i);
1917                                 break;
1918                         }
1919                 }
1920
1921                 if (!debugstrings[i])
1922                 {
1923                         fprintf(stderr, "Invalid debug token \"%s\"\n", token);
1924                         exit(1);
1925                 }
1926         }
1927         debug(D_ALWAYS, "Setting debug level to 0x%0x", flag_debug);
1928         free(string);
1929 }
1930
1931 /*
1932    Output a line to syslog using print format, but only if the appropriate
1933    debug level is set.  The D_ALWAYS level is always enabled.
1934 */
1935 void debug(enum debuglevel level, const char* fmt, ...)
1936 {
1937         if ((1<<level) & flag_debug)
1938         {
1939 #if defined(HAVE_VSYSLOG)
1940                 va_list vl;
1941                 va_start(vl, fmt);
1942                 vsyslog(LOG_ERR, fmt, vl);
1943                 va_end(vl);
1944 #else
1945 #if defined(HAVE_VASPRINTF)
1946                 char *buf;
1947 #else
1948                 char buf[1024];
1949 #endif
1950                 va_list vl;
1951                 va_start(vl, fmt);
1952 #if defined(HAVE_VASPRINTF)
1953                 vasprintf(&buf, fmt, vl);
1954 #else
1955 #if defined(HAVE_VSNPRINTF)
1956                 vsnprintf(buf, sizeof(buf)-1, fmt, vl);
1957 #else
1958                 /* XXX possible buffer overflow here; be careful what you pass to debug() */
1959                 vsprintf(buf, fmt, vl);
1960 #endif
1961 #endif
1962                 va_end(vl);
1963                 syslog(LOG_ERR, "%s", buf);
1964 #if defined(HAVE_VASPRINTF)
1965                 free(buf);
1966 #endif 
1967 #endif /* vsyslog */
1968         }
1969 }
1970
1971 // case-insensitive search 
1972 string::size_type 
1973 find_nocase(const string& array, const string& pattern, string::size_type start)
1974 {
1975   string::size_type pos(start);
1976
1977   while (pos < array.size())
1978     {
1979       string::size_type ctr = 0;
1980
1981       while( (pos+ctr) < array.size() &&
1982              toupper(array[pos+ctr]) == toupper(pattern[ctr]) )
1983         {
1984           ++ctr;
1985           if (ctr == pattern.size())
1986           {
1987             debug(D_STR, "f_nc: <%s><%s>: hit", array.c_str(), pattern.c_str());
1988             return pos;
1989           }
1990         };
1991       
1992       ++pos;
1993     };
1994
1995   debug(D_STR, "f_nc: <%s><%s>: nohit", array.c_str(), pattern.c_str());
1996   return string::npos;
1997 }
1998
1999 // compare case-insensitive
2000 int
2001 cmp_nocase_partial(const string& s, const string& s2)
2002 {
2003   string::const_iterator p=s.begin();
2004   string::const_iterator p2=s2.begin();
2005
2006   while ( p != s.end() && p2 <= s2.end() ) {
2007     if (toupper(*p) != toupper(*p2))
2008     {
2009       debug(D_STR, "c_nc_p: <%s><%s> : miss", s.c_str(), s2.c_str());
2010       return (toupper(*p) < toupper(*p2)) ? -1 : 1;
2011     }
2012     ++p;
2013     ++p2;
2014   };
2015
2016   debug(D_STR, "c_nc_p: <%s><%s> : hit", s.c_str(), s2.c_str());
2017   return 0;
2018
2019 }
2020
2021 /* closeall() - close all FDs >= a specified value */ 
2022 void closeall(int fd) 
2023 {
2024         int fdlimit = sysconf(_SC_OPEN_MAX); 
2025         while (fd < fdlimit) 
2026                 close(fd++); 
2027 }
2028
2029 void parse_networklist(char *string, struct networklist *list)
2030 {
2031         char *token;
2032
2033         /* make a copy so we don't overwrite argv[] */
2034         string = strdup(string);
2035
2036         while ((token = strsep(&string, ", ")))
2037         {
2038                 char *tnet = strsep(&token, "/");
2039                 char *tmask = token;
2040                 struct in_addr net, mask;
2041
2042                 if (list->num_nets % 10 == 0)
2043                         list->nets = (struct net*)realloc(list->nets, sizeof(*list->nets) * (list->num_nets + 10));
2044
2045                 if (!inet_aton(tnet, &net))
2046                 {
2047                         fprintf(stderr, "Could not parse \"%s\" as a network\n", tnet);
2048                         exit(1);
2049                 }
2050
2051                 if (tmask)
2052                 {
2053                         if (strchr(tmask, '.') == NULL)
2054                         {
2055                                 /* CIDR */
2056                                 unsigned int bits;
2057                                 int ret;
2058                                 ret = sscanf(tmask, "%u", &bits);
2059                                 if (ret != 1 || bits > 32)
2060                                 {
2061                                         fprintf(stderr,"%s: bad CIDR value", tmask);
2062                                         exit(1);
2063                                 }
2064                                 mask.s_addr = htonl(~((1L << (32 - bits)) - 1) & 0xffffffff);
2065                         } else if (!inet_aton(tmask, &mask))
2066                         {
2067                                 fprintf(stderr, "Could not parse \"%s\" as a netmask\n", tmask);
2068                                 exit(1);
2069                         }
2070                 } else
2071                         mask.s_addr = 0xffffffff;
2072
2073                 {
2074                         char *snet = strdup(inet_ntoa(net));
2075                         debug(D_MISC, "Adding %s/%s to network list", snet, inet_ntoa(mask));
2076                         free(snet);
2077                 }
2078
2079                 net.s_addr = net.s_addr & mask.s_addr;
2080                 list->nets[list->num_nets].network = net;
2081                 list->nets[list->num_nets].netmask = mask;
2082                 list->num_nets++;
2083         }
2084         free(string);
2085 }
2086
2087 int ip_in_networklist(struct in_addr ip, struct networklist *list)
2088 {
2089         int i;
2090
2091         if (list->num_nets == 0)
2092                 return 0;
2093                 
2094         debug(D_NET, "Checking %s against:", inet_ntoa(ip));
2095         for (i = 0; i < list->num_nets; i++)
2096         {
2097                 debug(D_NET, "%s", inet_ntoa(list->nets[i].network));
2098                 debug(D_NET, "/%s", inet_ntoa(list->nets[i].netmask));
2099                 if ((ip.s_addr & list->nets[i].netmask.s_addr) == list->nets[i].network.s_addr)
2100         {
2101                 debug(D_NET, "Hit!");
2102                         return 1;
2103                 }
2104         }
2105
2106         return 0;
2107 }
2108
2109 char *strlwr(char *str)
2110 {
2111     char *s = str;
2112     while (*s)
2113     {
2114         *s = tolower(*s);
2115         s++;
2116     }
2117     return str;
2118 }
2119
2120 /* Log a message about missing milter macros, but only the first time */
2121 void warnmacro(char *macro, char *scope)
2122 {
2123         if (warnedmacro)
2124                 return;
2125         debug(D_ALWAYS, "Could not retrieve sendmail macro \"%s\"!.  Please add it to confMILTER_MACROS_%s for better spamassassin results",
2126                 macro, scope);
2127         warnedmacro = true;
2128 }
2129
2130 /*
2131    untrusted-argument-safe popen function - only supports "r" and "w" modes
2132    for simplicity, and always reads stdout and stderr in "r" mode.  Call
2133    fclose to close the FILE.
2134 */
2135 FILE *popenv(char *const argv[], const char *type, pid_t *pid)
2136 {
2137         FILE *iop;
2138         int pdes[2];
2139         int save_errno;
2140
2141         if ((*type != 'r' && *type != 'w') || type[1])
2142         {
2143                 errno = EINVAL;
2144                 return (NULL);
2145         }
2146         if (pipe(pdes) < 0)
2147                 return (NULL);
2148         
2149         *pid = fork();
2150         switch (*pid) {
2151         
2152         case -1:                        /* Error. */
2153                 save_errno = errno;
2154                 (void)close(pdes[0]);
2155                 (void)close(pdes[1]);
2156                 errno = save_errno;
2157                 return (NULL);
2158                 /* NOTREACHED */
2159         case 0:                         /* Child. */
2160                 if (*type == 'r') {
2161                         /*
2162                          * The dup2() to STDIN_FILENO is repeated to avoid
2163                          * writing to pdes[1], which might corrupt the
2164                          * parent's copy.  This isn't good enough in
2165                          * general, since the exit() is no return, so
2166                          * the compiler is free to corrupt all the local
2167                          * variables.
2168                          */
2169                         (void)close(pdes[0]);
2170                         (void)dup2(pdes[1], STDOUT_FILENO);
2171                         (void)dup2(pdes[1], STDERR_FILENO);
2172                         if (pdes[1] != STDOUT_FILENO && pdes[1] != STDERR_FILENO) {
2173                                 (void)close(pdes[1]);
2174                         } 
2175                 } else {
2176                         if (pdes[0] != STDIN_FILENO) {
2177                                 (void)dup2(pdes[0], STDIN_FILENO);
2178                                 (void)close(pdes[0]);
2179                         }
2180                         (void)close(pdes[1]);
2181                 }
2182                 execv(argv[0], argv);
2183                 exit(127);
2184                 /* NOTREACHED */
2185         }
2186
2187         /* Parent; assume fdopen can't fail. */
2188         if (*type == 'r') {
2189                 iop = fdopen(pdes[0], type);
2190                 (void)close(pdes[1]);
2191         } else {
2192                 iop = fdopen(pdes[1], type);
2193                 (void)close(pdes[0]);
2194         }
2195
2196         return (iop);
2197 }
2198
2199 // }}}
2200 // vim6:ai:noexpandtab