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