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