Applied signed/unsigned fixes. Need confirmation that this completely deals with...
[exim.git] / src / src / dcc.c
1 /* $Cambridge: exim/src/src/dcc.c,v 1.4 2009/11/11 10:08:01 nm4 Exp $ */
2
3 /*************************************************
4 *     Exim - an Internet mail transport agent    *
5 *************************************************/
6
7 /* Copyright (c) Wolfgang Breyha 2005-2009
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   FILE *data_file;
54   uschar *dcc_daemon_ip = US"";
55   uschar *dcc_default_ip_option = US"127.0.0.1";
56   uschar *dcc_ip_option = US"";
57   uschar *dcc_helo_option = US"localhost";
58   uschar *dcc_reject_message = US"Rejected by DCC";
59   uschar *xtra_hdrs = NULL;
60
61   /* from local_scan */
62   int i, j, k, c, retval, sockfd, servlen, resp, line;
63   unsigned int portnr;
64   struct sockaddr_un  serv_addr;
65   struct sockaddr_in  serv_addr_in;
66   struct hostent *ipaddress;
67   uschar sockpath[128];
68   uschar sockip[40], client_ip[40];
69   uschar opts[128];
70   uschar rcpt[128], from[128];
71   uschar sendbuf[4096];
72   uschar recvbuf[4096];
73   uschar xhdr[256];
74   uschar dcc_return_text[1024];
75   uschar mbox_path[1024];
76   uschar message_subdir[2];
77   struct header_line *dcchdr;
78   uschar *dcc_acl_options;
79   uschar dcc_acl_options_buffer[10];
80   uschar dcc_xtra_hdrs[1024];
81
82   /* grep 1st option */
83   if ((dcc_acl_options = string_nextinlist(&list, &sep,
84                                            dcc_acl_options_buffer,
85                                            sizeof(dcc_acl_options_buffer))) != NULL)
86   {
87     /* parse 1st option */
88     if ( (strcmpic(dcc_acl_options,US"false") == 0) ||
89          (Ustrcmp(dcc_acl_options,"0") == 0) ) {
90       /* explicitly no matching */
91       return FAIL;
92     };
93
94     /* special cases (match anything except empty) */
95     if ( (strcmpic(dcc_acl_options,US"true") == 0) ||
96          (Ustrcmp(dcc_acl_options,"*") == 0) ||
97          (Ustrcmp(dcc_acl_options,"1") == 0) ) {
98       dcc_acl_options = dcc_acl_options;
99     };
100   }
101   else {
102     /* empty means "don't match anything" */
103     return FAIL;
104   };
105
106   sep = 0;
107
108   /* if we scanned this message last time, just return */
109   if ( dcc_ok )
110       return dcc_rc;
111
112   /* open the spooled body */
113   message_subdir[1] = '\0';
114   for (i = 0; i < 2; i++) {
115     message_subdir[0] = (split_spool_directory == (i == 0))? message_id[5] : 0;
116     sprintf(CS mbox_path, "%s/input/%s/%s-D", spool_directory, message_subdir, message_id);
117     data_file = Ufopen(mbox_path,"rb");
118     if (data_file != NULL)
119       break;
120   };
121
122   if (data_file == NULL) {
123     /* error while spooling */
124     log_write(0, LOG_MAIN|LOG_PANIC,
125            "dcc acl condition: error while opening spool file");
126     return DEFER;
127   };
128
129   /* Initialize the variables */
130
131   bzero(sockip,sizeof(sockip));
132   if (dccifd_address) {
133     if (dccifd_address[0] == '/')
134       Ustrncpy(sockpath, dccifd_address, sizeof(sockpath));
135     else
136       if( sscanf(CS dccifd_address, "%s %u", sockip, &portnr) != 2) {
137         log_write(0, LOG_MAIN,
138           "dcc acl condition: warning - invalid dccifd address: '%s'", dccifd_address);
139         (void)fclose(data_file);
140         return DEFER;
141       }
142   }
143
144   /* opts is what we send as dccifd options - see man dccifd */
145   /* We don't support any other option than 'header' so just copy that */
146   bzero(opts,sizeof(opts));
147   Ustrncpy(opts, "header", sizeof(opts)-1);
148   Ustrncpy(client_ip, dcc_ip_option, sizeof(client_ip)-1);
149   /* If the dcc_client_ip is not provided use the
150    * sender_host_address or 127.0.0.1 if it is NULL */
151   DEBUG(D_acl)
152     debug_printf("my_ip_option = %s - client_ip = %s - sender_host_address = %s\n", dcc_ip_option, client_ip, sender_host_address);
153   if(!(Ustrcmp(client_ip, ""))){
154     /* Do we have a sender_host_address or is it NULL? */
155     if(sender_host_address){
156       Ustrncpy(client_ip, sender_host_address, sizeof(client_ip)-1);
157     } else {
158       /* sender_host_address is NULL which means it comes from localhost */
159       Ustrncpy(client_ip, dcc_default_ip_option, sizeof(client_ip)-1);
160     }
161   }
162   DEBUG(D_acl)
163     debug_printf("Client IP: %s\n", client_ip);
164   Ustrncpy(sockip, dcc_daemon_ip, sizeof(sockip)-1);
165   /* strncat(opts, my_request, strlen(my_request)); */
166   Ustrcat(opts, "\n");
167   Ustrncat(opts, client_ip, sizeof(opts)-Ustrlen(opts)-1);
168   Ustrncat(opts, "\nHELO ", sizeof(opts)-Ustrlen(opts)-1);
169   Ustrncat(opts, dcc_helo_option, sizeof(opts)-Ustrlen(opts)-2);
170   Ustrcat(opts, "\n");
171
172   /* initialize the other variables */
173   dcchdr = header_list;
174   /* we set the default return value to DEFER */
175   retval = DEFER;
176
177   bzero(sendbuf,sizeof(sendbuf));
178   bzero(xhdr,sizeof(xhdr));
179   bzero(rcpt,sizeof(rcpt));
180   bzero(from,sizeof(from));
181
182   /* send a null return path as "<>". */
183   if (Ustrlen(sender_address) > 0)
184     Ustrncpy(from, sender_address, sizeof(from));
185   else
186     Ustrncpy(from, "<>", sizeof(from));
187   Ustrncat(from, "\n", sizeof(from)-Ustrlen(from)-1);
188
189   /**************************************
190    * Now creating the socket connection *
191    **************************************/
192
193   /* If there is a dcc_daemon_ip, we use a tcp socket, otherwise a UNIX socket */
194   if(Ustrcmp(sockip, "")){
195     ipaddress = gethostbyname((char *)sockip);
196     bzero((char *) &serv_addr_in, sizeof(serv_addr_in));
197     serv_addr_in.sin_family = AF_INET;
198     bcopy((char *)ipaddress->h_addr, (char *)&serv_addr_in.sin_addr.s_addr, ipaddress->h_length);
199     serv_addr_in.sin_port = htons(portnr);
200     if ((sockfd = socket(AF_INET, SOCK_STREAM,0)) < 0){
201       DEBUG(D_acl)
202         debug_printf("Creating socket failed: %s\n", strerror(errno));
203       log_write(0,LOG_REJECT,"Creating socket failed: %s\n", strerror(errno));
204       /* if we cannot create the socket, defer the mail */
205       (void)fclose(data_file);
206       return retval;
207     }
208     /* Now connecting the socket (INET) */
209     if (connect(sockfd, (struct sockaddr *)&serv_addr_in, sizeof(serv_addr_in)) < 0){
210       DEBUG(D_acl)
211         debug_printf("Connecting socket failed: %s\n", strerror(errno));
212       log_write(0,LOG_REJECT,"Connecting socket failed: %s\n", strerror(errno));
213       /* if we cannot contact the socket, defer the mail */
214       (void)fclose(data_file);
215       return retval;
216     }
217   } else {
218     /* connecting to the dccifd UNIX socket */
219     bzero((char *)&serv_addr,sizeof(serv_addr));
220     serv_addr.sun_family = AF_UNIX;
221     Ustrcpy(serv_addr.sun_path, sockpath);
222     servlen = Ustrlen(serv_addr.sun_path) + sizeof(serv_addr.sun_family);
223     if ((sockfd = socket(AF_UNIX, SOCK_STREAM,0)) < 0){
224       DEBUG(D_acl)
225         debug_printf("Creating socket failed: %s\n", strerror(errno));
226       log_write(0,LOG_REJECT,"Creating socket failed: %s\n", strerror(errno));
227       /* if we cannot create the socket, defer the mail */
228       (void)fclose(data_file);
229       return retval;
230     }
231     /* Now connecting the socket (UNIX) */
232     if (connect(sockfd, (struct sockaddr *) &serv_addr, servlen) < 0){
233       DEBUG(D_acl)
234                             debug_printf("Connecting socket failed: %s\n", strerror(errno));
235       log_write(0,LOG_REJECT,"Connecting socket failed: %s\n", strerror(errno));
236       /* if we cannot contact the socket, defer the mail */
237       (void)fclose(data_file);
238       return retval;
239     }
240   }
241   /* the socket is open, now send the options to dccifd*/
242   DEBUG(D_acl)
243     debug_printf("\n---------------------------\nSocket opened; now sending input\n-----------------\n");
244   /* First, fill in the input buffer */
245   Ustrncpy(sendbuf, opts, sizeof(sendbuf));
246   Ustrncat(sendbuf, from, sizeof(sendbuf)-Ustrlen(sendbuf)-1);
247
248   DEBUG(D_acl)
249   {
250     debug_printf("opts = %s\nsender = %s\nrcpt count = %d\n", opts, from, recipients_count);
251     debug_printf("Sending options:\n****************************\n");
252   }
253
254   /* let's send each of the recipients to dccifd */
255   for (i = 0; i < recipients_count; i++){
256     DEBUG(D_acl)
257       debug_printf("recipient = %s\n",recipients_list[i].address);
258     if(Ustrlen(sendbuf) + Ustrlen(recipients_list[i].address) > sizeof(sendbuf))
259     {
260       DEBUG(D_acl)
261         debug_printf("Writing buffer: %s\n", sendbuf);
262       flushbuffer(sockfd, sendbuf);
263       bzero(sendbuf, sizeof(sendbuf));
264     }
265     Ustrncat(sendbuf, recipients_list[i].address, sizeof(sendbuf)-Ustrlen(sendbuf)-1);
266     Ustrncat(sendbuf, "\r\n", sizeof(sendbuf)-Ustrlen(sendbuf)-1);
267   }
268   /* send a blank line between options and message */
269   Ustrncat(sendbuf, "\n", sizeof(sendbuf)-Ustrlen(sendbuf)-1);
270   /* Now we send the input buffer */
271   DEBUG(D_acl)
272     debug_printf("%s\n****************************\n", sendbuf);
273   flushbuffer(sockfd, sendbuf);
274
275   /* now send the message */
276   /* Clear the input buffer */
277   bzero(sendbuf, sizeof(sendbuf));
278   /* First send the headers */
279   /* Now send the headers */
280   DEBUG(D_acl)
281     debug_printf("Sending headers:\n****************************\n");
282   Ustrncpy(sendbuf, dcchdr->text, sizeof(sendbuf)-2);
283   while((dcchdr=dcchdr->next)) {
284     if(dcchdr->slen > sizeof(sendbuf)-2) {
285       /* The size of the header is bigger than the size of
286        * the input buffer, so split it up in smaller parts. */
287        flushbuffer(sockfd, sendbuf);
288        bzero(sendbuf, sizeof(sendbuf));
289        j = 0;
290        while(j < dcchdr->slen)
291        {
292         for(i = 0; i < sizeof(sendbuf)-2; i++) {
293           sendbuf[i] = dcchdr->text[j];
294           j++;
295         }
296         flushbuffer(sockfd, sendbuf);
297         bzero(sendbuf, sizeof(sendbuf));
298        }
299     } else if(Ustrlen(sendbuf) + dcchdr->slen > sizeof(sendbuf)-2) {
300       flushbuffer(sockfd, sendbuf);
301       bzero(sendbuf, sizeof(sendbuf));
302       Ustrncpy(sendbuf, dcchdr->text, sizeof(sendbuf)-2);
303     } else {
304       Ustrncat(sendbuf, dcchdr->text, sizeof(sendbuf)-Ustrlen(sendbuf)-2);
305     }
306   }
307
308   /* a blank line separates header from body */
309   Ustrncat(sendbuf, "\n", sizeof(sendbuf)-Ustrlen(sendbuf)-1);
310   flushbuffer(sockfd, sendbuf);
311   DEBUG(D_acl)
312     debug_printf("\n****************************\n%s", sendbuf);
313
314   /* Clear the input buffer */
315   bzero(sendbuf, sizeof(sendbuf));
316
317   /* now send the body */
318   DEBUG(D_acl)
319     debug_printf("Writing body:\n****************************\n");
320   (void)fseek(data_file, SPOOL_DATA_START_OFFSET, SEEK_SET);
321   while((fread(sendbuf, 1, sizeof(sendbuf)-1, data_file)) > 0) {
322     flushbuffer(sockfd, sendbuf);
323     bzero(sendbuf, sizeof(sendbuf));
324   }
325   DEBUG(D_acl)
326     debug_printf("\n****************************\n");
327
328   /* shutdown() the socket */
329   if(shutdown(sockfd, 1) < 0){
330     DEBUG(D_acl)
331       debug_printf("Couldn't shutdown socket: %s\n", strerror(errno));
332     log_write(0,LOG_MAIN,"Couldn't shutdown socket: %s\n", strerror(errno));
333     /* If there is a problem with the shutdown()
334      * defer the mail. */
335     (void)fclose(data_file);
336     return retval;
337   }
338   DEBUG(D_acl)
339     debug_printf("\n-------------------------\nInput sent.\n-------------------------\n");
340
341     /********************************
342    * receiving output from dccifd *
343    ********************************/
344   DEBUG(D_acl)
345     debug_printf("\n-------------------------------------\nNow receiving output from server\n-----------------------------------\n");
346
347   /******************************************************************
348    * We should get 3 lines:                                         *
349    * 1/ First line is overall result: either 'A' for Accept,        *
350    *    'R' for Reject, 'S' for accept Some recipients or           *
351    *    'T' for a Temporary error.                                  *
352    * 2/ Second line contains the list of Accepted/Rejected          *
353    *    recipients in the form AARRA (A = accepted, R = rejected).  *
354    * 3/ Third line contains the X-DCC header.                       *
355    ******************************************************************/
356
357   line = 1;    /* we start at the first line of the output */
358   j = 0;       /* will be used as index for the recipients list */
359   k = 0;       /* initializing the index of the X-DCC header: xhdr[k] */
360
361   /* Let's read from the socket until there's nothing left to read */
362   bzero(recvbuf, sizeof(recvbuf));
363   while((resp = read(sockfd, recvbuf, sizeof(recvbuf)-1)) > 0) {
364     /* How much did we get from the socket */
365     c = Ustrlen(recvbuf) + 1;
366     DEBUG(D_acl)
367       debug_printf("Length of the output buffer is: %d\nOutput buffer is:\n------------\n%s\n-----------\n", c, recvbuf);
368
369     /* Now let's read each character and see what we've got */
370     for(i = 0; i < c; i++) {
371       /* First check if we reached the end of the line and
372        * then increment the line counter */
373       if(recvbuf[i] == '\n') {
374         line++;
375       }
376       else {
377         /* The first character of the first line is the
378          * overall response. If there's another character
379          * on that line it is not correct. */
380         if(line == 1) {
381           if(i == 0) {
382             /* Now get the value and set the
383              * return value accordingly */
384             if(recvbuf[i] == 'A') {
385               DEBUG(D_acl)
386                 debug_printf("Overall result = A\treturning OK\n");
387               Ustrcpy(dcc_return_text, "Mail accepted by DCC");
388               dcc_result = US"A";
389               retval = OK;
390             }
391             else if(recvbuf[i] == 'R') {
392               DEBUG(D_acl)
393                 debug_printf("Overall result = R\treturning FAIL\n");
394               dcc_result = US"R";
395               retval = FAIL;
396               if(sender_host_name) {
397                 log_write(0, LOG_MAIN, "H=%s [%s] F=<%s>: rejected by DCC", sender_host_name, sender_host_address, sender_address);
398               }
399               else {
400                 log_write(0, LOG_MAIN, "H=[%s] F=<%s>: rejected by DCC", sender_host_address, sender_address);
401               }
402               Ustrncpy(dcc_return_text, dcc_reject_message, Ustrlen(dcc_reject_message) + 1);
403             }
404             else if(recvbuf[i] == 'S') {
405               DEBUG(D_acl)
406                 debug_printf("Overall result  = S\treturning OK\n");
407               Ustrcpy(dcc_return_text, "Not all recipients accepted by DCC");
408               /* Since we're in an ACL we want a global result
409                * so we accept for all */
410               dcc_result = US"A";
411               retval = OK;
412             }
413             else if(recvbuf[i] == 'G') {
414               DEBUG(D_acl)
415                 debug_printf("Overall result  = G\treturning FAIL\n");
416               Ustrcpy(dcc_return_text, "Greylisted by DCC");
417               dcc_result = US"G";
418               retval = FAIL;
419             }
420             else if(recvbuf[i] == 'T') {
421               DEBUG(D_acl)
422                 debug_printf("Overall result = T\treturning DEFER\n");
423               retval = DEFER;
424               log_write(0,LOG_MAIN,"Temporary error with DCC: %s\n", recvbuf);
425               Ustrcpy(dcc_return_text, "Temporary error with DCC");
426               dcc_result = US"T";
427             }
428             else {
429               DEBUG(D_acl)
430                 debug_printf("Overall result = something else\treturning DEFER\n");
431               retval = DEFER;
432               log_write(0,LOG_MAIN,"Unknown DCC response: %s\n", recvbuf);
433               Ustrcpy(dcc_return_text, "Unknown DCC response");
434               dcc_result = US"T";
435             }
436           }
437           else {
438           /* We're on the first line but not on the first character,
439            * there must be something wrong. */
440             DEBUG(D_acl)
441               debug_printf("Line = %d but i = %d != 0  character is %c - This is wrong!\n", line, i, recvbuf[i]);
442               log_write(0,LOG_MAIN,"Wrong header from DCC, output is %s\n", recvbuf);
443           }
444         }
445         else if(line == 2) {
446           /* On the second line we get a list of
447            * answer for each recipient. We don't care about
448            * it because we're in an acl and so just take the
449            * global result. */
450         }
451         else if(line > 2) {
452           /* The third and following lines is the X-DCC header,
453            * so we store it in xhdr. */
454           /* check if we don't get more than what we can handle */
455           if(k < sizeof(xhdr)) { /* xhdr has a length of 120 */
456             xhdr[k] = recvbuf[i];
457             k++;
458           }
459           else {
460             DEBUG(D_acl)
461               debug_printf("We got more output than we can store in the X-DCC header. Truncating at 120 characters.\n");
462           }
463         }
464         else {
465           /* Wrong line number. There must be a problem with the output. */
466           DEBUG(D_acl)
467             debug_printf("Wrong line number in output. Line number is %d\n", line);
468         }
469       }
470     }
471     /* we reinitialize the output buffer before we read again */
472     bzero(recvbuf,sizeof(recvbuf));
473   }
474   /* We have read everything from the socket */
475
476   /* We need the terminate the X-DCC header with a '\n' character. This needs to be k-1
477    * for xhdr[k] contains '\0'. */
478   xhdr[k-1] = '\n';
479
480   /* Now let's sum up what we've got. */
481   DEBUG(D_acl)
482     debug_printf("\n--------------------------\nOverall result = %d\nX-DCC header: %sReturn message: %s\ndcc_result: %s\n", retval, xhdr, dcc_return_text, dcc_result);
483
484   /* We only add the X-DCC header if it starts with X-DCC */
485   if(!(Ustrncmp(xhdr, "X-DCC", 5))){
486     dcc_header = xhdr;
487     if(dcc_direct_add_header) {
488       header_add(' ' , "%s", xhdr);
489   /* since the MIME ACL already writes the .eml file to disk without DCC Header we've to erase it */
490       unspool_mbox();
491     }
492   }
493   else {
494     DEBUG(D_acl)
495       debug_printf("Wrong format of the X-DCC header: %s\n", xhdr);
496   }
497
498   /* check if we should add additional headers passed in acl_m_dcc_add_header */
499   if(dcc_direct_add_header) {
500     if (((xtra_hdrs = expand_string(US"$acl_m_dcc_add_header")) != NULL) && (xtra_hdrs[0] != '\0')) {
501       Ustrncpy(dcc_xtra_hdrs, xtra_hdrs, sizeof(dcc_xtra_hdrs) - 2);
502       if (dcc_xtra_hdrs[Ustrlen(dcc_xtra_hdrs)-1] != '\n')
503         Ustrcat(dcc_xtra_hdrs, "\n");
504       header_add(' ', "%s", dcc_xtra_hdrs);
505       DEBUG(D_acl)
506         debug_printf("adding additional headers in $acl_m_dcc_add_header: %s", dcc_xtra_hdrs);
507     }
508   }
509
510   dcc_ok = 1;
511   /* Now return to exim main process */
512   DEBUG(D_acl)
513     debug_printf("Before returning to exim main process:\nreturn_text = %s - retval = %d\ndcc_result = %s\n", dcc_return_text, retval, dcc_result);
514
515   (void)fclose(data_file);
516   return retval;
517 }
518
519 #endif