Fix pointers to NOTICE
[exim.git] / src / src / dcc.c
1 /* $Cambridge: exim/src/src/dcc.c,v 1.2 2009/06/30 18:25:03 tom Exp $ */
2
3 /*************************************************
4 *     Exim - an Internet mail transport agent    *
5 *************************************************/
6
7 /* Copyright (c) Wolfgang Breyha 2005-2008
8  * Vienna University Computer Center
9  * wbreyha@gmx.net
10  * See the file NOTICE for conditions of use and distribution.
11  */
12
13 /* This patch is based on code from Tom Kistners exiscan (ACL integration) and
14  * the DCC local_scan patch from Christopher Bodenstein */
15
16 /* Code for calling dccifd. Called from acl.c. */
17
18 #include "exim.h"
19 #ifdef EXPERIMENTAL_DCC
20 #include "dcc.h"
21 #include "unistd.h"
22
23 uschar dcc_header_str[256];
24 uschar dcc_result_str[256];
25 int dcc_ok = 0;
26 int dcc_rc = 0;
27
28 /* This function takes a file descriptor and a buffer as input and
29  * returns either 0 for success or errno in case of error. */
30
31 int flushbuffer (int socket, uschar *buffer)
32  {
33   int retval, rsp;
34   rsp = write(socket, buffer, Ustrlen(buffer));
35   DEBUG(D_acl)
36     debug_printf("Result of the write() = %d\n", rsp);
37   if(rsp < 0)
38   {
39     DEBUG(D_acl)
40       debug_printf("Error writing buffer to socket: %s\n", strerror(errno));
41     retval = errno;
42   } else {
43     DEBUG(D_acl)
44       debug_printf("Wrote buffer to socket:\n%s\n", buffer);
45     retval = 0;
46   }
47   return retval;
48 }
49
50 int dcc_process(uschar **listptr) {
51   int sep = 0;
52   uschar *list = *listptr;
53   uschar *user_name;
54   uschar *body_begin;
55   uschar user_name_buffer[128];
56   unsigned long mbox_size;
57   FILE *data_file;
58   int dcc_sock;
59   uschar dcc_buffer[32600];
60   uschar *dcc_daemon_ip = US"";
61   int dcc_daemon_port = 6276;
62   uschar *dcc_request = US"header";
63   uschar *dcc_default_ip_option = US"127.0.0.1";
64   uschar *dcc_ip_option = US"";
65   uschar *dcc_helo_option = US"localhost";
66   uschar *dcc_reject_message = US"Rejected by DCC";
67
68   /* from local_scan */
69   int i, j, k, c, retval, sockfd, servlen, resp, rcpt_count, portnr, line;
70   struct sockaddr_un  serv_addr;
71   struct sockaddr_in  serv_addr_in;
72   struct hostent *ipaddress;
73   uschar sockpath[128];
74   uschar sockip[40], client_ip[40];
75   uschar opts[128];
76   uschar rcpt[128], from[128];
77   uschar sendbuf[4096];
78   uschar recvbuf[4096];
79   uschar xhdr[256];
80   uschar dcc_return_text[1024];
81   uschar mbox_path[1024];
82   uschar message_subdir[2];
83   struct header_line *dcchdr;
84   struct recipient_item *dcc_rcpt = recipients_list;
85   int some;
86   uschar *dcc_acl_options;
87   uschar dcc_acl_options_buffer[10];
88
89   int offset, result;
90   uschar *p,*q;
91   int override = 0;
92   time_t start;
93   struct sockaddr_un server;
94 #ifndef NO_POLL_H
95   struct pollfd pollfd;
96 #endif
97
98   /* stop compiler warning */
99   result = result;
100
101   /* grep 1st option */
102   if ((dcc_acl_options = string_nextinlist(&list, &sep,
103                                            dcc_acl_options_buffer,
104                                            sizeof(dcc_acl_options_buffer))) != NULL)
105   {
106     /* parse 1st option */
107     if ( (strcmpic(dcc_acl_options,US"false") == 0) ||
108          (Ustrcmp(dcc_acl_options,"0") == 0) ) {
109       /* explicitly no matching */
110       return FAIL;
111     };
112
113     /* special cases (match anything except empty) */
114     if ( (strcmpic(dcc_acl_options,US"true") == 0) ||
115          (Ustrcmp(dcc_acl_options,"*") == 0) ||
116          (Ustrcmp(dcc_acl_options,"1") == 0) ) {
117       dcc_acl_options = dcc_acl_options;
118     };
119   }
120   else {
121     /* empty means "don't match anything" */
122     return FAIL;
123   };
124
125   sep = 0;
126
127   /* if we scanned this message last time, just return */
128   if ( dcc_ok )
129       return dcc_rc;
130
131   /* open the spooled body */
132   message_subdir[1] = '\0';
133   for (i = 0; i < 2; i++) {
134     message_subdir[0] = (split_spool_directory == (i == 0))? message_id[5] : 0;
135     sprintf(CS mbox_path, "%s/input/%s/%s-D", spool_directory, message_subdir, message_id);
136     data_file = Ufopen(mbox_path,"rb");
137     if (data_file != NULL)
138       break;
139   };
140
141   if (data_file == NULL) {
142     /* error while spooling */
143     log_write(0, LOG_MAIN|LOG_PANIC,
144            "dcc acl condition: error while opening spool file");
145     return DEFER;
146   };
147
148   /* Initialize the variables */
149
150   bzero(sockip,sizeof(sockip));
151   if (dccifd_address) {
152     if (dccifd_address[0] == '/')
153       Ustrncpy(sockpath, dccifd_address, sizeof(sockpath));
154     else
155       if( sscanf(CS dccifd_address, "%s %u", sockip, portnr) != 2) {
156         log_write(0, LOG_MAIN,
157           "dcc acl condition: warning - invalid dccifd address: '%s'", dccifd_address);
158         (void)fclose(data_file);
159         return DEFER;
160       }
161   }
162
163   /* opts is what we send as dccifd options - see man dccifd */
164   /* We don't support any other option than 'header' so just copy that */
165   bzero(opts,sizeof(opts));
166   Ustrncpy(opts, "header", sizeof(opts)-1);
167   Ustrncpy(client_ip, dcc_ip_option, sizeof(client_ip)-1);
168   /* If the dcc_client_ip is not provided use the
169    * sender_host_address or 127.0.0.1 if it is NULL */
170   DEBUG(D_acl)
171     debug_printf("my_ip_option = %s - client_ip = %s - sender_host_address = %s\n", dcc_ip_option, client_ip, sender_host_address);
172   if(!(Ustrcmp(client_ip, ""))){
173     /* Do we have a sender_host_address or is it NULL? */
174     if(sender_host_address){
175       /* check if it is an ipv6 address */
176       if(Ustrchr(sender_host_address, ':')){
177         /* This is an IPv6 address
178          * For the moment we will not use it, but use 127.0.0.1 instead */
179         DEBUG(D_acl)
180           debug_printf("IPv6 address!\n");
181         Ustrncpy(client_ip, dcc_default_ip_option, sizeof(client_ip)-1);
182       } else {
183         Ustrncpy(client_ip, sender_host_address, sizeof(client_ip)-1);
184       }
185     } else {
186       /* sender_host_address is NULL which means it comes from localhost */
187       Ustrncpy(client_ip, dcc_default_ip_option, sizeof(client_ip)-1);
188     }
189   }
190   DEBUG(D_acl)
191     debug_printf("Client IP: %s\n", client_ip);
192   Ustrncpy(sockip, dcc_daemon_ip, sizeof(sockip)-1);
193   /* strncat(opts, my_request, strlen(my_request)); */
194   Ustrcat(opts, "\n");
195   Ustrncat(opts, client_ip, sizeof(opts)-Ustrlen(opts)-1);
196   Ustrncat(opts, "\nHELO ", sizeof(opts)-Ustrlen(opts)-1);
197   Ustrncat(opts, dcc_helo_option, sizeof(opts)-Ustrlen(opts)-2);
198   Ustrcat(opts, "\n");
199
200   /* initialize the other variables */
201   dcchdr = header_list;
202   rcpt_count = 0;
203   /* we set the default return value to DEFER */
204   retval = DEFER;
205
206   bzero(sendbuf,sizeof(sendbuf));
207   bzero(xhdr,sizeof(xhdr));
208   bzero(rcpt,sizeof(rcpt));
209   bzero(from,sizeof(from));
210
211   Ustrncpy(from, sender_address, sizeof(from));
212   Ustrncat(from, "\n", sizeof(from)-Ustrlen(from)-1);
213
214   /**************************************
215    * Now creating the socket connection *
216    **************************************/
217
218   /* If there is a dcc_daemon_ip, we use a tcp socket, otherwise a UNIX socket */
219   if(Ustrcmp(sockip, "")){
220     ipaddress = gethostbyname((char *)sockip);
221     bzero((char *) &serv_addr_in, sizeof(serv_addr_in));
222     serv_addr_in.sin_family = AF_INET;
223     bcopy((char *)ipaddress->h_addr, (char *)&serv_addr_in.sin_addr.s_addr, ipaddress->h_length);
224     serv_addr_in.sin_port = htons(portnr);
225     if ((sockfd = socket(AF_INET, SOCK_STREAM,0)) < 0){
226       DEBUG(D_acl)
227         debug_printf("Creating socket failed: %s\n", strerror(errno));
228       log_write(0,LOG_REJECT,"Creating socket failed: %s\n", strerror(errno));
229       /* if we cannot create the socket, defer the mail */
230       (void)fclose(data_file);
231       return retval;
232     }
233     /* Now connecting the socket (INET) */
234     if (connect(sockfd, (struct sockaddr *)&serv_addr_in, sizeof(serv_addr_in)) < 0){
235       DEBUG(D_acl)
236         debug_printf("Connecting socket failed: %s\n", strerror(errno));
237       log_write(0,LOG_REJECT,"Connecting socket failed: %s\n", strerror(errno));
238       /* if we cannot contact the socket, defer the mail */
239       (void)fclose(data_file);
240       return retval;
241     }
242   } else {
243     /* connecting to the dccifd UNIX socket */
244     bzero((char *)&serv_addr,sizeof(serv_addr));
245     serv_addr.sun_family = AF_UNIX;
246     Ustrcpy(serv_addr.sun_path, sockpath);
247     servlen = Ustrlen(serv_addr.sun_path) + sizeof(serv_addr.sun_family);
248     if ((sockfd = socket(AF_UNIX, SOCK_STREAM,0)) < 0){
249       DEBUG(D_acl)
250         debug_printf("Creating socket failed: %s\n", strerror(errno));
251       log_write(0,LOG_REJECT,"Creating socket failed: %s\n", strerror(errno));
252       /* if we cannot create the socket, defer the mail */
253       (void)fclose(data_file);
254       return retval;
255     }
256     /* Now connecting the socket (UNIX) */
257     if (connect(sockfd, (struct sockaddr *) &serv_addr, servlen) < 0){
258       DEBUG(D_acl)
259                             debug_printf("Connecting socket failed: %s\n", strerror(errno));
260       log_write(0,LOG_REJECT,"Connecting socket failed: %s\n", strerror(errno));
261       /* if we cannot contact the socket, defer the mail */
262       (void)fclose(data_file);
263       return retval;
264     }
265   }
266   /* the socket is open, now send the options to dccifd*/
267   DEBUG(D_acl)
268     debug_printf("\n---------------------------\nSocket opened; now sending input\n-----------------\n");
269   /* First, fill in the input buffer */
270   Ustrncpy(sendbuf, opts, sizeof(sendbuf));
271   Ustrncat(sendbuf, from, sizeof(sendbuf)-Ustrlen(sendbuf)-1);
272
273   DEBUG(D_acl)
274   {
275     debug_printf("opts = %s\nsender = %s\nrcpt count = %d\n", opts, from, recipients_count);
276     debug_printf("Sending options:\n****************************\n");
277   }
278
279   /* let's send each of the recipients to dccifd */
280   for (i = 0; i < recipients_count; i++){
281     DEBUG(D_acl)
282       debug_printf("recipient = %s\n",recipients_list[i].address);
283     if(Ustrlen(sendbuf) + Ustrlen(recipients_list[i].address) > sizeof(sendbuf))
284     {
285       DEBUG(D_acl)
286         debug_printf("Writing buffer: %s\n", sendbuf);
287       flushbuffer(sockfd, sendbuf);
288       bzero(sendbuf, sizeof(sendbuf));
289     }
290     Ustrncat(sendbuf, recipients_list[i].address, sizeof(sendbuf)-Ustrlen(sendbuf)-1);
291     Ustrncat(sendbuf, "\r\n", sizeof(sendbuf)-Ustrlen(sendbuf)-1);
292   }
293   /* send a blank line between options and message */
294   Ustrncat(sendbuf, "\n", sizeof(sendbuf)-Ustrlen(sendbuf)-1);
295   /* Now we send the input buffer */
296   DEBUG(D_acl)
297     debug_printf("%s\n****************************\n", sendbuf);
298   flushbuffer(sockfd, sendbuf);
299
300   /* now send the message */
301   /* Clear the input buffer */
302   bzero(sendbuf, sizeof(sendbuf));
303   /* First send the headers */
304   /* Now send the headers */
305   DEBUG(D_acl)
306     debug_printf("Sending headers:\n****************************\n");
307   Ustrncpy(sendbuf, dcchdr->text, sizeof(sendbuf)-2);
308   while((dcchdr=dcchdr->next)) {
309     if(dcchdr->slen > sizeof(sendbuf)-2) {
310       /* The size of the header is bigger than the size of
311        * the input buffer, so split it up in smaller parts. */
312        flushbuffer(sockfd, sendbuf);
313        bzero(sendbuf, sizeof(sendbuf));
314        j = 0;
315        while(j < dcchdr->slen)
316        {
317         for(i = 0; i < sizeof(sendbuf)-2; i++) {
318           sendbuf[i] = dcchdr->text[j];
319           j++;
320         }
321         flushbuffer(sockfd, sendbuf);
322         bzero(sendbuf, sizeof(sendbuf));
323        }
324     } else if(Ustrlen(sendbuf) + dcchdr->slen > sizeof(sendbuf)-2) {
325       flushbuffer(sockfd, sendbuf);
326       bzero(sendbuf, sizeof(sendbuf));
327       Ustrncpy(sendbuf, dcchdr->text, sizeof(sendbuf)-2);
328     } else {
329       Ustrncat(sendbuf, dcchdr->text, sizeof(sendbuf)-Ustrlen(sendbuf)-2);
330     }
331   }
332
333   /* a blank line separates header from body */
334   Ustrncat(sendbuf, "\n", sizeof(sendbuf)-Ustrlen(sendbuf)-1);
335   flushbuffer(sockfd, sendbuf);
336   DEBUG(D_acl)
337     debug_printf("\n****************************\n", sendbuf);
338
339   /* Clear the input buffer */
340   bzero(sendbuf, sizeof(sendbuf));
341
342   /* now send the body */
343   DEBUG(D_acl)
344     debug_printf("Writing body:\n****************************\n");
345   (void)fseek(data_file, SPOOL_DATA_START_OFFSET, SEEK_SET);
346   while((fread(sendbuf, 1, sizeof(sendbuf)-1, data_file)) > 0) {
347     flushbuffer(sockfd, sendbuf);
348     bzero(sendbuf, sizeof(sendbuf));
349   }
350   DEBUG(D_acl)
351     debug_printf("\n****************************\n");
352
353   /* shutdown() the socket */
354   if(shutdown(sockfd, 1) < 0){
355     DEBUG(D_acl)
356       debug_printf("Couldn't shutdown socket: %s\n", strerror(errno));
357     log_write(0,LOG_MAIN,"Couldn't shutdown socket: %s\n", strerror(errno));
358     /* If there is a problem with the shutdown()
359      * defer the mail. */
360     (void)fclose(data_file);
361     return retval;
362   }
363   DEBUG(D_acl)
364     debug_printf("\n-------------------------\nInput sent.\n-------------------------\n");
365
366     /********************************
367    * receiving output from dccifd *
368    ********************************/
369   DEBUG(D_acl)
370     debug_printf("\n-------------------------------------\nNow receiving output from server\n-----------------------------------\n");
371
372   /******************************************************************
373    * We should get 3 lines:                                         *
374    * 1/ First line is overall result: either 'A' for Accept,        *
375    *    'R' for Reject, 'S' for accept Some recipients or           *
376    *    'T' for a Temporary error.                                  *
377    * 2/ Second line contains the list of Accepted/Rejected          *
378    *    recipients in the form AARRA (A = accepted, R = rejected).  *
379    * 3/ Third line contains the X-DCC header.                       *
380    ******************************************************************/
381
382   line = 1;    /* we start at the first line of the output */
383   rcpt_count = 0; /* initializing the recipients counter */
384   j = 0;       /* will be used as index for the recipients list */
385   k = 0;       /* initializing the index of the X-DCC header: xhdr[k] */
386   some = 0;
387
388   /* Let's read from the socket until there's nothing left to read */
389   bzero(recvbuf, sizeof(recvbuf));
390   while(resp = read(sockfd, recvbuf, sizeof(recvbuf)-1) > 0) {
391     /* How much did we get from the socket */
392     c = Ustrlen(recvbuf) + 1;
393     DEBUG(D_acl)
394       debug_printf("Length of the output buffer is: %d\nOutput buffer is:\n------------\n%s\n-----------\n", c, recvbuf);
395
396     /* Now let's read each character and see what we've got */
397     for(i = 0; i < c; i++) {
398       /* First check if we reached the end of the line and
399        * then increment the line counter */
400       if(recvbuf[i] == '\n') {
401         line++;
402       }
403       else {
404         /* The first character of the first line is the
405          * overall response. If there's another character
406          * on that line it is not correct. */
407         if(line == 1) {
408           if(i == 0) {
409             /* Now get the value and set the
410              * return value accordingly */
411             if(recvbuf[i] == 'A') {
412               DEBUG(D_acl)
413                 debug_printf("Overall result = A\treturning OK\n");
414               Ustrcpy(dcc_return_text, "Mail accepted by DCC");
415               retval = OK;
416             }
417             else if(recvbuf[i] == 'R') {
418               DEBUG(D_acl)
419                 debug_printf("Overall result = R\treturning FAIL\n");
420               retval = FAIL;
421               if(sender_host_name) {
422                 log_write(0, LOG_MAIN, "H=%s [%s] F=<%s>: rejected by DCC", sender_host_name, sender_host_address, sender_address);
423               }
424               else {
425                 log_write(0, LOG_MAIN, "H=[%s] F=<%s>: rejected by DCC", sender_host_address, sender_address);
426               }
427               Ustrncpy(dcc_return_text, dcc_reject_message, Ustrlen(dcc_reject_message) + 1);
428             }
429             else if(recvbuf[i] == 'S') {
430               DEBUG(D_acl)
431                 debug_printf("Overall result  = S\treturning OK\n");
432               Ustrcpy(dcc_return_text, "Not all recipients accepted by DCC");
433               some = 1;
434               retval = OK;
435             }
436             else if(recvbuf[i] == 'G') {
437               DEBUG(D_acl)
438                 debug_printf("Overall result  = G\treturning FAIL\n");
439               Ustrcpy(dcc_return_text, "Greylisted by DCC");
440               retval = DEFER;
441             }
442             else if(recvbuf[i] == 'T') {
443               DEBUG(D_acl)
444                 debug_printf("Overall result = T\treturning DEFER\n");
445               retval = DEFER;
446               log_write(0,LOG_MAIN,"Temporary error with DCC: %s\n", recvbuf);
447               Ustrcpy(dcc_return_text, "Temporary error with DCC");
448             }
449             else {
450               DEBUG(D_acl)
451                 debug_printf("Overall result = something else\treturning DEFER\n");
452               retval = DEFER;
453               log_write(0,LOG_MAIN,"Unknown DCC response: %s\n", recvbuf);
454               Ustrcpy(dcc_return_text, "Unknown DCC response");
455             }
456           }
457           else {
458           /* We're on the first line but not on the first character,
459            * there must be something wrong. */
460             DEBUG(D_acl)
461               debug_printf("Line = %d but i = %d != 0  character is %c - This is wrong!\n", line, i, recvbuf[i]);
462               log_write(0,LOG_MAIN,"Wrong header from DCC, output is %s\n", recvbuf);
463           }
464         }
465         else if(line == 2) {
466           /* On the second line we get a list of
467            * answer for each recipient */
468            /* We only need to copy the list of recipients if we
469             * accept the mail i.e. if retval is LOCAL_SCAN_ACCEPT */
470 // I don't care about results "SOME" since we're in the DATA stage. So we've a global result
471           if(some) {
472             if(j > recipients_count - 1) {
473               DEBUG(D_acl)
474                 debug_printf("More recipients returned than sent!\nSent %d recipients, got %d in return.\n", recipients_count, j);
475             }
476             else {
477               if(recvbuf[i] == 'A') {
478                 DEBUG(D_acl)
479                   debug_printf("Accepted recipient: %c - %s\n", recvbuf[i], recipients_list[j].address);
480 //                Ustrcpy(dcc_rcpt[rcpt_count].address, recipients_list[j].address);
481                 rcpt_count++;
482               }
483               else {
484                 DEBUG(D_acl)
485                   debug_printf("Rejected recipient: %c - %s\n", recvbuf[i], recipients_list[j].address);
486               }
487               j++;
488             }
489           }
490           else {
491             DEBUG(D_acl)
492               debug_printf("result was not SOME, so we take the overall result\n");
493           }
494         }
495         else if(line > 2) {
496           /* The third and following lines is the X-DCC header,
497            * so we store it in xhdr. */
498           /* check if we don't get more than what we can handle */
499           if(k < sizeof(xhdr)) { /* xhdr has a length of 120 */
500 //            DEBUG(D_acl)
501 //              debug_printf("Writing X-DCC header: k = %d recvbuf[%d] = %c\n", k, i, recvbuf[i]);
502             xhdr[k] = recvbuf[i];
503             k++;
504           }
505           else {
506             DEBUG(D_acl)
507               debug_printf("We got more output than we can store in the X-DCC header. Truncating at 120 characters.\n");
508           }
509         }
510         else {
511           /* Wrong line number. There must be a problem with the output. */
512           DEBUG(D_acl)
513             debug_printf("Wrong line number in output. Line number is %d\n", line);
514         }
515       }
516     }
517     /* we reinitialize the output buffer before we read again */
518     bzero(recvbuf,sizeof(recvbuf));
519   }
520   /* We have read everything from the socket */
521
522   /* We need the terminate the X-DCC header with a '\n' character. This needs to be k-1
523    * for xhdr[k] contains '\0'. */
524   xhdr[k-1] = '\n';
525
526   /* Now let's sum up what we've got. */
527   DEBUG(D_acl)
528     debug_printf("\n--------------------------\nOverall result = %d\nNumber of recipients accepted: %d\nX-DCC header: %s\nReturn message: %s\n", retval, rcpt_count, xhdr, dcc_return_text);
529
530   /* If some recipients were rejected, then rcpt_count is
531    * less than the original recipients_count.
532    * Then reconstruct the recipients list for those accepted
533    * recipients only. */
534   if((rcpt_count == 0) & (retval == OK)) { /* There should be at least 1 recipient; but who knows... */
535     DEBUG(D_acl)
536       debug_printf("List of accepted recipients is 0!\n");
537     retval = FAIL;
538   }
539   else {
540 /*  if(rcpt_count < recipients_count) {
541     recipients_count=0;
542     for(i=0; i < rcpt_count; i++){
543       DEBUG(D_acl)
544         debug_printf("Adding the new recipient: %s\n", dcc_rcpt[i].address);
545       receive_add_recipient(dcc_rcpt[i].address, -1);
546     } */
547     retval = OK;
548   }
549
550   /* We only add the X-DCC header if it starts with X-DCC */
551   if(!(Ustrncmp(xhdr, "X-DCC", 5))){
552     dcc_header = xhdr;
553     if(dcc_direct_add_header) {
554       header_add(' ' , "%s", xhdr);
555   /* since the MIME ACL already writes the .eml file to disk without DCC Header we've to earase it */
556       unspool_mbox();
557     }
558   }
559   else {
560     DEBUG(D_acl)
561       debug_printf("Wrong format of the X-DCC header: %s\n", xhdr);
562   }
563
564   dcc_ok = 1;
565   /* Now return to exim main process */
566   DEBUG(D_acl)
567     debug_printf("Before returning to exim main process:\nreturn_text = %s - retval = %d\n", dcc_return_text, retval);
568
569   (void)fclose(data_file);
570   return retval;
571 }
572
573 #endif