Reformat to project standard
[exim.git] / src / src / spam.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2003-???? */
6 /* License: GPL */
7
8 /* Code for calling spamassassin's spamd. Called from acl.c. */
9
10 #include "exim.h"
11 #ifdef WITH_CONTENT_SCAN
12 #include "spam.h"
13
14 uschar spam_score_buffer[16];
15 uschar spam_score_int_buffer[16];
16 uschar spam_bar_buffer[128];
17 uschar spam_report_buffer[32600];
18 uschar prev_user_name[128] = "";
19 int spam_ok = 0;
20 int spam_rc = 0;
21 uschar *prev_spamd_address_work = NULL;
22
23 int
24 spam(uschar **listptr)
25 {
26   int sep = 0;
27   uschar *list = *listptr;
28   uschar *user_name;
29   uschar user_name_buffer[128];
30   unsigned long mbox_size;
31   FILE *mbox_file;
32   int spamd_sock = -1;
33   uschar spamd_buffer[32600];
34   int i, j, offset, result;
35   uschar spamd_version[8];
36   uschar spamd_score_char;
37   double spamd_threshold, spamd_score;
38   int spamd_report_offset;
39   uschar *p,*q;
40   int override = 0;
41   time_t start;
42   size_t read, wrote;
43   struct sockaddr_un server;
44 #ifndef NO_POLL_H
45   struct pollfd pollfd;
46 #else                               /* Patch posted by Erik ? for OS X */
47   struct timeval select_tv;         /* and applied by PH */
48   fd_set select_fd;
49 #endif
50   uschar *spamd_address_work;
51
52   /* stop compiler warning */
53   result = 0;
54
55   /* find the username from the option list */
56   if ((user_name = string_nextinlist(&list, &sep,
57                                      user_name_buffer,
58                                      sizeof(user_name_buffer))) == NULL)
59     {
60     /* no username given, this means no scanning should be done */
61     return FAIL;
62     }
63
64   /* if username is "0" or "false", do not scan */
65   if ( (Ustrcmp(user_name,"0") == 0) ||
66        (strcmpic(user_name,US"false") == 0) )
67     return FAIL;
68
69   /* if there is an additional option, check if it is "true" */
70   if (strcmpic(list,US"true") == 0)
71     /* in that case, always return true later */
72     override = 1;
73
74   /* expand spamd_address if needed */
75   if (*spamd_address == '$')
76     {
77     spamd_address_work = expand_string(spamd_address);
78     if (spamd_address_work == NULL)
79       {
80       log_write(0, LOG_MAIN|LOG_PANIC,
81         "spamassassin acl condition: spamd_address starts with $, but expansion failed: %s", expand_string_message);
82       return DEFER;
83       }
84     }
85   else
86     spamd_address_work = spamd_address;
87
88   /* check if previous spamd_address was expanded and has changed. dump cached results if so */
89   if (  spam_ok
90      && prev_spamd_address_work != NULL
91      && Ustrcmp(prev_spamd_address_work, spamd_address_work) != 0
92      )
93     spam_ok = 0;
94
95   /* if we scanned for this username last time, just return */
96   if ( spam_ok && Ustrcmp(prev_user_name, user_name) == 0)
97     if (override)
98       return OK;
99     else
100       return spam_rc;
101
102   /* make sure the eml mbox file is spooled up */
103   mbox_file = spool_mbox(&mbox_size, NULL);
104
105   if (mbox_file == NULL)
106     {
107     /* error while spooling */
108     log_write(0, LOG_MAIN|LOG_PANIC,
109            "spam acl condition: error while creating mbox spool file");
110     return DEFER;
111     }
112
113   start = time(NULL);
114
115   /* socket does not start with '/' -> network socket */
116   if (*spamd_address_work != '/')
117     {
118     int num_servers = 0;
119     int current_server;
120     uschar *address = NULL;
121     uschar *spamd_address_list_ptr = spamd_address_work;
122     uschar address_buffer[256];
123     spamd_address_container * spamd_address_vector[32];
124
125     /* Check how many spamd servers we have
126        and register their addresses */
127     while ((address = string_nextinlist(&spamd_address_list_ptr, &sep,
128                                         address_buffer,
129                                         sizeof(address_buffer))) != NULL)
130       {
131
132       /* Potential memory leak as we never free the store. */
133       spamd_address_container *this_spamd =
134         (spamd_address_container *)store_get(sizeof(spamd_address_container));
135
136       /* grok spamd address and port */
137       if (sscanf(CS address, "%23s %u", this_spamd->tcp_addr, &(this_spamd->tcp_port)) != 2)
138         {
139         log_write(0, LOG_MAIN,
140           "spam acl condition: warning - invalid spamd address: '%s'", address);
141         continue;
142         }
143
144       spamd_address_vector[num_servers] = this_spamd;
145       if (++num_servers > 31)
146         break;
147       }
148
149     /* check if we have at least one server */
150     if (!num_servers)
151       {
152       log_write(0, LOG_MAIN|LOG_PANIC,
153          "spam acl condition: no useable spamd server addresses in spamd_address configuration option.");
154       (void)fclose(mbox_file);
155       return DEFER;
156       }
157
158     while ( num_servers > 0 )
159       {
160       int i;
161
162       /* Randomly pick a server to try */
163       current_server = random_number( num_servers );
164
165       debug_printf("trying server %s, port %u\n",
166                    spamd_address_vector[current_server]->tcp_addr,
167                    spamd_address_vector[current_server]->tcp_port);
168
169       /* contact a spamd */
170       if ( (spamd_sock = ip_socket(SOCK_STREAM, AF_INET)) < 0)
171         {
172         log_write(0, LOG_MAIN|LOG_PANIC,
173            "spam acl condition: error creating IP socket for spamd");
174         (void)fclose(mbox_file);
175         return DEFER;
176         }
177
178       if (ip_connect( spamd_sock,
179                       AF_INET,
180                       spamd_address_vector[current_server]->tcp_addr,
181                       spamd_address_vector[current_server]->tcp_port,
182                       5 ) > -1)
183         /* connection OK */
184         break;
185
186       log_write(0, LOG_MAIN|LOG_PANIC,
187          "spam acl condition: warning - spamd connection to %s, port %u failed: %s",
188          spamd_address_vector[current_server]->tcp_addr,
189          spamd_address_vector[current_server]->tcp_port,
190          strerror(errno));
191
192       (void)close(spamd_sock);
193
194       /* Remove the server from the list. XXX We should free the memory */
195       num_servers--;
196       for ( i = current_server; i < num_servers; i++ )
197         spamd_address_vector[i] = spamd_address_vector[i+1];
198       }
199
200     if ( num_servers == 0 )
201       {
202       log_write(0, LOG_MAIN|LOG_PANIC, "spam acl condition: all spamd servers failed");
203       (void)fclose(mbox_file);
204       return DEFER;
205       }
206     }
207   else
208     {
209     /* open the local socket */
210
211     if ((spamd_sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
212       {
213       log_write(0, LOG_MAIN|LOG_PANIC,
214                 "malware acl condition: spamd: unable to acquire socket (%s)",
215                 strerror(errno));
216       (void)fclose(mbox_file);
217       return DEFER;
218       }
219
220     server.sun_family = AF_UNIX;
221     Ustrcpy(server.sun_path, spamd_address_work);
222
223     if (connect(spamd_sock, (struct sockaddr *) &server, sizeof(struct sockaddr_un)) < 0)
224       {
225       log_write(0, LOG_MAIN|LOG_PANIC,
226                 "malware acl condition: spamd: unable to connect to UNIX socket %s (%s)",
227                 spamd_address_work, strerror(errno) );
228       (void)fclose(mbox_file);
229       (void)close(spamd_sock);
230       return DEFER;
231       }
232     }
233
234   if (spamd_sock == -1)
235     {
236     log_write(0, LOG_MAIN|LOG_PANIC,
237         "programming fault, spamd_sock unexpectedly unset");
238     (void)fclose(mbox_file);
239     (void)close(spamd_sock);
240     return DEFER;
241     }
242
243   /* now we are connected to spamd on spamd_sock */
244   (void)string_format(spamd_buffer,
245            sizeof(spamd_buffer),
246            "REPORT SPAMC/1.2\r\nUser: %s\r\nContent-length: %ld\r\n\r\n",
247            user_name,
248            mbox_size);
249
250   /* send our request */
251   if (send(spamd_sock, spamd_buffer, Ustrlen(spamd_buffer), 0) < 0)
252     {
253     (void)close(spamd_sock);
254     log_write(0, LOG_MAIN|LOG_PANIC,
255          "spam acl condition: spamd send failed: %s", strerror(errno));
256     (void)fclose(mbox_file);
257     (void)close(spamd_sock);
258     return DEFER;
259     }
260
261   /* now send the file */
262   /* spamd sometimes accepts conections but doesn't read data off
263    * the connection.  We make the file descriptor non-blocking so
264    * that the write will only write sufficient data without blocking
265    * and we poll the desciptor to make sure that we can write without
266    * blocking.  Short writes are gracefully handled and if the whole
267    * trasaction takes too long it is aborted.
268    * Note: poll() is not supported in OSX 10.2 and is reported to be
269    *       broken in more recent versions (up to 10.4).
270    */
271 #ifndef NO_POLL_H
272   pollfd.fd = spamd_sock;
273   pollfd.events = POLLOUT;
274 #endif
275   (void)fcntl(spamd_sock, F_SETFL, O_NONBLOCK);
276   do
277     {
278     read = fread(spamd_buffer,1,sizeof(spamd_buffer),mbox_file);
279     if (read > 0)
280       {
281       offset = 0;
282 again:
283 #ifndef NO_POLL_H
284       result = poll(&pollfd, 1, 1000);
285
286 /* Patch posted by Erik ? for OS X and applied by PH */
287 #else
288       select_tv.tv_sec = 1;
289       select_tv.tv_usec = 0;
290       FD_ZERO(&select_fd);
291       FD_SET(spamd_sock, &select_fd);
292       result = select(spamd_sock+1, NULL, &select_fd, NULL, &select_tv);
293 #endif
294 /* End Erik's patch */
295
296       if (result == -1 && errno == EINTR)
297         goto again;
298       else if (result < 1)
299         {
300         if (result == -1)
301           log_write(0, LOG_MAIN|LOG_PANIC,
302             "spam acl condition: %s on spamd socket", strerror(errno));
303         else
304           {
305           if (time(NULL) - start < SPAMD_TIMEOUT)
306             goto again;
307           log_write(0, LOG_MAIN|LOG_PANIC,
308             "spam acl condition: timed out writing spamd socket");
309           }
310         (void)close(spamd_sock);
311         (void)fclose(mbox_file);
312         return DEFER;
313         }
314
315       wrote = send(spamd_sock,spamd_buffer + offset,read - offset,0);
316       if (wrote == -1)
317         {
318         log_write(0, LOG_MAIN|LOG_PANIC,
319             "spam acl condition: %s on spamd socket", strerror(errno));
320         (void)close(spamd_sock);
321         (void)fclose(mbox_file);
322         return DEFER;
323         }
324       if (offset + wrote != read)
325         {
326         offset += wrote;
327         goto again;
328         }
329       }
330     }
331   while (!feof(mbox_file) && !ferror(mbox_file));
332
333   if (ferror(mbox_file))
334     {
335     log_write(0, LOG_MAIN|LOG_PANIC,
336       "spam acl condition: error reading spool file: %s", strerror(errno));
337     (void)close(spamd_sock);
338     (void)fclose(mbox_file);
339     return DEFER;
340     }
341
342   (void)fclose(mbox_file);
343
344   /* we're done sending, close socket for writing */
345   shutdown(spamd_sock,SHUT_WR);
346
347   /* read spamd response using what's left of the timeout.
348    */
349   memset(spamd_buffer, 0, sizeof(spamd_buffer));
350   offset = 0;
351   while ((i = ip_recv(spamd_sock,
352                      spamd_buffer + offset,
353                      sizeof(spamd_buffer) - offset - 1,
354                      SPAMD_TIMEOUT - time(NULL) + start)) > 0 )
355     offset += i;
356
357   /* error handling */
358   if (i <= 0 && errno != 0)
359     {
360     log_write(0, LOG_MAIN|LOG_PANIC,
361          "spam acl condition: error reading from spamd socket: %s", strerror(errno));
362     (void)close(spamd_sock);
363     return DEFER;
364     }
365
366   /* reading done */
367   (void)close(spamd_sock);
368
369   /* dig in the spamd output and put the report in a multiline header, if requested */
370   if (sscanf(CS spamd_buffer,
371               "SPAMD/%7s 0 EX_OK\r\nContent-length: %*u\r\n\r\n%lf/%lf\r\n%n",
372               spamd_version, &spamd_score, &spamd_threshold,
373               &spamd_report_offset) != 3)
374     {
375
376     /* try to fall back to pre-2.50 spamd output */
377     if (sscanf(CS spamd_buffer,
378                 "SPAMD/%7s 0 EX_OK\r\nSpam: %*s ; %lf / %lf\r\n\r\n%n",
379                 spamd_version, &spamd_score, &spamd_threshold,
380                 &spamd_report_offset) != 3 )
381       {
382       log_write(0, LOG_MAIN|LOG_PANIC,
383          "spam acl condition: cannot parse spamd output");
384       return DEFER;
385       }
386     }
387
388   /* Create report. Since this is a multiline string,
389   we must hack it into shape first */
390   p = &spamd_buffer[spamd_report_offset];
391   q = spam_report_buffer;
392   while (*p != '\0')
393     {
394     /* skip \r */
395     if (*p == '\r')
396       {
397       p++;
398       continue;
399       }
400     *q++ = *p;
401     if (*p++ == '\n')
402       {
403       /* add an extra space after the newline to ensure
404       that it is treated as a header continuation line */
405       *q++ = ' ';
406       }
407     }
408   /* NULL-terminate */
409   *q-- = '\0';
410   /* cut off trailing leftovers */
411   while (*q <= ' ')
412     *q-- = '\0';
413
414   spam_report = spam_report_buffer;
415
416   /* create spam bar */
417   spamd_score_char = spamd_score > 0 ? '+' : '-';
418   j = abs((int)(spamd_score));
419   i = 0;
420   if (j != 0)
421     while ((i < j) && (i <= MAX_SPAM_BAR_CHARS))
422        spam_bar_buffer[i++] = spamd_score_char;
423   else
424     {
425     spam_bar_buffer[0] = '/';
426     i = 1;
427     }
428   spam_bar_buffer[i] = '\0';
429   spam_bar = spam_bar_buffer;
430
431   /* create "float" spam score */
432   (void)string_format(spam_score_buffer, sizeof(spam_score_buffer),"%.1f", spamd_score);
433   spam_score = spam_score_buffer;
434
435   /* create "int" spam score */
436   j = (int)((spamd_score + 0.001)*10);
437   (void)string_format(spam_score_int_buffer, sizeof(spam_score_int_buffer), "%d", j);
438   spam_score_int = spam_score_int_buffer;
439
440   /* compare threshold against score */
441   if (spamd_score >= spamd_threshold)
442     {
443     /* spam as determined by user's threshold */
444     spam_rc = OK;
445     }
446   else
447     {
448     /* not spam */
449     spam_rc = FAIL;
450     }
451
452   /* remember expanded spamd_address if needed */
453   if (spamd_address_work != spamd_address)
454     prev_spamd_address_work = string_copy(spamd_address_work);
455
456   /* remember user name and "been here" for it */
457   Ustrcpy(prev_user_name, user_name);
458   spam_ok = 1;
459
460   if (override) /* always return OK, no matter what the score */
461     return OK;
462   else
463     return spam_rc;
464 }
465
466 #endif