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