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