tidying: coverity issues
[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, 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   message_subdir[1] = '\0';
101   for (i = 0; i < 2; i++)
102     {
103     message_subdir[0] = (split_spool_directory == (i == 0))? message_id[5] : 0;
104     sprintf(CS mbox_path, "%s/input/%s/%s-D", spool_directory, message_subdir, message_id);
105     data_file = Ufopen(mbox_path,"rb");
106     if (data_file != NULL)
107       break;
108     }
109
110   if (data_file == NULL)
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, "\n");
158   Ustrncat(opts, client_ip, sizeof(opts)-Ustrlen(opts)-1);
159   Ustrncat(opts, "\nHELO ", sizeof(opts)-Ustrlen(opts)-1);
160   Ustrncat(opts, dcc_helo_option, sizeof(opts)-Ustrlen(opts)-2);
161   Ustrcat(opts, "\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, "<>", sizeof(from));
178   Ustrncat(from, "\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((char *)sockip);
187     bzero((char *) &serv_addr_in, sizeof(serv_addr_in));
188     serv_addr_in.sin_family = AF_INET;
189     bcopy((char *)ipaddress->h_addr, (char *)&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(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 (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, "\r\n", sizeof(sendbuf)-Ustrlen(sendbuf)-1);
257   }
258   /* send a blank line between options and message */
259   Ustrncat(sendbuf, "\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(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 seperates header from body */
299   Ustrncat(sendbuf, "\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(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       }
366       else {
367         /* The first character of the first line is the
368          * overall response. If there's another character
369          * on that line it is not correct. */
370         if(line == 1) {
371           if(i == 0) {
372             /* Now get the value and set the
373              * return value accordingly */
374             if(recvbuf[i] == 'A') {
375               DEBUG(D_acl)
376                 debug_printf("DCC: Overall result = A\treturning OK\n");
377               Ustrcpy(dcc_return_text, "Mail accepted by DCC");
378               dcc_result = US"A";
379               retval = OK;
380             }
381             else if(recvbuf[i] == 'R') {
382               DEBUG(D_acl)
383                 debug_printf("DCC: Overall result = R\treturning FAIL\n");
384               dcc_result = US"R";
385               retval = FAIL;
386               if(sender_host_name) {
387                 log_write(0, LOG_MAIN, "H=%s [%s] F=<%s>: rejected by DCC", sender_host_name, sender_host_address, sender_address);
388               }
389               else {
390                 log_write(0, LOG_MAIN, "H=[%s] F=<%s>: rejected by DCC", sender_host_address, sender_address);
391               }
392               Ustrncpy(dcc_return_text, dcc_reject_message, Ustrlen(dcc_reject_message) + 1);
393             }
394             else if(recvbuf[i] == 'S') {
395               DEBUG(D_acl)
396                 debug_printf("DCC: Overall result  = S\treturning OK\n");
397               Ustrcpy(dcc_return_text, "Not all recipients accepted by DCC");
398               /* Since we're in an ACL we want a global result
399                * so we accept for all */
400               dcc_result = US"A";
401               retval = OK;
402             }
403             else if(recvbuf[i] == 'G') {
404               DEBUG(D_acl)
405                 debug_printf("DCC: Overall result  = G\treturning FAIL\n");
406               Ustrcpy(dcc_return_text, "Greylisted by DCC");
407               dcc_result = US"G";
408               retval = FAIL;
409             }
410             else if(recvbuf[i] == 'T') {
411               DEBUG(D_acl)
412                 debug_printf("DCC: Overall result = T\treturning DEFER\n");
413               retval = DEFER;
414               log_write(0,LOG_MAIN,"Temporary error with DCC: %s\n", recvbuf);
415               Ustrcpy(dcc_return_text, "Temporary error with DCC");
416               dcc_result = US"T";
417             }
418             else {
419               DEBUG(D_acl)
420                 debug_printf("DCC: Overall result = something else\treturning DEFER\n");
421               retval = DEFER;
422               log_write(0,LOG_MAIN,"Unknown DCC response: %s\n", recvbuf);
423               Ustrcpy(dcc_return_text, "Unknown DCC response");
424               dcc_result = US"T";
425             }
426           }
427           else {
428             /* We're on the first line but not on the first character,
429              * there must be something wrong. */
430             DEBUG(D_acl) debug_printf("DCC: Line = %d but i = %d != 0"
431                 "  character is %c - This is wrong!\n", line, i, recvbuf[i]);
432             log_write(0,LOG_MAIN,"Wrong header from DCC, output is %s\n", recvbuf);
433           }
434         }
435         else if(line == 2) {
436           /* On the second line we get a list of
437            * answers for each recipient. We don't care about
438            * it because we're in an acl and take the
439            * global result. */
440         }
441         else if(line > 2) {
442           /* The third and following lines are the X-DCC header,
443            * so we store it in dcc_header_str. */
444           /* check if we don't get more than we can handle */
445           if(k < sizeof(dcc_header_str)) {
446             dcc_header_str[k] = recvbuf[i];
447             k++;
448           }
449           else {
450             DEBUG(D_acl) debug_printf("DCC: We got more output than we can store"
451                 " in the X-DCC header. Truncating at 120 characters.\n");
452           }
453         }
454         else {
455           /* Wrong line number. There must be a problem with the output. */
456           DEBUG(D_acl)
457             debug_printf("DCC: Wrong line number in output. Line number is %d\n", line);
458         }
459       }
460     }
461     /* we reinitialize the output buffer before we read again */
462     bzero(recvbuf,sizeof(recvbuf));
463   }
464   /* We have read everything from the socket */
465
466   /* We need to terminate the X-DCC header with a '\n' character. This needs to be k-1
467    * since dcc_header_str[k] contains '\0'. */
468   dcc_header_str[k-1] = '\n';
469
470   /* Now let's sum up what we've got. */
471   DEBUG(D_acl)
472     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);
473
474   /* We only add the X-DCC header if it starts with X-DCC */
475   if(!(Ustrncmp(dcc_header_str, "X-DCC", 5))){
476     dcc_header = dcc_header_str;
477     if(dcc_direct_add_header) {
478       header_add(' ' , "%s", dcc_header_str);
479   /* since the MIME ACL already writes the .eml file to disk without DCC Header we've to erase it */
480       unspool_mbox();
481     }
482   }
483   else {
484     DEBUG(D_acl)
485       debug_printf("DCC: Wrong format of the X-DCC header: %s\n", dcc_header_str);
486   }
487
488   /* check if we should add additional headers passed in acl_m_dcc_add_header */
489   if(dcc_direct_add_header) {
490     if (((xtra_hdrs = expand_string(US"$acl_m_dcc_add_header")) != NULL) && (xtra_hdrs[0] != '\0')) {
491       Ustrncpy(dcc_xtra_hdrs, xtra_hdrs, sizeof(dcc_xtra_hdrs) - 2);
492       if (dcc_xtra_hdrs[Ustrlen(dcc_xtra_hdrs)-1] != '\n')
493         Ustrcat(dcc_xtra_hdrs, "\n");
494       header_add(' ', "%s", dcc_xtra_hdrs);
495       DEBUG(D_acl)
496         debug_printf("DCC: adding additional headers in $acl_m_dcc_add_header: %s", dcc_xtra_hdrs);
497     }
498   }
499
500   dcc_ok = 1;
501   /* Now return to exim main process */
502   DEBUG(D_acl)
503     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);
504
505   (void)fclose(data_file);
506   dcc_rc = retval;
507   return dcc_rc;
508 }
509
510 #endif