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