Start
[exim.git] / src / src / transports / lmtp.c
CommitLineData
0756eb3c
PH
1/* $Cambridge: exim/src/src/transports/lmtp.c,v 1.1 2004/10/07 13:10:02 ph10 Exp $ */
2
3/*************************************************
4* Exim - an Internet mail transport agent *
5*************************************************/
6
7/* Copyright (c) University of Cambridge 1995 - 2004 */
8/* See the file NOTICE for conditions of use and distribution. */
9
10
11#include "../exim.h"
12#include "lmtp.h"
13
14#define PENDING_OK 256
15
16
17/* Options specific to the lmtp transport. They must be in alphabetic
18order (note that "_" comes before the lower case letters). Those starting
19with "*" are not settable by the user but are used by the option-reading
20software for alternative value types. Some options are stored in the transport
21instance block so as to be publicly visible; these are flagged with opt_public.
22*/
23
24optionlist lmtp_transport_options[] = {
25 { "batch_id", opt_stringptr | opt_public,
26 (void *)offsetof(transport_instance, batch_id) },
27 { "batch_max", opt_int | opt_public,
28 (void *)offsetof(transport_instance, batch_max) },
29 { "command", opt_stringptr,
30 (void *)offsetof(lmtp_transport_options_block, cmd) },
31 { "socket", opt_stringptr,
32 (void *)offsetof(lmtp_transport_options_block, skt) },
33 { "timeout", opt_time,
34 (void *)offsetof(lmtp_transport_options_block, timeout) }
35};
36
37/* Size of the options list. An extern variable has to be used so that its
38address can appear in the tables drtables.c. */
39
40int lmtp_transport_options_count =
41 sizeof(lmtp_transport_options)/sizeof(optionlist);
42
43/* Default private options block for the lmtp transport. */
44
45lmtp_transport_options_block lmtp_transport_option_defaults = {
46 NULL, /* cmd */
47 NULL, /* skt */
48 5*60, /* timeout */
49 0 /* options */
50};
51
52
53
54/*************************************************
55* Initialization entry point *
56*************************************************/
57
58/* Called for each instance, after its options have been read, to
59enable consistency checks to be done, or anything else that needs
60to be set up. */
61
62void
63lmtp_transport_init(transport_instance *tblock)
64{
65lmtp_transport_options_block *ob =
66 (lmtp_transport_options_block *)(tblock->options_block);
67
68/* Either the command field or the socket field must be set */
69
70if ((ob->cmd == NULL) == (ob->skt == NULL))
71 log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
72 "one (and only one) of command or socket must be set for the %s transport",
73 tblock->name);
74
75/* If a fixed uid field is set, then a gid field must also be set. */
76
77if (tblock->uid_set && !tblock->gid_set && tblock->expand_gid == NULL)
78 log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
79 "user set without group for the %s transport", tblock->name);
80
81/* Set up the bitwise options for transport_write_message from the various
82driver options. Only one of body_only and headers_only can be set. */
83
84ob->options |=
85 (tblock->body_only? topt_no_headers : 0) |
86 (tblock->headers_only? topt_no_body : 0) |
87 (tblock->return_path_add? topt_add_return_path : 0) |
88 (tblock->delivery_date_add? topt_add_delivery_date : 0) |
89 (tblock->envelope_to_add? topt_add_envelope_to : 0) |
90 topt_use_crlf | topt_end_dot;
91}
92
93
94/*************************************************
95* Check an LMTP response *
96*************************************************/
97
98/* This function is given an errno code and the LMTP response buffer to
99analyse. It sets an appropriate message and puts the first digit of the
100response code into the yield variable. If no response was actually read, a
101suitable digit is chosen.
102
103Arguments:
104 errno_value pointer to the errno value
105 more_errno from the top address for use with ERRNO_FILTER_FAIL
106 buffer the LMTP response buffer
107 yield where to put a one-digit LMTP response code
108 message where to put an errror message
109
110Returns: TRUE if a "QUIT" command should be sent, else FALSE
111*/
112
113static BOOL check_response(int *errno_value, int more_errno, uschar *buffer,
114 int *yield, uschar **message)
115{
116*yield = '4'; /* Default setting is to give a temporary error */
117
118/* Handle response timeout */
119
120if (*errno_value == ETIMEDOUT)
121 {
122 *message = string_sprintf("LMTP timeout after %s", big_buffer);
123 if (transport_count > 0)
124 *message = string_sprintf("%s (%d bytes written)", *message,
125 transport_count);
126 *errno_value = 0;
127 return FALSE;
128 }
129
130/* Handle malformed LMTP response */
131
132if (*errno_value == ERRNO_SMTPFORMAT)
133 {
134 *message = string_sprintf("Malformed LMTP response after %s: %s",
135 big_buffer, string_printing(buffer));
136 return FALSE;
137 }
138
139/* Handle a failed filter process error; can't send QUIT as we mustn't
140end the DATA. */
141
142if (*errno_value == ERRNO_FILTER_FAIL)
143 {
144 *message = string_sprintf("transport filter process failed (%d)", more_errno);
145 return FALSE;
146 }
147
148/* Handle a failed add_headers expansion; can't send QUIT as we mustn't
149end the DATA. */
150
151if (*errno_value == ERRNO_CHHEADER_FAIL)
152 {
153 *message =
154 string_sprintf("failed to expand headers_add or headers_remove: %s",
155 expand_string_message);
156 return FALSE;
157 }
158
159/* Handle failure to write a complete data block */
160
161if (*errno_value == ERRNO_WRITEINCOMPLETE)
162 {
163 *message = string_sprintf("failed to write a data block");
164 return FALSE;
165 }
166
167/* Handle error responses from the remote process. */
168
169if (buffer[0] != 0)
170 {
171 uschar *s = string_printing(buffer);
172 *message = string_sprintf("LMTP error after %s: %s", big_buffer, s);
173 *yield = buffer[0];
174 return TRUE;
175 }
176
177/* No data was read. If there is no errno, this must be the EOF (i.e.
178connection closed) case, which causes deferral. Otherwise, leave the errno
179value to be interpreted. In all cases, we have to assume the connection is now
180dead. */
181
182if (*errno_value == 0)
183 {
184 *errno_value = ERRNO_SMTPCLOSED;
185 *message = string_sprintf("LMTP connection closed after %s", big_buffer);
186 }
187
188return FALSE;
189}
190
191
192
193/*************************************************
194* Write LMTP command *
195*************************************************/
196
197/* The formatted command is left in big_buffer so that it can be reflected in
198any error message.
199
200Arguments:
201 fd the fd to write to
202 format a format, starting with one of
203 of HELO, MAIL FROM, RCPT TO, DATA, ".", or QUIT.
204 ... data for the format
205
206Returns: TRUE if successful, FALSE if not, with errno set
207*/
208
209static BOOL
210lmtp_write_command(int fd, char *format, ...)
211{
212int count, rc;
213va_list ap;
214va_start(ap, format);
215if (!string_vformat(big_buffer, big_buffer_size, CS format, ap))
216 {
217 errno = ERRNO_SMTPFORMAT;
218 return FALSE;
219 }
220va_end(ap);
221count = Ustrlen(big_buffer);
222DEBUG(D_transport|D_v) debug_printf(" LMTP>> %s", big_buffer);
223rc = write(fd, big_buffer, count);
224big_buffer[count-2] = 0; /* remove \r\n for debug and error message */
225if (rc > 0) return TRUE;
226DEBUG(D_transport) debug_printf("write failed: %s\n", strerror(errno));
227return FALSE;
228}
229
230
231
232
233/*************************************************
234* Read LMTP response *
235*************************************************/
236
237/* This function reads an LMTP response with a timeout, and returns the
238response in the given buffer. It also analyzes the first digit of the reply
239code and returns FALSE if it is not acceptable.
240
241FALSE is also returned after a reading error. In this case buffer[0] will be
242zero, and the error code will be in errno.
243
244Arguments:
245 f a file to read from
246 buffer where to put the response
247 size the size of the buffer
248 okdigit the expected first digit of the response
249 timeout the timeout to use
250
251Returns: TRUE if a valid, non-error response was received; else FALSE
252*/
253
254static BOOL
255lmtp_read_response(FILE *f, uschar *buffer, int size, int okdigit, int timeout)
256{
257int count;
258uschar *ptr = buffer;
259uschar *readptr = buffer;
260
261/* Ensure errno starts out zero */
262
263errno = 0;
264
265/* Loop for handling LMTP responses that do not all come in one line. */
266
267for (;;)
268 {
269 /* If buffer is too full, something has gone wrong. */
270
271 if (size < 10)
272 {
273 *readptr = 0;
274 errno = ERRNO_SMTPFORMAT;
275 return FALSE;
276 }
277
278 /* Loop to cover the read getting interrupted. */
279
280 for (;;)
281 {
282 char *rc;
283 int save_errno;
284
285 *readptr = 0; /* In case nothing gets read */
286 sigalrm_seen = FALSE;
287 alarm(timeout);
288 rc = Ufgets(readptr, size-1, f);
289 save_errno = errno;
290 alarm(0);
291 errno = save_errno;
292
293 if (rc != NULL) break; /* A line has been read */
294
295 /* Handle timeout; must do this first because it uses EINTR */
296
297 if (sigalrm_seen) errno = ETIMEDOUT;
298
299 /* If some other interrupt arrived, just retry. We presume this to be rare,
300 but it can happen (e.g. the SIGUSR1 signal sent by exiwhat causes
301 read() to exit). */
302
303 else if (errno == EINTR)
304 {
305 DEBUG(D_transport) debug_printf("EINTR while reading LMTP response\n");
306 continue;
307 }
308
309 /* Handle other errors, including EOF; ensure buffer is completely empty. */
310
311 buffer[0] = 0;
312 return FALSE;
313 }
314
315 /* Adjust size in case we have to read another line, and adjust the
316 count to be the length of the line we are about to inspect. */
317
318 count = Ustrlen(readptr);
319 size -= count;
320 count += readptr - ptr;
321
322 /* See if the final two characters in the buffer are \r\n. If not, we
323 have to read some more. At least, that is what we should do on a strict
324 interpretation of the RFC. But accept LF as well, as we do for SMTP. */
325
326 if (ptr[count-1] != '\n')
327 {
328 DEBUG(D_transport)
329 {
330 int i;
331 debug_printf("LMTP input line incomplete in one buffer:\n ");
332 for (i = 0; i < count; i++)
333 {
334 int c = (ptr[i]);
335 if (mac_isprint(c)) debug_printf("%c", c); else debug_printf("<%d>", c);
336 }
337 debug_printf("\n");
338 }
339 readptr = ptr + count;
340 continue;
341 }
342
343 /* Remove any whitespace at the end of the buffer. This gets rid of CR, LF
344 etc. at the end. Show it, if debugging, formatting multi-line responses. */
345
346 while (count > 0 && isspace(ptr[count-1])) count--;
347 ptr[count] = 0;
348
349 DEBUG(D_transport|D_v)
350 {
351 uschar *s = ptr;
352 uschar *t = ptr;
353 while (*t != 0)
354 {
355 while (*t != 0 && *t != '\n') t++;
356 debug_printf(" %s %*s\n", (s == ptr)? "LMTP<<" : " ",
357 (int)(t-s), s);
358 if (*t == 0) break;
359 s = t = t + 1;
360 }
361 }
362
363 /* Check the format of the response: it must start with three digits; if
364 these are followed by a space or end of line, the response is complete. If
365 they are followed by '-' this is a multi-line response and we must look for
366 another line until the final line is reached. The only use made of multi-line
367 responses is to pass them back as error messages. We therefore just
368 concatenate them all within the buffer, which should be large enough to
369 accept any reasonable number of lines. A multiline response may already
370 have been read in one go - hence the loop here. */
371
372 for(;;)
373 {
374 uschar *p;
375 if (count < 3 ||
376 !isdigit(ptr[0]) ||
377 !isdigit(ptr[1]) ||
378 !isdigit(ptr[2]) ||
379 (ptr[3] != '-' && ptr[3] != ' ' && ptr[3] != 0))
380 {
381 errno = ERRNO_SMTPFORMAT; /* format error */
382 return FALSE;
383 }
384
385 /* If a single-line response, exit the loop */
386
387 if (ptr[3] != '-') break;
388
389 /* For a multi-line response see if the next line is already read, and if
390 so, stay in this loop to check it. */
391
392 p = ptr + 3;
393 while (*(++p) != 0)
394 {
395 if (*p == '\n')
396 {
397 ptr = ++p;
398 break;
399 }
400 }
401 if (*p == 0) break; /* No more lines to check */
402 }
403
404 /* End of response. If the last of the lines we are looking at is the final
405 line, we are done. Otherwise more data has to be read. */
406
407 if (ptr[3] != '-') break;
408
409 /* Move the reading pointer upwards in the buffer and insert \n in case this
410 is an error message that subsequently gets printed. Set the scanning pointer
411 to the reading pointer position. */
412
413 ptr += count;
414 *ptr++ = '\n';
415 size--;
416 readptr = ptr;
417 }
418
419/* Return a value that depends on the LMTP return code. Ensure that errno is
420zero, because the caller of this function looks at errno when FALSE is
421returned, to distinguish between an unexpected return code and other errors
422such as timeouts, lost connections, etc. */
423
424errno = 0;
425return buffer[0] == okdigit;
426}
427
428
429
430
431
432
433/*************************************************
434* Main entry point *
435*************************************************/
436
437/* See local README for interface details. For setup-errors, this transport
438returns FALSE, indicating that the first address has the status for all; in
439normal cases it returns TRUE, indicating that each address has its own status
440set. */
441
442BOOL
443lmtp_transport_entry(
444 transport_instance *tblock, /* data for this instantiation */
445 address_item *addrlist) /* address(es) we are working on */
446{
447pid_t pid = 0;
448FILE *out;
449lmtp_transport_options_block *ob =
450 (lmtp_transport_options_block *)(tblock->options_block);
451struct sockaddr_un sockun; /* don't call this "sun" ! */
452int timeout = ob->timeout;
453int fd_in = -1, fd_out = -1;
454int code, save_errno;
455BOOL send_data;
456BOOL yield = FALSE;
457address_item *addr;
458uschar *sockname = NULL;
459uschar **argv;
460uschar buffer[256];
461
462DEBUG(D_transport) debug_printf("%s transport entered\n", tblock->name);
463
464/* Initialization ensures that either a command or a socket is specified, but
465not both. When a command is specified, call the common function for creating an
466argument list and expanding the items. */
467
468if (ob->cmd != NULL)
469 {
470 DEBUG(D_transport) debug_printf("using command %s\n", ob->cmd);
471 sprintf(CS buffer, "%.50s transport", tblock->name);
472 if (!transport_set_up_command(&argv, ob->cmd, TRUE, PANIC, addrlist, buffer,
473 NULL))
474 return FALSE;
475 }
476
477/* When a socket is specified, expand the string and create a socket. */
478
479else
480 {
481 DEBUG(D_transport) debug_printf("using socket %s\n", ob->skt);
482 sockname = expand_string(ob->skt);
483 if (sockname == NULL)
484 {
485 addrlist->message = string_sprintf("Expansion of \"%s\" (socket setting "
486 "for %s transport) failed: %s", ob->skt, tblock->name,
487 expand_string_message);
488 return FALSE;
489 }
490 if ((fd_in = fd_out = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
491 {
492 addrlist->message = string_sprintf(
493 "Failed to create socket %s for %s transport: %s",
494 ob->skt, tblock->name, strerror(errno));
495 return FALSE;
496 }
497 }
498
499/* If the -N option is set, can't do any more. Presume all has gone well. */
500
501if (dont_deliver)
502 {
503 DEBUG(D_transport)
504 debug_printf("*** delivery by %s transport bypassed by -N option",
505 tblock->name);
506 addrlist->transport_return = OK;
507 return FALSE;
508 }
509
510/* As this is a local transport, we are already running with the required
511uid/gid and current directory. Request that the new process be a process group
512leader, so we can kill it and all its children on an error. */
513
514if (ob->cmd != NULL)
515 {
516 if ((pid = child_open(argv, NULL, 0, &fd_in, &fd_out, TRUE)) < 0)
517 {
518 addrlist->message = string_sprintf(
519 "Failed to create child process for %s transport: %s", tblock->name,
520 strerror(errno));
521 return FALSE;
522 }
523 }
524
525/* For a socket, try to make the connection */
526
527else
528 {
529 sockun.sun_family = AF_UNIX;
530 sprintf(sockun.sun_path, "%.*s", (int)(sizeof(sockun.sun_path)-1), sockname);
531 if(connect(fd_out, (struct sockaddr *)(&sockun), sizeof(sockun)) == -1)
532 {
533 addrlist->message = string_sprintf(
534 "Failed to connect to socket %s for %s transport: %s",
535 sockun.sun_path, tblock->name, strerror(errno));
536 return FALSE;
537 }
538 }
539
540/* Make the output we are going to read into a file. */
541
542out = fdopen(fd_out, "rb");
543
544/* Now we must implement the LMTP protocol. It is like SMTP, except that after
545the end of the message, a return code for every accepted RCPT TO is sent. This
546allows for message+recipient checks after the message has been received. */
547
548/* First thing is to wait for an initial greeting. */
549
550Ustrcpy(big_buffer, "initial connection");
551if (!lmtp_read_response(out, buffer, sizeof(buffer), '2',
552 timeout)) goto RESPONSE_FAILED;
553
554/* Next, we send a LHLO command, and expect a positive response */
555
556if (!lmtp_write_command(fd_in, "%s %s\r\n", "LHLO",
557 primary_hostname)) goto WRITE_FAILED;
558
559if (!lmtp_read_response(out, buffer, sizeof(buffer), '2',
560 timeout)) goto RESPONSE_FAILED;
561
562/* Now the envelope sender */
563
564if (!lmtp_write_command(fd_in, "MAIL FROM:<%s>\r\n", return_path))
565 goto WRITE_FAILED;
566
567if (!lmtp_read_response(out, buffer, sizeof(buffer), '2', timeout))
568 goto RESPONSE_FAILED;
569
570/* Next, we hand over all the recipients. Some may be permanently or
571temporarily rejected; others may be accepted, for now. */
572
573send_data = FALSE;
574for (addr = addrlist; addr != NULL; addr = addr->next)
575 {
576 if (!lmtp_write_command(fd_in, "RCPT TO:<%s>\r\n",
577 transport_rcpt_address(addr, tblock->rcpt_include_affixes)))
578 goto WRITE_FAILED;
579 if (lmtp_read_response(out, buffer, sizeof(buffer), '2', timeout))
580 {
581 send_data = TRUE;
582 addr->transport_return = PENDING_OK;
583 }
584 else
585 {
586 if (errno != 0 || buffer[0] == 0) goto RESPONSE_FAILED;
587 addr->message = string_sprintf("LMTP error after %s: %s", big_buffer,
588 string_printing(buffer));
589 if (buffer[0] == '5') addr->transport_return = FAIL; else
590 {
591 int bincode = (buffer[1] - '0')*10 + buffer[2] - '0';
592 addr->basic_errno = ERRNO_RCPT4XX;
593 addr->more_errno |= bincode << 8;
594 }
595 }
596 }
597
598/* Now send the text of the message if there were any good recipients. */
599
600if (send_data)
601 {
602 BOOL ok;
603
604 if (!lmtp_write_command(fd_in, "DATA\r\n")) goto WRITE_FAILED;
605 if (!lmtp_read_response(out, buffer, sizeof(buffer), '3', timeout))
606 goto RESPONSE_FAILED;
607
608 sigalrm_seen = FALSE;
609 transport_write_timeout = timeout;
610 Ustrcpy(big_buffer, "sending data block"); /* For error messages */
611 DEBUG(D_transport|D_v)
612 debug_printf(" LMTP>> writing message and terminating \".\"\n");
613
614 transport_count = 0;
615 ok = transport_write_message(addrlist, fd_in, ob->options, 0,
616 tblock->add_headers, tblock->remove_headers, US".", US"..",
617 tblock->rewrite_rules, tblock->rewrite_existflags);
618
619 /* Failure can either be some kind of I/O disaster (including timeout),
620 or the failure of a transport filter or the expansion of added headers. */
621
622 if (!ok)
623 {
624 buffer[0] = 0; /* There hasn't been a response */
625 goto RESPONSE_FAILED;
626 }
627
628 Ustrcpy(big_buffer, "end of data"); /* For error messages */
629
630 /* We now expect a response for every address that was accepted above,
631 in the same order. For those that get a response, their status is fixed;
632 any that are accepted have been handed over, even if later responses crash -
633 at least, that's how I read RFC 2033. */
634
635 for (addr = addrlist; addr != NULL; addr = addr->next)
636 {
637 if (addr->transport_return != PENDING_OK) continue;
638
639 if (lmtp_read_response(out, buffer, sizeof(buffer), '2', timeout))
640 addr->transport_return = OK;
641
642 /* If the response has failed badly, use it for all the remaining pending
643 addresses and give up. */
644
645 else if (errno != 0 || buffer[0] == 0)
646 {
647 address_item *a;
648 save_errno = errno;
649 check_response(&save_errno, addr->more_errno, buffer, &code,
650 &(addr->message));
651 addr->transport_return = (code == '5')? FAIL : DEFER;
652 for (a = addr->next; a != NULL; a = a->next)
653 {
654 if (a->transport_return != PENDING_OK) continue;
655 a->basic_errno = addr->basic_errno;
656 a->message = addr->message;
657 a->transport_return = addr->transport_return;
658 }
659 break;
660 }
661
662 /* Otherwise, it's an LMTP error code return for one address */
663
664 else
665 {
666 addr->message = string_sprintf("LMTP error after %s: %s", big_buffer,
667 string_printing(buffer));
668 addr->transport_return = (buffer[0] == '5')? FAIL : DEFER;
669 }
670 }
671 }
672
673/* The message transaction has completed successfully - this doesn't mean that
674all the addresses have necessarily been transferred, but each has its status
675set, so we change the yield to TRUE. */
676
677yield = TRUE;
678(void) lmtp_write_command(fd_in, "QUIT\r\n");
679(void) lmtp_read_response(out, buffer, sizeof(buffer), '2', 1);
680
681goto RETURN;
682
683
684/* Come here if any call to read_response, other than a response after the data
685phase, failed. Put the error in the top address - this will be replicated
686because the yield is still FALSE. Analyse the error, and if if isn't too bad,
687send a QUIT command. Wait for the response with a short timeout, so we don't
688wind up this process before the far end has had time to read the QUIT. */
689
690RESPONSE_FAILED:
691
692save_errno = errno;
693addrlist->message = NULL;
694
695if (check_response(&save_errno, addrlist->more_errno,
696 buffer, &code, &(addrlist->message)))
697 {
698 (void) lmtp_write_command(fd_in, "QUIT\r\n");
699 (void) lmtp_read_response(out, buffer, sizeof(buffer), '2', 1);
700 }
701
702addrlist->transport_return = (code == '5')? FAIL : DEFER;
703if (code == '4' && save_errno > 0)
704 addrlist->message = string_sprintf("%s: %s", addrlist->message,
705 strerror(save_errno));
706goto KILL_AND_RETURN;
707
708/* Come here if there are errors during writing of a command or the message
709itself. This error will be applied to all the addresses. */
710
711WRITE_FAILED:
712
713addrlist->transport_return = PANIC;
714addrlist->basic_errno = errno;
715if (errno == ERRNO_CHHEADER_FAIL)
716 addrlist->message =
717 string_sprintf("Failed to expand headers_add or headers_remove: %s",
718 expand_string_message);
719else if (errno == ERRNO_FILTER_FAIL)
720 addrlist->message = string_sprintf("Filter process failure");
721else if (errno == ERRNO_WRITEINCOMPLETE)
722 addrlist->message = string_sprintf("Failed repeatedly to write data");
723else if (errno == ERRNO_SMTPFORMAT)
724 addrlist->message = US"overlong LMTP command generated";
725else
726 addrlist->message = string_sprintf("Error %d", errno);
727
728/* Come here after errors. Kill off the process. */
729
730KILL_AND_RETURN:
731
732if (pid > 0) killpg(pid, SIGKILL);
733
734/* Come here from all paths after the subprocess is created. Wait for the
735process, but with a timeout. */
736
737RETURN:
738
739(void)child_close(pid, timeout);
740
741if (fd_in >= 0) (void) close(fd_in);
742if (fd_out >= 0) (void) fclose(out);
743
744DEBUG(D_transport)
745 debug_printf("%s transport yields %d\n", tblock->name, yield);
746
747return yield;
748}
749
750/* End of transport/lmtp.c */