1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2015 */
6 /* See the file NOTICE for conditions of use and distribution. */
12 #define PENDING_OK 256
15 /* Options specific to the lmtp transport. They must be in alphabetic
16 order (note that "_" comes before the lower case letters). Those starting
17 with "*" are not settable by the user but are used by the option-reading
18 software for alternative value types. Some options are stored in the transport
19 instance block so as to be publicly visible; these are flagged with opt_public.
22 optionlist lmtp_transport_options[] = {
23 { "batch_id", opt_stringptr | opt_public,
24 (void *)offsetof(transport_instance, batch_id) },
25 { "batch_max", opt_int | opt_public,
26 (void *)offsetof(transport_instance, batch_max) },
27 { "command", opt_stringptr,
28 (void *)offsetof(lmtp_transport_options_block, cmd) },
29 { "ignore_quota", opt_bool,
30 (void *)offsetof(lmtp_transport_options_block, ignore_quota) },
31 { "socket", opt_stringptr,
32 (void *)offsetof(lmtp_transport_options_block, skt) },
33 { "timeout", opt_time,
34 (void *)offsetof(lmtp_transport_options_block, timeout) }
37 /* Size of the options list. An extern variable has to be used so that its
38 address can appear in the tables drtables.c. */
40 int lmtp_transport_options_count =
41 sizeof(lmtp_transport_options)/sizeof(optionlist);
43 /* Default private options block for the lmtp transport. */
45 lmtp_transport_options_block lmtp_transport_option_defaults = {
50 FALSE /* ignore_quota */
55 /*************************************************
56 * Initialization entry point *
57 *************************************************/
59 /* Called for each instance, after its options have been read, to
60 enable consistency checks to be done, or anything else that needs
64 lmtp_transport_init(transport_instance *tblock)
66 lmtp_transport_options_block *ob =
67 (lmtp_transport_options_block *)(tblock->options_block);
69 /* Either the command field or the socket field must be set */
71 if ((ob->cmd == NULL) == (ob->skt == NULL))
72 log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
73 "one (and only one) of command or socket must be set for the %s transport",
76 /* If a fixed uid field is set, then a gid field must also be set. */
78 if (tblock->uid_set && !tblock->gid_set && tblock->expand_gid == NULL)
79 log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
80 "user set without group for the %s transport", tblock->name);
82 /* Set up the bitwise options for transport_write_message from the various
83 driver options. Only one of body_only and headers_only can be set. */
86 (tblock->body_only? topt_no_headers : 0) |
87 (tblock->headers_only? topt_no_body : 0) |
88 (tblock->return_path_add? topt_add_return_path : 0) |
89 (tblock->delivery_date_add? topt_add_delivery_date : 0) |
90 (tblock->envelope_to_add? topt_add_envelope_to : 0) |
91 topt_use_crlf | topt_end_dot;
95 /*************************************************
96 * Check an LMTP response *
97 *************************************************/
99 /* This function is given an errno code and the LMTP response buffer to
100 analyse. It sets an appropriate message and puts the first digit of the
101 response code into the yield variable. If no response was actually read, a
102 suitable digit is chosen.
105 errno_value pointer to the errno value
106 more_errno from the top address for use with ERRNO_FILTER_FAIL
107 buffer the LMTP response buffer
108 yield where to put a one-digit LMTP response code
109 message where to put an errror message
111 Returns: TRUE if a "QUIT" command should be sent, else FALSE
114 static BOOL check_response(int *errno_value, int more_errno, uschar *buffer,
115 int *yield, uschar **message)
117 *yield = '4'; /* Default setting is to give a temporary error */
119 /* Handle response timeout */
121 if (*errno_value == ETIMEDOUT)
123 *message = string_sprintf("LMTP timeout after %s", big_buffer);
124 if (transport_count > 0)
125 *message = string_sprintf("%s (%d bytes written)", *message,
131 /* Handle malformed LMTP response */
133 if (*errno_value == ERRNO_SMTPFORMAT)
135 *message = string_sprintf("Malformed LMTP response after %s: %s",
136 big_buffer, string_printing(buffer));
140 /* Handle a failed filter process error; can't send QUIT as we mustn't
143 if (*errno_value == ERRNO_FILTER_FAIL)
145 *message = string_sprintf("transport filter process failed (%d)%s",
147 (more_errno == EX_EXECFAILED)? ": unable to execute command" : "");
151 /* Handle a failed add_headers expansion; can't send QUIT as we mustn't
154 if (*errno_value == ERRNO_CHHEADER_FAIL)
157 string_sprintf("failed to expand headers_add or headers_remove: %s",
158 expand_string_message);
162 /* Handle failure to write a complete data block */
164 if (*errno_value == ERRNO_WRITEINCOMPLETE)
166 *message = string_sprintf("failed to write a data block");
170 /* Handle error responses from the remote process. */
174 const uschar *s = string_printing(buffer);
175 *message = string_sprintf("LMTP error after %s: %s", big_buffer, s);
180 /* No data was read. If there is no errno, this must be the EOF (i.e.
181 connection closed) case, which causes deferral. Otherwise, leave the errno
182 value to be interpreted. In all cases, we have to assume the connection is now
185 if (*errno_value == 0)
187 *errno_value = ERRNO_SMTPCLOSED;
188 *message = string_sprintf("LMTP connection closed after %s", big_buffer);
196 /*************************************************
197 * Write LMTP command *
198 *************************************************/
200 /* The formatted command is left in big_buffer so that it can be reflected in
204 fd the fd to write to
205 format a format, starting with one of
206 of HELO, MAIL FROM, RCPT TO, DATA, ".", or QUIT.
207 ... data for the format
209 Returns: TRUE if successful, FALSE if not, with errno set
213 lmtp_write_command(int fd, const char *format, ...)
217 va_start(ap, format);
218 if (!string_vformat(big_buffer, big_buffer_size, CS format, ap))
220 errno = ERRNO_SMTPFORMAT;
224 count = Ustrlen(big_buffer);
225 DEBUG(D_transport|D_v) debug_printf(" LMTP>> %s", big_buffer);
226 rc = write(fd, big_buffer, count);
227 big_buffer[count-2] = 0; /* remove \r\n for debug and error message */
228 if (rc > 0) return TRUE;
229 DEBUG(D_transport) debug_printf("write failed: %s\n", strerror(errno));
236 /*************************************************
237 * Read LMTP response *
238 *************************************************/
240 /* This function reads an LMTP response with a timeout, and returns the
241 response in the given buffer. It also analyzes the first digit of the reply
242 code and returns FALSE if it is not acceptable.
244 FALSE is also returned after a reading error. In this case buffer[0] will be
245 zero, and the error code will be in errno.
248 f a file to read from
249 buffer where to put the response
250 size the size of the buffer
251 okdigit the expected first digit of the response
252 timeout the timeout to use
254 Returns: TRUE if a valid, non-error response was received; else FALSE
258 lmtp_read_response(FILE *f, uschar *buffer, int size, int okdigit, int timeout)
261 uschar *ptr = buffer;
262 uschar *readptr = buffer;
264 /* Ensure errno starts out zero */
268 /* Loop for handling LMTP responses that do not all come in one line. */
272 /* If buffer is too full, something has gone wrong. */
277 errno = ERRNO_SMTPFORMAT;
281 /* Loop to cover the read getting interrupted. */
288 *readptr = 0; /* In case nothing gets read */
289 sigalrm_seen = FALSE;
291 rc = Ufgets(readptr, size-1, f);
296 if (rc != NULL) break; /* A line has been read */
298 /* Handle timeout; must do this first because it uses EINTR */
300 if (sigalrm_seen) errno = ETIMEDOUT;
302 /* If some other interrupt arrived, just retry. We presume this to be rare,
303 but it can happen (e.g. the SIGUSR1 signal sent by exiwhat causes
306 else if (errno == EINTR)
308 DEBUG(D_transport) debug_printf("EINTR while reading LMTP response\n");
312 /* Handle other errors, including EOF; ensure buffer is completely empty. */
318 /* Adjust size in case we have to read another line, and adjust the
319 count to be the length of the line we are about to inspect. */
321 count = Ustrlen(readptr);
323 count += readptr - ptr;
325 /* See if the final two characters in the buffer are \r\n. If not, we
326 have to read some more. At least, that is what we should do on a strict
327 interpretation of the RFC. But accept LF as well, as we do for SMTP. */
329 if (ptr[count-1] != '\n')
334 debug_printf("LMTP input line incomplete in one buffer:\n ");
335 for (i = 0; i < count; i++)
338 if (mac_isprint(c)) debug_printf("%c", c); else debug_printf("<%d>", c);
342 readptr = ptr + count;
346 /* Remove any whitespace at the end of the buffer. This gets rid of CR, LF
347 etc. at the end. Show it, if debugging, formatting multi-line responses. */
349 while (count > 0 && isspace(ptr[count-1])) count--;
352 DEBUG(D_transport|D_v)
358 while (*t != 0 && *t != '\n') t++;
359 debug_printf(" %s %*s\n", (s == ptr)? "LMTP<<" : " ",
366 /* Check the format of the response: it must start with three digits; if
367 these are followed by a space or end of line, the response is complete. If
368 they are followed by '-' this is a multi-line response and we must look for
369 another line until the final line is reached. The only use made of multi-line
370 responses is to pass them back as error messages. We therefore just
371 concatenate them all within the buffer, which should be large enough to
372 accept any reasonable number of lines. A multiline response may already
373 have been read in one go - hence the loop here. */
382 (ptr[3] != '-' && ptr[3] != ' ' && ptr[3] != 0))
384 errno = ERRNO_SMTPFORMAT; /* format error */
388 /* If a single-line response, exit the loop */
390 if (ptr[3] != '-') break;
392 /* For a multi-line response see if the next line is already read, and if
393 so, stay in this loop to check it. */
404 if (*p == 0) break; /* No more lines to check */
407 /* End of response. If the last of the lines we are looking at is the final
408 line, we are done. Otherwise more data has to be read. */
410 if (ptr[3] != '-') break;
412 /* Move the reading pointer upwards in the buffer and insert \n in case this
413 is an error message that subsequently gets printed. Set the scanning pointer
414 to the reading pointer position. */
422 /* Return a value that depends on the LMTP return code. Ensure that errno is
423 zero, because the caller of this function looks at errno when FALSE is
424 returned, to distinguish between an unexpected return code and other errors
425 such as timeouts, lost connections, etc. */
428 return buffer[0] == okdigit;
436 /*************************************************
438 *************************************************/
440 /* See local README for interface details. For setup-errors, this transport
441 returns FALSE, indicating that the first address has the status for all; in
442 normal cases it returns TRUE, indicating that each address has its own status
446 lmtp_transport_entry(
447 transport_instance *tblock, /* data for this instantiation */
448 address_item *addrlist) /* address(es) we are working on */
452 lmtp_transport_options_block *ob =
453 (lmtp_transport_options_block *)(tblock->options_block);
454 struct sockaddr_un sockun; /* don't call this "sun" ! */
455 int timeout = ob->timeout;
456 int fd_in = -1, fd_out = -1;
457 int code, save_errno;
461 uschar *igquotstr = US"";
462 uschar *sockname = NULL;
466 DEBUG(D_transport) debug_printf("%s transport entered\n", tblock->name);
468 /* Initialization ensures that either a command or a socket is specified, but
469 not both. When a command is specified, call the common function for creating an
470 argument list and expanding the items. */
474 DEBUG(D_transport) debug_printf("using command %s\n", ob->cmd);
475 sprintf(CS buffer, "%.50s transport", tblock->name);
476 if (!transport_set_up_command(&argv, ob->cmd, TRUE, PANIC, addrlist, buffer,
480 /* If the -N option is set, can't do any more. Presume all has gone well. */
484 /* As this is a local transport, we are already running with the required
485 uid/gid and current directory. Request that the new process be a process group
486 leader, so we can kill it and all its children on an error. */
488 if ((pid = child_open(USS argv, NULL, 0, &fd_in, &fd_out, TRUE)) < 0)
490 addrlist->message = string_sprintf(
491 "Failed to create child process for %s transport: %s", tblock->name,
497 /* When a socket is specified, expand the string and create a socket. */
501 DEBUG(D_transport) debug_printf("using socket %s\n", ob->skt);
502 sockname = expand_string(ob->skt);
503 if (sockname == NULL)
505 addrlist->message = string_sprintf("Expansion of \"%s\" (socket setting "
506 "for %s transport) failed: %s", ob->skt, tblock->name,
507 expand_string_message);
510 if ((fd_in = fd_out = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
512 addrlist->message = string_sprintf(
513 "Failed to create socket %s for %s transport: %s",
514 ob->skt, tblock->name, strerror(errno));
518 /* If the -N option is set, can't do any more. Presume all has gone well. */
522 sockun.sun_family = AF_UNIX;
523 sprintf(sockun.sun_path, "%.*s", (int)(sizeof(sockun.sun_path)-1), sockname);
524 if(connect(fd_out, (struct sockaddr *)(&sockun), sizeof(sockun)) == -1)
526 addrlist->message = string_sprintf(
527 "Failed to connect to socket %s for %s transport: %s",
528 sockun.sun_path, tblock->name, strerror(errno));
534 /* Make the output we are going to read into a file. */
536 out = fdopen(fd_out, "rb");
538 /* Now we must implement the LMTP protocol. It is like SMTP, except that after
539 the end of the message, a return code for every accepted RCPT TO is sent. This
540 allows for message+recipient checks after the message has been received. */
542 /* First thing is to wait for an initial greeting. */
544 Ustrcpy(big_buffer, "initial connection");
545 if (!lmtp_read_response(out, buffer, sizeof(buffer), '2',
546 timeout)) goto RESPONSE_FAILED;
548 /* Next, we send a LHLO command, and expect a positive response */
550 if (!lmtp_write_command(fd_in, "%s %s\r\n", "LHLO",
551 primary_hostname)) goto WRITE_FAILED;
553 if (!lmtp_read_response(out, buffer, sizeof(buffer), '2',
554 timeout)) goto RESPONSE_FAILED;
556 /* If the ignore_quota option is set, note whether the server supports the
557 IGNOREQUOTA option, and if so, set an appropriate addition for RCPT. */
559 if (ob->ignore_quota)
560 igquotstr = (pcre_exec(regex_IGNOREQUOTA, NULL, CS buffer,
561 Ustrlen(CS buffer), 0, PCRE_EOPT, NULL, 0) >= 0)? US" IGNOREQUOTA" : US"";
563 /* Now the envelope sender */
565 if (!lmtp_write_command(fd_in, "MAIL FROM:<%s>\r\n", return_path))
568 if (!lmtp_read_response(out, buffer, sizeof(buffer), '2', timeout))
570 if (errno == 0 && buffer[0] == '4')
572 errno = ERRNO_MAIL4XX;
573 addrlist->more_errno |= ((buffer[1] - '0')*10 + buffer[2] - '0') << 8;
575 goto RESPONSE_FAILED;
578 /* Next, we hand over all the recipients. Some may be permanently or
579 temporarily rejected; others may be accepted, for now. */
582 for (addr = addrlist; addr != NULL; addr = addr->next)
584 if (!lmtp_write_command(fd_in, "RCPT TO:<%s>%s\r\n",
585 transport_rcpt_address(addr, tblock->rcpt_include_affixes), igquotstr))
587 if (lmtp_read_response(out, buffer, sizeof(buffer), '2', timeout))
590 addr->transport_return = PENDING_OK;
594 if (errno != 0 || buffer[0] == 0) goto RESPONSE_FAILED;
595 addr->message = string_sprintf("LMTP error after %s: %s", big_buffer,
596 string_printing(buffer));
597 setflag(addr, af_pass_message); /* Allow message to go to user */
598 if (buffer[0] == '5') addr->transport_return = FAIL; else
600 addr->basic_errno = ERRNO_RCPT4XX;
601 addr->more_errno |= ((buffer[1] - '0')*10 + buffer[2] - '0') << 8;
606 /* Now send the text of the message if there were any good recipients. */
612 if (!lmtp_write_command(fd_in, "DATA\r\n")) goto WRITE_FAILED;
613 if (!lmtp_read_response(out, buffer, sizeof(buffer), '3', timeout))
615 if (errno == 0 && buffer[0] == '4')
617 errno = ERRNO_DATA4XX;
618 addrlist->more_errno |= ((buffer[1] - '0')*10 + buffer[2] - '0') << 8;
620 goto RESPONSE_FAILED;
623 sigalrm_seen = FALSE;
624 transport_write_timeout = timeout;
625 Ustrcpy(big_buffer, "sending data block"); /* For error messages */
626 DEBUG(D_transport|D_v)
627 debug_printf(" LMTP>> writing message and terminating \".\"\n");
630 ok = transport_write_message(addrlist, fd_in, ob->options, 0,
631 tblock->add_headers, tblock->remove_headers, US".", US"..",
632 tblock->rewrite_rules, tblock->rewrite_existflags);
634 /* Failure can either be some kind of I/O disaster (including timeout),
635 or the failure of a transport filter or the expansion of added headers. */
639 buffer[0] = 0; /* There hasn't been a response */
640 goto RESPONSE_FAILED;
643 Ustrcpy(big_buffer, "end of data"); /* For error messages */
645 /* We now expect a response for every address that was accepted above,
646 in the same order. For those that get a response, their status is fixed;
647 any that are accepted have been handed over, even if later responses crash -
648 at least, that's how I read RFC 2033. */
650 for (addr = addrlist; addr != NULL; addr = addr->next)
652 if (addr->transport_return != PENDING_OK) continue;
654 if (lmtp_read_response(out, buffer, sizeof(buffer), '2', timeout))
656 addr->transport_return = OK;
657 if (LOGGING(smtp_confirmation))
659 const uschar *s = string_printing(buffer);
660 /* de-const safe here as string_printing known to have alloc'n'copied */
661 addr->message = (s == buffer)? (uschar *)string_copy(s) : US s;
664 /* If the response has failed badly, use it for all the remaining pending
665 addresses and give up. */
667 else if (errno != 0 || buffer[0] == 0)
671 check_response(&save_errno, addr->more_errno, buffer, &code,
673 addr->transport_return = (code == '5')? FAIL : DEFER;
674 for (a = addr->next; a != NULL; a = a->next)
676 if (a->transport_return != PENDING_OK) continue;
677 a->basic_errno = addr->basic_errno;
678 a->message = addr->message;
679 a->transport_return = addr->transport_return;
684 /* Otherwise, it's an LMTP error code return for one address */
688 if (buffer[0] == '4')
690 addr->basic_errno = ERRNO_DATA4XX;
691 addr->more_errno |= ((buffer[1] - '0')*10 + buffer[2] - '0') << 8;
693 addr->message = string_sprintf("LMTP error after %s: %s", big_buffer,
694 string_printing(buffer));
695 addr->transport_return = (buffer[0] == '5')? FAIL : DEFER;
696 setflag(addr, af_pass_message); /* Allow message to go to user */
701 /* The message transaction has completed successfully - this doesn't mean that
702 all the addresses have necessarily been transferred, but each has its status
703 set, so we change the yield to TRUE. */
706 (void) lmtp_write_command(fd_in, "QUIT\r\n");
707 (void) lmtp_read_response(out, buffer, sizeof(buffer), '2', 1);
712 /* Come here if any call to read_response, other than a response after the data
713 phase, failed. Put the error in the top address - this will be replicated
714 because the yield is still FALSE. (But omit ETIMEDOUT, as there will already be
715 a suitable message.) Analyse the error, and if if isn't too bad, send a QUIT
716 command. Wait for the response with a short timeout, so we don't wind up this
717 process before the far end has had time to read the QUIT. */
722 if (errno != ETIMEDOUT && errno != 0) addrlist->basic_errno = errno;
723 addrlist->message = NULL;
725 if (check_response(&save_errno, addrlist->more_errno,
726 buffer, &code, &(addrlist->message)))
728 (void) lmtp_write_command(fd_in, "QUIT\r\n");
729 (void) lmtp_read_response(out, buffer, sizeof(buffer), '2', 1);
732 addrlist->transport_return = (code == '5')? FAIL : DEFER;
733 if (code == '4' && save_errno > 0)
734 addrlist->message = string_sprintf("%s: %s", addrlist->message,
735 strerror(save_errno));
736 goto KILL_AND_RETURN;
738 /* Come here if there are errors during writing of a command or the message
739 itself. This error will be applied to all the addresses. */
743 addrlist->transport_return = PANIC;
744 addrlist->basic_errno = errno;
745 if (errno == ERRNO_CHHEADER_FAIL)
747 string_sprintf("Failed to expand headers_add or headers_remove: %s",
748 expand_string_message);
749 else if (errno == ERRNO_FILTER_FAIL)
750 addrlist->message = string_sprintf("Filter process failure");
751 else if (errno == ERRNO_WRITEINCOMPLETE)
752 addrlist->message = string_sprintf("Failed repeatedly to write data");
753 else if (errno == ERRNO_SMTPFORMAT)
754 addrlist->message = US"overlong LMTP command generated";
756 addrlist->message = string_sprintf("Error %d", errno);
758 /* Come here after errors. Kill off the process. */
762 if (pid > 0) killpg(pid, SIGKILL);
764 /* Come here from all paths after the subprocess is created. Wait for the
765 process, but with a timeout. */
769 (void)child_close(pid, timeout);
771 if (fd_in >= 0) (void)close(fd_in);
772 if (fd_out >= 0) (void)fclose(out);
775 debug_printf("%s transport yields %d\n", tblock->name, yield);
782 debug_printf("*** delivery by %s transport bypassed by -N option",
784 addrlist->transport_return = OK;
788 /* End of transport/lmtp.c */