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