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