1 /* $NetBSD: smtp_proto.c,v 1.1.1.3 2011/03/02 19:32:32 tron Exp $ */ 2 3 /*++ 4 /* NAME 5 /* smtp_proto 3 6 /* SUMMARY 7 /* client SMTP/LMTP protocol 8 /* SYNOPSIS 9 /* #include "smtp.h" 10 /* 11 /* int smtp_helo(state) 12 /* SMTP_STATE *state; 13 /* 14 /* int smtp_xfer(state) 15 /* SMTP_STATE *state; 16 /* 17 /* int smtp_rset(state) 18 /* SMTP_STATE *state; 19 /* 20 /* int smtp_quit(state) 21 /* SMTP_STATE *state; 22 /* DESCRIPTION 23 /* In the subsequent text, SMTP implies LMTP. 24 /* This module implements the client side of the SMTP protocol. 25 /* 26 /* smtp_helo() performs the initial handshake with the SMTP server. 27 /* When TLS is enabled, this includes STARTTLS negotiations. 28 /* 29 /* smtp_xfer() sends message envelope information followed by the 30 /* message data, and finishes the SMTP conversation. These operations 31 /* are combined in one function, in order to implement SMTP pipelining. 32 /* Recipients are marked as "done" in the mail queue file when 33 /* bounced or delivered. The message delivery status is updated 34 /* accordingly. 35 /* 36 /* smtp_rset() sends a single RSET command and waits for the 37 /* response. In case of a negative reply it sets the 38 /* CANT_RSET_THIS_SESSION flag. 39 /* 40 /* smtp_quit() sends a single QUIT command and waits for the 41 /* response if configured to do so. It always turns off connection 42 /* caching. 43 /* DIAGNOSTICS 44 /* smtp_helo(), smtp_xfer(), smtp_rset() and smtp_quit() return 45 /* 0 in case of success, -1 in case of failure. For smtp_xfer(), 46 /* smtp_rset() and smtp_quit(), success means the ability to 47 /* perform an SMTP conversation, not necessarily the ability 48 /* to deliver mail, or the achievement of server happiness. 49 /* 50 /* In case of a rejected or failed connection, a connection 51 /* is marked as "bad, do not cache". Otherwise, connection 52 /* caching may be turned off (without being marked "bad") at 53 /* the discretion of the code that implements the individual 54 /* protocol steps. 55 /* 56 /* Warnings: corrupt message file. A corrupt message is marked 57 /* as "corrupt" by changing its queue file permissions. 58 /* BUGS 59 /* Some SMTP servers will abort when the number of recipients 60 /* for one message exceeds their capacity. This behavior violates 61 /* the SMTP protocol. 62 /* The only way around this is to limit the number of recipients 63 /* per transaction to an artificially-low value. 64 /* SEE ALSO 65 /* smtp(3h) internal data structures 66 /* smtp_chat(3) query/reply SMTP support 67 /* smtp_trouble(3) error handlers 68 /* LICENSE 69 /* .ad 70 /* .fi 71 /* The Secure Mailer license must be distributed with this software. 72 /* AUTHOR(S) 73 /* Wietse Venema 74 /* IBM T.J. Watson Research 75 /* P.O. Box 704 76 /* Yorktown Heights, NY 10598, USA 77 /* 78 /* Pipelining code in cooperation with: 79 /* Jon Ribbens 80 /* Oaktree Internet Solutions Ltd., 81 /* Internet House, 82 /* Canal Basin, 83 /* Coventry, 84 /* CV1 4LY, United Kingdom. 85 /* 86 /* Connection caching in cooperation with: 87 /* Victor Duchovni 88 /* Morgan Stanley 89 /* 90 /* TLS support originally by: 91 /* Lutz Jaenicke 92 /* BTU Cottbus 93 /* Allgemeine Elektrotechnik 94 /* Universitaetsplatz 3-4 95 /* D-03044 Cottbus, Germany 96 /*--*/ 97 98 /* System library. */ 99 100 #include <sys_defs.h> 101 #include <sys/stat.h> 102 #include <sys/socket.h> /* shutdown(2) */ 103 #include <netinet/in.h> /* ntohs() */ 104 #include <string.h> 105 #include <unistd.h> 106 #include <stdlib.h> /* 44BSD stdarg.h uses abort() */ 107 #include <stdarg.h> 108 #include <time.h> 109 110 #ifdef STRCASECMP_IN_STRINGS_H 111 #include <strings.h> 112 #endif 113 114 /* Utility library. */ 115 116 #include <msg.h> 117 #include <vstring.h> 118 #include <vstream.h> 119 #include <vstring_vstream.h> 120 #include <stringops.h> 121 #include <mymalloc.h> 122 #include <iostuff.h> 123 #include <split_at.h> 124 #include <name_code.h> 125 #include <name_mask.h> 126 127 /* Global library. */ 128 129 #include <mail_params.h> 130 #include <smtp_stream.h> 131 #include <mail_queue.h> 132 #include <recipient_list.h> 133 #include <deliver_request.h> 134 #include <defer.h> 135 #include <bounce.h> 136 #include <record.h> 137 #include <rec_type.h> 138 #include <off_cvt.h> 139 #include <mark_corrupt.h> 140 #include <quote_821_local.h> 141 #include <quote_822_local.h> 142 #include <mail_proto.h> 143 #include <mime_state.h> 144 #include <ehlo_mask.h> 145 #include <maps.h> 146 #include <tok822.h> 147 #include <mail_addr_map.h> 148 #include <ext_prop.h> 149 #include <lex_822.h> 150 #include <dsn_mask.h> 151 #include <xtext.h> 152 153 /* Application-specific. */ 154 155 #include "smtp.h" 156 #include "smtp_sasl.h" 157 158 /* 159 * Sender and receiver state. A session does not necessarily go through a 160 * linear progression, but states are guaranteed to not jump backwards. 161 * Normal sessions go from MAIL->RCPT->DATA->DOT->QUIT->LAST. The states 162 * MAIL, RCPT, and DATA may also be followed by ABORT->QUIT->LAST. 163 * 164 * When connection caching is enabled, the QUIT state is suppressed. Normal 165 * sessions proceed as MAIL->RCPT->DATA->DOT->LAST, while aborted sessions 166 * end with ABORT->LAST. The connection is left open for a limited time. An 167 * RSET probe should be sent before attempting to reuse an open connection 168 * for a new transaction. 169 * 170 * The code to send an RSET probe is a special case with its own initial state 171 * and with its own dedicated state transitions. The session proceeds as 172 * RSET->LAST. This code is kept inside the main protocol engine for 173 * consistent error handling and error reporting. It is not to be confused 174 * with the code that sends RSET to abort a mail transaction in progress. 175 * 176 * The code to send QUIT without message delivery transaction jumps into the 177 * main state machine. If this introduces complications, then we should 178 * introduce a second QUIT state with its own dedicated state transitions, 179 * just like we did for RSET probes. 180 * 181 * By default, the receiver skips the QUIT response. Some SMTP servers 182 * disconnect after responding to ".", and some SMTP servers wait before 183 * responding to QUIT. 184 * 185 * Client states that are associated with sending mail (up to and including 186 * SMTP_STATE_DOT) must have smaller numerical values than the non-sending 187 * states (SMTP_STATE_ABORT .. SMTP_STATE_LAST). 188 */ 189 #define SMTP_STATE_XFORWARD_NAME_ADDR 0 190 #define SMTP_STATE_XFORWARD_PROTO_HELO 1 191 #define SMTP_STATE_MAIL 2 192 #define SMTP_STATE_RCPT 3 193 #define SMTP_STATE_DATA 4 194 #define SMTP_STATE_DOT 5 195 #define SMTP_STATE_ABORT 6 196 #define SMTP_STATE_RSET 7 197 #define SMTP_STATE_QUIT 8 198 #define SMTP_STATE_LAST 9 199 200 int *xfer_timeouts[SMTP_STATE_LAST] = { 201 &var_smtp_xfwd_tmout, /* name/addr */ 202 &var_smtp_xfwd_tmout, /* helo/proto */ 203 &var_smtp_mail_tmout, 204 &var_smtp_rcpt_tmout, 205 &var_smtp_data0_tmout, 206 &var_smtp_data2_tmout, 207 &var_smtp_rset_tmout, 208 &var_smtp_rset_tmout, 209 &var_smtp_quit_tmout, 210 }; 211 212 char *xfer_states[SMTP_STATE_LAST] = { 213 "sending XFORWARD name/address", 214 "sending XFORWARD protocol/helo_name", 215 "sending MAIL FROM", 216 "sending RCPT TO", 217 "sending DATA command", 218 "sending end of data -- message may be sent more than once", 219 "sending final RSET", 220 "sending RSET probe", 221 "sending QUIT", 222 }; 223 224 char *xfer_request[SMTP_STATE_LAST] = { 225 "XFORWARD name/address command", 226 "XFORWARD helo/protocol command", 227 "MAIL FROM command", 228 "RCPT TO command", 229 "DATA command", 230 "end of DATA command", 231 "final RSET command", 232 "RSET probe", 233 "QUIT command", 234 }; 235 236 #define SMTP_MIME_DOWNGRADE(session, request) \ 237 (var_disable_mime_oconv == 0 \ 238 && (session->features & SMTP_FEATURE_8BITMIME) == 0 \ 239 && strcmp(request->encoding, MAIL_ATTR_ENC_7BIT) != 0) 240 241 static int smtp_start_tls(SMTP_STATE *); 242 243 /* 244 * Call-back information for header/body checks. We don't provide call-backs 245 * for actions that change the message delivery time or destination. 246 */ 247 static void smtp_hbc_logger(void *, const char *, const char *, const char *, const char *); 248 static void smtp_text_out(void *, int, const char *, ssize_t, off_t); 249 250 HBC_CALL_BACKS smtp_hbc_callbacks[1] = { 251 smtp_hbc_logger, 252 smtp_text_out, 253 }; 254 255 /* smtp_helo - perform initial handshake with SMTP server */ 256 257 int smtp_helo(SMTP_STATE *state) 258 { 259 const char *myname = "smtp_helo"; 260 SMTP_SESSION *session = state->session; 261 DELIVER_REQUEST *request = state->request; 262 SMTP_RESP *resp; 263 SMTP_RESP fake; 264 int except; 265 char *lines; 266 char *words; 267 char *word; 268 int n; 269 static const NAME_CODE xforward_features[] = { 270 XFORWARD_NAME, SMTP_FEATURE_XFORWARD_NAME, 271 XFORWARD_ADDR, SMTP_FEATURE_XFORWARD_ADDR, 272 XFORWARD_PORT, SMTP_FEATURE_XFORWARD_PORT, 273 XFORWARD_PROTO, SMTP_FEATURE_XFORWARD_PROTO, 274 XFORWARD_HELO, SMTP_FEATURE_XFORWARD_HELO, 275 XFORWARD_IDENT, SMTP_FEATURE_XFORWARD_IDENT, 276 XFORWARD_DOMAIN, SMTP_FEATURE_XFORWARD_DOMAIN, 277 0, 0, 278 }; 279 const char *ehlo_words; 280 int discard_mask; 281 static const NAME_MASK pix_bug_table[] = { 282 PIX_BUG_DISABLE_ESMTP, SMTP_FEATURE_PIX_NO_ESMTP, 283 PIX_BUG_DELAY_DOTCRLF, SMTP_FEATURE_PIX_DELAY_DOTCRLF, 284 0, 285 }; 286 const char *pix_bug_words; 287 const char *pix_bug_source; 288 int pix_bug_mask; 289 290 #ifdef USE_TLS 291 int saved_features = session->features; 292 int tls_helo_status; 293 294 #endif 295 const char *NOCLOBBER where; 296 297 /* 298 * Prepare for disaster. 299 */ 300 smtp_timeout_setup(state->session->stream, var_smtp_helo_tmout); 301 if ((except = vstream_setjmp(state->session->stream)) != 0) 302 return (smtp_stream_except(state, except, where)); 303 304 /* 305 * If not recursing after STARTTLS, examine the server greeting banner 306 * and decide if we are going to send EHLO as the next command. 307 */ 308 if ((state->misc_flags & SMTP_MISC_FLAG_IN_STARTTLS) == 0) { 309 310 /* 311 * Read and parse the server's SMTP greeting banner. 312 */ 313 where = "receiving the initial server greeting"; 314 switch ((resp = smtp_chat_resp(session))->code / 100) { 315 case 2: 316 break; 317 case 5: 318 if (var_smtp_skip_5xx_greeting) 319 STR(resp->dsn_buf)[0] = '4'; 320 /* FALLTHROUGH */ 321 default: 322 return (smtp_site_fail(state, session->host, resp, 323 "host %s refused to talk to me: %s", 324 session->namaddr, 325 translit(resp->str, "\n", " "))); 326 } 327 328 /* 329 * If the policy table specifies a bogus TLS security level, fail 330 * now. 331 */ 332 #ifdef USE_TLS 333 if (session->tls_level == TLS_LEV_INVALID) 334 /* Warning is already logged. */ 335 return (smtp_site_fail(state, DSN_BY_LOCAL_MTA, 336 SMTP_RESP_FAKE(&fake, "4.7.0"), 337 "client TLS configuration problem")); 338 #endif 339 340 /* 341 * XXX Some PIX firewall versions require flush before ".<CR><LF>" so 342 * it does not span a packet boundary. This hurts performance so it 343 * is not on by default. 344 */ 345 if (resp->str[strspn(resp->str, "20 *\t\n")] == 0) { 346 if (smtp_pix_bug_maps != 0 347 && (pix_bug_words = 348 maps_find(smtp_pix_bug_maps, 349 state->session->addr, 0)) != 0) { 350 pix_bug_source = VAR_SMTP_PIX_BUG_MAPS; 351 } else { 352 pix_bug_words = var_smtp_pix_bug_words; 353 pix_bug_source = VAR_SMTP_PIX_BUG_WORDS; 354 } 355 if (*pix_bug_words) { 356 pix_bug_mask = name_mask_opt(pix_bug_source, pix_bug_table, 357 pix_bug_words, 358 NAME_MASK_ANY_CASE | NAME_MASK_IGNORE); 359 msg_info("%s: enabling PIX workarounds: %s for %s", 360 request->queue_id, 361 str_name_mask("pix workaround bitmask", 362 pix_bug_table, pix_bug_mask), 363 session->namaddrport); 364 session->features |= pix_bug_mask; 365 } 366 } 367 368 /* 369 * See if we are talking to ourself. This should not be possible with 370 * the way we implement DNS lookups. However, people are known to 371 * sometimes screw up the naming service. And, mailer loops are still 372 * possible when our own mailer routing tables are mis-configured. 373 */ 374 words = resp->str; 375 (void) mystrtok(&words, "- \t\n"); 376 for (n = 0; (word = mystrtok(&words, " \t\n")) != 0; n++) { 377 if (n == 0 && strcasecmp(word, var_myhostname) == 0) { 378 if (state->misc_flags & SMTP_MISC_FLAG_LOOP_DETECT) 379 msg_warn("host %s greeted me with my own hostname %s", 380 session->namaddrport, var_myhostname); 381 } else if (strcasecmp(word, "ESMTP") == 0) 382 session->features |= SMTP_FEATURE_ESMTP; 383 } 384 if ((state->misc_flags & SMTP_MISC_FLAG_USE_LMTP) == 0) { 385 if (var_smtp_always_ehlo 386 && (session->features & SMTP_FEATURE_PIX_NO_ESMTP) == 0) 387 session->features |= SMTP_FEATURE_ESMTP; 388 if (var_smtp_never_ehlo 389 || (session->features & SMTP_FEATURE_PIX_NO_ESMTP) != 0) 390 session->features &= ~SMTP_FEATURE_ESMTP; 391 } else { 392 session->features |= SMTP_FEATURE_ESMTP; 393 } 394 } 395 396 /* 397 * If recursing after STARTTLS, there is no server greeting banner. 398 * Always send EHLO as the next command. 399 */ 400 else { 401 session->features |= SMTP_FEATURE_ESMTP; 402 } 403 404 /* 405 * Return the compliment. Fall back to SMTP if our ESMTP recognition 406 * heuristic failed. 407 */ 408 if ((state->misc_flags & SMTP_MISC_FLAG_USE_LMTP) == 0) { 409 where = "performing the EHLO handshake"; 410 if (session->features & SMTP_FEATURE_ESMTP) { 411 smtp_chat_cmd(session, "EHLO %s", var_smtp_helo_name); 412 if ((resp = smtp_chat_resp(session))->code / 100 != 2) { 413 if (resp->code == 421) 414 return (smtp_site_fail(state, session->host, resp, 415 "host %s refused to talk to me: %s", 416 session->namaddr, 417 translit(resp->str, "\n", " "))); 418 else 419 session->features &= ~SMTP_FEATURE_ESMTP; 420 } 421 } 422 if ((session->features & SMTP_FEATURE_ESMTP) == 0) { 423 where = "performing the HELO handshake"; 424 smtp_chat_cmd(session, "HELO %s", var_smtp_helo_name); 425 if ((resp = smtp_chat_resp(session))->code / 100 != 2) 426 return (smtp_site_fail(state, session->host, resp, 427 "host %s refused to talk to me: %s", 428 session->namaddr, 429 translit(resp->str, "\n", " "))); 430 } 431 } else { 432 where = "performing the LHLO handshake"; 433 smtp_chat_cmd(session, "LHLO %s", var_smtp_helo_name); 434 if ((resp = smtp_chat_resp(session))->code / 100 != 2) 435 return (smtp_site_fail(state, session->host, resp, 436 "host %s refused to talk to me: %s", 437 session->namaddr, 438 translit(resp->str, "\n", " "))); 439 } 440 441 /* 442 * No early returns allowed, to ensure consistent handling of TLS and 443 * SASL policies. 444 */ 445 if (session->features & SMTP_FEATURE_ESMTP) { 446 447 /* 448 * Determine what server EHLO keywords to ignore, typically to avoid 449 * inter-operability problems. 450 */ 451 if (smtp_ehlo_dis_maps == 0 452 || (ehlo_words = maps_find(smtp_ehlo_dis_maps, 453 state->session->addr, 0)) == 0) 454 ehlo_words = var_smtp_ehlo_dis_words; 455 discard_mask = ehlo_mask(ehlo_words); 456 if (discard_mask && !(discard_mask & EHLO_MASK_SILENT)) 457 msg_info("discarding EHLO keywords: %s", 458 str_ehlo_mask(discard_mask)); 459 460 /* 461 * Pick up some useful features offered by the SMTP server. XXX Until 462 * we have a portable routine to convert from string to off_t with 463 * proper overflow detection, ignore the message size limit 464 * advertised by the SMTP server. Otherwise, we might do the wrong 465 * thing when the server advertises a really huge message size limit. 466 * 467 * XXX Allow for "code (SP|-) ehlo-keyword (SP|=) ehlo-param...", 468 * because MicroSoft implemented AUTH based on an old draft. 469 */ 470 lines = resp->str; 471 for (n = 0; (words = mystrtok(&lines, "\n")) != 0; /* see below */ ) { 472 if (mystrtok(&words, "- ") 473 && (word = mystrtok(&words, " \t=")) != 0) { 474 if (n == 0) { 475 if (session->helo != 0) 476 myfree(session->helo); 477 478 /* 479 * XXX: Keep the original case: we don't expect a single 480 * SMTP server to randomly change the case of its helo 481 * response. If different capitalization is detected, we 482 * should assume disjoint TLS caches. 483 */ 484 session->helo = mystrdup(word); 485 if (strcasecmp(word, var_myhostname) == 0 486 && (state->misc_flags & SMTP_MISC_FLAG_LOOP_DETECT) != 0) { 487 msg_warn("host %s replied to HELO/EHLO" 488 " with my own hostname %s", 489 session->namaddrport, var_myhostname); 490 if (session->features & SMTP_FEATURE_BEST_MX) 491 return (smtp_site_fail(state, DSN_BY_LOCAL_MTA, 492 SMTP_RESP_FAKE(&fake, "5.4.6"), 493 "mail for %s loops back to myself", 494 request->nexthop)); 495 else 496 return (smtp_site_fail(state, DSN_BY_LOCAL_MTA, 497 SMTP_RESP_FAKE(&fake, "4.4.6"), 498 "mail for %s loops back to myself", 499 request->nexthop)); 500 } 501 } else if (strcasecmp(word, "8BITMIME") == 0) { 502 if ((discard_mask & EHLO_MASK_8BITMIME) == 0) 503 session->features |= SMTP_FEATURE_8BITMIME; 504 } else if (strcasecmp(word, "PIPELINING") == 0) { 505 if ((discard_mask & EHLO_MASK_PIPELINING) == 0) 506 session->features |= SMTP_FEATURE_PIPELINING; 507 } else if (strcasecmp(word, "XFORWARD") == 0) { 508 if ((discard_mask & EHLO_MASK_XFORWARD) == 0) 509 while ((word = mystrtok(&words, " \t")) != 0) 510 session->features |= 511 name_code(xforward_features, 512 NAME_CODE_FLAG_NONE, word); 513 } else if (strcasecmp(word, "SIZE") == 0) { 514 if ((discard_mask & EHLO_MASK_SIZE) == 0) { 515 session->features |= SMTP_FEATURE_SIZE; 516 if ((word = mystrtok(&words, " \t")) != 0) { 517 if (!alldig(word)) 518 msg_warn("bad EHLO SIZE limit \"%s\" from %s", 519 word, session->namaddrport); 520 else 521 session->size_limit = off_cvt_string(word); 522 } 523 } 524 #ifdef USE_TLS 525 } else if (strcasecmp(word, "STARTTLS") == 0) { 526 /* Ignored later if we already sent STARTTLS. */ 527 if ((discard_mask & EHLO_MASK_STARTTLS) == 0) 528 session->features |= SMTP_FEATURE_STARTTLS; 529 #endif 530 #ifdef USE_SASL_AUTH 531 } else if (var_smtp_sasl_enable 532 && strcasecmp(word, "AUTH") == 0) { 533 if ((discard_mask & EHLO_MASK_AUTH) == 0) 534 smtp_sasl_helo_auth(session, words); 535 #endif 536 } else if (strcasecmp(word, "DSN") == 0) { 537 if ((discard_mask & EHLO_MASK_DSN) == 0) 538 session->features |= SMTP_FEATURE_DSN; 539 } 540 n++; 541 } 542 } 543 } 544 if (msg_verbose) 545 msg_info("server features: 0x%x size %.0f", 546 session->features, (double) session->size_limit); 547 548 /* 549 * We use SMTP command pipelining if the server said it supported it. 550 * Since we use blocking I/O, RFC 2197 says that we should inspect the 551 * TCP window size and not send more than this amount of information. 552 * Unfortunately this information is unavailable using the sockets 553 * interface. However, we *can* get the TCP send buffer size on the local 554 * TCP/IP stack. We should be able to fill this buffer without being 555 * blocked, and then the kernel will effectively do non-blocking I/O for 556 * us by automatically writing out the contents of its send buffer while 557 * we are reading in the responses. In addition to TCP buffering we have 558 * to be aware of application-level buffering by the vstream module, 559 * which is limited to a couple kbytes. 560 * 561 * XXX No need to do this before and after STARTTLS, but it's not a big deal 562 * if we do. 563 * 564 * XXX When TLS is turned on, the SMTP-level writes will be encapsulated as 565 * TLS messages. Thus, the TCP-level payload will be larger than the 566 * SMTP-level payload. This has implications for the PIPELINING engine. 567 * 568 * To avoid deadlock, the PIPELINING engine needs to request a TCP send 569 * buffer size that can hold the unacknowledged commands plus the TLS 570 * encapsulation overhead. 571 * 572 * The PIPELINING engine keeps the unacknowledged command size <= the 573 * default VSTREAM buffer size (to avoid small-write performance issues 574 * when the VSTREAM buffer size is at its default size). With a default 575 * VSTREAM buffer size of 4096 there is no reason to increase the 576 * unacknowledged command size as the TCP MSS increases. It's safer to 577 * spread the remote SMTP server's recipient processing load over time, 578 * than dumping a very large recipient list all at once. 579 * 580 * For TLS encapsulation overhead we make a conservative guess: take the 581 * current protocol overhead of ~40 bytes, double the number for future 582 * proofing (~80 bytes), then round up the result to the nearest power of 583 * 2 (128 bytes). Plus, be prepared for worst-case compression that 584 * expands data by 1 kbyte, so that the worst-case SMTP payload per TLS 585 * message becomes 15 kbytes. 586 */ 587 #define PIPELINING_BUFSIZE VSTREAM_BUFSIZE 588 #ifdef USE_TLS 589 #define TLS_WORST_PAYLOAD 16384 590 #define TLS_WORST_COMP_OVERHD 1024 591 #define TLS_WORST_PROTO_OVERHD 128 592 #define TLS_WORST_SMTP_PAYLOAD (TLS_WORST_PAYLOAD - TLS_WORST_COMP_OVERHD) 593 #define TLS_WORST_TOTAL_OVERHD (TLS_WORST_COMP_OVERHD + TLS_WORST_PROTO_OVERHD) 594 #endif 595 596 if (session->features & SMTP_FEATURE_PIPELINING) { 597 SOCKOPT_SIZE optlen; 598 int tcp_bufsize; 599 int enc_overhead = 0; 600 601 optlen = sizeof(tcp_bufsize); 602 if (getsockopt(vstream_fileno(session->stream), SOL_SOCKET, 603 SO_SNDBUF, (char *) &tcp_bufsize, &optlen) < 0) 604 msg_fatal("%s: getsockopt: %m", myname); 605 #ifdef USE_TLS 606 if (state->misc_flags & SMTP_MISC_FLAG_IN_STARTTLS) 607 enc_overhead += 608 (1 + (PIPELINING_BUFSIZE - 1) 609 / TLS_WORST_SMTP_PAYLOAD) * TLS_WORST_TOTAL_OVERHD; 610 #endif 611 if (tcp_bufsize < PIPELINING_BUFSIZE + enc_overhead) { 612 tcp_bufsize = PIPELINING_BUFSIZE + enc_overhead; 613 if (setsockopt(vstream_fileno(session->stream), SOL_SOCKET, 614 SO_SNDBUF, (char *) &tcp_bufsize, optlen) < 0) 615 msg_fatal("%s: setsockopt: %m", myname); 616 } 617 if (msg_verbose) 618 msg_info("Using %s PIPELINING, TCP send buffer size is %d, " 619 "PIPELINING buffer size is %d", (state->misc_flags & 620 SMTP_MISC_FLAG_USE_LMTP) ? "LMTP" : "ESMTP", 621 tcp_bufsize, PIPELINING_BUFSIZE); 622 } 623 #ifdef USE_TLS 624 625 /* 626 * Skip this part if we already sent STARTTLS. 627 */ 628 if ((state->misc_flags & SMTP_MISC_FLAG_IN_STARTTLS) == 0) { 629 630 /* 631 * Optionally log unused STARTTLS opportunities. 632 */ 633 if ((session->features & SMTP_FEATURE_STARTTLS) && 634 var_smtp_tls_note_starttls_offer && 635 session->tls_level <= TLS_LEV_NONE) 636 msg_info("Host offered STARTTLS: [%s]", session->host); 637 638 /* 639 * Decide whether or not to send STARTTLS. 640 */ 641 if ((session->features & SMTP_FEATURE_STARTTLS) != 0 642 && smtp_tls_ctx != 0 && session->tls_level >= TLS_LEV_MAY) { 643 644 /* 645 * Prepare for disaster. 646 */ 647 smtp_timeout_setup(state->session->stream, var_smtp_starttls_tmout); 648 if ((except = vstream_setjmp(state->session->stream)) != 0) 649 return (smtp_stream_except(state, except, 650 "receiving the STARTTLS response")); 651 652 /* 653 * Send STARTTLS. Recurse when the server accepts STARTTLS, after 654 * resetting the SASL and EHLO features lists. 655 * 656 * Reset the SASL mechanism list to avoid spurious warnings. 657 * 658 * Use the smtp_sasl_tls_security_options feature to allow SASL 659 * mechanisms that may not be allowed with plain-text 660 * connections. 661 */ 662 smtp_chat_cmd(session, "STARTTLS"); 663 if ((resp = smtp_chat_resp(session))->code / 100 == 2) { 664 #ifdef USE_SASL_AUTH 665 if (session->features & SMTP_FEATURE_AUTH) 666 smtp_sasl_cleanup(session); 667 #endif 668 session->features = saved_features; 669 /* XXX Mix-up of per-session and per-request flags. */ 670 state->misc_flags |= SMTP_MISC_FLAG_IN_STARTTLS; 671 tls_helo_status = smtp_start_tls(state); 672 state->misc_flags &= ~SMTP_MISC_FLAG_IN_STARTTLS; 673 return (tls_helo_status); 674 } 675 676 /* 677 * Give up if we must use TLS but the server rejects STARTTLS 678 * although support for it was announced in the EHLO response. 679 */ 680 session->features &= ~SMTP_FEATURE_STARTTLS; 681 if (session->tls_level >= TLS_LEV_ENCRYPT) 682 return (smtp_site_fail(state, session->host, resp, 683 "TLS is required, but host %s refused to start TLS: %s", 684 session->namaddr, 685 translit(resp->str, "\n", " "))); 686 /* Else try to continue in plain-text mode. */ 687 } 688 689 /* 690 * Give up if we must use TLS but can't for various reasons. 691 * 692 * 200412 Be sure to provide the default clause at the bottom of this 693 * block. When TLS is required we must never, ever, end up in 694 * plain-text mode. 695 */ 696 if (session->tls_level >= TLS_LEV_ENCRYPT) { 697 if (!(session->features & SMTP_FEATURE_STARTTLS)) { 698 return (smtp_site_fail(state, DSN_BY_LOCAL_MTA, 699 SMTP_RESP_FAKE(&fake, "4.7.4"), 700 "TLS is required, but was not offered by host %s", 701 session->namaddr)); 702 } else if (smtp_tls_ctx == 0) { 703 return (smtp_site_fail(state, DSN_BY_LOCAL_MTA, 704 SMTP_RESP_FAKE(&fake, "4.7.5"), 705 "TLS is required, but our TLS engine is unavailable")); 706 } else { 707 msg_warn("%s: TLS is required but unavailable, don't know why", 708 myname); 709 return (smtp_site_fail(state, DSN_BY_LOCAL_MTA, 710 SMTP_RESP_FAKE(&fake, "4.7.0"), 711 "TLS is required, but unavailable")); 712 } 713 } 714 } 715 #endif 716 #ifdef USE_SASL_AUTH 717 if (var_smtp_sasl_enable && (session->features & SMTP_FEATURE_AUTH)) 718 return (smtp_sasl_helo_login(state)); 719 #endif 720 721 return (0); 722 } 723 724 #ifdef USE_TLS 725 726 /* smtp_start_tls - turn on TLS and recurse into the HELO dialog */ 727 728 static int smtp_start_tls(SMTP_STATE *state) 729 { 730 SMTP_SESSION *session = state->session; 731 TLS_CLIENT_START_PROPS tls_props; 732 VSTRING *serverid; 733 SMTP_RESP fake; 734 735 /* 736 * Turn off SMTP connection caching. When the TLS handshake succeeds, we 737 * can't reuse the SMTP connection. Reason: we can't turn off TLS in one 738 * process, save the connection to the cache which is shared with all 739 * SMTP clients, migrate the connection to another SMTP client, and 740 * resume TLS there. When the TLS handshake fails, we can't reuse the 741 * SMTP connection either, because the conversation is in an unknown 742 * state. 743 */ 744 DONT_CACHE_THIS_SESSION; 745 746 /* 747 * As of Postfix 2.5, tls_client_start() tries hard to always complete 748 * the TLS handshake. It records the verification and match status in the 749 * resulting TLScontext. It is now up to the application to abort the TLS 750 * connection if it chooses. 751 * 752 * XXX When tls_client_start() fails then we don't know what state the SMTP 753 * connection is in, so we give up on this connection even if we are not 754 * required to use TLS. 755 * 756 * The following assumes sites that use TLS in a perverse configuration: 757 * multiple hosts per hostname, or even multiple hosts per IP address. 758 * All this without a shared TLS session cache, and they still want to 759 * use TLS session caching??? 760 * 761 * The TLS session cache records the trust chain verification status of 762 * cached sessions. Different transports may have different CAfile or 763 * CApath settings, perhaps to allow authenticated connections to sites 764 * with private CA certs without trusting said private certs for other 765 * sites. So we cannot assume that a trust chain valid for one transport 766 * is valid for another. Therefore the client session id must include 767 * either the transport name or the values of CAfile and CApath. We use 768 * the transport name. 769 * 770 * XXX: We store only one session per lookup key. Ideally the the key maps 771 * 1-to-1 to a server TLS session cache. We use the IP address, port and 772 * ehlo response name to build a lookup key that works for split caches 773 * (that announce distinct names) behind a load balancer. 774 * 775 * XXX: The TLS library may salt the serverid with further details of the 776 * protocol and cipher requirements. 777 * 778 * Large parameter lists are error-prone, so we emulate a language feature 779 * that C does not have natively: named parameter lists. 780 */ 781 serverid = vstring_alloc(10); 782 vstring_sprintf(serverid, "%s:%s:%u:%s", state->service, session->addr, 783 ntohs(session->port), session->helo ? session->helo : ""); 784 session->tls_context = 785 TLS_CLIENT_START(&tls_props, 786 ctx = smtp_tls_ctx, 787 stream = session->stream, 788 log_level = var_smtp_tls_loglevel, 789 timeout = var_smtp_starttls_tmout, 790 tls_level = session->tls_level, 791 nexthop = session->tls_nexthop, 792 host = session->host, 793 namaddr = session->namaddrport, 794 serverid = vstring_str(serverid), 795 protocols = session->tls_protocols, 796 cipher_grade = session->tls_grade, 797 cipher_exclusions 798 = vstring_str(session->tls_exclusions), 799 matchargv = session->tls_matchargv, 800 fpt_dgst = var_smtp_tls_fpt_dgst); 801 vstring_free(serverid); 802 803 if (session->tls_context == 0) { 804 805 /* 806 * We must avoid further I/O, the peer is in an undefined state. 807 */ 808 (void) vstream_fpurge(session->stream, VSTREAM_PURGE_BOTH); 809 DONT_USE_DEAD_SESSION; 810 811 /* 812 * If TLS is optional, try delivery to the same server over a 813 * plaintext connection. Otherwise we would defer mail forever with 814 * destinations that have no alternate MX host. 815 * 816 * Don't fall back to plaintext if we were willing to use SASL-over-TLS 817 * authentication. If the server doesn't announce SASL support over 818 * plaintext connections, then we don't want delivery to fail with 819 * "relay access denied". 820 */ 821 if (session->tls_level == TLS_LEV_MAY 822 #ifdef USE_SASL_AUTH 823 && !(var_smtp_sasl_enable 824 && *var_smtp_sasl_passwd 825 && smtp_sasl_passwd_lookup(session)) 826 #endif 827 ) 828 RETRY_AS_PLAINTEXT; 829 return (smtp_site_fail(state, DSN_BY_LOCAL_MTA, 830 SMTP_RESP_FAKE(&fake, "4.7.5"), 831 "Cannot start TLS: handshake failure")); 832 } 833 834 /* 835 * If we are verifying the server certificate and are not happy with the 836 * result, abort the delivery here. We have a usable TLS session with the 837 * server, so no need to disable I/O, ... we can even be polite and send 838 * "QUIT". 839 * 840 * See src/tls/tls_level.c. Levels above encrypt require matching. Levels >= 841 * verify require CA trust. 842 */ 843 if (session->tls_level >= TLS_LEV_VERIFY) 844 if (!TLS_CERT_IS_TRUSTED(session->tls_context)) 845 return (smtp_site_fail(state, DSN_BY_LOCAL_MTA, 846 SMTP_RESP_FAKE(&fake, "4.7.5"), 847 "Server certificate not trusted")); 848 if (session->tls_level > TLS_LEV_ENCRYPT) 849 if (!TLS_CERT_IS_MATCHED(session->tls_context)) 850 return (smtp_site_fail(state, DSN_BY_LOCAL_MTA, 851 SMTP_RESP_FAKE(&fake, "4.7.5"), 852 "Server certificate not verified")); 853 854 855 /* At this point there must not be any pending plaintext. */ 856 vstream_fpurge(session->stream, VSTREAM_PURGE_BOTH); 857 858 /* 859 * At this point we have to re-negotiate the "EHLO" to reget the 860 * feature-list. 861 */ 862 return (smtp_helo(state)); 863 } 864 865 #endif 866 867 /* smtp_hbc_logger - logging call-back for header/body checks */ 868 869 static void smtp_hbc_logger(void *context, const char *action, 870 const char *where, const char *content, 871 const char *text) 872 { 873 const SMTP_STATE *state = (SMTP_STATE *) context; 874 875 if (*text) { 876 msg_info("%s: %s: %s %.60s: %s", 877 state->request->queue_id, action, where, content, text); 878 } else { 879 msg_info("%s: %s: %s %.60s", 880 state->request->queue_id, action, where, content); 881 } 882 } 883 884 /* smtp_text_out - output one header/body record */ 885 886 static void smtp_text_out(void *context, int rec_type, 887 const char *text, ssize_t len, 888 off_t unused_offset) 889 { 890 SMTP_STATE *state = (SMTP_STATE *) context; 891 SMTP_SESSION *session = state->session; 892 ssize_t data_left; 893 const char *data_start; 894 895 /* 896 * Deal with an impedance mismatch between Postfix queue files (record 897 * length <= $message_line_length_limit) and SMTP (DATA record length <= 898 * $smtp_line_length_limit). The code below does a little too much work 899 * when the SMTP line length limit is disabled, but it avoids code 900 * duplication, and thus, it avoids testing and maintenance problems. 901 */ 902 data_left = len; 903 data_start = text; 904 do { 905 if (state->space_left == var_smtp_line_limit 906 && data_left > 0 && *data_start == '.') 907 smtp_fputc('.', session->stream); 908 if (var_smtp_line_limit > 0 && data_left >= state->space_left) { 909 smtp_fputs(data_start, state->space_left, session->stream); 910 data_start += state->space_left; 911 data_left -= state->space_left; 912 state->space_left = var_smtp_line_limit; 913 if (data_left > 0 || rec_type == REC_TYPE_CONT) { 914 smtp_fputc(' ', session->stream); 915 state->space_left -= 1; 916 } 917 } else { 918 if (rec_type == REC_TYPE_CONT) { 919 smtp_fwrite(data_start, data_left, session->stream); 920 state->space_left -= data_left; 921 } else { 922 smtp_fputs(data_start, data_left, session->stream); 923 state->space_left = var_smtp_line_limit; 924 } 925 break; 926 } 927 } while (data_left > 0); 928 } 929 930 /* smtp_format_out - output one header/body record */ 931 932 static void PRINTFLIKE(3, 4) smtp_format_out(void *, int, const char *,...); 933 934 static void smtp_format_out(void *context, int rec_type, const char *fmt,...) 935 { 936 static VSTRING *vp; 937 va_list ap; 938 939 if (vp == 0) 940 vp = vstring_alloc(100); 941 va_start(ap, fmt); 942 vstring_vsprintf(vp, fmt, ap); 943 va_end(ap); 944 smtp_text_out(context, rec_type, vstring_str(vp), VSTRING_LEN(vp), 0); 945 } 946 947 /* smtp_header_out - output one message header */ 948 949 static void smtp_header_out(void *context, int unused_header_class, 950 const HEADER_OPTS *unused_info, 951 VSTRING *buf, off_t offset) 952 { 953 char *start = vstring_str(buf); 954 char *line; 955 char *next_line; 956 957 /* 958 * This code destroys the header. We could try to avoid clobbering it, 959 * but we're not going to use the data any further. 960 */ 961 for (line = start; line; line = next_line) { 962 next_line = split_at(line, '\n'); 963 smtp_text_out(context, REC_TYPE_NORM, line, next_line ? 964 next_line - line - 1 : strlen(line), offset); 965 } 966 } 967 968 /* smtp_header_rewrite - rewrite message header before output */ 969 970 static void smtp_header_rewrite(void *context, int header_class, 971 const HEADER_OPTS *header_info, 972 VSTRING *buf, off_t offset) 973 { 974 SMTP_STATE *state = (SMTP_STATE *) context; 975 int did_rewrite = 0; 976 char *line; 977 char *start; 978 char *next_line; 979 char *end_line; 980 char *result; 981 982 /* 983 * Apply optional header filtering. 984 */ 985 if (smtp_header_checks) { 986 result = hbc_header_checks(context, smtp_header_checks, header_class, 987 header_info, buf, offset); 988 if (result == 0) 989 return; 990 if (result != STR(buf)) { 991 vstring_strcpy(buf, result); 992 myfree(result); 993 } 994 } 995 996 /* 997 * Rewrite primary header addresses that match the smtp_generic_maps. The 998 * cleanup server already enforces that all headers have proper lengths 999 * and that all addresses are in proper form, so we don't have to repeat 1000 * that. 1001 */ 1002 if (smtp_generic_maps && header_info && header_class == MIME_HDR_PRIMARY 1003 && (header_info->flags & (HDR_OPT_SENDER | HDR_OPT_RECIP)) != 0) { 1004 TOK822 *tree; 1005 TOK822 **addr_list; 1006 TOK822 **tpp; 1007 1008 tree = tok822_parse(vstring_str(buf) 1009 + strlen(header_info->name) + 1); 1010 addr_list = tok822_grep(tree, TOK822_ADDR); 1011 for (tpp = addr_list; *tpp; tpp++) 1012 did_rewrite |= smtp_map11_tree(tpp[0], smtp_generic_maps, 1013 smtp_ext_prop_mask & EXT_PROP_GENERIC); 1014 if (did_rewrite) { 1015 vstring_truncate(buf, strlen(header_info->name)); 1016 vstring_strcat(buf, ": "); 1017 tok822_externalize(buf, tree, TOK822_STR_HEAD); 1018 } 1019 myfree((char *) addr_list); 1020 tok822_free_tree(tree); 1021 } 1022 1023 /* 1024 * Pass through unmodified headers without reconstruction. 1025 */ 1026 if (did_rewrite == 0) { 1027 smtp_header_out(context, header_class, header_info, buf, offset); 1028 return; 1029 } 1030 1031 /* 1032 * A rewritten address list contains one address per line. The code below 1033 * replaces newlines by spaces, to fit as many addresses on a line as 1034 * possible (without rearranging the order of addresses). Prepending 1035 * white space to the beginning of lines is delegated to the output 1036 * routine. 1037 * 1038 * Code derived from cleanup_fold_header(). 1039 */ 1040 for (line = start = vstring_str(buf); line != 0; line = next_line) { 1041 end_line = line + strcspn(line, "\n"); 1042 if (line > start) { 1043 if (end_line - start < 70) { /* TAB counts as one */ 1044 line[-1] = ' '; 1045 } else { 1046 start = line; 1047 } 1048 } 1049 next_line = *end_line ? end_line + 1 : 0; 1050 } 1051 1052 /* 1053 * Prepend a tab to continued header lines that went through the address 1054 * rewriting machinery. Just like smtp_header_out(), this code destroys 1055 * the header. We could try to avoid clobbering it, but we're not going 1056 * to use the data any further. 1057 * 1058 * Code derived from cleanup_out_header(). 1059 */ 1060 for (line = start = vstring_str(buf); line != 0; line = next_line) { 1061 next_line = split_at(line, '\n'); 1062 if (line == start || IS_SPACE_TAB(*line)) { 1063 smtp_text_out(state, REC_TYPE_NORM, line, next_line ? 1064 next_line - line - 1 : strlen(line), offset); 1065 } else { 1066 smtp_format_out(state, REC_TYPE_NORM, "\t%s", line); 1067 } 1068 } 1069 } 1070 1071 /* smtp_body_rewrite - rewrite message body before output */ 1072 1073 static void smtp_body_rewrite(void *context, int type, 1074 const char *buf, ssize_t len, 1075 off_t offset) 1076 { 1077 SMTP_STATE *state = (SMTP_STATE *) context; 1078 char *result; 1079 1080 /* 1081 * Apply optional body filtering. 1082 */ 1083 if (smtp_body_checks) { 1084 result = hbc_body_checks(context, smtp_body_checks, buf, len, offset); 1085 if (result == buf) { 1086 smtp_text_out(state, type, buf, len, offset); 1087 } else if (result != 0) { 1088 smtp_text_out(state, type, result, strlen(result), offset); 1089 myfree(result); 1090 } 1091 } 1092 } 1093 1094 /* smtp_mime_fail - MIME problem */ 1095 1096 static void smtp_mime_fail(SMTP_STATE *state, int mime_errs) 1097 { 1098 const MIME_STATE_DETAIL *detail; 1099 SMTP_RESP fake; 1100 1101 detail = mime_state_detail(mime_errs); 1102 smtp_mesg_fail(state, DSN_BY_LOCAL_MTA, 1103 SMTP_RESP_FAKE(&fake, detail->dsn), 1104 "%s", detail->text); 1105 } 1106 1107 /* smtp_loop - exercise the SMTP protocol engine */ 1108 1109 static int smtp_loop(SMTP_STATE *state, NOCLOBBER int send_state, 1110 NOCLOBBER int recv_state) 1111 { 1112 const char *myname = "smtp_loop"; 1113 DELIVER_REQUEST *request = state->request; 1114 SMTP_SESSION *session = state->session; 1115 SMTP_RESP *resp; 1116 RECIPIENT *rcpt; 1117 VSTRING *next_command = vstring_alloc(100); 1118 int *NOCLOBBER survivors = 0; 1119 NOCLOBBER int next_state; 1120 NOCLOBBER int next_rcpt; 1121 NOCLOBBER int send_rcpt; 1122 NOCLOBBER int recv_rcpt; 1123 NOCLOBBER int nrcpt; 1124 NOCLOBBER int recv_done; 1125 int except; 1126 int rec_type; 1127 NOCLOBBER int prev_type = 0; 1128 NOCLOBBER int mail_from_rejected; 1129 NOCLOBBER int downgrading; 1130 int mime_errs; 1131 SMTP_RESP fake; 1132 int fail_status; 1133 1134 /* 1135 * Macros for readability. 1136 */ 1137 #define REWRITE_ADDRESS(dst, src) do { \ 1138 vstring_strcpy(dst, src); \ 1139 if (*(src) && smtp_generic_maps) \ 1140 smtp_map11_internal(dst, smtp_generic_maps, \ 1141 smtp_ext_prop_mask & EXT_PROP_GENERIC); \ 1142 } while (0) 1143 1144 #define QUOTE_ADDRESS(dst, src) do { \ 1145 if (*(src) && var_smtp_quote_821_env) { \ 1146 quote_821_local(dst, src); \ 1147 } else { \ 1148 vstring_strcpy(dst, src); \ 1149 } \ 1150 } while (0) 1151 1152 /* Caution: changes to RETURN() also affect code outside the main loop. */ 1153 1154 #define RETURN(x) do { \ 1155 if (recv_state != SMTP_STATE_LAST) \ 1156 DONT_CACHE_THIS_SESSION; \ 1157 vstring_free(next_command); \ 1158 if (survivors) \ 1159 myfree((char *) survivors); \ 1160 if (session->mime_state) \ 1161 session->mime_state = mime_state_free(session->mime_state); \ 1162 return (x); \ 1163 } while (0) 1164 1165 #define SENDER_IS_AHEAD \ 1166 (recv_state < send_state || recv_rcpt != send_rcpt) 1167 1168 #define SENDER_IN_WAIT_STATE \ 1169 (send_state == SMTP_STATE_DOT || send_state == SMTP_STATE_LAST) 1170 1171 #define SENDING_MAIL \ 1172 (recv_state <= SMTP_STATE_DOT) 1173 1174 #define CANT_RSET_THIS_SESSION \ 1175 (session->features |= SMTP_FEATURE_RSET_REJECTED) 1176 1177 /* 1178 * Pipelining support requires two loops: one loop for sending and one 1179 * for receiving. Each loop has its own independent state. Most of the 1180 * time the sender can run ahead of the receiver by as much as the TCP 1181 * send buffer permits. There are only two places where the sender must 1182 * wait for status information from the receiver: once after sending DATA 1183 * and once after sending QUIT. 1184 * 1185 * The sender state advances until the TCP send buffer would overflow, or 1186 * until the sender needs status information from the receiver. At that 1187 * point the receiver starts processing responses. Once the receiver has 1188 * caught up with the sender, the sender resumes sending commands. If the 1189 * receiver detects a serious problem (MAIL FROM rejected, all RCPT TO 1190 * commands rejected, DATA rejected) it forces the sender to abort the 1191 * SMTP dialog with RSET and QUIT. 1192 */ 1193 nrcpt = 0; 1194 next_rcpt = send_rcpt = recv_rcpt = recv_done = 0; 1195 mail_from_rejected = 0; 1196 1197 /* 1198 * Prepare for disaster. This should not be needed because the design 1199 * guarantees that no output is flushed before smtp_chat_resp() is 1200 * called. 1201 * 1202 * 1) Every SMTP command fits entirely in a VSTREAM output buffer. 1203 * 1204 * 2) smtp_loop() never invokes smtp_chat_cmd() without making sure that 1205 * there is sufficient space for the command in the output buffer. 1206 * 1207 * 3) smtp_loop() flushes the output buffer to avoid server timeouts. 1208 * 1209 * Changing any of these would violate the design, and would likely break 1210 * SMTP pipelining. 1211 * 1212 * We set up the error handler anyway (only upon entry to avoid wasting 1213 * resources) because 1) there is code below that expects that VSTREAM 1214 * timeouts are enabled, and 2) this allows us to detect if someone broke 1215 * Postfix by introducing spurious flush before read operations. 1216 */ 1217 if (send_state < SMTP_STATE_XFORWARD_NAME_ADDR 1218 || send_state > SMTP_STATE_QUIT) 1219 msg_panic("%s: bad sender state %d (receiver state %d)", 1220 myname, send_state, recv_state); 1221 smtp_timeout_setup(session->stream, 1222 *xfer_timeouts[send_state]); 1223 if ((except = vstream_setjmp(session->stream)) != 0) { 1224 msg_warn("smtp_proto: spurious flush before read in send state %d", 1225 send_state); 1226 RETURN(SENDING_MAIL ? smtp_stream_except(state, except, 1227 xfer_states[send_state]) : -1); 1228 } 1229 1230 /* 1231 * The main protocol loop. 1232 */ 1233 do { 1234 1235 /* 1236 * Build the next command. 1237 */ 1238 switch (send_state) { 1239 1240 /* 1241 * Sanity check. 1242 */ 1243 default: 1244 msg_panic("%s: bad sender state %d", myname, send_state); 1245 1246 /* 1247 * Build the XFORWARD command. With properly sanitized 1248 * information, the command length stays within the 512 byte 1249 * command line length limit. 1250 * 1251 * XXX smtpd_xforward_preset() initializes some fields as "unknown" 1252 * and some as null; historically, pickup(8) does not send any of 1253 * these, and the queue manager presets absent fields to "not 1254 * available" except for the rewrite context which is preset to 1255 * local by way of migration aid. These definitions need to be 1256 * centralized for maintainability. 1257 */ 1258 #ifndef CAN_FORWARD_CLIENT_NAME 1259 #define _ATTR_AVAIL_AND_KNOWN_(val) \ 1260 (DEL_REQ_ATTR_AVAIL(val) && strcasecmp((val), "unknown")) 1261 #define CAN_FORWARD_CLIENT_NAME _ATTR_AVAIL_AND_KNOWN_ 1262 #define CAN_FORWARD_CLIENT_ADDR _ATTR_AVAIL_AND_KNOWN_ 1263 #define CAN_FORWARD_CLIENT_PORT _ATTR_AVAIL_AND_KNOWN_ 1264 #define CAN_FORWARD_PROTO_NAME _ATTR_AVAIL_AND_KNOWN_ 1265 #define CAN_FORWARD_HELO_NAME DEL_REQ_ATTR_AVAIL 1266 #define CAN_FORWARD_IDENT_NAME DEL_REQ_ATTR_AVAIL 1267 #define CAN_FORWARD_RWR_CONTEXT DEL_REQ_ATTR_AVAIL 1268 #endif 1269 1270 case SMTP_STATE_XFORWARD_NAME_ADDR: 1271 vstring_strcpy(next_command, XFORWARD_CMD); 1272 if ((session->features & SMTP_FEATURE_XFORWARD_NAME) 1273 && CAN_FORWARD_CLIENT_NAME(request->client_name)) { 1274 vstring_strcat(next_command, " " XFORWARD_NAME "="); 1275 xtext_quote_append(next_command, request->client_name, ""); 1276 } 1277 if ((session->features & SMTP_FEATURE_XFORWARD_ADDR) 1278 && CAN_FORWARD_CLIENT_ADDR(request->client_addr)) { 1279 vstring_strcat(next_command, " " XFORWARD_ADDR "="); 1280 xtext_quote_append(next_command, request->client_addr, ""); 1281 } 1282 if ((session->features & SMTP_FEATURE_XFORWARD_PORT) 1283 && CAN_FORWARD_CLIENT_PORT(request->client_port)) { 1284 vstring_strcat(next_command, " " XFORWARD_PORT "="); 1285 xtext_quote_append(next_command, request->client_port, ""); 1286 } 1287 if (session->send_proto_helo) 1288 next_state = SMTP_STATE_XFORWARD_PROTO_HELO; 1289 else 1290 next_state = SMTP_STATE_MAIL; 1291 break; 1292 1293 case SMTP_STATE_XFORWARD_PROTO_HELO: 1294 vstring_strcpy(next_command, XFORWARD_CMD); 1295 if ((session->features & SMTP_FEATURE_XFORWARD_PROTO) 1296 && CAN_FORWARD_PROTO_NAME(request->client_proto)) { 1297 vstring_strcat(next_command, " " XFORWARD_PROTO "="); 1298 xtext_quote_append(next_command, request->client_proto, ""); 1299 } 1300 if ((session->features & SMTP_FEATURE_XFORWARD_HELO) 1301 && CAN_FORWARD_HELO_NAME(request->client_helo)) { 1302 vstring_strcat(next_command, " " XFORWARD_HELO "="); 1303 xtext_quote_append(next_command, request->client_helo, ""); 1304 } 1305 if ((session->features & SMTP_FEATURE_XFORWARD_IDENT) 1306 && CAN_FORWARD_IDENT_NAME(request->log_ident)) { 1307 vstring_strcat(next_command, " " XFORWARD_IDENT "="); 1308 xtext_quote_append(next_command, request->log_ident, ""); 1309 } 1310 if ((session->features & SMTP_FEATURE_XFORWARD_DOMAIN) 1311 && CAN_FORWARD_RWR_CONTEXT(request->rewrite_context)) { 1312 vstring_strcat(next_command, " " XFORWARD_DOMAIN "="); 1313 xtext_quote_append(next_command, 1314 strcmp(request->rewrite_context, MAIL_ATTR_RWR_LOCAL) ? 1315 XFORWARD_DOM_REMOTE : XFORWARD_DOM_LOCAL, ""); 1316 } 1317 next_state = SMTP_STATE_MAIL; 1318 break; 1319 1320 /* 1321 * Build the MAIL FROM command. 1322 */ 1323 case SMTP_STATE_MAIL: 1324 request->msg_stats.reuse_count = session->reuse_count; 1325 GETTIMEOFDAY(&request->msg_stats.conn_setup_done); 1326 REWRITE_ADDRESS(session->scratch2, request->sender); 1327 QUOTE_ADDRESS(session->scratch, vstring_str(session->scratch2)); 1328 vstring_sprintf(next_command, "MAIL FROM:<%s>", 1329 vstring_str(session->scratch)); 1330 /* XXX Don't announce SIZE if we're going to MIME downgrade. */ 1331 if (session->features & SMTP_FEATURE_SIZE /* RFC 1870 */ 1332 && !SMTP_MIME_DOWNGRADE(session, request)) 1333 vstring_sprintf_append(next_command, " SIZE=%lu", 1334 request->data_size); 1335 if (session->features & SMTP_FEATURE_8BITMIME) { /* RFC 1652 */ 1336 if (strcmp(request->encoding, MAIL_ATTR_ENC_8BIT) == 0) 1337 vstring_strcat(next_command, " BODY=8BITMIME"); 1338 else if (strcmp(request->encoding, MAIL_ATTR_ENC_7BIT) == 0) 1339 vstring_strcat(next_command, " BODY=7BIT"); 1340 else if (strcmp(request->encoding, MAIL_ATTR_ENC_NONE) != 0) 1341 msg_warn("%s: unknown content encoding: %s", 1342 request->queue_id, request->encoding); 1343 } 1344 if (session->features & SMTP_FEATURE_DSN) { 1345 if (request->dsn_envid[0]) { 1346 vstring_sprintf_append(next_command, " ENVID="); 1347 xtext_quote_append(next_command, request->dsn_envid, "+="); 1348 } 1349 if (request->dsn_ret) 1350 vstring_sprintf_append(next_command, " RET=%s", 1351 dsn_ret_str(request->dsn_ret)); 1352 } 1353 1354 /* 1355 * We authenticate the local MTA only, but not the sender. 1356 */ 1357 #ifdef USE_SASL_AUTH 1358 if (var_smtp_sasl_enable 1359 && (session->features & SMTP_FEATURE_AUTH)) 1360 vstring_strcat(next_command, " AUTH=<>"); 1361 #endif 1362 1363 /* 1364 * CVE-2009-3555 (TLS renegotiation). Try to detect a mail 1365 * hijacking attack that prepends malicious EHLO/MAIL/RCPT/DATA 1366 * commands to our TLS session. 1367 * 1368 * For the attack to succeed, the remote SMTP server must reply to 1369 * the malicious EHLO/MAIL/RCPT/DATA commands after completing 1370 * TLS (re)negotiation, so that the replies arrive in our TLS 1371 * session (otherwise the Postfix SMTP client would time out 1372 * waiting for an answer). With some luck we can detect this 1373 * specific attack as a server MAIL reply that arrives before we 1374 * send our own MAIL command. 1375 * 1376 * We don't apply this test to the HELO command because the result 1377 * would be very timing sensitive, and we don't apply this test 1378 * to RCPT and DATA replies because these may be pipelined for 1379 * legitimate reasons. 1380 */ 1381 #ifdef USE_TLS 1382 if (var_smtp_tls_blk_early_mail_reply 1383 && (state->misc_flags & SMTP_MISC_FLAG_IN_STARTTLS) != 0 1384 && (vstream_peek(session->stream) > 0 1385 || peekfd(vstream_fileno(session->stream)) > 0)) 1386 session->features |= SMTP_FEATURE_EARLY_TLS_MAIL_REPLY; 1387 #endif 1388 1389 /* 1390 * We now return to our regular broadcast. 1391 */ 1392 next_state = SMTP_STATE_RCPT; 1393 break; 1394 1395 /* 1396 * Build one RCPT TO command before we have seen the MAIL FROM 1397 * response. 1398 */ 1399 case SMTP_STATE_RCPT: 1400 rcpt = request->rcpt_list.info + send_rcpt; 1401 REWRITE_ADDRESS(session->scratch2, rcpt->address); 1402 QUOTE_ADDRESS(session->scratch, vstring_str(session->scratch2)); 1403 vstring_sprintf(next_command, "RCPT TO:<%s>", 1404 vstring_str(session->scratch)); 1405 if (session->features & SMTP_FEATURE_DSN) { 1406 /* XXX DSN xtext encode address value not type. */ 1407 if (rcpt->dsn_orcpt[0]) { 1408 xtext_quote(session->scratch, rcpt->dsn_orcpt, "+="); 1409 vstring_sprintf_append(next_command, " ORCPT=%s", 1410 vstring_str(session->scratch)); 1411 } else if (rcpt->orig_addr[0]) { 1412 quote_822_local(session->scratch, rcpt->orig_addr); 1413 vstring_sprintf(session->scratch2, "rfc822;%s", 1414 vstring_str(session->scratch)); 1415 xtext_quote(session->scratch, vstring_str(session->scratch2), "+="); 1416 vstring_sprintf_append(next_command, " ORCPT=%s", 1417 vstring_str(session->scratch)); 1418 } 1419 if (rcpt->dsn_notify) 1420 vstring_sprintf_append(next_command, " NOTIFY=%s", 1421 dsn_notify_str(rcpt->dsn_notify)); 1422 } 1423 if ((next_rcpt = send_rcpt + 1) == SMTP_RCPT_LEFT(state)) 1424 next_state = DEL_REQ_TRACE_ONLY(request->flags) ? 1425 SMTP_STATE_ABORT : SMTP_STATE_DATA; 1426 break; 1427 1428 /* 1429 * Build the DATA command before we have seen all the RCPT TO 1430 * responses. 1431 */ 1432 case SMTP_STATE_DATA: 1433 vstring_strcpy(next_command, "DATA"); 1434 next_state = SMTP_STATE_DOT; 1435 break; 1436 1437 /* 1438 * Build the "." command after we have seen the DATA response 1439 * (DATA is a protocol synchronization point). 1440 * 1441 * Changing the connection caching state here is safe because it 1442 * affects none of the not-yet processed replies to 1443 * already-generated commands. 1444 */ 1445 case SMTP_STATE_DOT: 1446 vstring_strcpy(next_command, "."); 1447 if (THIS_SESSION_IS_EXPIRED) 1448 DONT_CACHE_THIS_SESSION; 1449 next_state = THIS_SESSION_IS_CACHED ? 1450 SMTP_STATE_LAST : SMTP_STATE_QUIT; 1451 break; 1452 1453 /* 1454 * The SMTP_STATE_ABORT sender state is entered by the sender 1455 * when it has verified all recipients; or it is entered by the 1456 * receiver when all recipients are verified or rejected, and is 1457 * then left before the bottom of the main loop. 1458 * 1459 * Changing the connection caching state here is safe because there 1460 * are no not-yet processed replies to already-generated 1461 * commands. 1462 */ 1463 case SMTP_STATE_ABORT: 1464 vstring_strcpy(next_command, "RSET"); 1465 if (THIS_SESSION_IS_EXPIRED) 1466 DONT_CACHE_THIS_SESSION; 1467 next_state = THIS_SESSION_IS_CACHED ? 1468 SMTP_STATE_LAST : SMTP_STATE_QUIT; 1469 break; 1470 1471 /* 1472 * Build the RSET command. This is entered as initial state from 1473 * smtp_rset() and has its own dedicated state transitions. It is 1474 * used to find out the status of a cached session before 1475 * attempting mail delivery. 1476 */ 1477 case SMTP_STATE_RSET: 1478 vstring_strcpy(next_command, "RSET"); 1479 next_state = SMTP_STATE_LAST; 1480 break; 1481 1482 /* 1483 * Build the QUIT command before we have seen the "." or RSET 1484 * response. This is entered as initial state from smtp_quit(), 1485 * or is reached near the end of any non-cached session. 1486 * 1487 * Changing the connection caching state here is safe. If this 1488 * command is pipelined together with a preceding command, then 1489 * connection caching was already turned off. Do not clobber the 1490 * "bad connection" flag. 1491 */ 1492 case SMTP_STATE_QUIT: 1493 vstring_strcpy(next_command, "QUIT"); 1494 next_state = SMTP_STATE_LAST; 1495 if (THIS_SESSION_IS_CACHED) 1496 DONT_CACHE_THIS_SESSION; 1497 break; 1498 1499 /* 1500 * The final sender state has no action associated with it. 1501 */ 1502 case SMTP_STATE_LAST: 1503 VSTRING_RESET(next_command); 1504 break; 1505 } 1506 VSTRING_TERMINATE(next_command); 1507 1508 /* 1509 * Process responses until the receiver has caught up. Vstreams 1510 * automatically flush buffered output when reading new data. 1511 * 1512 * Flush unsent output if command pipelining is off or if no I/O 1513 * happened for a while. This limits the accumulation of client-side 1514 * delays in pipelined sessions. 1515 * 1516 * The PIPELINING engine will flush the VSTREAM buffer if the sender 1517 * could otherwise produce more output than fits the PIPELINING 1518 * buffer. This generally works because we know exactly how much 1519 * output we produced since the last time that the sender and 1520 * receiver synchronized the SMTP state. However this logic is not 1521 * applicable after the sender enters the DATA phase, where it does 1522 * not synchronize with the receiver until the <CR><LF>.<CR><LF>. 1523 * Thus, the PIPELINING engine no longer knows how much data is 1524 * pending in the TCP send buffer. For this reason, if PIPELINING is 1525 * enabled, we always pipeline QUIT after <CR><LF>.<CR><LF>. This is 1526 * safe because once the receiver reads <CR><LF>.<CR><LF>, its TCP 1527 * stack either has already received the QUIT<CR><LF>, or else it 1528 * acknowledges all bytes up to and including <CR><LF>.<CR><LF>, 1529 * making room in the sender's TCP stack for QUIT<CR><LF>. 1530 */ 1531 #define CHECK_PIPELINING_BUFSIZE \ 1532 (recv_state != SMTP_STATE_DOT || send_state != SMTP_STATE_QUIT) 1533 1534 if (SENDER_IN_WAIT_STATE 1535 || (SENDER_IS_AHEAD 1536 && ((session->features & SMTP_FEATURE_PIPELINING) == 0 1537 || (CHECK_PIPELINING_BUFSIZE 1538 && (VSTRING_LEN(next_command) + 2 1539 + vstream_bufstat(session->stream, VSTREAM_BST_OUT_PEND) 1540 > PIPELINING_BUFSIZE)) 1541 || time((time_t *) 0) 1542 - vstream_ftime(session->stream) > 10))) { 1543 while (SENDER_IS_AHEAD) { 1544 1545 /* 1546 * Sanity check. 1547 */ 1548 if (recv_state < SMTP_STATE_XFORWARD_NAME_ADDR 1549 || recv_state > SMTP_STATE_QUIT) 1550 msg_panic("%s: bad receiver state %d (sender state %d)", 1551 myname, recv_state, send_state); 1552 1553 /* 1554 * Receive the next server response. Use the proper timeout, 1555 * and log the proper client state in case of trouble. 1556 * 1557 * XXX If we lose the connection before sending end-of-data, 1558 * find out if the server sent a premature end-of-data reply. 1559 * If this read attempt fails, report "lost connection while 1560 * sending message body", not "lost connection while sending 1561 * end-of-data". 1562 * 1563 * "except" becomes zero just above the protocol loop, and stays 1564 * zero or triggers an early return from the loop. In just 1565 * one case: loss of the connection when sending the message 1566 * body, we record the exception, and keep processing in the 1567 * hope of detecting a premature 5XX. We must be careful to 1568 * not clobber this non-zero value once it is set. The 1569 * variable need not survive longjmp() calls, since the only 1570 * setjmp() which does not return early is the one sets this 1571 * condition, subquent failures always return early. 1572 */ 1573 #define LOST_CONNECTION_INSIDE_DATA (except == SMTP_ERR_EOF) 1574 1575 smtp_timeout_setup(session->stream, 1576 *xfer_timeouts[recv_state]); 1577 if (LOST_CONNECTION_INSIDE_DATA) { 1578 if (vstream_setjmp(session->stream) != 0) 1579 RETURN(smtp_stream_except(state, SMTP_ERR_EOF, 1580 "sending message body")); 1581 } else { 1582 if ((except = vstream_setjmp(session->stream)) != 0) 1583 RETURN(SENDING_MAIL ? smtp_stream_except(state, except, 1584 xfer_states[recv_state]) : -1); 1585 } 1586 resp = smtp_chat_resp(session); 1587 1588 /* 1589 * Process the response. 1590 */ 1591 switch (recv_state) { 1592 1593 /* 1594 * Process the XFORWARD response. 1595 */ 1596 case SMTP_STATE_XFORWARD_NAME_ADDR: 1597 if (resp->code / 100 != 2) 1598 msg_warn("host %s said: %s (in reply to %s)", 1599 session->namaddrport, 1600 translit(resp->str, "\n", " "), 1601 xfer_request[SMTP_STATE_XFORWARD_NAME_ADDR]); 1602 if (session->send_proto_helo) 1603 recv_state = SMTP_STATE_XFORWARD_PROTO_HELO; 1604 else 1605 recv_state = SMTP_STATE_MAIL; 1606 break; 1607 1608 case SMTP_STATE_XFORWARD_PROTO_HELO: 1609 if (resp->code / 100 != 2) 1610 msg_warn("host %s said: %s (in reply to %s)", 1611 session->namaddrport, 1612 translit(resp->str, "\n", " "), 1613 xfer_request[SMTP_STATE_XFORWARD_PROTO_HELO]); 1614 recv_state = SMTP_STATE_MAIL; 1615 break; 1616 1617 /* 1618 * Process the MAIL FROM response. When the server 1619 * rejects the sender, set the mail_from_rejected flag so 1620 * that the receiver may apply a course correction. 1621 */ 1622 case SMTP_STATE_MAIL: 1623 if (resp->code / 100 != 2) { 1624 smtp_mesg_fail(state, session->host, resp, 1625 "host %s said: %s (in reply to %s)", 1626 session->namaddr, 1627 translit(resp->str, "\n", " "), 1628 xfer_request[SMTP_STATE_MAIL]); 1629 mail_from_rejected = 1; 1630 } 1631 1632 /* 1633 * CVE-2009-3555 (TLS renegotiation). Whatever it was 1634 * that arrived before we sent our MAIL FROM command, it 1635 * was not a fatal-level TLS alert message. It could be a 1636 * warning-level TLS alert message, or a ChangeCipherSpec 1637 * message, but such messages are not normally sent in 1638 * the middle of a TLS session. We disconnect and try 1639 * again later. 1640 */ 1641 #ifdef USE_TLS 1642 if (var_smtp_tls_blk_early_mail_reply 1643 && (session->features & SMTP_FEATURE_EARLY_TLS_MAIL_REPLY)) { 1644 smtp_site_fail(state, DSN_BY_LOCAL_MTA, 1645 SMTP_RESP_FAKE(&fake, "4.7.0"), 1646 "unexpected server message"); 1647 msg_warn("server %s violates %s policy", 1648 session->namaddr, 1649 VAR_SMTP_TLS_BLK_EARLY_MAIL_REPLY); 1650 mail_from_rejected = 1; 1651 } 1652 #endif 1653 1654 /* 1655 * We now return to our regular broadcast. 1656 */ 1657 recv_state = SMTP_STATE_RCPT; 1658 break; 1659 1660 /* 1661 * Process one RCPT TO response. If MAIL FROM was 1662 * rejected, ignore RCPT TO responses: all recipients are 1663 * dead already. When all recipients are rejected the 1664 * receiver may apply a course correction. 1665 * 1666 * XXX 2821: Section 4.5.3.1 says that a 552 RCPT TO reply 1667 * must be treated as if the server replied with 452. 1668 * However, this causes "too much mail data" to be 1669 * treated as a recoverable error, which is wrong. I'll 1670 * stick with RFC 821. 1671 */ 1672 case SMTP_STATE_RCPT: 1673 if (!mail_from_rejected) { 1674 #ifdef notdef 1675 if (resp->code == 552) { 1676 resp->code = 452; 1677 resp->dsn[0] = '4'; 1678 } 1679 #endif 1680 rcpt = request->rcpt_list.info + recv_rcpt; 1681 if (resp->code / 100 == 2) { 1682 if (state->misc_flags & SMTP_MISC_FLAG_USE_LMTP) { 1683 if (survivors == 0) 1684 survivors = (int *) 1685 mymalloc(request->rcpt_list.len 1686 * sizeof(int)); 1687 survivors[nrcpt] = recv_rcpt; 1688 } 1689 ++nrcpt; 1690 /* If trace-only, mark the recipient done. */ 1691 if (DEL_REQ_TRACE_ONLY(request->flags)) { 1692 translit(resp->str, "\n", " "); 1693 smtp_rcpt_done(state, resp, rcpt); 1694 } 1695 } else { 1696 smtp_rcpt_fail(state, rcpt, session->host, resp, 1697 "host %s said: %s (in reply to %s)", 1698 session->namaddr, 1699 translit(resp->str, "\n", " "), 1700 xfer_request[SMTP_STATE_RCPT]); 1701 } 1702 } 1703 /* If trace-only, send RSET instead of DATA. */ 1704 if (++recv_rcpt == SMTP_RCPT_LEFT(state)) 1705 recv_state = DEL_REQ_TRACE_ONLY(request->flags) ? 1706 SMTP_STATE_ABORT : SMTP_STATE_DATA; 1707 /* XXX Also: record if non-delivering session. */ 1708 break; 1709 1710 /* 1711 * Process the DATA response. When the server rejects 1712 * DATA, set nrcpt to a negative value so that the 1713 * receiver can apply a course correction. 1714 */ 1715 case SMTP_STATE_DATA: 1716 if (resp->code / 100 != 3) { 1717 if (nrcpt > 0) 1718 smtp_mesg_fail(state, session->host, resp, 1719 "host %s said: %s (in reply to %s)", 1720 session->namaddr, 1721 translit(resp->str, "\n", " "), 1722 xfer_request[SMTP_STATE_DATA]); 1723 nrcpt = -1; 1724 } 1725 recv_state = SMTP_STATE_DOT; 1726 break; 1727 1728 /* 1729 * Process the end of message response. Ignore the 1730 * response when no recipient was accepted: all 1731 * recipients are dead already, and the next receiver 1732 * state is SMTP_STATE_LAST/QUIT regardless. Otherwise, 1733 * if the message transfer fails, bounce all remaining 1734 * recipients, else cross off the recipients that were 1735 * delivered. 1736 */ 1737 case SMTP_STATE_DOT: 1738 GETTIMEOFDAY(&request->msg_stats.deliver_done); 1739 if ((state->misc_flags & SMTP_MISC_FLAG_USE_LMTP) == 0) { 1740 if (nrcpt > 0) { 1741 if (resp->code / 100 != 2) { 1742 smtp_mesg_fail(state, session->host, resp, 1743 "host %s said: %s (in reply to %s)", 1744 session->namaddr, 1745 translit(resp->str, "\n", " "), 1746 xfer_request[SMTP_STATE_DOT]); 1747 } else { 1748 for (nrcpt = 0; nrcpt < recv_rcpt; nrcpt++) { 1749 rcpt = request->rcpt_list.info + nrcpt; 1750 if (!SMTP_RCPT_ISMARKED(rcpt)) { 1751 translit(resp->str, "\n", " "); 1752 smtp_rcpt_done(state, resp, rcpt); 1753 } 1754 } 1755 } 1756 } 1757 } 1758 1759 /* 1760 * With LMTP we have one response per accepted RCPT TO 1761 * command. Stay in the SMTP_STATE_DOT state until we 1762 * have collected all responses. 1763 */ 1764 else { 1765 if (nrcpt > 0) { 1766 rcpt = request->rcpt_list.info 1767 + survivors[recv_done++]; 1768 if (resp->code / 100 != 2) { 1769 smtp_rcpt_fail(state, rcpt, session->host, resp, 1770 "host %s said: %s (in reply to %s)", 1771 session->namaddr, 1772 translit(resp->str, "\n", " "), 1773 xfer_request[SMTP_STATE_DOT]); 1774 } else { 1775 translit(resp->str, "\n", " "); 1776 smtp_rcpt_done(state, resp, rcpt); 1777 } 1778 } 1779 if (msg_verbose) 1780 msg_info("%s: got %d of %d end-of-data replies", 1781 myname, recv_done, nrcpt); 1782 if (recv_done < nrcpt) 1783 break; 1784 } 1785 1786 /* 1787 * XXX Do not change the connection caching state here, 1788 * even if the connection caching timer expired between 1789 * generating the command and processing the reply, 1790 * otherwise the sender and receiver loops get out of 1791 * sync. The caller will call smtp_quit() if appropriate. 1792 */ 1793 if (var_skip_quit_resp || THIS_SESSION_IS_CACHED 1794 || LOST_CONNECTION_INSIDE_DATA) 1795 recv_state = SMTP_STATE_LAST; 1796 else 1797 recv_state = SMTP_STATE_QUIT; 1798 break; 1799 1800 /* 1801 * Receive the RSET response. 1802 * 1803 * The SMTP_STATE_ABORT sender state is entered by the 1804 * sender when it has verified all recipients; or it is 1805 * entered by the receiver when all recipients are 1806 * verified or rejected, and is then left before the 1807 * bottom of the main loop. 1808 * 1809 * XXX Do not change the connection caching state here, even 1810 * if the server rejected RSET or if the connection 1811 * caching timer expired between generating the command 1812 * and processing the reply, otherwise the sender and 1813 * receiver loops get out of sync. The caller will call 1814 * smtp_quit() if appropriate. 1815 */ 1816 case SMTP_STATE_ABORT: 1817 recv_state = (var_skip_quit_resp || THIS_SESSION_IS_CACHED ? 1818 SMTP_STATE_LAST : SMTP_STATE_QUIT); 1819 break; 1820 1821 /* 1822 * This is the initial receiver state from smtp_rset(). 1823 * It is used to find out the status of a cached session 1824 * before attempting mail delivery. 1825 */ 1826 case SMTP_STATE_RSET: 1827 if (resp->code / 100 != 2) 1828 CANT_RSET_THIS_SESSION; 1829 recv_state = SMTP_STATE_LAST; 1830 break; 1831 1832 /* 1833 * Receive, but otherwise ignore, the QUIT response. 1834 */ 1835 case SMTP_STATE_QUIT: 1836 recv_state = SMTP_STATE_LAST; 1837 break; 1838 } 1839 } 1840 1841 /* 1842 * At this point, the sender and receiver are fully synchronized. 1843 */ 1844 1845 /* 1846 * We know the server response to every command that was sent. 1847 * Apply a course correction if necessary: the sender wants to 1848 * send RCPT TO but MAIL FROM was rejected; the sender wants to 1849 * send DATA but all recipients were rejected; the sender wants 1850 * to deliver the message but DATA was rejected. 1851 */ 1852 if ((send_state == SMTP_STATE_RCPT && mail_from_rejected) 1853 || (send_state == SMTP_STATE_DATA && nrcpt == 0) 1854 || (send_state == SMTP_STATE_DOT && nrcpt < 0)) { 1855 send_state = recv_state = SMTP_STATE_ABORT; 1856 send_rcpt = recv_rcpt = 0; 1857 vstring_strcpy(next_command, "RSET"); 1858 if (THIS_SESSION_IS_EXPIRED) 1859 DONT_CACHE_THIS_SESSION; 1860 next_state = THIS_SESSION_IS_CACHED ? 1861 SMTP_STATE_LAST : SMTP_STATE_QUIT; 1862 /* XXX Also: record if non-delivering session. */ 1863 next_rcpt = 0; 1864 } 1865 } 1866 1867 /* 1868 * Make the next sender state the current sender state. 1869 */ 1870 if (send_state == SMTP_STATE_LAST) 1871 continue; 1872 1873 /* 1874 * Special case if the server accepted the DATA command. If the 1875 * server accepted at least one recipient send the entire message. 1876 * Otherwise, just send "." as per RFC 2197. 1877 * 1878 * XXX If there is a hard MIME error while downgrading to 7-bit mail, 1879 * disconnect ungracefully, because there is no other way to cancel a 1880 * transaction in progress. 1881 */ 1882 if (send_state == SMTP_STATE_DOT && nrcpt > 0) { 1883 1884 smtp_timeout_setup(session->stream, 1885 var_smtp_data1_tmout); 1886 1887 if ((except = vstream_setjmp(session->stream)) == 0) { 1888 1889 if (vstream_fseek(state->src, request->data_offset, SEEK_SET) < 0) 1890 msg_fatal("seek queue file: %m"); 1891 1892 downgrading = SMTP_MIME_DOWNGRADE(session, request); 1893 1894 /* 1895 * XXX Don't downgrade just because generic_maps is turned 1896 * on. 1897 */ 1898 #define SMTP_ANY_CHECKS (smtp_header_checks || smtp_body_checks) 1899 1900 if (downgrading || smtp_generic_maps || SMTP_ANY_CHECKS) 1901 session->mime_state = mime_state_alloc(downgrading ? 1902 MIME_OPT_DOWNGRADE 1903 | MIME_OPT_REPORT_NESTING : 1904 SMTP_ANY_CHECKS == 0 ? 1905 MIME_OPT_DISABLE_MIME : 1906 0, 1907 smtp_generic_maps 1908 || smtp_header_checks ? 1909 smtp_header_rewrite : 1910 smtp_header_out, 1911 (MIME_STATE_ANY_END) 0, 1912 smtp_body_checks ? 1913 smtp_body_rewrite : 1914 smtp_text_out, 1915 (MIME_STATE_ANY_END) 0, 1916 (MIME_STATE_ERR_PRINT) 0, 1917 (void *) state); 1918 state->space_left = var_smtp_line_limit; 1919 1920 while ((rec_type = rec_get(state->src, session->scratch, 0)) > 0) { 1921 if (rec_type != REC_TYPE_NORM && rec_type != REC_TYPE_CONT) 1922 break; 1923 if (session->mime_state == 0) { 1924 smtp_text_out((void *) state, rec_type, 1925 vstring_str(session->scratch), 1926 VSTRING_LEN(session->scratch), 1927 (off_t) 0); 1928 } else { 1929 mime_errs = 1930 mime_state_update(session->mime_state, rec_type, 1931 vstring_str(session->scratch), 1932 VSTRING_LEN(session->scratch)); 1933 if (mime_errs) { 1934 smtp_mime_fail(state, mime_errs); 1935 RETURN(0); 1936 } 1937 } 1938 prev_type = rec_type; 1939 } 1940 1941 if (session->mime_state) { 1942 1943 /* 1944 * The cleanup server normally ends MIME content with a 1945 * normal text record. The following code is needed to 1946 * flush an internal buffer when someone submits 8-bit 1947 * mail not ending in newline via /usr/sbin/sendmail 1948 * while MIME input processing is turned off, and MIME 1949 * 8bit->7bit conversion is requested upon delivery. 1950 * 1951 * Or some error while doing generic address mapping. 1952 */ 1953 mime_errs = 1954 mime_state_update(session->mime_state, rec_type, "", 0); 1955 if (mime_errs) { 1956 smtp_mime_fail(state, mime_errs); 1957 RETURN(0); 1958 } 1959 } else if (prev_type == REC_TYPE_CONT) /* missing newline */ 1960 smtp_fputs("", 0, session->stream); 1961 if ((session->features & SMTP_FEATURE_PIX_DELAY_DOTCRLF) != 0 1962 && request->msg_stats.incoming_arrival.tv_sec 1963 <= vstream_ftime(session->stream) - var_smtp_pix_thresh) { 1964 smtp_flush(session->stream);/* hurts performance */ 1965 sleep(var_smtp_pix_delay); /* not to mention this */ 1966 } 1967 if (vstream_ferror(state->src)) 1968 msg_fatal("queue file read error"); 1969 if (rec_type != REC_TYPE_XTRA) { 1970 msg_warn("%s: bad record type: %d in message content", 1971 request->queue_id, rec_type); 1972 fail_status = smtp_mesg_fail(state, DSN_BY_LOCAL_MTA, 1973 SMTP_RESP_FAKE(&fake, "5.3.0"), 1974 "unreadable mail queue entry"); 1975 /* Bailing out, abort stream with prejudice */ 1976 (void) vstream_fpurge(session->stream, VSTREAM_PURGE_BOTH); 1977 DONT_USE_DEAD_SESSION; 1978 /* If bounce_append() succeeded, status is still 0 */ 1979 if (state->status == 0) 1980 (void) mark_corrupt(state->src); 1981 /* Don't override smtp_mesg_fail() here. */ 1982 RETURN(fail_status); 1983 } 1984 } else { 1985 if (!LOST_CONNECTION_INSIDE_DATA) 1986 RETURN(smtp_stream_except(state, except, 1987 "sending message body")); 1988 1989 /* 1990 * We will clear the stream error flag to try and read a 1991 * premature 5XX response, so it is important to flush any 1992 * unwritten data. Otherwise, we will try to flush it again 1993 * before reading, which may incur an unnecessary delay and 1994 * will prevent the reading of any response that is not 1995 * already buffered (bundled with the DATA 354 response). 1996 * 1997 * Not much point in sending QUIT at this point, skip right to 1998 * SMTP_STATE_LAST. The read engine above will likewise avoid 1999 * looking for a QUIT response. 2000 */ 2001 (void) vstream_fpurge(session->stream, VSTREAM_PURGE_WRITE); 2002 next_state = SMTP_STATE_LAST; 2003 } 2004 } 2005 2006 /* 2007 * Copy the next command to the buffer and update the sender state. 2008 */ 2009 if (except == 0) { 2010 smtp_chat_cmd(session, "%s", vstring_str(next_command)); 2011 } else { 2012 DONT_CACHE_THIS_SESSION; 2013 } 2014 send_state = next_state; 2015 send_rcpt = next_rcpt; 2016 } while (recv_state != SMTP_STATE_LAST); 2017 RETURN(0); 2018 } 2019 2020 /* smtp_xfer - send a batch of envelope information and the message data */ 2021 2022 int smtp_xfer(SMTP_STATE *state) 2023 { 2024 DELIVER_REQUEST *request = state->request; 2025 SMTP_SESSION *session = state->session; 2026 SMTP_RESP fake; 2027 int send_state; 2028 int recv_state; 2029 int send_name_addr; 2030 int result; 2031 2032 /* 2033 * Sanity check. Recipients should be unmarked at this point. 2034 */ 2035 if (SMTP_RCPT_LEFT(state) <= 0) 2036 msg_panic("smtp_xfer: bad recipient count: %d", 2037 SMTP_RCPT_LEFT(state)); 2038 if (SMTP_RCPT_ISMARKED(request->rcpt_list.info)) 2039 msg_panic("smtp_xfer: bad recipient status: %d", 2040 request->rcpt_list.info->u.status); 2041 2042 /* 2043 * See if we should even try to send this message at all. This code sits 2044 * here rather than in the EHLO processing code, because of SMTP 2045 * connection caching. 2046 */ 2047 if (session->size_limit > 0 && session->size_limit < request->data_size) { 2048 smtp_mesg_fail(state, DSN_BY_LOCAL_MTA, 2049 SMTP_RESP_FAKE(&fake, "5.3.4"), 2050 "message size %lu exceeds size limit %.0f of server %s", 2051 request->data_size, (double) session->size_limit, 2052 session->namaddr); 2053 /* Redundant. We abort this delivery attempt. */ 2054 state->misc_flags |= SMTP_MISC_FLAG_COMPLETE_SESSION; 2055 return (0); 2056 } 2057 2058 /* 2059 * Use XFORWARD to forward the origin of this email message across an 2060 * SMTP-based content filter. Send client attribute information only if 2061 * it exists (i.e. remote submission). Local submissions have no client 2062 * attributes; the mail will appear to originate from the content filter 2063 * which is acceptable. 2064 */ 2065 send_name_addr = 2066 var_smtp_send_xforward 2067 && (((session->features & SMTP_FEATURE_XFORWARD_NAME) 2068 && CAN_FORWARD_CLIENT_NAME(request->client_name)) 2069 || ((session->features & SMTP_FEATURE_XFORWARD_ADDR) 2070 && CAN_FORWARD_CLIENT_ADDR(request->client_addr)) 2071 || ((session->features & SMTP_FEATURE_XFORWARD_PORT) 2072 && CAN_FORWARD_CLIENT_PORT(request->client_port))); 2073 session->send_proto_helo = 2074 var_smtp_send_xforward 2075 && (((session->features & SMTP_FEATURE_XFORWARD_PROTO) 2076 && CAN_FORWARD_PROTO_NAME(request->client_proto)) 2077 || ((session->features & SMTP_FEATURE_XFORWARD_HELO) 2078 && CAN_FORWARD_HELO_NAME(request->client_helo)) 2079 || ((session->features & SMTP_FEATURE_XFORWARD_IDENT) 2080 && CAN_FORWARD_IDENT_NAME(request->log_ident)) 2081 || ((session->features & SMTP_FEATURE_XFORWARD_DOMAIN) 2082 && CAN_FORWARD_RWR_CONTEXT(request->rewrite_context))); 2083 if (send_name_addr) 2084 recv_state = send_state = SMTP_STATE_XFORWARD_NAME_ADDR; 2085 else if (session->send_proto_helo) 2086 recv_state = send_state = SMTP_STATE_XFORWARD_PROTO_HELO; 2087 else 2088 recv_state = send_state = SMTP_STATE_MAIL; 2089 2090 /* 2091 * Remember this session's "normal completion", even if the server 4xx-ed 2092 * some or all recipients. Connection or handshake errors with a later MX 2093 * host should not cause this destination be marked as unreachable. 2094 */ 2095 result = smtp_loop(state, send_state, recv_state); 2096 2097 if (result == 0 2098 /* Just in case */ 2099 && vstream_ferror(session->stream) == 0 2100 && vstream_feof(session->stream) == 0) 2101 state->misc_flags |= SMTP_MISC_FLAG_COMPLETE_SESSION; 2102 2103 return (result); 2104 } 2105 2106 /* smtp_rset - send a lone RSET command */ 2107 2108 int smtp_rset(SMTP_STATE *state) 2109 { 2110 2111 /* 2112 * This works because SMTP_STATE_RSET is a dedicated sender/recipient 2113 * entry state, with SMTP_STATE_LAST as next sender/recipient state. 2114 */ 2115 return (smtp_loop(state, SMTP_STATE_RSET, SMTP_STATE_RSET)); 2116 } 2117 2118 /* smtp_quit - send a lone QUIT command */ 2119 2120 int smtp_quit(SMTP_STATE *state) 2121 { 2122 2123 /* 2124 * This works because SMTP_STATE_QUIT is the last state with a sender 2125 * action, with SMTP_STATE_LAST as the next sender/recipient state. 2126 */ 2127 return (smtp_loop(state, SMTP_STATE_QUIT, var_skip_quit_resp ? 2128 SMTP_STATE_LAST : SMTP_STATE_QUIT)); 2129 } 2130