1 /* $NetBSD: smtp_connect.c,v 1.3 2020/03/18 19:05:20 christos Exp $ */ 2 3 /*++ 4 /* NAME 5 /* smtp_connect 3 6 /* SUMMARY 7 /* connect to SMTP/LMTP server and deliver 8 /* SYNOPSIS 9 /* #include "smtp.h" 10 /* 11 /* int smtp_connect(state) 12 /* SMTP_STATE *state; 13 /* DESCRIPTION 14 /* This module implements SMTP/LMTP connection management and controls 15 /* mail delivery. 16 /* 17 /* smtp_connect() attempts to establish an SMTP/LMTP session with a host 18 /* that represents the destination domain, or with an optional fallback 19 /* relay when {the destination cannot be found, or when all the 20 /* destination servers are unavailable}. It skips over IP addresses 21 /* that fail to complete the SMTP/LMTP handshake and tries to find 22 /* an alternate server when an SMTP/LMTP session fails to deliver. 23 /* 24 /* This layer also controls what connections are retrieved from 25 /* the connection cache, and what connections are saved to the cache. 26 /* 27 /* The destination is either a host (or domain) name or a numeric 28 /* address. Symbolic or numeric service port information may be 29 /* appended, separated by a colon (":"). In the case of LMTP, 30 /* destinations may be specified as "unix:pathname", "inet:host" 31 /* or "inet:host:port". 32 /* 33 /* With SMTP, the Internet domain name service is queried for mail 34 /* exchanger hosts. Quote the domain name with `[' and `]' to 35 /* suppress mail exchanger lookups. 36 /* 37 /* Numerical address information should always be quoted with `[]'. 38 /* DIAGNOSTICS 39 /* The delivery status is the result value. 40 /* SEE ALSO 41 /* smtp_proto(3) SMTP client protocol 42 /* LICENSE 43 /* .ad 44 /* .fi 45 /* The Secure Mailer license must be distributed with this software. 46 /* AUTHOR(S) 47 /* Wietse Venema 48 /* IBM T.J. Watson Research 49 /* P.O. Box 704 50 /* Yorktown Heights, NY 10598, USA 51 /* 52 /* Wietse Venema 53 /* Google, Inc. 54 /* 111 8th Avenue 55 /* New York, NY 10011, USA 56 /* 57 /* Connection caching in cooperation with: 58 /* Victor Duchovni 59 /* Morgan Stanley 60 /*--*/ 61 62 /* System library. */ 63 64 #include <sys_defs.h> 65 #include <stdlib.h> 66 #include <sys/socket.h> 67 #include <sys/un.h> 68 #include <netinet/in.h> 69 #include <arpa/inet.h> 70 #include <errno.h> 71 #include <netdb.h> 72 #include <stdlib.h> 73 #include <string.h> 74 #include <unistd.h> 75 #include <fcntl.h> 76 #include <ctype.h> 77 78 #ifndef IPPORT_SMTP 79 #define IPPORT_SMTP 25 80 #endif 81 82 /* Utility library. */ 83 84 #include <msg.h> 85 #include <vstream.h> 86 #include <vstring.h> 87 #include <split_at.h> 88 #include <mymalloc.h> 89 #include <inet_addr_list.h> 90 #include <iostuff.h> 91 #include <timed_connect.h> 92 #include <stringops.h> 93 #include <host_port.h> 94 #include <sane_connect.h> 95 #include <myaddrinfo.h> 96 #include <sock_addr.h> 97 #include <inet_proto.h> 98 99 /* Global library. */ 100 101 #include <mail_params.h> 102 #include <own_inet_addr.h> 103 #include <deliver_pass.h> 104 #include <mail_error.h> 105 #include <dsn_buf.h> 106 #include <mail_addr.h> 107 108 /* DNS library. */ 109 110 #include <dns.h> 111 112 /* Application-specific. */ 113 114 #include <smtp.h> 115 #include <smtp_addr.h> 116 #include <smtp_reuse.h> 117 118 /* 119 * Forward declaration. 120 */ 121 static SMTP_SESSION *smtp_connect_sock(int, struct sockaddr *, int, 122 SMTP_ITERATOR *, DSN_BUF *, 123 int); 124 125 /* smtp_connect_unix - connect to UNIX-domain address */ 126 127 static SMTP_SESSION *smtp_connect_unix(SMTP_ITERATOR *iter, DSN_BUF *why, 128 int sess_flags) 129 { 130 const char *myname = "smtp_connect_unix"; 131 struct sockaddr_un sock_un; 132 const char *addr = STR(iter->addr); 133 int len = strlen(addr); 134 int sock; 135 136 dsb_reset(why); /* Paranoia */ 137 138 /* 139 * Sanity checks. 140 */ 141 if (len >= (int) sizeof(sock_un.sun_path)) { 142 msg_warn("unix-domain name too long: %s", addr); 143 dsb_simple(why, "4.3.5", "Server configuration error"); 144 return (0); 145 } 146 147 /* 148 * Initialize. 149 */ 150 memset((void *) &sock_un, 0, sizeof(sock_un)); 151 sock_un.sun_family = AF_UNIX; 152 #ifdef HAS_SUN_LEN 153 sock_un.sun_len = len + 1; 154 #endif 155 memcpy(sock_un.sun_path, addr, len + 1); 156 157 /* 158 * Create a client socket. 159 */ 160 if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) 161 msg_fatal("%s: socket: %m", myname); 162 163 /* 164 * Connect to the server. 165 */ 166 if (msg_verbose) 167 msg_info("%s: trying: %s...", myname, addr); 168 169 return (smtp_connect_sock(sock, (struct sockaddr *) &sock_un, 170 sizeof(sock_un), iter, why, sess_flags)); 171 } 172 173 /* smtp_connect_addr - connect to explicit address */ 174 175 static SMTP_SESSION *smtp_connect_addr(SMTP_ITERATOR *iter, DSN_BUF *why, 176 int sess_flags) 177 { 178 const char *myname = "smtp_connect_addr"; 179 struct sockaddr_storage ss; /* remote */ 180 struct sockaddr *sa = (struct sockaddr *) &ss; 181 SOCKADDR_SIZE salen = sizeof(ss); 182 MAI_HOSTADDR_STR hostaddr; 183 DNS_RR *addr = iter->rr; 184 unsigned port = iter->port; 185 int sock; 186 char *bind_addr; 187 char *bind_var; 188 189 dsb_reset(why); /* Paranoia */ 190 191 /* 192 * Sanity checks. 193 */ 194 if (dns_rr_to_sa(addr, port, sa, &salen) != 0) { 195 msg_warn("%s: skip address type %s: %m", 196 myname, dns_strtype(addr->type)); 197 dsb_simple(why, "4.4.0", "network address conversion failed: %m"); 198 return (0); 199 } 200 201 /* 202 * Initialize. 203 */ 204 if ((sock = socket(sa->sa_family, SOCK_STREAM, 0)) < 0) 205 msg_fatal("%s: socket: %m", myname); 206 207 if (inet_windowsize > 0) 208 set_inet_windowsize(sock, inet_windowsize); 209 210 /* 211 * Allow the sysadmin to specify the source address, for example, as "-o 212 * smtp_bind_address=x.x.x.x" in the master.cf file. 213 */ 214 #ifdef HAS_IPV6 215 if (sa->sa_family == AF_INET6) { 216 bind_addr = var_smtp_bind_addr6; 217 bind_var = VAR_LMTP_SMTP(BIND_ADDR6); 218 } else 219 #endif 220 if (sa->sa_family == AF_INET) { 221 bind_addr = var_smtp_bind_addr; 222 bind_var = VAR_LMTP_SMTP(BIND_ADDR); 223 } else 224 bind_var = bind_addr = ""; 225 if (*bind_addr) { 226 int aierr; 227 struct addrinfo *res0; 228 229 if ((aierr = hostaddr_to_sockaddr(bind_addr, (char *) 0, 0, &res0)) != 0) 230 msg_fatal("%s: bad %s parameter: %s: %s", 231 myname, bind_var, bind_addr, MAI_STRERROR(aierr)); 232 if (bind(sock, res0->ai_addr, res0->ai_addrlen) < 0) 233 msg_warn("%s: bind %s: %m", myname, bind_addr); 234 else if (msg_verbose) 235 msg_info("%s: bind %s", myname, bind_addr); 236 freeaddrinfo(res0); 237 } 238 239 /* 240 * When running as a virtual host, bind to the virtual interface so that 241 * the mail appears to come from the "right" machine address. 242 * 243 * XXX The IPv6 patch expands the null host (as client endpoint) and uses 244 * the result as the loopback address list. 245 */ 246 else { 247 int count = 0; 248 struct sockaddr *own_addr = 0; 249 INET_ADDR_LIST *addr_list = own_inet_addr_list(); 250 struct sockaddr_storage *s; 251 252 for (s = addr_list->addrs; s < addr_list->addrs + addr_list->used; s++) { 253 if (SOCK_ADDR_FAMILY(s) == sa->sa_family) { 254 if (count++ > 0) 255 break; 256 own_addr = SOCK_ADDR_PTR(s); 257 } 258 } 259 if (count == 1 && !sock_addr_in_loopback(own_addr)) { 260 if (bind(sock, own_addr, SOCK_ADDR_LEN(own_addr)) < 0) { 261 SOCKADDR_TO_HOSTADDR(own_addr, SOCK_ADDR_LEN(own_addr), 262 &hostaddr, (MAI_SERVPORT_STR *) 0, 0); 263 msg_warn("%s: bind %s: %m", myname, hostaddr.buf); 264 } else if (msg_verbose) { 265 SOCKADDR_TO_HOSTADDR(own_addr, SOCK_ADDR_LEN(own_addr), 266 &hostaddr, (MAI_SERVPORT_STR *) 0, 0); 267 msg_info("%s: bind %s", myname, hostaddr.buf); 268 } 269 } 270 } 271 272 /* 273 * Connect to the server. 274 */ 275 if (msg_verbose) 276 msg_info("%s: trying: %s[%s] port %d...", 277 myname, STR(iter->host), STR(iter->addr), ntohs(port)); 278 279 return (smtp_connect_sock(sock, sa, salen, iter, why, sess_flags)); 280 } 281 282 /* smtp_connect_sock - connect a socket over some transport */ 283 284 static SMTP_SESSION *smtp_connect_sock(int sock, struct sockaddr *sa, 285 int salen, 286 SMTP_ITERATOR *iter, 287 DSN_BUF *why, 288 int sess_flags) 289 { 290 int conn_stat; 291 int saved_errno; 292 VSTREAM *stream; 293 time_t start_time; 294 const char *name = STR(iter->host); 295 const char *addr = STR(iter->addr); 296 unsigned port = iter->port; 297 298 start_time = time((time_t *) 0); 299 if (var_smtp_conn_tmout > 0) { 300 non_blocking(sock, NON_BLOCKING); 301 conn_stat = timed_connect(sock, sa, salen, var_smtp_conn_tmout); 302 saved_errno = errno; 303 non_blocking(sock, BLOCKING); 304 errno = saved_errno; 305 } else { 306 conn_stat = sane_connect(sock, sa, salen); 307 } 308 if (conn_stat < 0) { 309 if (port) 310 dsb_simple(why, "4.4.1", "connect to %s[%s]:%d: %m", 311 name, addr, ntohs(port)); 312 else 313 dsb_simple(why, "4.4.1", "connect to %s[%s]: %m", name, addr); 314 close(sock); 315 return (0); 316 } 317 stream = vstream_fdopen(sock, O_RDWR); 318 319 /* 320 * Avoid poor performance when TCP MSS > VSTREAM_BUFSIZE. 321 */ 322 if (sa->sa_family == AF_INET 323 #ifdef AF_INET6 324 || sa->sa_family == AF_INET6 325 #endif 326 ) 327 vstream_tweak_tcp(stream); 328 329 /* 330 * Bundle up what we have into a nice SMTP_SESSION object. 331 */ 332 return (smtp_session_alloc(stream, iter, start_time, sess_flags)); 333 } 334 335 /* smtp_parse_destination - parse host/port destination */ 336 337 static char *smtp_parse_destination(char *destination, char *def_service, 338 char **hostp, unsigned *portp) 339 { 340 char *buf = mystrdup(destination); 341 char *service; 342 struct servent *sp; 343 char *protocol = "tcp"; /* XXX configurable? */ 344 unsigned port; 345 const char *err; 346 347 if (msg_verbose) 348 msg_info("smtp_parse_destination: %s %s", destination, def_service); 349 350 /* 351 * Parse the host/port information. We're working with a copy of the 352 * destination argument so the parsing can be destructive. 353 */ 354 if ((err = host_port(buf, hostp, (char *) 0, &service, def_service)) != 0) 355 msg_fatal("%s in server description: %s", err, destination); 356 357 /* 358 * Convert service to port number, network byte order. 359 */ 360 if (alldig(service)) { 361 if ((port = atoi(service)) >= 65536 || port == 0) 362 msg_fatal("bad network port in destination: %s", destination); 363 *portp = htons(port); 364 } else { 365 if ((sp = getservbyname(service, protocol)) == 0) 366 msg_fatal("unknown service: %s/%s", service, protocol); 367 *portp = sp->s_port; 368 } 369 return (buf); 370 } 371 372 /* smtp_cleanup_session - clean up after using a session */ 373 374 static void smtp_cleanup_session(SMTP_STATE *state) 375 { 376 DELIVER_REQUEST *request = state->request; 377 SMTP_SESSION *session = state->session; 378 int throttled; 379 380 /* 381 * Inform the postmaster of trouble. 382 * 383 * XXX Don't send notifications about errors while sending notifications. 384 */ 385 #define POSSIBLE_NOTIFICATION(sender) \ 386 (*sender == 0 || strcmp(sender, mail_addr_double_bounce()) == 0) 387 388 if (session->history != 0 389 && (session->error_mask & name_mask(VAR_NOTIFY_CLASSES, 390 mail_error_masks, 391 var_notify_classes)) != 0 392 && POSSIBLE_NOTIFICATION(request->sender) == 0) 393 smtp_chat_notify(session); 394 395 /* 396 * When session caching is enabled, cache the first good session for this 397 * delivery request under the next-hop destination, and cache all good 398 * sessions under their server network address (destroying the session in 399 * the process). 400 * 401 * Caching under the next-hop destination name (rather than the fall-back 402 * destination) allows us to skip over non-responding primary or backup 403 * hosts. In fact, this is the only benefit of caching logical to 404 * physical bindings; caching a session under its own hostname provides 405 * no performance benefit, given the way smtp_connect() works. 406 */ 407 throttled = THIS_SESSION_IS_THROTTLED; /* smtp_quit() may fail */ 408 if (THIS_SESSION_IS_EXPIRED) 409 smtp_quit(state); /* also disables caching */ 410 if (THIS_SESSION_IS_CACHED 411 /* Redundant tests for safety... */ 412 && vstream_ferror(session->stream) == 0 413 && vstream_feof(session->stream) == 0) { 414 smtp_save_session(state, SMTP_KEY_MASK_SCACHE_DEST_LABEL, 415 SMTP_KEY_MASK_SCACHE_ENDP_LABEL); 416 } else { 417 smtp_session_free(session); 418 } 419 state->session = 0; 420 421 /* 422 * If this session was good, reset the scache next-hop destination, so 423 * that we won't cache connections to less-preferred servers under the 424 * same next-hop destination. Otherwise we could end up skipping over the 425 * available and more-preferred servers. 426 */ 427 if (HAVE_SCACHE_REQUEST_NEXTHOP(state) && !throttled) 428 CLEAR_SCACHE_REQUEST_NEXTHOP(state); 429 430 /* 431 * Clean up the lists with todo and dropped recipients. 432 */ 433 smtp_rcpt_cleanup(state); 434 435 /* 436 * Reset profiling info. 437 * 438 * XXX When one delivery request results in multiple sessions, the set-up 439 * and transmission latencies of the earlier sessions will count as 440 * connection set-up time for the later sessions. 441 * 442 * XXX On the other hand, when we first try to connect to one or more dead 443 * hosts before we reach a good host, then all that time must be counted 444 * as connection set-up time for the session with the good host. 445 * 446 * XXX So this set-up attribution problem exists only when we actually 447 * engage in a session, spend a lot of time delivering a message, find 448 * that it fails, and then connect to an alternate host. 449 */ 450 memset((void *) &request->msg_stats.conn_setup_done, 0, 451 sizeof(request->msg_stats.conn_setup_done)); 452 memset((void *) &request->msg_stats.deliver_done, 0, 453 sizeof(request->msg_stats.deliver_done)); 454 request->msg_stats.reuse_count = 0; 455 } 456 457 static void smtp_cache_policy(SMTP_STATE *state, const char *dest) 458 { 459 DELIVER_REQUEST *request = state->request; 460 461 state->misc_flags &= ~SMTP_MISC_FLAG_CONN_CACHE_MASK; 462 463 if (smtp_cache_dest && string_list_match(smtp_cache_dest, dest)) { 464 state->misc_flags |= SMTP_MISC_FLAG_CONN_CACHE_MASK; 465 } else if (var_smtp_cache_demand) { 466 if (request->flags & DEL_REQ_FLAG_CONN_LOAD) 467 state->misc_flags |= SMTP_MISC_FLAG_CONN_LOAD; 468 if (request->flags & DEL_REQ_FLAG_CONN_STORE) 469 state->misc_flags |= SMTP_MISC_FLAG_CONN_STORE; 470 } 471 } 472 473 /* smtp_connect_local - connect to local server */ 474 475 static void smtp_connect_local(SMTP_STATE *state, const char *path) 476 { 477 const char *myname = "smtp_connect_local"; 478 SMTP_ITERATOR *iter = state->iterator; 479 SMTP_SESSION *session; 480 DSN_BUF *why = state->why; 481 482 /* 483 * Do not silently ignore an unused setting. 484 */ 485 if (*var_fallback_relay) 486 msg_warn("ignoring \"%s = %s\" setting for non-TCP connections", 487 VAR_LMTP_FALLBACK, var_fallback_relay); 488 489 /* 490 * It's too painful to weave this code into the SMTP connection 491 * management routine. 492 * 493 * Connection cache management is based on the UNIX-domain pathname, without 494 * the "unix:" prefix. 495 */ 496 smtp_cache_policy(state, path); 497 if (state->misc_flags & SMTP_MISC_FLAG_CONN_CACHE_MASK) 498 SET_SCACHE_REQUEST_NEXTHOP(state, path); 499 500 /* 501 * Here we ensure that the iter->addr member refers to a copy of the 502 * UNIX-domain pathname, so that smtp_save_session() will cache the 503 * connection using the pathname as the physical endpoint name. 504 * 505 * We set dest=path for backwards compatibility. 506 */ 507 #define NO_PORT 0 508 509 SMTP_ITER_INIT(iter, path, var_myhostname, path, NO_PORT, state); 510 511 /* 512 * Opportunistic TLS for unix domain sockets does not make much sense, 513 * since the channel is private, mere encryption without authentication 514 * is just wasted cycles and opportunity for breakage. Since we are not 515 * willing to retry after TLS handshake failures here, we downgrade "may" 516 * no "none". Nothing is lost, and much waste is avoided. 517 * 518 * We don't know who is authenticating whom, so if a client cert is 519 * available, "encrypt" may be a sensible policy. Otherwise, we also 520 * downgrade "encrypt" to "none", this time just to avoid waste. 521 * 522 * We use smtp_reuse_nexthop() instead of smtp_reuse_addr(), so that we can 523 * reuse a SASL-authenticated connection (however unlikely this scenario 524 * may be). The smtp_reuse_addr() interface currently supports only reuse 525 * of SASL-unauthenticated connections. 526 */ 527 #ifdef USE_TLS 528 if (!smtp_tls_policy_cache_query(why, state->tls, iter)) { 529 msg_warn("TLS policy lookup error for %s/%s: %s", 530 STR(iter->host), STR(iter->addr), STR(why->reason)); 531 return; 532 } 533 #endif 534 if ((state->misc_flags & SMTP_MISC_FLAG_CONN_LOAD) == 0 535 || (session = smtp_reuse_nexthop(state, 536 SMTP_KEY_MASK_SCACHE_DEST_LABEL)) == 0) 537 session = smtp_connect_unix(iter, why, state->misc_flags); 538 if ((state->session = session) != 0) { 539 session->state = state; 540 #ifdef USE_TLS 541 session->tls_nexthop = var_myhostname; /* for TLS_LEV_SECURE */ 542 if (state->tls->level == TLS_LEV_MAY) { 543 msg_warn("%s: opportunistic TLS encryption is not appropriate " 544 "for unix-domain destinations.", myname); 545 state->tls->level = TLS_LEV_NONE; 546 } 547 #endif 548 /* All delivery errors bounce or defer. */ 549 state->misc_flags |= SMTP_MISC_FLAG_FINAL_SERVER; 550 551 /* 552 * When a TLS handshake fails, the stream is marked "dead" to avoid 553 * further I/O over a broken channel. 554 */ 555 if ((session->features & SMTP_FEATURE_FROM_CACHE) == 0 556 && smtp_helo(state) != 0) { 557 if (!THIS_SESSION_IS_FORBIDDEN 558 && vstream_ferror(session->stream) == 0 559 && vstream_feof(session->stream) == 0) 560 smtp_quit(state); 561 } else { 562 smtp_xfer(state); 563 } 564 565 /* 566 * With opportunistic TLS disabled we don't expect to be asked to 567 * retry connections without TLS, and so we expect the final server 568 * flag to stay on. 569 */ 570 if ((state->misc_flags & SMTP_MISC_FLAG_FINAL_SERVER) == 0) 571 msg_panic("%s: unix-domain destination not final!", myname); 572 smtp_cleanup_session(state); 573 } 574 575 /* 576 * Cleanup. 577 */ 578 if (HAVE_SCACHE_REQUEST_NEXTHOP(state)) 579 CLEAR_SCACHE_REQUEST_NEXTHOP(state); 580 } 581 582 /* smtp_scrub_address_list - delete all cached addresses from list */ 583 584 static void smtp_scrub_addr_list(HTABLE *cached_addr, DNS_RR **addr_list) 585 { 586 MAI_HOSTADDR_STR hostaddr; 587 DNS_RR *addr; 588 DNS_RR *next; 589 590 /* 591 * XXX Extend the DNS_RR structure with fields for the printable address 592 * and/or binary sockaddr representations, so that we can avoid repeated 593 * binary->string transformations for the same address. 594 */ 595 for (addr = *addr_list; addr; addr = next) { 596 next = addr->next; 597 if (dns_rr_to_pa(addr, &hostaddr) == 0) { 598 msg_warn("cannot convert type %s record to printable address", 599 dns_strtype(addr->type)); 600 continue; 601 } 602 if (htable_locate(cached_addr, hostaddr.buf)) 603 *addr_list = dns_rr_remove(*addr_list, addr); 604 } 605 } 606 607 /* smtp_update_addr_list - common address list update */ 608 609 static void smtp_update_addr_list(DNS_RR **addr_list, const char *server_addr, 610 int session_count) 611 { 612 DNS_RR *addr; 613 DNS_RR *next; 614 int aierr; 615 struct addrinfo *res0; 616 617 if (*addr_list == 0) 618 return; 619 620 /* 621 * Truncate the address list if we are not going to use it anyway. 622 */ 623 if (session_count == var_smtp_mxsess_limit 624 || session_count == var_smtp_mxaddr_limit) { 625 dns_rr_free(*addr_list); 626 *addr_list = 0; 627 return; 628 } 629 630 /* 631 * Convert server address to internal form, and look it up in the address 632 * list. 633 * 634 * XXX smtp_reuse_session() breaks if we remove two or more adjacent list 635 * elements but do not truncate the list to zero length. 636 * 637 * XXX Extend the SMTP_SESSION structure with sockaddr information so that 638 * we can avoid repeated string->binary transformations for the same 639 * address. 640 */ 641 if ((aierr = hostaddr_to_sockaddr(server_addr, (char *) 0, 0, &res0)) != 0) { 642 msg_warn("hostaddr_to_sockaddr %s: %s", 643 server_addr, MAI_STRERROR(aierr)); 644 } else { 645 for (addr = *addr_list; addr; addr = next) { 646 next = addr->next; 647 if (DNS_RR_EQ_SA(addr, (struct sockaddr *) res0->ai_addr)) { 648 *addr_list = dns_rr_remove(*addr_list, addr); 649 break; 650 } 651 } 652 freeaddrinfo(res0); 653 } 654 } 655 656 /* smtp_reuse_session - try to use existing connection, return session count */ 657 658 static int smtp_reuse_session(SMTP_STATE *state, DNS_RR **addr_list, 659 int domain_best_pref) 660 { 661 int session_count = 0; 662 DNS_RR *addr; 663 DNS_RR *next; 664 MAI_HOSTADDR_STR hostaddr; 665 SMTP_SESSION *session; 666 SMTP_ITERATOR *iter = state->iterator; 667 DSN_BUF *why = state->why; 668 669 /* 670 * First, search the cache by delivery request nexthop. We truncate the 671 * server address list when all the sessions for this destination are 672 * used up, to reduce the number of variables that need to be checked 673 * later. 674 * 675 * Note: connection reuse by delivery request nexthop restores the "best MX" 676 * bit. 677 * 678 * smtp_reuse_nexthop() clobbers the iterators's "dest" attribute. We save 679 * and restore it here, so that subsequent connections will use the 680 * proper nexthop information. 681 * 682 * We don't use TLS level info for nexthop-based connection cache storage 683 * keys. The combination of (service, nexthop, etc.) should be stable 684 * over the time range of interest, and the policy is still enforced on 685 * an individual connection to an MX host, before that connection is 686 * stored under a nexthop- or host-based storage key. 687 */ 688 #ifdef USE_TLS 689 smtp_tls_policy_dummy(state->tls); 690 #endif 691 SMTP_ITER_SAVE_DEST(state->iterator); 692 if (*addr_list && SMTP_RCPT_LEFT(state) > 0 693 && HAVE_SCACHE_REQUEST_NEXTHOP(state) 694 && (session = smtp_reuse_nexthop(state, SMTP_KEY_MASK_SCACHE_DEST_LABEL)) != 0) { 695 session_count = 1; 696 smtp_update_addr_list(addr_list, STR(iter->addr), session_count); 697 if ((state->misc_flags & SMTP_MISC_FLAG_FINAL_NEXTHOP) 698 && *addr_list == 0) 699 state->misc_flags |= SMTP_MISC_FLAG_FINAL_SERVER; 700 smtp_xfer(state); 701 smtp_cleanup_session(state); 702 } 703 SMTP_ITER_RESTORE_DEST(state->iterator); 704 705 /* 706 * Second, search the cache by primary MX address. Again, we use address 707 * list truncation so that we have to check fewer variables later. 708 * 709 * XXX This loop is safe because smtp_update_addr_list() either truncates 710 * the list to zero length, or removes at most one list element. 711 * 712 * Currently, we use smtp_reuse_addr() only for SASL-unauthenticated 713 * connections. Furthermore, we rely on smtp_reuse_addr() to look up an 714 * existing SASL-unauthenticated connection only when a new connection 715 * would be guaranteed not to require SASL authentication. 716 * 717 * In addition, we rely on smtp_reuse_addr() to look up an existing 718 * plaintext connection only when a new connection would be guaranteed 719 * not to use TLS. 720 * 721 * For more precise control over reuse, the iterator should look up SASL and 722 * TLS policy as it evaluates mail exchangers in order, instead of 723 * relying on duplicate lookup request code in smtp_reuse(3) and 724 * smtp_session(3). 725 */ 726 for (addr = *addr_list; SMTP_RCPT_LEFT(state) > 0 && addr; addr = next) { 727 if (addr->pref != domain_best_pref) 728 break; 729 next = addr->next; 730 if (dns_rr_to_pa(addr, &hostaddr) == 0) { 731 msg_warn("cannot convert type %s record to printable address", 732 dns_strtype(addr->type)); 733 /* XXX Assume there is no code at the end of this loop. */ 734 continue; 735 } 736 vstring_strcpy(iter->addr, hostaddr.buf); 737 vstring_strcpy(iter->host, SMTP_HNAME(addr)); 738 iter->rr = addr; 739 #ifdef USE_TLS 740 if (!smtp_tls_policy_cache_query(why, state->tls, iter)) { 741 msg_warn("TLS policy lookup error for %s/%s: %s", 742 STR(iter->dest), STR(iter->host), STR(why->reason)); 743 continue; 744 /* XXX Assume there is no code at the end of this loop. */ 745 } 746 #endif 747 if ((session = smtp_reuse_addr(state, 748 SMTP_KEY_MASK_SCACHE_ENDP_LABEL)) != 0) { 749 session->features |= SMTP_FEATURE_BEST_MX; 750 session_count += 1; 751 smtp_update_addr_list(addr_list, STR(iter->addr), session_count); 752 if (*addr_list == 0) 753 next = 0; 754 if ((state->misc_flags & SMTP_MISC_FLAG_FINAL_NEXTHOP) 755 && next == 0) 756 state->misc_flags |= SMTP_MISC_FLAG_FINAL_SERVER; 757 smtp_xfer(state); 758 smtp_cleanup_session(state); 759 } 760 } 761 return (session_count); 762 } 763 764 /* smtp_connect_inet - establish network connection */ 765 766 static void smtp_connect_inet(SMTP_STATE *state, const char *nexthop, 767 char *def_service) 768 { 769 DELIVER_REQUEST *request = state->request; 770 SMTP_ITERATOR *iter = state->iterator; 771 ARGV *sites; 772 char *dest; 773 char **cpp; 774 int non_fallback_sites; 775 int retry_plain = 0; 776 DSN_BUF *why = state->why; 777 778 /* 779 * For sanity, require that at least one of INET or INET6 is enabled. 780 * Otherwise, we can't look up interface information, and we can't 781 * convert names or addresses. 782 */ 783 if (inet_proto_info()->ai_family_list[0] == 0) { 784 dsb_simple(why, "4.4.4", "all network protocols are disabled"); 785 return; 786 } 787 788 /* 789 * Do a null destination sanity check in case the primary destination is 790 * a list that consists of only separators. 791 */ 792 sites = argv_split(nexthop, CHARS_COMMA_SP); 793 if (sites->argc == 0) 794 msg_panic("null destination: \"%s\"", nexthop); 795 non_fallback_sites = sites->argc; 796 argv_split_append(sites, var_fallback_relay, CHARS_COMMA_SP); 797 798 /* 799 * Don't give up after a hard host lookup error until we have tried the 800 * fallback relay servers. 801 * 802 * Don't bounce mail after a host lookup problem with a relayhost or with a 803 * fallback relay. 804 * 805 * Don't give up after a qualifying soft error until we have tried all 806 * qualifying backup mail servers. 807 * 808 * All this means that error handling and error reporting depends on whether 809 * the error qualifies for trying to deliver to a backup mail server, or 810 * whether we're looking up a relayhost or fallback relay. The challenge 811 * then is to build this into the pre-existing SMTP client without 812 * getting lost in the complexity. 813 */ 814 #define IS_FALLBACK_RELAY(cpp, sites, non_fallback_sites) \ 815 (*(cpp) && (cpp) >= (sites)->argv + (non_fallback_sites)) 816 817 for (cpp = sites->argv, (state->misc_flags |= SMTP_MISC_FLAG_FIRST_NEXTHOP); 818 SMTP_RCPT_LEFT(state) > 0 && (dest = *cpp) != 0; 819 cpp++, (state->misc_flags &= ~SMTP_MISC_FLAG_FIRST_NEXTHOP)) { 820 char *dest_buf; 821 char *domain; 822 unsigned port; 823 DNS_RR *addr_list; 824 DNS_RR *addr; 825 DNS_RR *next; 826 int addr_count; 827 int sess_count; 828 SMTP_SESSION *session; 829 int lookup_mx; 830 unsigned domain_best_pref; 831 MAI_HOSTADDR_STR hostaddr; 832 833 if (cpp[1] == 0) 834 state->misc_flags |= SMTP_MISC_FLAG_FINAL_NEXTHOP; 835 836 /* 837 * Parse the destination. If no TCP port is specified, use the port 838 * that is reserved for the protocol (SMTP or LMTP). 839 */ 840 dest_buf = smtp_parse_destination(dest, def_service, &domain, &port); 841 if (var_helpful_warnings && var_smtp_tls_wrappermode == 0 842 && ntohs(port) == 465) { 843 msg_info("SMTPS wrappermode (TCP port 465) requires setting " 844 "\"%s = yes\", and \"%s = encrypt\" (or stronger)", 845 VAR_LMTP_SMTP(TLS_WRAPPER), VAR_LMTP_SMTP(TLS_LEVEL)); 846 } 847 #define NO_HOST "" /* safety */ 848 #define NO_ADDR "" /* safety */ 849 850 SMTP_ITER_INIT(iter, dest, NO_HOST, NO_ADDR, port, state); 851 852 /* 853 * Resolve an SMTP or LMTP server. In the case of SMTP, skip mail 854 * exchanger lookups when a quoted host is specified or when DNS 855 * lookups are disabled. 856 */ 857 if (msg_verbose) 858 msg_info("connecting to %s port %d", domain, ntohs(port)); 859 if (smtp_mode) { 860 if (ntohs(port) == IPPORT_SMTP) 861 state->misc_flags |= SMTP_MISC_FLAG_LOOP_DETECT; 862 else 863 state->misc_flags &= ~SMTP_MISC_FLAG_LOOP_DETECT; 864 lookup_mx = (smtp_dns_support != SMTP_DNS_DISABLED && *dest != '['); 865 } else 866 lookup_mx = 0; 867 if (!lookup_mx) { 868 addr_list = smtp_host_addr(domain, state->misc_flags, why); 869 /* XXX We could be an MX host for this destination... */ 870 } else { 871 int i_am_mx = 0; 872 873 addr_list = smtp_domain_addr(domain, &iter->mx, state->misc_flags, 874 why, &i_am_mx); 875 /* If we're MX host, don't connect to non-MX backups. */ 876 if (i_am_mx) 877 state->misc_flags |= SMTP_MISC_FLAG_FINAL_NEXTHOP; 878 } 879 880 /* 881 * Don't try fall-back hosts if mail loops to myself. That would just 882 * make the problem worse. 883 */ 884 if (addr_list == 0 && SMTP_HAS_LOOP_DSN(why)) 885 state->misc_flags |= SMTP_MISC_FLAG_FINAL_NEXTHOP; 886 887 /* 888 * No early loop exit or we have a memory leak with dest_buf. 889 */ 890 if (addr_list) 891 domain_best_pref = addr_list->pref; 892 893 /* 894 * When connection caching is enabled, store the first good 895 * connection for this delivery request under the delivery request 896 * next-hop name. Good connections will also be stored under their 897 * specific server IP address. 898 * 899 * XXX smtp_session_cache_destinations specifies domain names without 900 * :port, because : is already used for maptype:mapname. Because of 901 * this limitation we use the bare domain without the optional [] or 902 * non-default TCP port. 903 * 904 * Opportunistic (a.k.a. on-demand) session caching on request by the 905 * queue manager. This is turned temporarily when a destination has a 906 * high volume of mail in the active queue. When the surge reaches 907 * its end, the queue manager requests that connections be retrieved 908 * but not stored. 909 */ 910 if (addr_list && (state->misc_flags & SMTP_MISC_FLAG_FIRST_NEXTHOP)) { 911 smtp_cache_policy(state, domain); 912 if (state->misc_flags & SMTP_MISC_FLAG_CONN_CACHE_MASK) 913 SET_SCACHE_REQUEST_NEXTHOP(state, dest); 914 } 915 916 /* 917 * Delete visited cached hosts from the address list. 918 * 919 * Optionally search the connection cache by domain name or by primary 920 * MX address before we try to create new connections. 921 * 922 * Enforce the MX session and MX address counts per next-hop or 923 * fall-back destination. smtp_reuse_session() will truncate the 924 * address list when either limit is reached. 925 */ 926 if (addr_list && (state->misc_flags & SMTP_MISC_FLAG_CONN_LOAD)) { 927 if (state->cache_used->used > 0) 928 smtp_scrub_addr_list(state->cache_used, &addr_list); 929 sess_count = addr_count = 930 smtp_reuse_session(state, &addr_list, domain_best_pref); 931 } else 932 sess_count = addr_count = 0; 933 934 /* 935 * Connect to an SMTP server: create primary MX connections, and 936 * reuse or create backup MX connections. 937 * 938 * At the start of an SMTP session, all recipients are unmarked. In the 939 * course of an SMTP session, recipients are marked as KEEP (deliver 940 * to alternate mail server) or DROP (remove from recipient list). At 941 * the end of an SMTP session, weed out the recipient list. Unmark 942 * any left-over recipients and try to deliver them to a backup mail 943 * server. 944 * 945 * Cache the first good session under the next-hop destination name. 946 * Cache all good sessions under their physical endpoint. 947 * 948 * Don't query the session cache for primary MX hosts. We already did 949 * that in smtp_reuse_session(), and if any were found in the cache, 950 * they were already deleted from the address list. 951 * 952 * Currently, we use smtp_reuse_addr() only for SASL-unauthenticated 953 * connections. Furthermore, we rely on smtp_reuse_addr() to look up 954 * an existing SASL-unauthenticated connection only when a new 955 * connection would be guaranteed not to require SASL authentication. 956 * 957 * In addition, we rely on smtp_reuse_addr() to look up an existing 958 * plaintext connection only when a new connection would be 959 * guaranteed not to use TLS. 960 */ 961 for (addr = addr_list; SMTP_RCPT_LEFT(state) > 0 && addr; addr = next) { 962 next = addr->next; 963 if (++addr_count == var_smtp_mxaddr_limit) 964 next = 0; 965 if (dns_rr_to_pa(addr, &hostaddr) == 0) { 966 msg_warn("cannot convert type %s record to printable address", 967 dns_strtype(addr->type)); 968 /* XXX Assume there is no code at the end of this loop. */ 969 continue; 970 } 971 vstring_strcpy(iter->addr, hostaddr.buf); 972 vstring_strcpy(iter->host, SMTP_HNAME(addr)); 973 iter->rr = addr; 974 #ifdef USE_TLS 975 if (!smtp_tls_policy_cache_query(why, state->tls, iter)) { 976 msg_warn("TLS policy lookup for %s/%s: %s", 977 STR(iter->dest), STR(iter->host), STR(why->reason)); 978 continue; 979 /* XXX Assume there is no code at the end of this loop. */ 980 } 981 if (var_smtp_tls_wrappermode 982 && state->tls->level < TLS_LEV_ENCRYPT) { 983 msg_warn("%s requires \"%s = encrypt\" (or stronger)", 984 VAR_LMTP_SMTP(TLS_WRAPPER), VAR_LMTP_SMTP(TLS_LEVEL)); 985 continue; 986 /* XXX Assume there is no code at the end of this loop. */ 987 } 988 /* Disable TLS when retrying after a handshake failure */ 989 if (retry_plain) { 990 state->tls->level = TLS_LEV_NONE; 991 retry_plain = 0; 992 } 993 #endif 994 if ((state->misc_flags & SMTP_MISC_FLAG_CONN_LOAD) == 0 995 || addr->pref == domain_best_pref 996 || !(session = smtp_reuse_addr(state, 997 SMTP_KEY_MASK_SCACHE_ENDP_LABEL))) 998 session = smtp_connect_addr(iter, why, state->misc_flags); 999 if ((state->session = session) != 0) { 1000 session->state = state; 1001 #ifdef USE_TLS 1002 session->tls_nexthop = domain; 1003 #endif 1004 if (addr->pref == domain_best_pref) 1005 session->features |= SMTP_FEATURE_BEST_MX; 1006 /* Don't count handshake errors towards the session limit. */ 1007 if ((state->misc_flags & SMTP_MISC_FLAG_FINAL_NEXTHOP) 1008 && next == 0) 1009 state->misc_flags |= SMTP_MISC_FLAG_FINAL_SERVER; 1010 if ((session->features & SMTP_FEATURE_FROM_CACHE) == 0 1011 && smtp_helo(state) != 0) { 1012 #ifdef USE_TLS 1013 1014 /* 1015 * When an opportunistic TLS handshake fails, try the 1016 * same address again, with TLS disabled. See also the 1017 * RETRY_AS_PLAINTEXT macro. 1018 */ 1019 if ((retry_plain = session->tls_retry_plain) != 0) { 1020 --addr_count; 1021 next = addr; 1022 } 1023 #endif 1024 1025 /* 1026 * When a TLS handshake fails, the stream is marked 1027 * "dead" to avoid further I/O over a broken channel. 1028 */ 1029 if (!THIS_SESSION_IS_FORBIDDEN 1030 && vstream_ferror(session->stream) == 0 1031 && vstream_feof(session->stream) == 0) 1032 smtp_quit(state); 1033 } else { 1034 /* Do count delivery errors towards the session limit. */ 1035 if (++sess_count == var_smtp_mxsess_limit) 1036 next = 0; 1037 if ((state->misc_flags & SMTP_MISC_FLAG_FINAL_NEXTHOP) 1038 && next == 0) 1039 state->misc_flags |= SMTP_MISC_FLAG_FINAL_SERVER; 1040 smtp_xfer(state); 1041 #ifdef USE_TLS 1042 1043 /* 1044 * When opportunistic TLS fails after the STARTTLS 1045 * handshake, try the same address again, with TLS 1046 * disabled. See also the RETRY_AS_PLAINTEXT macro. 1047 */ 1048 if ((retry_plain = session->tls_retry_plain) != 0) { 1049 --sess_count; 1050 --addr_count; 1051 next = addr; 1052 } 1053 #endif 1054 } 1055 smtp_cleanup_session(state); 1056 } else { 1057 /* The reason already includes the IP address and TCP port. */ 1058 msg_info("%s", STR(why->reason)); 1059 } 1060 /* XXX Code above assumes there is no code at this loop ending. */ 1061 } 1062 dns_rr_free(addr_list); 1063 if (iter->mx) { 1064 dns_rr_free(iter->mx); 1065 iter->mx = 0; /* Just in case */ 1066 } 1067 myfree(dest_buf); 1068 if (state->misc_flags & SMTP_MISC_FLAG_FINAL_NEXTHOP) 1069 break; 1070 } 1071 1072 /* 1073 * We still need to deliver, bounce or defer some left-over recipients: 1074 * either mail loops or some backup mail server was unavailable. 1075 */ 1076 if (SMTP_RCPT_LEFT(state) > 0) { 1077 1078 /* 1079 * In case of a "no error" indication we make up an excuse: we did 1080 * find the host address, but we did not attempt to connect to it. 1081 * This can happen when the fall-back relay was already tried via a 1082 * cached connection, so that the address list scrubber left behind 1083 * an empty list. 1084 */ 1085 if (!SMTP_HAS_DSN(why)) { 1086 dsb_simple(why, "4.3.0", 1087 "server unavailable or unable to receive mail"); 1088 } 1089 1090 /* 1091 * Pay attention to what could be configuration problems, and pretend 1092 * that these are recoverable rather than bouncing the mail. 1093 */ 1094 else if (!SMTP_HAS_SOFT_DSN(why)) { 1095 1096 /* 1097 * The fall-back destination did not resolve as expected, or it 1098 * is refusing to talk to us, or mail for it loops back to us. 1099 */ 1100 if (IS_FALLBACK_RELAY(cpp, sites, non_fallback_sites)) { 1101 msg_warn("%s configuration problem", VAR_SMTP_FALLBACK); 1102 vstring_strcpy(why->status, "4.3.5"); 1103 /* XXX Keep the diagnostic code and MTA. */ 1104 } 1105 1106 /* 1107 * The next-hop relayhost did not resolve as expected, or it is 1108 * refusing to talk to us, or mail for it loops back to us. 1109 * 1110 * XXX There is no equivalent safety net for mis-configured 1111 * sender-dependent relay hosts. The trivial-rewrite resolver 1112 * would have to flag the result, and the queue manager would 1113 * have to provide that information to delivery agents. 1114 */ 1115 else if (smtp_mode && strcmp(sites->argv[0], var_relayhost) == 0) { 1116 msg_warn("%s configuration problem", VAR_RELAYHOST); 1117 vstring_strcpy(why->status, "4.3.5"); 1118 /* XXX Keep the diagnostic code and MTA. */ 1119 } 1120 1121 /* 1122 * Mail for the next-hop destination loops back to myself. Pass 1123 * the mail to the best_mx_transport or bounce it. 1124 */ 1125 else if (smtp_mode && SMTP_HAS_LOOP_DSN(why) && *var_bestmx_transp) { 1126 dsb_reset(why); /* XXX */ 1127 state->status = deliver_pass_all(MAIL_CLASS_PRIVATE, 1128 var_bestmx_transp, 1129 request); 1130 SMTP_RCPT_LEFT(state) = 0; /* XXX */ 1131 } 1132 } 1133 } 1134 1135 /* 1136 * Cleanup. 1137 */ 1138 if (HAVE_SCACHE_REQUEST_NEXTHOP(state)) 1139 CLEAR_SCACHE_REQUEST_NEXTHOP(state); 1140 argv_free(sites); 1141 } 1142 1143 /* smtp_connect - establish SMTP connection */ 1144 1145 int smtp_connect(SMTP_STATE *state) 1146 { 1147 DELIVER_REQUEST *request = state->request; 1148 char *destination = request->nexthop; 1149 1150 /* 1151 * All deliveries proceed along the same lines, whether they are over TCP 1152 * or UNIX-domain sockets, and whether they use SMTP or LMTP: get a 1153 * connection from the cache or create a new connection; deliver mail; 1154 * update the connection cache or disconnect. 1155 * 1156 * The major differences appear at a higher level: the expansion from 1157 * destination to address list, and whether to stop before we reach the 1158 * end of that list. 1159 */ 1160 1161 /* 1162 * With LMTP we have direct-to-host delivery only. The destination may 1163 * have multiple IP addresses. 1164 */ 1165 if (!smtp_mode) { 1166 if (strncmp(destination, "unix:", 5) == 0) { 1167 smtp_connect_local(state, destination + 5); 1168 } else { 1169 if (strncmp(destination, "inet:", 5) == 0) 1170 destination += 5; 1171 smtp_connect_inet(state, destination, var_smtp_tcp_port); 1172 } 1173 } 1174 1175 /* 1176 * XXX We don't add support for "unix:" or "inet:" prefixes in SMTP 1177 * destinations, because that would break compatibility with existing 1178 * Postfix configurations that have a host with such a name. 1179 */ 1180 else { 1181 smtp_connect_inet(state, destination, var_smtp_tcp_port); 1182 } 1183 1184 /* 1185 * We still need to bounce or defer some left-over recipients: either 1186 * (SMTP) mail loops or some server was unavailable. 1187 * 1188 * We could avoid this (and the "final server" complexity) by keeping one 1189 * DSN structure per recipient in memory, by updating those in-memory 1190 * structures with each delivery attempt, and by always flushing all 1191 * deferred recipients at the end. We'd probably still want to bounce 1192 * recipients immediately, so we'd end up with another chunk of code for 1193 * defer logging only. 1194 */ 1195 if (SMTP_RCPT_LEFT(state) > 0) { 1196 state->misc_flags |= SMTP_MISC_FLAG_FINAL_SERVER; /* XXX */ 1197 smtp_sess_fail(state); 1198 1199 /* 1200 * Sanity check. Don't silently lose recipients. 1201 */ 1202 smtp_rcpt_cleanup(state); 1203 if (SMTP_RCPT_LEFT(state) > 0) 1204 msg_panic("smtp_connect: left-over recipients"); 1205 } 1206 return (state->status); 1207 } 1208