2 * Copyright (c) 1998-2010, 2012 Proofpoint, Inc. and its suppliers.
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.
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.
17 SM_RCSID("@(#)$Id: deliver.c,v 8.1030 2013-11-22 20:51:55 ca Exp $")
20 # include <login_cap.h>
23 #if NETINET || NETINET6
24 # include <arpa/inet.h>
32 static int deliver __P((ENVELOPE *, ADDRESS *));
33 static void dup_queue_file __P((ENVELOPE *, ENVELOPE *, int));
34 static void mailfiletimeout __P((int));
35 static void endwaittimeout __P((int));
36 static int parse_hostsignature __P((char *, char **, MAILER *));
37 static void sendenvelope __P((ENVELOPE *, int));
38 static int coloncmp __P((const char *, const char *));
41 # include <openssl/err.h>
43 static int starttls __P((MAILER *, MCI *, ENVELOPE *, dane_vrfy_ctx_P));
45 static int starttls __P((MAILER *, MCI *, ENVELOPE *));
47 static int endtlsclt __P((MCI *));
50 static bool iscltflgset __P((ENVELOPE *, int));
54 # include <ratectrl.h>
58 ** SENDALL -- actually send all the messages.
61 ** e -- the envelope to send.
62 ** mode -- the delivery mode to use. If SM_DEFAULT, use
63 ** the current e->e_sendmode.
69 ** Scans the send lists and sends everything it finds.
70 ** Delivers any appropriate error messages.
71 ** If we are running in a non-interactive mode, takes the
72 ** appropriate action.
84 register ENVELOPE *ee;
85 ENVELOPE *splitenv = NULL;
86 int oldverbose = Verbose;
87 bool somedeliveries = false, expensive = false;
91 ** If this message is to be discarded, don't bother sending
92 ** the message at all.
95 if (bitset(EF_DISCARD, e->e_flags))
98 sm_dprintf("sendall: discarding id %s\n", e->e_id);
99 e->e_flags |= EF_CLRQUEUE;
101 logundelrcpts(e, "discarded", 9, true);
102 else if (LogLevel > 4)
103 sm_syslog(LOG_INFO, e->e_id, "discarded");
104 markstats(e, NULL, STATS_REJECT);
109 ** If we have had global, fatal errors, don't bother sending
110 ** the message at all if we are in SMTP mode. Local errors
111 ** (e.g., a single address failing) will still cause the other
112 ** addresses to be sent.
115 if (bitset(EF_FATALERRS, e->e_flags) &&
116 (OpMode == MD_SMTP || OpMode == MD_DAEMON))
118 e->e_flags |= EF_CLRQUEUE;
122 /* determine actual delivery mode */
123 if (mode == SM_DEFAULT)
125 mode = e->e_sendmode;
126 if (mode != SM_VERIFY && mode != SM_DEFER &&
127 shouldqueue(e->e_msgpriority, e->e_ctime))
133 sm_dprintf("\n===== SENDALL: mode %c, id %s, e_from ",
135 printaddr(sm_debug_file(), &e->e_from, false);
136 sm_dprintf("\te_flags = ");
138 sm_dprintf("sendqueue:\n");
139 printaddr(sm_debug_file(), e->e_sendqueue, true);
143 ** Do any preprocessing necessary for the mode we are running.
144 ** Check to make sure the hop count is reasonable.
145 ** Delete sends to the sender in mailing lists.
152 if (e->e_hopcount > MaxHopCount)
156 if (e->e_sendqueue != NULL &&
157 e->e_sendqueue->q_paddr != NULL)
158 recip = e->e_sendqueue->q_paddr;
163 queueup(e, WILL_BE_QUEUED(mode), false);
164 e->e_flags |= EF_FATALERRS|EF_PM_NOTIFY|EF_CLRQUEUE;
165 ExitStat = EX_UNAVAILABLE;
166 syserr("554 5.4.6 Too many hops %d (%d max): from %s via %s, to %s",
167 e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
168 RealHostName == NULL ? "localhost" : RealHostName,
170 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
172 if (QS_IS_DEAD(q->q_state))
174 q->q_state = QS_BADADDR;
175 q->q_status = "5.4.6";
176 q->q_rstatus = "554 5.4.6 Too many hops";
182 ** Do sender deletion.
184 ** If the sender should be queued up, skip this.
185 ** This can happen if the name server is hosed when you
186 ** are trying to send mail. The result is that the sender
187 ** is instantiated in the queue as a recipient.
190 if (!bitset(EF_METOO, e->e_flags) &&
191 !QS_IS_QUEUEUP(e->e_from.q_state))
195 sm_dprintf("sendall: QS_SENDER ");
196 printaddr(sm_debug_file(), &e->e_from, false);
198 e->e_from.q_state = QS_SENDER;
199 (void) recipient(&e->e_from, &e->e_sendqueue, 0, e);
203 ** Handle alias owners.
205 ** We scan up the q_alias chain looking for owners.
206 ** We discard owners that are the same as the return path.
209 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
211 register struct address *a;
213 for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias)
216 q->q_owner = a->q_owner;
218 if (q->q_owner != NULL &&
219 !QS_IS_DEAD(q->q_state) &&
220 strcmp(q->q_owner, e->e_from.q_paddr) == 0)
226 sm_dprintf("\nAfter first owner pass, sendq =\n");
227 printaddr(sm_debug_file(), e->e_sendqueue, true);
232 while (owner != NULL && otherowners > 0)
235 sm_dprintf("owner = \"%s\", otherowners = %d\n",
238 otherowners = bitset(EF_SENDRECEIPT, e->e_flags) ? 1 : 0;
240 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
244 sm_dprintf("Checking ");
245 printaddr(sm_debug_file(), q, false);
247 if (QS_IS_DEAD(q->q_state))
250 sm_dprintf(" ... QS_IS_DEAD\n");
253 if (tTd(13, 29) && !tTd(13, 30))
255 sm_dprintf("Checking ");
256 printaddr(sm_debug_file(), q, false);
259 if (q->q_owner != NULL)
264 sm_dprintf(" ... First owner = \"%s\"\n",
268 else if (owner != q->q_owner)
270 if (strcmp(owner, q->q_owner) == 0)
273 sm_dprintf(" ... Same owner = \"%s\"\n",
276 /* make future comparisons cheap */
282 sm_dprintf(" ... Another owner \"%s\"\n",
288 else if (tTd(13, 40))
289 sm_dprintf(" ... Same owner = \"%s\"\n",
295 sm_dprintf(" ... Null owner\n");
299 if (QS_IS_BADADDR(q->q_state))
302 sm_dprintf(" ... QS_IS_BADADDR\n");
306 if (QS_IS_QUEUEUP(q->q_state))
308 MAILER *m = q->q_mailer;
311 ** If we have temporary address failures
312 ** (e.g., dns failure) and a fallback MX is
313 ** set, send directly to the fallback MX host.
316 if (FallbackMX != NULL &&
317 !wordinclass(FallbackMX, 'w') &&
319 !bitnset(M_NOMX, m->m_flags) &&
320 strcmp(m->m_mailer, "[IPC]") == 0 &&
321 m->m_argv[0] != NULL &&
322 strcmp(m->m_argv[0], "TCP") == 0)
328 sm_dprintf(" ... FallbackMX\n");
330 len = strlen(FallbackMX) + 1;
331 p = sm_rpool_malloc_x(e->e_rpool, len);
332 (void) sm_strlcpy(p, FallbackMX, len);
339 sm_dprintf(" ... QS_IS_QUEUEUP\n");
345 ** If this mailer is expensive, and if we don't
346 ** want to make connections now, just mark these
347 ** addresses and return. This is useful if we
348 ** want to batch connections to reduce load. This
349 ** will cause the messages to be queued up, and a
350 ** daemon will come along to send the messages later.
353 if (NoConnect && !Verbose &&
354 bitnset(M_EXPENSIVE, q->q_mailer->m_flags))
357 sm_dprintf(" ... expensive\n");
358 q->q_state = QS_QUEUEUP;
361 else if (bitnset(M_HOLD, q->q_mailer->m_flags) &&
362 QueueLimitId == NULL &&
363 QueueLimitSender == NULL &&
364 QueueLimitRecipient == NULL)
367 sm_dprintf(" ... hold\n");
368 q->q_state = QS_QUEUEUP;
371 else if (QueueMode != QM_QUARANTINE &&
372 e->e_quarmsg != NULL)
375 sm_dprintf(" ... quarantine: %s\n",
377 q->q_state = QS_QUEUEUP;
383 sm_dprintf(" ... deliverable\n");
384 somedeliveries = true;
388 if (owner != NULL && otherowners > 0)
391 ** Split this envelope into two.
394 ee = (ENVELOPE *) sm_rpool_malloc_x(e->e_rpool,
397 ee->e_message = NULL;
402 sm_dprintf("sendall: split %s into %s, owner = \"%s\", otherowners = %d\n",
403 e->e_id, ee->e_id, owner,
406 ee->e_header = copyheader(e->e_header, ee->e_rpool);
407 ee->e_sendqueue = copyqueue(e->e_sendqueue,
409 ee->e_errorqueue = copyqueue(e->e_errorqueue,
411 ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS|EF_SENDRECEIPT|EF_RET_PARAM);
412 ee->e_flags |= EF_NORECEIPT;
413 setsender(owner, ee, NULL, '\0', true);
416 sm_dprintf("sendall(split): QS_SENDER ");
417 printaddr(sm_debug_file(), &ee->e_from, false);
419 ee->e_from.q_state = QS_SENDER;
423 ee->e_qgrp = e->e_qgrp;
424 ee->e_qdir = e->e_qdir;
425 ee->e_errormode = EM_MAIL;
426 ee->e_sibling = splitenv;
427 ee->e_statmsg = NULL;
428 if (e->e_quarmsg != NULL)
429 ee->e_quarmsg = sm_rpool_strdup_x(ee->e_rpool,
433 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
435 if (q->q_owner == owner)
437 q->q_state = QS_CLONED;
439 sm_dprintf("\t... stripping %s from original envelope\n",
443 for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
445 if (q->q_owner != owner)
447 q->q_state = QS_CLONED;
449 sm_dprintf("\t... dropping %s from cloned envelope\n",
454 /* clear DSN parameters */
455 q->q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS);
456 q->q_flags |= DefaultNotify & ~QPINGONSUCCESS;
458 sm_dprintf("\t... moving %s to cloned envelope\n",
463 if (mode != SM_VERIFY && bitset(EF_HAS_DF, e->e_flags))
464 dup_queue_file(e, ee, DATAFL_LETTER);
467 ** Give the split envelope access to the parent
468 ** transcript file for errors obtained while
469 ** processing the recipients (done before the
470 ** envelope splitting).
473 if (e->e_xfp != NULL)
474 ee->e_xfp = sm_io_dup(e->e_xfp);
476 /* failed to dup e->e_xfp, start a new transcript */
477 if (ee->e_xfp == NULL)
480 if (mode != SM_VERIFY && LogLevel > 4)
481 sm_syslog(LOG_INFO, e->e_id,
482 "%s: clone: owner=%s",
489 setsender(owner, e, NULL, '\0', true);
492 sm_dprintf("sendall(owner): QS_SENDER ");
493 printaddr(sm_debug_file(), &e->e_from, false);
495 e->e_from.q_state = QS_SENDER;
496 e->e_errormode = EM_MAIL;
497 e->e_flags |= EF_NORECEIPT;
498 e->e_flags &= ~EF_FATALERRS;
501 /* if nothing to be delivered, just queue up everything */
502 if (!somedeliveries && !WILL_BE_QUEUED(mode) &&
508 sm_dprintf("No deliveries: auto-queueing\n");
512 /* treat this as a delivery in terms of counting tries */
516 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
524 if ((WILL_BE_QUEUED(mode) || mode == SM_FORK ||
525 (mode != SM_VERIFY &&
526 (SuperSafe == SAFE_REALLY ||
527 SuperSafe == SAFE_REALLY_POSTMILTER))) &&
528 (!bitset(EF_INQUEUE, e->e_flags) || splitenv != NULL))
533 ** Be sure everything is instantiated in the queue.
534 ** Split envelopes first in case the machine crashes.
535 ** If the original were done first, we may lose
542 msync = mode == SM_FORK;
545 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
546 queueup(ee, WILL_BE_QUEUED(mode), msync);
547 queueup(e, WILL_BE_QUEUED(mode), msync);
551 checkfds("after envelope splitting");
554 ** If we belong in background, fork now.
559 sm_dprintf("sendall: final mode = %c\n", mode);
562 sm_dprintf("\n================ Final Send Queue(s) =====================\n");
563 sm_dprintf("\n *** Envelope %s, e_from=%s ***\n",
564 e->e_id, e->e_from.q_paddr);
565 printaddr(sm_debug_file(), e->e_sendqueue, true);
566 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
568 sm_dprintf("\n *** Envelope %s, e_from=%s ***\n",
569 ee->e_id, ee->e_from.q_paddr);
570 printaddr(sm_debug_file(), ee->e_sendqueue, true);
572 sm_dprintf("==========================================================\n\n");
587 e->e_flags |= EF_INQUEUE;
588 (void) dropenvelope(e, splitenv != NULL, true);
589 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
591 if (ee->e_nrcpts > 0)
592 ee->e_flags |= EF_INQUEUE;
593 (void) dropenvelope(ee, false, true);
598 if (e->e_xfp != NULL)
599 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
603 ** Since fcntl locking has the interesting semantic that
604 ** the lock is owned by a process, not by an open file
605 ** descriptor, we have to flush this to the queue, and
606 ** then restart from scratch in the child.
610 /* save id for future use */
613 /* now drop the envelope in the parent */
614 e->e_flags |= EF_INQUEUE;
615 (void) dropenvelope(e, splitenv != NULL, false);
617 /* arrange to reacquire lock after fork */
621 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
623 /* save id for future use */
624 char *qid = ee->e_id;
626 /* drop envelope in parent */
627 ee->e_flags |= EF_INQUEUE;
628 (void) dropenvelope(ee, false, false);
630 /* and save qid for reacquisition */
634 #endif /* !HASFLOCK */
637 ** Since the delivery may happen in a child and the parent
638 ** does not wait, the parent may close the maps thereby
639 ** removing any shared memory used by the map. Therefore,
640 ** close the maps now so the child will dynamically open
641 ** them if necessary.
649 syserr("deliver: fork 1");
654 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
657 #endif /* HASFLOCK */
662 /* be sure we leave the temp files to our child */
663 /* close any random open files in the envelope */
665 if (e->e_dfp != NULL)
666 (void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
668 e->e_flags &= ~EF_HAS_DF;
670 /* can't call unlockqueue to avoid unlink of xfp */
671 if (e->e_lockfp != NULL)
672 (void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT);
674 syserr("%s: sendall: null lockfp", e->e_id);
676 #endif /* HASFLOCK */
678 /* make sure the parent doesn't own the envelope */
682 /* catch intermediate zombie */
688 /* Reset global flags */
689 RestartRequest = NULL;
690 RestartWorkGroup = false;
691 ShutdownRequest = NULL;
695 ** Initialize exception stack and default exception
696 ** handler for child process.
699 sm_exc_newthread(fatal_error);
702 ** Since we have accepted responsbility for the message,
703 ** change the SIGTERM handler. intsig() (the old handler)
704 ** would remove the envelope if this was a command line
705 ** message submission.
708 (void) sm_signal(SIGTERM, SIG_DFL);
711 /* double fork to avoid zombies */
716 #endif /* USE_DOUBLE_FORK */
718 CurrentPid = getpid();
720 /* be sure we are immune from the terminal */
724 /* prevent parent from waiting if there was an error */
728 syserr("deliver: fork 2");
730 e->e_flags |= EF_INQUEUE;
734 finis(true, true, ExitStat);
737 /* be sure to give error messages in child */
741 ** Close any cached connections.
743 ** We don't send the QUIT protocol because the parent
744 ** still knows about the connection.
746 ** This should only happen when delivering an error
750 mci_flush(false, NULL);
757 ** Now reacquire and run the various queue files.
760 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
762 ENVELOPE *sibling = ee->e_sibling;
764 (void) dowork(ee->e_qgrp, ee->e_qdir, ee->e_id,
766 ee->e_sibling = sibling;
768 (void) dowork(e->e_qgrp, e->e_qdir, e->e_id,
770 finis(true, true, ExitStat);
771 #endif /* HASFLOCK */
774 sendenvelope(e, mode);
775 (void) dropenvelope(e, true, true);
776 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
779 if (mode != SM_VERIFY)
781 sendenvelope(ee, mode);
782 (void) dropenvelope(ee, true, true);
786 Verbose = oldverbose;
788 finis(true, true, ExitStat);
792 sendenvelope(e, mode)
793 register ENVELOPE *e;
800 sm_dprintf("sendenvelope(%s) e_flags=0x%lx\n",
801 e->e_id == NULL ? "[NOQUEUE]" : e->e_id,
804 sm_syslog(LOG_DEBUG, e->e_id,
805 "sendenvelope, flags=0x%lx",
809 ** If we have had global, fatal errors, don't bother sending
810 ** the message at all if we are in SMTP mode. Local errors
811 ** (e.g., a single address failing) will still cause the other
812 ** addresses to be sent.
815 if (bitset(EF_FATALERRS, e->e_flags) &&
816 (OpMode == MD_SMTP || OpMode == MD_DAEMON))
818 e->e_flags |= EF_CLRQUEUE;
823 ** Don't attempt deliveries if we want to bounce now
824 ** or if deliver-by time is exceeded.
827 if (!bitset(EF_RESPONSE, e->e_flags) &&
828 (TimeOuts.to_q_return[e->e_timeoutclass] == NOW ||
829 (IS_DLVR_RETURN(e) && e->e_deliver_by > 0 &&
830 curtime() > e->e_ctime + e->e_deliver_by)))
834 ** Run through the list and send everything.
836 ** Set EF_GLOBALERRS so that error messages during delivery
837 ** result in returned mail.
841 e->e_flags |= EF_GLOBALERRS;
843 macdefine(&e->e_macro, A_PERM, macid("{envid}"), e->e_envid);
844 macdefine(&e->e_macro, A_PERM, macid("{bodytype}"), e->e_bodytype);
847 if (!bitset(EF_SPLIT, e->e_flags))
853 ** Save old sibling and set it to NULL to avoid
854 ** queueing up the same envelopes again.
855 ** This requires that envelopes in that list have
856 ** been take care of before (or at some other place).
859 oldsib = e->e_sibling;
861 if (!split_by_recipient(e) &&
862 bitset(EF_FATALERRS, e->e_flags))
864 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
865 e->e_flags |= EF_CLRQUEUE;
868 for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
869 queueup(ee, false, true);
872 for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
874 /* now unlock the job */
878 /* this envelope is marked unused */
879 if (ee->e_dfp != NULL)
881 (void) sm_io_close(ee->e_dfp, SM_TIME_DEFAULT);
885 ee->e_flags &= ~EF_HAS_DF;
887 e->e_sibling = oldsib;
890 /* now run through the queue */
891 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
894 char wbuf[MAXNAME + 20];
896 (void) sm_snprintf(wbuf, sizeof(wbuf), "sendall(%.*s)",
897 MAXNAME, q->q_paddr);
900 if (mode == SM_VERIFY)
902 e->e_to = q->q_paddr;
903 if (QS_IS_SENDABLE(q->q_state))
905 if (q->q_host != NULL && q->q_host[0] != '\0')
906 message("deliverable: mailer %s, host %s, user %s",
911 message("deliverable: mailer %s, user %s",
916 else if (QS_IS_OK(q->q_state))
919 ** Checkpoint the send list every few addresses
922 if (CheckpointInterval > 0 &&
923 e->e_nsent >= CheckpointInterval)
925 queueup(e, false, false);
928 (void) deliver(e, q);
934 e->e_dtime = curtime();
939 checkfd012("end of sendenvelope");
943 #if REQUIRES_DIR_FSYNC
945 ** SYNC_DIR -- fsync a directory based on a filename
948 ** filename -- path of file
956 sync_dir(filename, panic)
962 char dir[MAXPATHLEN];
964 if (!RequiresDirfsync)
967 /* filesystems which require the directory be synced */
968 dirp = strrchr(filename, '/');
971 if (sm_strlcpy(dir, filename, sizeof(dir)) >= sizeof(dir))
973 dir[dirp - filename] = '\0';
978 dirfd = open(dirp, O_RDONLY, 0700);
980 sm_syslog(LOG_INFO, NOQID, "sync_dir: %s: fsync(%d)",
984 if (fsync(dirfd) < 0)
987 syserr("!sync_dir: cannot fsync directory %s",
989 else if (LogLevel > 1)
990 sm_syslog(LOG_ERR, NOQID,
991 "sync_dir: cannot fsync directory %s: %s",
992 dirp, sm_errstring(errno));
997 #endif /* REQUIRES_DIR_FSYNC */
999 ** DUP_QUEUE_FILE -- duplicate a queue file into a split queue
1002 ** e -- the existing envelope
1003 ** ee -- the new envelope
1004 ** type -- the queue file type (e.g., DATAFL_LETTER)
1011 dup_queue_file(e, ee, type)
1015 char f1buf[MAXPATHLEN], f2buf[MAXPATHLEN];
1021 ** Make sure both are in the same directory.
1024 (void) sm_strlcpy(f1buf, queuename(e, type), sizeof(f1buf));
1025 (void) sm_strlcpy(f2buf, queuename(ee, type), sizeof(f2buf));
1027 /* Force the df to disk if it's not there yet */
1028 if (type == DATAFL_LETTER && e->e_dfp != NULL &&
1029 sm_io_setinfo(e->e_dfp, SM_BF_COMMIT, NULL) < 0 &&
1032 syserr("!dup_queue_file: can't commit %s", f1buf);
1036 if (link(f1buf, f2buf) < 0)
1038 int save_errno = errno;
1040 syserr("sendall: link(%s, %s)", f1buf, f2buf);
1041 if (save_errno == EEXIST)
1043 if (unlink(f2buf) < 0)
1045 syserr("!sendall: unlink(%s): permanent",
1049 if (link(f1buf, f2buf) < 0)
1051 syserr("!sendall: link(%s, %s): permanent",
1057 SYNC_DIR(f2buf, true);
1060 ** DOFORK -- do a fork, retrying a couple of times on failure.
1062 ** This MUST be a macro, since after a vfork we are running
1063 ** two processes on the same stack!!!
1069 ** From a macro??? You've got to be kidding!
1072 ** Modifies the ==> LOCAL <== variable 'pid', leaving:
1073 ** pid of child in parent, zero in child.
1074 ** -1 on unrecoverable error.
1077 ** I'm awfully sorry this looks so awful. That's
1078 ** vfork for you.....
1081 #define NFORKTRIES 5
1087 #define DOFORK(fORKfN) \
1091 for (i = NFORKTRIES; --i >= 0; )\
1097 (void) sleep((unsigned) NFORKTRIES - i);\
1101 ** DOFORK -- simple fork interface to DOFORK.
1107 ** pid of child in parent.
1112 ** returns twice, once in parent and once in child.
1118 register pid_t pid = -1;
1125 ** COLONCMP -- compare host-signatures up to first ':' or EOS
1127 ** This takes two strings which happen to be host-signatures and
1128 ** compares them. If the lowest preference portions of the MX-RR's
1129 ** match (up to ':' or EOS, whichever is first), then we have
1130 ** match. This is used for coattail-piggybacking messages during
1131 ** message delivery.
1132 ** If the signatures are the same up to the first ':' the remainder of
1133 ** the signatures are then compared with a normal strcmp(). This saves
1134 ** re-examining the first part of the signatures.
1137 ** a - first host-signature
1138 ** b - second host-signature
1141 ** HS_MATCH_NO -- no "match".
1142 ** HS_MATCH_FIRST -- "match" for the first MX preference
1143 ** (up to the first colon (':')).
1144 ** HS_MATCH_FULL -- match for the entire MX record.
1150 #define HS_MATCH_NO 0
1151 #define HS_MATCH_FIRST 1
1152 #define HS_MATCH_FULL 2
1156 register const char *a;
1157 register const char *b;
1159 int ret = HS_MATCH_NO;
1164 /* Need to account for IPv6 bracketed addresses */
1167 else if (*a == ']' && braclev > 0)
1169 else if (*a == ':' && braclev <= 0)
1171 ret = HS_MATCH_FIRST;
1175 else if (*a == '\0')
1176 return HS_MATCH_FULL; /* a full match */
1179 if (ret == HS_MATCH_NO &&
1181 ((*a == '\0' && *(b - 1) == ':') ||
1182 (*a == ':' && *(b - 1) == '\0')))
1183 return HS_MATCH_FIRST;
1184 if (ret == HS_MATCH_FIRST && strcmp(a, b) == 0)
1185 return HS_MATCH_FULL;
1191 ** SHOULD_TRY_FBSH -- Should try FallbackSmartHost?
1195 ** tried_fallbacksmarthost -- has been tried already? (in/out)
1196 ** hostbuf -- buffer for hostname (expand FallbackSmartHost) (out)
1197 ** hbsz -- size of hostbuf
1198 ** status -- current delivery status
1201 ** true iff FallbackSmartHost should be tried.
1204 static bool should_try_fbsh __P((ENVELOPE *, bool *, char *, size_t, int));
1207 should_try_fbsh(e, tried_fallbacksmarthost, hostbuf, hbsz, status)
1209 bool *tried_fallbacksmarthost;
1215 ** If the host was not found or a temporary failure occurred
1216 ** and a FallbackSmartHost is defined (and we have not yet
1217 ** tried it), then make one last try with it as the host.
1220 if ((status == EX_NOHOST || status == EX_TEMPFAIL) &&
1221 FallbackSmartHost != NULL && !*tried_fallbacksmarthost)
1223 *tried_fallbacksmarthost = true;
1224 expand(FallbackSmartHost, hostbuf, hbsz, e);
1225 if (!wordinclass(hostbuf, 'w'))
1228 sm_dprintf("one last try with FallbackSmartHost %s\n",
1237 ** DELIVER -- Deliver a message to a list of addresses.
1239 ** This routine delivers to everyone on the same host as the
1240 ** user on the head of the list. It is clever about mailers
1241 ** that don't handle multiple users. It is NOT guaranteed
1242 ** that it will deliver to all these addresses however -- so
1243 ** deliver should be called once for each address on the list.
1244 ** Deliver tries to be as opportunistic as possible about piggybacking
1245 ** messages. Some definitions to make understanding easier follow below.
1246 ** Piggybacking occurs when an existing connection to a mail host can
1247 ** be used to send the same message to more than one recipient at the
1248 ** same time. So "no piggybacking" means one message for one recipient
1249 ** per connection. "Intentional piggybacking" happens when the
1250 ** recipients' host address (not the mail host address) is used to
1251 ** attempt piggybacking. Recipients with the same host address
1252 ** have the same mail host. "Coincidental piggybacking" relies on
1253 ** piggybacking based on all the mail host addresses in the MX-RR. This
1254 ** is "coincidental" in the fact it could not be predicted until the
1255 ** MX Resource Records for the hosts were obtained and examined. For
1256 ** example (preference order and equivalence is important, not values):
1257 ** domain1 IN MX 10 mxhost-A
1258 ** IN MX 20 mxhost-B
1259 ** domain2 IN MX 4 mxhost-A
1261 ** Domain1 and domain2 can piggyback the same message to mxhost-A or
1262 ** mxhost-B (if mxhost-A cannot be reached).
1263 ** "Coattail piggybacking" relaxes the strictness of "coincidental
1264 ** piggybacking" in the hope that most significant (lowest value)
1265 ** MX preference host(s) can create more piggybacking. For example
1266 ** (again, preference order and equivalence is important, not values):
1267 ** domain3 IN MX 100 mxhost-C
1268 ** IN MX 100 mxhost-D
1269 ** IN MX 200 mxhost-E
1270 ** domain4 IN MX 50 mxhost-C
1271 ** IN MX 50 mxhost-D
1272 ** IN MX 80 mxhost-F
1273 ** A message for domain3 and domain4 can piggyback to mxhost-C if mxhost-C
1274 ** is available. Same with mxhost-D because in both RR's the preference
1275 ** value is the same as mxhost-C, respectively.
1276 ** So deliver attempts coattail piggybacking when possible. If the
1277 ** first MX preference level hosts cannot be used then the piggybacking
1278 ** reverts to coincidental piggybacking. Using the above example you
1279 ** cannot deliver to mxhost-F for domain3 regardless of preference value.
1280 ** ("Coattail" from "riding on the coattails of your predecessor" meaning
1281 ** gaining benefit from a predecessor effort with no or little addition
1282 ** effort. The predecessor here being the preceding MX RR).
1285 ** e -- the envelope to deliver.
1286 ** firstto -- head of the address list to deliver to.
1289 ** zero -- successfully delivered.
1290 ** else -- some failure, see ExitStat for more info.
1293 ** The standard input is passed off to someone.
1298 register ENVELOPE *e;
1301 char *host; /* host being sent to */
1302 char *user; /* user being sent to */
1304 register char **mvp;
1306 register MAILER *m; /* mailer for this recipient */
1307 ADDRESS *volatile ctladdr;
1308 #if HASSETUSERCONTEXT
1309 ADDRESS *volatile contextaddr = NULL;
1311 register MCI *volatile mci;
1312 register ADDRESS *SM_NONVOLATILE to = firstto;
1313 volatile bool clever = false; /* running user smtp to this mailer */
1314 ADDRESS *volatile tochain = NULL; /* users chain in this mailer call */
1315 int rcode; /* response code */
1316 SM_NONVOLATILE int lmtp_rcode = EX_OK;
1317 SM_NONVOLATILE int nummxhosts = 0; /* number of MX hosts available */
1318 SM_NONVOLATILE int hostnum = 0; /* current MX host index */
1319 char *firstsig; /* signature of firstto */
1320 volatile pid_t pid = -1;
1321 char *volatile curhost;
1322 SM_NONVOLATILE unsigned short port = 0;
1323 SM_NONVOLATILE time_t enough = 0;
1325 char *SM_NONVOLATILE mux_path = NULL; /* path to UNIX domain socket */
1329 bool anyok; /* at least one address was OK */
1330 SM_NONVOLATILE bool goodmxfound = false; /* at least one MX was OK */
1334 /* 0: try TLS, 1: try without TLS again, >1: don't try again */
1337 dane_vrfy_ctx_T dane_vrfy_ctx;
1341 #if STARTTLS || SASL
1344 # define RM_TRAIL_DOT(name) \
1346 dotpos = strlen(name) - 1; \
1349 if (name[dotpos] == '.') \
1350 name[dotpos] = '\0'; \
1356 # define FIX_TRAIL_DOT(name) \
1359 name[dotpos] = '.'; \
1366 static int tobufsize = 0;
1367 static char *tobuf = NULL;
1368 char *rpath; /* translated return path */
1371 char *mxhosts[MAXMXHOSTS + 1];
1372 char *pv[MAXPV + 1];
1373 char buf[MAXNAME + 1];
1374 char cbuf[MAXPATHLEN];
1377 SM_REQUIRE(firstto != NULL); /* same as to */
1378 if (!QS_IS_OK(to->q_state))
1381 suidwarn = geteuid() == 0;
1383 SM_REQUIRE(e != NULL);
1386 CurEnv = e; /* just in case */
1387 e->e_statmsg = NULL;
1388 SmtpError[0] = '\0';
1393 memset(&dane_vrfy_ctx, '\0', sizeof(dane_vrfy_ctx));
1399 sm_dprintf("\n--deliver, id=%s, mailer=%s, host=`%s', first user=`%s'\n",
1400 e->e_id, m->m_name, host, to->q_user);
1402 printopenfds(false);
1405 ** Clear {client_*} macros if this is a bounce message to
1406 ** prevent rejection by check_compat ruleset.
1409 if (bitset(EF_RESPONSE, e->e_flags))
1411 macdefine(&e->e_macro, A_PERM, macid("{client_name}"), "");
1412 macdefine(&e->e_macro, A_PERM, macid("{client_ptr}"), "");
1413 macdefine(&e->e_macro, A_PERM, macid("{client_addr}"), "");
1414 macdefine(&e->e_macro, A_PERM, macid("{client_port}"), "");
1415 macdefine(&e->e_macro, A_PERM, macid("{client_resolve}"), "");
1420 ADDRESS *skip_back = NULL;
1423 ** Do initial argv setup.
1424 ** Insert the mailer name. Notice that $x expansion is
1425 ** NOT done on the mailer name. Then, if the mailer has
1426 ** a picky -f flag, we insert it as appropriate. This
1427 ** code does not check for 'pv' overflow; this places a
1428 ** manifest lower limit of 4 for MAXPV.
1429 ** The from address rewrite is expected to make
1430 ** the address relative to the other end.
1433 /* rewrite from address, using rewriting rules */
1435 SM_ASSERT(e->e_from.q_mailer != NULL);
1436 if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags))
1439 p = e->e_from.q_paddr;
1440 rpath = remotename(p, m, RF_SENDERADDR|RF_CANONICAL, &rcode, e);
1441 if (rcode != EX_OK && bitnset(M_xSMTP, m->m_flags))
1443 if (strlen(rpath) > MAXNAME)
1445 rpath = shortenstring(rpath, MAXSHORTSTR);
1447 /* avoid bogus errno */
1449 syserr("remotename: huge return path %s", rpath);
1451 rpath = sm_rpool_strdup_x(e->e_rpool, rpath);
1452 macdefine(&e->e_macro, A_PERM, 'g', rpath);
1453 macdefine(&e->e_macro, A_PERM, 'h', host);
1456 *pvp++ = m->m_argv[0];
1458 /* ignore long term host status information if mailer flag W is set */
1459 if (bitnset(M_NOHOSTSTAT, m->m_flags))
1460 IgnoreHostStatus = true;
1462 /* insert -f or -r flag as appropriate */
1464 (bitnset(M_FOPT, m->m_flags) ||
1465 bitnset(M_ROPT, m->m_flags)))
1467 if (bitnset(M_FOPT, m->m_flags))
1475 ** Append the other fixed parts of the argv. These run
1476 ** up to the first entry containing "$u". There can only
1477 ** be one of these, and there are only a few more slots
1478 ** in the pv after it.
1481 for (mvp = m->m_argv; (p = *++mvp) != NULL; )
1483 /* can't use strchr here because of sign extension problems */
1486 if ((*p++ & 0377) == MACROEXPAND)
1496 /* this entry is safe -- go ahead and process it */
1497 expand(*mvp, buf, sizeof(buf), e);
1498 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1499 if (pvp >= &pv[MAXPV - 3])
1501 syserr("554 5.3.5 Too many parameters to %s before $u",
1509 ** If we have no substitution for the user name in the argument
1510 ** list, we know that we must supply the names otherwise -- and
1511 ** SMTP is the answer!!
1516 /* running LMTP or SMTP */
1519 setbitn(M_xSMTP, m->m_flags);
1521 else if (bitnset(M_LMTP, m->m_flags))
1523 /* not running LMTP */
1524 sm_syslog(LOG_ERR, NULL,
1525 "Warning: mailer %s: LMTP flag (F=z) turned off",
1527 clrbitn(M_LMTP, m->m_flags);
1531 ** At this point *mvp points to the argument with $u. We
1532 ** run through our address list and append all the addresses
1533 ** we can. If we run out of space, do not fret! We can
1534 ** always send another copy later.
1541 if (firstto->q_signature == NULL)
1542 firstto->q_signature = hostsignature(firstto->q_mailer,
1544 firstto->q_flags & QSECURE);
1545 firstsig = firstto->q_signature;
1547 for (; to != NULL; to = to->q_next)
1549 /* avoid sending multiple recipients to dumb mailers */
1550 if (tochain != NULL && !bitnset(M_MUSER, m->m_flags))
1553 /* if already sent or not for this host, don't send */
1554 if (!QS_IS_OK(to->q_state)) /* already sent; look at next */
1558 ** Must be same mailer to keep grouping rcpts.
1559 ** If mailers don't match: continue; sendqueue is not
1560 ** sorted by mailers, so don't break;
1563 if (to->q_mailer != firstto->q_mailer)
1566 if (to->q_signature == NULL) /* for safety */
1567 to->q_signature = hostsignature(to->q_mailer,
1569 to->q_flags & QSECURE);
1572 ** This is for coincidental and tailcoat piggybacking messages
1573 ** to the same mail host. While the signatures are identical
1574 ** (that's the MX-RR's are identical) we can do coincidental
1575 ** piggybacking. We try hard for coattail piggybacking
1576 ** with the same mail host when the next recipient has the
1577 ** same host at lowest preference. It may be that this
1578 ** won't work out, so 'skip_back' is maintained if a backup
1579 ** to coincidental piggybacking or full signature must happen.
1582 ret = firstto == to ? HS_MATCH_FULL :
1583 coloncmp(to->q_signature, firstsig);
1584 if (ret == HS_MATCH_FULL)
1586 else if (ret == HS_MATCH_NO)
1591 /* avoid overflowing tobuf */
1592 strsize += strlen(to->q_paddr) + 1;
1593 if (strsize > TOBUFSIZE)
1597 if (++rcptcount > to->q_mailer->m_maxrcpt)
1602 sm_dprintf("\nsend to ");
1603 printaddr(sm_debug_file(), to, false);
1606 /* compute effective uid/gid when sending */
1607 if (bitnset(M_RUNASRCPT, to->q_mailer->m_flags))
1608 #if HASSETUSERCONTEXT
1609 contextaddr = ctladdr = getctladdr(to);
1611 ctladdr = getctladdr(to);
1616 sm_dprintf("ctladdr=");
1617 printaddr(sm_debug_file(), ctladdr, false);
1621 e->e_to = to->q_paddr;
1624 ** Check to see that these people are allowed to
1625 ** talk to each other.
1626 ** Check also for overflow of e_msgsize.
1629 if (m->m_maxsize != 0 &&
1630 (e->e_msgsize > m->m_maxsize || e->e_msgsize < 0))
1632 e->e_flags |= EF_NO_BODY_RETN;
1633 if (bitnset(M_LOCALMAILER, to->q_mailer->m_flags))
1634 to->q_status = "5.2.3";
1636 to->q_status = "5.3.4";
1638 /* set to->q_rstatus = NULL; or to the following? */
1639 usrerrenh(to->q_status,
1640 "552 Message is too large; %ld bytes max",
1642 markfailure(e, to, NULL, EX_UNAVAILABLE, false);
1643 giveresponse(EX_UNAVAILABLE, to->q_status, m,
1644 NULL, ctladdr, xstart, e, to);
1650 /* do config file checking of compatibility */
1651 quarantine = (e->e_quarmsg != NULL);
1652 rcode = rscheck("check_compat", e->e_from.q_paddr, to->q_paddr,
1653 e, RSF_RMCOMM|RSF_COUNT, 3, NULL,
1654 e->e_id, NULL, NULL);
1657 /* do in-code checking if not discarding */
1658 if (!bitset(EF_DISCARD, e->e_flags))
1660 rcode = checkcompat(to, e);
1666 markfailure(e, to, NULL, rcode, ovr);
1667 giveresponse(rcode, to->q_status, m,
1668 NULL, ctladdr, xstart, e, to);
1671 if (!quarantine && e->e_quarmsg != NULL)
1674 ** check_compat or checkcompat() has tried
1675 ** to quarantine but that isn't supported.
1676 ** Revert the attempt.
1679 e->e_quarmsg = NULL;
1680 macdefine(&e->e_macro, A_PERM,
1681 macid("{quarantine}"), "");
1683 if (bitset(EF_DISCARD, e->e_flags))
1687 sm_dprintf("deliver: discarding recipient ");
1688 printaddr(sm_debug_file(), to, false);
1691 /* pretend the message was sent */
1692 /* XXX should we log something here? */
1693 to->q_state = QS_DISCARDED;
1696 ** Remove discard bit to prevent discard of
1697 ** future recipients. This is safe because the
1698 ** true "global discard" has been handled before
1702 e->e_flags &= ~EF_DISCARD;
1707 ** Strip quote bits from names if the mailer is dumb
1711 if (bitnset(M_STRIPQ, m->m_flags))
1718 ** Strip all leading backslashes if requested and the
1719 ** next character is alphanumerical (the latter can
1720 ** probably relaxed a bit, see RFC2821).
1723 if (bitnset(M_STRIPBACKSL, m->m_flags) && user[0] == '\\')
1724 stripbackslash(user);
1726 /* hack attack -- delivermail compatibility */
1727 if (m == ProgMailer && *user == '|')
1731 ** If an error message has already been given, don't
1732 ** bother to send to this address.
1734 ** >>>>>>>>>> This clause assumes that the local mailer
1735 ** >> NOTE >> cannot do any further aliasing; that
1736 ** >>>>>>>>>> function is subsumed by sendmail.
1739 if (!QS_IS_OK(to->q_state))
1743 ** See if this user name is "special".
1744 ** If the user name has a slash in it, assume that this
1745 ** is a file -- send it off without further ado. Note
1746 ** that this type of addresses is not processed along
1747 ** with the others, so we fudge on the To person.
1750 if (strcmp(m->m_mailer, "[FILE]") == 0)
1752 macdefine(&e->e_macro, A_PERM, 'u', user);
1754 if (p == NULL && ctladdr != NULL)
1755 p = ctladdr->q_home;
1756 macdefine(&e->e_macro, A_PERM, 'z', p);
1757 expand(m->m_argv[1], buf, sizeof(buf), e);
1758 if (strlen(buf) > 0)
1759 rcode = mailfile(buf, m, ctladdr, SFF_CREAT, e);
1762 syserr("empty filename specification for mailer %s",
1766 giveresponse(rcode, to->q_status, m, NULL,
1767 ctladdr, xstart, e, to);
1768 markfailure(e, to, NULL, rcode, true);
1772 to->q_state = QS_SENT;
1773 if (bitnset(M_LOCALMAILER, m->m_flags) &&
1774 bitset(QPINGONSUCCESS, to->q_flags))
1776 to->q_flags |= QDELIVERED;
1777 to->q_status = "2.1.5";
1778 (void) sm_io_fprintf(e->e_xfp,
1780 "%s... Successfully delivered\n",
1784 to->q_statdate = curtime();
1785 markstats(e, to, STATS_NORMAL);
1790 ** Address is verified -- add this user to mailer
1791 ** argv, and add it to the print list of recipients.
1794 /* link together the chain of recipients */
1795 to->q_tchain = tochain;
1797 e->e_to = "[CHAIN]";
1799 macdefine(&e->e_macro, A_PERM, 'u', user); /* to user */
1801 if (p == NULL && ctladdr != NULL)
1802 p = ctladdr->q_home;
1803 macdefine(&e->e_macro, A_PERM, 'z', p); /* user's home */
1805 /* set the ${dsn_notify} macro if applicable */
1806 if (bitset(QHASNOTIFY, to->q_flags))
1808 char notify[MAXLINE];
1811 if (bitset(QPINGONSUCCESS, to->q_flags))
1812 (void) sm_strlcat(notify, "SUCCESS,",
1814 if (bitset(QPINGONFAILURE, to->q_flags))
1815 (void) sm_strlcat(notify, "FAILURE,",
1817 if (bitset(QPINGONDELAY, to->q_flags))
1818 (void) sm_strlcat(notify, "DELAY,",
1821 /* Set to NEVER or drop trailing comma */
1822 if (notify[0] == '\0')
1823 (void) sm_strlcat(notify, "NEVER",
1826 notify[strlen(notify) - 1] = '\0';
1828 macdefine(&e->e_macro, A_TEMP,
1829 macid("{dsn_notify}"), notify);
1832 macdefine(&e->e_macro, A_PERM,
1833 macid("{dsn_notify}"), NULL);
1836 ** Expand out this user into argument list.
1841 expand(*mvp, buf, sizeof(buf), e);
1842 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1843 if (pvp >= &pv[MAXPV - 2])
1845 /* allow some space for trailing parms */
1851 /* see if any addresses still exist */
1852 if (tochain == NULL)
1858 /* print out messages as full list */
1860 for (to = tochain; to != NULL; to = to->q_tchain)
1861 strsize += strlen(to->q_paddr) + 1;
1862 if (strsize < TOBUFSIZE)
1863 strsize = TOBUFSIZE;
1864 if (strsize > tobufsize)
1867 tobuf = sm_pmalloc_x(strsize);
1868 tobufsize = strsize;
1872 for (to = tochain; to != NULL; to = to->q_tchain)
1874 (void) sm_strlcpyn(p, tobufsize - (p - tobuf), 2,
1878 e->e_to = tobuf + 1;
1881 ** Fill out any parameters after the $u parameter.
1886 while (*++mvp != NULL)
1888 expand(*mvp, buf, sizeof(buf), e);
1889 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1890 if (pvp >= &pv[MAXPV])
1891 syserr("554 5.3.0 deliver: pv overflow after $u for %s",
1899 ** The argument vector gets built, pipes
1900 ** are created as necessary, and we fork & exec as
1902 ** If we are running SMTP, we just need to clean up.
1905 /* XXX this seems a bit weird */
1906 if (ctladdr == NULL && m != ProgMailer && m != FileMailer &&
1907 bitset(QGOODUID, e->e_from.q_flags))
1908 ctladdr = &e->e_from;
1911 if (ConfigLevel < 2)
1912 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */
1917 sm_dprintf("openmailer:");
1918 printav(sm_debug_file(), pv);
1925 ** Deal with the special case of mail handled through an IPC
1927 ** In this case we don't actually fork. We must be
1928 ** running SMTP for this to work. We will return a
1929 ** zero pid to indicate that we are running IPC.
1930 ** We also handle a debug version that just talks to stdin/out.
1941 /* make absolutely certain 0, 1, and 2 are in use */
1942 (void) sm_snprintf(wbuf, sizeof(wbuf), "%s... openmailer(%s)",
1943 shortenstring(e->e_to, MAXSHORTSTR),
1949 /* check for 8-bit available */
1950 if (bitset(EF_HAS8BIT, e->e_flags) &&
1951 bitnset(M_7BITS, m->m_flags) &&
1952 (bitset(EF_DONT_MIME, e->e_flags) ||
1953 !(bitset(MM_MIME8BIT, MimeMode) ||
1954 (bitset(EF_IS_MIME, e->e_flags) &&
1955 bitset(MM_CVTMIME, MimeMode)))))
1957 e->e_status = "5.6.3";
1958 usrerrenh(e->e_status,
1959 "554 Cannot send 8-bit data to 7-bit destination");
1965 checkfds("before delivery");
1967 /* check for Local Person Communication -- not for mortals!!! */
1968 if (strcmp(m->m_mailer, "[LPC]") == 0)
1972 /* flush any expired connections */
1973 (void) mci_scan(NULL);
1975 /* try to get a cached connection or just a slot */
1976 mci = mci_get(m->m_name, m);
1977 if (mci->mci_host == NULL)
1978 mci->mci_host = m->m_name;
1979 CurHostName = mci->mci_host;
1980 if (mci->mci_state != MCIS_CLOSED)
1982 message("Using cached SMTP/LPC connection for %s...",
1984 mci->mci_deliveries++;
1990 mci = mci_new(e->e_rpool);
1992 mci->mci_in = smioin;
1993 mci->mci_out = smioout;
1994 mci->mci_mailer = m;
1995 mci->mci_host = m->m_name;
1998 mci->mci_state = MCIS_OPENING;
2002 mci->mci_state = MCIS_OPEN;
2004 else if (strcmp(m->m_mailer, "[IPC]") == 0)
2008 if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0')
2010 syserr("null destination for %s mailer", m->m_mailer);
2016 if (strcmp(pv[0], "FILE") == 0)
2018 curhost = CurHostName = "localhost";
2022 #endif /* NETUNIX */
2024 CurHostName = pv[1];
2026 curhost = hostsignature(m, pv[1], firstto->q_flags & QSECURE);
2029 if (curhost == NULL || curhost[0] == '\0')
2031 syserr("null host signature for %s", pv[1]);
2038 syserr("554 5.3.5 non-clever IPC");
2048 port = htons((unsigned short) atoi(pv[2]));
2051 #ifdef NO_GETSERVBYNAME
2052 syserr("Invalid port number: %s", pv[2]);
2053 #else /* NO_GETSERVBYNAME */
2054 struct servent *sp = getservbyname(pv[2], "tcp");
2057 syserr("Service %s unknown", pv[2]);
2060 #endif /* NO_GETSERVBYNAME */
2064 nummxhosts = parse_hostsignature(curhost, mxhosts, m);
2065 if (TimeOuts.to_aconnect > 0)
2066 enough = curtime() + TimeOuts.to_aconnect;
2068 while (hostnum < nummxhosts)
2072 static char hostbuf[MAXNAME + 1];
2073 bool tried_fallbacksmarthost = false;
2075 unsigned long tlsa_flags;
2081 if (*mxhosts[hostnum] == '[')
2083 endp = strchr(mxhosts[hostnum] + 1, ']');
2085 endp = strpbrk(endp + 1, ":,");
2088 endp = strpbrk(mxhosts[hostnum], ":,");
2089 #else /* NETINET6 */
2090 endp = strpbrk(mxhosts[hostnum], ":,");
2091 #endif /* NETINET6 */
2098 if (hostnum == 1 && skip_back != NULL)
2101 ** Coattail piggybacking is no longer an
2102 ** option with the mail host next to be tried
2103 ** no longer the lowest MX preference
2104 ** (hostnum == 1 meaning we're on the second
2105 ** preference). We do not try to coattail
2106 ** piggyback more than the first MX preference.
2107 ** Revert 'tochain' to last location for
2108 ** coincidental piggybacking. This works this
2109 ** easily because the q_tchain kept getting
2110 ** added to the top of the linked list.
2113 tochain = skip_back;
2116 if (*mxhosts[hostnum] == '\0')
2118 syserr("deliver: null host name in signature");
2124 (void) sm_strlcpy(hostbuf, mxhosts[hostnum],
2134 /* see if we already know that this host is fried */
2135 CurHostName = hostbuf;
2136 mci = mci_get(hostbuf, m);
2137 if (mci->mci_state != MCIS_CLOSED)
2143 sm_dprintf("openmailer: ");
2144 mci_dump(sm_debug_file(), mci, false);
2146 CurHostName = mci->mci_host;
2147 if (bitnset(M_LMTP, m->m_flags))
2149 else if (bitset(MCIF_ESMTP, mci->mci_flags))
2153 message("Using cached %sMTP connection to %s via %s...",
2154 type, hostbuf, m->m_name);
2155 mci->mci_deliveries++;
2158 mci->mci_mailer = m;
2162 (void) GETTLSA(hostbuf, &ste, m->m_port);
2164 /* XXX: check expiration! */
2165 if (ste != NULL && TLSA_RR_TEMPFAIL(ste->s_tlsa))
2168 sm_dprintf("skip: host=%s, TLSA_RR_lookup=%d\n"
2170 , ste->s_tlsa->dane_tlsa_dnsrc);
2172 tlsa_flags |= TLSAFLTEMP;
2176 if (mci->mci_exitstat != EX_OK)
2178 if (mci->mci_exitstat == EX_TEMPFAIL)
2181 /* Try FallbackSmartHost? */
2182 if (should_try_fbsh(e, &tried_fallbacksmarthost,
2183 hostbuf, sizeof(hostbuf),
2190 if (mci_lock_host(mci) != EX_OK)
2192 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2197 /* try the connection */
2198 sm_setproctitle(true, e, "%s %s: %s",
2200 hostbuf, "user open");
2202 if (mux_path != NULL)
2204 message("Connecting to %s via %s...",
2205 mux_path, m->m_name);
2206 i = makeconnection_ds((char *) mux_path, mci);
2209 #endif /* NETUNIX */
2212 message("Connecting to %s via %s...",
2213 hostbuf, m->m_name);
2215 message("Connecting to %s port %d via %s...",
2216 hostbuf, ntohs(port),
2219 tlsa_flags |= (ste != NULL) ? Dane : DANE_NEVER;
2220 dane_vrfy_ctx.dane_vrfy_chk = tlsa_flags;
2221 dane_vrfy_ctx.dane_vrfy_port = m->m_port;
2223 sm_dprintf("makeconnection: before: chk=%d, mode=%lX\n", dane_vrfy_ctx.dane_vrfy_chk, tlsa_flags);
2225 i = makeconnection(hostbuf, port, mci, e,
2233 sm_dprintf("makeconnection: after: chk=%d, mode=%lX\n", dane_vrfy_ctx.dane_vrfy_chk, tlsa_flags);
2234 if (dane_vrfy_ctx.dane_vrfy_chk != DANE_ALWAYS)
2235 dane_vrfy_ctx.dane_vrfy_chk = DANEMODE(tlsa_flags);
2236 if (EX_TEMPFAIL == i &&
2237 ((tlsa_flags & (TLSAFLTEMP|DANE_SECURE)) ==
2238 (TLSAFLTEMP|DANE_SECURE)))
2240 (void) sm_strlcpy(SmtpError,
2244 SM_SET_H_ERRNO(TRY_AGAIN);
2249 mci->mci_errno = errno;
2250 mci->mci_lastuse = curtime();
2251 mci->mci_deliveries = 0;
2252 mci->mci_exitstat = i;
2253 mci_clr_extensions(mci);
2255 mci->mci_herrno = h_errno;
2259 ** Have we tried long enough to get a connection?
2260 ** If yes, skip to the fallback MX hosts
2264 if (enough > 0 && mci->mci_lastuse >= enough)
2268 extern int NumFallbackMXHosts;
2270 const int NumFallbackMXHosts = 0;
2273 if (hostnum < nummxhosts && LogLevel > 9)
2274 sm_syslog(LOG_INFO, e->e_id,
2275 "Timeout.to_aconnect occurred before exhausting all addresses");
2277 /* turn off timeout if fallback available */
2278 if (NumFallbackMXHosts > 0)
2281 /* skip to a fallback MX host */
2282 h = nummxhosts - NumFallbackMXHosts;
2289 markstats(e, firstto, STATS_CONNECT);
2290 mci->mci_state = MCIS_OPENING;
2292 if (TrafficLogFile != NULL)
2293 (void) sm_io_fprintf(TrafficLogFile,
2295 "%05d === CONNECT %s\n",
2302 /* Try FallbackSmartHost? */
2303 if (should_try_fbsh(e, &tried_fallbacksmarthost,
2304 hostbuf, sizeof(hostbuf), i))
2308 sm_dprintf("openmailer: makeconnection => stat=%d, errno=%d\n",
2310 if (i == EX_TEMPFAIL)
2312 mci_unlock_host(mci);
2315 /* enter status of this host */
2318 /* should print some message here for -v mode */
2322 syserr("deliver: no host name");
2323 rcode = EX_SOFTWARE;
2330 /* flush any expired connections */
2331 (void) mci_scan(NULL);
2334 if (bitnset(M_LMTP, m->m_flags))
2336 /* try to get a cached connection */
2337 mci = mci_get(m->m_name, m);
2338 if (mci->mci_host == NULL)
2339 mci->mci_host = m->m_name;
2340 CurHostName = mci->mci_host;
2341 if (mci->mci_state != MCIS_CLOSED)
2343 message("Using cached LMTP connection for %s...",
2345 mci->mci_deliveries++;
2350 /* announce the connection to verbose listeners */
2351 if (host == NULL || host[0] == '\0')
2352 message("Connecting to %s...", m->m_name);
2354 message("Connecting to %s via %s...", host, m->m_name);
2355 if (TrafficLogFile != NULL)
2359 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
2360 "%05d === EXEC", (int) CurrentPid);
2361 for (av = pv; *av != NULL; av++)
2362 (void) sm_io_fprintf(TrafficLogFile,
2363 SM_TIME_DEFAULT, " %s",
2365 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
2370 checkfd012("before creating mail pipe");
2373 /* create a pipe to shove the mail through */
2374 if (pipe(mpvect) < 0)
2376 syserr("%s... openmailer(%s): pipe (to mailer)",
2377 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
2379 sm_dprintf("openmailer: NULL\n");
2385 /* make sure we didn't get one of the standard I/O files */
2386 if (mpvect[0] < 3 || mpvect[1] < 3)
2388 syserr("%s... openmailer(%s): bogus mpvect %d %d",
2389 shortenstring(e->e_to, MAXSHORTSTR), m->m_name,
2390 mpvect[0], mpvect[1]);
2393 sm_dprintf("openmailer: NULL\n");
2398 /* make sure system call isn't dead meat */
2399 checkfdopen(mpvect[0], "mpvect[0]");
2400 checkfdopen(mpvect[1], "mpvect[1]");
2401 if (mpvect[0] == mpvect[1] ||
2402 (e->e_lockfp != NULL &&
2403 (mpvect[0] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD,
2405 mpvect[1] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD,
2408 if (e->e_lockfp == NULL)
2409 syserr("%s... openmailer(%s): overlapping mpvect %d %d",
2410 shortenstring(e->e_to, MAXSHORTSTR),
2411 m->m_name, mpvect[0], mpvect[1]);
2413 syserr("%s... openmailer(%s): overlapping mpvect %d %d, lockfp = %d",
2414 shortenstring(e->e_to, MAXSHORTSTR),
2415 m->m_name, mpvect[0], mpvect[1],
2416 sm_io_getinfo(e->e_lockfp,
2417 SM_IO_WHAT_FD, NULL));
2421 /* create a return pipe */
2422 if (pipe(rpvect) < 0)
2424 syserr("%s... openmailer(%s): pipe (from mailer)",
2425 shortenstring(e->e_to, MAXSHORTSTR),
2427 (void) close(mpvect[0]);
2428 (void) close(mpvect[1]);
2430 sm_dprintf("openmailer: NULL\n");
2435 checkfdopen(rpvect[0], "rpvect[0]");
2436 checkfdopen(rpvect[1], "rpvect[1]");
2440 ** Actually fork the mailer process.
2441 ** DOFORK is clever about retrying.
2443 ** Dispose of SIGCHLD signal catchers that may be laying
2444 ** around so that endmailer will get it.
2447 if (e->e_xfp != NULL) /* for debugging */
2448 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
2449 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2450 (void) sm_signal(SIGCHLD, SIG_DFL);
2454 /* pid is set by DOFORK */
2459 syserr("%s... openmailer(%s): cannot fork",
2460 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
2461 (void) close(mpvect[0]);
2462 (void) close(mpvect[1]);
2463 (void) close(rpvect[0]);
2464 (void) close(rpvect[1]);
2466 sm_dprintf("openmailer: NULL\n");
2474 int new_euid = NO_UID;
2475 int new_ruid = NO_UID;
2476 int new_gid = NO_GID;
2479 extern int DtableSize;
2481 CurrentPid = getpid();
2483 /* clear the events to turn off SIGALRMs */
2486 /* Reset global flags */
2487 RestartRequest = NULL;
2488 RestartWorkGroup = false;
2489 ShutdownRequest = NULL;
2492 if (e->e_lockfp != NULL)
2493 (void) close(sm_io_getinfo(e->e_lockfp,
2497 /* child -- set up input & exec mailer */
2498 (void) sm_signal(SIGALRM, sm_signal_noop);
2499 (void) sm_signal(SIGCHLD, SIG_DFL);
2500 (void) sm_signal(SIGHUP, SIG_IGN);
2501 (void) sm_signal(SIGINT, SIG_IGN);
2502 (void) sm_signal(SIGTERM, SIG_DFL);
2504 (void) sm_signal(SIGUSR1, sm_signal_noop);
2507 if (m != FileMailer || stat(tochain->q_user, &stb) < 0)
2510 #if HASSETUSERCONTEXT
2512 ** Set user resources.
2515 if (contextaddr != NULL)
2520 if (contextaddr->q_ruser != NULL)
2521 pwd = sm_getpwnam(contextaddr->q_ruser);
2523 pwd = sm_getpwnam(contextaddr->q_user);
2524 sucflags = LOGIN_SETRESOURCES|LOGIN_SETPRIORITY;
2525 # ifdef LOGIN_SETCPUMASK
2526 sucflags |= LOGIN_SETCPUMASK;
2528 # ifdef LOGIN_SETLOGINCLASS
2529 sucflags |= LOGIN_SETLOGINCLASS;
2531 # ifdef LOGIN_SETMAC
2532 sucflags |= LOGIN_SETMAC;
2535 setusercontext(NULL, pwd, pwd->pw_uid,
2539 syserr("openmailer: setusercontext() failed");
2543 #endif /* HASSETUSERCONTEXT */
2546 /* tweak niceness */
2548 (void) nice(m->m_nice);
2549 #endif /* HASNICE */
2551 /* reset group id */
2552 if (bitnset(M_SPECIFIC_UID, m->m_flags))
2554 if (m->m_gid == NO_GID)
2559 else if (bitset(S_ISGID, stb.st_mode))
2560 new_gid = stb.st_gid;
2561 else if (ctladdr != NULL && ctladdr->q_gid != 0)
2563 if (!DontInitGroups)
2565 user = ctladdr->q_ruser;
2567 user = ctladdr->q_user;
2569 if (initgroups(user,
2570 ctladdr->q_gid) == -1
2573 syserr("openmailer: initgroups(%s, %ld) failed",
2574 user, (long) ctladdr->q_gid);
2582 gidset[0] = ctladdr->q_gid;
2583 if (setgroups(1, gidset) == -1
2586 syserr("openmailer: setgroups() failed");
2590 new_gid = ctladdr->q_gid;
2594 if (!DontInitGroups)
2597 if (initgroups(DefUser, DefGid) == -1 &&
2600 syserr("openmailer: initgroups(%s, %ld) failed",
2601 DefUser, (long) DefGid);
2610 if (setgroups(1, gidset) == -1
2613 syserr("openmailer: setgroups() failed");
2617 if (m->m_gid == NO_GID)
2622 if (new_gid != NO_GID)
2624 if (RunAsUid != 0 &&
2625 bitnset(M_SPECIFIC_UID, m->m_flags) &&
2626 new_gid != getgid() &&
2627 new_gid != getegid())
2629 /* Only root can change the gid */
2630 syserr("openmailer: insufficient privileges to change gid, RunAsUid=%ld, new_gid=%ld, gid=%ld, egid=%ld",
2631 (long) RunAsUid, (long) new_gid,
2632 (long) getgid(), (long) getegid());
2636 if (setgid(new_gid) < 0 && suidwarn)
2638 syserr("openmailer: setgid(%ld) failed",
2644 /* change root to some "safe" directory */
2645 if (m->m_rootdir != NULL)
2647 expand(m->m_rootdir, cbuf, sizeof(cbuf), e);
2649 sm_dprintf("openmailer: chroot %s\n",
2651 if (chroot(cbuf) < 0)
2653 syserr("openmailer: Cannot chroot(%s)",
2659 syserr("openmailer: cannot chdir(/)");
2666 sm_mbdb_terminate();
2667 if (bitnset(M_SPECIFIC_UID, m->m_flags))
2669 if (m->m_uid == NO_UID)
2670 new_euid = RunAsUid;
2672 new_euid = m->m_uid;
2675 ** Undo the effects of the uid change in main
2676 ** for signal handling. The real uid may
2677 ** be used by mailer in adding a "From "
2681 if (RealUid != 0 && RealUid != getuid())
2683 #if MAILER_SETUID_METHOD == USE_SETEUID
2685 if (setreuid(RealUid, geteuid()) < 0)
2687 syserr("openmailer: setreuid(%d, %d) failed",
2688 (int) RealUid, (int) geteuid());
2691 # endif /* HASSETREUID */
2692 #endif /* MAILER_SETUID_METHOD == USE_SETEUID */
2693 #if MAILER_SETUID_METHOD == USE_SETREUID
2698 else if (bitset(S_ISUID, stb.st_mode))
2699 new_ruid = stb.st_uid;
2700 else if (ctladdr != NULL && ctladdr->q_uid != 0)
2701 new_ruid = ctladdr->q_uid;
2702 else if (m->m_uid != NO_UID)
2703 new_ruid = m->m_uid;
2707 #if _FFR_USE_SETLOGIN
2708 /* run disconnected from terminal and set login name */
2709 if (setsid() >= 0 &&
2710 ctladdr != NULL && ctladdr->q_uid != 0 &&
2711 new_euid == ctladdr->q_uid)
2715 pwd = sm_getpwuid(ctladdr->q_uid);
2716 if (pwd != NULL && suidwarn)
2717 (void) setlogin(pwd->pw_name);
2720 #endif /* _FFR_USE_SETLOGIN */
2722 if (new_euid != NO_UID)
2724 if (RunAsUid != 0 && new_euid != RunAsUid)
2726 /* Only root can change the uid */
2727 syserr("openmailer: insufficient privileges to change uid, new_euid=%ld, RunAsUid=%ld",
2728 (long) new_euid, (long) RunAsUid);
2732 vendor_set_uid(new_euid);
2733 #if MAILER_SETUID_METHOD == USE_SETEUID
2734 if (seteuid(new_euid) < 0 && suidwarn)
2736 syserr("openmailer: seteuid(%ld) failed",
2740 #endif /* MAILER_SETUID_METHOD == USE_SETEUID */
2741 #if MAILER_SETUID_METHOD == USE_SETREUID
2742 if (setreuid(new_ruid, new_euid) < 0 && suidwarn)
2744 syserr("openmailer: setreuid(%ld, %ld) failed",
2745 (long) new_ruid, (long) new_euid);
2748 #endif /* MAILER_SETUID_METHOD == USE_SETREUID */
2749 #if MAILER_SETUID_METHOD == USE_SETUID
2750 if (new_euid != geteuid() && setuid(new_euid) < 0 && suidwarn)
2752 syserr("openmailer: setuid(%ld) failed",
2756 #endif /* MAILER_SETUID_METHOD == USE_SETUID */
2758 else if (new_ruid != NO_UID)
2760 vendor_set_uid(new_ruid);
2761 if (setuid(new_ruid) < 0 && suidwarn)
2763 syserr("openmailer: setuid(%ld) failed",
2770 sm_dprintf("openmailer: running as r/euid=%ld/%ld, r/egid=%ld/%ld\n",
2771 (long) getuid(), (long) geteuid(),
2772 (long) getgid(), (long) getegid());
2774 /* move into some "safe" directory */
2775 if (m->m_execdir != NULL)
2779 for (p = m->m_execdir; p != NULL; p = q)
2784 expand(p, cbuf, sizeof(cbuf), e);
2788 sm_dprintf("openmailer: trydir %s\n",
2790 if (cbuf[0] != '\0' &&
2796 /* Check safety of program to be run */
2797 sff = SFF_ROOTOK|SFF_EXECOK;
2798 if (!bitnset(DBS_RUNWRITABLEPROGRAM,
2800 sff |= SFF_NOGWFILES|SFF_NOWWFILES;
2801 if (bitnset(DBS_RUNPROGRAMINUNSAFEDIRPATH,
2803 sff |= SFF_NOPATHCHECK;
2805 sff |= SFF_SAFEDIRPATH;
2806 ret = safefile(m->m_mailer, getuid(), getgid(),
2807 user, sff, 0, NULL);
2809 sm_syslog(LOG_INFO, e->e_id,
2810 "Warning: program %s unsafe: %s",
2811 m->m_mailer, sm_errstring(ret));
2813 /* arrange to filter std & diag output of command */
2814 (void) close(rpvect[0]);
2815 if (dup2(rpvect[1], STDOUT_FILENO) < 0)
2817 syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
2818 shortenstring(e->e_to, MAXSHORTSTR),
2819 m->m_name, rpvect[1]);
2822 (void) close(rpvect[1]);
2824 if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
2826 syserr("%s... openmailer(%s): cannot dup stdout for stderr",
2827 shortenstring(e->e_to, MAXSHORTSTR),
2832 /* arrange to get standard input */
2833 (void) close(mpvect[1]);
2834 if (dup2(mpvect[0], STDIN_FILENO) < 0)
2836 syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
2837 shortenstring(e->e_to, MAXSHORTSTR),
2838 m->m_name, mpvect[0]);
2841 (void) close(mpvect[0]);
2843 /* arrange for all the files to be closed */
2844 sm_close_on_exec(STDERR_FILENO + 1, DtableSize);
2846 #if !_FFR_USE_SETLOGIN
2847 /* run disconnected from terminal */
2851 /* try to execute the mailer */
2852 (void) execve(m->m_mailer, (ARGV_T) pv,
2853 (ARGV_T) UserEnviron);
2855 syserr("Cannot exec %s", m->m_mailer);
2856 if (bitnset(M_LOCALMAILER, m->m_flags) ||
2857 transienterror(save_errno))
2859 _exit(EX_UNAVAILABLE);
2863 ** Set up return value.
2871 ** Allocate from general heap, not
2872 ** envelope rpool, because this mci
2873 ** is going to be cached.
2876 mci = mci_new(NULL);
2881 ** Prevent a storage leak by allocating
2882 ** this from the envelope rpool.
2885 mci = mci_new(e->e_rpool);
2888 mci->mci_mailer = m;
2891 mci->mci_state = MCIS_OPENING;
2896 mci->mci_state = MCIS_OPEN;
2899 (void) close(mpvect[0]);
2900 mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2901 (void *) &(mpvect[1]), SM_IO_WRONLY_B,
2903 if (mci->mci_out == NULL)
2905 syserr("deliver: cannot create mailer output channel, fd=%d",
2907 (void) close(mpvect[1]);
2908 (void) close(rpvect[0]);
2909 (void) close(rpvect[1]);
2914 (void) close(rpvect[1]);
2915 mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2916 (void *) &(rpvect[0]), SM_IO_RDONLY_B,
2918 if (mci->mci_in == NULL)
2920 syserr("deliver: cannot create mailer input channel, fd=%d",
2922 (void) close(rpvect[0]);
2923 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
2924 mci->mci_out = NULL;
2931 ** If we are in SMTP opening state, send initial protocol.
2934 if (bitnset(M_7BITS, m->m_flags) &&
2935 (!clever || mci->mci_state == MCIS_OPENING))
2936 mci->mci_flags |= MCIF_7BIT;
2937 if (clever && mci->mci_state != MCIS_CLOSED)
2939 #if STARTTLS || SASL
2941 extern SOCKADDR CurHostAddr;
2942 #endif /* STARTTLS || SASL */
2945 # define DONE_AUTH(f) bitset(MCIF_AUTHACT, f)
2948 # define DONE_STARTTLS(f) bitset(MCIF_TLSACT, f)
2950 #define ONLY_HELO(f) bitset(MCIF_ONLY_EHLO, f)
2951 #define SET_HELO(f) f |= MCIF_ONLY_EHLO
2952 #define CLR_HELO(f) f &= ~MCIF_ONLY_EHLO
2954 #if STARTTLS || SASL
2955 /* don't use CurHostName, it is changed in many places */
2956 if (mci->mci_host != NULL)
2958 srvname = mci->mci_host;
2959 RM_TRAIL_DOT(srvname);
2961 else if (mci->mci_mailer != NULL)
2963 srvname = mci->mci_mailer->m_name;
2972 /* don't set {server_name} to NULL or "": see getauth() */
2973 macdefine(&mci->mci_macro, A_TEMP, macid("{server_name}"),
2976 /* CurHostAddr is set by makeconnection() and mci_get() */
2977 if (CurHostAddr.sa.sa_family != 0)
2979 macdefine(&mci->mci_macro, A_TEMP,
2980 macid("{server_addr}"),
2981 anynet_ntoa(&CurHostAddr));
2983 else if (mci->mci_mailer != NULL)
2985 /* mailer name is unique, use it as address */
2986 macdefine(&mci->mci_macro, A_PERM,
2987 macid("{server_addr}"),
2988 mci->mci_mailer->m_name);
2992 /* don't set it to NULL or "": see getauth() */
2993 macdefine(&mci->mci_macro, A_PERM,
2994 macid("{server_addr}"), "0");
2998 SM_FREE(dane_vrfy_ctx.dane_vrfy_host);
2999 SM_FREE(dane_vrfy_ctx.dane_vrfy_sni);
3000 dane_vrfy_ctx.dane_vrfy_fp[0] = '\0';
3001 if (ste != NULL && ste->s_tlsa != NULL &&
3002 ste->s_tlsa->dane_tlsa_sni != NULL)
3003 dane_vrfy_ctx.dane_vrfy_sni = sm_strdup(ste->s_tlsa->dane_tlsa_sni);
3004 dane_vrfy_ctx.dane_vrfy_host = sm_strdup(srvname);
3007 /* undo change of srvname (mci->mci_host) */
3008 FIX_TRAIL_DOT(srvname);
3010 reconnect: /* after switching to an encrypted connection */
3012 if (DONE_STARTTLS(mci->mci_flags))
3014 /* use a "reset" function? */
3015 SM_FREE(dane_vrfy_ctx.dane_vrfy_host);
3016 SM_FREE(dane_vrfy_ctx.dane_vrfy_sni);
3017 dane_vrfy_ctx.dane_vrfy_fp[0] = '\0';
3018 dane_vrfy_ctx.dane_vrfy_res = 0;
3022 #endif /* STARTTLS || SASL */
3024 /* set the current connection information */
3027 mci->mci_saslcap = NULL;
3029 smtpinit(m, mci, e, ONLY_HELO(mci->mci_flags));
3030 CLR_HELO(mci->mci_flags);
3032 if (IS_DLVR_RETURN(e))
3035 ** Check whether other side can deliver e-mail
3039 if (!bitset(MCIF_DLVR_BY, mci->mci_flags))
3041 e->e_status = "5.4.7";
3042 usrerrenh(e->e_status,
3043 "554 Server does not support Deliver By");
3044 rcode = EX_UNAVAILABLE;
3047 if (e->e_deliver_by > 0 &&
3048 e->e_deliver_by - (curtime() - e->e_ctime) <
3051 e->e_status = "5.4.7";
3052 usrerrenh(e->e_status,
3053 "554 Message can't be delivered in time; %ld < %ld",
3054 e->e_deliver_by - (long) (curtime() -
3057 rcode = EX_UNAVAILABLE;
3063 /* first TLS then AUTH to provide a security layer */
3064 if (mci->mci_state != MCIS_CLOSED &&
3065 !DONE_STARTTLS(mci->mci_flags))
3069 bool saveQuickAbort = QuickAbort;
3070 bool saveSuprErrs = SuprErrs;
3074 usetls = bitset(MCIF_TLS, mci->mci_flags);
3076 usetls = !iscltflgset(e, D_NOTLS);
3078 usetls = tlsstate == 0;
3080 host = macvalue(macid("{server_name}"), e);
3086 if (rscheck("try_tls", host, NULL, e,
3087 RSF_RMCOMM, 7, host, NOQID, NULL,
3089 || Errors > olderrors)
3093 SuprErrs = saveSuprErrs;
3094 QuickAbort = saveQuickAbort;
3099 if ((rcode = starttls(m, mci, e
3105 /* start again without STARTTLS */
3106 mci->mci_flags |= MCIF_TLSACT;
3113 ** TLS negotiation failed, what to do?
3114 ** fall back to unencrypted connection
3115 ** or abort? How to decide?
3116 ** set a macro and call a ruleset.
3119 mci->mci_flags &= ~MCIF_TLS;
3134 case EX_UNAVAILABLE:
3138 /* everything else is a failure */
3141 rcode = EX_TEMPFAIL;
3143 macdefine(&e->e_macro, A_PERM,
3144 macid("{verify}"), s);
3149 p = tlsstate == 0 ? "NONE": "CLEAR";
3152 ** TLSA found but STARTTLS not offered?
3153 ** What is the best way to "fail"?
3154 ** XXX: check expiration!
3157 if (!bitset(MCIF_TLS, mci->mci_flags) &&
3159 ste->s_tlsa != NULL &&
3160 ste->s_tlsa->dane_tlsa_n > 0)
3163 sm_syslog(LOG_NOTICE, NOQID,
3164 "STARTTLS=client, relay=%.100s, warning=DANE configured in DNS but no STARTTLS available",
3166 /* XXX include TLSA RR from DNS? */
3171 macdefine(&e->e_macro, A_PERM,
3172 macid("{verify}"), p);
3179 ** rcode == EX_SOFTWARE is special:
3180 ** the TLS negotiation failed
3181 ** we have to drop the connection no matter what
3182 ** However, we call tls_server to give it the chance
3183 ** to log the problem and return an appropriate
3187 if (rscheck("tls_server",
3188 macvalue(macid("{verify}"), e),
3189 NULL, e, RSF_RMCOMM|RSF_COUNT, 5,
3190 host, NOQID, NULL, NULL) != EX_OK ||
3191 Errors > olderrors ||
3192 rcode == EX_SOFTWARE)
3194 char enhsc[ENHSCLEN];
3195 extern char MsgBuf[];
3197 if (ISSMTPCODE(MsgBuf) &&
3198 extenhsc(MsgBuf + 4, ' ', enhsc) > 0)
3200 p = sm_rpool_strdup_x(e->e_rpool,
3205 p = "403 4.7.0 server not authenticated.";
3206 (void) sm_strlcpy(enhsc, "4.7.0",
3209 SuprErrs = saveSuprErrs;
3210 QuickAbort = saveQuickAbort;
3212 if (rcode == EX_SOFTWARE)
3214 /* drop the connection */
3215 mci->mci_state = MCIS_QUITING;
3216 if (mci->mci_in != NULL)
3218 (void) sm_io_close(mci->mci_in,
3222 mci->mci_flags &= ~MCIF_TLSACT;
3223 (void) endmailer(mci, e, pv);
3225 if ((TLSFallbacktoClear ||
3226 SM_TLSI_IS(&(mci->mci_tlsi),
3228 !SM_TLSI_IS(&(mci->mci_tlsi),
3231 && dane_vrfy_ctx.dane_vrfy_chk !=
3241 /* abort transfer */
3242 smtpquit(m, mci, e);
3245 /* avoid bogus error msg */
3248 /* temp or permanent failure? */
3249 rcode = (*p == '4') ? EX_TEMPFAIL
3251 mci_setstat(mci, rcode, enhsc, p);
3254 ** hack to get the error message into
3255 ** the envelope (done in giveresponse())
3258 (void) sm_strlcpy(SmtpError, p,
3261 else if (mci->mci_state == MCIS_CLOSED)
3263 /* connection close caused by 421 */
3265 rcode = EX_TEMPFAIL;
3266 mci_setstat(mci, rcode, NULL, "421");
3271 QuickAbort = saveQuickAbort;
3272 SuprErrs = saveSuprErrs;
3273 if (DONE_STARTTLS(mci->mci_flags) &&
3274 mci->mci_state != MCIS_CLOSED)
3276 SET_HELO(mci->mci_flags);
3277 mci_clr_extensions(mci);
3284 sm_syslog(LOG_DEBUG, NOQID,
3285 "STARTTLS=client, relay=%.100s, tlsstate=%d, status=trying_again",
3286 mci->mci_host, tlsstate);
3287 mci_dump(NULL, mci, true);
3292 ** Fake the status so a new connection is
3293 ** tried, otherwise the TLS error will
3294 ** "persist" during this delivery attempt.
3299 mci_setstat(mci, rcode, NULL, NULL);
3303 #endif /* STARTTLS */
3305 /* if other server supports authentication let's authenticate */
3306 if (mci->mci_state != MCIS_CLOSED &&
3307 mci->mci_saslcap != NULL &&
3308 !DONE_AUTH(mci->mci_flags) && !iscltflgset(e, D_NOAUTH))
3310 /* Should we require some minimum authentication? */
3311 if ((ret = smtpauth(m, mci, e)) == EX_OK)
3314 sasl_ssf_t *ssf = NULL;
3316 /* Get security strength (features) */
3317 result = sasl_getprop(mci->mci_conn, SASL_SSF,
3319 (const void **) &ssf);
3326 sm_syslog(LOG_INFO, NOQID,
3327 "AUTH=client, relay=%.100s, mech=%.16s, bits=%d",
3329 macvalue(macid("{auth_type}"), e),
3330 result == SASL_OK ? *ssf : 0);
3333 ** Only switch to encrypted connection
3334 ** if a security layer has been negotiated
3337 if (result == SASL_OK && *ssf > 0)
3342 ** Convert I/O layer to use SASL.
3343 ** If the call fails, the connection
3347 tmo = DATA_PROGRESS_TIMEOUT * 1000;
3348 if (sfdcsasl(&mci->mci_in,
3350 mci->mci_conn, tmo) == 0)
3352 mci_clr_extensions(mci);
3353 mci->mci_flags |= MCIF_AUTHACT|
3357 syserr("AUTH TLS switch failed in client");
3360 mci->mci_flags |= MCIF_AUTHACT;
3363 else if (ret == EX_TEMPFAIL)
3366 sm_syslog(LOG_ERR, NOQID,
3367 "AUTH=client, relay=%.100s, temporary failure, connection abort",
3369 smtpquit(m, mci, e);
3371 /* avoid bogus error msg */
3373 rcode = EX_TEMPFAIL;
3374 mci_setstat(mci, rcode, "4.3.0", p);
3377 ** hack to get the error message into
3378 ** the envelope (done in giveresponse())
3381 (void) sm_strlcpy(SmtpError,
3382 "Temporary AUTH failure",
3390 /* clear out per-message flags from connection structure */
3391 mci->mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
3393 if (bitset(EF_HAS8BIT, e->e_flags) &&
3394 !bitset(EF_DONT_MIME, e->e_flags) &&
3395 bitnset(M_7BITS, m->m_flags))
3396 mci->mci_flags |= MCIF_CVT8TO7;
3399 if (bitnset(M_MAKE8BIT, m->m_flags) &&
3400 !bitset(MCIF_7BIT, mci->mci_flags) &&
3401 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
3402 (sm_strcasecmp(p, "quoted-printable") == 0 ||
3403 sm_strcasecmp(p, "base64") == 0) &&
3404 (p = hvalue("Content-Type", e->e_header)) != NULL)
3406 /* may want to convert 7 -> 8 */
3407 /* XXX should really parse it here -- and use a class XXX */
3408 if (sm_strncasecmp(p, "text/plain", 10) == 0 &&
3409 (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
3410 mci->mci_flags |= MCIF_CVT7TO8;
3412 #endif /* MIME7TO8 */
3416 sm_dprintf("openmailer: ");
3417 mci_dump(sm_debug_file(), mci, false);
3420 #if _FFR_CLIENT_SIZE
3422 ** See if we know the maximum size and
3423 ** abort if the message is too big.
3425 ** NOTE: _FFR_CLIENT_SIZE is untested.
3428 if (bitset(MCIF_SIZE, mci->mci_flags) &&
3429 mci->mci_maxsize > 0 &&
3430 e->e_msgsize > mci->mci_maxsize)
3432 e->e_flags |= EF_NO_BODY_RETN;
3433 if (bitnset(M_LOCALMAILER, m->m_flags))
3434 e->e_status = "5.2.3";
3436 e->e_status = "5.3.4";
3438 usrerrenh(e->e_status,
3439 "552 Message is too large; %ld bytes max",
3443 /* Need an e_message for error */
3444 (void) sm_snprintf(SmtpError, sizeof(SmtpError),
3445 "Message is too large; %ld bytes max",
3449 #endif /* _FFR_CLIENT_SIZE */
3451 if (mci->mci_state != MCIS_OPEN)
3453 /* couldn't open the mailer */
3454 rcode = mci->mci_exitstat;
3455 errno = mci->mci_errno;
3456 SM_SET_H_ERRNO(mci->mci_herrno);
3459 /* shouldn't happen */
3460 syserr("554 5.3.5 deliver: mci=%lx rcode=%d errno=%d state=%d sig=%s",
3461 (unsigned long) mci, rcode, errno,
3462 mci->mci_state, firstsig);
3463 mci_dump_all(smioout, true);
3464 rcode = EX_SOFTWARE;
3466 else if (nummxhosts > hostnum)
3468 /* try next MX site */
3477 ** Format and send message.
3482 ok = putfromline(mci, e);
3484 ok = (*e->e_puthdr)(mci, e->e_header, e, M87F_OUTER);
3486 ok = (*e->e_putbody)(mci, e, NULL);
3487 if (ok && bitset(MCIF_INLONGLINE, mci->mci_flags))
3488 ok = putline("", mci);
3491 ** Ignore an I/O error that was caused by EPIPE.
3492 ** Some broken mailers don't read the entire body
3493 ** but just exit() thus causing an I/O error.
3496 if (!ok && (sm_io_error(mci->mci_out) && errno == EPIPE))
3499 /* (always) get the exit status */
3500 rcode = endmailer(mci, e, pv);
3502 rcode = EX_TEMPFAIL;
3503 if (rcode == EX_TEMPFAIL && SmtpError[0] == '\0')
3506 ** Need an e_message for mailq display.
3507 ** We set SmtpError as
3510 (void) sm_snprintf(SmtpError, sizeof(SmtpError),
3511 "%s mailer (%s) exited with EX_TEMPFAIL",
3512 m->m_name, m->m_mailer);
3518 ** Send the MAIL FROM: protocol
3521 /* XXX this isn't pipelined... */
3522 rcode = smtpmailfrom(m, mci, e);
3527 ADDRESS *volatile pchain;
3530 /* send the recipient list */
3532 mci->mci_retryrcpt = false;
3533 mci->mci_tolist = tobuf;
3536 mci->mci_nextaddr = NULL;
3539 for (to = tochain; to != NULL; to = to->q_tchain)
3541 if (!QS_IS_UNMARKED(to->q_state))
3544 /* mark recipient state as "ok so far" */
3545 to->q_state = QS_OK;
3546 e->e_to = to->q_paddr;
3548 i = rscheck("tls_rcpt", to->q_user, NULL, e,
3549 RSF_RMCOMM|RSF_COUNT, 3,
3550 mci->mci_host, e->e_id, NULL, NULL);
3553 markfailure(e, to, mci, i, false);
3554 giveresponse(i, to->q_status, m, mci,
3555 ctladdr, xstart, e, to);
3556 if (i == EX_TEMPFAIL)
3558 mci->mci_retryrcpt = true;
3559 to->q_state = QS_RETRY;
3563 #endif /* STARTTLS */
3565 i = smtprcpt(to, m, mci, e, ctladdr, xstart);
3568 bitset(MCIF_PIPELINED, mci->mci_flags))
3571 ** Add new element to list of
3572 ** recipients for pipelining.
3575 to->q_pchain = NULL;
3576 if (mci->mci_nextaddr == NULL)
3577 mci->mci_nextaddr = to;
3582 pchain->q_pchain = to;
3583 pchain = pchain->q_pchain;
3586 #endif /* PIPELINING */
3589 markfailure(e, to, mci, i, false);
3590 giveresponse(i, to->q_status, m, mci,
3591 ctladdr, xstart, e, to);
3592 if (i == EX_TEMPFAIL)
3593 to->q_state = QS_RETRY;
3597 /* No recipients in list and no missing responses? */
3598 if (tobuf[0] == '\0'
3600 && bitset(MCIF_PIPELINED, mci->mci_flags)
3601 && mci->mci_nextaddr == NULL
3607 if (bitset(MCIF_CACHED, mci->mci_flags))
3608 smtprset(m, mci, e);
3612 e->e_to = tobuf + 1;
3613 rcode = smtpdata(m, mci, e, ctladdr, xstart);
3616 if (rcode == EX_TEMPFAIL && nummxhosts > hostnum)
3618 /* try next MX site */
3623 if (ConfigLevel < 2)
3624 _res.options |= RES_DEFNAMES | RES_DNSRCH; /* XXX */
3628 checkfds("after delivery");
3631 ** Do final status disposal.
3632 ** We check for something in tobuf for the SMTP case.
3633 ** If we got a temporary failure, arrange to queue the
3638 if (bitnset(M_LMTP, m->m_flags))
3646 anyok = rcode == EX_OK;
3648 for (to = tochain; to != NULL; to = to->q_tchain)
3650 /* see if address already marked */
3651 if (!QS_IS_OK(to->q_state))
3654 /* if running LMTP, get the status for each address */
3655 if (bitnset(M_LMTP, m->m_flags))
3657 if (lmtp_rcode == EX_OK)
3658 rcode = smtpgetstat(m, mci, e);
3661 strsize += sm_strlcat2(tobuf + strsize, ",",
3663 tobufsize - strsize);
3664 SM_ASSERT(strsize < tobufsize);
3669 e->e_to = to->q_paddr;
3670 markfailure(e, to, mci, rcode, true);
3671 giveresponse(rcode, to->q_status, m, mci,
3672 ctladdr, xstart, e, to);
3673 e->e_to = tobuf + 1;
3679 /* mark bad addresses */
3682 if (goodmxfound && rcode == EX_NOHOST)
3683 rcode = EX_TEMPFAIL;
3684 markfailure(e, to, mci, rcode, true);
3689 /* successful delivery */
3690 to->q_state = QS_SENT;
3691 to->q_statdate = curtime();
3695 ** Checkpoint the send list every few addresses
3698 if (CheckpointInterval > 0 && e->e_nsent >= CheckpointInterval)
3700 queueup(e, false, false);
3704 if (bitnset(M_LOCALMAILER, m->m_flags) &&
3705 bitset(QPINGONSUCCESS, to->q_flags))
3707 to->q_flags |= QDELIVERED;
3708 to->q_status = "2.1.5";
3709 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3710 "%s... Successfully delivered\n",
3713 else if (bitset(QPINGONSUCCESS, to->q_flags) &&
3714 bitset(QPRIMARY, to->q_flags) &&
3715 !bitset(MCIF_DSN, mci->mci_flags))
3717 to->q_flags |= QRELAYED;
3718 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3719 "%s... relayed; expect no further notifications\n",
3722 else if (IS_DLVR_NOTIFY(e) &&
3723 !bitset(MCIF_DLVR_BY, mci->mci_flags) &&
3724 bitset(QPRIMARY, to->q_flags) &&
3725 (!bitset(QHASNOTIFY, to->q_flags) ||
3726 bitset(QPINGONSUCCESS, to->q_flags) ||
3727 bitset(QPINGONFAILURE, to->q_flags) ||
3728 bitset(QPINGONDELAY, to->q_flags)))
3730 /* RFC 2852, 4.1.4.2: no NOTIFY, or not NEVER */
3731 to->q_flags |= QBYNRELAY;
3732 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3733 "%s... Deliver-by notify: relayed\n",
3736 else if (IS_DLVR_TRACE(e) &&
3737 (!bitset(QHASNOTIFY, to->q_flags) ||
3738 bitset(QPINGONSUCCESS, to->q_flags) ||
3739 bitset(QPINGONFAILURE, to->q_flags) ||
3740 bitset(QPINGONDELAY, to->q_flags)) &&
3741 bitset(QPRIMARY, to->q_flags))
3743 /* RFC 2852, 4.1.4: no NOTIFY, or not NEVER */
3744 to->q_flags |= QBYTRACE;
3745 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3746 "%s... Deliver-By trace: relayed\n",
3751 if (bitnset(M_LMTP, m->m_flags))
3754 ** Global information applies to the last recipient only;
3755 ** clear it out to avoid bogus errors.
3759 e->e_statmsg = NULL;
3761 /* reset the mci state for the next transaction */
3763 (mci->mci_state == MCIS_MAIL ||
3764 mci->mci_state == MCIS_RCPT ||
3765 mci->mci_state == MCIS_DATA))
3767 mci->mci_state = MCIS_OPEN;
3768 SmtpPhase = mci->mci_phase = "idle";
3769 sm_setproctitle(true, e, "%s: %s", CurHostName,
3774 if (tobuf[0] != '\0')
3776 giveresponse(rcode, NULL, m, mci, ctladdr, xstart, e, NULL);
3779 ** This code is disabled for now because I am not
3780 ** sure that copying status from the first recipient
3781 ** to all non-status'ed recipients is a good idea.
3784 if (tochain->q_message != NULL &&
3785 !bitnset(M_LMTP, m->m_flags) && rcode != EX_OK)
3787 for (to = tochain->q_tchain; to != NULL;
3790 /* see if address already marked */
3791 if (QS_IS_QUEUEUP(to->q_state) &&
3792 to->q_message == NULL)
3793 to->q_message = sm_rpool_strdup_x(e->e_rpool,
3794 tochain->q_message);
3800 markstats(e, tochain, STATS_NORMAL);
3801 mci_store_persistent(mci);
3805 ** HACK: this is NOT the right place to "close" a connection!
3807 ** add a flag to mci to indicate that rate/conc. was increased?
3812 extern SOCKADDR CurHostAddr;
3814 /* check family... {} */
3815 /* r = anynet_pton(AF_INET, p, dst); */
3816 occ_close(e, mci, host, &CurHostAddr);
3818 #endif /* _FFR_OCC */
3820 /* Some recipients were tempfailed, try them on the next host */
3821 if (mci != NULL && mci->mci_retryrcpt && nummxhosts > hostnum)
3823 /* try next MX site */
3827 /* now close the connection */
3828 if (clever && mci != NULL && mci->mci_state != MCIS_CLOSED &&
3829 !bitset(MCIF_CACHED, mci->mci_flags))
3830 smtpquit(m, mci, e);
3837 ** Restore state and return.
3842 /* make absolutely certain 0, 1, and 2 are in use */
3843 (void) sm_snprintf(wbuf, sizeof(wbuf),
3844 "%s... end of deliver(%s)",
3845 e->e_to == NULL ? "NO-TO-LIST"
3846 : shortenstring(e->e_to,
3855 ** It was originally necessary to set macro 'g' to NULL
3856 ** because it previously pointed to an auto buffer.
3857 ** We don't do this any more, so this may be unnecessary.
3860 macdefine(&e->e_macro, A_PERM, 'g', (char *) NULL);
3868 ** MARKFAILURE -- mark a failure on a specific address.
3871 ** e -- the envelope we are sending.
3872 ** q -- the address to mark.
3873 ** mci -- mailer connection information.
3874 ** rcode -- the code signifying the particular failure.
3875 ** ovr -- override an existing code?
3881 ** marks the address (and possibly the envelope) with the
3882 ** failure so that an error will be returned or
3883 ** the message will be queued, as appropriate.
3887 markfailure(e, q, mci, rcode, ovr)
3888 register ENVELOPE *e;
3889 register ADDRESS *q;
3894 int save_errno = errno;
3895 char *status = NULL;
3896 char *rstatus = NULL;
3906 q->q_state = QS_QUEUEUP;
3910 q->q_state = QS_BADADDR;
3914 /* find most specific error code possible */
3915 if (mci != NULL && mci->mci_status != NULL)
3917 status = sm_rpool_strdup_x(e->e_rpool, mci->mci_status);
3918 if (mci->mci_rstatus != NULL)
3919 rstatus = sm_rpool_strdup_x(e->e_rpool,
3922 else if (e->e_status != NULL)
3924 status = e->e_status;
3952 case EX_UNAVAILABLE:
3972 if (status != NULL && *status != '\0' && (ovr || q->q_status == NULL ||
3973 *q->q_status == '\0' || *q->q_status < *status))
3975 q->q_status = status;
3976 q->q_rstatus = rstatus;
3978 if (rcode != EX_OK && q->q_rstatus == NULL &&
3979 q->q_mailer != NULL && q->q_mailer->m_diagtype != NULL &&
3980 sm_strcasecmp(q->q_mailer->m_diagtype, "X-UNIX") == 0)
3984 (void) sm_snprintf(buf, sizeof(buf), "%d", rcode);
3985 q->q_rstatus = sm_rpool_strdup_x(e->e_rpool, buf);
3988 q->q_statdate = curtime();
3989 if (CurHostName != NULL && CurHostName[0] != '\0' &&
3990 mci != NULL && !bitset(M_LOCALMAILER, mci->mci_flags))
3991 q->q_statmta = sm_rpool_strdup_x(e->e_rpool, CurHostName);
3997 ** ENDMAILER -- Wait for mailer to terminate.
3999 ** We should never get fatal errors (e.g., segmentation
4000 ** violation), so we report those specially. For other
4001 ** errors, we choose a status message (into statmsg),
4002 ** and if it represents an error, we print it.
4005 ** mci -- the mailer connection info.
4006 ** e -- the current envelope.
4007 ** pv -- the parameter vector that invoked the mailer
4008 ** (for error messages).
4011 ** exit code of mailer.
4017 static jmp_buf EndWaitTimeout;
4020 endwaittimeout(ignore)
4024 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
4025 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
4030 longjmp(EndWaitTimeout, 1);
4034 endmailer(mci, e, pv)
4036 register ENVELOPE *e;
4040 int save_errno = errno;
4042 SM_EVENT *ev = NULL;
4045 mci_unlock_host(mci);
4047 /* close output to mailer */
4048 if (mci->mci_out != NULL)
4050 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
4051 mci->mci_out = NULL;
4054 /* copy any remaining input to transcript */
4055 if (mci->mci_in != NULL && mci->mci_state != MCIS_ERROR &&
4058 while (sfgets(buf, sizeof(buf), mci->mci_in,
4059 TimeOuts.to_quit, "Draining Input") != NULL)
4060 (void) sm_io_fputs(e->e_xfp, SM_TIME_DEFAULT, buf);
4064 /* close SASL connection */
4065 if (bitset(MCIF_AUTHACT, mci->mci_flags))
4067 sasl_dispose(&mci->mci_conn);
4068 mci->mci_flags &= ~MCIF_AUTHACT;
4074 (void) endtlsclt(mci);
4077 /* now close the input */
4078 if (mci->mci_in != NULL)
4080 (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT);
4083 mci->mci_state = MCIS_CLOSED;
4087 /* in the IPC case there is nothing to wait for */
4088 if (mci->mci_pid == 0)
4091 /* put a timeout around the wait */
4092 if (mci->mci_mailer->m_wait > 0)
4094 if (setjmp(EndWaitTimeout) == 0)
4095 ev = sm_setevent(mci->mci_mailer->m_wait,
4099 syserr("endmailer %s: wait timeout (%ld)",
4100 mci->mci_mailer->m_name,
4101 (long) mci->mci_mailer->m_wait);
4106 /* wait for the mailer process, collect status */
4107 st = waitfor(mci->mci_pid);
4115 syserr("endmailer %s: wait", mci->mci_mailer->m_name);
4121 /* normal death -- return status */
4122 return (WEXITSTATUS(st));
4125 /* it died a horrid death */
4126 syserr("451 4.3.0 mailer %s died with signal %d%s",
4127 mci->mci_mailer->m_name, WTERMSIG(st),
4128 WCOREDUMP(st) ? " (core dumped)" :
4129 (WIFSTOPPED(st) ? " (stopped)" : ""));
4131 /* log the arguments */
4132 if (pv != NULL && e->e_xfp != NULL)
4136 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "Arguments:");
4137 for (av = pv; *av != NULL; av++)
4138 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, " %s",
4140 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "\n");
4143 ExitStat = EX_TEMPFAIL;
4147 ** GIVERESPONSE -- Interpret an error response from a mailer
4150 ** status -- the status code from the mailer (high byte
4151 ** only; core dumps must have been taken care of
4153 ** dsn -- the DSN associated with the address, if any.
4154 ** m -- the mailer info for this mailer.
4155 ** mci -- the mailer connection info -- can be NULL if the
4156 ** response is given before the connection is made.
4157 ** ctladdr -- the controlling address for the recipient
4159 ** xstart -- the transaction start time, for computing
4160 ** transaction delays.
4161 ** e -- the current envelope.
4162 ** to -- the current recipient (NULL if none).
4168 ** Errors may be incremented.
4169 ** ExitStat may be set.
4173 giveresponse(status, dsn, m, mci, ctladdr, xstart, e, to)
4183 register const char *statmsg;
4186 bool usestat = false;
4187 char dsnbuf[ENHSCLEN];
4193 syserr("giveresponse: null envelope");
4199 ** Compute status message from code.
4202 exmsg = sm_sysexmsg(status);
4205 statmsg = "250 2.0.0 Sent";
4206 if (e->e_statmsg != NULL)
4208 (void) sm_snprintf(buf, sizeof(buf), "%s (%s)",
4210 shortenstring(e->e_statmsg, 403));
4214 else if (exmsg == NULL)
4216 (void) sm_snprintf(buf, sizeof(buf),
4217 "554 5.3.0 unknown mailer error %d",
4219 status = EX_UNAVAILABLE;
4223 else if (status == EX_TEMPFAIL)
4227 (void) sm_strlcpy(bp, exmsg + 1, SPACELEFT(buf, bp));
4230 if (h_errno == TRY_AGAIN)
4231 statmsg = sm_errstring(h_errno + E_DNSBASE);
4233 #endif /* NAMED_BIND */
4236 statmsg = sm_errstring(errnum);
4238 statmsg = SmtpError;
4240 if (statmsg != NULL && statmsg[0] != '\0')
4245 case ENETDOWN: /* Network is down */
4248 case ENETUNREACH: /* Network is unreachable */
4251 case ENETRESET: /* Network dropped connection on reset */
4254 case ECONNABORTED: /* Software caused connection abort */
4257 case EHOSTDOWN: /* Host is down */
4260 case EHOSTUNREACH: /* No route to host */
4262 if (mci != NULL && mci->mci_host != NULL)
4264 (void) sm_strlcpyn(bp,
4272 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ": ",
4275 if (errnum == 0 && SmtpError[0] != '\0' &&
4276 h_errno == TRY_AGAIN &&
4277 mci->mci_exitstat == EX_TEMPFAIL)
4279 (void) sm_strlcat(bp, SmtpError,
4280 SPACELEFT(buf, bp));
4289 else if (status == EX_NOHOST && h_errno != 0)
4291 statmsg = sm_errstring(h_errno + E_DNSBASE);
4292 (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", exmsg + 1,
4297 #endif /* NAMED_BIND */
4301 if (*statmsg++ == ':' && errnum != 0)
4303 (void) sm_snprintf(buf, sizeof(buf), "%s: %s", statmsg,
4304 sm_errstring(errnum));
4308 else if (bitnset(M_LMTP, m->m_flags) && e->e_statmsg != NULL)
4310 (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", statmsg,
4311 shortenstring(e->e_statmsg, 403));
4318 ** Print the message as appropriate
4321 if (status == EX_OK || status == EX_TEMPFAIL)
4323 extern char MsgBuf[];
4325 if ((off = isenhsc(statmsg + 4, ' ')) > 0)
4329 (void) sm_snprintf(dsnbuf, sizeof(dsnbuf),
4330 "%.*s", off, statmsg + 4);
4339 message("%s", statmsg + off);
4340 if (status == EX_TEMPFAIL && e->e_xfp != NULL)
4341 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s\n",
4346 char mbuf[ENHSCLEN + 4];
4349 if ((off = isenhsc(statmsg + 4, ' ')) > 0 &&
4350 off < sizeof(mbuf) - 4)
4354 (void) sm_snprintf(dsnbuf, sizeof(dsnbuf),
4355 "%.*s", off, statmsg + 4);
4360 /* copy only part of statmsg to mbuf */
4361 (void) sm_strlcpy(mbuf, statmsg, off);
4362 (void) sm_strlcat(mbuf, " %s", sizeof(mbuf));
4367 (void) sm_snprintf(mbuf, sizeof(mbuf), "%.3s %%s",
4371 usrerr(mbuf, &statmsg[off]);
4376 ** Log a record of the transaction. Compute the new ExitStat
4377 ** -- if we already had an error, stick with that.
4380 if (OpMode != MD_VERIFY && !bitset(EF_VRFYONLY, e->e_flags) &&
4381 LogLevel > ((status == EX_TEMPFAIL) ? 8 : (status == EX_OK) ? 7 : 6))
4382 logdelivery(m, mci, dsn, statmsg + off, ctladdr, xstart, e, to, status);
4385 sm_dprintf("giveresponse: status=%d, dsn=%s, e->e_message=%s, errnum=%d\n",
4387 dsn == NULL ? "<NULL>" : dsn,
4388 e->e_message == NULL ? "<NULL>" : e->e_message,
4391 if (status != EX_TEMPFAIL)
4393 if (status != EX_OK && (status != EX_TEMPFAIL || e->e_message == NULL))
4394 e->e_message = sm_rpool_strdup_x(e->e_rpool, statmsg + off);
4395 if (status != EX_OK && to != NULL && to->q_message == NULL)
4397 if (!usestat && e->e_message != NULL)
4398 to->q_message = sm_rpool_strdup_x(e->e_rpool,
4401 to->q_message = sm_rpool_strdup_x(e->e_rpool,
4408 ** LOGDELIVERY -- log the delivery in the system log
4410 ** Care is taken to avoid logging lines that are too long, because
4411 ** some versions of syslog have an unfortunate proclivity for core
4412 ** dumping. This is a hack, to be sure, that is at best empirical.
4415 ** m -- the mailer info. Can be NULL for initial queue.
4416 ** mci -- the mailer connection info -- can be NULL if the
4417 ** log is occurring when no connection is active.
4418 ** dsn -- the DSN attached to the status.
4419 ** status -- the message to print for the status.
4420 ** ctladdr -- the controlling address for the to list.
4421 ** xstart -- the transaction start time, used for
4422 ** computing transaction delay.
4423 ** e -- the current envelope.
4424 ** to -- the current recipient (NULL if none).
4425 ** rcode -- status code
4435 logdelivery(m, mci, dsn, status, ctladdr, xstart, e, to, rcode)
4442 register ENVELOPE *e;
4449 time_t now = curtime();
4452 #if (SYSLOG_BUFSIZE) >= 256
4453 /* ctladdr: max 106 bytes */
4455 if (ctladdr != NULL)
4457 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", ctladdr=",
4458 shortenstring(ctladdr->q_paddr, 83));
4460 if (bitset(QGOODUID, ctladdr->q_flags))
4462 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
4463 (int) ctladdr->q_uid,
4464 (int) ctladdr->q_gid);
4469 /* delay & xdelay: max 41 bytes */
4470 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", delay=",
4471 pintvl(now - e->e_ctime, true));
4474 if (xstart != (time_t) 0)
4476 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=",
4477 pintvl(now - xstart, true));
4481 /* mailer: assume about 19 bytes (max 10 byte mailer name) */
4484 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=",
4493 /* pri: changes with each delivery attempt */
4494 (void) sm_snprintf(bp, SPACELEFT(buf, bp), ", pri=%ld",
4495 PRT_NONNEGL(e->e_msgpriority));
4498 /* relay: max 66 bytes for IPv4 addresses */
4499 if (mci != NULL && mci->mci_host != NULL)
4501 extern SOCKADDR CurHostAddr;
4503 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", relay=",
4504 shortenstring(mci->mci_host, 40));
4507 if (CurHostAddr.sa.sa_family != 0)
4509 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " [%s]",
4510 anynet_ntoa(&CurHostAddr));
4513 else if (strcmp(status, "quarantined") == 0)
4515 if (e->e_quarmsg != NULL)
4516 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4518 shortenstring(e->e_quarmsg, 40));
4520 else if (strcmp(status, "queued") != 0)
4522 p = macvalue('h', e);
4523 if (p != NULL && p[0] != '\0')
4525 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4526 ", relay=%s", shortenstring(p, 40));
4532 if (dsn != NULL && *dsn != '\0')
4534 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", dsn=",
4535 shortenstring(dsn, ENHSCLEN));
4539 # if _FFR_LOG_NTRIES
4541 if (e->e_ntries >= 0)
4543 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4544 ", ntries=%d", e->e_ntries + 1);
4547 # endif /* _FFR_LOG_NTRIES */
4549 # define STATLEN (((SYSLOG_BUFSIZE) - 100) / 4)
4553 # endif /* (STATLEN) < 63 */
4554 # if (STATLEN) > 203
4556 # define STATLEN 203
4557 # endif /* (STATLEN) > 203 */
4561 ** per-rcpt status: to->q_rstatus
4562 ** global status: e->e_text
4564 ** We (re)use STATLEN here, is that a good choice?
4566 ** stat=Deferred: ...
4567 ** has sometimes the same text?
4569 ** Note: this doesn't show the stage at which the error happened.
4570 ** can/should we log that?
4571 ** XS_* in reply() basically encodes the state.
4573 ** Note: in some case the normal logging might show the same server
4574 ** reply - how to avoid that?
4577 /* only show errors */
4578 if (rcode != EX_OK && to != NULL && to->q_rstatus != NULL &&
4579 *to->q_rstatus != '\0')
4581 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4583 shortenstring(to->q_rstatus, STATLEN));
4586 else if (rcode != EX_OK && e->e_text != NULL)
4588 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4589 ", reply=%d %s%s%s",
4592 (e->e_renhsc[0] != '\0') ? " " : "",
4593 shortenstring(e->e_text, STATLEN));
4597 /* stat: max 210 bytes */
4598 if ((bp - buf) > (sizeof(buf) - ((STATLEN) + 20)))
4600 /* desperation move -- truncate data */
4601 bp = buf + sizeof(buf) - ((STATLEN) + 17);
4602 (void) sm_strlcpy(bp, "...", SPACELEFT(buf, bp));
4606 (void) sm_strlcpy(bp, ", stat=", SPACELEFT(buf, bp));
4609 (void) sm_strlcpy(bp, shortenstring(status, STATLEN),
4610 SPACELEFT(buf, bp));
4612 /* id, to: max 13 + TOBUFSIZE bytes */
4613 l = SYSLOG_BUFSIZE - 100 - strlen(buf);
4616 p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
4617 while (strlen(p) >= l)
4621 for (q = p + l; q > p; q--)
4623 /* XXX a comma in an address will break this! */
4629 sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]%s",
4630 (int) (++q - p), p, buf);
4633 sm_syslog(LOG_INFO, e->e_id, "to=%.*s%s", l, p, buf);
4635 #else /* (SYSLOG_BUFSIZE) >= 256 */
4637 l = SYSLOG_BUFSIZE - 85;
4640 p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
4641 while (strlen(p) >= l)
4645 for (q = p + l; q > p; q--)
4653 sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]",
4654 (int) (++q - p), p);
4657 sm_syslog(LOG_INFO, e->e_id, "to=%.*s", l, p);
4659 if (ctladdr != NULL)
4662 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "ctladdr=",
4663 shortenstring(ctladdr->q_paddr, 83));
4665 if (bitset(QGOODUID, ctladdr->q_flags))
4667 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
4668 ctladdr->q_uid, ctladdr->q_gid);
4671 sm_syslog(LOG_INFO, e->e_id, "%s", buf);
4674 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "delay=",
4675 pintvl(now - e->e_ctime, true));
4677 if (xstart != (time_t) 0)
4679 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=",
4680 pintvl(now - xstart, true));
4686 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=",
4690 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
4694 if (mci != NULL && mci->mci_host != NULL)
4696 extern SOCKADDR CurHostAddr;
4698 (void) sm_snprintf(bp, SPACELEFT(buf, bp), "relay=%.100s",
4702 if (CurHostAddr.sa.sa_family != 0)
4703 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4705 anynet_ntoa(&CurHostAddr));
4707 else if (strcmp(status, "quarantined") == 0)
4709 if (e->e_quarmsg != NULL)
4710 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4711 ", quarantine=%.100s",
4714 else if (strcmp(status, "queued") != 0)
4716 p = macvalue('h', e);
4717 if (p != NULL && p[0] != '\0')
4718 (void) sm_snprintf(buf, sizeof(buf), "relay=%.100s", p);
4721 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
4723 sm_syslog(LOG_INFO, e->e_id, "stat=%s", shortenstring(status, 63));
4724 #endif /* (SYSLOG_BUFSIZE) >= 256 */
4727 ** PUTFROMLINE -- output a UNIX-style from line (or whatever)
4729 ** This can be made an arbitrary message separator by changing $l
4731 ** One of the ugliest hacks seen by human eyes is contained herein:
4732 ** UUCP wants those stupid "remote from <host>" lines. Why oh why
4733 ** does a well-meaning programmer such as myself have to deal with
4734 ** this kind of antique garbage????
4737 ** mci -- the connection information.
4738 ** e -- the envelope.
4741 ** true iff line was written successfully
4744 ** outputs some text to fp.
4752 char *template = UnixFromLine;
4756 if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
4759 mci->mci_flags |= MCIF_INHEADER;
4761 if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
4765 expand("\201g", buf, sizeof(buf), e);
4766 bang = strchr(buf, '!');
4770 char hname[MAXNAME];
4773 ** If we can construct a UUCP path, do so
4776 at = strrchr(buf, '@');
4779 expand("\201k", hname, sizeof(hname), e);
4784 (void) sm_snprintf(xbuf, sizeof(xbuf),
4785 "From %.800s \201d remote from %.100s\n",
4791 (void) sm_snprintf(xbuf, sizeof(xbuf),
4792 "From %.800s \201d remote from %.100s\n",
4797 expand(template, buf, sizeof(buf), e);
4798 return putxline(buf, strlen(buf), mci, PXLF_HEADER);
4802 ** PUTBODY -- put the body of a message.
4805 ** mci -- the connection information.
4806 ** e -- the envelope to put out.
4807 ** separator -- if non-NULL, a message separator that must
4808 ** not be permitted in the resulting message.
4811 ** true iff message was written successfully
4814 ** The message is written onto fp.
4817 /* values for output state variable */
4818 #define OSTATE_HEAD 0 /* at beginning of line */
4819 #define OSTATE_CR 1 /* read a carriage return */
4820 #define OSTATE_INLINE 2 /* putting rest of line */
4823 putbody(mci, e, separator)
4825 register ENVELOPE *e;
4833 char *boundaries[MAXMIMENESTING + 1];
4837 ** Output the body of the message
4840 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
4842 char *df = queuename(e, DATAFL_LETTER);
4844 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df,
4845 SM_IO_RDONLY_B, NULL);
4846 if (e->e_dfp == NULL)
4848 char *msg = "!putbody: Cannot open %s for %s from %s";
4850 if (errno == ENOENT)
4852 syserr(msg, df, e->e_to, e->e_from.q_paddr);
4856 if (e->e_dfp == NULL)
4858 if (bitset(MCIF_INHEADER, mci->mci_flags))
4860 if (!putline("", mci))
4862 mci->mci_flags &= ~MCIF_INHEADER;
4864 if (!putline("<<< No Message Collected >>>", mci))
4869 if (e->e_dfino == (ino_t) 0)
4873 if (fstat(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), &stbuf)
4878 e->e_dfdev = stbuf.st_dev;
4879 e->e_dfino = stbuf.st_ino;
4883 /* paranoia: the data file should always be in a rewound state */
4884 (void) bfrewind(e->e_dfp);
4886 /* simulate an I/O timeout when used as source */
4891 if (bitset(MCIF_CVT8TO7, mci->mci_flags))
4894 ** Do 8 to 7 bit MIME conversion.
4897 /* make sure it looks like a MIME message */
4898 if (hvalue("MIME-Version", e->e_header) == NULL &&
4899 !putline("MIME-Version: 1.0", mci))
4902 if (hvalue("Content-Type", e->e_header) == NULL)
4904 (void) sm_snprintf(buf, sizeof(buf),
4905 "Content-Type: text/plain; charset=%s",
4907 if (!putline(buf, mci))
4911 /* now do the hard work */
4912 boundaries[0] = NULL;
4913 mci->mci_flags |= MCIF_INHEADER;
4914 if (mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER, 0) ==
4919 else if (bitset(MCIF_CVT7TO8, mci->mci_flags))
4921 if (!mime7to8(mci, e->e_header, e))
4924 # endif /* MIME7TO8 */
4925 else if (MaxMimeHeaderLength > 0 || MaxMimeFieldLength > 0)
4927 bool oldsuprerrs = SuprErrs;
4929 /* Use mime8to7 to check multipart for MIME header overflows */
4930 boundaries[0] = NULL;
4931 mci->mci_flags |= MCIF_INHEADER;
4934 ** If EF_DONT_MIME is set, we have a broken MIME message
4935 ** and don't want to generate a new bounce message whose
4936 ** body propagates the broken MIME. We can't just not call
4937 ** mime8to7() as is done above since we need the security
4938 ** checks. The best we can do is suppress the errors.
4941 if (bitset(EF_DONT_MIME, e->e_flags))
4944 if (mime8to7(mci, e->e_header, e, boundaries,
4945 M87F_OUTER|M87F_NO8TO7, 0) == SM_IO_EOF)
4948 /* restore SuprErrs */
4949 SuprErrs = oldsuprerrs;
4952 #endif /* MIME8TO7 */
4964 if (bitset(MCIF_INHEADER, mci->mci_flags))
4966 if (!putline("", mci))
4968 mci->mci_flags &= ~MCIF_INHEADER;
4971 /* determine end of buffer; allow for short mailer lines */
4972 buflim = &buf[sizeof(buf) - 1];
4973 if (mci->mci_mailer->m_linelimit > 0 &&
4974 mci->mci_mailer->m_linelimit < sizeof(buf) - 1)
4975 buflim = &buf[mci->mci_mailer->m_linelimit - 1];
4977 /* copy temp file to output with mapping */
4978 ostate = OSTATE_HEAD;
4981 while (!sm_io_error(mci->mci_out) && !dead)
4985 else if ((c = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT))
4988 if (bitset(MCIF_7BIT, mci->mci_flags))
4995 mci->mci_mailer->m_flags))
4997 if (c != '\r' && c != '\n' && bp < buflim)
5003 /* check beginning of line for special cases */
5007 if (buf[0] == 'F' &&
5008 bitnset(M_ESCFROM, mci->mci_mailer->m_flags)
5009 && strncmp(buf, "From ", 5) == 0)
5013 if (buf[0] == '-' && buf[1] == '-' &&
5016 /* possible separator */
5017 int sl = strlen(separator);
5019 if (strncmp(&buf[2], separator, sl)
5023 if (buf[0] == '.' &&
5024 bitnset(M_XDOT, mci->mci_mailer->m_flags))
5029 /* now copy out saved line */
5030 if (TrafficLogFile != NULL)
5032 (void) sm_io_fprintf(TrafficLogFile,
5036 if (padc != SM_IO_EOF)
5037 (void) sm_io_putc(TrafficLogFile,
5040 for (xp = buf; xp < bp; xp++)
5041 (void) sm_io_putc(TrafficLogFile,
5043 (unsigned char) *xp);
5045 (void) sm_io_fputs(TrafficLogFile,
5047 mci->mci_mailer->m_eol);
5049 if (padc != SM_IO_EOF)
5051 if (sm_io_putc(mci->mci_out,
5052 SM_TIME_DEFAULT, padc)
5060 for (xp = buf; xp < bp; xp++)
5062 if (sm_io_putc(mci->mci_out,
5064 (unsigned char) *xp)
5075 if (sm_io_fputs(mci->mci_out,
5077 mci->mci_mailer->m_eol)
5087 SM_ASSERT(pbp < peekbuf +
5095 /* determine next state */
5097 ostate = OSTATE_HEAD;
5101 ostate = OSTATE_INLINE;
5108 if (sm_io_fputs(mci->mci_out,
5110 mci->mci_mailer->m_eol)
5114 if (TrafficLogFile != NULL)
5116 (void) sm_io_fputs(TrafficLogFile,
5118 mci->mci_mailer->m_eol);
5121 ostate = OSTATE_HEAD;
5125 /* had a naked carriage return */
5126 SM_ASSERT(pbp < peekbuf + sizeof(peekbuf));
5129 ostate = OSTATE_INLINE;
5140 mci->mci_mailer->m_flags))
5143 if (mci->mci_mailer->m_linelimit > 0 &&
5144 pos >= mci->mci_mailer->m_linelimit - 1 &&
5149 /* check next character for EOL */
5152 else if ((d = sm_io_getc(e->e_dfp,
5156 SM_ASSERT(pbp < peekbuf +
5161 if (d == '\n' || d == SM_IO_EOF)
5163 if (TrafficLogFile != NULL)
5164 (void) sm_io_putc(TrafficLogFile,
5167 if (sm_io_putc(mci->mci_out,
5179 if (sm_io_putc(mci->mci_out,
5180 SM_TIME_DEFAULT, '!')
5182 sm_io_fputs(mci->mci_out,
5184 mci->mci_mailer->m_eol)
5191 if (TrafficLogFile != NULL)
5193 (void) sm_io_fprintf(TrafficLogFile,
5196 mci->mci_mailer->m_eol);
5198 ostate = OSTATE_HEAD;
5199 SM_ASSERT(pbp < peekbuf +
5206 if (TrafficLogFile != NULL)
5207 (void) sm_io_fputs(TrafficLogFile,
5209 mci->mci_mailer->m_eol);
5210 if (sm_io_fputs(mci->mci_out,
5212 mci->mci_mailer->m_eol)
5216 ostate = OSTATE_HEAD;
5220 if (TrafficLogFile != NULL)
5221 (void) sm_io_putc(TrafficLogFile,
5224 if (sm_io_putc(mci->mci_out,
5233 ostate = OSTATE_INLINE;
5239 /* make sure we are at the beginning of a line */
5242 if (TrafficLogFile != NULL)
5244 for (xp = buf; xp < bp; xp++)
5245 (void) sm_io_putc(TrafficLogFile,
5247 (unsigned char) *xp);
5249 for (xp = buf; xp < bp; xp++)
5251 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT,
5252 (unsigned char) *xp)
5261 if (!dead && pos > 0)
5263 if (TrafficLogFile != NULL)
5264 (void) sm_io_fputs(TrafficLogFile,
5266 mci->mci_mailer->m_eol);
5267 if (sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT,
5268 mci->mci_mailer->m_eol) == SM_IO_EOF)
5273 if (sm_io_error(e->e_dfp))
5275 syserr("putbody: %s/%cf%s: read error",
5276 qid_printqueue(e->e_dfqgrp, e->e_dfqdir),
5277 DATAFL_LETTER, e->e_id);
5278 ExitStat = EX_IOERR;
5284 ** Since mailfile() uses e_dfp in a child process,
5285 ** the file offset in the stdio library for the
5286 ** parent process will not agree with the in-kernel
5287 ** file offset since the file descriptor is shared
5288 ** between the processes. Therefore, it is vital
5289 ** that the file always be rewound. This forces the
5290 ** kernel offset (lseek) and stdio library (ftell)
5295 if (e->e_dfp != NULL)
5296 (void) bfrewind(e->e_dfp);
5298 /* some mailers want extra blank line at end of message */
5299 if (!dead && bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
5300 buf[0] != '\0' && buf[0] != '\n')
5302 if (!putline("", mci))
5307 (sm_io_flush(mci->mci_out, SM_TIME_DEFAULT) == SM_IO_EOF ||
5308 (sm_io_error(mci->mci_out) && errno != EPIPE)))
5311 syserr("putbody: write error");
5312 ExitStat = EX_IOERR;
5317 return !dead && !ioerr;
5324 ** MAILFILE -- Send a message to a file.
5326 ** If the file has the set-user-ID/set-group-ID bits set, but NO
5327 ** execute bits, sendmail will try to become the owner of that file
5328 ** rather than the real user. Obviously, this only works if
5329 ** sendmail runs as root.
5331 ** This could be done as a subordinate mailer, except that it
5332 ** is used implicitly to save messages in ~/dead.letter. We
5333 ** view this as being sufficiently important as to include it
5334 ** here. For example, if the system is dying, we shouldn't have
5335 ** to create another process plus some pipes to save the message.
5338 ** filename -- the name of the file to send to.
5339 ** mailer -- mailer definition for recipient -- if NULL,
5341 ** ctladdr -- the controlling address header -- includes
5342 ** the userid/groupid to be when sending.
5343 ** sfflags -- flags for opening.
5344 ** e -- the current envelope.
5347 ** The exit code associated with the operation.
5353 # define RETURN(st) exit(st);
5355 static jmp_buf CtxMailfileTimeout;
5358 mailfile(filename, mailer, ctladdr, sfflags, e)
5359 char *volatile filename;
5360 MAILER *volatile mailer;
5362 volatile long sfflags;
5363 register ENVELOPE *e;
5365 register SM_FILE_T *f;
5366 register pid_t pid = -1;
5370 bool suidwarn = geteuid() == 0;
5372 char *volatile realfile;
5374 char buf[MAXPATHLEN];
5375 char targetfile[MAXPATHLEN];
5379 sm_dprintf("mailfile %s\n ctladdr=", filename);
5380 printaddr(sm_debug_file(), ctladdr, false);
5384 mailer = FileMailer;
5386 if (e->e_xfp != NULL)
5387 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
5390 ** Special case /dev/null. This allows us to restrict file
5391 ** delivery to regular files only.
5394 if (sm_path_isdevnull(filename))
5397 /* check for 8-bit available */
5398 if (bitset(EF_HAS8BIT, e->e_flags) &&
5399 bitnset(M_7BITS, mailer->m_flags) &&
5400 (bitset(EF_DONT_MIME, e->e_flags) ||
5401 !(bitset(MM_MIME8BIT, MimeMode) ||
5402 (bitset(EF_IS_MIME, e->e_flags) &&
5403 bitset(MM_CVTMIME, MimeMode)))))
5405 e->e_status = "5.6.3";
5406 usrerrenh(e->e_status,
5407 "554 Cannot send 8-bit data to 7-bit destination");
5412 /* Find the actual file */
5413 if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0')
5415 len = strlen(SafeFileEnv);
5417 if (strncmp(SafeFileEnv, filename, len) == 0)
5420 if (len + strlen(filename) + 1 >= sizeof(targetfile))
5422 syserr("mailfile: filename too long (%s/%s)",
5423 SafeFileEnv, filename);
5424 return EX_CANTCREAT;
5426 (void) sm_strlcpy(targetfile, SafeFileEnv, sizeof(targetfile));
5427 realfile = targetfile + len;
5428 if (*filename == '/')
5430 if (*filename != '\0')
5432 /* paranoia: trailing / should be removed in readcf */
5433 if (targetfile[len - 1] != '/')
5434 (void) sm_strlcat(targetfile,
5435 "/", sizeof(targetfile));
5436 (void) sm_strlcat(targetfile, filename,
5437 sizeof(targetfile));
5440 else if (mailer->m_rootdir != NULL)
5442 expand(mailer->m_rootdir, targetfile, sizeof(targetfile), e);
5443 len = strlen(targetfile);
5445 if (strncmp(targetfile, filename, len) == 0)
5448 if (len + strlen(filename) + 1 >= sizeof(targetfile))
5450 syserr("mailfile: filename too long (%s/%s)",
5451 targetfile, filename);
5452 return EX_CANTCREAT;
5454 realfile = targetfile + len;
5455 if (targetfile[len - 1] != '/')
5456 (void) sm_strlcat(targetfile, "/", sizeof(targetfile));
5457 if (*filename == '/')
5458 (void) sm_strlcat(targetfile, filename + 1,
5459 sizeof(targetfile));
5461 (void) sm_strlcat(targetfile, filename,
5462 sizeof(targetfile));
5466 if (sm_strlcpy(targetfile, filename, sizeof(targetfile)) >=
5469 syserr("mailfile: filename too long (%s)", filename);
5470 return EX_CANTCREAT;
5472 realfile = targetfile;
5476 ** Fork so we can change permissions here.
5477 ** Note that we MUST use fork, not vfork, because of
5478 ** the complications of calling subroutines, etc.
5483 ** Dispose of SIGCHLD signal catchers that may be laying
5484 ** around so that the waitfor() below will get it.
5487 (void) sm_signal(SIGCHLD, SIG_DFL);
5495 /* child -- actually write to file */
5499 volatile int oflags = O_WRONLY|O_APPEND;
5501 /* Reset global flags */
5502 RestartRequest = NULL;
5503 RestartWorkGroup = false;
5504 ShutdownRequest = NULL;
5506 CurrentPid = getpid();
5508 if (e->e_lockfp != NULL)
5512 fd = sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL);
5513 /* SM_ASSERT(fd >= 0); */
5518 (void) sm_signal(SIGINT, SIG_DFL);
5519 (void) sm_signal(SIGHUP, SIG_DFL);
5520 (void) sm_signal(SIGTERM, SIG_DFL);
5521 (void) umask(OldUmask);
5525 if (setjmp(CtxMailfileTimeout) != 0)
5527 RETURN(EX_TEMPFAIL);
5530 if (TimeOuts.to_fileopen > 0)
5531 ev = sm_setevent(TimeOuts.to_fileopen, mailfiletimeout,
5536 /* check file mode to see if set-user-ID */
5537 if (stat(targetfile, &stb) < 0)
5542 /* limit the errors to those actually caused in the child */
5546 /* Allow alias expansions to use the S_IS{U,G}ID bits */
5547 if ((ctladdr != NULL && !bitset(QALIAS, ctladdr->q_flags)) ||
5548 bitset(SFF_RUNASREALUID, sfflags))
5550 /* ignore set-user-ID and set-group-ID bits */
5551 mode &= ~(S_ISGID|S_ISUID);
5553 sm_dprintf("mailfile: ignoring set-user-ID/set-group-ID bits\n");
5556 /* we have to open the data file BEFORE setuid() */
5557 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
5559 char *df = queuename(e, DATAFL_LETTER);
5561 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df,
5562 SM_IO_RDONLY_B, NULL);
5563 if (e->e_dfp == NULL)
5565 syserr("mailfile: Cannot open %s for %s from %s",
5566 df, e->e_to, e->e_from.q_paddr);
5570 /* select a new user to run as */
5571 if (!bitset(SFF_RUNASREALUID, sfflags))
5573 if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
5575 RealUserName = NULL;
5576 if (mailer->m_uid == NO_UID)
5579 RealUid = mailer->m_uid;
5580 if (RunAsUid != 0 && RealUid != RunAsUid)
5582 /* Only root can change the uid */
5583 syserr("mailfile: insufficient privileges to change uid, RunAsUid=%ld, RealUid=%ld",
5584 (long) RunAsUid, (long) RealUid);
5585 RETURN(EX_TEMPFAIL);
5588 else if (bitset(S_ISUID, mode))
5590 RealUserName = NULL;
5591 RealUid = stb.st_uid;
5593 else if (ctladdr != NULL && ctladdr->q_uid != 0)
5595 if (ctladdr->q_ruser != NULL)
5596 RealUserName = ctladdr->q_ruser;
5598 RealUserName = ctladdr->q_user;
5599 RealUid = ctladdr->q_uid;
5601 else if (mailer != NULL && mailer->m_uid != NO_UID)
5603 RealUserName = DefUser;
5604 RealUid = mailer->m_uid;
5608 RealUserName = DefUser;
5612 /* select a new group to run as */
5613 if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
5615 if (mailer->m_gid == NO_GID)
5618 RealGid = mailer->m_gid;
5619 if (RunAsUid != 0 &&
5620 (RealGid != getgid() ||
5621 RealGid != getegid()))
5623 /* Only root can change the gid */
5624 syserr("mailfile: insufficient privileges to change gid, RealGid=%ld, RunAsUid=%ld, gid=%ld, egid=%ld",
5625 (long) RealGid, (long) RunAsUid,
5626 (long) getgid(), (long) getegid());
5627 RETURN(EX_TEMPFAIL);
5630 else if (bitset(S_ISGID, mode))
5631 RealGid = stb.st_gid;
5632 else if (ctladdr != NULL &&
5633 ctladdr->q_uid == DefUid &&
5634 ctladdr->q_gid == 0)
5637 ** Special case: This means it is an
5638 ** alias and we should act as DefaultUser.
5639 ** See alias()'s comments.
5643 RealUserName = DefUser;
5645 else if (ctladdr != NULL && ctladdr->q_uid != 0)
5646 RealGid = ctladdr->q_gid;
5647 else if (mailer != NULL && mailer->m_gid != NO_GID)
5648 RealGid = mailer->m_gid;
5654 if (!bitset(SFF_ROOTOK, sfflags))
5662 /* set group id list (needs /etc/group access) */
5663 if (RealUserName != NULL && !DontInitGroups)
5665 if (initgroups(RealUserName, RealGid) == -1 && suidwarn)
5667 syserr("mailfile: initgroups(%s, %ld) failed",
5668 RealUserName, (long) RealGid);
5669 RETURN(EX_TEMPFAIL);
5676 gidset[0] = RealGid;
5677 if (setgroups(1, gidset) == -1 && suidwarn)
5679 syserr("mailfile: setgroups() failed");
5680 RETURN(EX_TEMPFAIL);
5685 ** If you have a safe environment, go into it.
5688 if (realfile != targetfile)
5695 sm_dprintf("mailfile: chroot %s\n", targetfile);
5696 if (chroot(targetfile) < 0)
5698 syserr("mailfile: Cannot chroot(%s)",
5700 RETURN(EX_CANTCREAT);
5706 sm_dprintf("mailfile: deliver to %s\n", realfile);
5710 syserr("mailfile: cannot chdir(/)");
5711 RETURN(EX_CANTCREAT);
5714 /* now reset the group and user ids */
5716 sm_mbdb_terminate();
5717 if (setgid(RealGid) < 0 && suidwarn)
5719 syserr("mailfile: setgid(%ld) failed", (long) RealGid);
5720 RETURN(EX_TEMPFAIL);
5722 vendor_set_uid(RealUid);
5723 if (setuid(RealUid) < 0 && suidwarn)
5725 syserr("mailfile: setuid(%ld) failed", (long) RealUid);
5726 RETURN(EX_TEMPFAIL);
5730 sm_dprintf("mailfile: running as r/euid=%ld/%ld, r/egid=%ld/%ld\n",
5731 (long) getuid(), (long) geteuid(),
5732 (long) getgid(), (long) getegid());
5735 /* move into some "safe" directory */
5736 if (mailer->m_execdir != NULL)
5740 for (p = mailer->m_execdir; p != NULL; p = q)
5745 expand(p, buf, sizeof(buf), e);
5749 sm_dprintf("mailfile: trydir %s\n",
5751 if (buf[0] != '\0' && chdir(buf) >= 0)
5757 ** Recheck the file after we have assumed the ID of the
5758 ** delivery user to make sure we can deliver to it as
5759 ** that user. This is necessary if sendmail is running
5760 ** as root and the file is on an NFS mount which treats
5765 if (bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
5766 err = stat(realfile, &stb);
5768 err = lstat(realfile, &stb);
5769 #else /* HASLSTAT */
5770 err = stat(realfile, &stb);
5771 #endif /* HASLSTAT */
5775 stb.st_mode = ST_MODE_NOFILE;
5777 oflags |= O_CREAT|O_EXCL;
5779 else if (bitset(S_IXUSR|S_IXGRP|S_IXOTH, mode) ||
5780 (!bitnset(DBS_FILEDELIVERYTOHARDLINK,
5781 DontBlameSendmail) &&
5782 stb.st_nlink != 1) ||
5783 (realfile != targetfile && !S_ISREG(mode)))
5788 if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
5789 sfflags |= SFF_NOSLINK;
5790 if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
5791 sfflags |= SFF_NOHLINK;
5792 sfflags &= ~SFF_OPENASROOT;
5793 f = safefopen(realfile, oflags, mode, sfflags);
5796 if (transienterror(errno))
5798 usrerr("454 4.3.0 cannot open %s: %s",
5799 shortenstring(realfile, MAXSHORTSTR),
5800 sm_errstring(errno));
5801 RETURN(EX_TEMPFAIL);
5805 usrerr("554 5.3.0 cannot open %s: %s",
5806 shortenstring(realfile, MAXSHORTSTR),
5807 sm_errstring(errno));
5808 RETURN(EX_CANTCREAT);
5811 if (filechanged(realfile, sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5814 syserr("554 5.3.0 file changed after open");
5815 RETURN(EX_CANTCREAT);
5817 if (fstat(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), &stb) < 0)
5819 syserr("554 5.3.0 cannot fstat %s",
5820 sm_errstring(errno));
5821 RETURN(EX_CANTCREAT);
5824 curoff = stb.st_size;
5829 memset(&mcibuf, '\0', sizeof(mcibuf));
5830 mcibuf.mci_mailer = mailer;
5832 if (bitnset(M_7BITS, mailer->m_flags))
5833 mcibuf.mci_flags |= MCIF_7BIT;
5835 /* clear out per-message flags from connection structure */
5836 mcibuf.mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
5838 if (bitset(EF_HAS8BIT, e->e_flags) &&
5839 !bitset(EF_DONT_MIME, e->e_flags) &&
5840 bitnset(M_7BITS, mailer->m_flags))
5841 mcibuf.mci_flags |= MCIF_CVT8TO7;
5844 if (bitnset(M_MAKE8BIT, mailer->m_flags) &&
5845 !bitset(MCIF_7BIT, mcibuf.mci_flags) &&
5846 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
5847 (sm_strcasecmp(p, "quoted-printable") == 0 ||
5848 sm_strcasecmp(p, "base64") == 0) &&
5849 (p = hvalue("Content-Type", e->e_header)) != NULL)
5851 /* may want to convert 7 -> 8 */
5852 /* XXX should really parse it here -- and use a class XXX */
5853 if (sm_strncasecmp(p, "text/plain", 10) == 0 &&
5854 (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
5855 mcibuf.mci_flags |= MCIF_CVT7TO8;
5857 #endif /* MIME7TO8 */
5859 if (!putfromline(&mcibuf, e) ||
5860 !(*e->e_puthdr)(&mcibuf, e->e_header, e, M87F_OUTER) ||
5861 !(*e->e_putbody)(&mcibuf, e, NULL) ||
5862 !putline("\n", &mcibuf) ||
5863 (sm_io_flush(f, SM_TIME_DEFAULT) != 0 ||
5864 (SuperSafe != SAFE_NO &&
5865 fsync(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL)) < 0) ||
5870 (void) ftruncate(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5875 /* reset ISUID & ISGID bits for paranoid systems */
5877 (void) fchmod(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5879 #else /* HASFCHMOD */
5880 (void) chmod(filename, (MODE_T) mode);
5881 #endif /* HASFCHMOD */
5882 if (sm_io_close(f, SM_TIME_DEFAULT) < 0)
5884 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
5885 (void) setuid(RealUid);
5891 /* parent -- wait for exit status */
5897 syserr("mailfile: %s: wait", mailer->m_name);
5903 return (WEXITSTATUS(st));
5907 syserr("mailfile: %s: child died on signal %d",
5908 mailer->m_name, st);
5909 return EX_UNAVAILABLE;
5913 return EX_UNAVAILABLE; /* avoid compiler warning on IRIX */
5917 mailfiletimeout(ignore)
5921 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
5922 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
5927 longjmp(CtxMailfileTimeout, 1);
5933 ** GETMPORT -- return the port of a mailer
5936 ** m -- the mailer describing this host.
5939 ** the port of the mailer if defined.
5944 static int getmport __P((MAILER *));
5950 unsigned long ulval;
5956 if (NULL == m->m_argv[0] ||NULL == m->m_argv[1])
5963 ulval = strtoul(buf, &ep, 0);
5964 if (buf[0] == '\0' || *ep != '\0')
5966 if (errno == ERANGE && ulval == ULONG_MAX)
5968 if (ulval > USHRT_MAX)
5970 m->m_port = (unsigned short) ulval;
5972 sm_dprintf("getmport: mailer=%s, port=%d\n", m->m_name,
5976 # define GETMPORT(m) getmport(m)
5978 # define GETMPORT(m) 25
5982 ** HOSTSIGNATURE -- return the "signature" for a host.
5984 ** The signature describes how we are going to send this -- it
5985 ** can be just the hostname (for non-Internet hosts) or can be
5986 ** an ordered list of MX hosts.
5989 ** m -- the mailer describing this host.
5990 ** host -- the host name.
5994 ** The signature for this host.
5997 ** Can tweak the symbol table.
6000 #define MAXHOSTSIGNATURE 8192 /* max len of hostsignature */
6003 hostsignature(m, host, ad)
6020 int oldoptions = _res.options;
6021 char *mxhosts[MAXMXHOSTS + 1];
6022 unsigned short mxprefs[MAXMXHOSTS + 1];
6023 #endif /* NAMED_BIND */
6026 sm_dprintf("hostsignature(%s), ad=%d\n", host, ad);
6029 ** If local delivery (and not remote), just return a constant.
6032 if (bitnset(M_LOCALMAILER, m->m_flags) &&
6033 strcmp(m->m_mailer, "[IPC]") != 0 &&
6034 !(m->m_argv[0] != NULL && strcmp(m->m_argv[0], "TCP") == 0))
6037 /* an empty host does not have MX records */
6042 ** Check to see if this uses IPC -- if not, it can't have MX records.
6045 if (strcmp(m->m_mailer, "[IPC]") != 0 ||
6046 CurEnv->e_sendmode == SM_DEFER)
6048 /* just an ordinary mailer or deferred mode */
6052 else if (m->m_argv[0] != NULL &&
6053 strcmp(m->m_argv[0], "FILE") == 0)
6055 /* rendezvous in the file system, no MX records */
6058 #endif /* NETUNIX */
6061 ** Look it up in the symbol table.
6065 s = stab(host, ST_HOSTSIG, ST_ENTER);
6066 if (s->s_hostsig.hs_sig != NULL)
6068 if (s->s_hostsig.hs_exp >= now)
6071 sm_dprintf("hostsignature(): stab(%s) found %s\n", host,
6072 s->s_hostsig.hs_sig);
6073 return s->s_hostsig.hs_sig;
6076 /* signature is expired: clear it */
6077 sm_free(s->s_hostsig.hs_sig);
6078 s->s_hostsig.hs_sig = NULL;
6081 /* set default TTL */
6082 s->s_hostsig.hs_exp = now + SM_DEFAULT_TTL;
6085 ** Not already there or expired -- create a signature.
6089 if (ConfigLevel < 2)
6090 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */
6092 for (hp = host; hp != NULL; hp = endp)
6097 endp = strchr(hp + 1, ']');
6099 endp = strpbrk(endp + 1, ":,");
6102 endp = strpbrk(hp, ":,");
6103 # else /* NETINET6 */
6104 endp = strpbrk(hp, ":,");
6105 # endif /* NETINET6 */
6112 if (bitnset(M_NOMX, m->m_flags))
6114 /* skip MX lookups */
6124 nmx = getmxrr(hp, mxhosts, mxprefs,
6125 DROPLOCALHOST|TRYFALLBACK|(ad ? ISAD :0),
6126 &rcode, &ttl, M_PORT(m));
6132 /* update the connection info for this host */
6134 mci = mci_get(hp, m);
6135 mci->mci_errno = save_errno;
6136 mci->mci_herrno = h_errno;
6137 mci->mci_lastuse = now;
6139 mci_setstat(mci, rcode, "5.7.27",
6140 "550 Host does not accept mail");
6141 else if (rcode == EX_NOHOST)
6142 mci_setstat(mci, rcode, "5.1.2",
6143 "550 Host unknown");
6145 mci_setstat(mci, rcode, NULL, NULL);
6147 /* use the original host name as signature */
6152 sm_dprintf("hostsignature(): getmxrr() returned %d, mxhosts[0]=%s\n",
6156 ** Set new TTL: we use only one!
6157 ** We could try to use the minimum instead.
6160 s->s_hostsig.hs_exp = now + SM_MIN(ttl, SM_DEFAULT_TTL);
6164 for (i = 0; i < nmx; i++)
6165 len += strlen(mxhosts[i]) + 1;
6166 if (s->s_hostsig.hs_sig != NULL)
6167 len += strlen(s->s_hostsig.hs_sig) + 1;
6168 if (len < 0 || len >= MAXHOSTSIGNATURE)
6170 sm_syslog(LOG_WARNING, NOQID, "hostsignature for host '%s' exceeds maxlen (%d): %d",
6171 host, MAXHOSTSIGNATURE, len);
6172 len = MAXHOSTSIGNATURE;
6174 p = sm_pmalloc_x(len);
6175 if (s->s_hostsig.hs_sig != NULL)
6177 (void) sm_strlcpy(p, s->s_hostsig.hs_sig, len);
6178 sm_free(s->s_hostsig.hs_sig); /* XXX */
6179 s->s_hostsig.hs_sig = p;
6186 s->s_hostsig.hs_sig = p;
6187 for (i = 0; i < nmx; i++)
6189 hl = strlen(mxhosts[i]);
6190 if (len - 1 < hl || len <= 1)
6192 /* force to drop out of outer loop */
6198 if (mxprefs[i] == mxprefs[i - 1])
6204 (void) sm_strlcpy(p, mxhosts[i], len);
6210 ** break out of loop if len exceeded MAXHOSTSIGNATURE
6211 ** because we won't have more space for further hosts
6212 ** anyway (separated by : in the .cf file).
6221 makelower(s->s_hostsig.hs_sig);
6222 if (ConfigLevel < 2)
6223 _res.options = oldoptions;
6224 #else /* NAMED_BIND */
6225 /* not using BIND -- the signature is just the host name */
6227 ** 'host' points to storage that will be freed after we are
6228 ** done processing the current envelope, so we copy it.
6230 s->s_hostsig.hs_sig = sm_pstrdup_x(host);
6231 #endif /* NAMED_BIND */
6233 sm_dprintf("hostsignature(%s) = %s\n", host, s->s_hostsig.hs_sig);
6234 return s->s_hostsig.hs_sig;
6237 ** PARSE_HOSTSIGNATURE -- parse the "signature" and return MX host array.
6239 ** The signature describes how we are going to send this -- it
6240 ** can be just the hostname (for non-Internet hosts) or can be
6241 ** an ordered list of MX hosts which must be randomized for equal
6242 ** MX preference values.
6245 ** sig -- the host signature.
6246 ** mxhosts -- array to populate.
6247 ** mailer -- mailer.
6250 ** The number of hosts inserted into mxhosts array.
6253 ** Randomizes equal MX preference hosts in mxhosts.
6257 parse_hostsignature(sig, mxhosts, mailer)
6262 unsigned short curpref = 0;
6263 int nmx = 0, i, j; /* NOTE: i, j, and nmx must have same type */
6265 unsigned short prefer[MAXMXHOSTS];
6266 long rndm[MAXMXHOSTS];
6268 for (hp = sig; hp != NULL; hp = endp)
6275 endp = strchr(hp + 1, ']');
6277 endp = strpbrk(endp + 1, ":,");
6280 endp = strpbrk(hp, ":,");
6281 #else /* NETINET6 */
6282 endp = strpbrk(hp, ":,");
6283 #endif /* NETINET6 */
6291 prefer[nmx] = curpref;
6292 if (mci_match(hp, mailer))
6295 rndm[nmx] = get_random();
6300 ** Since we don't have the original MX prefs,
6301 ** make our own. If the separator is a ':', that
6302 ** means the preference for the next host will be
6303 ** higher than this one, so simply increment curpref.
6311 if (++nmx >= MAXMXHOSTS)
6315 /* sort the records using the random factor for equal preferences */
6316 for (i = 0; i < nmx; i++)
6318 for (j = i + 1; j < nmx; j++)
6321 ** List is already sorted by MX preference, only
6322 ** need to look for equal preference MX records
6325 if (prefer[i] < prefer[j])
6328 if (prefer[i] > prefer[j] ||
6329 (prefer[i] == prefer[j] && rndm[i] > rndm[j]))
6331 register unsigned short tempp;
6332 register long tempr;
6333 register char *temp1;
6336 prefer[i] = prefer[j];
6339 mxhosts[i] = mxhosts[j];
6351 static SSL_CTX *clt_ctx = NULL;
6352 static bool tls_ok_clt = true;
6355 ** SETCLTTLS -- client side TLS: allow/disallow.
6358 ** tls_ok -- should tls be done?
6364 ** sets tls_ok_clt (static variable in this module)
6371 tls_ok_clt = tls_ok;
6375 ** INITCLTTLS -- initialize client side TLS
6378 ** tls_ok -- should tls initialization be done?
6384 ** sets tls_ok_clt (static variable in this module)
6393 tls_ok_clt = tls_ok;
6396 if (clt_ctx != NULL)
6397 return true; /* already done */
6398 tls_ok_clt = inittls(&clt_ctx, TLS_I_CLT, Clt_SSL_Options, false,
6399 CltCertFile, CltKeyFile,
6401 (CltCACertPath != NULL) ? CltCACertPath :
6405 (CltCACertFile != NULL) ? CltCACertFile :
6413 ** STARTTLS -- try to start secure connection (client side)
6417 ** mci -- the mailer connection info.
6418 ** e -- the envelope.
6422 ** (maybe this should be some other code than EX_
6423 ** that denotes which stage failed.)
6436 dane_vrfy_ctx_P dane_vrfy_ctx;
6442 SSL *clt_ssl = NULL;
6444 extern int TLSsslidx;
6446 if (clt_ctx == NULL && !initclttls(true))
6449 if (!TLS_set_engine(SSLEngine, false))
6451 sm_syslog(LOG_ERR, NOQID,
6452 "STARTTLS=client, engine=%s, TLS_set_engine=failed",
6457 smtpmessage("STARTTLS", m, mci);
6460 smtpresult = reply(m, mci, e, TimeOuts.to_starttls, NULL, NULL,
6463 /* check return code from server */
6464 if (REPLYTYPE(smtpresult) == 4)
6466 if (smtpresult == 501)
6468 if (smtpresult == -1)
6471 /* not an expected reply but we have to deal with it */
6472 if (REPLYTYPE(smtpresult) == 5)
6473 return EX_UNAVAILABLE;
6474 if (smtpresult != 220)
6478 sm_syslog(LOG_INFO, NOQID, "STARTTLS=client, start=ok");
6480 /* start connection */
6481 if ((clt_ssl = SSL_new(clt_ctx)) == NULL)
6485 sm_syslog(LOG_ERR, NOQID,
6486 "STARTTLS=client, error: SSL_new failed");
6487 tlslogerr(LOG_WARNING, 9, "client");
6491 /* SSL_clear(clt_ssl); ? */
6493 if (get_tls_se_options(e, clt_ssl, &mci->mci_tlsi, false) != 0)
6495 sm_syslog(LOG_ERR, NOQID,
6496 "STARTTLS=client, get_tls_se_options=fail");
6499 result = SSL_set_ex_data(clt_ssl, TLSsslidx, &mci->mci_tlsi);
6504 sm_syslog(LOG_ERR, NOQID,
6505 "STARTTLS=client, error: SSL_set_ex_data failed=%d, idx=%d",
6507 tlslogerr(LOG_WARNING, 9, "client");
6512 if (SM_TLSI_IS(&(mci->mci_tlsi), TLSI_FL_NODANE))
6513 dane_vrfy_ctx->dane_vrfy_chk = DANE_NEVER;
6518 # define SM_IS_EMPTY(s) (NULL == (s) || '\0' == *(s))
6520 /* set SNI only if there is a TLSA RR */
6521 if (dane_get_tlsa(dane_vrfy_ctx) != NULL &&
6522 !(SM_IS_EMPTY(dane_vrfy_ctx->dane_vrfy_host) &&
6523 SM_IS_EMPTY(dane_vrfy_ctx->dane_vrfy_sni)) &&
6524 (r = SSL_set_tlsext_host_name(clt_ssl,
6525 (!SM_IS_EMPTY(dane_vrfy_ctx->dane_vrfy_sni)
6526 ? dane_vrfy_ctx->dane_vrfy_sni
6527 : dane_vrfy_ctx->dane_vrfy_host))) <= 0)
6531 sm_syslog(LOG_ERR, NOQID,
6532 "STARTTLS=client, host=%s, SSL_set_tlsext_host_name=%d",
6533 dane_vrfy_ctx->dane_vrfy_host, r);
6535 tlslogerr(LOG_ERR, 5, "client");
6536 /* return EX_SOFTWARE; */
6539 memcpy(&mci->mci_tlsi.tlsi_dvc, dane_vrfy_ctx, sizeof(*dane_vrfy_ctx));
6542 rfd = sm_io_getinfo(mci->mci_in, SM_IO_WHAT_FD, NULL);
6543 wfd = sm_io_getinfo(mci->mci_out, SM_IO_WHAT_FD, NULL);
6545 if (rfd < 0 || wfd < 0 ||
6546 (result = SSL_set_rfd(clt_ssl, rfd)) != 1 ||
6547 (result = SSL_set_wfd(clt_ssl, wfd)) != 1)
6551 sm_syslog(LOG_ERR, NOQID,
6552 "STARTTLS=client, error: SSL_set_xfd failed=%d",
6554 tlslogerr(LOG_WARNING, 9, "client");
6558 SSL_set_connect_state(clt_ssl);
6559 tlsstart = curtime();
6562 if ((result = SSL_connect(clt_ssl)) <= 0)
6565 int save_errno = errno;
6567 ssl_err = SSL_get_error(clt_ssl, result);
6568 i = tls_retry(clt_ssl, rfd, wfd, tlsstart,
6569 TimeOuts.to_starttls, ssl_err, "client");
6578 l = ERR_peek_error();
6579 sr = ERR_reason_error_string(l);
6580 sm_syslog(LOG_WARNING, NOQID,
6581 "STARTTLS=client, error: connect failed=%d, reason=%s, SSL_error=%d, errno=%d, retry=%d",
6582 result, sr == NULL ? "unknown" : sr, ssl_err,
6584 tlslogerr(LOG_WARNING, 9, "client");
6587 SM_SSL_FREE(clt_ssl);
6590 mci->mci_ssl = clt_ssl;
6591 result = tls_get_info(mci->mci_ssl, false, mci->mci_host,
6592 &mci->mci_macro, true);
6594 /* switch to use TLS... */
6595 if (sfdctls(&mci->mci_in, &mci->mci_out, mci->mci_ssl) == 0)
6599 SM_SSL_FREE(clt_ssl);
6603 ** ENDTLSCLT -- shutdown secure connection (client side)
6606 ** mci -- the mailer connection info.
6618 if (!bitset(MCIF_TLSACT, mci->mci_flags))
6620 r = endtls(&mci->mci_ssl, "client");
6621 mci->mci_flags &= ~MCIF_TLSACT;
6624 #endif /* STARTTLS */
6625 #if STARTTLS || SASL
6627 ** ISCLTFLGSET -- check whether client flag is set.
6631 ** flag -- flag to check in {client_flags}
6634 ** true iff flag is set.
6638 iscltflgset(e, flag)
6644 p = macvalue(macid("{client_flags}"), e);
6647 for (; *p != '\0'; p++)
6649 /* look for just this one flag */
6650 if (*p == (char) flag)
6655 #endif /* STARTTLS || SASL */