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