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