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