1 /* 2 * Copyright (c) 1998-2010, 2012 Proofpoint, Inc. and its suppliers. 3 * All rights reserved. 4 * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. 5 * Copyright (c) 1988, 1993 6 * The Regents of the University of California. All rights reserved. 7 * 8 * By using this file, you agree to the terms and conditions set 9 * forth in the LICENSE file which can be found at the top level of 10 * the sendmail distribution. 11 * 12 */ 13 14 #include <sendmail.h> 15 #include <sm/time.h> 16 17 SM_RCSID("@(#)$Id: deliver.c,v 8.1030 2013-11-22 20:51:55 ca Exp $") 18 19 #include <sm/sendmail.h> 20 21 #if HASSETUSERCONTEXT 22 # include <login_cap.h> 23 #endif 24 25 #if NETINET || NETINET6 26 # include <arpa/inet.h> 27 #endif 28 29 #if STARTTLS || SASL 30 # include "sfsasl.h" 31 # include "tls.h" 32 #endif 33 34 static int deliver __P((ENVELOPE *, ADDRESS *)); 35 static void dup_queue_file __P((ENVELOPE *, ENVELOPE *, int)); 36 static void mailfiletimeout __P((int)); 37 static void endwaittimeout __P((int)); 38 static int parse_hostsignature __P((char *, char **, MAILER *)); 39 static void sendenvelope __P((ENVELOPE *, int)); 40 static int coloncmp __P((const char *, const char *)); 41 42 #if STARTTLS 43 # include <openssl/err.h> 44 # if DANE 45 static int starttls __P((MAILER *, MCI *, ENVELOPE *, dane_vrfy_ctx_P)); 46 # else 47 static int starttls __P((MAILER *, MCI *, ENVELOPE *)); 48 # endif 49 static int endtlsclt __P((MCI *)); 50 #endif /* STARTTLS */ 51 #if STARTTLS || SASL 52 static bool iscltflgset __P((ENVELOPE *, int)); 53 #endif 54 55 #if _FFR_OCC 56 # include <ratectrl.h> 57 #endif 58 59 #define ESCNULLMXRCPT "5.1.10" 60 #define ERRNULLMX "556 Host does not accept mail: MX 0 ." 61 62 /* 63 ** SENDALL -- actually send all the messages. 64 ** 65 ** Parameters: 66 ** e -- the envelope to send. 67 ** mode -- the delivery mode to use. If SM_DEFAULT, use 68 ** the current e->e_sendmode. 69 ** 70 ** Returns: 71 ** none. 72 ** 73 ** Side Effects: 74 ** Scans the send lists and sends everything it finds. 75 ** Delivers any appropriate error messages. 76 ** If we are running in a non-interactive mode, takes the 77 ** appropriate action. 78 */ 79 80 void 81 sendall(e, mode) 82 ENVELOPE *e; 83 int mode; 84 { 85 register ADDRESS *q; 86 char *owner; 87 int otherowners; 88 int save_errno; 89 register ENVELOPE *ee; 90 ENVELOPE *splitenv = NULL; 91 int oldverbose = Verbose; 92 bool somedeliveries = false, expensive = false; 93 pid_t pid; 94 95 /* 96 ** If this message is to be discarded, don't bother sending 97 ** the message at all. 98 */ 99 100 if (bitset(EF_DISCARD, e->e_flags)) 101 { 102 if (tTd(13, 1)) 103 sm_dprintf("sendall: discarding id %s\n", e->e_id); 104 e->e_flags |= EF_CLRQUEUE; 105 if (LogLevel > 9) 106 logundelrcpts(e, "discarded", 9, true); 107 else if (LogLevel > 4) 108 sm_syslog(LOG_INFO, e->e_id, "discarded"); 109 markstats(e, NULL, STATS_REJECT); 110 return; 111 } 112 113 /* 114 ** If we have had global, fatal errors, don't bother sending 115 ** the message at all if we are in SMTP mode. Local errors 116 ** (e.g., a single address failing) will still cause the other 117 ** addresses to be sent. 118 */ 119 120 if (bitset(EF_FATALERRS, e->e_flags) && 121 (OpMode == MD_SMTP || OpMode == MD_DAEMON)) 122 { 123 e->e_flags |= EF_CLRQUEUE; 124 return; 125 } 126 127 /* determine actual delivery mode */ 128 if (mode == SM_DEFAULT) 129 { 130 mode = e->e_sendmode; 131 if (mode != SM_VERIFY && mode != SM_DEFER && 132 shouldqueue(e->e_msgpriority, e->e_ctime)) 133 mode = SM_QUEUE; 134 } 135 136 if (tTd(13, 1)) 137 { 138 sm_dprintf("\n===== SENDALL: mode %c, id %s, e_from ", 139 mode, e->e_id); 140 printaddr(sm_debug_file(), &e->e_from, false); 141 sm_dprintf("\te_flags = "); 142 printenvflags(e); 143 sm_dprintf("sendqueue:\n"); 144 printaddr(sm_debug_file(), e->e_sendqueue, true); 145 } 146 147 /* 148 ** Do any preprocessing necessary for the mode we are running. 149 ** Check to make sure the hop count is reasonable. 150 ** Delete sends to the sender in mailing lists. 151 */ 152 153 CurEnv = e; 154 if (tTd(62, 1)) 155 checkfds(NULL); 156 157 if (e->e_hopcount > MaxHopCount) 158 { 159 char *recip; 160 161 if (e->e_sendqueue != NULL && 162 e->e_sendqueue->q_paddr != NULL) 163 recip = e->e_sendqueue->q_paddr; 164 else 165 recip = "(nobody)"; 166 167 errno = 0; 168 queueup(e, WILL_BE_QUEUED(mode) ? QUP_FL_ANNOUNCE : QUP_FL_NONE); 169 e->e_flags |= EF_FATALERRS|EF_PM_NOTIFY|EF_CLRQUEUE; 170 ExitStat = EX_UNAVAILABLE; 171 syserr("554 5.4.6 Too many hops %d (%d max): from %s via %s, to %s", 172 e->e_hopcount, MaxHopCount, e->e_from.q_paddr, 173 RealHostName == NULL ? "localhost" : RealHostName, 174 recip); 175 for (q = e->e_sendqueue; q != NULL; q = q->q_next) 176 { 177 if (QS_IS_DEAD(q->q_state)) 178 continue; 179 q->q_state = QS_BADADDR; 180 q->q_status = "5.4.6"; 181 q->q_rstatus = "554 5.4.6 Too many hops"; 182 } 183 return; 184 } 185 186 /* 187 ** Do sender deletion. 188 ** 189 ** If the sender should be queued up, skip this. 190 ** This can happen if the name server is hosed when you 191 ** are trying to send mail. The result is that the sender 192 ** is instantiated in the queue as a recipient. 193 */ 194 195 if (!bitset(EF_METOO, e->e_flags) && 196 !QS_IS_QUEUEUP(e->e_from.q_state)) 197 { 198 if (tTd(13, 5)) 199 { 200 sm_dprintf("sendall: QS_SENDER "); 201 printaddr(sm_debug_file(), &e->e_from, false); 202 } 203 e->e_from.q_state = QS_SENDER; 204 (void) recipient(&e->e_from, &e->e_sendqueue, 0, e); 205 } 206 207 /* 208 ** Handle alias owners. 209 ** 210 ** We scan up the q_alias chain looking for owners. 211 ** We discard owners that are the same as the return path. 212 */ 213 214 for (q = e->e_sendqueue; q != NULL; q = q->q_next) 215 { 216 register struct address *a; 217 218 for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias) 219 continue; 220 if (a != NULL) 221 q->q_owner = a->q_owner; 222 223 if (q->q_owner != NULL && 224 !QS_IS_DEAD(q->q_state) && 225 strcmp(q->q_owner, e->e_from.q_paddr) == 0) 226 q->q_owner = NULL; 227 } 228 229 if (tTd(13, 25)) 230 { 231 sm_dprintf("\nAfter first owner pass, sendq =\n"); 232 printaddr(sm_debug_file(), e->e_sendqueue, true); 233 } 234 235 owner = ""; 236 otherowners = 1; 237 while (owner != NULL && otherowners > 0) 238 { 239 if (tTd(13, 28)) 240 sm_dprintf("owner = \"%s\", otherowners = %d\n", 241 owner, otherowners); 242 owner = NULL; 243 otherowners = bitset(EF_SENDRECEIPT, e->e_flags) ? 1 : 0; 244 245 for (q = e->e_sendqueue; q != NULL; q = q->q_next) 246 { 247 if (tTd(13, 30)) 248 { 249 sm_dprintf("Checking "); 250 printaddr(sm_debug_file(), q, false); 251 } 252 if (QS_IS_DEAD(q->q_state)) 253 { 254 if (tTd(13, 30)) 255 sm_dprintf(" ... QS_IS_DEAD\n"); 256 continue; 257 } 258 if (tTd(13, 29) && !tTd(13, 30)) 259 { 260 sm_dprintf("Checking "); 261 printaddr(sm_debug_file(), q, false); 262 } 263 264 if (q->q_owner != NULL) 265 { 266 if (owner == NULL) 267 { 268 if (tTd(13, 40)) 269 sm_dprintf(" ... First owner = \"%s\"\n", 270 q->q_owner); 271 owner = q->q_owner; 272 } 273 else if (owner != q->q_owner) 274 { 275 if (strcmp(owner, q->q_owner) == 0) 276 { 277 if (tTd(13, 40)) 278 sm_dprintf(" ... Same owner = \"%s\"\n", 279 owner); 280 281 /* make future comparisons cheap */ 282 q->q_owner = owner; 283 } 284 else 285 { 286 if (tTd(13, 40)) 287 sm_dprintf(" ... Another owner \"%s\"\n", 288 q->q_owner); 289 otherowners++; 290 } 291 owner = q->q_owner; 292 } 293 else if (tTd(13, 40)) 294 sm_dprintf(" ... Same owner = \"%s\"\n", 295 owner); 296 } 297 else 298 { 299 if (tTd(13, 40)) 300 sm_dprintf(" ... Null owner\n"); 301 otherowners++; 302 } 303 304 if (QS_IS_BADADDR(q->q_state)) 305 { 306 if (tTd(13, 30)) 307 sm_dprintf(" ... QS_IS_BADADDR\n"); 308 continue; 309 } 310 311 if (QS_IS_QUEUEUP(q->q_state)) 312 { 313 MAILER *m = q->q_mailer; 314 315 /* 316 ** If we have temporary address failures 317 ** (e.g., dns failure) and a fallback MX is 318 ** set, send directly to the fallback MX host. 319 */ 320 321 if (FallbackMX != NULL && 322 !wordinclass(FallbackMX, 'w') && 323 mode != SM_VERIFY && 324 !bitnset(M_NOMX, m->m_flags) && 325 strcmp(m->m_mailer, "[IPC]") == 0 && 326 m->m_argv[0] != NULL && 327 strcmp(m->m_argv[0], "TCP") == 0) 328 { 329 int len; 330 char *p; 331 332 if (tTd(13, 30)) 333 sm_dprintf(" ... FallbackMX\n"); 334 335 len = strlen(FallbackMX) + 1; 336 p = sm_rpool_malloc_x(e->e_rpool, len); 337 (void) sm_strlcpy(p, FallbackMX, len); 338 q->q_state = QS_OK; 339 q->q_host = p; 340 } 341 else 342 { 343 if (tTd(13, 30)) 344 sm_dprintf(" ... QS_IS_QUEUEUP\n"); 345 continue; 346 } 347 } 348 349 /* 350 ** If this mailer is expensive, and if we don't 351 ** want to make connections now, just mark these 352 ** addresses and return. This is useful if we 353 ** want to batch connections to reduce load. This 354 ** will cause the messages to be queued up, and a 355 ** daemon will come along to send the messages later. 356 */ 357 358 if (NoConnect && !Verbose && 359 bitnset(M_EXPENSIVE, q->q_mailer->m_flags)) 360 { 361 if (tTd(13, 30)) 362 sm_dprintf(" ... expensive\n"); 363 q->q_state = QS_QUEUEUP; 364 expensive = true; 365 } 366 else if (bitnset(M_HOLD, q->q_mailer->m_flags) && 367 QueueLimitId == NULL && 368 QueueLimitSender == NULL && 369 QueueLimitRecipient == NULL) 370 { 371 if (tTd(13, 30)) 372 sm_dprintf(" ... hold\n"); 373 q->q_state = QS_QUEUEUP; 374 expensive = true; 375 } 376 else if (QueueMode != QM_QUARANTINE && 377 e->e_quarmsg != NULL) 378 { 379 if (tTd(13, 30)) 380 sm_dprintf(" ... quarantine: %s\n", 381 e->e_quarmsg); 382 q->q_state = QS_QUEUEUP; 383 expensive = true; 384 } 385 else 386 { 387 if (tTd(13, 30)) 388 sm_dprintf(" ... deliverable\n"); 389 somedeliveries = true; 390 } 391 } 392 393 if (owner != NULL && otherowners > 0) 394 { 395 /* 396 ** Split this envelope into two. 397 */ 398 399 ee = (ENVELOPE *) sm_rpool_malloc_x(e->e_rpool, 400 sizeof(*ee)); 401 STRUCTCOPY(*e, *ee); 402 ee->e_message = NULL; 403 ee->e_id = NULL; 404 assign_queueid(ee); 405 406 if (tTd(13, 1)) 407 sm_dprintf("sendall: split %s into %s, owner = \"%s\", otherowners = %d\n", 408 e->e_id, ee->e_id, owner, 409 otherowners); 410 411 ee->e_header = copyheader(e->e_header, ee->e_rpool); 412 ee->e_sendqueue = copyqueue(e->e_sendqueue, 413 ee->e_rpool); 414 ee->e_errorqueue = copyqueue(e->e_errorqueue, 415 ee->e_rpool); 416 ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS|EF_SENDRECEIPT|EF_RET_PARAM); 417 ee->e_flags |= EF_NORECEIPT; 418 setsender(owner, ee, NULL, '\0', true); 419 if (tTd(13, 5)) 420 { 421 sm_dprintf("sendall(split): QS_SENDER "); 422 printaddr(sm_debug_file(), &ee->e_from, false); 423 } 424 ee->e_from.q_state = QS_SENDER; 425 ee->e_dfp = NULL; 426 ee->e_lockfp = NULL; 427 ee->e_xfp = NULL; 428 ee->e_qgrp = e->e_qgrp; 429 ee->e_qdir = e->e_qdir; 430 ee->e_errormode = EM_MAIL; 431 ee->e_sibling = splitenv; 432 ee->e_statmsg = NULL; 433 if (e->e_quarmsg != NULL) 434 ee->e_quarmsg = sm_rpool_strdup_x(ee->e_rpool, 435 e->e_quarmsg); 436 splitenv = ee; 437 438 for (q = e->e_sendqueue; q != NULL; q = q->q_next) 439 { 440 if (q->q_owner == owner) 441 { 442 q->q_state = QS_CLONED; 443 if (tTd(13, 6)) 444 sm_dprintf("\t... stripping %s from original envelope\n", 445 q->q_paddr); 446 } 447 } 448 for (q = ee->e_sendqueue; q != NULL; q = q->q_next) 449 { 450 if (q->q_owner != owner) 451 { 452 q->q_state = QS_CLONED; 453 if (tTd(13, 6)) 454 sm_dprintf("\t... dropping %s from cloned envelope\n", 455 q->q_paddr); 456 } 457 else 458 { 459 /* clear DSN parameters */ 460 q->q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS); 461 q->q_flags |= DefaultNotify & ~QPINGONSUCCESS; 462 if (tTd(13, 6)) 463 sm_dprintf("\t... moving %s to cloned envelope\n", 464 q->q_paddr); 465 } 466 } 467 468 if (mode != SM_VERIFY && bitset(EF_HAS_DF, e->e_flags)) 469 dup_queue_file(e, ee, DATAFL_LETTER); 470 471 /* 472 ** Give the split envelope access to the parent 473 ** transcript file for errors obtained while 474 ** processing the recipients (done before the 475 ** envelope splitting). 476 */ 477 478 if (e->e_xfp != NULL) 479 ee->e_xfp = sm_io_dup(e->e_xfp); 480 481 /* failed to dup e->e_xfp, start a new transcript */ 482 if (ee->e_xfp == NULL) 483 openxscript(ee); 484 485 if (mode != SM_VERIFY && LogLevel > 4) 486 sm_syslog(LOG_INFO, e->e_id, 487 "%s: clone: owner=%s", 488 ee->e_id, owner); 489 } 490 } 491 492 if (owner != NULL) 493 { 494 setsender(owner, e, NULL, '\0', true); 495 if (tTd(13, 5)) 496 { 497 sm_dprintf("sendall(owner): QS_SENDER "); 498 printaddr(sm_debug_file(), &e->e_from, false); 499 } 500 e->e_from.q_state = QS_SENDER; 501 e->e_errormode = EM_MAIL; 502 e->e_flags |= EF_NORECEIPT; 503 e->e_flags &= ~EF_FATALERRS; 504 } 505 506 /* if nothing to be delivered, just queue up everything */ 507 if (!somedeliveries && !WILL_BE_QUEUED(mode) && 508 mode != SM_VERIFY) 509 { 510 time_t now; 511 512 if (tTd(13, 29)) 513 sm_dprintf("No deliveries: auto-queueing\n"); 514 mode = SM_QUEUE; 515 now = curtime(); 516 517 /* treat this as a delivery in terms of counting tries */ 518 e->e_dtime = now; 519 if (!expensive) 520 e->e_ntries++; 521 for (ee = splitenv; ee != NULL; ee = ee->e_sibling) 522 { 523 ee->e_dtime = now; 524 if (!expensive) 525 ee->e_ntries++; 526 } 527 } 528 529 if ((WILL_BE_QUEUED(mode) || mode == SM_FORK || 530 (mode != SM_VERIFY && 531 (SuperSafe == SAFE_REALLY || 532 SuperSafe == SAFE_REALLY_POSTMILTER))) && 533 (!bitset(EF_INQUEUE, e->e_flags) || splitenv != NULL)) 534 { 535 unsigned int qup_flags; 536 537 /* 538 ** Be sure everything is instantiated in the queue. 539 ** Split envelopes first in case the machine crashes. 540 ** If the original were done first, we may lose 541 ** recipients. 542 */ 543 544 if (WILL_BE_QUEUED(mode)) 545 qup_flags = QUP_FL_ANNOUNCE; 546 else 547 qup_flags = QUP_FL_NONE; 548 #if HASFLOCK 549 if (mode == SM_FORK) 550 qup_flags |= QUP_FL_MSYNC; 551 #endif 552 553 for (ee = splitenv; ee != NULL; ee = ee->e_sibling) 554 queueup(ee, qup_flags); 555 queueup(e, qup_flags); 556 } 557 558 if (tTd(62, 10)) 559 checkfds("after envelope splitting"); 560 561 /* 562 ** If we belong in background, fork now. 563 */ 564 565 if (tTd(13, 20)) 566 { 567 sm_dprintf("sendall: final mode = %c\n", mode); 568 if (tTd(13, 21)) 569 { 570 sm_dprintf("\n================ Final Send Queue(s) =====================\n"); 571 sm_dprintf("\n *** Envelope %s, e_from=%s ***\n", 572 e->e_id, e->e_from.q_paddr); 573 printaddr(sm_debug_file(), e->e_sendqueue, true); 574 for (ee = splitenv; ee != NULL; ee = ee->e_sibling) 575 { 576 sm_dprintf("\n *** Envelope %s, e_from=%s ***\n", 577 ee->e_id, ee->e_from.q_paddr); 578 printaddr(sm_debug_file(), ee->e_sendqueue, true); 579 } 580 sm_dprintf("==========================================================\n\n"); 581 } 582 } 583 switch (mode) 584 { 585 case SM_VERIFY: 586 Verbose = 2; 587 break; 588 589 case SM_QUEUE: 590 case SM_DEFER: 591 #if HASFLOCK 592 queueonly: 593 #endif 594 if (e->e_nrcpts > 0) 595 e->e_flags |= EF_INQUEUE; 596 (void) dropenvelope(e, splitenv != NULL, true); 597 for (ee = splitenv; ee != NULL; ee = ee->e_sibling) 598 { 599 if (ee->e_nrcpts > 0) 600 ee->e_flags |= EF_INQUEUE; 601 (void) dropenvelope(ee, false, true); 602 } 603 return; 604 605 case SM_FORK: 606 if (e->e_xfp != NULL) 607 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT); 608 609 #if !HASFLOCK 610 /* 611 ** Since fcntl locking has the interesting semantic that 612 ** the lock is owned by a process, not by an open file 613 ** descriptor, we have to flush this to the queue, and 614 ** then restart from scratch in the child. 615 */ 616 617 { 618 /* save id for future use */ 619 char *qid = e->e_id; 620 621 /* now drop the envelope in the parent */ 622 e->e_flags |= EF_INQUEUE; 623 (void) dropenvelope(e, splitenv != NULL, false); 624 625 /* arrange to reacquire lock after fork */ 626 e->e_id = qid; 627 } 628 629 for (ee = splitenv; ee != NULL; ee = ee->e_sibling) 630 { 631 /* save id for future use */ 632 char *qid = ee->e_id; 633 634 /* drop envelope in parent */ 635 ee->e_flags |= EF_INQUEUE; 636 (void) dropenvelope(ee, false, false); 637 638 /* and save qid for reacquisition */ 639 ee->e_id = qid; 640 } 641 642 #endif /* !HASFLOCK */ 643 644 /* 645 ** Since the delivery may happen in a child and the parent 646 ** does not wait, the parent may close the maps thereby 647 ** removing any shared memory used by the map. Therefore, 648 ** close the maps now so the child will dynamically open 649 ** them if necessary. 650 */ 651 652 closemaps(false); 653 654 pid = fork(); 655 if (pid < 0) 656 { 657 syserr("deliver: fork 1"); 658 #if HASFLOCK 659 goto queueonly; 660 #else /* HASFLOCK */ 661 e->e_id = NULL; 662 for (ee = splitenv; ee != NULL; ee = ee->e_sibling) 663 ee->e_id = NULL; 664 return; 665 #endif /* HASFLOCK */ 666 } 667 else if (pid > 0) 668 { 669 #if HASFLOCK 670 /* be sure we leave the temp files to our child */ 671 /* close any random open files in the envelope */ 672 closexscript(e); 673 SM_CLOSE_FP(e->e_dfp); 674 e->e_flags &= ~EF_HAS_DF; 675 676 /* can't call unlockqueue to avoid unlink of xfp */ 677 if (e->e_lockfp != NULL) 678 (void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT); 679 else 680 syserr("%s: sendall: null lockfp", e->e_id); 681 e->e_lockfp = NULL; 682 #endif /* HASFLOCK */ 683 684 /* make sure the parent doesn't own the envelope */ 685 e->e_id = NULL; 686 687 #if USE_DOUBLE_FORK 688 /* catch intermediate zombie */ 689 (void) waitfor(pid); 690 #endif 691 return; 692 } 693 694 /* Reset global flags */ 695 RestartRequest = NULL; 696 RestartWorkGroup = false; 697 ShutdownRequest = NULL; 698 PendingSignal = 0; 699 700 /* 701 ** Initialize exception stack and default exception 702 ** handler for child process. 703 */ 704 705 sm_exc_newthread(fatal_error); 706 707 /* 708 ** Since we have accepted responsbility for the message, 709 ** change the SIGTERM handler. intsig() (the old handler) 710 ** would remove the envelope if this was a command line 711 ** message submission. 712 */ 713 714 (void) sm_signal(SIGTERM, SIG_DFL); 715 716 #if USE_DOUBLE_FORK 717 /* double fork to avoid zombies */ 718 pid = fork(); 719 if (pid > 0) 720 exit(EX_OK); 721 save_errno = errno; 722 #endif /* USE_DOUBLE_FORK */ 723 724 CurrentPid = getpid(); 725 726 /* be sure we are immune from the terminal */ 727 disconnect(2, e); 728 clearstats(); 729 730 /* prevent parent from waiting if there was an error */ 731 if (pid < 0) 732 { 733 errno = save_errno; 734 syserr("deliver: fork 2"); 735 #if HASFLOCK 736 e->e_flags |= EF_INQUEUE; 737 #else 738 e->e_id = NULL; 739 #endif 740 finis(true, true, ExitStat); 741 } 742 743 /* be sure to give error messages in child */ 744 QuickAbort = false; 745 746 /* 747 ** Close any cached connections. 748 ** 749 ** We don't send the QUIT protocol because the parent 750 ** still knows about the connection. 751 ** 752 ** This should only happen when delivering an error 753 ** message. 754 */ 755 756 mci_flush(false, NULL); 757 758 #if HASFLOCK 759 break; 760 #else /* HASFLOCK */ 761 762 /* 763 ** Now reacquire and run the various queue files. 764 */ 765 766 for (ee = splitenv; ee != NULL; ee = ee->e_sibling) 767 { 768 ENVELOPE *sibling = ee->e_sibling; 769 770 (void) dowork(ee->e_qgrp, ee->e_qdir, ee->e_id, 771 false, false, ee); 772 ee->e_sibling = sibling; 773 } 774 (void) dowork(e->e_qgrp, e->e_qdir, e->e_id, 775 false, false, e); 776 finis(true, true, ExitStat); 777 #endif /* HASFLOCK */ 778 } 779 780 sendenvelope(e, mode); 781 (void) dropenvelope(e, true, true); 782 for (ee = splitenv; ee != NULL; ee = ee->e_sibling) 783 { 784 CurEnv = ee; 785 if (mode != SM_VERIFY) 786 openxscript(ee); 787 sendenvelope(ee, mode); 788 (void) dropenvelope(ee, true, true); 789 } 790 CurEnv = e; 791 792 Verbose = oldverbose; 793 if (mode == SM_FORK) 794 finis(true, true, ExitStat); 795 } 796 797 static void 798 sendenvelope(e, mode) 799 register ENVELOPE *e; 800 int mode; 801 { 802 register ADDRESS *q; 803 bool didany; 804 805 if (tTd(13, 10)) 806 sm_dprintf("sendenvelope(%s) e_flags=0x%lx\n", 807 e->e_id == NULL ? "[NOQUEUE]" : e->e_id, 808 e->e_flags); 809 if (LogLevel > 80) 810 sm_syslog(LOG_DEBUG, e->e_id, 811 "sendenvelope, flags=0x%lx", 812 e->e_flags); 813 814 /* 815 ** If we have had global, fatal errors, don't bother sending 816 ** the message at all if we are in SMTP mode. Local errors 817 ** (e.g., a single address failing) will still cause the other 818 ** addresses to be sent. 819 */ 820 821 if (bitset(EF_FATALERRS, e->e_flags) && 822 (OpMode == MD_SMTP || OpMode == MD_DAEMON)) 823 { 824 e->e_flags |= EF_CLRQUEUE; 825 return; 826 } 827 828 /* 829 ** Don't attempt deliveries if we want to bounce now 830 ** or if deliver-by time is exceeded. 831 */ 832 833 if (!bitset(EF_RESPONSE, e->e_flags) && 834 (TimeOuts.to_q_return[e->e_timeoutclass] == NOW || 835 (IS_DLVR_RETURN(e) && e->e_deliver_by > 0 && 836 curtime() > e->e_ctime + e->e_deliver_by))) 837 return; 838 839 /* 840 ** Run through the list and send everything. 841 ** 842 ** Set EF_GLOBALERRS so that error messages during delivery 843 ** result in returned mail. 844 */ 845 846 e->e_nsent = 0; 847 e->e_flags |= EF_GLOBALERRS; 848 849 macdefine(&e->e_macro, A_PERM, macid("{envid}"), e->e_envid); 850 macdefine(&e->e_macro, A_PERM, macid("{bodytype}"), e->e_bodytype); 851 didany = false; 852 853 if (!bitset(EF_SPLIT, e->e_flags)) 854 { 855 ENVELOPE *oldsib; 856 ENVELOPE *ee; 857 858 /* 859 ** Save old sibling and set it to NULL to avoid 860 ** queueing up the same envelopes again. 861 ** This requires that envelopes in that list have 862 ** been take care of before (or at some other place). 863 */ 864 865 oldsib = e->e_sibling; 866 e->e_sibling = NULL; 867 if (!split_by_recipient(e) && 868 bitset(EF_FATALERRS, e->e_flags)) 869 { 870 if (OpMode == MD_SMTP || OpMode == MD_DAEMON) 871 e->e_flags |= EF_CLRQUEUE; 872 return; 873 } 874 for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling) 875 queueup(ee, QUP_FL_MSYNC); 876 877 /* clean up */ 878 for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling) 879 { 880 /* now unlock the job */ 881 closexscript(ee); 882 unlockqueue(ee); 883 884 /* this envelope is marked unused */ 885 SM_CLOSE_FP(ee->e_dfp); 886 ee->e_id = NULL; 887 ee->e_flags &= ~EF_HAS_DF; 888 } 889 e->e_sibling = oldsib; 890 } 891 892 /* now run through the queue */ 893 for (q = e->e_sendqueue; q != NULL; q = q->q_next) 894 { 895 #if XDEBUG 896 char wbuf[MAXNAME + 20]; /* EAI: might be too short, but that's ok for debugging */ 897 898 (void) sm_snprintf(wbuf, sizeof(wbuf), "sendall(%.*s)", 899 MAXNAME, q->q_paddr); /* EAI: see above */ 900 checkfd012(wbuf); 901 #endif /* XDEBUG */ 902 if (mode == SM_VERIFY) 903 { 904 e->e_to = q->q_paddr; 905 if (QS_IS_SENDABLE(q->q_state)) 906 { 907 if (q->q_host != NULL && q->q_host[0] != '\0') 908 message("deliverable: mailer %s, host %s, user %s", 909 q->q_mailer->m_name, 910 q->q_host, 911 q->q_user); 912 else 913 message("deliverable: mailer %s, user %s", 914 q->q_mailer->m_name, 915 q->q_user); 916 } 917 } 918 else if (QS_IS_OK(q->q_state)) 919 { 920 /* 921 ** Checkpoint the send list every few addresses 922 */ 923 924 if (CheckpointInterval > 0 && 925 e->e_nsent >= CheckpointInterval) 926 { 927 queueup(e, QUP_FL_NONE); 928 e->e_nsent = 0; 929 } 930 (void) deliver(e, q); 931 didany = true; 932 } 933 } 934 if (didany) 935 { 936 e->e_dtime = curtime(); 937 e->e_ntries++; 938 } 939 940 #if XDEBUG 941 checkfd012("end of sendenvelope"); 942 #endif 943 } 944 945 #if REQUIRES_DIR_FSYNC 946 /* 947 ** SYNC_DIR -- fsync a directory based on a filename 948 ** 949 ** Parameters: 950 ** filename -- path of file 951 ** panic -- panic? 952 ** 953 ** Returns: 954 ** none 955 */ 956 957 void 958 sync_dir(filename, panic) 959 char *filename; 960 bool panic; 961 { 962 int dirfd; 963 char *dirp; 964 char dir[MAXPATHLEN]; 965 966 if (!RequiresDirfsync) 967 return; 968 969 /* filesystems which require the directory be synced */ 970 dirp = strrchr(filename, '/'); 971 if (dirp != NULL) 972 { 973 if (sm_strlcpy(dir, filename, sizeof(dir)) >= sizeof(dir)) 974 return; 975 dir[dirp - filename] = '\0'; 976 dirp = dir; 977 } 978 else 979 dirp = "."; 980 dirfd = open(dirp, O_RDONLY, 0700); 981 if (tTd(40,32)) 982 sm_syslog(LOG_INFO, NOQID, "sync_dir: %s: fsync(%d)", 983 dirp, dirfd); 984 if (dirfd >= 0) 985 { 986 if (fsync(dirfd) < 0) 987 { 988 if (panic) 989 syserr("!sync_dir: cannot fsync directory %s", 990 dirp); 991 else if (LogLevel > 1) 992 sm_syslog(LOG_ERR, NOQID, 993 "sync_dir: cannot fsync directory %s: %s", 994 dirp, sm_errstring(errno)); 995 } 996 (void) close(dirfd); 997 } 998 } 999 #endif /* REQUIRES_DIR_FSYNC */ 1000 /* 1001 ** DUP_QUEUE_FILE -- duplicate a queue file into a split queue 1002 ** 1003 ** Parameters: 1004 ** e -- the existing envelope 1005 ** ee -- the new envelope 1006 ** type -- the queue file type (e.g., DATAFL_LETTER) 1007 ** 1008 ** Returns: 1009 ** none 1010 */ 1011 1012 static void 1013 dup_queue_file(e, ee, type) 1014 ENVELOPE *e, *ee; 1015 int type; 1016 { 1017 char f1buf[MAXPATHLEN], f2buf[MAXPATHLEN]; 1018 1019 ee->e_dfp = NULL; 1020 ee->e_xfp = NULL; 1021 1022 /* 1023 ** Make sure both are in the same directory. 1024 */ 1025 1026 (void) sm_strlcpy(f1buf, queuename(e, type), sizeof(f1buf)); 1027 (void) sm_strlcpy(f2buf, queuename(ee, type), sizeof(f2buf)); 1028 1029 /* Force the df to disk if it's not there yet */ 1030 if (type == DATAFL_LETTER && e->e_dfp != NULL && 1031 sm_io_setinfo(e->e_dfp, SM_BF_COMMIT, NULL) < 0 && 1032 errno != EINVAL) 1033 { 1034 syserr("!dup_queue_file: can't commit %s", f1buf); 1035 /* NOTREACHED */ 1036 } 1037 1038 if (link(f1buf, f2buf) < 0) 1039 { 1040 int save_errno = errno; 1041 1042 syserr("sendall: link(%s, %s)", f1buf, f2buf); 1043 if (save_errno == EEXIST) 1044 { 1045 if (unlink(f2buf) < 0) 1046 { 1047 syserr("!sendall: unlink(%s): permanent", 1048 f2buf); 1049 /* NOTREACHED */ 1050 } 1051 if (link(f1buf, f2buf) < 0) 1052 { 1053 syserr("!sendall: link(%s, %s): permanent", 1054 f1buf, f2buf); 1055 /* NOTREACHED */ 1056 } 1057 } 1058 } 1059 SYNC_DIR(f2buf, true); 1060 } 1061 /* 1062 ** DOFORK -- do a fork, retrying a couple of times on failure. 1063 ** 1064 ** This MUST be a macro, since after a vfork we are running 1065 ** two processes on the same stack!!! 1066 ** 1067 ** Parameters: 1068 ** none. 1069 ** 1070 ** Returns: 1071 ** From a macro??? You've got to be kidding! 1072 ** 1073 ** Side Effects: 1074 ** Modifies the ==> LOCAL <== variable 'pid', leaving: 1075 ** pid of child in parent, zero in child. 1076 ** -1 on unrecoverable error. 1077 ** 1078 ** Notes: 1079 ** I'm awfully sorry this looks so awful. That's 1080 ** vfork for you..... 1081 */ 1082 1083 #define NFORKTRIES 5 1084 1085 #ifndef FORK 1086 # define FORK fork 1087 #endif 1088 1089 #define DOFORK(fORKfN) \ 1090 {\ 1091 register int i;\ 1092 \ 1093 for (i = NFORKTRIES; --i >= 0; )\ 1094 {\ 1095 pid = fORKfN();\ 1096 if (pid >= 0)\ 1097 break;\ 1098 if (i > 0)\ 1099 (void) sleep((unsigned) NFORKTRIES - i);\ 1100 }\ 1101 } 1102 /* 1103 ** DOFORK -- simple fork interface to DOFORK. 1104 ** 1105 ** Parameters: 1106 ** none. 1107 ** 1108 ** Returns: 1109 ** pid of child in parent. 1110 ** zero in child. 1111 ** -1 on error. 1112 ** 1113 ** Side Effects: 1114 ** returns twice, once in parent and once in child. 1115 */ 1116 1117 pid_t 1118 dofork() 1119 { 1120 register pid_t pid = -1; 1121 1122 DOFORK(fork); 1123 return pid; 1124 } 1125 1126 /* 1127 ** COLONCMP -- compare host-signatures up to first ':' or EOS 1128 ** 1129 ** This takes two strings which happen to be host-signatures and 1130 ** compares them. If the lowest preference portions of the MX-RR's 1131 ** match (up to ':' or EOS, whichever is first), then we have 1132 ** match. This is used for coattail-piggybacking messages during 1133 ** message delivery. 1134 ** If the signatures are the same up to the first ':' the remainder of 1135 ** the signatures are then compared with a normal strcmp(). This saves 1136 ** re-examining the first part of the signatures. 1137 ** 1138 ** Parameters: 1139 ** a - first host-signature 1140 ** b - second host-signature 1141 ** 1142 ** Returns: 1143 ** HS_MATCH_NO -- no "match". 1144 ** HS_MATCH_FIRST -- "match" for the first MX preference 1145 ** (up to the first colon (':')). 1146 ** HS_MATCH_FULL -- match for the entire MX record. 1147 ** 1148 ** Side Effects: 1149 ** none. 1150 */ 1151 1152 #define HS_MATCH_NO 0 1153 #define HS_MATCH_FIRST 1 1154 #define HS_MATCH_FULL 2 1155 1156 static int 1157 coloncmp(a, b) 1158 register const char *a; 1159 register const char *b; 1160 { 1161 int ret = HS_MATCH_NO; 1162 int braclev = 0; 1163 1164 while (*a == *b++) 1165 { 1166 /* Need to account for IPv6 bracketed addresses */ 1167 if (*a == '[') 1168 braclev++; 1169 else if (*a == ']' && braclev > 0) 1170 braclev--; 1171 else if (*a == ':' && braclev <= 0) 1172 { 1173 ret = HS_MATCH_FIRST; 1174 a++; 1175 break; 1176 } 1177 else if (*a == '\0') 1178 return HS_MATCH_FULL; /* a full match */ 1179 a++; 1180 } 1181 if (ret == HS_MATCH_NO && 1182 braclev <= 0 && 1183 ((*a == '\0' && *(b - 1) == ':') || 1184 (*a == ':' && *(b - 1) == '\0'))) 1185 return HS_MATCH_FIRST; 1186 if (ret == HS_MATCH_FIRST && strcmp(a, b) == 0) 1187 return HS_MATCH_FULL; 1188 1189 return ret; 1190 } 1191 1192 /* 1193 ** SHOULD_TRY_FBSH -- Should try FallbackSmartHost? 1194 ** 1195 ** Parameters: 1196 ** e -- envelope 1197 ** tried_fallbacksmarthost -- has been tried already? (in/out) 1198 ** hostbuf -- buffer for hostname (expand FallbackSmartHost) (out) 1199 ** hbsz -- size of hostbuf 1200 ** status -- current delivery status 1201 ** 1202 ** Returns: 1203 ** true iff FallbackSmartHost should be tried. 1204 */ 1205 1206 static bool should_try_fbsh __P((ENVELOPE *, bool *, char *, size_t, int)); 1207 1208 static bool 1209 should_try_fbsh(e, tried_fallbacksmarthost, hostbuf, hbsz, status) 1210 ENVELOPE *e; 1211 bool *tried_fallbacksmarthost; 1212 char *hostbuf; 1213 size_t hbsz; 1214 int status; 1215 { 1216 /* 1217 ** If the host was not found or a temporary failure occurred 1218 ** and a FallbackSmartHost is defined (and we have not yet 1219 ** tried it), then make one last try with it as the host. 1220 */ 1221 1222 if ((status == EX_NOHOST || status == EX_TEMPFAIL) && 1223 FallbackSmartHost != NULL && !*tried_fallbacksmarthost) 1224 { 1225 *tried_fallbacksmarthost = true; 1226 expand(FallbackSmartHost, hostbuf, hbsz, e); 1227 if (!wordinclass(hostbuf, 'w')) 1228 { 1229 if (tTd(11, 1)) 1230 sm_dprintf("one last try with FallbackSmartHost %s\n", 1231 hostbuf); 1232 return true; 1233 } 1234 } 1235 return false; 1236 } 1237 1238 /* 1239 ** CLTFEATURES -- Get features for SMTP client 1240 ** 1241 ** Parameters: 1242 ** e -- envelope 1243 ** clientname -- name of client. 1244 ** 1245 ** Returns: 1246 ** EX_OK or EX_TEMPFAIL 1247 */ 1248 1249 static int cltfeatures __P((ENVELOPE *, char *)); 1250 static int 1251 cltfeatures(e, clientname) 1252 ENVELOPE *e; 1253 char *clientname; 1254 { 1255 int r, i, idx; 1256 char **pvp, c; 1257 char pvpbuf[PSBUFSIZE]; 1258 char flags[64]; /* XXX */ 1259 1260 SM_ASSERT(e != NULL); 1261 SM_ASSERT(e->e_mci != NULL); 1262 macdefine(&e->e_mci->mci_macro, A_PERM, macid("{client_flags}"), ""); 1263 pvp = NULL; 1264 r = rscap("clt_features", clientname, "", e, &pvp, pvpbuf, 1265 sizeof(pvpbuf)); 1266 if (r != EX_OK) 1267 return EX_OK; 1268 if (pvp == NULL || pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET) 1269 return EX_OK; 1270 if (pvp[1] != NULL && sm_strncasecmp(pvp[1], "temp", 4) == 0) 1271 return EX_TEMPFAIL; 1272 1273 /* XXX Note: this does not inherit defaults! */ 1274 for (idx = 0, i = 1; pvp[i] != NULL; i++) 1275 { 1276 c = pvp[i][0]; 1277 if (!(isascii(c) && !isspace(c) && isprint(c))) 1278 continue; 1279 if (idx >= sizeof(flags) - 4) 1280 break; 1281 flags[idx++] = c; 1282 if (isupper(c)) 1283 flags[idx++] = c; 1284 flags[idx++] = ' '; 1285 } 1286 flags[idx] = '\0'; 1287 1288 macdefine(&e->e_mci->mci_macro, A_TEMP, macid("{client_flags}"), flags); 1289 if (tTd(10, 30)) 1290 sm_dprintf("cltfeatures: mci=%p, flags=%s, {client_flags}=%s\n", 1291 e->e_mci, flags, macvalue(macid("{client_flags}"), e)); 1292 return EX_OK; 1293 } 1294 1295 /* 1296 ** DELIVER -- Deliver a message to a list of addresses. 1297 ** 1298 ** This routine delivers to everyone on the same host as the 1299 ** user on the head of the list. It is clever about mailers 1300 ** that don't handle multiple users. It is NOT guaranteed 1301 ** that it will deliver to all these addresses however -- so 1302 ** deliver should be called once for each address on the list. 1303 ** Deliver tries to be as opportunistic as possible about piggybacking 1304 ** messages. Some definitions to make understanding easier follow below. 1305 ** Piggybacking occurs when an existing connection to a mail host can 1306 ** be used to send the same message to more than one recipient at the 1307 ** same time. So "no piggybacking" means one message for one recipient 1308 ** per connection. "Intentional piggybacking" happens when the 1309 ** recipients' host address (not the mail host address) is used to 1310 ** attempt piggybacking. Recipients with the same host address 1311 ** have the same mail host. "Coincidental piggybacking" relies on 1312 ** piggybacking based on all the mail host addresses in the MX-RR. This 1313 ** is "coincidental" in the fact it could not be predicted until the 1314 ** MX Resource Records for the hosts were obtained and examined. For 1315 ** example (preference order and equivalence is important, not values): 1316 ** domain1 IN MX 10 mxhost-A 1317 ** IN MX 20 mxhost-B 1318 ** domain2 IN MX 4 mxhost-A 1319 ** IN MX 8 mxhost-B 1320 ** Domain1 and domain2 can piggyback the same message to mxhost-A or 1321 ** mxhost-B (if mxhost-A cannot be reached). 1322 ** "Coattail piggybacking" relaxes the strictness of "coincidental 1323 ** piggybacking" in the hope that most significant (lowest value) 1324 ** MX preference host(s) can create more piggybacking. For example 1325 ** (again, preference order and equivalence is important, not values): 1326 ** domain3 IN MX 100 mxhost-C 1327 ** IN MX 100 mxhost-D 1328 ** IN MX 200 mxhost-E 1329 ** domain4 IN MX 50 mxhost-C 1330 ** IN MX 50 mxhost-D 1331 ** IN MX 80 mxhost-F 1332 ** A message for domain3 and domain4 can piggyback to mxhost-C if mxhost-C 1333 ** is available. Same with mxhost-D because in both RR's the preference 1334 ** value is the same as mxhost-C, respectively. 1335 ** So deliver attempts coattail piggybacking when possible. If the 1336 ** first MX preference level hosts cannot be used then the piggybacking 1337 ** reverts to coincidental piggybacking. Using the above example you 1338 ** cannot deliver to mxhost-F for domain3 regardless of preference value. 1339 ** ("Coattail" from "riding on the coattails of your predecessor" meaning 1340 ** gaining benefit from a predecessor effort with no or little addition 1341 ** effort. The predecessor here being the preceding MX RR). 1342 ** 1343 ** Parameters: 1344 ** e -- the envelope to deliver. 1345 ** firstto -- head of the address list to deliver to. 1346 ** 1347 ** Returns: 1348 ** zero -- successfully delivered. 1349 ** else -- some failure, see ExitStat for more info. 1350 ** 1351 ** Side Effects: 1352 ** The standard input is passed off to someone. 1353 */ 1354 1355 static int 1356 deliver(e, firstto) 1357 register ENVELOPE *e; 1358 ADDRESS *firstto; 1359 { 1360 char *host; /* host being sent to */ 1361 char *user; /* user being sent to */ 1362 char **pvp; 1363 register char **mvp; 1364 register char *p; 1365 register MAILER *m; /* mailer for this recipient */ 1366 ADDRESS *volatile ctladdr; 1367 #if HASSETUSERCONTEXT 1368 ADDRESS *volatile contextaddr = NULL; 1369 #endif 1370 register MCI *volatile mci; 1371 register ADDRESS *SM_NONVOLATILE to = firstto; 1372 volatile bool clever = false; /* running user smtp to this mailer */ 1373 ADDRESS *volatile tochain = NULL; /* users chain in this mailer call */ 1374 int rcode; /* response code */ 1375 SM_NONVOLATILE int lmtp_rcode = EX_OK; 1376 SM_NONVOLATILE int nummxhosts = 0; /* number of MX hosts available */ 1377 SM_NONVOLATILE int hostnum = 0; /* current MX host index */ 1378 char *firstsig; /* signature of firstto */ 1379 volatile pid_t pid = -1; 1380 char *volatile curhost; 1381 SM_NONVOLATILE unsigned short port = 0; 1382 SM_NONVOLATILE time_t enough = 0; 1383 #if NETUNIX 1384 char *SM_NONVOLATILE mux_path = NULL; /* path to UNIX domain socket */ 1385 #endif 1386 time_t xstart; 1387 bool suidwarn; 1388 bool anyok; /* at least one address was OK */ 1389 SM_NONVOLATILE bool goodmxfound = false; /* at least one MX was OK */ 1390 bool ovr; 1391 bool quarantine; 1392 #if STARTTLS 1393 /* 0: try TLS, 1: try without TLS again, >1: don't try again */ 1394 int tlsstate; 1395 # if DANE 1396 dane_vrfy_ctx_T dane_vrfy_ctx; 1397 STAB *ste; 1398 # endif 1399 #endif 1400 #if STARTTLS || SASL 1401 int dotpos; 1402 1403 # define RM_TRAIL_DOT(name) \ 1404 do { \ 1405 dotpos = strlen(name) - 1; \ 1406 if (dotpos >= 0) \ 1407 { \ 1408 if (name[dotpos] == '.') \ 1409 name[dotpos] = '\0'; \ 1410 else \ 1411 dotpos = -1; \ 1412 } \ 1413 } while (0) 1414 1415 # define FIX_TRAIL_DOT(name) \ 1416 do { \ 1417 if (dotpos >= 0) \ 1418 name[dotpos] = '.'; \ 1419 } while (0) 1420 1421 #endif 1422 int strsize; 1423 int rcptcount; 1424 int ret; 1425 static int tobufsize = 0; 1426 static char *tobuf = NULL; 1427 char *rpath; /* translated return path */ 1428 int mpvect[2]; 1429 int rpvect[2]; 1430 char *mxhosts[MAXMXHOSTS + 1]; 1431 char *pv[MAXPV + 1]; 1432 char buf[MAXNAME + 1]; /* EAI:ok */ 1433 char cbuf[MAXPATHLEN]; 1434 1435 errno = 0; 1436 SM_REQUIRE(firstto != NULL); /* same as to */ 1437 if (!QS_IS_OK(to->q_state)) 1438 return 0; 1439 1440 suidwarn = geteuid() == 0; 1441 1442 SM_REQUIRE(e != NULL); 1443 m = to->q_mailer; 1444 host = to->q_host; 1445 CurEnv = e; /* just in case */ 1446 e->e_statmsg = NULL; 1447 SmtpError[0] = '\0'; 1448 xstart = curtime(); 1449 #if STARTTLS 1450 tlsstate = 0; 1451 # if DANE 1452 memset(&dane_vrfy_ctx, '\0', sizeof(dane_vrfy_ctx)); 1453 ste = NULL; 1454 # endif 1455 #endif 1456 1457 if (tTd(10, 1)) 1458 sm_dprintf("\n--deliver, id=%s, mailer=%s, host=`%s', first user=`%s'\n", 1459 e->e_id, m->m_name, host, to->q_user); 1460 if (tTd(10, 100)) 1461 printopenfds(false); 1462 1463 /* 1464 ** Clear {client_*} macros if this is a bounce message to 1465 ** prevent rejection by check_compat ruleset. 1466 */ 1467 1468 if (bitset(EF_RESPONSE, e->e_flags)) 1469 { 1470 macdefine(&e->e_macro, A_PERM, macid("{client_name}"), ""); 1471 macdefine(&e->e_macro, A_PERM, macid("{client_ptr}"), ""); 1472 macdefine(&e->e_macro, A_PERM, macid("{client_addr}"), ""); 1473 macdefine(&e->e_macro, A_PERM, macid("{client_port}"), ""); 1474 macdefine(&e->e_macro, A_PERM, macid("{client_resolve}"), ""); 1475 } 1476 1477 SM_TRY 1478 { 1479 ADDRESS *skip_back = NULL; 1480 1481 /* 1482 ** Do initial argv setup. 1483 ** Insert the mailer name. Notice that $x expansion is 1484 ** NOT done on the mailer name. Then, if the mailer has 1485 ** a picky -f flag, we insert it as appropriate. This 1486 ** code does not check for 'pv' overflow; this places a 1487 ** manifest lower limit of 4 for MAXPV. 1488 ** The from address rewrite is expected to make 1489 ** the address relative to the other end. 1490 */ 1491 1492 /* rewrite from address, using rewriting rules */ 1493 rcode = EX_OK; 1494 SM_ASSERT(e->e_from.q_mailer != NULL); 1495 if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags)) 1496 p = e->e_sender; 1497 else 1498 p = e->e_from.q_paddr; 1499 rpath = remotename(p, m, RF_SENDERADDR|RF_CANONICAL, &rcode, e); 1500 if (rcode != EX_OK && bitnset(M_xSMTP, m->m_flags)) 1501 goto cleanup; 1502 1503 /* need to check external format, not internal! */ 1504 if (strlen(rpath) > MAXNAME_I) 1505 { 1506 rpath = shortenstring(rpath, MAXSHORTSTR); 1507 1508 /* avoid bogus errno */ 1509 errno = 0; 1510 syserr("remotename: huge return path %s", rpath); 1511 } 1512 rpath = sm_rpool_strdup_x(e->e_rpool, rpath); 1513 macdefine(&e->e_macro, A_PERM, 'g', rpath); 1514 macdefine(&e->e_macro, A_PERM, 'h', host); 1515 Errors = 0; 1516 pvp = pv; 1517 *pvp++ = m->m_argv[0]; 1518 1519 /* ignore long term host status information if mailer flag W is set */ 1520 if (bitnset(M_NOHOSTSTAT, m->m_flags)) 1521 IgnoreHostStatus = true; 1522 1523 /* insert -f or -r flag as appropriate */ 1524 if (FromFlag && 1525 (bitnset(M_FOPT, m->m_flags) || 1526 bitnset(M_ROPT, m->m_flags))) 1527 { 1528 if (bitnset(M_FOPT, m->m_flags)) 1529 *pvp++ = "-f"; 1530 else 1531 *pvp++ = "-r"; 1532 *pvp++ = rpath; 1533 } 1534 1535 /* 1536 ** Append the other fixed parts of the argv. These run 1537 ** up to the first entry containing "$u". There can only 1538 ** be one of these, and there are only a few more slots 1539 ** in the pv after it. 1540 */ 1541 1542 for (mvp = m->m_argv; (p = *++mvp) != NULL; ) 1543 { 1544 /* can't use strchr here because of sign extension problems */ 1545 while (*p != '\0') 1546 { 1547 if ((*p++ & 0377) == MACROEXPAND) 1548 { 1549 if (*p == 'u') 1550 break; 1551 } 1552 } 1553 1554 if (*p != '\0') 1555 break; 1556 1557 /* this entry is safe -- go ahead and process it */ 1558 expand(*mvp, buf, sizeof(buf), e); 1559 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf); 1560 if (pvp >= &pv[MAXPV - 3]) 1561 { 1562 syserr("554 5.3.5 Too many parameters to %s before $u", 1563 pv[0]); 1564 rcode = -1; 1565 goto cleanup; 1566 } 1567 } 1568 1569 /* 1570 ** If we have no substitution for the user name in the argument 1571 ** list, we know that we must supply the names otherwise -- and 1572 ** SMTP is the answer!! 1573 */ 1574 1575 if (*mvp == NULL) 1576 { 1577 /* running LMTP or SMTP */ 1578 clever = true; 1579 *pvp = NULL; 1580 setbitn(M_xSMTP, m->m_flags); 1581 } 1582 else if (bitnset(M_LMTP, m->m_flags)) 1583 { 1584 /* not running LMTP */ 1585 sm_syslog(LOG_ERR, NULL, 1586 "Warning: mailer %s: LMTP flag (F=z) turned off", 1587 m->m_name); 1588 clrbitn(M_LMTP, m->m_flags); 1589 } 1590 1591 /* 1592 ** At this point *mvp points to the argument with $u. We 1593 ** run through our address list and append all the addresses 1594 ** we can. If we run out of space, do not fret! We can 1595 ** always send another copy later. 1596 */ 1597 1598 e->e_to = NULL; 1599 strsize = 2; 1600 rcptcount = 0; 1601 ctladdr = NULL; 1602 if (firstto->q_signature == NULL) 1603 firstto->q_signature = hostsignature(firstto->q_mailer, 1604 firstto->q_host, 1605 firstto->q_flags & QSECURE); 1606 firstsig = firstto->q_signature; 1607 1608 for (; to != NULL; to = to->q_next) 1609 { 1610 /* avoid sending multiple recipients to dumb mailers */ 1611 if (tochain != NULL && !bitnset(M_MUSER, m->m_flags)) 1612 break; 1613 1614 /* if already sent or not for this host, don't send */ 1615 if (!QS_IS_OK(to->q_state)) /* already sent; look at next */ 1616 continue; 1617 1618 /* 1619 ** Must be same mailer to keep grouping rcpts. 1620 ** If mailers don't match: continue; sendqueue is not 1621 ** sorted by mailers, so don't break; 1622 */ 1623 1624 if (to->q_mailer != firstto->q_mailer) 1625 continue; 1626 1627 if (to->q_signature == NULL) /* for safety */ 1628 to->q_signature = hostsignature(to->q_mailer, 1629 to->q_host, 1630 to->q_flags & QSECURE); 1631 1632 /* 1633 ** This is for coincidental and tailcoat piggybacking messages 1634 ** to the same mail host. While the signatures are identical 1635 ** (that's the MX-RR's are identical) we can do coincidental 1636 ** piggybacking. We try hard for coattail piggybacking 1637 ** with the same mail host when the next recipient has the 1638 ** same host at lowest preference. It may be that this 1639 ** won't work out, so 'skip_back' is maintained if a backup 1640 ** to coincidental piggybacking or full signature must happen. 1641 */ 1642 1643 ret = firstto == to ? HS_MATCH_FULL : 1644 coloncmp(to->q_signature, firstsig); 1645 if (ret == HS_MATCH_FULL) 1646 skip_back = to; 1647 else if (ret == HS_MATCH_NO) 1648 break; 1649 1650 if (!clever) 1651 { 1652 /* avoid overflowing tobuf */ 1653 strsize += strlen(to->q_paddr) + 1; 1654 if (strsize > TOBUFSIZE) 1655 break; 1656 } 1657 1658 if (++rcptcount > to->q_mailer->m_maxrcpt) 1659 break; 1660 1661 /* 1662 ** prepare envelope for new session to avoid leakage 1663 ** between delivery attempts. 1664 */ 1665 1666 smtpclrse(e); 1667 1668 if (tTd(10, 1)) 1669 { 1670 sm_dprintf("\nsend to "); 1671 printaddr(sm_debug_file(), to, false); 1672 } 1673 1674 /* compute effective uid/gid when sending */ 1675 if (bitnset(M_RUNASRCPT, to->q_mailer->m_flags)) 1676 #if HASSETUSERCONTEXT 1677 contextaddr = ctladdr = getctladdr(to); 1678 #else 1679 ctladdr = getctladdr(to); 1680 #endif 1681 1682 if (tTd(10, 2)) 1683 { 1684 sm_dprintf("ctladdr="); 1685 printaddr(sm_debug_file(), ctladdr, false); 1686 } 1687 1688 user = to->q_user; 1689 e->e_to = to->q_paddr; 1690 1691 /* 1692 ** Check to see that these people are allowed to 1693 ** talk to each other. 1694 ** Check also for overflow of e_msgsize. 1695 */ 1696 1697 if (m->m_maxsize != 0 && 1698 (e->e_msgsize > m->m_maxsize || e->e_msgsize < 0)) 1699 { 1700 e->e_flags |= EF_NO_BODY_RETN; 1701 if (bitnset(M_LOCALMAILER, to->q_mailer->m_flags)) 1702 to->q_status = "5.2.3"; 1703 else 1704 to->q_status = "5.3.4"; 1705 1706 /* set to->q_rstatus = NULL; or to the following? */ 1707 usrerrenh(to->q_status, 1708 "552 Message is too large; %ld bytes max", 1709 m->m_maxsize); 1710 markfailure(e, to, NULL, EX_UNAVAILABLE, false); 1711 giveresponse(EX_UNAVAILABLE, to->q_status, m, 1712 NULL, ctladdr, xstart, e, to); 1713 continue; 1714 } 1715 SM_SET_H_ERRNO(0); 1716 ovr = true; 1717 1718 /* do config file checking of compatibility */ 1719 quarantine = (e->e_quarmsg != NULL); 1720 rcode = rscheck("check_compat", e->e_from.q_paddr, to->q_paddr, 1721 e, RSF_RMCOMM|RSF_COUNT, 3, NULL, 1722 e->e_id, NULL, NULL); 1723 if (rcode == EX_OK) 1724 { 1725 /* do in-code checking if not discarding */ 1726 if (!bitset(EF_DISCARD, e->e_flags)) 1727 { 1728 rcode = checkcompat(to, e); 1729 ovr = false; 1730 } 1731 } 1732 if (rcode != EX_OK) 1733 { 1734 markfailure(e, to, NULL, rcode, ovr); 1735 giveresponse(rcode, to->q_status, m, 1736 NULL, ctladdr, xstart, e, to); 1737 continue; 1738 } 1739 if (!quarantine && e->e_quarmsg != NULL) 1740 { 1741 /* 1742 ** check_compat or checkcompat() has tried 1743 ** to quarantine but that isn't supported. 1744 ** Revert the attempt. 1745 */ 1746 1747 e->e_quarmsg = NULL; 1748 macdefine(&e->e_macro, A_PERM, 1749 macid("{quarantine}"), ""); 1750 } 1751 if (bitset(EF_DISCARD, e->e_flags)) 1752 { 1753 if (tTd(10, 5)) 1754 { 1755 sm_dprintf("deliver: discarding recipient "); 1756 printaddr(sm_debug_file(), to, false); 1757 } 1758 1759 /* pretend the message was sent */ 1760 /* XXX should we log something here? */ 1761 to->q_state = QS_DISCARDED; 1762 1763 /* 1764 ** Remove discard bit to prevent discard of 1765 ** future recipients. This is safe because the 1766 ** true "global discard" has been handled before 1767 ** we get here. 1768 */ 1769 1770 e->e_flags &= ~EF_DISCARD; 1771 continue; 1772 } 1773 1774 /* 1775 ** Strip quote bits from names if the mailer is dumb 1776 ** about them. 1777 */ 1778 1779 if (bitnset(M_STRIPQ, m->m_flags)) 1780 { 1781 stripquotes(user); 1782 stripquotes(host); 1783 } 1784 1785 /* 1786 ** Strip all leading backslashes if requested and the 1787 ** next character is alphanumerical (the latter can 1788 ** probably relaxed a bit, see RFC2821). 1789 */ 1790 1791 if (bitnset(M_STRIPBACKSL, m->m_flags) && user[0] == '\\') 1792 stripbackslash(user); 1793 1794 /* hack attack -- delivermail compatibility */ 1795 if (m == ProgMailer && *user == '|') 1796 user++; 1797 1798 /* 1799 ** If an error message has already been given, don't 1800 ** bother to send to this address. 1801 ** 1802 ** >>>>>>>>>> This clause assumes that the local mailer 1803 ** >> NOTE >> cannot do any further aliasing; that 1804 ** >>>>>>>>>> function is subsumed by sendmail. 1805 */ 1806 1807 if (!QS_IS_OK(to->q_state)) 1808 continue; 1809 1810 /* 1811 ** See if this user name is "special". 1812 ** If the user name has a slash in it, assume that this 1813 ** is a file -- send it off without further ado. Note 1814 ** that this type of addresses is not processed along 1815 ** with the others, so we fudge on the To person. 1816 */ 1817 1818 if (strcmp(m->m_mailer, "[FILE]") == 0) 1819 { 1820 macdefine(&e->e_macro, A_PERM, 'u', user); 1821 p = to->q_home; 1822 if (p == NULL && ctladdr != NULL) 1823 p = ctladdr->q_home; 1824 macdefine(&e->e_macro, A_PERM, 'z', p); 1825 expand(m->m_argv[1], buf, sizeof(buf), e); 1826 if (strlen(buf) > 0) 1827 rcode = mailfile(buf, m, ctladdr, SFF_CREAT, e); 1828 else 1829 { 1830 syserr("empty filename specification for mailer %s", 1831 m->m_name); 1832 rcode = EX_CONFIG; 1833 } 1834 giveresponse(rcode, to->q_status, m, NULL, 1835 ctladdr, xstart, e, to); 1836 markfailure(e, to, NULL, rcode, true); 1837 e->e_nsent++; 1838 if (rcode == EX_OK) 1839 { 1840 to->q_state = QS_SENT; 1841 if (bitnset(M_LOCALMAILER, m->m_flags) && 1842 bitset(QPINGONSUCCESS, to->q_flags)) 1843 { 1844 to->q_flags |= QDELIVERED; 1845 to->q_status = "2.1.5"; 1846 (void) sm_io_fprintf(e->e_xfp, 1847 SM_TIME_DEFAULT, 1848 "%s... Successfully delivered\n", 1849 to->q_paddr); 1850 } 1851 } 1852 to->q_statdate = curtime(); 1853 markstats(e, to, STATS_NORMAL); 1854 continue; 1855 } 1856 1857 /* 1858 ** Address is verified -- add this user to mailer 1859 ** argv, and add it to the print list of recipients. 1860 */ 1861 1862 /* link together the chain of recipients */ 1863 to->q_tchain = tochain; 1864 tochain = to; 1865 e->e_to = "[CHAIN]"; 1866 1867 macdefine(&e->e_macro, A_PERM, 'u', user); /* to user */ 1868 p = to->q_home; 1869 if (p == NULL && ctladdr != NULL) 1870 p = ctladdr->q_home; 1871 macdefine(&e->e_macro, A_PERM, 'z', p); /* user's home */ 1872 1873 /* set the ${dsn_notify} macro if applicable */ 1874 if (bitset(QHASNOTIFY, to->q_flags)) 1875 { 1876 char notify[MAXLINE]; 1877 1878 notify[0] = '\0'; 1879 if (bitset(QPINGONSUCCESS, to->q_flags)) 1880 (void) sm_strlcat(notify, "SUCCESS,", 1881 sizeof(notify)); 1882 if (bitset(QPINGONFAILURE, to->q_flags)) 1883 (void) sm_strlcat(notify, "FAILURE,", 1884 sizeof(notify)); 1885 if (bitset(QPINGONDELAY, to->q_flags)) 1886 (void) sm_strlcat(notify, "DELAY,", 1887 sizeof(notify)); 1888 1889 /* Set to NEVER or drop trailing comma */ 1890 if (notify[0] == '\0') 1891 (void) sm_strlcat(notify, "NEVER", 1892 sizeof(notify)); 1893 else 1894 notify[strlen(notify) - 1] = '\0'; 1895 1896 macdefine(&e->e_macro, A_TEMP, 1897 macid("{dsn_notify}"), notify); 1898 } 1899 else 1900 macdefine(&e->e_macro, A_PERM, 1901 macid("{dsn_notify}"), NULL); 1902 1903 /* 1904 ** Expand out this user into argument list. 1905 */ 1906 1907 if (!clever) 1908 { 1909 expand(*mvp, buf, sizeof(buf), e); 1910 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf); 1911 if (pvp >= &pv[MAXPV - 2]) 1912 { 1913 /* allow some space for trailing parms */ 1914 break; 1915 } 1916 } 1917 } 1918 1919 /* see if any addresses still exist */ 1920 if (tochain == NULL) 1921 { 1922 rcode = 0; 1923 goto cleanup; 1924 } 1925 1926 /* print out messages as full list */ 1927 strsize = 1; 1928 for (to = tochain; to != NULL; to = to->q_tchain) 1929 strsize += strlen(to->q_paddr) + 1; 1930 if (strsize < TOBUFSIZE) 1931 strsize = TOBUFSIZE; 1932 if (strsize > tobufsize) 1933 { 1934 SM_FREE(tobuf); 1935 tobuf = sm_pmalloc_x(strsize); 1936 tobufsize = strsize; 1937 } 1938 p = tobuf; 1939 *p = '\0'; 1940 for (to = tochain; to != NULL; to = to->q_tchain) 1941 { 1942 (void) sm_strlcpyn(p, tobufsize - (p - tobuf), 2, 1943 ",", to->q_paddr); 1944 p += strlen(p); 1945 } 1946 e->e_to = tobuf + 1; 1947 1948 /* 1949 ** Fill out any parameters after the $u parameter. 1950 */ 1951 1952 if (!clever) 1953 { 1954 while (*++mvp != NULL) 1955 { 1956 expand(*mvp, buf, sizeof(buf), e); 1957 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf); 1958 if (pvp >= &pv[MAXPV]) 1959 syserr("554 5.3.0 deliver: pv overflow after $u for %s", 1960 pv[0]); 1961 } 1962 } 1963 *pvp++ = NULL; 1964 1965 /* 1966 ** Call the mailer. 1967 ** The argument vector gets built, pipes 1968 ** are created as necessary, and we fork & exec as 1969 ** appropriate. 1970 ** If we are running SMTP, we just need to clean up. 1971 */ 1972 1973 /* XXX this seems a bit weird */ 1974 if (ctladdr == NULL && m != ProgMailer && m != FileMailer && 1975 bitset(QGOODUID, e->e_from.q_flags)) 1976 ctladdr = &e->e_from; 1977 1978 #if NAMED_BIND 1979 if (ConfigLevel < 2) 1980 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */ 1981 #endif 1982 1983 if (tTd(11, 1)) 1984 { 1985 sm_dprintf("openmailer:"); 1986 printav(sm_debug_file(), pv); 1987 } 1988 errno = 0; 1989 SM_SET_H_ERRNO(0); 1990 CurHostName = NULL; 1991 1992 /* 1993 ** Deal with the special case of mail handled through an IPC 1994 ** connection. 1995 ** In this case we don't actually fork. We must be 1996 ** running SMTP for this to work. We will return a 1997 ** zero pid to indicate that we are running IPC. 1998 ** We also handle a debug version that just talks to stdin/out. 1999 */ 2000 2001 curhost = NULL; 2002 SmtpPhase = NULL; 2003 mci = NULL; 2004 2005 #if XDEBUG 2006 { 2007 char wbuf[MAXLINE]; 2008 2009 /* make absolutely certain 0, 1, and 2 are in use */ 2010 (void) sm_snprintf(wbuf, sizeof(wbuf), "%s... openmailer(%s)", 2011 shortenstring(e->e_to, MAXSHORTSTR), 2012 m->m_name); 2013 checkfd012(wbuf); 2014 } 2015 #endif /* XDEBUG */ 2016 2017 /* check for 8-bit available */ 2018 if (bitset(EF_HAS8BIT, e->e_flags) && 2019 bitnset(M_7BITS, m->m_flags) && 2020 (bitset(EF_DONT_MIME, e->e_flags) || 2021 !(bitset(MM_MIME8BIT, MimeMode) || 2022 (bitset(EF_IS_MIME, e->e_flags) && 2023 bitset(MM_CVTMIME, MimeMode))))) 2024 { 2025 e->e_status = "5.6.3"; 2026 usrerrenh(e->e_status, 2027 "554 Cannot send 8-bit data to 7-bit destination"); 2028 rcode = EX_DATAERR; 2029 goto give_up; 2030 } 2031 2032 if (tTd(62, 8)) 2033 checkfds("before delivery"); 2034 2035 /* check for Local Person Communication -- not for mortals!!! */ 2036 if (strcmp(m->m_mailer, "[LPC]") == 0) 2037 { 2038 if (clever) 2039 { 2040 /* flush any expired connections */ 2041 (void) mci_scan(NULL); 2042 2043 /* try to get a cached connection or just a slot */ 2044 mci = mci_get(m->m_name, m); 2045 if (mci->mci_host == NULL) 2046 mci->mci_host = m->m_name; 2047 CurHostName = mci->mci_host; 2048 if (mci->mci_state != MCIS_CLOSED) 2049 { 2050 message("Using cached SMTP/LPC connection for %s...", 2051 m->m_name); 2052 mci->mci_deliveries++; 2053 goto do_transfer; 2054 } 2055 } 2056 else 2057 { 2058 mci = mci_new(e->e_rpool); 2059 } 2060 mci->mci_in = smioin; 2061 mci->mci_out = smioout; 2062 mci->mci_mailer = m; 2063 mci->mci_host = m->m_name; 2064 if (clever) 2065 { 2066 mci->mci_state = MCIS_OPENING; 2067 mci_cache(mci); 2068 } 2069 else 2070 mci->mci_state = MCIS_OPEN; 2071 } 2072 else if (strcmp(m->m_mailer, "[IPC]") == 0) 2073 { 2074 register int i; 2075 2076 if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0') 2077 { 2078 syserr("null destination for %s mailer", m->m_mailer); 2079 rcode = EX_CONFIG; 2080 goto give_up; 2081 } 2082 2083 #if NETUNIX 2084 if (strcmp(pv[0], "FILE") == 0) 2085 { 2086 curhost = CurHostName = "localhost"; 2087 mux_path = pv[1]; 2088 } 2089 else 2090 #endif /* NETUNIX */ 2091 /* "else" in #if code above */ 2092 { 2093 CurHostName = pv[1]; 2094 /* XXX ??? */ 2095 curhost = hostsignature(m, pv[1], firstto->q_flags & QSECURE); 2096 } 2097 2098 if (curhost == NULL || curhost[0] == '\0') 2099 { 2100 syserr("null host signature for %s", pv[1]); 2101 rcode = EX_CONFIG; 2102 goto give_up; 2103 } 2104 2105 if (!clever) 2106 { 2107 syserr("554 5.3.5 non-clever IPC"); 2108 rcode = EX_CONFIG; 2109 goto give_up; 2110 } 2111 if (pv[2] != NULL 2112 #if NETUNIX 2113 && mux_path == NULL 2114 #endif 2115 ) 2116 { 2117 port = htons((unsigned short) atoi(pv[2])); 2118 if (port == 0) 2119 { 2120 #ifdef NO_GETSERVBYNAME 2121 syserr("Invalid port number: %s", pv[2]); 2122 #else /* NO_GETSERVBYNAME */ 2123 struct servent *sp = getservbyname(pv[2], "tcp"); 2124 2125 if (sp == NULL) 2126 syserr("Service %s unknown", pv[2]); 2127 else 2128 port = sp->s_port; 2129 #endif /* NO_GETSERVBYNAME */ 2130 } 2131 } 2132 2133 nummxhosts = parse_hostsignature(curhost, mxhosts, m); 2134 if (TimeOuts.to_aconnect > 0) 2135 enough = curtime() + TimeOuts.to_aconnect; 2136 tryhost: 2137 while (hostnum < nummxhosts) 2138 { 2139 char sep = ':'; 2140 char *endp; 2141 static char hostbuf[MAXNAME_I + 1]; 2142 bool tried_fallbacksmarthost = false; 2143 #if DANE 2144 unsigned long tlsa_flags; 2145 2146 ste = NULL; 2147 tlsa_flags = 0; 2148 #endif 2149 #if NETINET6 2150 if (*mxhosts[hostnum] == '[') 2151 { 2152 endp = strchr(mxhosts[hostnum] + 1, ']'); 2153 if (endp != NULL) 2154 endp = strpbrk(endp + 1, ":,"); 2155 } 2156 else 2157 endp = strpbrk(mxhosts[hostnum], ":,"); 2158 #else /* NETINET6 */ 2159 endp = strpbrk(mxhosts[hostnum], ":,"); 2160 #endif /* NETINET6 */ 2161 if (endp != NULL) 2162 { 2163 sep = *endp; 2164 *endp = '\0'; 2165 } 2166 2167 if (hostnum == 1 && skip_back != NULL) 2168 { 2169 /* 2170 ** Coattail piggybacking is no longer an 2171 ** option with the mail host next to be tried 2172 ** no longer the lowest MX preference 2173 ** (hostnum == 1 meaning we're on the second 2174 ** preference). We do not try to coattail 2175 ** piggyback more than the first MX preference. 2176 ** Revert 'tochain' to last location for 2177 ** coincidental piggybacking. This works this 2178 ** easily because the q_tchain kept getting 2179 ** added to the top of the linked list. 2180 */ 2181 2182 tochain = skip_back; 2183 } 2184 2185 if (*mxhosts[hostnum] == '\0') 2186 { 2187 syserr("deliver: null host name in signature"); 2188 hostnum++; 2189 if (endp != NULL) 2190 *endp = sep; 2191 continue; 2192 } 2193 (void) sm_strlcpy(hostbuf, mxhosts[hostnum], 2194 sizeof(hostbuf)); 2195 hostnum++; 2196 if (endp != NULL) 2197 *endp = sep; 2198 #if STARTTLS 2199 tlsstate = 0; 2200 #endif 2201 2202 one_last_try: 2203 /* see if we already know that this host is fried */ 2204 CurHostName = hostbuf; 2205 mci = mci_get(hostbuf, m); 2206 if (mci->mci_state != MCIS_CLOSED) 2207 { 2208 char *type; 2209 2210 if (tTd(11, 1)) 2211 { 2212 sm_dprintf("openmailer: "); 2213 mci_dump(sm_debug_file(), mci, false); 2214 } 2215 CurHostName = mci->mci_host; 2216 if (bitnset(M_LMTP, m->m_flags)) 2217 type = "L"; 2218 else if (bitset(MCIF_ESMTP, mci->mci_flags)) 2219 type = "ES"; 2220 else 2221 type = "S"; 2222 message("Using cached %sMTP connection to %s via %s...", 2223 type, hostbuf, m->m_name); 2224 mci->mci_deliveries++; 2225 break; 2226 } 2227 mci->mci_mailer = m; 2228 #if DANE 2229 tlsa_flags = 0; 2230 if (CHK_DANE(Dane)) 2231 (void) GETTLSA(hostbuf, &ste, m->m_port); 2232 2233 /* XXX: check expiration! */ 2234 if (ste != NULL && TLSA_RR_TEMPFAIL(ste->s_tlsa)) 2235 { 2236 if (tTd(11, 1)) 2237 sm_dprintf("skip: host=%s, TLSA_RR_lookup=%d\n" 2238 , hostbuf 2239 , ste->s_tlsa->dane_tlsa_dnsrc); 2240 2241 tlsa_flags |= TLSAFLTEMP; 2242 } 2243 #endif /* DANE */ 2244 2245 if (mci->mci_exitstat != EX_OK) 2246 { 2247 if (mci->mci_exitstat == EX_TEMPFAIL) 2248 goodmxfound = true; 2249 2250 /* Try FallbackSmartHost? */ 2251 if (should_try_fbsh(e, &tried_fallbacksmarthost, 2252 hostbuf, sizeof(hostbuf), 2253 mci->mci_exitstat)) 2254 goto one_last_try; 2255 2256 continue; 2257 } 2258 2259 if (mci_lock_host(mci) != EX_OK) 2260 { 2261 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL); 2262 goodmxfound = true; 2263 continue; 2264 } 2265 2266 /* try the connection */ 2267 sm_setproctitle(true, e, "%s %s: %s", 2268 qid_printname(e), 2269 hostbuf, "user open"); 2270 #if NETUNIX 2271 if (mux_path != NULL) 2272 { 2273 message("Connecting to %s via %s...", 2274 mux_path, m->m_name); 2275 i = makeconnection_ds((char *) mux_path, mci); 2276 } 2277 else 2278 #endif /* NETUNIX */ 2279 /* "else" in #if code above */ 2280 { 2281 if (port == 0) 2282 message("Connecting to %s via %s...", 2283 hostbuf, m->m_name); 2284 else 2285 message("Connecting to %s port %d via %s...", 2286 hostbuf, ntohs(port), 2287 m->m_name); 2288 2289 /* 2290 ** XXX OK to do this here already? 2291 ** set the current connection information 2292 ** required to set {client_flags} in e->e_mci 2293 */ 2294 2295 e->e_mci = mci; 2296 if ((i = cltfeatures(e, hostbuf)) != EX_OK) 2297 { 2298 if (LogLevel > 8) 2299 sm_syslog(LOG_WARNING, e->e_id, 2300 "clt_features=TEMPFAIL, host=%s, status=skipped" 2301 , hostbuf); 2302 /* XXX handle error! */ 2303 (void) sm_strlcpy(SmtpError, 2304 "clt_features=TEMPFAIL", 2305 sizeof(SmtpError)); 2306 #if DANE 2307 tlsa_flags &= ~TLSAFLTEMP; 2308 #endif 2309 } 2310 #if DANE 2311 /* hack: disable DANE if requested */ 2312 if (iscltflgset(e, D_NODANE)) 2313 ste = NULL; 2314 tlsa_flags |= ste != NULL ? Dane : DANE_NEVER; 2315 dane_vrfy_ctx.dane_vrfy_chk = tlsa_flags; 2316 dane_vrfy_ctx.dane_vrfy_port = m->m_port; 2317 if (tTd(11, 11)) 2318 sm_dprintf("makeconnection: before: chk=%d, tlsa_flags=%lX, {client_flags}=%s\n", dane_vrfy_ctx.dane_vrfy_chk, tlsa_flags, macvalue(macid("{client_flags}"), e)); 2319 #endif 2320 if (EX_OK == i) 2321 i = makeconnection(hostbuf, port, mci, 2322 e, enough 2323 #if DANE 2324 , &tlsa_flags 2325 #endif 2326 ); 2327 #if DANE 2328 if (tTd(11, 11)) 2329 sm_dprintf("makeconnection: after: chk=%d, tlsa_flags=%lX\n", dane_vrfy_ctx.dane_vrfy_chk, tlsa_flags); 2330 if (dane_vrfy_ctx.dane_vrfy_chk != DANE_ALWAYS) 2331 dane_vrfy_ctx.dane_vrfy_chk = DANEMODE(tlsa_flags); 2332 if (EX_TEMPFAIL == i && 2333 ((tlsa_flags & (TLSAFLTEMP|DANE_SECURE)) == 2334 (TLSAFLTEMP|DANE_SECURE))) 2335 { 2336 (void) sm_strlcpy(SmtpError, 2337 " for TLSA RR", 2338 sizeof(SmtpError)); 2339 # if NAMED_BIND 2340 SM_SET_H_ERRNO(TRY_AGAIN); 2341 # endif 2342 } 2343 #endif 2344 } 2345 mci->mci_errno = errno; 2346 mci->mci_lastuse = curtime(); 2347 mci->mci_deliveries = 0; 2348 mci->mci_exitstat = i; 2349 mci_clr_extensions(mci); 2350 #if NAMED_BIND 2351 mci->mci_herrno = h_errno; 2352 #endif 2353 2354 /* 2355 ** Have we tried long enough to get a connection? 2356 ** If yes, skip to the fallback MX hosts 2357 ** (if existent). 2358 */ 2359 2360 if (enough > 0 && mci->mci_lastuse >= enough) 2361 { 2362 int h; 2363 #if NAMED_BIND 2364 extern int NumFallbackMXHosts; 2365 #else 2366 const int NumFallbackMXHosts = 0; 2367 #endif 2368 2369 if (hostnum < nummxhosts && LogLevel > 9) 2370 sm_syslog(LOG_INFO, e->e_id, 2371 "Timeout.to_aconnect occurred before exhausting all addresses"); 2372 2373 /* turn off timeout if fallback available */ 2374 if (NumFallbackMXHosts > 0) 2375 enough = 0; 2376 2377 /* skip to a fallback MX host */ 2378 h = nummxhosts - NumFallbackMXHosts; 2379 if (hostnum < h) 2380 hostnum = h; 2381 } 2382 if (i == EX_OK) 2383 { 2384 goodmxfound = true; 2385 markstats(e, firstto, STATS_CONNECT); 2386 mci->mci_state = MCIS_OPENING; 2387 mci_cache(mci); 2388 if (TrafficLogFile != NULL) 2389 (void) sm_io_fprintf(TrafficLogFile, 2390 SM_TIME_DEFAULT, 2391 "%05d === CONNECT %s\n", 2392 (int) CurrentPid, 2393 hostbuf); 2394 break; 2395 } 2396 else 2397 { 2398 /* Try FallbackSmartHost? */ 2399 if (should_try_fbsh(e, &tried_fallbacksmarthost, 2400 hostbuf, sizeof(hostbuf), i)) 2401 goto one_last_try; 2402 2403 if (tTd(11, 1)) 2404 sm_dprintf("openmailer: makeconnection => stat=%d, errno=%d\n", 2405 i, errno); 2406 if (i == EX_TEMPFAIL) 2407 goodmxfound = true; 2408 mci_unlock_host(mci); 2409 } 2410 2411 /* enter status of this host */ 2412 setstat(i); 2413 2414 /* should print some message here for -v mode */ 2415 } 2416 if (mci == NULL) 2417 { 2418 syserr("deliver: no host name"); 2419 rcode = EX_SOFTWARE; 2420 goto give_up; 2421 } 2422 mci->mci_pid = 0; 2423 } 2424 else 2425 { 2426 /* flush any expired connections */ 2427 (void) mci_scan(NULL); 2428 mci = NULL; 2429 2430 if (bitnset(M_LMTP, m->m_flags)) 2431 { 2432 /* try to get a cached connection */ 2433 mci = mci_get(m->m_name, m); 2434 if (mci->mci_host == NULL) 2435 mci->mci_host = m->m_name; 2436 CurHostName = mci->mci_host; 2437 if (mci->mci_state != MCIS_CLOSED) 2438 { 2439 message("Using cached LMTP connection for %s...", 2440 m->m_name); 2441 mci->mci_deliveries++; 2442 goto do_transfer; 2443 } 2444 } 2445 2446 /* announce the connection to verbose listeners */ 2447 if (host == NULL || host[0] == '\0') 2448 message("Connecting to %s...", m->m_name); 2449 else 2450 message("Connecting to %s via %s...", host, m->m_name); 2451 if (TrafficLogFile != NULL) 2452 { 2453 char **av; 2454 2455 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, 2456 "%05d === EXEC", (int) CurrentPid); 2457 for (av = pv; *av != NULL; av++) 2458 (void) sm_io_fprintf(TrafficLogFile, 2459 SM_TIME_DEFAULT, " %s", 2460 *av); 2461 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, 2462 "\n"); 2463 } 2464 2465 #if XDEBUG 2466 checkfd012("before creating mail pipe"); 2467 #endif 2468 2469 /* create a pipe to shove the mail through */ 2470 if (pipe(mpvect) < 0) 2471 { 2472 syserr("%s... openmailer(%s): pipe (to mailer)", 2473 shortenstring(e->e_to, MAXSHORTSTR), m->m_name); 2474 if (tTd(11, 1)) 2475 sm_dprintf("openmailer: NULL\n"); 2476 rcode = EX_OSERR; 2477 goto give_up; 2478 } 2479 2480 #if XDEBUG 2481 /* make sure we didn't get one of the standard I/O files */ 2482 if (mpvect[0] < 3 || mpvect[1] < 3) 2483 { 2484 syserr("%s... openmailer(%s): bogus mpvect %d %d", 2485 shortenstring(e->e_to, MAXSHORTSTR), m->m_name, 2486 mpvect[0], mpvect[1]); 2487 printopenfds(true); 2488 if (tTd(11, 1)) 2489 sm_dprintf("openmailer: NULL\n"); 2490 rcode = EX_OSERR; 2491 goto give_up; 2492 } 2493 2494 /* make sure system call isn't dead meat */ 2495 checkfdopen(mpvect[0], "mpvect[0]"); 2496 checkfdopen(mpvect[1], "mpvect[1]"); 2497 if (mpvect[0] == mpvect[1] || 2498 (e->e_lockfp != NULL && 2499 (mpvect[0] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, 2500 NULL) || 2501 mpvect[1] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, 2502 NULL)))) 2503 { 2504 if (e->e_lockfp == NULL) 2505 syserr("%s... openmailer(%s): overlapping mpvect %d %d", 2506 shortenstring(e->e_to, MAXSHORTSTR), 2507 m->m_name, mpvect[0], mpvect[1]); 2508 else 2509 syserr("%s... openmailer(%s): overlapping mpvect %d %d, lockfp = %d", 2510 shortenstring(e->e_to, MAXSHORTSTR), 2511 m->m_name, mpvect[0], mpvect[1], 2512 sm_io_getinfo(e->e_lockfp, 2513 SM_IO_WHAT_FD, NULL)); 2514 } 2515 #endif /* XDEBUG */ 2516 2517 /* create a return pipe */ 2518 if (pipe(rpvect) < 0) 2519 { 2520 syserr("%s... openmailer(%s): pipe (from mailer)", 2521 shortenstring(e->e_to, MAXSHORTSTR), 2522 m->m_name); 2523 (void) close(mpvect[0]); 2524 (void) close(mpvect[1]); 2525 if (tTd(11, 1)) 2526 sm_dprintf("openmailer: NULL\n"); 2527 rcode = EX_OSERR; 2528 goto give_up; 2529 } 2530 #if XDEBUG 2531 checkfdopen(rpvect[0], "rpvect[0]"); 2532 checkfdopen(rpvect[1], "rpvect[1]"); 2533 #endif 2534 2535 /* 2536 ** Actually fork the mailer process. 2537 ** DOFORK is clever about retrying. 2538 ** 2539 ** Dispose of SIGCHLD signal catchers that may be laying 2540 ** around so that endmailer will get it. 2541 */ 2542 2543 if (e->e_xfp != NULL) /* for debugging */ 2544 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT); 2545 (void) sm_io_flush(smioout, SM_TIME_DEFAULT); 2546 (void) sm_signal(SIGCHLD, SIG_DFL); 2547 2548 2549 DOFORK(FORK); 2550 /* pid is set by DOFORK */ 2551 2552 if (pid < 0) 2553 { 2554 /* failure */ 2555 syserr("%s... openmailer(%s): cannot fork", 2556 shortenstring(e->e_to, MAXSHORTSTR), m->m_name); 2557 (void) close(mpvect[0]); 2558 (void) close(mpvect[1]); 2559 (void) close(rpvect[0]); 2560 (void) close(rpvect[1]); 2561 if (tTd(11, 1)) 2562 sm_dprintf("openmailer: NULL\n"); 2563 rcode = EX_OSERR; 2564 goto give_up; 2565 } 2566 else if (pid == 0) 2567 { 2568 int save_errno; 2569 int sff; 2570 int new_euid = NO_UID; 2571 int new_ruid = NO_UID; 2572 int new_gid = NO_GID; 2573 char *user = NULL; 2574 struct stat stb; 2575 extern int DtableSize; 2576 2577 CurrentPid = getpid(); 2578 2579 /* clear the events to turn off SIGALRMs */ 2580 sm_clear_events(); 2581 2582 /* Reset global flags */ 2583 RestartRequest = NULL; 2584 RestartWorkGroup = false; 2585 ShutdownRequest = NULL; 2586 PendingSignal = 0; 2587 2588 if (e->e_lockfp != NULL) 2589 (void) close(sm_io_getinfo(e->e_lockfp, 2590 SM_IO_WHAT_FD, 2591 NULL)); 2592 2593 /* child -- set up input & exec mailer */ 2594 (void) sm_signal(SIGALRM, sm_signal_noop); 2595 (void) sm_signal(SIGCHLD, SIG_DFL); 2596 (void) sm_signal(SIGHUP, SIG_IGN); 2597 (void) sm_signal(SIGINT, SIG_IGN); 2598 (void) sm_signal(SIGTERM, SIG_DFL); 2599 #ifdef SIGUSR1 2600 (void) sm_signal(SIGUSR1, sm_signal_noop); 2601 #endif 2602 2603 if (m != FileMailer || stat(tochain->q_user, &stb) < 0) 2604 stb.st_mode = 0; 2605 2606 #if HASSETUSERCONTEXT 2607 /* 2608 ** Set user resources. 2609 */ 2610 2611 if (contextaddr != NULL) 2612 { 2613 int sucflags; 2614 struct passwd *pwd; 2615 2616 if (contextaddr->q_ruser != NULL) 2617 pwd = sm_getpwnam(contextaddr->q_ruser); 2618 else 2619 pwd = sm_getpwnam(contextaddr->q_user); 2620 sucflags = LOGIN_SETRESOURCES|LOGIN_SETPRIORITY; 2621 # ifdef LOGIN_SETCPUMASK 2622 sucflags |= LOGIN_SETCPUMASK; 2623 # endif 2624 # ifdef LOGIN_SETLOGINCLASS 2625 sucflags |= LOGIN_SETLOGINCLASS; 2626 # endif 2627 # ifdef LOGIN_SETMAC 2628 sucflags |= LOGIN_SETMAC; 2629 # endif 2630 if (pwd != NULL && 2631 setusercontext(NULL, pwd, pwd->pw_uid, 2632 sucflags) == -1 && 2633 suidwarn) 2634 { 2635 syserr("openmailer: setusercontext() failed"); 2636 exit(EX_TEMPFAIL); 2637 } 2638 } 2639 #endif /* HASSETUSERCONTEXT */ 2640 2641 #if HASNICE 2642 /* tweak niceness */ 2643 if (m->m_nice != 0) 2644 (void) nice(m->m_nice); 2645 #endif 2646 2647 /* reset group id */ 2648 if (bitnset(M_SPECIFIC_UID, m->m_flags)) 2649 { 2650 if (m->m_gid == NO_GID) 2651 new_gid = RunAsGid; 2652 else 2653 new_gid = m->m_gid; 2654 } 2655 else if (bitset(S_ISGID, stb.st_mode)) 2656 new_gid = stb.st_gid; 2657 else if (ctladdr != NULL && ctladdr->q_gid != 0) 2658 { 2659 if (!DontInitGroups) 2660 { 2661 user = ctladdr->q_ruser; 2662 if (user == NULL) 2663 user = ctladdr->q_user; 2664 2665 if (initgroups(user, 2666 ctladdr->q_gid) == -1 2667 && suidwarn) 2668 { 2669 syserr("openmailer: initgroups(%s, %ld) failed", 2670 user, (long) ctladdr->q_gid); 2671 exit(EX_TEMPFAIL); 2672 } 2673 } 2674 else 2675 { 2676 GIDSET_T gidset[1]; 2677 2678 gidset[0] = ctladdr->q_gid; 2679 if (setgroups(1, gidset) == -1 2680 && suidwarn) 2681 { 2682 syserr("openmailer: setgroups() failed"); 2683 exit(EX_TEMPFAIL); 2684 } 2685 } 2686 new_gid = ctladdr->q_gid; 2687 } 2688 else 2689 { 2690 if (!DontInitGroups) 2691 { 2692 user = DefUser; 2693 if (initgroups(DefUser, DefGid) == -1 && 2694 suidwarn) 2695 { 2696 syserr("openmailer: initgroups(%s, %ld) failed", 2697 DefUser, (long) DefGid); 2698 exit(EX_TEMPFAIL); 2699 } 2700 } 2701 else 2702 { 2703 GIDSET_T gidset[1]; 2704 2705 gidset[0] = DefGid; 2706 if (setgroups(1, gidset) == -1 2707 && suidwarn) 2708 { 2709 syserr("openmailer: setgroups() failed"); 2710 exit(EX_TEMPFAIL); 2711 } 2712 } 2713 if (m->m_gid == NO_GID) 2714 new_gid = DefGid; 2715 else 2716 new_gid = m->m_gid; 2717 } 2718 if (new_gid != NO_GID) 2719 { 2720 if (RunAsUid != 0 && 2721 bitnset(M_SPECIFIC_UID, m->m_flags) && 2722 new_gid != getgid() && 2723 new_gid != getegid()) 2724 { 2725 /* Only root can change the gid */ 2726 syserr("openmailer: insufficient privileges to change gid, RunAsUid=%ld, new_gid=%ld, gid=%ld, egid=%ld", 2727 (long) RunAsUid, (long) new_gid, 2728 (long) getgid(), (long) getegid()); 2729 exit(EX_TEMPFAIL); 2730 } 2731 2732 if (setgid(new_gid) < 0 && suidwarn) 2733 { 2734 syserr("openmailer: setgid(%ld) failed", 2735 (long) new_gid); 2736 exit(EX_TEMPFAIL); 2737 } 2738 } 2739 2740 /* change root to some "safe" directory */ 2741 if (m->m_rootdir != NULL) 2742 { 2743 expand(m->m_rootdir, cbuf, sizeof(cbuf), e); 2744 if (tTd(11, 20)) 2745 sm_dprintf("openmailer: chroot %s\n", 2746 cbuf); 2747 if (chroot(cbuf) < 0) 2748 { 2749 syserr("openmailer: Cannot chroot(%s)", 2750 cbuf); 2751 exit(EX_TEMPFAIL); 2752 } 2753 if (chdir("/") < 0) 2754 { 2755 syserr("openmailer: cannot chdir(/)"); 2756 exit(EX_TEMPFAIL); 2757 } 2758 } 2759 2760 /* reset user id */ 2761 endpwent(); 2762 sm_mbdb_terminate(); 2763 if (bitnset(M_SPECIFIC_UID, m->m_flags)) 2764 { 2765 if (m->m_uid == NO_UID) 2766 new_euid = RunAsUid; 2767 else 2768 new_euid = m->m_uid; 2769 2770 /* 2771 ** Undo the effects of the uid change in main 2772 ** for signal handling. The real uid may 2773 ** be used by mailer in adding a "From " 2774 ** line. 2775 */ 2776 2777 if (RealUid != 0 && RealUid != getuid()) 2778 { 2779 #if MAILER_SETUID_METHOD == USE_SETEUID 2780 # if HASSETREUID 2781 if (setreuid(RealUid, geteuid()) < 0) 2782 { 2783 syserr("openmailer: setreuid(%d, %d) failed", 2784 (int) RealUid, (int) geteuid()); 2785 exit(EX_OSERR); 2786 } 2787 # endif /* HASSETREUID */ 2788 #endif /* MAILER_SETUID_METHOD == USE_SETEUID */ 2789 #if MAILER_SETUID_METHOD == USE_SETREUID 2790 new_ruid = RealUid; 2791 #endif 2792 } 2793 } 2794 else if (bitset(S_ISUID, stb.st_mode)) 2795 new_ruid = stb.st_uid; 2796 else if (ctladdr != NULL && ctladdr->q_uid != 0) 2797 new_ruid = ctladdr->q_uid; 2798 else if (m->m_uid != NO_UID) 2799 new_ruid = m->m_uid; 2800 else 2801 new_ruid = DefUid; 2802 2803 #if _FFR_USE_SETLOGIN 2804 /* run disconnected from terminal and set login name */ 2805 if (setsid() >= 0 && 2806 ctladdr != NULL && ctladdr->q_uid != 0 && 2807 new_euid == ctladdr->q_uid) 2808 { 2809 struct passwd *pwd; 2810 2811 pwd = sm_getpwuid(ctladdr->q_uid); 2812 if (pwd != NULL && suidwarn) 2813 (void) setlogin(pwd->pw_name); 2814 endpwent(); 2815 } 2816 #endif /* _FFR_USE_SETLOGIN */ 2817 2818 if (new_euid != NO_UID) 2819 { 2820 if (RunAsUid != 0 && new_euid != RunAsUid) 2821 { 2822 /* Only root can change the uid */ 2823 syserr("openmailer: insufficient privileges to change uid, new_euid=%ld, RunAsUid=%ld", 2824 (long) new_euid, (long) RunAsUid); 2825 exit(EX_TEMPFAIL); 2826 } 2827 2828 vendor_set_uid(new_euid); 2829 #if MAILER_SETUID_METHOD == USE_SETEUID 2830 if (seteuid(new_euid) < 0 && suidwarn) 2831 { 2832 syserr("openmailer: seteuid(%ld) failed", 2833 (long) new_euid); 2834 exit(EX_TEMPFAIL); 2835 } 2836 #endif /* MAILER_SETUID_METHOD == USE_SETEUID */ 2837 #if MAILER_SETUID_METHOD == USE_SETREUID 2838 if (setreuid(new_ruid, new_euid) < 0 && suidwarn) 2839 { 2840 syserr("openmailer: setreuid(%ld, %ld) failed", 2841 (long) new_ruid, (long) new_euid); 2842 exit(EX_TEMPFAIL); 2843 } 2844 #endif /* MAILER_SETUID_METHOD == USE_SETREUID */ 2845 #if MAILER_SETUID_METHOD == USE_SETUID 2846 if (new_euid != geteuid() && setuid(new_euid) < 0 && suidwarn) 2847 { 2848 syserr("openmailer: setuid(%ld) failed", 2849 (long) new_euid); 2850 exit(EX_TEMPFAIL); 2851 } 2852 #endif /* MAILER_SETUID_METHOD == USE_SETUID */ 2853 } 2854 else if (new_ruid != NO_UID) 2855 { 2856 vendor_set_uid(new_ruid); 2857 if (setuid(new_ruid) < 0 && suidwarn) 2858 { 2859 syserr("openmailer: setuid(%ld) failed", 2860 (long) new_ruid); 2861 exit(EX_TEMPFAIL); 2862 } 2863 } 2864 2865 if (tTd(11, 2)) 2866 sm_dprintf("openmailer: running as r/euid=%ld/%ld, r/egid=%ld/%ld\n", 2867 (long) getuid(), (long) geteuid(), 2868 (long) getgid(), (long) getegid()); 2869 2870 /* move into some "safe" directory */ 2871 if (m->m_execdir != NULL) 2872 { 2873 char *q; 2874 2875 for (p = m->m_execdir; p != NULL; p = q) 2876 { 2877 q = strchr(p, ':'); 2878 if (q != NULL) 2879 *q = '\0'; 2880 expand(p, cbuf, sizeof(cbuf), e); 2881 if (q != NULL) 2882 *q++ = ':'; 2883 if (tTd(11, 20)) 2884 sm_dprintf("openmailer: trydir %s\n", 2885 cbuf); 2886 if (cbuf[0] != '\0' && 2887 chdir(cbuf) >= 0) 2888 break; 2889 } 2890 } 2891 2892 /* Check safety of program to be run */ 2893 sff = SFF_ROOTOK|SFF_EXECOK; 2894 if (!bitnset(DBS_RUNWRITABLEPROGRAM, 2895 DontBlameSendmail)) 2896 sff |= SFF_NOGWFILES|SFF_NOWWFILES; 2897 if (bitnset(DBS_RUNPROGRAMINUNSAFEDIRPATH, 2898 DontBlameSendmail)) 2899 sff |= SFF_NOPATHCHECK; 2900 else 2901 sff |= SFF_SAFEDIRPATH; 2902 ret = safefile(m->m_mailer, getuid(), getgid(), 2903 user, sff, 0, NULL); 2904 if (ret != 0) 2905 sm_syslog(LOG_INFO, e->e_id, 2906 "Warning: program %s unsafe: %s", 2907 m->m_mailer, sm_errstring(ret)); 2908 2909 /* arrange to filter std & diag output of command */ 2910 (void) close(rpvect[0]); 2911 if (dup2(rpvect[1], STDOUT_FILENO) < 0) 2912 { 2913 syserr("%s... openmailer(%s): cannot dup pipe %d for stdout", 2914 shortenstring(e->e_to, MAXSHORTSTR), 2915 m->m_name, rpvect[1]); 2916 _exit(EX_OSERR); 2917 } 2918 (void) close(rpvect[1]); 2919 2920 if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0) 2921 { 2922 syserr("%s... openmailer(%s): cannot dup stdout for stderr", 2923 shortenstring(e->e_to, MAXSHORTSTR), 2924 m->m_name); 2925 _exit(EX_OSERR); 2926 } 2927 2928 /* arrange to get standard input */ 2929 (void) close(mpvect[1]); 2930 if (dup2(mpvect[0], STDIN_FILENO) < 0) 2931 { 2932 syserr("%s... openmailer(%s): cannot dup pipe %d for stdin", 2933 shortenstring(e->e_to, MAXSHORTSTR), 2934 m->m_name, mpvect[0]); 2935 _exit(EX_OSERR); 2936 } 2937 (void) close(mpvect[0]); 2938 2939 /* arrange for all the files to be closed */ 2940 sm_close_on_exec(STDERR_FILENO + 1, DtableSize); 2941 2942 #if !_FFR_USE_SETLOGIN 2943 /* run disconnected from terminal */ 2944 (void) setsid(); 2945 #endif 2946 2947 /* try to execute the mailer */ 2948 (void) execve(m->m_mailer, (ARGV_T) pv, 2949 (ARGV_T) UserEnviron); 2950 save_errno = errno; 2951 syserr("Cannot exec %s", m->m_mailer); 2952 if (bitnset(M_LOCALMAILER, m->m_flags) || 2953 transienterror(save_errno)) 2954 _exit(EX_OSERR); 2955 _exit(EX_UNAVAILABLE); 2956 } 2957 2958 /* 2959 ** Set up return value. 2960 */ 2961 2962 if (mci == NULL) 2963 { 2964 if (clever) 2965 { 2966 /* 2967 ** Allocate from general heap, not 2968 ** envelope rpool, because this mci 2969 ** is going to be cached. 2970 */ 2971 2972 mci = mci_new(NULL); 2973 } 2974 else 2975 { 2976 /* 2977 ** Prevent a storage leak by allocating 2978 ** this from the envelope rpool. 2979 */ 2980 2981 mci = mci_new(e->e_rpool); 2982 } 2983 } 2984 mci->mci_mailer = m; 2985 if (clever) 2986 { 2987 mci->mci_state = MCIS_OPENING; 2988 mci_cache(mci); 2989 } 2990 else 2991 { 2992 mci->mci_state = MCIS_OPEN; 2993 } 2994 mci->mci_pid = pid; 2995 (void) close(mpvect[0]); 2996 mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, 2997 (void *) &(mpvect[1]), SM_IO_WRONLY_B, 2998 NULL); 2999 if (mci->mci_out == NULL) 3000 { 3001 syserr("deliver: cannot create mailer output channel, fd=%d", 3002 mpvect[1]); 3003 (void) close(mpvect[1]); 3004 (void) close(rpvect[0]); 3005 (void) close(rpvect[1]); 3006 rcode = EX_OSERR; 3007 goto give_up; 3008 } 3009 3010 (void) close(rpvect[1]); 3011 mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, 3012 (void *) &(rpvect[0]), SM_IO_RDONLY_B, 3013 NULL); 3014 if (mci->mci_in == NULL) 3015 { 3016 syserr("deliver: cannot create mailer input channel, fd=%d", 3017 mpvect[1]); 3018 (void) close(rpvect[0]); 3019 SM_CLOSE_FP(mci->mci_out); 3020 rcode = EX_OSERR; 3021 goto give_up; 3022 } 3023 } 3024 3025 /* 3026 ** If we are in SMTP opening state, send initial protocol. 3027 */ 3028 3029 if (bitnset(M_7BITS, m->m_flags) && 3030 (!clever || mci->mci_state == MCIS_OPENING)) 3031 mci->mci_flags |= MCIF_7BIT; 3032 if (clever && mci->mci_state != MCIS_CLOSED) 3033 { 3034 #if STARTTLS || SASL 3035 char *srvname; 3036 extern SOCKADDR CurHostAddr; 3037 #endif 3038 3039 #if SASL 3040 # define DONE_AUTH(f) bitset(MCIF_AUTHACT, f) 3041 #endif 3042 #if STARTTLS 3043 # define DONE_STARTTLS(f) bitset(MCIF_TLSACT, f) 3044 #endif 3045 #define ONLY_HELO(f) bitset(MCIF_ONLY_EHLO, f) 3046 #define SET_HELO(f) f |= MCIF_ONLY_EHLO 3047 #define CLR_HELO(f) f &= ~MCIF_ONLY_EHLO 3048 3049 #if STARTTLS || SASL 3050 /* don't use CurHostName, it is changed in many places */ 3051 if (mci->mci_host != NULL) 3052 { 3053 srvname = mci->mci_host; 3054 RM_TRAIL_DOT(srvname); 3055 } 3056 else if (mci->mci_mailer != NULL) 3057 { 3058 srvname = mci->mci_mailer->m_name; 3059 dotpos = -1; 3060 } 3061 else 3062 { 3063 srvname = "local"; 3064 dotpos = -1; 3065 } 3066 3067 /* don't set {server_name} to NULL or "": see getauth() */ 3068 macdefine(&mci->mci_macro, A_TEMP, macid("{server_name}"), 3069 srvname); 3070 3071 /* CurHostAddr is set by makeconnection() and mci_get() */ 3072 if (CurHostAddr.sa.sa_family != 0) 3073 { 3074 macdefine(&mci->mci_macro, A_TEMP, 3075 macid("{server_addr}"), 3076 anynet_ntoa(&CurHostAddr)); 3077 } 3078 else if (mci->mci_mailer != NULL) 3079 { 3080 /* mailer name is unique, use it as address */ 3081 macdefine(&mci->mci_macro, A_PERM, 3082 macid("{server_addr}"), 3083 mci->mci_mailer->m_name); 3084 } 3085 else 3086 { 3087 /* don't set it to NULL or "": see getauth() */ 3088 macdefine(&mci->mci_macro, A_PERM, 3089 macid("{server_addr}"), "0"); 3090 } 3091 3092 # if DANE 3093 SM_FREE(dane_vrfy_ctx.dane_vrfy_host); 3094 SM_FREE(dane_vrfy_ctx.dane_vrfy_sni); 3095 dane_vrfy_ctx.dane_vrfy_fp[0] = '\0'; 3096 if (ste != NULL && ste->s_tlsa != NULL && 3097 ste->s_tlsa->dane_tlsa_sni != NULL) 3098 dane_vrfy_ctx.dane_vrfy_sni = sm_strdup(ste->s_tlsa->dane_tlsa_sni); 3099 dane_vrfy_ctx.dane_vrfy_host = sm_strdup(srvname); 3100 # endif 3101 3102 /* undo change of srvname (mci->mci_host) */ 3103 FIX_TRAIL_DOT(srvname); 3104 3105 reconnect: /* after switching to an encrypted connection */ 3106 # if DANE 3107 if (DONE_STARTTLS(mci->mci_flags)) 3108 { 3109 /* use a "reset" function? */ 3110 SM_FREE(dane_vrfy_ctx.dane_vrfy_host); 3111 SM_FREE(dane_vrfy_ctx.dane_vrfy_sni); 3112 dane_vrfy_ctx.dane_vrfy_fp[0] = '\0'; 3113 dane_vrfy_ctx.dane_vrfy_res = 0; 3114 } 3115 # endif /* DANE */ 3116 3117 #endif /* STARTTLS || SASL */ 3118 3119 /* set the current connection information */ 3120 e->e_mci = mci; 3121 #if SASL 3122 mci->mci_saslcap = NULL; 3123 #endif 3124 #if _FFR_MTA_STS 3125 # define USEMTASTS (MTASTS && !SM_TLSI_IS(&(mci->mci_tlsi), TLSI_FL_NOSTS) && !iscltflgset(e, D_NOSTS)) 3126 # if DANE 3127 # define CHKMTASTS (USEMTASTS && (ste == NULL || ste->s_tlsa == NULL || SM_TLSI_IS(&(mci->mci_tlsi), TLSI_FL_NODANE))) 3128 # else 3129 # define CHKMTASTS USEMTASTS 3130 # endif 3131 #endif /* _FFR_MTA_STS */ 3132 #if _FFR_MTA_STS 3133 if (!DONE_STARTTLS(mci->mci_flags)) 3134 { 3135 /* 3136 ** HACK: use the domain of the first valid RCPT for STS. 3137 ** It seems whoever wrote the specs did not consider 3138 ** SMTP sessions versus transactions. 3139 ** (but what would you expect from people who try 3140 ** to use https for "security" after relying on DNS?) 3141 */ 3142 3143 macdefine(&e->e_macro, A_PERM, macid("{rcpt_addr}"), ""); 3144 # if DANE 3145 if (MTASTS && (ste != NULL && ste->s_tlsa != NULL)) 3146 macdefine(&e->e_macro, A_PERM, macid("{sts_sni}"), "DANE"); 3147 else 3148 # endif 3149 macdefine(&e->e_macro, A_PERM, macid("{sts_sni}"), ""); 3150 if (USEMTASTS && firstto->q_user != NULL) 3151 { 3152 if (tTd(10, 64)) 3153 { 3154 sm_dprintf("firstto "); 3155 printaddr(sm_debug_file(), firstto, false); 3156 } 3157 macdefine(&e->e_macro, A_TEMP, 3158 macid("{rcpt_addr}"), firstto->q_user); 3159 } 3160 else if (USEMTASTS) 3161 { 3162 if (tTd(10, 64)) 3163 { 3164 sm_dprintf("tochain "); 3165 printaddr(sm_debug_file(), tochain, false); 3166 } 3167 for (to = tochain; to != NULL; to = to->q_tchain) 3168 { 3169 if (!QS_IS_UNMARKED(to->q_state)) 3170 continue; 3171 if (to->q_user == NULL) 3172 continue; 3173 macdefine(&e->e_macro, A_TEMP, 3174 macid("{rcpt_addr}"), to->q_user); 3175 break; 3176 } 3177 } 3178 } 3179 #endif /* _FFR_MTA_STS */ 3180 #if USE_EAI 3181 if (!addr_is_ascii(e->e_from.q_paddr) && !e->e_smtputf8) 3182 e->e_smtputf8 = true; 3183 for (to = tochain; to != NULL && !e->e_smtputf8; to = to->q_tchain) 3184 { 3185 if (!QS_IS_UNMARKED(to->q_state)) 3186 continue; 3187 if (!addr_is_ascii(to->q_user)) 3188 e->e_smtputf8 = true; 3189 } 3190 /* XXX reset e_smtputf8 to original state at the end? */ 3191 #endif /* USE_EAI */ 3192 3193 smtpinit(m, mci, e, ONLY_HELO(mci->mci_flags)); 3194 CLR_HELO(mci->mci_flags); 3195 3196 if (IS_DLVR_RETURN(e)) 3197 { 3198 /* 3199 ** Check whether other side can deliver e-mail 3200 ** fast enough 3201 */ 3202 3203 if (!bitset(MCIF_DLVR_BY, mci->mci_flags)) 3204 { 3205 e->e_status = "5.4.7"; 3206 usrerrenh(e->e_status, 3207 "554 Server does not support Deliver By"); 3208 rcode = EX_UNAVAILABLE; 3209 goto give_up; 3210 } 3211 if (e->e_deliver_by > 0 && 3212 e->e_deliver_by - (curtime() - e->e_ctime) < 3213 mci->mci_min_by) 3214 { 3215 e->e_status = "5.4.7"; 3216 usrerrenh(e->e_status, 3217 "554 Message can't be delivered in time; %ld < %ld", 3218 e->e_deliver_by - (long) (curtime() - 3219 e->e_ctime), 3220 mci->mci_min_by); 3221 rcode = EX_UNAVAILABLE; 3222 goto give_up; 3223 } 3224 } 3225 3226 #if STARTTLS 3227 /* first TLS then AUTH to provide a security layer */ 3228 if (mci->mci_state != MCIS_CLOSED && 3229 !DONE_STARTTLS(mci->mci_flags)) 3230 { 3231 int olderrors; 3232 bool usetls; 3233 bool saveQuickAbort = QuickAbort; 3234 bool saveSuprErrs = SuprErrs; 3235 char *host = NULL; 3236 3237 rcode = EX_OK; 3238 usetls = bitset(MCIF_TLS, mci->mci_flags); 3239 if (usetls) 3240 usetls = !iscltflgset(e, D_NOTLS); 3241 if (usetls) 3242 usetls = tlsstate == 0; 3243 3244 host = macvalue(macid("{server_name}"), e); 3245 if (usetls) 3246 { 3247 olderrors = Errors; 3248 QuickAbort = false; 3249 SuprErrs = true; 3250 if (rscheck("try_tls", host, NULL, e, 3251 RSF_RMCOMM, 7, host, NOQID, NULL, 3252 NULL) != EX_OK 3253 || Errors > olderrors) 3254 { 3255 usetls = false; 3256 } 3257 SuprErrs = saveSuprErrs; 3258 QuickAbort = saveQuickAbort; 3259 } 3260 3261 if (usetls) 3262 { 3263 if ((rcode = starttls(m, mci, e 3264 # if DANE 3265 , &dane_vrfy_ctx 3266 # endif 3267 )) == EX_OK) 3268 { 3269 /* start again without STARTTLS */ 3270 mci->mci_flags |= MCIF_TLSACT; 3271 # if DANE && _FFR_MTA_STS 3272 /* if DANE is used (and STS should be used): disable STS */ 3273 /* also check MTASTS and NOSTS flag? */ 3274 if (ste != NULL && ste->s_tlsa != NULL && 3275 !SM_TLSI_IS(&(mci->mci_tlsi), TLSI_FL_NODANE)) 3276 macdefine(&e->e_macro, A_PERM, macid("{rcpt_addr}"), ""); 3277 # endif 3278 } 3279 else 3280 { 3281 char *s; 3282 3283 /* 3284 ** TLS negotiation failed, what to do? 3285 ** fall back to unencrypted connection 3286 ** or abort? How to decide? 3287 ** set a macro and call a ruleset. 3288 */ 3289 3290 mci->mci_flags &= ~MCIF_TLS; 3291 switch (rcode) 3292 { 3293 case EX_TEMPFAIL: 3294 s = "TEMP"; 3295 break; 3296 case EX_USAGE: 3297 s = "USAGE"; 3298 break; 3299 case EX_PROTOCOL: 3300 s = "PROTOCOL"; 3301 break; 3302 case EX_SOFTWARE: 3303 s = "SOFTWARE"; 3304 break; 3305 case EX_UNAVAILABLE: 3306 s = "NONE"; 3307 break; 3308 case EX_CONFIG: 3309 s = "CONFIG"; 3310 break; 3311 3312 /* everything else is a failure */ 3313 default: 3314 s = "FAILURE"; 3315 rcode = EX_TEMPFAIL; 3316 } 3317 macdefine(&e->e_macro, A_PERM, 3318 macid("{verify}"), s); 3319 } 3320 } 3321 else 3322 { 3323 p = tlsstate == 0 ? "NONE": "CLEAR"; 3324 # if DANE 3325 /* 3326 ** TLSA found but STARTTLS not offered? 3327 ** What is the best way to "fail"? 3328 ** XXX: check expiration! 3329 */ 3330 3331 if (!bitset(MCIF_TLS, mci->mci_flags) && 3332 !iscltflgset(e, D_NODANE) && 3333 ste != NULL && 3334 ste->s_tlsa != NULL && 3335 ste->s_tlsa->dane_tlsa_n > 0) 3336 { 3337 if (LogLevel > 8) 3338 sm_syslog(LOG_NOTICE, NOQID, 3339 "STARTTLS=client, relay=%.100s, warning=DANE configured in DNS but no STARTTLS available", 3340 host); 3341 /* XXX include TLSA RR from DNS? */ 3342 3343 p = "DANE_FAIL"; 3344 } 3345 # endif /* DANE */ 3346 macdefine(&e->e_macro, A_PERM, 3347 macid("{verify}"), p); 3348 } 3349 olderrors = Errors; 3350 QuickAbort = false; 3351 SuprErrs = true; 3352 3353 /* 3354 ** rcode == EX_SOFTWARE is special: 3355 ** the TLS negotiation failed 3356 ** we have to drop the connection no matter what. 3357 ** However, we call tls_server to give it the chance 3358 ** to log the problem and return an appropriate 3359 ** error code. 3360 */ 3361 3362 if (rscheck("tls_server", 3363 macvalue(macid("{verify}"), e), 3364 NULL, e, RSF_RMCOMM|RSF_COUNT, 5, 3365 host, NOQID, NULL, NULL) != EX_OK || 3366 Errors > olderrors || 3367 rcode == EX_SOFTWARE) 3368 { 3369 char enhsc[ENHSCLEN]; 3370 extern char MsgBuf[]; 3371 3372 if (ISSMTPCODE(MsgBuf) && 3373 extenhsc(MsgBuf + 4, ' ', enhsc) > 0) 3374 { 3375 p = sm_rpool_strdup_x(e->e_rpool, 3376 MsgBuf); 3377 } 3378 else 3379 { 3380 p = "403 4.7.0 server not authenticated."; 3381 (void) sm_strlcpy(enhsc, "4.7.0", 3382 sizeof(enhsc)); 3383 } 3384 SuprErrs = saveSuprErrs; 3385 QuickAbort = saveQuickAbort; 3386 3387 if (rcode == EX_SOFTWARE) 3388 { 3389 /* drop the connection */ 3390 mci->mci_state = MCIS_QUITING; 3391 SM_CLOSE_FP(mci->mci_out); 3392 mci->mci_flags &= ~MCIF_TLSACT; 3393 (void) endmailer(mci, e, pv); 3394 3395 if ((TLSFallbacktoClear || 3396 SM_TLSI_IS(&(mci->mci_tlsi), 3397 TLSI_FL_FB2CLR)) && 3398 !SM_TLSI_IS(&(mci->mci_tlsi), 3399 TLSI_FL_NOFB2CLR) 3400 # if DANE 3401 && dane_vrfy_ctx.dane_vrfy_chk != 3402 DANE_SECURE 3403 # endif 3404 # if _FFR_MTA_STS 3405 && !SM_TLSI_IS(&(mci->mci_tlsi), 3406 TLSI_FL_STS_NOFB2CLR) 3407 # endif 3408 ) 3409 { 3410 ++tlsstate; 3411 } 3412 } 3413 else 3414 { 3415 /* abort transfer */ 3416 smtpquit(m, mci, e); 3417 } 3418 3419 /* avoid bogus error msg */ 3420 mci->mci_errno = 0; 3421 3422 /* temp or permanent failure? */ 3423 rcode = (*p == '4') ? EX_TEMPFAIL 3424 : EX_UNAVAILABLE; 3425 mci_setstat(mci, rcode, enhsc, p); 3426 3427 /* 3428 ** hack to get the error message into 3429 ** the envelope (done in giveresponse()) 3430 */ 3431 3432 (void) sm_strlcpy(SmtpError, p, 3433 sizeof(SmtpError)); 3434 } 3435 else if (mci->mci_state == MCIS_CLOSED) 3436 { 3437 /* connection close caused by 421 */ 3438 mci->mci_errno = 0; 3439 rcode = EX_TEMPFAIL; 3440 mci_setstat(mci, rcode, NULL, "421"); 3441 } 3442 else 3443 rcode = 0; 3444 3445 QuickAbort = saveQuickAbort; 3446 SuprErrs = saveSuprErrs; 3447 if (DONE_STARTTLS(mci->mci_flags) && 3448 mci->mci_state != MCIS_CLOSED) 3449 { 3450 SET_HELO(mci->mci_flags); 3451 mci_clr_extensions(mci); 3452 goto reconnect; 3453 } 3454 if (tlsstate == 1) 3455 { 3456 if (tTd(11, 1)) 3457 { 3458 sm_syslog(LOG_DEBUG, NOQID, 3459 "STARTTLS=client, relay=%.100s, tlsstate=%d, status=trying_again", 3460 mci->mci_host, tlsstate); 3461 mci_dump(NULL, mci, true); 3462 } 3463 ++tlsstate; 3464 3465 /* 3466 ** Fake the status so a new connection is 3467 ** tried, otherwise the TLS error will 3468 ** "persist" during this delivery attempt. 3469 */ 3470 3471 mci->mci_errno = 0; 3472 rcode = EX_OK; 3473 mci_setstat(mci, rcode, NULL, NULL); 3474 goto one_last_try; 3475 } 3476 } 3477 #endif /* STARTTLS */ 3478 #if SASL 3479 /* if other server supports authentication let's authenticate */ 3480 if (mci->mci_state != MCIS_CLOSED && 3481 mci->mci_saslcap != NULL && 3482 !DONE_AUTH(mci->mci_flags) && !iscltflgset(e, D_NOAUTH)) 3483 { 3484 /* Should we require some minimum authentication? */ 3485 if ((ret = smtpauth(m, mci, e)) == EX_OK) 3486 { 3487 int result; 3488 sasl_ssf_t *ssf = NULL; 3489 3490 /* Get security strength (features) */ 3491 result = sasl_getprop(mci->mci_conn, SASL_SSF, 3492 # if SASL >= 20000 3493 (const void **) &ssf); 3494 # else 3495 (void **) &ssf); 3496 # endif 3497 3498 /* XXX authid? */ 3499 if (LogLevel > 9) 3500 sm_syslog(LOG_INFO, NOQID, 3501 "AUTH=client, relay=%.100s, mech=%.16s, bits=%d", 3502 mci->mci_host, 3503 macvalue(macid("{auth_type}"), e), 3504 result == SASL_OK ? *ssf : 0); 3505 3506 /* 3507 ** Only switch to encrypted connection 3508 ** if a security layer has been negotiated 3509 */ 3510 3511 if (result == SASL_OK && *ssf > 0) 3512 { 3513 int tmo; 3514 3515 /* 3516 ** Convert I/O layer to use SASL. 3517 ** If the call fails, the connection 3518 ** is aborted. 3519 */ 3520 3521 tmo = DATA_PROGRESS_TIMEOUT * 1000; 3522 if (sfdcsasl(&mci->mci_in, 3523 &mci->mci_out, 3524 mci->mci_conn, tmo) == 0) 3525 { 3526 mci_clr_extensions(mci); 3527 mci->mci_flags |= MCIF_AUTHACT| 3528 MCIF_ONLY_EHLO; 3529 goto reconnect; 3530 } 3531 syserr("AUTH TLS switch failed in client"); 3532 } 3533 /* else? XXX */ 3534 mci->mci_flags |= MCIF_AUTHACT; 3535 3536 } 3537 else if (ret == EX_TEMPFAIL) 3538 { 3539 if (LogLevel > 8) 3540 sm_syslog(LOG_ERR, NOQID, 3541 "AUTH=client, relay=%.100s, temporary failure, connection abort", 3542 mci->mci_host); 3543 smtpquit(m, mci, e); 3544 3545 /* avoid bogus error msg */ 3546 mci->mci_errno = 0; 3547 rcode = EX_TEMPFAIL; 3548 mci_setstat(mci, rcode, "4.3.0", p); 3549 3550 /* 3551 ** hack to get the error message into 3552 ** the envelope (done in giveresponse()) 3553 */ 3554 3555 (void) sm_strlcpy(SmtpError, 3556 "Temporary AUTH failure", 3557 sizeof(SmtpError)); 3558 } 3559 } 3560 #endif /* SASL */ 3561 } 3562 3563 do_transfer: 3564 /* clear out per-message flags from connection structure */ 3565 mci->mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7); 3566 3567 if (bitset(EF_HAS8BIT, e->e_flags) && 3568 !bitset(EF_DONT_MIME, e->e_flags) && 3569 bitnset(M_7BITS, m->m_flags)) 3570 mci->mci_flags |= MCIF_CVT8TO7; 3571 3572 #if MIME7TO8 3573 if (bitnset(M_MAKE8BIT, m->m_flags) && 3574 !bitset(MCIF_7BIT, mci->mci_flags) && 3575 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL && 3576 (SM_STRCASEEQ(p, "quoted-printable") || 3577 SM_STRCASEEQ(p, "base64")) && 3578 (p = hvalue("Content-Type", e->e_header)) != NULL) 3579 { 3580 /* may want to convert 7 -> 8 */ 3581 /* XXX should really parse it here -- and use a class XXX */ 3582 if (sm_strncasecmp(p, "text/plain", 10) == 0 && 3583 (p[10] == '\0' || p[10] == ' ' || p[10] == ';')) 3584 mci->mci_flags |= MCIF_CVT7TO8; 3585 } 3586 #endif /* MIME7TO8 */ 3587 3588 if (tTd(11, 1)) 3589 { 3590 sm_dprintf("openmailer: "); 3591 mci_dump(sm_debug_file(), mci, false); 3592 } 3593 3594 #if _FFR_CLIENT_SIZE 3595 /* 3596 ** See if we know the maximum size and 3597 ** abort if the message is too big. 3598 ** 3599 ** NOTE: _FFR_CLIENT_SIZE is untested. 3600 */ 3601 3602 if (bitset(MCIF_SIZE, mci->mci_flags) && 3603 mci->mci_maxsize > 0 && 3604 e->e_msgsize > mci->mci_maxsize) 3605 { 3606 e->e_flags |= EF_NO_BODY_RETN; 3607 if (bitnset(M_LOCALMAILER, m->m_flags)) 3608 e->e_status = "5.2.3"; 3609 else 3610 e->e_status = "5.3.4"; 3611 3612 usrerrenh(e->e_status, 3613 "552 Message is too large; %ld bytes max", 3614 mci->mci_maxsize); 3615 rcode = EX_DATAERR; 3616 3617 /* Need an e_message for error */ 3618 (void) sm_snprintf(SmtpError, sizeof(SmtpError), 3619 "Message is too large; %ld bytes max", 3620 mci->mci_maxsize); 3621 goto give_up; 3622 } 3623 #endif /* _FFR_CLIENT_SIZE */ 3624 3625 if (mci->mci_state != MCIS_OPEN) 3626 { 3627 /* couldn't open the mailer */ 3628 rcode = mci->mci_exitstat; 3629 errno = mci->mci_errno; 3630 SM_SET_H_ERRNO(mci->mci_herrno); 3631 if (rcode == EX_OK) 3632 { 3633 /* shouldn't happen */ 3634 syserr("554 5.3.5 deliver: mci=%lx rcode=%d errno=%d state=%d sig=%s", 3635 (unsigned long) mci, rcode, errno, 3636 mci->mci_state, firstsig); 3637 mci_dump_all(smioout, true); 3638 rcode = EX_SOFTWARE; 3639 } 3640 else if (nummxhosts > hostnum) 3641 { 3642 /* try next MX site */ 3643 goto tryhost; 3644 } 3645 } 3646 else if (!clever) 3647 { 3648 bool ok; 3649 3650 /* 3651 ** Format and send message. 3652 */ 3653 3654 rcode = EX_OK; 3655 errno = 0; 3656 ok = putfromline(mci, e); 3657 if (ok) 3658 ok = (*e->e_puthdr)(mci, e->e_header, e, M87F_OUTER); 3659 if (ok) 3660 ok = (*e->e_putbody)(mci, e, NULL); 3661 if (ok && bitset(MCIF_INLONGLINE, mci->mci_flags)) 3662 ok = putline("", mci); 3663 3664 /* 3665 ** Ignore an I/O error that was caused by EPIPE. 3666 ** Some broken mailers don't read the entire body 3667 ** but just exit() thus causing an I/O error. 3668 */ 3669 3670 if (!ok && (sm_io_error(mci->mci_out) && errno == EPIPE)) 3671 ok = true; 3672 3673 /* (always) get the exit status */ 3674 rcode = endmailer(mci, e, pv); 3675 if (!ok) 3676 rcode = EX_TEMPFAIL; 3677 if (rcode == EX_TEMPFAIL && SmtpError[0] == '\0') 3678 { 3679 /* 3680 ** Need an e_message for mailq display. 3681 ** We set SmtpError as 3682 */ 3683 3684 (void) sm_snprintf(SmtpError, sizeof(SmtpError), 3685 "%s mailer (%s) exited with EX_TEMPFAIL", 3686 m->m_name, m->m_mailer); 3687 } 3688 } 3689 else 3690 { 3691 /* 3692 ** Send the MAIL FROM: protocol 3693 */ 3694 3695 /* XXX this isn't pipelined... */ 3696 rcode = smtpmailfrom(m, mci, e); 3697 mci->mci_okrcpts = 0; 3698 mci->mci_retryrcpt = rcode == EX_TEMPFAIL; 3699 if (rcode == EX_OK) 3700 { 3701 register int rc; 3702 #if PIPELINING 3703 ADDRESS *volatile pchain; 3704 #endif 3705 3706 /* send the recipient list */ 3707 rc = EX_OK; 3708 tobuf[0] = '\0'; 3709 mci->mci_retryrcpt = false; 3710 mci->mci_tolist = tobuf; 3711 #if PIPELINING 3712 pchain = NULL; 3713 mci->mci_nextaddr = NULL; 3714 #endif 3715 3716 for (to = tochain; to != NULL; to = to->q_tchain) 3717 { 3718 if (!QS_IS_UNMARKED(to->q_state)) 3719 continue; 3720 3721 /* mark recipient state as "ok so far" */ 3722 to->q_state = QS_OK; 3723 e->e_to = to->q_paddr; 3724 #if _FFR_MTA_STS 3725 if (CHKMTASTS && to->q_user != NULL) 3726 macdefine(&e->e_macro, A_TEMP, 3727 macid("{rcpt_addr}"), to->q_user); 3728 else 3729 macdefine(&e->e_macro, A_PERM, 3730 macid("{rcpt_addr}"), ""); 3731 #endif /* _FFR_MTA_STS */ 3732 #if STARTTLS 3733 rc = rscheck("tls_rcpt", to->q_user, NULL, e, 3734 RSF_RMCOMM|RSF_COUNT, 3, 3735 mci->mci_host, e->e_id, NULL, NULL); 3736 if (rc != EX_OK) 3737 { 3738 to->q_flags |= QINTREPLY; 3739 markfailure(e, to, mci, rc, false); 3740 giveresponse(rc, to->q_status, m, mci, 3741 ctladdr, xstart, e, to); 3742 if (rc == EX_TEMPFAIL) 3743 { 3744 mci->mci_retryrcpt = true; 3745 to->q_state = QS_RETRY; 3746 } 3747 continue; 3748 } 3749 #endif /* STARTTLS */ 3750 3751 rc = smtprcpt(to, m, mci, e, ctladdr, xstart); 3752 #if PIPELINING 3753 if (rc == EX_OK && 3754 bitset(MCIF_PIPELINED, mci->mci_flags)) 3755 { 3756 /* 3757 ** Add new element to list of 3758 ** recipients for pipelining. 3759 */ 3760 3761 to->q_pchain = NULL; 3762 if (mci->mci_nextaddr == NULL) 3763 mci->mci_nextaddr = to; 3764 if (pchain == NULL) 3765 pchain = to; 3766 else 3767 { 3768 pchain->q_pchain = to; 3769 pchain = pchain->q_pchain; 3770 } 3771 } 3772 #endif /* PIPELINING */ 3773 if (rc != EX_OK) 3774 { 3775 markfailure(e, to, mci, rc, false); 3776 giveresponse(rc, to->q_status, m, mci, 3777 ctladdr, xstart, e, to); 3778 if (rc == EX_TEMPFAIL) 3779 to->q_state = QS_RETRY; 3780 } 3781 } 3782 3783 /* No recipients in list and no missing responses? */ 3784 if (tobuf[0] == '\0' 3785 #if PIPELINING 3786 /* && bitset(MCIF_PIPELINED, mci->mci_flags) */ 3787 && mci->mci_nextaddr == NULL 3788 #endif 3789 ) 3790 { 3791 rcode = rc; 3792 e->e_to = NULL; 3793 if (bitset(MCIF_CACHED, mci->mci_flags)) 3794 smtprset(m, mci, e); 3795 } 3796 else 3797 { 3798 e->e_to = tobuf + 1; 3799 rcode = smtpdata(m, mci, e, ctladdr, xstart); 3800 } 3801 } 3802 3803 if (rcode == EX_TEMPFAIL && nummxhosts > hostnum 3804 && (mci->mci_retryrcpt || mci->mci_okrcpts > 0) 3805 ) 3806 { 3807 /* try next MX site */ 3808 goto tryhost; 3809 } 3810 } 3811 #if NAMED_BIND 3812 if (ConfigLevel < 2) 3813 _res.options |= RES_DEFNAMES | RES_DNSRCH; /* XXX */ 3814 #endif 3815 3816 if (tTd(62, 1)) 3817 checkfds("after delivery"); 3818 3819 /* 3820 ** Do final status disposal. 3821 ** We check for something in tobuf for the SMTP case. 3822 ** If we got a temporary failure, arrange to queue the 3823 ** addressees. 3824 */ 3825 3826 give_up: 3827 if (bitnset(M_LMTP, m->m_flags)) 3828 { 3829 lmtp_rcode = rcode; 3830 tobuf[0] = '\0'; 3831 anyok = false; 3832 strsize = 0; 3833 } 3834 else 3835 anyok = rcode == EX_OK; 3836 3837 for (to = tochain; to != NULL; to = to->q_tchain) 3838 { 3839 /* see if address already marked */ 3840 if (!QS_IS_OK(to->q_state)) 3841 continue; 3842 3843 /* if running LMTP, get the status for each address */ 3844 if (bitnset(M_LMTP, m->m_flags)) 3845 { 3846 if (lmtp_rcode == EX_OK) 3847 rcode = smtpgetstat(m, mci, e); 3848 if (rcode == EX_OK) 3849 { 3850 strsize += sm_strlcat2(tobuf + strsize, ",", 3851 to->q_paddr, 3852 tobufsize - strsize); 3853 SM_ASSERT(strsize < tobufsize); 3854 anyok = true; 3855 } 3856 else 3857 { 3858 e->e_to = to->q_paddr; 3859 markfailure(e, to, mci, rcode, true); 3860 giveresponse(rcode, to->q_status, m, mci, 3861 ctladdr, xstart, e, to); 3862 e->e_to = tobuf + 1; 3863 continue; 3864 } 3865 } 3866 else 3867 { 3868 /* mark bad addresses */ 3869 if (rcode != EX_OK) 3870 { 3871 if (goodmxfound && rcode == EX_NOHOST) 3872 rcode = EX_TEMPFAIL; 3873 markfailure(e, to, mci, rcode, true); 3874 continue; 3875 } 3876 } 3877 3878 /* successful delivery */ 3879 to->q_state = QS_SENT; 3880 to->q_statdate = curtime(); 3881 e->e_nsent++; 3882 3883 /* 3884 ** Checkpoint the send list every few addresses 3885 */ 3886 3887 if (CheckpointInterval > 0 && e->e_nsent >= CheckpointInterval) 3888 { 3889 queueup(e, QUP_FL_NONE); 3890 e->e_nsent = 0; 3891 } 3892 3893 if (bitnset(M_LOCALMAILER, m->m_flags) && 3894 bitset(QPINGONSUCCESS, to->q_flags)) 3895 { 3896 to->q_flags |= QDELIVERED; 3897 to->q_status = "2.1.5"; 3898 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, 3899 "%s... Successfully delivered\n", 3900 to->q_paddr); 3901 } 3902 else if (bitset(QPINGONSUCCESS, to->q_flags) && 3903 bitset(QPRIMARY, to->q_flags) && 3904 !bitset(MCIF_DSN, mci->mci_flags)) 3905 { 3906 to->q_flags |= QRELAYED; 3907 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, 3908 "%s... relayed; expect no further notifications\n", 3909 to->q_paddr); 3910 } 3911 else if (IS_DLVR_NOTIFY(e) && 3912 !bitset(MCIF_DLVR_BY, mci->mci_flags) && 3913 bitset(QPRIMARY, to->q_flags) && 3914 (!bitset(QHASNOTIFY, to->q_flags) || 3915 bitset(QPINGONSUCCESS, to->q_flags) || 3916 bitset(QPINGONFAILURE, to->q_flags) || 3917 bitset(QPINGONDELAY, to->q_flags))) 3918 { 3919 /* RFC 2852, 4.1.4.2: no NOTIFY, or not NEVER */ 3920 to->q_flags |= QBYNRELAY; 3921 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, 3922 "%s... Deliver-by notify: relayed\n", 3923 to->q_paddr); 3924 } 3925 else if (IS_DLVR_TRACE(e) && 3926 (!bitset(QHASNOTIFY, to->q_flags) || 3927 bitset(QPINGONSUCCESS, to->q_flags) || 3928 bitset(QPINGONFAILURE, to->q_flags) || 3929 bitset(QPINGONDELAY, to->q_flags)) && 3930 bitset(QPRIMARY, to->q_flags)) 3931 { 3932 /* RFC 2852, 4.1.4: no NOTIFY, or not NEVER */ 3933 to->q_flags |= QBYTRACE; 3934 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, 3935 "%s... Deliver-By trace: relayed\n", 3936 to->q_paddr); 3937 } 3938 } 3939 3940 if (bitnset(M_LMTP, m->m_flags)) 3941 { 3942 /* 3943 ** Global information applies to the last recipient only; 3944 ** clear it out to avoid bogus errors. 3945 */ 3946 3947 rcode = EX_OK; 3948 e->e_statmsg = NULL; 3949 3950 /* reset the mci state for the next transaction */ 3951 if (mci != NULL && 3952 (mci->mci_state == MCIS_MAIL || 3953 mci->mci_state == MCIS_RCPT || 3954 mci->mci_state == MCIS_DATA)) 3955 { 3956 mci->mci_state = MCIS_OPEN; 3957 SmtpPhase = mci->mci_phase = "idle"; 3958 sm_setproctitle(true, e, "%s: %s", CurHostName, 3959 mci->mci_phase); 3960 } 3961 } 3962 3963 if (tobuf[0] != '\0') 3964 { 3965 giveresponse(rcode, 3966 #if _FFR_NULLMX_STATUS 3967 (NULL == mci || SM_IS_EMPTY(mci->mci_status)) 3968 ? NULL : 3969 #endif 3970 mci->mci_status, 3971 m, mci, ctladdr, xstart, e, NULL); 3972 #if 0 3973 /* 3974 ** This code is disabled for now because I am not 3975 ** sure that copying status from the first recipient 3976 ** to all non-status'ed recipients is a good idea. 3977 */ 3978 3979 if (tochain->q_message != NULL && 3980 !bitnset(M_LMTP, m->m_flags) && rcode != EX_OK) 3981 { 3982 for (to = tochain->q_tchain; to != NULL; 3983 to = to->q_tchain) 3984 { 3985 /* see if address already marked */ 3986 if (QS_IS_QUEUEUP(to->q_state) && 3987 to->q_message == NULL) 3988 to->q_message = sm_rpool_strdup_x(e->e_rpool, 3989 tochain->q_message); 3990 } 3991 } 3992 #endif /* 0 */ 3993 } 3994 if (anyok) 3995 markstats(e, tochain, STATS_NORMAL); 3996 mci_store_persistent(mci); 3997 3998 #if _FFR_OCC 3999 /* 4000 ** HACK: this is NOT the right place to "close" a connection! 4001 ** use smtpquit? 4002 ** add a flag to mci to indicate that rate/conc. was increased? 4003 */ 4004 4005 if (clever) 4006 { 4007 extern SOCKADDR CurHostAddr; 4008 4009 /* check family... {} */ 4010 /* r = anynet_pton(AF_INET, p, dst); */ 4011 occ_close(e, mci, host, &CurHostAddr); 4012 } 4013 #endif /* _FFR_OCC */ 4014 4015 /* Some recipients were tempfailed, try them on the next host */ 4016 if (mci != NULL && mci->mci_retryrcpt && nummxhosts > hostnum) 4017 { 4018 /* try next MX site */ 4019 goto tryhost; 4020 } 4021 4022 /* now close the connection */ 4023 if (clever && mci != NULL && mci->mci_state != MCIS_CLOSED && 4024 !bitset(MCIF_CACHED, mci->mci_flags)) 4025 smtpquit(m, mci, e); 4026 4027 cleanup: ; 4028 } 4029 SM_FINALLY 4030 { 4031 /* 4032 ** Restore state and return. 4033 */ 4034 #if XDEBUG 4035 char wbuf[MAXLINE]; 4036 4037 /* make absolutely certain 0, 1, and 2 are in use */ 4038 (void) sm_snprintf(wbuf, sizeof(wbuf), 4039 "%s... end of deliver(%s)", 4040 e->e_to == NULL ? "NO-TO-LIST" 4041 : shortenstring(e->e_to, 4042 MAXSHORTSTR), 4043 m->m_name); 4044 checkfd012(wbuf); 4045 #endif /* XDEBUG */ 4046 4047 errno = 0; 4048 4049 /* 4050 ** It was originally necessary to set macro 'g' to NULL 4051 ** because it previously pointed to an auto buffer. 4052 ** We don't do this any more, so this may be unnecessary. 4053 */ 4054 4055 macdefine(&e->e_macro, A_PERM, 'g', (char *) NULL); 4056 e->e_to = NULL; 4057 } 4058 SM_END_TRY 4059 return rcode; 4060 } 4061 4062 /* 4063 ** MARKFAILURE -- mark a failure on a specific address. 4064 ** 4065 ** Parameters: 4066 ** e -- the envelope we are sending. 4067 ** q -- the address to mark. 4068 ** mci -- mailer connection information. 4069 ** rcode -- the code signifying the particular failure. 4070 ** ovr -- override an existing code? 4071 ** 4072 ** Returns: 4073 ** none. 4074 ** 4075 ** Side Effects: 4076 ** marks the address (and possibly the envelope) with the 4077 ** failure so that an error will be returned or 4078 ** the message will be queued, as appropriate. 4079 */ 4080 4081 void 4082 markfailure(e, q, mci, rcode, ovr) 4083 register ENVELOPE *e; 4084 register ADDRESS *q; 4085 register MCI *mci; 4086 int rcode; 4087 bool ovr; 4088 { 4089 int save_errno = errno; 4090 char *status = NULL; 4091 char *rstatus = NULL; 4092 4093 switch (rcode) 4094 { 4095 case EX_OK: 4096 break; 4097 4098 case EX_TEMPFAIL: 4099 case EX_IOERR: 4100 case EX_OSERR: 4101 q->q_state = QS_QUEUEUP; 4102 break; 4103 4104 default: 4105 q->q_state = QS_BADADDR; 4106 break; 4107 } 4108 4109 /* find most specific error code possible */ 4110 if (mci != NULL && mci->mci_status != NULL) 4111 { 4112 status = sm_rpool_strdup_x(e->e_rpool, mci->mci_status); 4113 if (mci->mci_rstatus != NULL) 4114 rstatus = sm_rpool_strdup_x(e->e_rpool, 4115 mci->mci_rstatus); 4116 } 4117 else if (e->e_status != NULL) 4118 { 4119 status = e->e_status; 4120 } 4121 else 4122 { 4123 switch (rcode) 4124 { 4125 case EX_USAGE: 4126 status = "5.5.4"; 4127 break; 4128 4129 case EX_DATAERR: 4130 status = "5.5.2"; 4131 break; 4132 4133 case EX_NOUSER: 4134 status = "5.1.1"; 4135 break; 4136 4137 case EX_NOHOST: 4138 status = "5.1.2"; 4139 break; 4140 4141 case EX_NOINPUT: 4142 case EX_CANTCREAT: 4143 case EX_NOPERM: 4144 status = "5.3.0"; 4145 break; 4146 4147 case EX_UNAVAILABLE: 4148 case EX_SOFTWARE: 4149 case EX_OSFILE: 4150 case EX_PROTOCOL: 4151 case EX_CONFIG: 4152 status = "5.5.0"; 4153 break; 4154 4155 case EX_OSERR: 4156 case EX_IOERR: 4157 status = "4.5.0"; 4158 break; 4159 4160 case EX_TEMPFAIL: 4161 status = "4.2.0"; 4162 break; 4163 } 4164 } 4165 4166 /* new status? */ 4167 if (status != NULL && *status != '\0' && (ovr || q->q_status == NULL || 4168 *q->q_status == '\0' || *q->q_status < *status)) 4169 { 4170 q->q_status = status; 4171 q->q_rstatus = rstatus; 4172 } 4173 if (rcode != EX_OK && q->q_rstatus == NULL && 4174 q->q_mailer != NULL && q->q_mailer->m_diagtype != NULL && 4175 SM_STRCASEEQ(q->q_mailer->m_diagtype, "X-UNIX")) 4176 { 4177 char buf[16]; 4178 4179 (void) sm_snprintf(buf, sizeof(buf), "%d", rcode); 4180 q->q_rstatus = sm_rpool_strdup_x(e->e_rpool, buf); 4181 } 4182 4183 q->q_statdate = curtime(); 4184 if (CurHostName != NULL && CurHostName[0] != '\0' && 4185 mci != NULL && !bitset(M_LOCALMAILER, mci->mci_flags)) 4186 q->q_statmta = sm_rpool_strdup_x(e->e_rpool, CurHostName); 4187 4188 /* restore errno */ 4189 errno = save_errno; 4190 } 4191 /* 4192 ** ENDMAILER -- Wait for mailer to terminate. 4193 ** 4194 ** We should never get fatal errors (e.g., segmentation 4195 ** violation), so we report those specially. For other 4196 ** errors, we choose a status message (into statmsg), 4197 ** and if it represents an error, we print it. 4198 ** 4199 ** Parameters: 4200 ** mci -- the mailer connection info. 4201 ** e -- the current envelope. 4202 ** pv -- the parameter vector that invoked the mailer 4203 ** (for error messages). 4204 ** 4205 ** Returns: 4206 ** exit code of mailer. 4207 ** 4208 ** Side Effects: 4209 ** none. 4210 */ 4211 4212 static jmp_buf EndWaitTimeout; 4213 4214 static void 4215 endwaittimeout(ignore) 4216 int ignore; 4217 { 4218 /* 4219 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD 4220 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE 4221 ** DOING. 4222 */ 4223 4224 errno = ETIMEDOUT; 4225 longjmp(EndWaitTimeout, 1); 4226 } 4227 4228 int 4229 endmailer(mci, e, pv) 4230 register MCI *mci; 4231 register ENVELOPE *e; 4232 char **pv; 4233 { 4234 int st; 4235 int save_errno = errno; 4236 char buf[MAXLINE]; 4237 SM_EVENT *ev = NULL; 4238 4239 4240 mci_unlock_host(mci); 4241 4242 /* close output to mailer */ 4243 SM_CLOSE_FP(mci->mci_out); 4244 4245 /* copy any remaining input to transcript */ 4246 if (mci->mci_in != NULL && mci->mci_state != MCIS_ERROR && 4247 e->e_xfp != NULL) 4248 { 4249 while (sfgets(buf, sizeof(buf), mci->mci_in, 4250 TimeOuts.to_quit, "Draining Input") != NULL) 4251 (void) sm_io_fputs(e->e_xfp, SM_TIME_DEFAULT, buf); 4252 } 4253 4254 #if SASL 4255 /* close SASL connection */ 4256 if (bitset(MCIF_AUTHACT, mci->mci_flags)) 4257 { 4258 sasl_dispose(&mci->mci_conn); 4259 mci->mci_flags &= ~MCIF_AUTHACT; 4260 } 4261 #endif /* SASL */ 4262 4263 #if STARTTLS 4264 /* shutdown TLS */ 4265 (void) endtlsclt(mci); 4266 #endif 4267 4268 /* now close the input */ 4269 SM_CLOSE_FP(mci->mci_in); 4270 mci->mci_state = MCIS_CLOSED; 4271 4272 errno = save_errno; 4273 4274 /* in the IPC case there is nothing to wait for */ 4275 if (mci->mci_pid == 0) 4276 return EX_OK; 4277 4278 /* put a timeout around the wait */ 4279 if (mci->mci_mailer->m_wait > 0) 4280 { 4281 if (setjmp(EndWaitTimeout) == 0) 4282 ev = sm_setevent(mci->mci_mailer->m_wait, 4283 endwaittimeout, 0); 4284 else 4285 { 4286 syserr("endmailer %s: wait timeout (%ld)", 4287 mci->mci_mailer->m_name, 4288 (long) mci->mci_mailer->m_wait); 4289 return EX_TEMPFAIL; 4290 } 4291 } 4292 4293 /* wait for the mailer process, collect status */ 4294 st = waitfor(mci->mci_pid); 4295 save_errno = errno; 4296 if (ev != NULL) 4297 sm_clrevent(ev); 4298 errno = save_errno; 4299 4300 if (st == -1) 4301 { 4302 syserr("endmailer %s: wait", mci->mci_mailer->m_name); 4303 return EX_SOFTWARE; 4304 } 4305 4306 if (WIFEXITED(st)) 4307 { 4308 /* normal death -- return status */ 4309 return (WEXITSTATUS(st)); 4310 } 4311 4312 /* it died a horrid death */ 4313 syserr("451 4.3.0 mailer %s died with signal %d%s", 4314 mci->mci_mailer->m_name, WTERMSIG(st), 4315 WCOREDUMP(st) ? " (core dumped)" : 4316 (WIFSTOPPED(st) ? " (stopped)" : "")); 4317 4318 /* log the arguments */ 4319 if (pv != NULL && e->e_xfp != NULL) 4320 { 4321 register char **av; 4322 4323 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "Arguments:"); 4324 for (av = pv; *av != NULL; av++) 4325 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, " %s", 4326 *av); 4327 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "\n"); 4328 } 4329 4330 ExitStat = EX_TEMPFAIL; 4331 return EX_TEMPFAIL; 4332 } 4333 /* 4334 ** GIVERESPONSE -- Interpret an error response from a mailer 4335 ** 4336 ** Parameters: 4337 ** status -- the status code from the mailer (high byte 4338 ** only; core dumps must have been taken care of 4339 ** already). 4340 ** dsn -- the DSN associated with the address, if any. 4341 ** m -- the mailer info for this mailer. 4342 ** mci -- the mailer connection info -- can be NULL if the 4343 ** response is given before the connection is made. 4344 ** ctladdr -- the controlling address for the recipient 4345 ** address(es). 4346 ** xstart -- the transaction start time, for computing 4347 ** transaction delays. 4348 ** e -- the current envelope. 4349 ** to -- the current recipient (NULL if none). 4350 ** 4351 ** Returns: 4352 ** none. 4353 ** 4354 ** Side Effects: 4355 ** Errors may be incremented. 4356 ** ExitStat may be set. 4357 */ 4358 4359 void 4360 giveresponse(status, dsn, m, mci, ctladdr, xstart, e, to) 4361 int status; 4362 char *dsn; 4363 register MAILER *m; 4364 register MCI *mci; 4365 ADDRESS *ctladdr; 4366 time_t xstart; 4367 ENVELOPE *e; 4368 ADDRESS *to; 4369 { 4370 register const char *statmsg; 4371 int errnum = errno; 4372 int off = 4; 4373 bool usestat = false; 4374 char dsnbuf[ENHSCLEN]; 4375 char buf[MAXLINE]; 4376 char *exmsg; 4377 4378 if (e == NULL) 4379 { 4380 syserr("giveresponse: null envelope"); 4381 /* NOTREACHED */ 4382 SM_ASSERT(0); 4383 } 4384 4385 if (tTd(11, 4)) 4386 sm_dprintf("giveresponse: status=%d, e->e_message=%s, SmtpError=%s\n", 4387 status, e->e_message, SmtpError); 4388 4389 /* 4390 ** Compute status message from code. 4391 */ 4392 4393 exmsg = sm_sysexmsg(status); 4394 if (status == 0) 4395 { 4396 statmsg = "250 2.0.0 Sent"; 4397 if (e->e_statmsg != NULL) 4398 { 4399 (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", 4400 statmsg, 4401 shortenstring(e->e_statmsg, 403)); 4402 statmsg = buf; 4403 } 4404 } 4405 else if (exmsg == NULL) 4406 { 4407 (void) sm_snprintf(buf, sizeof(buf), 4408 "554 5.3.0 unknown mailer error %d", 4409 status); 4410 status = EX_UNAVAILABLE; 4411 statmsg = buf; 4412 usestat = true; 4413 } 4414 else if (status == EX_TEMPFAIL) 4415 { 4416 char *bp = buf; 4417 4418 (void) sm_strlcpy(bp, exmsg + 1, SPACELEFT(buf, bp)); 4419 bp += strlen(bp); 4420 #if NAMED_BIND 4421 if (h_errno == TRY_AGAIN) 4422 statmsg = sm_errstring(h_errno + E_DNSBASE); 4423 else 4424 #endif 4425 { 4426 if (errnum != 0) 4427 statmsg = sm_errstring(errnum); 4428 else 4429 statmsg = SmtpError; 4430 } 4431 if (statmsg != NULL && statmsg[0] != '\0') 4432 { 4433 switch (errnum) 4434 { 4435 #ifdef ENETDOWN 4436 case ENETDOWN: /* Network is down */ 4437 #endif 4438 #ifdef ENETUNREACH 4439 case ENETUNREACH: /* Network is unreachable */ 4440 #endif 4441 #ifdef ENETRESET 4442 case ENETRESET: /* Network dropped connection on reset */ 4443 #endif 4444 #ifdef ECONNABORTED 4445 case ECONNABORTED: /* Software caused connection abort */ 4446 #endif 4447 #ifdef EHOSTDOWN 4448 case EHOSTDOWN: /* Host is down */ 4449 #endif 4450 #ifdef EHOSTUNREACH 4451 case EHOSTUNREACH: /* No route to host */ 4452 #endif 4453 if (mci != NULL && mci->mci_host != NULL) 4454 { 4455 (void) sm_strlcpyn(bp, 4456 SPACELEFT(buf, bp), 4457 2, ": ", 4458 mci->mci_host); 4459 bp += strlen(bp); 4460 } 4461 break; 4462 } 4463 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ": ", 4464 statmsg); 4465 #if DANE 4466 if (errnum == 0 && SmtpError[0] != '\0' && 4467 h_errno == TRY_AGAIN && 4468 mci->mci_exitstat == EX_TEMPFAIL) 4469 { 4470 (void) sm_strlcat(bp, SmtpError, 4471 SPACELEFT(buf, bp)); 4472 bp += strlen(bp); 4473 } 4474 #endif /* DANE */ 4475 usestat = true; 4476 } 4477 statmsg = buf; 4478 } 4479 #if NAMED_BIND 4480 else if (status == EX_NOHOST && h_errno != 0) 4481 { 4482 statmsg = sm_errstring(h_errno + E_DNSBASE); 4483 (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", exmsg + 1, 4484 statmsg); 4485 statmsg = buf; 4486 usestat = true; 4487 } 4488 #endif /* NAMED_BIND */ 4489 #if USE_EAI 4490 else if (errnum == 0 && status == EX_DATAERR 4491 && e->e_message != NULL && e->e_message[0] != '\0') 4492 { 4493 int m; 4494 4495 /* XREF: 2nd arg must be coordinated with smtpmailfrom() */ 4496 m = skipaddrhost(e->e_message, false); 4497 4498 /* 4499 ** XXX Why is the SMTP reply code needed here? 4500 ** How to avoid a hard-coded value? 4501 */ 4502 4503 (void) sm_snprintf(buf, sizeof(buf), "550 %s", e->e_message + m); 4504 statmsg = buf; 4505 usestat = true; 4506 } 4507 #endif /* USE_EAI */ 4508 else 4509 { 4510 statmsg = exmsg; 4511 if (*statmsg++ == ':' && errnum != 0) 4512 { 4513 (void) sm_snprintf(buf, sizeof(buf), "%s: %s", statmsg, 4514 sm_errstring(errnum)); 4515 statmsg = buf; 4516 usestat = true; 4517 } 4518 else if (bitnset(M_LMTP, m->m_flags) && e->e_statmsg != NULL) 4519 { 4520 (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", statmsg, 4521 shortenstring(e->e_statmsg, 403)); 4522 statmsg = buf; 4523 usestat = true; 4524 } 4525 } 4526 4527 /* 4528 ** Print the message as appropriate 4529 */ 4530 4531 if (status == EX_OK || status == EX_TEMPFAIL) 4532 { 4533 extern char MsgBuf[]; 4534 4535 if ((off = isenhsc(statmsg + 4, ' ')) > 0) 4536 { 4537 if (dsn == NULL) 4538 { 4539 (void) sm_snprintf(dsnbuf, sizeof(dsnbuf), 4540 "%.*s", off, statmsg + 4); 4541 dsn = dsnbuf; 4542 } 4543 off += 5; 4544 } 4545 else 4546 { 4547 off = 4; 4548 } 4549 message("%s", statmsg + off); 4550 if (status == EX_TEMPFAIL && e->e_xfp != NULL) 4551 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s\n", 4552 &MsgBuf[4]); 4553 } 4554 else 4555 { 4556 char mbuf[ENHSCLEN + 4]; 4557 4558 Errors++; 4559 if ((off = isenhsc(statmsg + 4, ' ')) > 0 && 4560 off < sizeof(mbuf) - 4) 4561 { 4562 if (dsn == NULL) 4563 { 4564 (void) sm_snprintf(dsnbuf, sizeof(dsnbuf), 4565 "%.*s", off, statmsg + 4); 4566 dsn = dsnbuf; 4567 } 4568 off += 5; 4569 4570 /* copy only part of statmsg to mbuf */ 4571 (void) sm_strlcpy(mbuf, statmsg, off); 4572 (void) sm_strlcat(mbuf, " %s", sizeof(mbuf)); 4573 } 4574 else 4575 { 4576 dsnbuf[0] = '\0'; 4577 (void) sm_snprintf(mbuf, sizeof(mbuf), "%.3s %%s", 4578 statmsg); 4579 off = 4; 4580 } 4581 usrerr(mbuf, &statmsg[off]); 4582 } 4583 4584 /* 4585 ** Final cleanup. 4586 ** Log a record of the transaction. Compute the new ExitStat 4587 ** -- if we already had an error, stick with that. 4588 */ 4589 4590 if (OpMode != MD_VERIFY && !bitset(EF_VRFYONLY, e->e_flags) && 4591 LogLevel > ((status == EX_TEMPFAIL) ? 8 : (status == EX_OK) ? 7 : 6)) 4592 logdelivery(m, mci, dsn, statmsg + off, ctladdr, xstart, e, to, status); 4593 4594 if (tTd(11, 2)) 4595 sm_dprintf("giveresponse: status=%d, dsn=%s, e->e_message=%s, errnum=%d, statmsg=%s\n", 4596 status, 4597 dsn == NULL ? "<NULL>" : dsn, 4598 e->e_message == NULL ? "<NULL>" : e->e_message, 4599 errnum, statmsg); 4600 4601 if (status != EX_TEMPFAIL) 4602 setstat(status); 4603 if (status != EX_OK && (status != EX_TEMPFAIL || e->e_message == NULL)) 4604 e->e_message = sm_rpool_strdup_x(e->e_rpool, statmsg + off); 4605 if (status != EX_OK && to != NULL && to->q_message == NULL) 4606 { 4607 if (!usestat && e->e_message != NULL) 4608 to->q_message = sm_rpool_strdup_x(e->e_rpool, 4609 e->e_message); 4610 else 4611 to->q_message = sm_rpool_strdup_x(e->e_rpool, 4612 statmsg + off); 4613 } 4614 errno = 0; 4615 SM_SET_H_ERRNO(0); 4616 } 4617 /* 4618 ** LOGDELIVERY -- log the delivery in the system log 4619 ** 4620 ** Care is taken to avoid logging lines that are too long, because 4621 ** some versions of syslog have an unfortunate proclivity for core 4622 ** dumping. This is a hack, to be sure, that is at best empirical. 4623 ** 4624 ** Parameters: 4625 ** m -- the mailer info. Can be NULL for initial queue. 4626 ** mci -- the mailer connection info -- can be NULL if the 4627 ** log is occurring when no connection is active. 4628 ** dsn -- the DSN attached to the status. 4629 ** status -- the message to print for the status. 4630 ** ctladdr -- the controlling address for the to list. 4631 ** xstart -- the transaction start time, used for 4632 ** computing transaction delay. 4633 ** e -- the current envelope. 4634 ** to -- the current recipient (NULL if none). 4635 ** rcode -- status code 4636 ** 4637 ** Returns: 4638 ** none 4639 ** 4640 ** Side Effects: 4641 ** none 4642 */ 4643 4644 void 4645 logdelivery(m, mci, dsn, status, ctladdr, xstart, e, to, rcode) 4646 MAILER *m; 4647 register MCI *mci; 4648 char *dsn; 4649 const char *status; 4650 ADDRESS *ctladdr; 4651 time_t xstart; 4652 register ENVELOPE *e; 4653 ADDRESS *to; 4654 int rcode; 4655 { 4656 register char *bp; 4657 register char *p; 4658 int l; 4659 time_t now = curtime(); 4660 char buf[1024]; 4661 #if _FFR_8BITENVADDR 4662 char xbuf[SM_MAX(SYSLOG_BUFSIZE, MAXNAME)]; /* EAI:ok */ 4663 #endif 4664 char *xstr; 4665 4666 #if (SYSLOG_BUFSIZE) >= 256 4667 /* ctladdr: max 106 bytes */ 4668 bp = buf; 4669 if (ctladdr != NULL) 4670 { 4671 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", ctladdr=", 4672 shortenstring(ctladdr->q_paddr, 83)); 4673 bp += strlen(bp); 4674 if (bitset(QGOODUID, ctladdr->q_flags)) 4675 { 4676 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)", 4677 (int) ctladdr->q_uid, 4678 (int) ctladdr->q_gid); 4679 bp += strlen(bp); 4680 } 4681 } 4682 4683 /* delay & xdelay: max 41 bytes */ 4684 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", delay=", 4685 pintvl(now - e->e_ctime, true)); 4686 bp += strlen(bp); 4687 4688 if (xstart != (time_t) 0) 4689 { 4690 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=", 4691 pintvl(now - xstart, true)); 4692 bp += strlen(bp); 4693 } 4694 4695 /* mailer: assume about 19 bytes (max 10 byte mailer name) */ 4696 if (m != NULL) 4697 { 4698 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=", 4699 m->m_name); 4700 bp += strlen(bp); 4701 } 4702 4703 # if _FFR_LOG_MORE2 4704 LOG_MORE(buf, bp); 4705 # endif 4706 4707 /* pri: changes with each delivery attempt */ 4708 (void) sm_snprintf(bp, SPACELEFT(buf, bp), ", pri=%ld", 4709 PRT_NONNEGL(e->e_msgpriority)); 4710 bp += strlen(bp); 4711 4712 /* relay: max 66 bytes for IPv4 addresses */ 4713 if (mci != NULL && mci->mci_host != NULL) 4714 { 4715 extern SOCKADDR CurHostAddr; 4716 4717 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", relay=", 4718 shortenstring(mci->mci_host, 40)); 4719 bp += strlen(bp); 4720 4721 if (CurHostAddr.sa.sa_family != 0) 4722 { 4723 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " [%s]", 4724 anynet_ntoa(&CurHostAddr)); 4725 } 4726 } 4727 else if (strcmp(status, "quarantined") == 0) 4728 { 4729 if (e->e_quarmsg != NULL) 4730 (void) sm_snprintf(bp, SPACELEFT(buf, bp), 4731 ", quarantine=%s", 4732 shortenstring(e->e_quarmsg, 40)); 4733 } 4734 else if (strcmp(status, "queued") != 0) 4735 { 4736 p = macvalue('h', e); 4737 if (p != NULL && p[0] != '\0') 4738 { 4739 (void) sm_snprintf(bp, SPACELEFT(buf, bp), 4740 ", relay=%s", shortenstring(p, 40)); 4741 } 4742 } 4743 bp += strlen(bp); 4744 4745 /* dsn */ 4746 if (dsn != NULL && *dsn != '\0') 4747 { 4748 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", dsn=", 4749 shortenstring(dsn, ENHSCLEN)); 4750 bp += strlen(bp); 4751 } 4752 4753 # if _FFR_LOG_NTRIES 4754 /* ntries */ 4755 if (e->e_ntries >= 0) 4756 { 4757 (void) sm_snprintf(bp, SPACELEFT(buf, bp), 4758 ", ntries=%d", e->e_ntries + 1); 4759 bp += strlen(bp); 4760 } 4761 # endif /* _FFR_LOG_NTRIES */ 4762 4763 # define STATLEN (((SYSLOG_BUFSIZE) - 100) / 4) 4764 # if (STATLEN) < 63 4765 # undef STATLEN 4766 # define STATLEN 63 4767 # endif 4768 # if (STATLEN) > 203 4769 # undef STATLEN 4770 # define STATLEN 203 4771 # endif 4772 4773 /* 4774 ** Notes: 4775 ** per-rcpt status: to->q_rstatus 4776 ** global status: e->e_text 4777 ** 4778 ** We (re)use STATLEN here, is that a good choice? 4779 ** 4780 ** stat=Deferred: ... 4781 ** has sometimes the same text? 4782 ** 4783 ** Note: this doesn't show the stage at which the error happened. 4784 ** can/should we log that? 4785 ** XS_* in reply() basically encodes the state. 4786 ** 4787 ** Note: in some case the normal logging might show the same server 4788 ** reply - how to avoid that? 4789 */ 4790 4791 /* only show errors from server */ 4792 if (rcode != EX_OK && to != NULL && !SM_IS_EMPTY(to->q_rstatus) 4793 && !bitset(QINTREPLY, to->q_flags)) 4794 { 4795 (void) sm_snprintf(bp, SPACELEFT(buf, bp), 4796 ", reply=%s", 4797 shortenstring(to->q_rstatus, STATLEN)); 4798 bp += strlen(bp); 4799 } 4800 else if (rcode != EX_OK && e->e_text != NULL) 4801 { 4802 (void) sm_snprintf(bp, SPACELEFT(buf, bp), 4803 ", reply=%d %s%s%s", 4804 e->e_rcode, 4805 e->e_renhsc, 4806 (e->e_renhsc[0] != '\0') ? " " : "", 4807 shortenstring(e->e_text, STATLEN)); 4808 bp += strlen(bp); 4809 } 4810 #if _FFR_NULLMX_STATUS 4811 /* Hack for MX 0 . : how to make this general? */ 4812 else if (rcode != EX_OK && NULL == to && dsn != NULL && 4813 strcmp(dsn, ESCNULLMXRCPT) == 0) 4814 { 4815 (void) sm_snprintf(bp, SPACELEFT(buf, bp), 4816 ", status=%s", ERRNULLMX); 4817 bp += strlen(bp); 4818 } 4819 #endif 4820 4821 /* stat: max 210 bytes */ 4822 if ((bp - buf) > (sizeof(buf) - ((STATLEN) + 20))) 4823 { 4824 /* desperation move -- truncate data */ 4825 bp = buf + sizeof(buf) - ((STATLEN) + 17); 4826 (void) sm_strlcpy(bp, "...", SPACELEFT(buf, bp)); 4827 bp += 3; 4828 } 4829 4830 (void) sm_strlcpy(bp, ", stat=", SPACELEFT(buf, bp)); 4831 bp += strlen(bp); 4832 4833 (void) sm_strlcpy(bp, shortenstring(status, STATLEN), 4834 SPACELEFT(buf, bp)); 4835 4836 /* id, to: max 13 + TOBUFSIZE bytes */ 4837 l = SYSLOG_BUFSIZE - 100 - strlen(buf); 4838 if (l < 0) 4839 l = 0; 4840 p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to; 4841 while (strlen(p) >= l) 4842 { 4843 register char *q; 4844 4845 for (q = p + l; q > p; q--) 4846 { 4847 /* XXX a comma in an address will break this! */ 4848 if (*q == ',') 4849 break; 4850 } 4851 if (p == q) 4852 break; 4853 # if _FFR_8BITENVADDR 4854 /* XXX is this correct? dequote all of p? */ 4855 (void) dequote_internal_chars(p, xbuf, sizeof(xbuf)); 4856 xstr = xbuf; 4857 # else 4858 xstr = p; 4859 # endif 4860 sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]%s", 4861 (int) (++q - p), xstr, buf); 4862 p = q; 4863 } 4864 # if _FFR_8BITENVADDR 4865 (void) dequote_internal_chars(p, xbuf, sizeof(xbuf)); 4866 xstr = xbuf; 4867 # else 4868 xstr = p; 4869 # endif 4870 sm_syslog(LOG_INFO, e->e_id, "to=%.*s%s", l, xstr, buf); 4871 4872 #else /* (SYSLOG_BUFSIZE) >= 256 */ 4873 4874 l = SYSLOG_BUFSIZE - 85; 4875 if (l < 0) 4876 l = 0; 4877 p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to; 4878 while (strlen(p) >= l) 4879 { 4880 register char *q; 4881 4882 for (q = p + l; q > p; q--) 4883 { 4884 if (*q == ',') 4885 break; 4886 } 4887 if (p == q) 4888 break; 4889 4890 sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]", 4891 (int) (++q - p), p); 4892 p = q; 4893 } 4894 sm_syslog(LOG_INFO, e->e_id, "to=%.*s", l, p); 4895 4896 if (ctladdr != NULL) 4897 { 4898 bp = buf; 4899 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "ctladdr=", 4900 shortenstring(ctladdr->q_paddr, 83)); 4901 bp += strlen(bp); 4902 if (bitset(QGOODUID, ctladdr->q_flags)) 4903 { 4904 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)", 4905 ctladdr->q_uid, ctladdr->q_gid); 4906 bp += strlen(bp); 4907 } 4908 sm_syslog(LOG_INFO, e->e_id, "%s", buf); 4909 } 4910 bp = buf; 4911 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "delay=", 4912 pintvl(now - e->e_ctime, true)); 4913 bp += strlen(bp); 4914 if (xstart != (time_t) 0) 4915 { 4916 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=", 4917 pintvl(now - xstart, true)); 4918 bp += strlen(bp); 4919 } 4920 4921 if (m != NULL) 4922 { 4923 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=", 4924 m->m_name); 4925 bp += strlen(bp); 4926 } 4927 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf); 4928 4929 buf[0] = '\0'; 4930 bp = buf; 4931 if (mci != NULL && mci->mci_host != NULL) 4932 { 4933 extern SOCKADDR CurHostAddr; 4934 4935 (void) sm_snprintf(bp, SPACELEFT(buf, bp), "relay=%.100s", 4936 mci->mci_host); 4937 bp += strlen(bp); 4938 4939 if (CurHostAddr.sa.sa_family != 0) 4940 (void) sm_snprintf(bp, SPACELEFT(buf, bp), 4941 " [%.100s]", 4942 anynet_ntoa(&CurHostAddr)); 4943 } 4944 else if (strcmp(status, "quarantined") == 0) 4945 { 4946 if (e->e_quarmsg != NULL) 4947 (void) sm_snprintf(bp, SPACELEFT(buf, bp), 4948 ", quarantine=%.100s", 4949 e->e_quarmsg); 4950 } 4951 else if (strcmp(status, "queued") != 0) 4952 { 4953 p = macvalue('h', e); 4954 if (p != NULL && p[0] != '\0') 4955 (void) sm_snprintf(buf, sizeof(buf), "relay=%.100s", p); 4956 } 4957 if (buf[0] != '\0') 4958 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf); 4959 4960 sm_syslog(LOG_INFO, e->e_id, "stat=%s", shortenstring(status, 63)); 4961 #endif /* (SYSLOG_BUFSIZE) >= 256 */ 4962 } 4963 /* 4964 ** PUTFROMLINE -- output a UNIX-style from line (or whatever) 4965 ** 4966 ** This can be made an arbitrary message separator by changing $l 4967 ** 4968 ** One of the ugliest hacks seen by human eyes is contained herein: 4969 ** UUCP wants those stupid "remote from <host>" lines. Why oh why 4970 ** does a well-meaning programmer such as myself have to deal with 4971 ** this kind of antique garbage???? 4972 ** 4973 ** Parameters: 4974 ** mci -- the connection information. 4975 ** e -- the envelope. 4976 ** 4977 ** Returns: 4978 ** true iff line was written successfully 4979 ** 4980 ** Side Effects: 4981 ** outputs some text to fp. 4982 */ 4983 4984 bool 4985 putfromline(mci, e) 4986 register MCI *mci; 4987 ENVELOPE *e; 4988 { 4989 char *template = UnixFromLine; 4990 char buf[MAXLINE]; 4991 char xbuf[MAXLINE]; 4992 4993 if (bitnset(M_NHDR, mci->mci_mailer->m_flags)) 4994 return true; 4995 4996 mci->mci_flags |= MCIF_INHEADER; 4997 4998 if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags)) 4999 { 5000 char *bang; 5001 5002 expand("\201g", buf, sizeof(buf), e); 5003 bang = strchr(buf, '!'); 5004 if (bang == NULL) 5005 { 5006 char *at; 5007 char hname[MAXNAME]; /* EAI:ok */ 5008 5009 /* 5010 ** If we can construct a UUCP path, do so 5011 */ 5012 5013 at = strrchr(buf, '@'); 5014 if (at == NULL) 5015 { 5016 expand("\201k", hname, sizeof(hname), e); 5017 at = hname; 5018 } 5019 else 5020 *at++ = '\0'; 5021 (void) sm_snprintf(xbuf, sizeof(xbuf), 5022 "From %.800s \201d remote from %.100s\n", 5023 buf, at); 5024 } 5025 else 5026 { 5027 *bang++ = '\0'; 5028 (void) sm_snprintf(xbuf, sizeof(xbuf), 5029 "From %.800s \201d remote from %.100s\n", 5030 bang, buf); 5031 template = xbuf; 5032 } 5033 } 5034 expand(template, buf, sizeof(buf), e); 5035 return putxline(buf, strlen(buf), mci, PXLF_HEADER); 5036 } 5037 5038 /* 5039 ** PUTBODY -- put the body of a message. 5040 ** 5041 ** Parameters: 5042 ** mci -- the connection information. 5043 ** e -- the envelope to put out. 5044 ** separator -- if non-NULL, a message separator that must 5045 ** not be permitted in the resulting message. 5046 ** 5047 ** Returns: 5048 ** true iff message was written successfully 5049 ** 5050 ** Side Effects: 5051 ** The message is written onto fp. 5052 */ 5053 5054 /* values for output state variable */ 5055 #define OSTATE_HEAD 0 /* at beginning of line */ 5056 #define OSTATE_CR 1 /* read a carriage return */ 5057 #define OSTATE_INLINE 2 /* putting rest of line */ 5058 5059 bool 5060 putbody(mci, e, separator) 5061 register MCI *mci; 5062 register ENVELOPE *e; 5063 char *separator; 5064 { 5065 bool dead = false; 5066 bool ioerr = false; 5067 int save_errno; 5068 char buf[MAXLINE]; 5069 #if MIME8TO7 5070 char *boundaries[MAXMIMENESTING + 1]; 5071 #endif 5072 5073 /* 5074 ** Output the body of the message 5075 */ 5076 5077 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags)) 5078 { 5079 char *df = queuename(e, DATAFL_LETTER); 5080 5081 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df, 5082 SM_IO_RDONLY_B, NULL); 5083 if (e->e_dfp == NULL) 5084 { 5085 char *msg = "!putbody: Cannot open %s for %s from %s"; 5086 5087 if (errno == ENOENT) 5088 msg++; 5089 syserr(msg, df, e->e_to, e->e_from.q_paddr); 5090 } 5091 5092 } 5093 if (e->e_dfp == NULL) 5094 { 5095 if (bitset(MCIF_INHEADER, mci->mci_flags)) 5096 { 5097 if (!putline("", mci)) 5098 goto writeerr; 5099 mci->mci_flags &= ~MCIF_INHEADER; 5100 } 5101 if (!putline("<<< No Message Collected >>>", mci)) 5102 goto writeerr; 5103 goto endofmessage; 5104 } 5105 5106 if (e->e_dfino == (ino_t) 0) 5107 { 5108 struct stat stbuf; 5109 5110 if (fstat(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), &stbuf) 5111 < 0) 5112 e->e_dfino = -1; 5113 else 5114 { 5115 e->e_dfdev = stbuf.st_dev; 5116 e->e_dfino = stbuf.st_ino; 5117 } 5118 } 5119 5120 /* paranoia: the data file should always be in a rewound state */ 5121 (void) bfrewind(e->e_dfp); 5122 5123 /* simulate an I/O timeout when used as source */ 5124 if (tTd(84, 101)) 5125 sleep(319); 5126 5127 #if MIME8TO7 5128 if (bitset(MCIF_CVT8TO7, mci->mci_flags)) 5129 { 5130 /* 5131 ** Do 8 to 7 bit MIME conversion. 5132 */ 5133 5134 /* make sure it looks like a MIME message */ 5135 if (hvalue("MIME-Version", e->e_header) == NULL && 5136 !putline("MIME-Version: 1.0", mci)) 5137 goto writeerr; 5138 5139 if (hvalue("Content-Type", e->e_header) == NULL) 5140 { 5141 (void) sm_snprintf(buf, sizeof(buf), 5142 "Content-Type: text/plain; charset=%s", 5143 defcharset(e)); 5144 if (!putline(buf, mci)) 5145 goto writeerr; 5146 } 5147 5148 /* now do the hard work */ 5149 boundaries[0] = NULL; 5150 mci->mci_flags |= MCIF_INHEADER; 5151 if (mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER, 0) == 5152 SM_IO_EOF) 5153 goto writeerr; 5154 } 5155 # if MIME7TO8 5156 else if (bitset(MCIF_CVT7TO8, mci->mci_flags)) 5157 { 5158 if (!mime7to8(mci, e->e_header, e)) 5159 goto writeerr; 5160 } 5161 # endif /* MIME7TO8 */ 5162 else if (MaxMimeHeaderLength > 0 || MaxMimeFieldLength > 0) 5163 { 5164 bool oldsuprerrs = SuprErrs; 5165 5166 /* Use mime8to7 to check multipart for MIME header overflows */ 5167 boundaries[0] = NULL; 5168 mci->mci_flags |= MCIF_INHEADER; 5169 5170 /* 5171 ** If EF_DONT_MIME is set, we have a broken MIME message 5172 ** and don't want to generate a new bounce message whose 5173 ** body propagates the broken MIME. We can't just not call 5174 ** mime8to7() as is done above since we need the security 5175 ** checks. The best we can do is suppress the errors. 5176 */ 5177 5178 if (bitset(EF_DONT_MIME, e->e_flags)) 5179 SuprErrs = true; 5180 5181 if (mime8to7(mci, e->e_header, e, boundaries, 5182 M87F_OUTER|M87F_NO8TO7, 0) == SM_IO_EOF) 5183 goto writeerr; 5184 5185 /* restore SuprErrs */ 5186 SuprErrs = oldsuprerrs; 5187 } 5188 else 5189 #endif /* MIME8TO7 */ 5190 { 5191 int ostate; 5192 register char *bp; 5193 register char *pbp; 5194 register int c; 5195 register char *xp; 5196 int padc; 5197 char *buflim; 5198 int pos = 0; 5199 char peekbuf[12]; 5200 5201 if (bitset(MCIF_INHEADER, mci->mci_flags)) 5202 { 5203 if (!putline("", mci)) 5204 goto writeerr; 5205 mci->mci_flags &= ~MCIF_INHEADER; 5206 } 5207 5208 /* determine end of buffer; allow for short mailer lines */ 5209 buflim = &buf[sizeof(buf) - 1]; 5210 if (mci->mci_mailer->m_linelimit > 0 && 5211 mci->mci_mailer->m_linelimit < sizeof(buf) - 1) 5212 buflim = &buf[mci->mci_mailer->m_linelimit - 1]; 5213 5214 /* copy temp file to output with mapping */ 5215 ostate = OSTATE_HEAD; 5216 bp = buf; 5217 pbp = peekbuf; 5218 while (!sm_io_error(mci->mci_out) && !dead) 5219 { 5220 if (pbp > peekbuf) 5221 c = *--pbp; 5222 else if ((c = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT)) 5223 == SM_IO_EOF) 5224 break; 5225 if (bitset(MCIF_7BIT, mci->mci_flags)) 5226 c &= 0x7f; 5227 switch (ostate) 5228 { 5229 case OSTATE_HEAD: 5230 if (c == '\0' && 5231 bitnset(M_NONULLS, 5232 mci->mci_mailer->m_flags)) 5233 break; 5234 if (c != '\r' && c != '\n' && bp < buflim) 5235 { 5236 *bp++ = c; 5237 break; 5238 } 5239 5240 /* check beginning of line for special cases */ 5241 *bp = '\0'; 5242 pos = 0; 5243 padc = SM_IO_EOF; 5244 if (buf[0] == 'F' && 5245 bitnset(M_ESCFROM, mci->mci_mailer->m_flags) 5246 && strncmp(buf, "From ", 5) == 0) 5247 { 5248 padc = '>'; 5249 } 5250 if (buf[0] == '-' && buf[1] == '-' && 5251 separator != NULL) 5252 { 5253 /* possible separator */ 5254 int sl = strlen(separator); 5255 5256 if (strncmp(&buf[2], separator, sl) 5257 == 0) 5258 padc = ' '; 5259 } 5260 if (buf[0] == '.' && 5261 bitnset(M_XDOT, mci->mci_mailer->m_flags)) 5262 { 5263 padc = '.'; 5264 } 5265 5266 /* now copy out saved line */ 5267 if (TrafficLogFile != NULL) 5268 { 5269 (void) sm_io_fprintf(TrafficLogFile, 5270 SM_TIME_DEFAULT, 5271 "%05d >>> ", 5272 (int) CurrentPid); 5273 if (padc != SM_IO_EOF) 5274 (void) sm_io_putc(TrafficLogFile, 5275 SM_TIME_DEFAULT, 5276 padc); 5277 for (xp = buf; xp < bp; xp++) 5278 (void) sm_io_putc(TrafficLogFile, 5279 SM_TIME_DEFAULT, 5280 (unsigned char) *xp); 5281 if (c == '\n') 5282 (void) sm_io_fputs(TrafficLogFile, 5283 SM_TIME_DEFAULT, 5284 mci->mci_mailer->m_eol); 5285 } 5286 if (padc != SM_IO_EOF) 5287 { 5288 if (sm_io_putc(mci->mci_out, 5289 SM_TIME_DEFAULT, padc) 5290 == SM_IO_EOF) 5291 { 5292 dead = true; 5293 continue; 5294 } 5295 pos++; 5296 } 5297 for (xp = buf; xp < bp; xp++) 5298 { 5299 if (sm_io_putc(mci->mci_out, 5300 SM_TIME_DEFAULT, 5301 (unsigned char) *xp) 5302 == SM_IO_EOF) 5303 { 5304 dead = true; 5305 break; 5306 } 5307 } 5308 if (dead) 5309 continue; 5310 if (c == '\n') 5311 { 5312 if (sm_io_fputs(mci->mci_out, 5313 SM_TIME_DEFAULT, 5314 mci->mci_mailer->m_eol) 5315 == SM_IO_EOF) 5316 break; 5317 pos = 0; 5318 } 5319 else 5320 { 5321 pos += bp - buf; 5322 if (c != '\r') 5323 { 5324 SM_ASSERT(pbp < peekbuf + 5325 sizeof(peekbuf)); 5326 *pbp++ = c; 5327 } 5328 } 5329 5330 bp = buf; 5331 5332 /* determine next state */ 5333 if (c == '\n') 5334 ostate = OSTATE_HEAD; 5335 else if (c == '\r') 5336 ostate = OSTATE_CR; 5337 else 5338 ostate = OSTATE_INLINE; 5339 continue; 5340 5341 case OSTATE_CR: 5342 if (c == '\n') 5343 { 5344 /* got CRLF */ 5345 if (sm_io_fputs(mci->mci_out, 5346 SM_TIME_DEFAULT, 5347 mci->mci_mailer->m_eol) 5348 == SM_IO_EOF) 5349 continue; 5350 5351 if (TrafficLogFile != NULL) 5352 { 5353 (void) sm_io_fputs(TrafficLogFile, 5354 SM_TIME_DEFAULT, 5355 mci->mci_mailer->m_eol); 5356 } 5357 pos = 0; 5358 ostate = OSTATE_HEAD; 5359 continue; 5360 } 5361 5362 /* had a naked carriage return */ 5363 SM_ASSERT(pbp < peekbuf + sizeof(peekbuf)); 5364 *pbp++ = c; 5365 c = '\r'; 5366 ostate = OSTATE_INLINE; 5367 goto putch; 5368 5369 case OSTATE_INLINE: 5370 if (c == '\r') 5371 { 5372 ostate = OSTATE_CR; 5373 continue; 5374 } 5375 if (c == '\0' && 5376 bitnset(M_NONULLS, 5377 mci->mci_mailer->m_flags)) 5378 break; 5379 putch: 5380 if (mci->mci_mailer->m_linelimit > 0 && 5381 pos >= mci->mci_mailer->m_linelimit - 1 && 5382 c != '\n') 5383 { 5384 int d; 5385 5386 /* check next character for EOL */ 5387 if (pbp > peekbuf) 5388 d = *(pbp - 1); 5389 else if ((d = sm_io_getc(e->e_dfp, 5390 SM_TIME_DEFAULT)) 5391 != SM_IO_EOF) 5392 { 5393 SM_ASSERT(pbp < peekbuf + 5394 sizeof(peekbuf)); 5395 *pbp++ = d; 5396 } 5397 5398 if (d == '\n' || d == SM_IO_EOF) 5399 { 5400 if (TrafficLogFile != NULL) 5401 (void) sm_io_putc(TrafficLogFile, 5402 SM_TIME_DEFAULT, 5403 (unsigned char) c); 5404 if (sm_io_putc(mci->mci_out, 5405 SM_TIME_DEFAULT, 5406 (unsigned char) c) 5407 == SM_IO_EOF) 5408 { 5409 dead = true; 5410 continue; 5411 } 5412 pos++; 5413 continue; 5414 } 5415 5416 if (sm_io_putc(mci->mci_out, 5417 SM_TIME_DEFAULT, '!') 5418 == SM_IO_EOF || 5419 sm_io_fputs(mci->mci_out, 5420 SM_TIME_DEFAULT, 5421 mci->mci_mailer->m_eol) 5422 == SM_IO_EOF) 5423 { 5424 dead = true; 5425 continue; 5426 } 5427 5428 if (TrafficLogFile != NULL) 5429 { 5430 (void) sm_io_fprintf(TrafficLogFile, 5431 SM_TIME_DEFAULT, 5432 "!%s", 5433 mci->mci_mailer->m_eol); 5434 } 5435 ostate = OSTATE_HEAD; 5436 SM_ASSERT(pbp < peekbuf + 5437 sizeof(peekbuf)); 5438 *pbp++ = c; 5439 continue; 5440 } 5441 if (c == '\n') 5442 { 5443 if (TrafficLogFile != NULL) 5444 (void) sm_io_fputs(TrafficLogFile, 5445 SM_TIME_DEFAULT, 5446 mci->mci_mailer->m_eol); 5447 if (sm_io_fputs(mci->mci_out, 5448 SM_TIME_DEFAULT, 5449 mci->mci_mailer->m_eol) 5450 == SM_IO_EOF) 5451 continue; 5452 pos = 0; 5453 ostate = OSTATE_HEAD; 5454 } 5455 else 5456 { 5457 if (TrafficLogFile != NULL) 5458 (void) sm_io_putc(TrafficLogFile, 5459 SM_TIME_DEFAULT, 5460 (unsigned char) c); 5461 if (sm_io_putc(mci->mci_out, 5462 SM_TIME_DEFAULT, 5463 (unsigned char) c) 5464 == SM_IO_EOF) 5465 { 5466 dead = true; 5467 continue; 5468 } 5469 pos++; 5470 ostate = OSTATE_INLINE; 5471 } 5472 break; 5473 } 5474 } 5475 5476 /* make sure we are at the beginning of a line */ 5477 if (bp > buf) 5478 { 5479 if (TrafficLogFile != NULL) 5480 { 5481 for (xp = buf; xp < bp; xp++) 5482 (void) sm_io_putc(TrafficLogFile, 5483 SM_TIME_DEFAULT, 5484 (unsigned char) *xp); 5485 } 5486 for (xp = buf; xp < bp; xp++) 5487 { 5488 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, 5489 (unsigned char) *xp) 5490 == SM_IO_EOF) 5491 { 5492 dead = true; 5493 break; 5494 } 5495 } 5496 pos += bp - buf; 5497 } 5498 if (!dead && pos > 0) 5499 { 5500 if (TrafficLogFile != NULL) 5501 (void) sm_io_fputs(TrafficLogFile, 5502 SM_TIME_DEFAULT, 5503 mci->mci_mailer->m_eol); 5504 if (sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT, 5505 mci->mci_mailer->m_eol) == SM_IO_EOF) 5506 goto writeerr; 5507 } 5508 } 5509 5510 if (sm_io_error(e->e_dfp)) 5511 { 5512 syserr("putbody: %s/%cf%s: read error", 5513 qid_printqueue(e->e_dfqgrp, e->e_dfqdir), 5514 DATAFL_LETTER, e->e_id); 5515 ExitStat = EX_IOERR; 5516 ioerr = true; 5517 } 5518 5519 endofmessage: 5520 /* 5521 ** Since mailfile() uses e_dfp in a child process, 5522 ** the file offset in the stdio library for the 5523 ** parent process will not agree with the in-kernel 5524 ** file offset since the file descriptor is shared 5525 ** between the processes. Therefore, it is vital 5526 ** that the file always be rewound. This forces the 5527 ** kernel offset (lseek) and stdio library (ftell) 5528 ** offset to match. 5529 */ 5530 5531 save_errno = errno; 5532 if (e->e_dfp != NULL) 5533 (void) bfrewind(e->e_dfp); 5534 5535 /* some mailers want extra blank line at end of message */ 5536 if (!dead && bitnset(M_BLANKEND, mci->mci_mailer->m_flags) && 5537 buf[0] != '\0' && buf[0] != '\n') 5538 { 5539 if (!putline("", mci)) 5540 goto writeerr; 5541 } 5542 5543 if (!dead && 5544 (sm_io_flush(mci->mci_out, SM_TIME_DEFAULT) == SM_IO_EOF || 5545 (sm_io_error(mci->mci_out) && errno != EPIPE))) 5546 { 5547 save_errno = errno; 5548 syserr("putbody: write error"); 5549 ExitStat = EX_IOERR; 5550 ioerr = true; 5551 } 5552 5553 errno = save_errno; 5554 return !dead && !ioerr; 5555 5556 writeerr: 5557 return false; 5558 } 5559 5560 /* 5561 ** MAILFILE -- Send a message to a file. 5562 ** 5563 ** If the file has the set-user-ID/set-group-ID bits set, but NO 5564 ** execute bits, sendmail will try to become the owner of that file 5565 ** rather than the real user. Obviously, this only works if 5566 ** sendmail runs as root. 5567 ** 5568 ** This could be done as a subordinate mailer, except that it 5569 ** is used implicitly to save messages in ~/dead.letter. We 5570 ** view this as being sufficiently important as to include it 5571 ** here. For example, if the system is dying, we shouldn't have 5572 ** to create another process plus some pipes to save the message. 5573 ** 5574 ** Parameters: 5575 ** filename -- the name of the file to send to. 5576 ** mailer -- mailer definition for recipient -- if NULL, 5577 ** use FileMailer. 5578 ** ctladdr -- the controlling address header -- includes 5579 ** the userid/groupid to be when sending. 5580 ** sfflags -- flags for opening. 5581 ** e -- the current envelope. 5582 ** 5583 ** Returns: 5584 ** The exit code associated with the operation. 5585 ** 5586 ** Side Effects: 5587 ** none. 5588 */ 5589 5590 # define RETURN(st) exit(st); 5591 5592 static jmp_buf CtxMailfileTimeout; 5593 5594 int 5595 mailfile(filename, mailer, ctladdr, sfflags, e) 5596 char *volatile filename; 5597 MAILER *volatile mailer; 5598 ADDRESS *ctladdr; 5599 volatile long sfflags; 5600 register ENVELOPE *e; 5601 { 5602 register SM_FILE_T *f; 5603 register pid_t pid = -1; 5604 volatile int mode; 5605 int len; 5606 off_t curoff; 5607 bool suidwarn = geteuid() == 0; 5608 char *p; 5609 char *volatile realfile; 5610 SM_EVENT *ev; 5611 char buf[MAXPATHLEN]; 5612 char targetfile[MAXPATHLEN]; 5613 5614 if (tTd(11, 1)) 5615 { 5616 sm_dprintf("mailfile %s\n ctladdr=", filename); 5617 printaddr(sm_debug_file(), ctladdr, false); 5618 } 5619 5620 if (mailer == NULL) 5621 mailer = FileMailer; 5622 5623 if (e->e_xfp != NULL) 5624 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT); 5625 5626 /* 5627 ** Special case /dev/null. This allows us to restrict file 5628 ** delivery to regular files only. 5629 */ 5630 5631 if (sm_path_isdevnull(filename)) 5632 return EX_OK; 5633 5634 /* check for 8-bit available */ 5635 if (bitset(EF_HAS8BIT, e->e_flags) && 5636 bitnset(M_7BITS, mailer->m_flags) && 5637 (bitset(EF_DONT_MIME, e->e_flags) || 5638 !(bitset(MM_MIME8BIT, MimeMode) || 5639 (bitset(EF_IS_MIME, e->e_flags) && 5640 bitset(MM_CVTMIME, MimeMode))))) 5641 { 5642 e->e_status = "5.6.3"; 5643 usrerrenh(e->e_status, 5644 "554 Cannot send 8-bit data to 7-bit destination"); 5645 errno = 0; 5646 return EX_DATAERR; 5647 } 5648 5649 /* Find the actual file */ 5650 if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0') 5651 { 5652 len = strlen(SafeFileEnv); 5653 5654 if (strncmp(SafeFileEnv, filename, len) == 0) 5655 filename += len; 5656 5657 if (len + strlen(filename) + 1 >= sizeof(targetfile)) 5658 { 5659 syserr("mailfile: filename too long (%s/%s)", 5660 SafeFileEnv, filename); 5661 return EX_CANTCREAT; 5662 } 5663 (void) sm_strlcpy(targetfile, SafeFileEnv, sizeof(targetfile)); 5664 realfile = targetfile + len; 5665 if (*filename == '/') 5666 filename++; 5667 if (*filename != '\0') 5668 { 5669 /* paranoia: trailing / should be removed in readcf */ 5670 if (targetfile[len - 1] != '/') 5671 (void) sm_strlcat(targetfile, 5672 "/", sizeof(targetfile)); 5673 (void) sm_strlcat(targetfile, filename, 5674 sizeof(targetfile)); 5675 } 5676 } 5677 else if (mailer->m_rootdir != NULL) 5678 { 5679 expand(mailer->m_rootdir, targetfile, sizeof(targetfile), e); 5680 len = strlen(targetfile); 5681 5682 if (strncmp(targetfile, filename, len) == 0) 5683 filename += len; 5684 5685 if (len + strlen(filename) + 1 >= sizeof(targetfile)) 5686 { 5687 syserr("mailfile: filename too long (%s/%s)", 5688 targetfile, filename); 5689 return EX_CANTCREAT; 5690 } 5691 realfile = targetfile + len; 5692 if (targetfile[len - 1] != '/') 5693 (void) sm_strlcat(targetfile, "/", sizeof(targetfile)); 5694 if (*filename == '/') 5695 (void) sm_strlcat(targetfile, filename + 1, 5696 sizeof(targetfile)); 5697 else 5698 (void) sm_strlcat(targetfile, filename, 5699 sizeof(targetfile)); 5700 } 5701 else 5702 { 5703 if (sm_strlcpy(targetfile, filename, sizeof(targetfile)) >= 5704 sizeof(targetfile)) 5705 { 5706 syserr("mailfile: filename too long (%s)", filename); 5707 return EX_CANTCREAT; 5708 } 5709 realfile = targetfile; 5710 } 5711 5712 /* 5713 ** Fork so we can change permissions here. 5714 ** Note that we MUST use fork, not vfork, because of 5715 ** the complications of calling subroutines, etc. 5716 */ 5717 5718 5719 /* 5720 ** Dispose of SIGCHLD signal catchers that may be laying 5721 ** around so that the waitfor() below will get it. 5722 */ 5723 5724 (void) sm_signal(SIGCHLD, SIG_DFL); 5725 5726 DOFORK(fork); 5727 5728 if (pid < 0) 5729 return EX_OSERR; 5730 else if (pid == 0) 5731 { 5732 /* child -- actually write to file */ 5733 struct stat stb; 5734 MCI mcibuf; 5735 int err; 5736 volatile int oflags = O_WRONLY|O_APPEND; 5737 5738 /* Reset global flags */ 5739 RestartRequest = NULL; 5740 RestartWorkGroup = false; 5741 ShutdownRequest = NULL; 5742 PendingSignal = 0; 5743 CurrentPid = getpid(); 5744 5745 if (e->e_lockfp != NULL) 5746 { 5747 int fd; 5748 5749 fd = sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL); 5750 /* SM_ASSERT(fd >= 0); */ 5751 if (fd >= 0) 5752 (void) close(fd); 5753 } 5754 5755 (void) sm_signal(SIGINT, SIG_DFL); 5756 (void) sm_signal(SIGHUP, SIG_DFL); 5757 (void) sm_signal(SIGTERM, SIG_DFL); 5758 (void) umask(OldUmask); 5759 e->e_to = filename; 5760 ExitStat = EX_OK; 5761 5762 if (setjmp(CtxMailfileTimeout) != 0) 5763 { 5764 RETURN(EX_TEMPFAIL); 5765 } 5766 5767 if (TimeOuts.to_fileopen > 0) 5768 ev = sm_setevent(TimeOuts.to_fileopen, mailfiletimeout, 5769 0); 5770 else 5771 ev = NULL; 5772 5773 /* check file mode to see if set-user-ID */ 5774 if (stat(targetfile, &stb) < 0) 5775 mode = FileMode; 5776 else 5777 mode = stb.st_mode; 5778 5779 /* limit the errors to those actually caused in the child */ 5780 errno = 0; 5781 ExitStat = EX_OK; 5782 5783 /* Allow alias expansions to use the S_IS{U,G}ID bits */ 5784 if ((ctladdr != NULL && !bitset(QALIAS, ctladdr->q_flags)) || 5785 bitset(SFF_RUNASREALUID, sfflags)) 5786 { 5787 /* ignore set-user-ID and set-group-ID bits */ 5788 mode &= ~(S_ISGID|S_ISUID); 5789 if (tTd(11, 20)) 5790 sm_dprintf("mailfile: ignoring set-user-ID/set-group-ID bits\n"); 5791 } 5792 5793 /* we have to open the data file BEFORE setuid() */ 5794 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags)) 5795 { 5796 char *df = queuename(e, DATAFL_LETTER); 5797 5798 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df, 5799 SM_IO_RDONLY_B, NULL); 5800 if (e->e_dfp == NULL) 5801 { 5802 syserr("mailfile: Cannot open %s for %s from %s", 5803 df, e->e_to, e->e_from.q_paddr); 5804 } 5805 } 5806 5807 /* select a new user to run as */ 5808 if (!bitset(SFF_RUNASREALUID, sfflags)) 5809 { 5810 if (bitnset(M_SPECIFIC_UID, mailer->m_flags)) 5811 { 5812 RealUserName = NULL; 5813 if (mailer->m_uid == NO_UID) 5814 RealUid = RunAsUid; 5815 else 5816 RealUid = mailer->m_uid; 5817 if (RunAsUid != 0 && RealUid != RunAsUid) 5818 { 5819 /* Only root can change the uid */ 5820 syserr("mailfile: insufficient privileges to change uid, RunAsUid=%ld, RealUid=%ld", 5821 (long) RunAsUid, (long) RealUid); 5822 RETURN(EX_TEMPFAIL); 5823 } 5824 } 5825 else if (bitset(S_ISUID, mode)) 5826 { 5827 RealUserName = NULL; 5828 RealUid = stb.st_uid; 5829 } 5830 else if (ctladdr != NULL && ctladdr->q_uid != 0) 5831 { 5832 if (ctladdr->q_ruser != NULL) 5833 RealUserName = ctladdr->q_ruser; 5834 else 5835 RealUserName = ctladdr->q_user; 5836 RealUid = ctladdr->q_uid; 5837 } 5838 else if (mailer != NULL && mailer->m_uid != NO_UID) 5839 { 5840 RealUserName = DefUser; 5841 RealUid = mailer->m_uid; 5842 } 5843 else 5844 { 5845 RealUserName = DefUser; 5846 RealUid = DefUid; 5847 } 5848 5849 /* select a new group to run as */ 5850 if (bitnset(M_SPECIFIC_UID, mailer->m_flags)) 5851 { 5852 if (mailer->m_gid == NO_GID) 5853 RealGid = RunAsGid; 5854 else 5855 RealGid = mailer->m_gid; 5856 if (RunAsUid != 0 && 5857 (RealGid != getgid() || 5858 RealGid != getegid())) 5859 { 5860 /* Only root can change the gid */ 5861 syserr("mailfile: insufficient privileges to change gid, RealGid=%ld, RunAsUid=%ld, gid=%ld, egid=%ld", 5862 (long) RealGid, (long) RunAsUid, 5863 (long) getgid(), (long) getegid()); 5864 RETURN(EX_TEMPFAIL); 5865 } 5866 } 5867 else if (bitset(S_ISGID, mode)) 5868 RealGid = stb.st_gid; 5869 else if (ctladdr != NULL && 5870 ctladdr->q_uid == DefUid && 5871 ctladdr->q_gid == 0) 5872 { 5873 /* 5874 ** Special case: This means it is an 5875 ** alias and we should act as DefaultUser. 5876 ** See alias()'s comments. 5877 */ 5878 5879 RealGid = DefGid; 5880 RealUserName = DefUser; 5881 } 5882 else if (ctladdr != NULL && ctladdr->q_uid != 0) 5883 RealGid = ctladdr->q_gid; 5884 else if (mailer != NULL && mailer->m_gid != NO_GID) 5885 RealGid = mailer->m_gid; 5886 else 5887 RealGid = DefGid; 5888 } 5889 5890 /* last ditch */ 5891 if (!bitset(SFF_ROOTOK, sfflags)) 5892 { 5893 if (RealUid == 0) 5894 RealUid = DefUid; 5895 if (RealGid == 0) 5896 RealGid = DefGid; 5897 } 5898 5899 /* set group id list (needs /etc/group access) */ 5900 if (RealUserName != NULL && !DontInitGroups) 5901 { 5902 if (initgroups(RealUserName, RealGid) == -1 && suidwarn) 5903 { 5904 syserr("mailfile: initgroups(%s, %ld) failed", 5905 RealUserName, (long) RealGid); 5906 RETURN(EX_TEMPFAIL); 5907 } 5908 } 5909 else 5910 { 5911 GIDSET_T gidset[1]; 5912 5913 gidset[0] = RealGid; 5914 if (setgroups(1, gidset) == -1 && suidwarn) 5915 { 5916 syserr("mailfile: setgroups() failed"); 5917 RETURN(EX_TEMPFAIL); 5918 } 5919 } 5920 5921 /* 5922 ** If you have a safe environment, go into it. 5923 */ 5924 5925 if (realfile != targetfile) 5926 { 5927 char save; 5928 5929 save = *realfile; 5930 *realfile = '\0'; 5931 if (tTd(11, 20)) 5932 sm_dprintf("mailfile: chroot %s\n", targetfile); 5933 if (chroot(targetfile) < 0) 5934 { 5935 syserr("mailfile: Cannot chroot(%s)", 5936 targetfile); 5937 RETURN(EX_CANTCREAT); 5938 } 5939 *realfile = save; 5940 } 5941 5942 if (tTd(11, 40)) 5943 sm_dprintf("mailfile: deliver to %s\n", realfile); 5944 5945 if (chdir("/") < 0) 5946 { 5947 syserr("mailfile: cannot chdir(/)"); 5948 RETURN(EX_CANTCREAT); 5949 } 5950 5951 /* now reset the group and user ids */ 5952 endpwent(); 5953 sm_mbdb_terminate(); 5954 if (setgid(RealGid) < 0 && suidwarn) 5955 { 5956 syserr("mailfile: setgid(%ld) failed", (long) RealGid); 5957 RETURN(EX_TEMPFAIL); 5958 } 5959 vendor_set_uid(RealUid); 5960 if (setuid(RealUid) < 0 && suidwarn) 5961 { 5962 syserr("mailfile: setuid(%ld) failed", (long) RealUid); 5963 RETURN(EX_TEMPFAIL); 5964 } 5965 5966 if (tTd(11, 2)) 5967 sm_dprintf("mailfile: running as r/euid=%ld/%ld, r/egid=%ld/%ld\n", 5968 (long) getuid(), (long) geteuid(), 5969 (long) getgid(), (long) getegid()); 5970 5971 5972 /* move into some "safe" directory */ 5973 if (mailer->m_execdir != NULL) 5974 { 5975 char *q; 5976 5977 for (p = mailer->m_execdir; p != NULL; p = q) 5978 { 5979 q = strchr(p, ':'); 5980 if (q != NULL) 5981 *q = '\0'; 5982 expand(p, buf, sizeof(buf), e); 5983 if (q != NULL) 5984 *q++ = ':'; 5985 if (tTd(11, 20)) 5986 sm_dprintf("mailfile: trydir %s\n", 5987 buf); 5988 if (buf[0] != '\0' && chdir(buf) >= 0) 5989 break; 5990 } 5991 } 5992 5993 /* 5994 ** Recheck the file after we have assumed the ID of the 5995 ** delivery user to make sure we can deliver to it as 5996 ** that user. This is necessary if sendmail is running 5997 ** as root and the file is on an NFS mount which treats 5998 ** root as nobody. 5999 */ 6000 6001 #if HASLSTAT 6002 if (bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail)) 6003 err = stat(realfile, &stb); 6004 else 6005 err = lstat(realfile, &stb); 6006 #else /* HASLSTAT */ 6007 err = stat(realfile, &stb); 6008 #endif /* HASLSTAT */ 6009 6010 if (err < 0) 6011 { 6012 stb.st_mode = ST_MODE_NOFILE; 6013 mode = FileMode; 6014 oflags |= O_CREAT|O_EXCL; 6015 } 6016 else if (bitset(S_IXUSR|S_IXGRP|S_IXOTH, mode) || 6017 (!bitnset(DBS_FILEDELIVERYTOHARDLINK, 6018 DontBlameSendmail) && 6019 stb.st_nlink != 1) || 6020 (realfile != targetfile && !S_ISREG(mode))) 6021 exit(EX_CANTCREAT); 6022 else 6023 mode = stb.st_mode; 6024 6025 if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail)) 6026 sfflags |= SFF_NOSLINK; 6027 if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail)) 6028 sfflags |= SFF_NOHLINK; 6029 sfflags &= ~SFF_OPENASROOT; 6030 f = safefopen(realfile, oflags, mode, sfflags); 6031 if (f == NULL) 6032 { 6033 if (transienterror(errno)) 6034 { 6035 usrerr("454 4.3.0 cannot open %s: %s", 6036 shortenstring(realfile, MAXSHORTSTR), 6037 sm_errstring(errno)); 6038 RETURN(EX_TEMPFAIL); 6039 } 6040 else 6041 { 6042 usrerr("554 5.3.0 cannot open %s: %s", 6043 shortenstring(realfile, MAXSHORTSTR), 6044 sm_errstring(errno)); 6045 RETURN(EX_CANTCREAT); 6046 } 6047 } 6048 if (filechanged(realfile, sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), 6049 &stb)) 6050 { 6051 syserr("554 5.3.0 file changed after open"); 6052 RETURN(EX_CANTCREAT); 6053 } 6054 if (fstat(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), &stb) < 0) 6055 { 6056 syserr("554 5.3.0 cannot fstat %s", 6057 sm_errstring(errno)); 6058 RETURN(EX_CANTCREAT); 6059 } 6060 6061 curoff = stb.st_size; 6062 6063 if (ev != NULL) 6064 sm_clrevent(ev); 6065 6066 memset(&mcibuf, '\0', sizeof(mcibuf)); 6067 mcibuf.mci_mailer = mailer; 6068 mcibuf.mci_out = f; 6069 if (bitnset(M_7BITS, mailer->m_flags)) 6070 mcibuf.mci_flags |= MCIF_7BIT; 6071 6072 /* clear out per-message flags from connection structure */ 6073 mcibuf.mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7); 6074 6075 if (bitset(EF_HAS8BIT, e->e_flags) && 6076 !bitset(EF_DONT_MIME, e->e_flags) && 6077 bitnset(M_7BITS, mailer->m_flags)) 6078 mcibuf.mci_flags |= MCIF_CVT8TO7; 6079 6080 #if MIME7TO8 6081 if (bitnset(M_MAKE8BIT, mailer->m_flags) && 6082 !bitset(MCIF_7BIT, mcibuf.mci_flags) && 6083 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL && 6084 (SM_STRCASEEQ(p, "quoted-printable") || 6085 SM_STRCASEEQ(p, "base64")) && 6086 (p = hvalue("Content-Type", e->e_header)) != NULL) 6087 { 6088 /* may want to convert 7 -> 8 */ 6089 /* XXX should really parse it here -- and use a class XXX */ 6090 if (sm_strncasecmp(p, "text/plain", 10) == 0 && 6091 (p[10] == '\0' || p[10] == ' ' || p[10] == ';')) 6092 mcibuf.mci_flags |= MCIF_CVT7TO8; 6093 } 6094 #endif /* MIME7TO8 */ 6095 6096 if (!putfromline(&mcibuf, e) || 6097 !(*e->e_puthdr)(&mcibuf, e->e_header, e, M87F_OUTER) || 6098 !(*e->e_putbody)(&mcibuf, e, NULL) || 6099 !putline("\n", &mcibuf) || 6100 (sm_io_flush(f, SM_TIME_DEFAULT) != 0 || 6101 (SuperSafe != SAFE_NO && 6102 fsync(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL)) < 0) || 6103 sm_io_error(f))) 6104 { 6105 setstat(EX_IOERR); 6106 #if !NOFTRUNCATE 6107 (void) ftruncate(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), 6108 curoff); 6109 #endif 6110 } 6111 6112 /* reset ISUID & ISGID bits for paranoid systems */ 6113 #if HASFCHMOD 6114 (void) fchmod(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), 6115 (MODE_T) mode); 6116 #else 6117 (void) chmod(filename, (MODE_T) mode); 6118 #endif 6119 if (sm_io_close(f, SM_TIME_DEFAULT) < 0) 6120 setstat(EX_IOERR); 6121 (void) sm_io_flush(smioout, SM_TIME_DEFAULT); 6122 (void) setuid(RealUid); 6123 exit(ExitStat); 6124 /* NOTREACHED */ 6125 } 6126 else 6127 { 6128 /* parent -- wait for exit status */ 6129 int st; 6130 6131 st = waitfor(pid); 6132 if (st == -1) 6133 { 6134 syserr("mailfile: %s: wait", mailer->m_name); 6135 return EX_SOFTWARE; 6136 } 6137 if (WIFEXITED(st)) 6138 { 6139 errno = 0; 6140 return (WEXITSTATUS(st)); 6141 } 6142 else 6143 { 6144 syserr("mailfile: %s: child died on signal %d", 6145 mailer->m_name, st); 6146 return EX_UNAVAILABLE; 6147 } 6148 /* NOTREACHED */ 6149 } 6150 return EX_UNAVAILABLE; /* avoid compiler warning on IRIX */ 6151 } 6152 6153 static void 6154 mailfiletimeout(ignore) 6155 int ignore; 6156 { 6157 /* 6158 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD 6159 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE 6160 ** DOING. 6161 */ 6162 6163 errno = ETIMEDOUT; 6164 longjmp(CtxMailfileTimeout, 1); 6165 } 6166 6167 #if DANE 6168 6169 /* 6170 ** GETMPORT -- return the port of a mailer 6171 ** 6172 ** Parameters: 6173 ** m -- the mailer describing this host. 6174 ** 6175 ** Returns: 6176 ** the port of the mailer if defined. 6177 ** 0 otherwise 6178 ** <0 error 6179 */ 6180 6181 static int getmport __P((MAILER *)); 6182 6183 static int 6184 getmport(m) 6185 MAILER *m; 6186 { 6187 unsigned long ulval; 6188 char *buf, *ep; 6189 6190 if (m->m_port > 0) 6191 return m->m_port; 6192 6193 if (NULL == m->m_argv[0] ||NULL == m->m_argv[1]) 6194 return -1; 6195 buf = m->m_argv[2]; 6196 if (NULL == buf) 6197 return 0; 6198 6199 errno = 0; 6200 ulval = strtoul(buf, &ep, 0); 6201 if (buf[0] == '\0' || *ep != '\0') 6202 return -1; 6203 if (errno == ERANGE && ulval == ULONG_MAX) 6204 return -1; 6205 if (ulval > USHRT_MAX) 6206 return -1; 6207 m->m_port = (unsigned short) ulval; 6208 if (tTd(17, 30)) 6209 sm_dprintf("getmport: mailer=%s, port=%d\n", m->m_name, 6210 m->m_port); 6211 return m->m_port; 6212 } 6213 # define GETMPORT(m) getmport(m) 6214 #else /* DANE */ 6215 # define GETMPORT(m) 25 6216 #endif /* DANE */ 6217 6218 /* 6219 ** HOSTSIGNATURE -- return the "signature" for a host. 6220 ** 6221 ** The signature describes how we are going to send this -- it 6222 ** can be just the hostname (for non-Internet hosts) or can be 6223 ** an ordered list of MX hosts. 6224 ** 6225 ** Parameters: 6226 ** m -- the mailer describing this host. 6227 ** host -- the host name. 6228 ** ad -- DNSSEC: ad 6229 ** 6230 ** Returns: 6231 ** The signature for this host. 6232 ** 6233 ** Side Effects: 6234 ** Can tweak the symbol table. 6235 */ 6236 6237 #define MAXHOSTSIGNATURE 8192 /* max len of hostsignature */ 6238 6239 char * 6240 hostsignature(m, host, ad) 6241 register MAILER *m; 6242 char *host; 6243 bool ad; 6244 { 6245 register char *p; 6246 register STAB *s; 6247 time_t now; 6248 #if NAMED_BIND 6249 char sep = ':'; 6250 char prevsep = ':'; 6251 int i; 6252 int len; 6253 int nmx; 6254 int hl; 6255 char *hp; 6256 char *endp; 6257 char *lstr; 6258 int oldoptions = _res.options; 6259 char *mxhosts[MAXMXHOSTS + 1]; 6260 unsigned short mxprefs[MAXMXHOSTS + 1]; 6261 #endif /* NAMED_BIND */ 6262 6263 if (tTd(17, 3)) 6264 sm_dprintf("hostsignature(%s), ad=%d\n", host, ad); 6265 6266 /* 6267 ** If local delivery (and not remote), just return a constant. 6268 */ 6269 6270 if (bitnset(M_LOCALMAILER, m->m_flags) && 6271 strcmp(m->m_mailer, "[IPC]") != 0 && 6272 !(m->m_argv[0] != NULL && strcmp(m->m_argv[0], "TCP") == 0)) 6273 return "localhost"; 6274 6275 /* an empty host does not have MX records */ 6276 if (*host == '\0') 6277 return "_empty_"; 6278 6279 /* 6280 ** Check to see if this uses IPC -- if not, it can't have MX records. 6281 */ 6282 6283 if (strcmp(m->m_mailer, "[IPC]") != 0 || 6284 CurEnv->e_sendmode == SM_DEFER) 6285 { 6286 /* just an ordinary mailer or deferred mode */ 6287 return host; 6288 } 6289 #if NETUNIX 6290 else if (m->m_argv[0] != NULL && 6291 strcmp(m->m_argv[0], "FILE") == 0) 6292 { 6293 /* rendezvous in the file system, no MX records */ 6294 return host; 6295 } 6296 #endif /* NETUNIX */ 6297 6298 /* 6299 ** Look it up in the symbol table. 6300 */ 6301 6302 now = curtime(); 6303 s = stab(host, ST_HOSTSIG, ST_ENTER); 6304 if (s->s_hostsig.hs_sig != NULL) 6305 { 6306 if (s->s_hostsig.hs_exp >= now) 6307 { 6308 if (tTd(17, 3)) 6309 sm_dprintf("hostsignature(): stab(%s) found %s\n", host, 6310 s->s_hostsig.hs_sig); 6311 return s->s_hostsig.hs_sig; 6312 } 6313 6314 /* signature is expired: clear it */ 6315 sm_free(s->s_hostsig.hs_sig); 6316 s->s_hostsig.hs_sig = NULL; 6317 } 6318 6319 /* set default TTL */ 6320 s->s_hostsig.hs_exp = now + SM_DEFAULT_TTL; 6321 6322 /* 6323 ** Not already there or expired -- create a signature. 6324 */ 6325 6326 #if NAMED_BIND 6327 if (ConfigLevel < 2) 6328 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */ 6329 6330 for (hp = host; hp != NULL; hp = endp) 6331 { 6332 # if NETINET6 6333 if (*hp == '[') 6334 { 6335 endp = strchr(hp + 1, ']'); 6336 if (endp != NULL) 6337 endp = strpbrk(endp + 1, ":,"); 6338 } 6339 else 6340 endp = strpbrk(hp, ":,"); 6341 # else /* NETINET6 */ 6342 endp = strpbrk(hp, ":,"); 6343 # endif /* NETINET6 */ 6344 if (endp != NULL) 6345 { 6346 sep = *endp; 6347 *endp = '\0'; 6348 } 6349 6350 if (bitnset(M_NOMX, m->m_flags)) 6351 { 6352 /* skip MX lookups */ 6353 nmx = 1; 6354 mxhosts[0] = hp; 6355 } 6356 else 6357 { 6358 auto int rcode; 6359 int ttl; 6360 6361 nmx = getmxrr(hp, mxhosts, mxprefs, 6362 DROPLOCALHOST|TRYFALLBACK|(ad ? ISAD :0), 6363 &rcode, &ttl, GETMPORT(m)); 6364 if (nmx <= 0) 6365 { 6366 int save_errno; 6367 register MCI *mci; 6368 6369 /* update the connection info for this host */ 6370 save_errno = errno; 6371 mci = mci_get(hp, m); 6372 mci->mci_errno = save_errno; 6373 mci->mci_herrno = h_errno; 6374 mci->mci_lastuse = now; 6375 if (nmx == NULLMX) 6376 mci_setstat(mci, rcode, ESCNULLMXRCPT, 6377 ERRNULLMX); 6378 else if (rcode == EX_NOHOST) 6379 mci_setstat(mci, rcode, "5.1.2", 6380 "550 Host unknown"); 6381 else 6382 mci_setstat(mci, rcode, NULL, NULL); 6383 6384 /* use the original host name as signature */ 6385 nmx = 1; 6386 mxhosts[0] = hp; 6387 } 6388 if (tTd(17, 3)) 6389 sm_dprintf("hostsignature(): getmxrr() returned %d, mxhosts[0]=%s\n", 6390 nmx, mxhosts[0]); 6391 6392 /* 6393 ** Set new TTL: we use only one! 6394 ** We could try to use the minimum instead. 6395 */ 6396 6397 s->s_hostsig.hs_exp = now + SM_MIN(ttl, SM_DEFAULT_TTL); 6398 } 6399 6400 len = 0; 6401 for (i = 0; i < nmx; i++) 6402 len += strlen(mxhosts[i]) + 1; 6403 if (s->s_hostsig.hs_sig != NULL) 6404 len += strlen(s->s_hostsig.hs_sig) + 1; 6405 if (len < 0 || len >= MAXHOSTSIGNATURE) 6406 { 6407 sm_syslog(LOG_WARNING, NOQID, "hostsignature for host '%s' exceeds maxlen (%d): %d", 6408 host, MAXHOSTSIGNATURE, len); 6409 len = MAXHOSTSIGNATURE; 6410 } 6411 p = sm_pmalloc_x(len); 6412 if (s->s_hostsig.hs_sig != NULL) 6413 { 6414 (void) sm_strlcpy(p, s->s_hostsig.hs_sig, len); 6415 sm_free(s->s_hostsig.hs_sig); /* XXX */ 6416 s->s_hostsig.hs_sig = p; 6417 hl = strlen(p); 6418 p += hl; 6419 *p++ = prevsep; 6420 len -= hl + 1; 6421 } 6422 else 6423 s->s_hostsig.hs_sig = p; 6424 for (i = 0; i < nmx; i++) 6425 { 6426 hl = strlen(mxhosts[i]); 6427 if (len - 1 < hl || len <= 1) 6428 { 6429 /* force to drop out of outer loop */ 6430 len = -1; 6431 break; 6432 } 6433 if (i != 0) 6434 { 6435 if (mxprefs[i] == mxprefs[i - 1]) 6436 *p++ = ','; 6437 else 6438 *p++ = ':'; 6439 len--; 6440 } 6441 (void) sm_strlcpy(p, mxhosts[i], len); 6442 p += hl; 6443 len -= hl; 6444 } 6445 6446 /* 6447 ** break out of loop if len exceeded MAXHOSTSIGNATURE 6448 ** because we won't have more space for further hosts 6449 ** anyway (separated by : in the .cf file). 6450 */ 6451 6452 if (len < 0) 6453 break; 6454 if (endp != NULL) 6455 *endp++ = sep; 6456 prevsep = sep; 6457 } 6458 lstr = makelower_a(&s->s_hostsig.hs_sig, NULL); 6459 ASSIGN_IFDIFF(s->s_hostsig.hs_sig, lstr); 6460 if (ConfigLevel < 2) 6461 _res.options = oldoptions; 6462 #else /* NAMED_BIND */ 6463 /* not using BIND -- the signature is just the host name */ 6464 /* 6465 ** 'host' points to storage that will be freed after we are 6466 ** done processing the current envelope, so we copy it. 6467 */ 6468 s->s_hostsig.hs_sig = sm_pstrdup_x(host); 6469 #endif /* NAMED_BIND */ 6470 if (tTd(17, 1)) 6471 sm_dprintf("hostsignature(%s) = %s\n", host, s->s_hostsig.hs_sig); 6472 return s->s_hostsig.hs_sig; 6473 } 6474 /* 6475 ** PARSE_HOSTSIGNATURE -- parse the "signature" and return MX host array. 6476 ** 6477 ** The signature describes how we are going to send this -- it 6478 ** can be just the hostname (for non-Internet hosts) or can be 6479 ** an ordered list of MX hosts which must be randomized for equal 6480 ** MX preference values. 6481 ** 6482 ** Parameters: 6483 ** sig -- the host signature. 6484 ** mxhosts -- array to populate. 6485 ** mailer -- mailer. 6486 ** 6487 ** Returns: 6488 ** The number of hosts inserted into mxhosts array. 6489 ** 6490 ** Side Effects: 6491 ** Randomizes equal MX preference hosts in mxhosts. 6492 */ 6493 6494 static int 6495 parse_hostsignature(sig, mxhosts, mailer) 6496 char *sig; 6497 char **mxhosts; 6498 MAILER *mailer; 6499 { 6500 unsigned short curpref = 0; 6501 int nmx = 0, i, j; /* NOTE: i, j, and nmx must have same type */ 6502 char *hp, *endp; 6503 unsigned short prefer[MAXMXHOSTS]; 6504 long rndm[MAXMXHOSTS]; 6505 6506 for (hp = sig; hp != NULL; hp = endp) 6507 { 6508 char sep = ':'; 6509 6510 #if NETINET6 6511 if (*hp == '[') 6512 { 6513 endp = strchr(hp + 1, ']'); 6514 if (endp != NULL) 6515 endp = strpbrk(endp + 1, ":,"); 6516 } 6517 else 6518 endp = strpbrk(hp, ":,"); 6519 #else /* NETINET6 */ 6520 endp = strpbrk(hp, ":,"); 6521 #endif /* NETINET6 */ 6522 if (endp != NULL) 6523 { 6524 sep = *endp; 6525 *endp = '\0'; 6526 } 6527 6528 mxhosts[nmx] = hp; 6529 prefer[nmx] = curpref; 6530 if (mci_match(hp, mailer)) 6531 rndm[nmx] = 0; 6532 else 6533 rndm[nmx] = get_random(); 6534 6535 if (endp != NULL) 6536 { 6537 /* 6538 ** Since we don't have the original MX prefs, 6539 ** make our own. If the separator is a ':', that 6540 ** means the preference for the next host will be 6541 ** higher than this one, so simply increment curpref. 6542 */ 6543 6544 if (sep == ':') 6545 curpref++; 6546 6547 *endp++ = sep; 6548 } 6549 if (++nmx >= MAXMXHOSTS) 6550 break; 6551 } 6552 6553 /* sort the records using the random factor for equal preferences */ 6554 for (i = 0; i < nmx; i++) 6555 { 6556 for (j = i + 1; j < nmx; j++) 6557 { 6558 /* 6559 ** List is already sorted by MX preference, only 6560 ** need to look for equal preference MX records 6561 */ 6562 6563 if (prefer[i] < prefer[j]) 6564 break; 6565 6566 if (prefer[i] > prefer[j] || 6567 (prefer[i] == prefer[j] && rndm[i] > rndm[j])) 6568 { 6569 register unsigned short tempp; 6570 register long tempr; 6571 register char *temp1; 6572 6573 tempp = prefer[i]; 6574 prefer[i] = prefer[j]; 6575 prefer[j] = tempp; 6576 temp1 = mxhosts[i]; 6577 mxhosts[i] = mxhosts[j]; 6578 mxhosts[j] = temp1; 6579 tempr = rndm[i]; 6580 rndm[i] = rndm[j]; 6581 rndm[j] = tempr; 6582 } 6583 } 6584 } 6585 return nmx; 6586 } 6587 6588 #if STARTTLS 6589 static SSL_CTX *clt_ctx = NULL; 6590 static bool tls_ok_clt = true; 6591 6592 /* 6593 ** SETCLTTLS -- client side TLS: allow/disallow. 6594 ** 6595 ** Parameters: 6596 ** tls_ok -- should tls be done? 6597 ** 6598 ** Returns: 6599 ** none. 6600 ** 6601 ** Side Effects: 6602 ** sets tls_ok_clt (static variable in this module) 6603 */ 6604 6605 void 6606 setclttls(tls_ok) 6607 bool tls_ok; 6608 { 6609 tls_ok_clt = tls_ok; 6610 return; 6611 } 6612 /* 6613 ** INITCLTTLS -- initialize client side TLS 6614 ** 6615 ** Parameters: 6616 ** tls_ok -- should tls initialization be done? 6617 ** 6618 ** Returns: 6619 ** succeeded? 6620 ** 6621 ** Side Effects: 6622 ** sets tls_ok_clt (static variable in this module) 6623 */ 6624 6625 bool 6626 initclttls(tls_ok) 6627 bool tls_ok; 6628 { 6629 if (!tls_ok_clt) 6630 return false; 6631 tls_ok_clt = tls_ok; 6632 if (!tls_ok_clt) 6633 return false; 6634 if (clt_ctx != NULL) 6635 return true; /* already done */ 6636 tls_ok_clt = inittls(&clt_ctx, TLS_I_CLT, Clt_SSL_Options, false, 6637 CltCertFile, CltKeyFile, 6638 # if _FFR_CLIENTCA 6639 (CltCACertPath != NULL) ? CltCACertPath : 6640 # endif 6641 CACertPath, 6642 # if _FFR_CLIENTCA 6643 (CltCACertFile != NULL) ? CltCACertFile : 6644 # endif 6645 CACertFile, 6646 DHParams); 6647 return tls_ok_clt; 6648 } 6649 6650 /* 6651 ** STARTTLS -- try to start secure connection (client side) 6652 ** 6653 ** Parameters: 6654 ** m -- the mailer. 6655 ** mci -- the mailer connection info. 6656 ** e -- the envelope. 6657 ** 6658 ** Returns: 6659 ** success? 6660 ** (maybe this should be some other code than EX_ 6661 ** that denotes which stage failed.) 6662 */ 6663 6664 static int 6665 starttls(m, mci, e 6666 # if DANE 6667 , dane_vrfy_ctx 6668 # endif 6669 ) 6670 MAILER *m; 6671 MCI *mci; 6672 ENVELOPE *e; 6673 # if DANE 6674 dane_vrfy_ctx_P dane_vrfy_ctx; 6675 # endif 6676 { 6677 int smtpresult; 6678 int result = 0; 6679 int ret = EX_OK; 6680 int rfd, wfd; 6681 SSL *clt_ssl = NULL; 6682 time_t tlsstart; 6683 extern int TLSsslidx; 6684 6685 if (clt_ctx == NULL && !initclttls(true)) 6686 return EX_TEMPFAIL; 6687 6688 if (!TLS_set_engine(SSLEngine, false)) 6689 { 6690 sm_syslog(LOG_ERR, NOQID, 6691 "STARTTLS=client, engine=%s, TLS_set_engine=failed", 6692 SSLEngine); 6693 return EX_TEMPFAIL; 6694 } 6695 6696 /* clt_ssl needed for get_tls_se_features() hence create here */ 6697 if ((clt_ssl = SSL_new(clt_ctx)) == NULL) 6698 { 6699 if (LogLevel > 5) 6700 { 6701 sm_syslog(LOG_ERR, NOQID, 6702 "STARTTLS=client, error: SSL_new failed"); 6703 tlslogerr(LOG_WARNING, 9, "client"); 6704 } 6705 return EX_SOFTWARE; 6706 } 6707 6708 ret = get_tls_se_features(e, clt_ssl, &mci->mci_tlsi, false); 6709 if (EX_OK != ret) 6710 { 6711 sm_syslog(LOG_ERR, NOQID, 6712 "STARTTLS=client, get_tls_se_features=failed, ret=%d", 6713 ret); 6714 goto fail; 6715 } 6716 6717 smtpmessage("STARTTLS", m, mci); 6718 6719 /* get the reply */ 6720 smtpresult = reply(m, mci, e, TimeOuts.to_starttls, NULL, NULL, 6721 XS_STARTTLS); 6722 6723 /* check return code from server */ 6724 if (REPLYTYPE(smtpresult) == 4) 6725 { 6726 ret = EX_TEMPFAIL; 6727 goto fail; 6728 } 6729 if (smtpresult == 501) 6730 { 6731 ret = EX_USAGE; 6732 goto fail; 6733 } 6734 if (smtpresult == -1) 6735 { 6736 ret = smtpresult; 6737 goto fail; 6738 } 6739 6740 /* not an expected reply but we have to deal with it */ 6741 if (REPLYTYPE(smtpresult) == 5) 6742 { 6743 ret = EX_UNAVAILABLE; 6744 goto fail; 6745 } 6746 if (smtpresult != 220) 6747 { 6748 ret = EX_PROTOCOL; 6749 goto fail; 6750 } 6751 6752 if (LogLevel > 13) 6753 sm_syslog(LOG_INFO, NOQID, "STARTTLS=client, start=ok"); 6754 6755 /* SSL_clear(clt_ssl); ? */ 6756 result = SSL_set_ex_data(clt_ssl, TLSsslidx, &mci->mci_tlsi); 6757 if (0 == result) 6758 { 6759 if (LogLevel > 5) 6760 { 6761 sm_syslog(LOG_ERR, NOQID, 6762 "STARTTLS=client, error: SSL_set_ex_data failed=%d, idx=%d", 6763 result, TLSsslidx); 6764 tlslogerr(LOG_WARNING, 9, "client"); 6765 } 6766 goto fail; 6767 } 6768 # if DANE 6769 if (SM_TLSI_IS(&(mci->mci_tlsi), TLSI_FL_NODANE)) 6770 dane_vrfy_ctx->dane_vrfy_chk = DANE_NEVER; 6771 else 6772 { 6773 int r; 6774 6775 /* set SNI only if there is a TLSA RR */ 6776 if (dane_get_tlsa(dane_vrfy_ctx) != NULL && 6777 !(SM_IS_EMPTY(dane_vrfy_ctx->dane_vrfy_host) && 6778 SM_IS_EMPTY(dane_vrfy_ctx->dane_vrfy_sni))) 6779 { 6780 # if _FFR_MTA_STS 6781 SM_FREE(STS_SNI); 6782 # endif 6783 if ((r = SSL_set_tlsext_host_name(clt_ssl, 6784 (!SM_IS_EMPTY(dane_vrfy_ctx->dane_vrfy_sni) 6785 ? dane_vrfy_ctx->dane_vrfy_sni 6786 : dane_vrfy_ctx->dane_vrfy_host))) <= 0) 6787 { 6788 if (LogLevel > 5) 6789 { 6790 sm_syslog(LOG_ERR, NOQID, 6791 "STARTTLS=client, host=%s, SSL_set_tlsext_host_name=%d", 6792 dane_vrfy_ctx->dane_vrfy_host, r); 6793 } 6794 tlslogerr(LOG_ERR, 5, "client"); 6795 /* return EX_SOFTWARE; */ 6796 } 6797 } 6798 } 6799 memcpy(&mci->mci_tlsi.tlsi_dvc, dane_vrfy_ctx, sizeof(*dane_vrfy_ctx)); 6800 # endif /* DANE */ 6801 # if _FFR_MTA_STS 6802 if (STS_SNI != NULL) 6803 { 6804 int r; 6805 6806 if ((r = SSL_set_tlsext_host_name(clt_ssl, STS_SNI)) <= 0) 6807 { 6808 if (LogLevel > 5) 6809 { 6810 sm_syslog(LOG_ERR, NOQID, 6811 "STARTTLS=client, host=%s, SSL_set_tlsext_host_name=%d", 6812 STS_SNI, r); 6813 } 6814 tlslogerr(LOG_ERR, 5, "client"); 6815 /* return EX_SOFTWARE; */ 6816 } 6817 } 6818 # endif /* _FFR_MTA_STS */ 6819 6820 rfd = sm_io_getinfo(mci->mci_in, SM_IO_WHAT_FD, NULL); 6821 wfd = sm_io_getinfo(mci->mci_out, SM_IO_WHAT_FD, NULL); 6822 6823 if (rfd < 0 || wfd < 0 || 6824 (result = SSL_set_rfd(clt_ssl, rfd)) != 1 || 6825 (result = SSL_set_wfd(clt_ssl, wfd)) != 1) 6826 { 6827 if (LogLevel > 5) 6828 { 6829 sm_syslog(LOG_ERR, NOQID, 6830 "STARTTLS=client, error: SSL_set_xfd failed=%d", 6831 result); 6832 tlslogerr(LOG_WARNING, 9, "client"); 6833 } 6834 goto fail; 6835 } 6836 SSL_set_connect_state(clt_ssl); 6837 tlsstart = curtime(); 6838 6839 ssl_retry: 6840 if ((result = SSL_connect(clt_ssl)) <= 0) 6841 { 6842 int i, ssl_err; 6843 int save_errno = errno; 6844 6845 ssl_err = SSL_get_error(clt_ssl, result); 6846 i = tls_retry(clt_ssl, rfd, wfd, tlsstart, 6847 TimeOuts.to_starttls, ssl_err, "client"); 6848 if (i > 0) 6849 goto ssl_retry; 6850 6851 if (LogLevel > 5) 6852 { 6853 unsigned long l; 6854 const char *sr; 6855 6856 l = ERR_peek_error(); 6857 sr = ERR_reason_error_string(l); 6858 sm_syslog(LOG_WARNING, NOQID, 6859 "STARTTLS=client, error: connect failed=%d, reason=%s, SSL_error=%d, errno=%d, retry=%d", 6860 result, sr == NULL ? "unknown" : sr, ssl_err, 6861 save_errno, i); 6862 tlslogerr(LOG_WARNING, 9, "client"); 6863 } 6864 6865 goto fail; 6866 } 6867 mci->mci_ssl = clt_ssl; 6868 result = tls_get_info(mci->mci_ssl, false, mci->mci_host, 6869 &mci->mci_macro, true); 6870 6871 /* switch to use TLS... */ 6872 if (sfdctls(&mci->mci_in, &mci->mci_out, mci->mci_ssl) == 0) 6873 return EX_OK; 6874 6875 fail: 6876 /* failure */ 6877 SM_SSL_FREE(clt_ssl); 6878 return (EX_OK == ret) ? EX_SOFTWARE : ret; 6879 } 6880 6881 /* 6882 ** ENDTLSCLT -- shutdown secure connection (client side) 6883 ** 6884 ** Parameters: 6885 ** mci -- the mailer connection info. 6886 ** 6887 ** Returns: 6888 ** success? 6889 */ 6890 6891 static int 6892 endtlsclt(mci) 6893 MCI *mci; 6894 { 6895 int r; 6896 6897 if (!bitset(MCIF_TLSACT, mci->mci_flags)) 6898 return EX_OK; 6899 r = endtls(&mci->mci_ssl, "client"); 6900 mci->mci_flags &= ~MCIF_TLSACT; 6901 return r; 6902 } 6903 #endif /* STARTTLS */ 6904 #if STARTTLS || SASL 6905 /* 6906 ** ISCLTFLGSET -- check whether client flag is set. 6907 ** 6908 ** Parameters: 6909 ** e -- envelope. 6910 ** flag -- flag to check in {client_flags} 6911 ** 6912 ** Returns: 6913 ** true iff flag is set. 6914 */ 6915 6916 static bool 6917 iscltflgset(e, flag) 6918 ENVELOPE *e; 6919 int flag; 6920 { 6921 char *p; 6922 6923 p = macvalue(macid("{client_flags}"), e); 6924 if (p == NULL) 6925 return false; 6926 for (; *p != '\0'; p++) 6927 { 6928 /* look for just this one flag */ 6929 if (*p == (char) flag) 6930 return true; 6931 } 6932 return false; 6933 } 6934 #endif /* STARTTLS || SASL */ 6935