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