2 * Copyright (c) 1998-2006 Sendmail, 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.1003.2.1 2006/05/23 01:32:08 ca Exp $")
20 # include <login_cap.h>
21 #endif /* HASSETUSERCONTEXT */
23 #if NETINET || NETINET6
24 # include <arpa/inet.h>
25 #endif /* NETINET || NETINET6 */
29 #endif /* STARTTLS || SASL */
31 static int deliver __P((ENVELOPE *, ADDRESS *));
32 static void dup_queue_file __P((ENVELOPE *, ENVELOPE *, int));
33 static void mailfiletimeout __P((int));
34 static void endwaittimeout __P((int));
35 static int parse_hostsignature __P((char *, char **, MAILER *));
36 static void sendenvelope __P((ENVELOPE *, int));
37 extern MCI *mci_new __P((SM_RPOOL_T *));
38 static int coloncmp __P((const char *, const char *));
41 static int starttls __P((MAILER *, MCI *, ENVELOPE *));
42 static int endtlsclt __P((MCI *));
45 static bool iscltflgset __P((ENVELOPE *, int));
46 # endif /* STARTTLS || SASL */
49 ** SENDALL -- actually send all the messages.
52 ** e -- the envelope to send.
53 ** mode -- the delivery mode to use. If SM_DEFAULT, use
54 ** the current e->e_sendmode.
60 ** Scans the send lists and sends everything it finds.
61 ** Delivers any appropriate error messages.
62 ** If we are running in a non-interactive mode, takes the
63 ** appropriate action.
75 register ENVELOPE *ee;
76 ENVELOPE *splitenv = NULL;
77 int oldverbose = Verbose;
78 bool somedeliveries = false, expensive = false;
82 ** If this message is to be discarded, don't bother sending
83 ** the message at all.
86 if (bitset(EF_DISCARD, e->e_flags))
89 sm_dprintf("sendall: discarding id %s\n", e->e_id);
90 e->e_flags |= EF_CLRQUEUE;
92 logundelrcpts(e, "discarded", 9, true);
93 else if (LogLevel > 4)
94 sm_syslog(LOG_INFO, e->e_id, "discarded");
95 markstats(e, NULL, STATS_REJECT);
100 ** If we have had global, fatal errors, don't bother sending
101 ** the message at all if we are in SMTP mode. Local errors
102 ** (e.g., a single address failing) will still cause the other
103 ** addresses to be sent.
106 if (bitset(EF_FATALERRS, e->e_flags) &&
107 (OpMode == MD_SMTP || OpMode == MD_DAEMON))
109 e->e_flags |= EF_CLRQUEUE;
113 /* determine actual delivery mode */
114 if (mode == SM_DEFAULT)
116 mode = e->e_sendmode;
117 if (mode != SM_VERIFY && mode != SM_DEFER &&
118 shouldqueue(e->e_msgpriority, e->e_ctime))
124 sm_dprintf("\n===== SENDALL: mode %c, id %s, e_from ",
126 printaddr(sm_debug_file(), &e->e_from, false);
127 sm_dprintf("\te_flags = ");
129 sm_dprintf("sendqueue:\n");
130 printaddr(sm_debug_file(), e->e_sendqueue, true);
134 ** Do any preprocessing necessary for the mode we are running.
135 ** Check to make sure the hop count is reasonable.
136 ** Delete sends to the sender in mailing lists.
143 if (e->e_hopcount > MaxHopCount)
147 if (e->e_sendqueue != NULL &&
148 e->e_sendqueue->q_paddr != NULL)
149 recip = e->e_sendqueue->q_paddr;
154 queueup(e, WILL_BE_QUEUED(mode), false);
155 e->e_flags |= EF_FATALERRS|EF_PM_NOTIFY|EF_CLRQUEUE;
156 ExitStat = EX_UNAVAILABLE;
157 syserr("554 5.4.6 Too many hops %d (%d max): from %s via %s, to %s",
158 e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
159 RealHostName == NULL ? "localhost" : RealHostName,
161 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
163 if (QS_IS_DEAD(q->q_state))
165 q->q_state = QS_BADADDR;
166 q->q_status = "5.4.6";
167 q->q_rstatus = "554 5.4.6 Too many hops";
173 ** Do sender deletion.
175 ** If the sender should be queued up, skip this.
176 ** This can happen if the name server is hosed when you
177 ** are trying to send mail. The result is that the sender
178 ** is instantiated in the queue as a recipient.
181 if (!bitset(EF_METOO, e->e_flags) &&
182 !QS_IS_QUEUEUP(e->e_from.q_state))
186 sm_dprintf("sendall: QS_SENDER ");
187 printaddr(sm_debug_file(), &e->e_from, false);
189 e->e_from.q_state = QS_SENDER;
190 (void) recipient(&e->e_from, &e->e_sendqueue, 0, e);
194 ** Handle alias owners.
196 ** We scan up the q_alias chain looking for owners.
197 ** We discard owners that are the same as the return path.
200 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
202 register struct address *a;
204 for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias)
207 q->q_owner = a->q_owner;
209 if (q->q_owner != NULL &&
210 !QS_IS_DEAD(q->q_state) &&
211 strcmp(q->q_owner, e->e_from.q_paddr) == 0)
217 sm_dprintf("\nAfter first owner pass, sendq =\n");
218 printaddr(sm_debug_file(), e->e_sendqueue, true);
223 while (owner != NULL && otherowners > 0)
226 sm_dprintf("owner = \"%s\", otherowners = %d\n",
229 otherowners = bitset(EF_SENDRECEIPT, e->e_flags) ? 1 : 0;
231 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
235 sm_dprintf("Checking ");
236 printaddr(sm_debug_file(), q, false);
238 if (QS_IS_DEAD(q->q_state))
241 sm_dprintf(" ... QS_IS_DEAD\n");
244 if (tTd(13, 29) && !tTd(13, 30))
246 sm_dprintf("Checking ");
247 printaddr(sm_debug_file(), q, false);
250 if (q->q_owner != NULL)
255 sm_dprintf(" ... First owner = \"%s\"\n",
259 else if (owner != q->q_owner)
261 if (strcmp(owner, q->q_owner) == 0)
264 sm_dprintf(" ... Same owner = \"%s\"\n",
267 /* make future comparisons cheap */
273 sm_dprintf(" ... Another owner \"%s\"\n",
279 else if (tTd(13, 40))
280 sm_dprintf(" ... Same owner = \"%s\"\n",
286 sm_dprintf(" ... Null owner\n");
290 if (QS_IS_BADADDR(q->q_state))
293 sm_dprintf(" ... QS_IS_BADADDR\n");
297 if (QS_IS_QUEUEUP(q->q_state))
299 MAILER *m = q->q_mailer;
302 ** If we have temporary address failures
303 ** (e.g., dns failure) and a fallback MX is
304 ** set, send directly to the fallback MX host.
307 if (FallbackMX != NULL &&
308 !wordinclass(FallbackMX, 'w') &&
310 !bitnset(M_NOMX, m->m_flags) &&
311 strcmp(m->m_mailer, "[IPC]") == 0 &&
312 m->m_argv[0] != NULL &&
313 strcmp(m->m_argv[0], "TCP") == 0)
319 sm_dprintf(" ... FallbackMX\n");
321 len = strlen(FallbackMX) + 1;
322 p = sm_rpool_malloc_x(e->e_rpool, len);
323 (void) sm_strlcpy(p, FallbackMX, len);
330 sm_dprintf(" ... QS_IS_QUEUEUP\n");
336 ** If this mailer is expensive, and if we don't
337 ** want to make connections now, just mark these
338 ** addresses and return. This is useful if we
339 ** want to batch connections to reduce load. This
340 ** will cause the messages to be queued up, and a
341 ** daemon will come along to send the messages later.
344 if (NoConnect && !Verbose &&
345 bitnset(M_EXPENSIVE, q->q_mailer->m_flags))
348 sm_dprintf(" ... expensive\n");
349 q->q_state = QS_QUEUEUP;
352 else if (bitnset(M_HOLD, q->q_mailer->m_flags) &&
353 QueueLimitId == NULL &&
354 QueueLimitSender == NULL &&
355 QueueLimitRecipient == NULL)
358 sm_dprintf(" ... hold\n");
359 q->q_state = QS_QUEUEUP;
362 else if (QueueMode != QM_QUARANTINE &&
363 e->e_quarmsg != NULL)
366 sm_dprintf(" ... quarantine: %s\n",
368 q->q_state = QS_QUEUEUP;
374 sm_dprintf(" ... deliverable\n");
375 somedeliveries = true;
379 if (owner != NULL && otherowners > 0)
382 ** Split this envelope into two.
385 ee = (ENVELOPE *) sm_rpool_malloc_x(e->e_rpool,
388 ee->e_message = NULL;
393 sm_dprintf("sendall: split %s into %s, owner = \"%s\", otherowners = %d\n",
394 e->e_id, ee->e_id, owner,
397 ee->e_header = copyheader(e->e_header, ee->e_rpool);
398 ee->e_sendqueue = copyqueue(e->e_sendqueue,
400 ee->e_errorqueue = copyqueue(e->e_errorqueue,
402 ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS|EF_SENDRECEIPT|EF_RET_PARAM);
403 ee->e_flags |= EF_NORECEIPT;
404 setsender(owner, ee, NULL, '\0', true);
407 sm_dprintf("sendall(split): QS_SENDER ");
408 printaddr(sm_debug_file(), &ee->e_from, false);
410 ee->e_from.q_state = QS_SENDER;
414 ee->e_qgrp = e->e_qgrp;
415 ee->e_qdir = e->e_qdir;
416 ee->e_errormode = EM_MAIL;
417 ee->e_sibling = splitenv;
418 ee->e_statmsg = NULL;
419 if (e->e_quarmsg != NULL)
420 ee->e_quarmsg = sm_rpool_strdup_x(ee->e_rpool,
424 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
426 if (q->q_owner == owner)
428 q->q_state = QS_CLONED;
430 sm_dprintf("\t... stripping %s from original envelope\n",
434 for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
436 if (q->q_owner != owner)
438 q->q_state = QS_CLONED;
440 sm_dprintf("\t... dropping %s from cloned envelope\n",
445 /* clear DSN parameters */
446 q->q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS);
447 q->q_flags |= DefaultNotify & ~QPINGONSUCCESS;
449 sm_dprintf("\t... moving %s to cloned envelope\n",
454 if (mode != SM_VERIFY && bitset(EF_HAS_DF, e->e_flags))
455 dup_queue_file(e, ee, DATAFL_LETTER);
458 ** Give the split envelope access to the parent
459 ** transcript file for errors obtained while
460 ** processing the recipients (done before the
461 ** envelope splitting).
464 if (e->e_xfp != NULL)
465 ee->e_xfp = sm_io_dup(e->e_xfp);
467 /* failed to dup e->e_xfp, start a new transcript */
468 if (ee->e_xfp == NULL)
471 if (mode != SM_VERIFY && LogLevel > 4)
472 sm_syslog(LOG_INFO, e->e_id,
473 "%s: clone: owner=%s",
480 setsender(owner, e, NULL, '\0', true);
483 sm_dprintf("sendall(owner): QS_SENDER ");
484 printaddr(sm_debug_file(), &e->e_from, false);
486 e->e_from.q_state = QS_SENDER;
487 e->e_errormode = EM_MAIL;
488 e->e_flags |= EF_NORECEIPT;
489 e->e_flags &= ~EF_FATALERRS;
492 /* if nothing to be delivered, just queue up everything */
493 if (!somedeliveries && !WILL_BE_QUEUED(mode) &&
499 sm_dprintf("No deliveries: auto-queuing\n");
503 /* treat this as a delivery in terms of counting tries */
507 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
515 if ((WILL_BE_QUEUED(mode) || mode == SM_FORK ||
516 (mode != SM_VERIFY &&
517 (SuperSafe == SAFE_REALLY ||
518 SuperSafe == SAFE_REALLY_POSTMILTER))) &&
519 (!bitset(EF_INQUEUE, e->e_flags) || splitenv != NULL))
524 ** Be sure everything is instantiated in the queue.
525 ** Split envelopes first in case the machine crashes.
526 ** If the original were done first, we may lose
532 #else /* !HASFLOCK */
533 msync = mode == SM_FORK;
534 #endif /* !HASFLOCK */
536 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
537 queueup(ee, WILL_BE_QUEUED(mode), msync);
538 queueup(e, WILL_BE_QUEUED(mode), msync);
542 checkfds("after envelope splitting");
545 ** If we belong in background, fork now.
550 sm_dprintf("sendall: final mode = %c\n", mode);
553 sm_dprintf("\n================ Final Send Queue(s) =====================\n");
554 sm_dprintf("\n *** Envelope %s, e_from=%s ***\n",
555 e->e_id, e->e_from.q_paddr);
556 printaddr(sm_debug_file(), e->e_sendqueue, true);
557 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
559 sm_dprintf("\n *** Envelope %s, e_from=%s ***\n",
560 ee->e_id, ee->e_from.q_paddr);
561 printaddr(sm_debug_file(), ee->e_sendqueue, true);
563 sm_dprintf("==========================================================\n\n");
576 #endif /* HASFLOCK */
578 e->e_flags |= EF_INQUEUE;
579 dropenvelope(e, splitenv != NULL, true);
580 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
582 if (ee->e_nrcpts > 0)
583 ee->e_flags |= EF_INQUEUE;
584 dropenvelope(ee, false, true);
589 if (e->e_xfp != NULL)
590 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
594 ** Since fcntl locking has the interesting semantic that
595 ** the lock is owned by a process, not by an open file
596 ** descriptor, we have to flush this to the queue, and
597 ** then restart from scratch in the child.
601 /* save id for future use */
604 /* now drop the envelope in the parent */
605 e->e_flags |= EF_INQUEUE;
606 dropenvelope(e, splitenv != NULL, false);
608 /* arrange to reacquire lock after fork */
612 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
614 /* save id for future use */
615 char *qid = ee->e_id;
617 /* drop envelope in parent */
618 ee->e_flags |= EF_INQUEUE;
619 dropenvelope(ee, false, false);
621 /* and save qid for reacquisition */
625 #endif /* !HASFLOCK */
628 ** Since the delivery may happen in a child and the parent
629 ** does not wait, the parent may close the maps thereby
630 ** removing any shared memory used by the map. Therefore,
631 ** close the maps now so the child will dynamically open
632 ** them if necessary.
640 syserr("deliver: fork 1");
645 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
648 #endif /* HASFLOCK */
653 /* be sure we leave the temp files to our child */
654 /* close any random open files in the envelope */
656 if (e->e_dfp != NULL)
657 (void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
659 e->e_flags &= ~EF_HAS_DF;
661 /* can't call unlockqueue to avoid unlink of xfp */
662 if (e->e_lockfp != NULL)
663 (void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT);
665 syserr("%s: sendall: null lockfp", e->e_id);
667 #endif /* HASFLOCK */
669 /* make sure the parent doesn't own the envelope */
673 /* catch intermediate zombie */
675 #endif /* USE_DOUBLE_FORK */
679 /* Reset global flags */
680 RestartRequest = NULL;
681 RestartWorkGroup = false;
682 ShutdownRequest = NULL;
686 ** Initialize exception stack and default exception
687 ** handler for child process.
690 sm_exc_newthread(fatal_error);
693 ** Since we have accepted responsbility for the message,
694 ** change the SIGTERM handler. intsig() (the old handler)
695 ** would remove the envelope if this was a command line
696 ** message submission.
699 (void) sm_signal(SIGTERM, SIG_DFL);
702 /* double fork to avoid zombies */
707 #endif /* USE_DOUBLE_FORK */
709 CurrentPid = getpid();
711 /* be sure we are immune from the terminal */
715 /* prevent parent from waiting if there was an error */
719 syserr("deliver: fork 2");
721 e->e_flags |= EF_INQUEUE;
724 #endif /* HASFLOCK */
725 finis(true, true, ExitStat);
728 /* be sure to give error messages in child */
732 ** Close any cached connections.
734 ** We don't send the QUIT protocol because the parent
735 ** still knows about the connection.
737 ** This should only happen when delivering an error
741 mci_flush(false, NULL);
748 ** Now reacquire and run the various queue files.
751 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
753 ENVELOPE *sibling = ee->e_sibling;
755 (void) dowork(ee->e_qgrp, ee->e_qdir, ee->e_id,
757 ee->e_sibling = sibling;
759 (void) dowork(e->e_qgrp, e->e_qdir, e->e_id,
761 finis(true, true, ExitStat);
762 #endif /* HASFLOCK */
765 sendenvelope(e, mode);
766 dropenvelope(e, true, true);
767 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
770 if (mode != SM_VERIFY)
772 sendenvelope(ee, mode);
773 dropenvelope(ee, true, true);
777 Verbose = oldverbose;
779 finis(true, true, ExitStat);
783 sendenvelope(e, mode)
784 register ENVELOPE *e;
791 sm_dprintf("sendenvelope(%s) e_flags=0x%lx\n",
792 e->e_id == NULL ? "[NOQUEUE]" : e->e_id,
795 sm_syslog(LOG_DEBUG, e->e_id,
796 "sendenvelope, flags=0x%lx",
800 ** If we have had global, fatal errors, don't bother sending
801 ** the message at all if we are in SMTP mode. Local errors
802 ** (e.g., a single address failing) will still cause the other
803 ** addresses to be sent.
806 if (bitset(EF_FATALERRS, e->e_flags) &&
807 (OpMode == MD_SMTP || OpMode == MD_DAEMON))
809 e->e_flags |= EF_CLRQUEUE;
814 ** Don't attempt deliveries if we want to bounce now
815 ** or if deliver-by time is exceeded.
818 if (!bitset(EF_RESPONSE, e->e_flags) &&
819 (TimeOuts.to_q_return[e->e_timeoutclass] == NOW ||
820 (IS_DLVR_RETURN(e) && e->e_deliver_by > 0 &&
821 curtime() > e->e_ctime + e->e_deliver_by)))
825 ** Run through the list and send everything.
827 ** Set EF_GLOBALERRS so that error messages during delivery
828 ** result in returned mail.
832 e->e_flags |= EF_GLOBALERRS;
834 macdefine(&e->e_macro, A_PERM, macid("{envid}"), e->e_envid);
835 macdefine(&e->e_macro, A_PERM, macid("{bodytype}"), e->e_bodytype);
838 if (!bitset(EF_SPLIT, e->e_flags))
844 ** Save old sibling and set it to NULL to avoid
845 ** queueing up the same envelopes again.
846 ** This requires that envelopes in that list have
847 ** been take care of before (or at some other place).
850 oldsib = e->e_sibling;
852 if (!split_by_recipient(e) &&
853 bitset(EF_FATALERRS, e->e_flags))
855 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
856 e->e_flags |= EF_CLRQUEUE;
859 for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
860 queueup(ee, false, true);
863 for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
865 /* now unlock the job */
869 /* this envelope is marked unused */
870 if (ee->e_dfp != NULL)
872 (void) sm_io_close(ee->e_dfp, SM_TIME_DEFAULT);
876 ee->e_flags &= ~EF_HAS_DF;
878 e->e_sibling = oldsib;
881 /* now run through the queue */
882 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
885 char wbuf[MAXNAME + 20];
887 (void) sm_snprintf(wbuf, sizeof wbuf, "sendall(%.*s)",
888 MAXNAME, q->q_paddr);
891 if (mode == SM_VERIFY)
893 e->e_to = q->q_paddr;
894 if (QS_IS_SENDABLE(q->q_state))
896 if (q->q_host != NULL && q->q_host[0] != '\0')
897 message("deliverable: mailer %s, host %s, user %s",
902 message("deliverable: mailer %s, user %s",
907 else if (QS_IS_OK(q->q_state))
910 ** Checkpoint the send list every few addresses
913 if (CheckpointInterval > 0 &&
914 e->e_nsent >= CheckpointInterval)
916 queueup(e, false, false);
919 (void) deliver(e, q);
925 e->e_dtime = curtime();
930 checkfd012("end of sendenvelope");
934 #if REQUIRES_DIR_FSYNC
936 ** SYNC_DIR -- fsync a directory based on a filename
939 ** filename -- path of file
947 sync_dir(filename, panic)
953 char dir[MAXPATHLEN];
955 if (!RequiresDirfsync)
958 /* filesystems which require the directory be synced */
959 dirp = strrchr(filename, '/');
962 if (sm_strlcpy(dir, filename, sizeof dir) >= sizeof dir)
964 dir[dirp - filename] = '\0';
969 dirfd = open(dirp, O_RDONLY, 0700);
971 sm_syslog(LOG_INFO, NOQID, "sync_dir: %s: fsync(%d)",
975 if (fsync(dirfd) < 0)
978 syserr("!sync_dir: cannot fsync directory %s",
980 else if (LogLevel > 1)
981 sm_syslog(LOG_ERR, NOQID,
982 "sync_dir: cannot fsync directory %s: %s",
983 dirp, sm_errstring(errno));
988 #endif /* REQUIRES_DIR_FSYNC */
990 ** DUP_QUEUE_FILE -- duplicate a queue file into a split queue
993 ** e -- the existing envelope
994 ** ee -- the new envelope
995 ** type -- the queue file type (e.g., DATAFL_LETTER)
1002 dup_queue_file(e, ee, type)
1006 char f1buf[MAXPATHLEN], f2buf[MAXPATHLEN];
1012 ** Make sure both are in the same directory.
1015 (void) sm_strlcpy(f1buf, queuename(e, type), sizeof f1buf);
1016 (void) sm_strlcpy(f2buf, queuename(ee, type), sizeof f2buf);
1018 /* Force the df to disk if it's not there yet */
1019 if (type == DATAFL_LETTER && e->e_dfp != NULL &&
1020 sm_io_setinfo(e->e_dfp, SM_BF_COMMIT, NULL) < 0 &&
1023 syserr("!dup_queue_file: can't commit %s", f1buf);
1027 if (link(f1buf, f2buf) < 0)
1029 int save_errno = errno;
1031 syserr("sendall: link(%s, %s)", f1buf, f2buf);
1032 if (save_errno == EEXIST)
1034 if (unlink(f2buf) < 0)
1036 syserr("!sendall: unlink(%s): permanent",
1040 if (link(f1buf, f2buf) < 0)
1042 syserr("!sendall: link(%s, %s): permanent",
1048 SYNC_DIR(f2buf, true);
1051 ** DOFORK -- do a fork, retrying a couple of times on failure.
1053 ** This MUST be a macro, since after a vfork we are running
1054 ** two processes on the same stack!!!
1060 ** From a macro??? You've got to be kidding!
1063 ** Modifies the ==> LOCAL <== variable 'pid', leaving:
1064 ** pid of child in parent, zero in child.
1065 ** -1 on unrecoverable error.
1068 ** I'm awfully sorry this looks so awful. That's
1069 ** vfork for you.....
1072 #define NFORKTRIES 5
1078 #define DOFORK(fORKfN) \
1082 for (i = NFORKTRIES; --i >= 0; )\
1088 (void) sleep((unsigned) NFORKTRIES - i);\
1092 ** DOFORK -- simple fork interface to DOFORK.
1098 ** pid of child in parent.
1103 ** returns twice, once in parent and once in child.
1109 register pid_t pid = -1;
1116 ** COLONCMP -- compare host-signatures up to first ':' or EOS
1118 ** This takes two strings which happen to be host-signatures and
1119 ** compares them. If the lowest preference portions of the MX-RR's
1120 ** match (up to ':' or EOS, whichever is first), then we have
1121 ** match. This is used for coattail-piggybacking messages during
1122 ** message delivery.
1123 ** If the signatures are the same up to the first ':' the remainder of
1124 ** the signatures are then compared with a normal strcmp(). This saves
1125 ** re-examining the first part of the signatures.
1128 ** a - first host-signature
1129 ** b - second host-signature
1132 ** HS_MATCH_NO -- no "match".
1133 ** HS_MATCH_FIRST -- "match" for the first MX preference
1134 ** (up to the first colon (':')).
1135 ** HS_MATCH_FULL -- match for the entire MX record.
1141 #define HS_MATCH_NO 0
1142 #define HS_MATCH_FIRST 1
1143 #define HS_MATCH_FULL 2
1147 register const char *a;
1148 register const char *b;
1150 int ret = HS_MATCH_NO;
1155 /* Need to account for IPv6 bracketed addresses */
1158 else if (*a == ']' && braclev > 0)
1160 else if (*a == ':' && braclev <= 0)
1162 ret = HS_MATCH_FIRST;
1166 else if (*a == '\0')
1167 return HS_MATCH_FULL; /* a full match */
1170 if (ret == HS_MATCH_NO &&
1172 ((*a == '\0' && *(b - 1) == ':') ||
1173 (*a == ':' && *(b - 1) == '\0')))
1174 return HS_MATCH_FIRST;
1175 if (ret == HS_MATCH_FIRST && strcmp(a, b) == 0)
1176 return HS_MATCH_FULL;
1182 ** SHOULD_TRY_FBSH -- Should try FallbackSmartHost?
1186 ** tried_fallbacksmarthost -- has been tried already? (in/out)
1187 ** hostbuf -- buffer for hostname (expand FallbackSmartHost) (out)
1188 ** hbsz -- size of hostbuf
1189 ** status -- current delivery status
1192 ** true iff FallbackSmartHost should be tried.
1196 should_try_fbsh(e, tried_fallbacksmarthost, hostbuf, hbsz, status)
1198 bool *tried_fallbacksmarthost;
1204 ** If the host was not found or a temporary failure occurred
1205 ** and a FallbackSmartHost is defined (and we have not yet
1206 ** tried it), then make one last try with it as the host.
1209 if ((status == EX_NOHOST || status == EX_TEMPFAIL) &&
1210 FallbackSmartHost != NULL && !*tried_fallbacksmarthost)
1212 *tried_fallbacksmarthost = true;
1213 expand(FallbackSmartHost, hostbuf, hbsz, e);
1214 if (!wordinclass(hostbuf, 'w'))
1217 sm_dprintf("one last try with FallbackSmartHost %s\n",
1225 ** DELIVER -- Deliver a message to a list of addresses.
1227 ** This routine delivers to everyone on the same host as the
1228 ** user on the head of the list. It is clever about mailers
1229 ** that don't handle multiple users. It is NOT guaranteed
1230 ** that it will deliver to all these addresses however -- so
1231 ** deliver should be called once for each address on the
1233 ** Deliver tries to be as opportunistic as possible about piggybacking
1234 ** messages. Some definitions to make understanding easier follow below.
1235 ** Piggybacking occurs when an existing connection to a mail host can
1236 ** be used to send the same message to more than one recipient at the
1237 ** same time. So "no piggybacking" means one message for one recipient
1238 ** per connection. "Intentional piggybacking" happens when the
1239 ** recipients' host address (not the mail host address) is used to
1240 ** attempt piggybacking. Recipients with the same host address
1241 ** have the same mail host. "Coincidental piggybacking" relies on
1242 ** piggybacking based on all the mail host addresses in the MX-RR. This
1243 ** is "coincidental" in the fact it could not be predicted until the
1244 ** MX Resource Records for the hosts were obtained and examined. For
1245 ** example (preference order and equivalence is important, not values):
1246 ** domain1 IN MX 10 mxhost-A
1247 ** IN MX 20 mxhost-B
1248 ** domain2 IN MX 4 mxhost-A
1250 ** Domain1 and domain2 can piggyback the same message to mxhost-A or
1251 ** mxhost-B (if mxhost-A cannot be reached).
1252 ** "Coattail piggybacking" relaxes the strictness of "coincidental
1253 ** piggybacking" in the hope that most significant (lowest value)
1254 ** MX preference host(s) can create more piggybacking. For example
1255 ** (again, preference order and equivalence is important, not values):
1256 ** domain3 IN MX 100 mxhost-C
1257 ** IN MX 100 mxhost-D
1258 ** IN MX 200 mxhost-E
1259 ** domain4 IN MX 50 mxhost-C
1260 ** IN MX 50 mxhost-D
1261 ** IN MX 80 mxhost-F
1262 ** A message for domain3 and domain4 can piggyback to mxhost-C if mxhost-C
1263 ** is available. Same with mxhost-D because in both RR's the preference
1264 ** value is the same as mxhost-C, respectively.
1265 ** So deliver attempts coattail piggybacking when possible. If the
1266 ** first MX preference level hosts cannot be used then the piggybacking
1267 ** reverts to coincidental piggybacking. Using the above example you
1268 ** cannot deliver to mxhost-F for domain3 regardless of preference value.
1269 ** ("Coattail" from "riding on the coattails of your predecessor" meaning
1270 ** gaining benefit from a predecessor effort with no or little addition
1271 ** effort. The predecessor here being the preceding MX RR).
1274 ** e -- the envelope to deliver.
1275 ** firstto -- head of the address list to deliver to.
1278 ** zero -- successfully delivered.
1279 ** else -- some failure, see ExitStat for more info.
1282 ** The standard input is passed off to someone.
1287 register ENVELOPE *e;
1290 char *host; /* host being sent to */
1291 char *user; /* user being sent to */
1293 register char **mvp;
1295 register MAILER *m; /* mailer for this recipient */
1296 ADDRESS *volatile ctladdr;
1297 #if HASSETUSERCONTEXT
1298 ADDRESS *volatile contextaddr = NULL;
1299 #endif /* HASSETUSERCONTEXT */
1300 register MCI *volatile mci;
1301 register ADDRESS *SM_NONVOLATILE to = firstto;
1302 volatile bool clever = false; /* running user smtp to this mailer */
1303 ADDRESS *volatile tochain = NULL; /* users chain in this mailer call */
1304 int rcode; /* response code */
1305 SM_NONVOLATILE int lmtp_rcode = EX_OK;
1306 SM_NONVOLATILE int nummxhosts = 0; /* number of MX hosts available */
1307 SM_NONVOLATILE int hostnum = 0; /* current MX host index */
1308 char *firstsig; /* signature of firstto */
1309 volatile pid_t pid = -1;
1310 char *volatile curhost;
1311 SM_NONVOLATILE unsigned short port = 0;
1312 SM_NONVOLATILE time_t enough = 0;
1314 char *SM_NONVOLATILE mux_path = NULL; /* path to UNIX domain socket */
1315 #endif /* NETUNIX */
1318 bool anyok; /* at least one address was OK */
1319 SM_NONVOLATILE bool goodmxfound = false; /* at least one MX was OK */
1325 static int tobufsize = 0;
1326 static char *tobuf = NULL;
1327 char *rpath; /* translated return path */
1330 char *mxhosts[MAXMXHOSTS + 1];
1331 char *pv[MAXPV + 1];
1332 char buf[MAXNAME + 1];
1333 char cbuf[MAXPATHLEN];
1336 if (!QS_IS_OK(to->q_state))
1339 suidwarn = geteuid() == 0;
1343 CurEnv = e; /* just in case */
1344 e->e_statmsg = NULL;
1345 SmtpError[0] = '\0';
1349 sm_dprintf("\n--deliver, id=%s, mailer=%s, host=`%s', first user=`%s'\n",
1350 e->e_id, m->m_name, host, to->q_user);
1352 printopenfds(false);
1355 ** Clear {client_*} macros if this is a bounce message to
1356 ** prevent rejection by check_compat ruleset.
1359 if (bitset(EF_RESPONSE, e->e_flags))
1361 macdefine(&e->e_macro, A_PERM, macid("{client_name}"), "");
1362 macdefine(&e->e_macro, A_PERM, macid("{client_ptr}"), "");
1363 macdefine(&e->e_macro, A_PERM, macid("{client_addr}"), "");
1364 macdefine(&e->e_macro, A_PERM, macid("{client_port}"), "");
1365 macdefine(&e->e_macro, A_PERM, macid("{client_resolve}"), "");
1370 ADDRESS *skip_back = NULL;
1373 ** Do initial argv setup.
1374 ** Insert the mailer name. Notice that $x expansion is
1375 ** NOT done on the mailer name. Then, if the mailer has
1376 ** a picky -f flag, we insert it as appropriate. This
1377 ** code does not check for 'pv' overflow; this places a
1378 ** manifest lower limit of 4 for MAXPV.
1379 ** The from address rewrite is expected to make
1380 ** the address relative to the other end.
1383 /* rewrite from address, using rewriting rules */
1385 if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags))
1388 p = e->e_from.q_paddr;
1389 rpath = remotename(p, m, RF_SENDERADDR|RF_CANONICAL, &rcode, e);
1390 if (strlen(rpath) > MAXSHORTSTR)
1392 rpath = shortenstring(rpath, MAXSHORTSTR);
1394 /* avoid bogus errno */
1396 syserr("remotename: huge return path %s", rpath);
1398 rpath = sm_rpool_strdup_x(e->e_rpool, rpath);
1399 macdefine(&e->e_macro, A_PERM, 'g', rpath);
1400 macdefine(&e->e_macro, A_PERM, 'h', host);
1403 *pvp++ = m->m_argv[0];
1405 /* ignore long term host status information if mailer flag W is set */
1406 if (bitnset(M_NOHOSTSTAT, m->m_flags))
1407 IgnoreHostStatus = true;
1409 /* insert -f or -r flag as appropriate */
1411 (bitnset(M_FOPT, m->m_flags) ||
1412 bitnset(M_ROPT, m->m_flags)))
1414 if (bitnset(M_FOPT, m->m_flags))
1422 ** Append the other fixed parts of the argv. These run
1423 ** up to the first entry containing "$u". There can only
1424 ** be one of these, and there are only a few more slots
1425 ** in the pv after it.
1428 for (mvp = m->m_argv; (p = *++mvp) != NULL; )
1430 /* can't use strchr here because of sign extension problems */
1433 if ((*p++ & 0377) == MACROEXPAND)
1443 /* this entry is safe -- go ahead and process it */
1444 expand(*mvp, buf, sizeof buf, e);
1445 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1446 if (pvp >= &pv[MAXPV - 3])
1448 syserr("554 5.3.5 Too many parameters to %s before $u",
1456 ** If we have no substitution for the user name in the argument
1457 ** list, we know that we must supply the names otherwise -- and
1458 ** SMTP is the answer!!
1463 /* running LMTP or SMTP */
1467 else if (bitnset(M_LMTP, m->m_flags))
1469 /* not running LMTP */
1470 sm_syslog(LOG_ERR, NULL,
1471 "Warning: mailer %s: LMTP flag (F=z) turned off",
1473 clrbitn(M_LMTP, m->m_flags);
1477 ** At this point *mvp points to the argument with $u. We
1478 ** run through our address list and append all the addresses
1479 ** we can. If we run out of space, do not fret! We can
1480 ** always send another copy later.
1487 if (firstto->q_signature == NULL)
1488 firstto->q_signature = hostsignature(firstto->q_mailer,
1490 firstsig = firstto->q_signature;
1492 for (; to != NULL; to = to->q_next)
1494 /* avoid sending multiple recipients to dumb mailers */
1495 if (tochain != NULL && !bitnset(M_MUSER, m->m_flags))
1498 /* if already sent or not for this host, don't send */
1499 if (!QS_IS_OK(to->q_state)) /* already sent; look at next */
1503 ** Must be same mailer to keep grouping rcpts.
1504 ** If mailers don't match: continue; sendqueue is not
1505 ** sorted by mailers, so don't break;
1508 if (to->q_mailer != firstto->q_mailer)
1511 if (to->q_signature == NULL) /* for safety */
1512 to->q_signature = hostsignature(to->q_mailer,
1516 ** This is for coincidental and tailcoat piggybacking messages
1517 ** to the same mail host. While the signatures are identical
1518 ** (that's the MX-RR's are identical) we can do coincidental
1519 ** piggybacking. We try hard for coattail piggybacking
1520 ** with the same mail host when the next recipient has the
1521 ** same host at lowest preference. It may be that this
1522 ** won't work out, so 'skip_back' is maintained if a backup
1523 ** to coincidental piggybacking or full signature must happen.
1526 ret = firstto == to ? HS_MATCH_FULL :
1527 coloncmp(to->q_signature, firstsig);
1528 if (ret == HS_MATCH_FULL)
1530 else if (ret == HS_MATCH_NO)
1535 /* avoid overflowing tobuf */
1536 strsize += strlen(to->q_paddr) + 1;
1537 if (strsize > TOBUFSIZE)
1541 if (++rcptcount > to->q_mailer->m_maxrcpt)
1546 sm_dprintf("\nsend to ");
1547 printaddr(sm_debug_file(), to, false);
1550 /* compute effective uid/gid when sending */
1551 if (bitnset(M_RUNASRCPT, to->q_mailer->m_flags))
1552 # if HASSETUSERCONTEXT
1553 contextaddr = ctladdr = getctladdr(to);
1554 # else /* HASSETUSERCONTEXT */
1555 ctladdr = getctladdr(to);
1556 # endif /* HASSETUSERCONTEXT */
1560 sm_dprintf("ctladdr=");
1561 printaddr(sm_debug_file(), ctladdr, false);
1565 e->e_to = to->q_paddr;
1568 ** Check to see that these people are allowed to
1569 ** talk to each other.
1570 ** Check also for overflow of e_msgsize.
1573 if (m->m_maxsize != 0 &&
1574 (e->e_msgsize > m->m_maxsize || e->e_msgsize < 0))
1576 e->e_flags |= EF_NO_BODY_RETN;
1577 if (bitnset(M_LOCALMAILER, to->q_mailer->m_flags))
1578 to->q_status = "5.2.3";
1580 to->q_status = "5.3.4";
1582 /* set to->q_rstatus = NULL; or to the following? */
1583 usrerrenh(to->q_status,
1584 "552 Message is too large; %ld bytes max",
1586 markfailure(e, to, NULL, EX_UNAVAILABLE, false);
1587 giveresponse(EX_UNAVAILABLE, to->q_status, m,
1588 NULL, ctladdr, xstart, e, to);
1594 /* do config file checking of compatibility */
1595 quarantine = (e->e_quarmsg != NULL);
1596 rcode = rscheck("check_compat", e->e_from.q_paddr, to->q_paddr,
1597 e, RSF_RMCOMM|RSF_COUNT, 3, NULL,
1601 /* do in-code checking if not discarding */
1602 if (!bitset(EF_DISCARD, e->e_flags))
1604 rcode = checkcompat(to, e);
1610 markfailure(e, to, NULL, rcode, ovr);
1611 giveresponse(rcode, to->q_status, m,
1612 NULL, ctladdr, xstart, e, to);
1615 if (!quarantine && e->e_quarmsg != NULL)
1618 ** check_compat or checkcompat() has tried
1619 ** to quarantine but that isn't supported.
1620 ** Revert the attempt.
1623 e->e_quarmsg = NULL;
1624 macdefine(&e->e_macro, A_PERM,
1625 macid("{quarantine}"), "");
1627 if (bitset(EF_DISCARD, e->e_flags))
1631 sm_dprintf("deliver: discarding recipient ");
1632 printaddr(sm_debug_file(), to, false);
1635 /* pretend the message was sent */
1636 /* XXX should we log something here? */
1637 to->q_state = QS_DISCARDED;
1640 ** Remove discard bit to prevent discard of
1641 ** future recipients. This is safe because the
1642 ** true "global discard" has been handled before
1646 e->e_flags &= ~EF_DISCARD;
1651 ** Strip quote bits from names if the mailer is dumb
1655 if (bitnset(M_STRIPQ, m->m_flags))
1662 ** Strip all leading backslashes if requested and the
1663 ** next character is alphanumerical (the latter can
1664 ** probably relaxed a bit, see RFC2821).
1667 if (bitnset(M_STRIPBACKSL, m->m_flags) && user[0] == '\\')
1668 stripbackslash(user);
1670 /* hack attack -- delivermail compatibility */
1671 if (m == ProgMailer && *user == '|')
1675 ** If an error message has already been given, don't
1676 ** bother to send to this address.
1678 ** >>>>>>>>>> This clause assumes that the local mailer
1679 ** >> NOTE >> cannot do any further aliasing; that
1680 ** >>>>>>>>>> function is subsumed by sendmail.
1683 if (!QS_IS_OK(to->q_state))
1687 ** See if this user name is "special".
1688 ** If the user name has a slash in it, assume that this
1689 ** is a file -- send it off without further ado. Note
1690 ** that this type of addresses is not processed along
1691 ** with the others, so we fudge on the To person.
1694 if (strcmp(m->m_mailer, "[FILE]") == 0)
1696 macdefine(&e->e_macro, A_PERM, 'u', user);
1698 if (p == NULL && ctladdr != NULL)
1699 p = ctladdr->q_home;
1700 macdefine(&e->e_macro, A_PERM, 'z', p);
1701 expand(m->m_argv[1], buf, sizeof buf, e);
1702 if (strlen(buf) > 0)
1703 rcode = mailfile(buf, m, ctladdr, SFF_CREAT, e);
1706 syserr("empty filename specification for mailer %s",
1710 giveresponse(rcode, to->q_status, m, NULL,
1711 ctladdr, xstart, e, to);
1712 markfailure(e, to, NULL, rcode, true);
1716 to->q_state = QS_SENT;
1717 if (bitnset(M_LOCALMAILER, m->m_flags) &&
1718 bitset(QPINGONSUCCESS, to->q_flags))
1720 to->q_flags |= QDELIVERED;
1721 to->q_status = "2.1.5";
1722 (void) sm_io_fprintf(e->e_xfp,
1724 "%s... Successfully delivered\n",
1728 to->q_statdate = curtime();
1729 markstats(e, to, STATS_NORMAL);
1734 ** Address is verified -- add this user to mailer
1735 ** argv, and add it to the print list of recipients.
1738 /* link together the chain of recipients */
1739 to->q_tchain = tochain;
1741 e->e_to = "[CHAIN]";
1743 macdefine(&e->e_macro, A_PERM, 'u', user); /* to user */
1745 if (p == NULL && ctladdr != NULL)
1746 p = ctladdr->q_home;
1747 macdefine(&e->e_macro, A_PERM, 'z', p); /* user's home */
1749 /* set the ${dsn_notify} macro if applicable */
1750 if (bitset(QHASNOTIFY, to->q_flags))
1752 char notify[MAXLINE];
1755 if (bitset(QPINGONSUCCESS, to->q_flags))
1756 (void) sm_strlcat(notify, "SUCCESS,",
1758 if (bitset(QPINGONFAILURE, to->q_flags))
1759 (void) sm_strlcat(notify, "FAILURE,",
1761 if (bitset(QPINGONDELAY, to->q_flags))
1762 (void) sm_strlcat(notify, "DELAY,",
1765 /* Set to NEVER or drop trailing comma */
1766 if (notify[0] == '\0')
1767 (void) sm_strlcat(notify, "NEVER",
1770 notify[strlen(notify) - 1] = '\0';
1772 macdefine(&e->e_macro, A_TEMP,
1773 macid("{dsn_notify}"), notify);
1776 macdefine(&e->e_macro, A_PERM,
1777 macid("{dsn_notify}"), NULL);
1780 ** Expand out this user into argument list.
1785 expand(*mvp, buf, sizeof buf, e);
1786 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1787 if (pvp >= &pv[MAXPV - 2])
1789 /* allow some space for trailing parms */
1795 /* see if any addresses still exist */
1796 if (tochain == NULL)
1802 /* print out messages as full list */
1804 for (to = tochain; to != NULL; to = to->q_tchain)
1805 strsize += strlen(to->q_paddr) + 1;
1806 if (strsize < TOBUFSIZE)
1807 strsize = TOBUFSIZE;
1808 if (strsize > tobufsize)
1811 tobuf = sm_pmalloc_x(strsize);
1812 tobufsize = strsize;
1816 for (to = tochain; to != NULL; to = to->q_tchain)
1818 (void) sm_strlcpyn(p, tobufsize - (p - tobuf), 2,
1822 e->e_to = tobuf + 1;
1825 ** Fill out any parameters after the $u parameter.
1830 while (*++mvp != NULL)
1832 expand(*mvp, buf, sizeof buf, e);
1833 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1834 if (pvp >= &pv[MAXPV])
1835 syserr("554 5.3.0 deliver: pv overflow after $u for %s",
1843 ** The argument vector gets built, pipes
1844 ** are created as necessary, and we fork & exec as
1846 ** If we are running SMTP, we just need to clean up.
1849 /* XXX this seems a bit wierd */
1850 if (ctladdr == NULL && m != ProgMailer && m != FileMailer &&
1851 bitset(QGOODUID, e->e_from.q_flags))
1852 ctladdr = &e->e_from;
1855 if (ConfigLevel < 2)
1856 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */
1857 #endif /* NAMED_BIND */
1861 sm_dprintf("openmailer:");
1862 printav(sm_debug_file(), pv);
1869 ** Deal with the special case of mail handled through an IPC
1871 ** In this case we don't actually fork. We must be
1872 ** running SMTP for this to work. We will return a
1873 ** zero pid to indicate that we are running IPC.
1874 ** We also handle a debug version that just talks to stdin/out.
1885 /* make absolutely certain 0, 1, and 2 are in use */
1886 (void) sm_snprintf(wbuf, sizeof wbuf, "%s... openmailer(%s)",
1887 shortenstring(e->e_to, MAXSHORTSTR),
1893 /* check for 8-bit available */
1894 if (bitset(EF_HAS8BIT, e->e_flags) &&
1895 bitnset(M_7BITS, m->m_flags) &&
1896 (bitset(EF_DONT_MIME, e->e_flags) ||
1897 !(bitset(MM_MIME8BIT, MimeMode) ||
1898 (bitset(EF_IS_MIME, e->e_flags) &&
1899 bitset(MM_CVTMIME, MimeMode)))))
1901 e->e_status = "5.6.3";
1902 usrerrenh(e->e_status,
1903 "554 Cannot send 8-bit data to 7-bit destination");
1909 checkfds("before delivery");
1911 /* check for Local Person Communication -- not for mortals!!! */
1912 if (strcmp(m->m_mailer, "[LPC]") == 0)
1916 /* flush any expired connections */
1917 (void) mci_scan(NULL);
1919 /* try to get a cached connection or just a slot */
1920 mci = mci_get(m->m_name, m);
1921 if (mci->mci_host == NULL)
1922 mci->mci_host = m->m_name;
1923 CurHostName = mci->mci_host;
1924 if (mci->mci_state != MCIS_CLOSED)
1926 message("Using cached SMTP/LPC connection for %s...",
1928 mci->mci_deliveries++;
1934 mci = mci_new(e->e_rpool);
1936 mci->mci_in = smioin;
1937 mci->mci_out = smioout;
1938 mci->mci_mailer = m;
1939 mci->mci_host = m->m_name;
1942 mci->mci_state = MCIS_OPENING;
1946 mci->mci_state = MCIS_OPEN;
1948 else if (strcmp(m->m_mailer, "[IPC]") == 0)
1952 if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0')
1954 syserr("null destination for %s mailer", m->m_mailer);
1960 if (strcmp(pv[0], "FILE") == 0)
1962 curhost = CurHostName = "localhost";
1966 # endif /* NETUNIX */
1968 CurHostName = pv[1];
1969 curhost = hostsignature(m, pv[1]);
1972 if (curhost == NULL || curhost[0] == '\0')
1974 syserr("null host signature for %s", pv[1]);
1981 syserr("554 5.3.5 non-clever IPC");
1988 # endif /* NETUNIX */
1991 port = htons((unsigned short) atoi(pv[2]));
1994 # ifdef NO_GETSERVBYNAME
1995 syserr("Invalid port number: %s", pv[2]);
1996 # else /* NO_GETSERVBYNAME */
1997 struct servent *sp = getservbyname(pv[2], "tcp");
2000 syserr("Service %s unknown", pv[2]);
2003 # endif /* NO_GETSERVBYNAME */
2007 nummxhosts = parse_hostsignature(curhost, mxhosts, m);
2008 if (TimeOuts.to_aconnect > 0)
2009 enough = curtime() + TimeOuts.to_aconnect;
2011 while (hostnum < nummxhosts)
2015 static char hostbuf[MAXNAME + 1];
2016 bool tried_fallbacksmarthost = false;
2019 if (*mxhosts[hostnum] == '[')
2021 endp = strchr(mxhosts[hostnum] + 1, ']');
2023 endp = strpbrk(endp + 1, ":,");
2026 endp = strpbrk(mxhosts[hostnum], ":,");
2027 # else /* NETINET6 */
2028 endp = strpbrk(mxhosts[hostnum], ":,");
2029 # endif /* NETINET6 */
2036 if (hostnum == 1 && skip_back != NULL)
2039 ** Coattail piggybacking is no longer an
2040 ** option with the mail host next to be tried
2041 ** no longer the lowest MX preference
2042 ** (hostnum == 1 meaning we're on the second
2043 ** preference). We do not try to coattail
2044 ** piggyback more than the first MX preference.
2045 ** Revert 'tochain' to last location for
2046 ** coincidental piggybacking. This works this
2047 ** easily because the q_tchain kept getting
2048 ** added to the top of the linked list.
2051 tochain = skip_back;
2054 if (*mxhosts[hostnum] == '\0')
2056 syserr("deliver: null host name in signature");
2062 (void) sm_strlcpy(hostbuf, mxhosts[hostnum],
2069 /* see if we already know that this host is fried */
2070 CurHostName = hostbuf;
2071 mci = mci_get(hostbuf, m);
2072 if (mci->mci_state != MCIS_CLOSED)
2078 sm_dprintf("openmailer: ");
2079 mci_dump(sm_debug_file(), mci, false);
2081 CurHostName = mci->mci_host;
2082 if (bitnset(M_LMTP, m->m_flags))
2084 else if (bitset(MCIF_ESMTP, mci->mci_flags))
2088 message("Using cached %sMTP connection to %s via %s...",
2089 type, hostbuf, m->m_name);
2090 mci->mci_deliveries++;
2093 mci->mci_mailer = m;
2094 if (mci->mci_exitstat != EX_OK)
2096 if (mci->mci_exitstat == EX_TEMPFAIL)
2099 /* Try FallbackSmartHost? */
2100 if (should_try_fbsh(e, &tried_fallbacksmarthost,
2101 hostbuf, sizeof hostbuf,
2108 if (mci_lock_host(mci) != EX_OK)
2110 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2115 /* try the connection */
2116 sm_setproctitle(true, e, "%s %s: %s",
2118 hostbuf, "user open");
2120 if (mux_path != NULL)
2122 message("Connecting to %s via %s...",
2123 mux_path, m->m_name);
2124 i = makeconnection_ds((char *) mux_path, mci);
2127 # endif /* NETUNIX */
2130 message("Connecting to %s via %s...",
2131 hostbuf, m->m_name);
2133 message("Connecting to %s port %d via %s...",
2134 hostbuf, ntohs(port),
2136 i = makeconnection(hostbuf, port, mci, e,
2139 mci->mci_errno = errno;
2140 mci->mci_lastuse = curtime();
2141 mci->mci_deliveries = 0;
2142 mci->mci_exitstat = i;
2144 mci->mci_herrno = h_errno;
2145 # endif /* NAMED_BIND */
2148 ** Have we tried long enough to get a connection?
2149 ** If yes, skip to the fallback MX hosts
2153 if (enough > 0 && mci->mci_lastuse >= enough)
2157 extern int NumFallbackMXHosts;
2158 # else /* NAMED_BIND */
2159 const int NumFallbackMXHosts = 0;
2160 # endif /* NAMED_BIND */
2162 if (hostnum < nummxhosts && LogLevel > 9)
2163 sm_syslog(LOG_INFO, e->e_id,
2164 "Timeout.to_aconnect occurred before exhausting all addresses");
2166 /* turn off timeout if fallback available */
2167 if (NumFallbackMXHosts > 0)
2170 /* skip to a fallback MX host */
2171 h = nummxhosts - NumFallbackMXHosts;
2178 markstats(e, firstto, STATS_CONNECT);
2179 mci->mci_state = MCIS_OPENING;
2181 if (TrafficLogFile != NULL)
2182 (void) sm_io_fprintf(TrafficLogFile,
2184 "%05d === CONNECT %s\n",
2191 /* Try FallbackSmartHost? */
2192 if (should_try_fbsh(e, &tried_fallbacksmarthost,
2193 hostbuf, sizeof hostbuf, i))
2197 sm_dprintf("openmailer: makeconnection => stat=%d, errno=%d\n",
2199 if (i == EX_TEMPFAIL)
2201 mci_unlock_host(mci);
2204 /* enter status of this host */
2207 /* should print some message here for -v mode */
2211 syserr("deliver: no host name");
2212 rcode = EX_SOFTWARE;
2219 /* flush any expired connections */
2220 (void) mci_scan(NULL);
2223 if (bitnset(M_LMTP, m->m_flags))
2225 /* try to get a cached connection */
2226 mci = mci_get(m->m_name, m);
2227 if (mci->mci_host == NULL)
2228 mci->mci_host = m->m_name;
2229 CurHostName = mci->mci_host;
2230 if (mci->mci_state != MCIS_CLOSED)
2232 message("Using cached LMTP connection for %s...",
2234 mci->mci_deliveries++;
2239 /* announce the connection to verbose listeners */
2240 if (host == NULL || host[0] == '\0')
2241 message("Connecting to %s...", m->m_name);
2243 message("Connecting to %s via %s...", host, m->m_name);
2244 if (TrafficLogFile != NULL)
2248 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
2249 "%05d === EXEC", (int) CurrentPid);
2250 for (av = pv; *av != NULL; av++)
2251 (void) sm_io_fprintf(TrafficLogFile,
2252 SM_TIME_DEFAULT, " %s",
2254 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
2259 checkfd012("before creating mail pipe");
2262 /* create a pipe to shove the mail through */
2263 if (pipe(mpvect) < 0)
2265 syserr("%s... openmailer(%s): pipe (to mailer)",
2266 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
2268 sm_dprintf("openmailer: NULL\n");
2274 /* make sure we didn't get one of the standard I/O files */
2275 if (mpvect[0] < 3 || mpvect[1] < 3)
2277 syserr("%s... openmailer(%s): bogus mpvect %d %d",
2278 shortenstring(e->e_to, MAXSHORTSTR), m->m_name,
2279 mpvect[0], mpvect[1]);
2282 sm_dprintf("openmailer: NULL\n");
2287 /* make sure system call isn't dead meat */
2288 checkfdopen(mpvect[0], "mpvect[0]");
2289 checkfdopen(mpvect[1], "mpvect[1]");
2290 if (mpvect[0] == mpvect[1] ||
2291 (e->e_lockfp != NULL &&
2292 (mpvect[0] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD,
2294 mpvect[1] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD,
2297 if (e->e_lockfp == NULL)
2298 syserr("%s... openmailer(%s): overlapping mpvect %d %d",
2299 shortenstring(e->e_to, MAXSHORTSTR),
2300 m->m_name, mpvect[0], mpvect[1]);
2302 syserr("%s... openmailer(%s): overlapping mpvect %d %d, lockfp = %d",
2303 shortenstring(e->e_to, MAXSHORTSTR),
2304 m->m_name, mpvect[0], mpvect[1],
2305 sm_io_getinfo(e->e_lockfp,
2306 SM_IO_WHAT_FD, NULL));
2310 /* create a return pipe */
2311 if (pipe(rpvect) < 0)
2313 syserr("%s... openmailer(%s): pipe (from mailer)",
2314 shortenstring(e->e_to, MAXSHORTSTR),
2316 (void) close(mpvect[0]);
2317 (void) close(mpvect[1]);
2319 sm_dprintf("openmailer: NULL\n");
2324 checkfdopen(rpvect[0], "rpvect[0]");
2325 checkfdopen(rpvect[1], "rpvect[1]");
2329 ** Actually fork the mailer process.
2330 ** DOFORK is clever about retrying.
2332 ** Dispose of SIGCHLD signal catchers that may be laying
2333 ** around so that endmailer will get it.
2336 if (e->e_xfp != NULL) /* for debugging */
2337 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
2338 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2339 (void) sm_signal(SIGCHLD, SIG_DFL);
2343 /* pid is set by DOFORK */
2348 syserr("%s... openmailer(%s): cannot fork",
2349 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
2350 (void) close(mpvect[0]);
2351 (void) close(mpvect[1]);
2352 (void) close(rpvect[0]);
2353 (void) close(rpvect[1]);
2355 sm_dprintf("openmailer: NULL\n");
2363 int new_euid = NO_UID;
2364 int new_ruid = NO_UID;
2365 int new_gid = NO_GID;
2368 extern int DtableSize;
2370 CurrentPid = getpid();
2372 /* clear the events to turn off SIGALRMs */
2375 /* Reset global flags */
2376 RestartRequest = NULL;
2377 RestartWorkGroup = false;
2378 ShutdownRequest = NULL;
2381 if (e->e_lockfp != NULL)
2382 (void) close(sm_io_getinfo(e->e_lockfp,
2386 /* child -- set up input & exec mailer */
2387 (void) sm_signal(SIGALRM, sm_signal_noop);
2388 (void) sm_signal(SIGCHLD, SIG_DFL);
2389 (void) sm_signal(SIGHUP, SIG_IGN);
2390 (void) sm_signal(SIGINT, SIG_IGN);
2391 (void) sm_signal(SIGTERM, SIG_DFL);
2393 (void) sm_signal(SIGUSR1, sm_signal_noop);
2394 # endif /* SIGUSR1 */
2396 if (m != FileMailer || stat(tochain->q_user, &stb) < 0)
2399 # if HASSETUSERCONTEXT
2401 ** Set user resources.
2404 if (contextaddr != NULL)
2409 if (contextaddr->q_ruser != NULL)
2410 pwd = sm_getpwnam(contextaddr->q_ruser);
2412 pwd = sm_getpwnam(contextaddr->q_user);
2413 sucflags = LOGIN_SETRESOURCES|LOGIN_SETPRIORITY;
2415 sucflags |= LOGIN_SETMAC;
2416 #endif /* LOGIN_SETMAC */
2418 setusercontext(NULL, pwd, pwd->pw_uid,
2422 syserr("openmailer: setusercontext() failed");
2426 # endif /* HASSETUSERCONTEXT */
2429 /* tweak niceness */
2431 (void) nice(m->m_nice);
2432 #endif /* HASNICE */
2434 /* reset group id */
2435 if (bitnset(M_SPECIFIC_UID, m->m_flags))
2437 if (m->m_gid == NO_GID)
2442 else if (bitset(S_ISGID, stb.st_mode))
2443 new_gid = stb.st_gid;
2444 else if (ctladdr != NULL && ctladdr->q_gid != 0)
2446 if (!DontInitGroups)
2448 user = ctladdr->q_ruser;
2450 user = ctladdr->q_user;
2452 if (initgroups(user,
2453 ctladdr->q_gid) == -1
2456 syserr("openmailer: initgroups(%s, %d) failed",
2457 user, ctladdr->q_gid);
2465 gidset[0] = ctladdr->q_gid;
2466 if (setgroups(1, gidset) == -1
2469 syserr("openmailer: setgroups() failed");
2473 new_gid = ctladdr->q_gid;
2477 if (!DontInitGroups)
2480 if (initgroups(DefUser, DefGid) == -1 &&
2483 syserr("openmailer: initgroups(%s, %d) failed",
2493 if (setgroups(1, gidset) == -1
2496 syserr("openmailer: setgroups() failed");
2500 if (m->m_gid == NO_GID)
2505 if (new_gid != NO_GID)
2507 if (RunAsUid != 0 &&
2508 bitnset(M_SPECIFIC_UID, m->m_flags) &&
2509 new_gid != getgid() &&
2510 new_gid != getegid())
2512 /* Only root can change the gid */
2513 syserr("openmailer: insufficient privileges to change gid, RunAsUid=%d, new_gid=%d, gid=%d, egid=%d",
2514 (int) RunAsUid, (int) new_gid,
2515 (int) getgid(), (int) getegid());
2519 if (setgid(new_gid) < 0 && suidwarn)
2521 syserr("openmailer: setgid(%ld) failed",
2527 /* change root to some "safe" directory */
2528 if (m->m_rootdir != NULL)
2530 expand(m->m_rootdir, cbuf, sizeof cbuf, e);
2532 sm_dprintf("openmailer: chroot %s\n",
2534 if (chroot(cbuf) < 0)
2536 syserr("openmailer: Cannot chroot(%s)",
2542 syserr("openmailer: cannot chdir(/)");
2549 sm_mbdb_terminate();
2550 if (bitnset(M_SPECIFIC_UID, m->m_flags))
2552 if (m->m_uid == NO_UID)
2553 new_euid = RunAsUid;
2555 new_euid = m->m_uid;
2558 ** Undo the effects of the uid change in main
2559 ** for signal handling. The real uid may
2560 ** be used by mailer in adding a "From "
2564 if (RealUid != 0 && RealUid != getuid())
2566 # if MAILER_SETUID_METHOD == USE_SETEUID
2568 if (setreuid(RealUid, geteuid()) < 0)
2570 syserr("openmailer: setreuid(%d, %d) failed",
2571 (int) RealUid, (int) geteuid());
2574 # endif /* HASSETREUID */
2575 # endif /* MAILER_SETUID_METHOD == USE_SETEUID */
2576 # if MAILER_SETUID_METHOD == USE_SETREUID
2578 # endif /* MAILER_SETUID_METHOD == USE_SETREUID */
2581 else if (bitset(S_ISUID, stb.st_mode))
2582 new_ruid = stb.st_uid;
2583 else if (ctladdr != NULL && ctladdr->q_uid != 0)
2584 new_ruid = ctladdr->q_uid;
2585 else if (m->m_uid != NO_UID)
2586 new_ruid = m->m_uid;
2590 # if _FFR_USE_SETLOGIN
2591 /* run disconnected from terminal and set login name */
2592 if (setsid() >= 0 &&
2593 ctladdr != NULL && ctladdr->q_uid != 0 &&
2594 new_euid == ctladdr->q_uid)
2598 pwd = sm_getpwuid(ctladdr->q_uid);
2599 if (pwd != NULL && suidwarn)
2600 (void) setlogin(pwd->pw_name);
2603 # endif /* _FFR_USE_SETLOGIN */
2605 if (new_euid != NO_UID)
2607 if (RunAsUid != 0 && new_euid != RunAsUid)
2609 /* Only root can change the uid */
2610 syserr("openmailer: insufficient privileges to change uid, new_euid=%d, RunAsUid=%d",
2611 (int) new_euid, (int) RunAsUid);
2615 vendor_set_uid(new_euid);
2616 # if MAILER_SETUID_METHOD == USE_SETEUID
2617 if (seteuid(new_euid) < 0 && suidwarn)
2619 syserr("openmailer: seteuid(%ld) failed",
2623 # endif /* MAILER_SETUID_METHOD == USE_SETEUID */
2624 # if MAILER_SETUID_METHOD == USE_SETREUID
2625 if (setreuid(new_ruid, new_euid) < 0 && suidwarn)
2627 syserr("openmailer: setreuid(%ld, %ld) failed",
2628 (long) new_ruid, (long) new_euid);
2631 # endif /* MAILER_SETUID_METHOD == USE_SETREUID */
2632 # if MAILER_SETUID_METHOD == USE_SETUID
2633 if (new_euid != geteuid() && setuid(new_euid) < 0 && suidwarn)
2635 syserr("openmailer: setuid(%ld) failed",
2639 # endif /* MAILER_SETUID_METHOD == USE_SETUID */
2641 else if (new_ruid != NO_UID)
2643 vendor_set_uid(new_ruid);
2644 if (setuid(new_ruid) < 0 && suidwarn)
2646 syserr("openmailer: setuid(%ld) failed",
2653 sm_dprintf("openmailer: running as r/euid=%d/%d, r/egid=%d/%d\n",
2654 (int) getuid(), (int) geteuid(),
2655 (int) getgid(), (int) getegid());
2657 /* move into some "safe" directory */
2658 if (m->m_execdir != NULL)
2662 for (p = m->m_execdir; p != NULL; p = q)
2667 expand(p, cbuf, sizeof cbuf, e);
2671 sm_dprintf("openmailer: trydir %s\n",
2673 if (cbuf[0] != '\0' &&
2679 /* Check safety of program to be run */
2680 sff = SFF_ROOTOK|SFF_EXECOK;
2681 if (!bitnset(DBS_RUNWRITABLEPROGRAM,
2683 sff |= SFF_NOGWFILES|SFF_NOWWFILES;
2684 if (bitnset(DBS_RUNPROGRAMINUNSAFEDIRPATH,
2686 sff |= SFF_NOPATHCHECK;
2688 sff |= SFF_SAFEDIRPATH;
2689 ret = safefile(m->m_mailer, getuid(), getgid(),
2690 user, sff, 0, NULL);
2692 sm_syslog(LOG_INFO, e->e_id,
2693 "Warning: program %s unsafe: %s",
2694 m->m_mailer, sm_errstring(ret));
2696 /* arrange to filter std & diag output of command */
2697 (void) close(rpvect[0]);
2698 if (dup2(rpvect[1], STDOUT_FILENO) < 0)
2700 syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
2701 shortenstring(e->e_to, MAXSHORTSTR),
2702 m->m_name, rpvect[1]);
2705 (void) close(rpvect[1]);
2707 if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
2709 syserr("%s... openmailer(%s): cannot dup stdout for stderr",
2710 shortenstring(e->e_to, MAXSHORTSTR),
2715 /* arrange to get standard input */
2716 (void) close(mpvect[1]);
2717 if (dup2(mpvect[0], STDIN_FILENO) < 0)
2719 syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
2720 shortenstring(e->e_to, MAXSHORTSTR),
2721 m->m_name, mpvect[0]);
2724 (void) close(mpvect[0]);
2726 /* arrange for all the files to be closed */
2727 sm_close_on_exec(STDERR_FILENO + 1, DtableSize);
2729 # if !_FFR_USE_SETLOGIN
2730 /* run disconnected from terminal */
2732 # endif /* !_FFR_USE_SETLOGIN */
2734 /* try to execute the mailer */
2735 (void) execve(m->m_mailer, (ARGV_T) pv,
2736 (ARGV_T) UserEnviron);
2738 syserr("Cannot exec %s", m->m_mailer);
2739 if (bitnset(M_LOCALMAILER, m->m_flags) ||
2740 transienterror(save_errno))
2742 _exit(EX_UNAVAILABLE);
2746 ** Set up return value.
2754 ** Allocate from general heap, not
2755 ** envelope rpool, because this mci
2756 ** is going to be cached.
2759 mci = mci_new(NULL);
2764 ** Prevent a storage leak by allocating
2765 ** this from the envelope rpool.
2768 mci = mci_new(e->e_rpool);
2771 mci->mci_mailer = m;
2774 mci->mci_state = MCIS_OPENING;
2779 mci->mci_state = MCIS_OPEN;
2782 (void) close(mpvect[0]);
2783 mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2784 (void *) &(mpvect[1]), SM_IO_WRONLY_B,
2786 if (mci->mci_out == NULL)
2788 syserr("deliver: cannot create mailer output channel, fd=%d",
2790 (void) close(mpvect[1]);
2791 (void) close(rpvect[0]);
2792 (void) close(rpvect[1]);
2797 (void) close(rpvect[1]);
2798 mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2799 (void *) &(rpvect[0]), SM_IO_RDONLY_B,
2801 if (mci->mci_in == NULL)
2803 syserr("deliver: cannot create mailer input channel, fd=%d",
2805 (void) close(rpvect[0]);
2806 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
2807 mci->mci_out = NULL;
2814 ** If we are in SMTP opening state, send initial protocol.
2817 if (bitnset(M_7BITS, m->m_flags) &&
2818 (!clever || mci->mci_state == MCIS_OPENING))
2819 mci->mci_flags |= MCIF_7BIT;
2820 if (clever && mci->mci_state != MCIS_CLOSED)
2822 # if STARTTLS || SASL
2825 extern SOCKADDR CurHostAddr;
2826 # endif /* STARTTLS || SASL */
2829 # define DONE_AUTH(f) bitset(MCIF_AUTHACT, f)
2832 # define DONE_STARTTLS(f) bitset(MCIF_TLSACT, f)
2833 # endif /* STARTTLS */
2834 # define ONLY_HELO(f) bitset(MCIF_ONLY_EHLO, f)
2835 # define SET_HELO(f) f |= MCIF_ONLY_EHLO
2836 # define CLR_HELO(f) f &= ~MCIF_ONLY_EHLO
2838 # if STARTTLS || SASL
2839 /* don't use CurHostName, it is changed in many places */
2840 if (mci->mci_host != NULL)
2842 srvname = mci->mci_host;
2843 dotpos = strlen(srvname) - 1;
2846 if (srvname[dotpos] == '.')
2847 srvname[dotpos] = '\0';
2852 else if (mci->mci_mailer != NULL)
2854 srvname = mci->mci_mailer->m_name;
2863 /* don't set {server_name} to NULL or "": see getauth() */
2864 macdefine(&mci->mci_macro, A_TEMP, macid("{server_name}"),
2867 /* CurHostAddr is set by makeconnection() and mci_get() */
2868 if (CurHostAddr.sa.sa_family != 0)
2870 macdefine(&mci->mci_macro, A_TEMP,
2871 macid("{server_addr}"),
2872 anynet_ntoa(&CurHostAddr));
2874 else if (mci->mci_mailer != NULL)
2876 /* mailer name is unique, use it as address */
2877 macdefine(&mci->mci_macro, A_PERM,
2878 macid("{server_addr}"),
2879 mci->mci_mailer->m_name);
2883 /* don't set it to NULL or "": see getauth() */
2884 macdefine(&mci->mci_macro, A_PERM,
2885 macid("{server_addr}"), "0");
2888 /* undo change of srvname (mci->mci_host) */
2890 srvname[dotpos] = '.';
2892 reconnect: /* after switching to an encrypted connection */
2893 # endif /* STARTTLS || SASL */
2895 /* set the current connection information */
2898 mci->mci_saslcap = NULL;
2900 smtpinit(m, mci, e, ONLY_HELO(mci->mci_flags));
2901 CLR_HELO(mci->mci_flags);
2903 if (IS_DLVR_RETURN(e))
2906 ** Check whether other side can deliver e-mail
2910 if (!bitset(MCIF_DLVR_BY, mci->mci_flags))
2912 e->e_status = "5.4.7";
2913 usrerrenh(e->e_status,
2914 "554 Server does not support Deliver By");
2915 rcode = EX_UNAVAILABLE;
2918 if (e->e_deliver_by > 0 &&
2919 e->e_deliver_by - (curtime() - e->e_ctime) <
2922 e->e_status = "5.4.7";
2923 usrerrenh(e->e_status,
2924 "554 Message can't be delivered in time; %ld < %ld",
2925 e->e_deliver_by - (curtime() - e->e_ctime),
2927 rcode = EX_UNAVAILABLE;
2933 /* first TLS then AUTH to provide a security layer */
2934 if (mci->mci_state != MCIS_CLOSED &&
2935 !DONE_STARTTLS(mci->mci_flags))
2939 bool saveQuickAbort = QuickAbort;
2940 bool saveSuprErrs = SuprErrs;
2944 usetls = bitset(MCIF_TLS, mci->mci_flags);
2946 usetls = !iscltflgset(e, D_NOTLS);
2950 host = macvalue(macid("{server_name}"), e);
2954 if (rscheck("try_tls", host, NULL, e,
2955 RSF_RMCOMM, 7, host, NOQID) != EX_OK
2956 || Errors > olderrors)
2958 SuprErrs = saveSuprErrs;
2959 QuickAbort = saveQuickAbort;
2964 if ((rcode = starttls(m, mci, e)) == EX_OK)
2966 /* start again without STARTTLS */
2967 mci->mci_flags |= MCIF_TLSACT;
2974 ** TLS negotation failed, what to do?
2975 ** fall back to unencrypted connection
2976 ** or abort? How to decide?
2977 ** set a macro and call a ruleset.
2980 mci->mci_flags &= ~MCIF_TLS;
2995 case EX_UNAVAILABLE:
2999 /* everything else is a failure */
3002 rcode = EX_TEMPFAIL;
3004 macdefine(&e->e_macro, A_PERM,
3005 macid("{verify}"), s);
3009 macdefine(&e->e_macro, A_PERM,
3010 macid("{verify}"), "NONE");
3016 ** rcode == EX_SOFTWARE is special:
3017 ** the TLS negotation failed
3018 ** we have to drop the connection no matter what
3019 ** However, we call tls_server to give it the chance
3020 ** to log the problem and return an appropriate
3024 if (rscheck("tls_server",
3025 macvalue(macid("{verify}"), e),
3026 NULL, e, RSF_RMCOMM|RSF_COUNT, 5,
3027 host, NOQID) != EX_OK ||
3028 Errors > olderrors ||
3029 rcode == EX_SOFTWARE)
3031 char enhsc[ENHSCLEN];
3032 extern char MsgBuf[];
3034 if (ISSMTPCODE(MsgBuf) &&
3035 extenhsc(MsgBuf + 4, ' ', enhsc) > 0)
3037 p = sm_rpool_strdup_x(e->e_rpool,
3042 p = "403 4.7.0 server not authenticated.";
3043 (void) sm_strlcpy(enhsc, "4.7.0",
3046 SuprErrs = saveSuprErrs;
3047 QuickAbort = saveQuickAbort;
3049 if (rcode == EX_SOFTWARE)
3051 /* drop the connection */
3052 mci->mci_state = MCIS_QUITING;
3053 if (mci->mci_in != NULL)
3055 (void) sm_io_close(mci->mci_in,
3059 mci->mci_flags &= ~MCIF_TLSACT;
3060 (void) endmailer(mci, e, pv);
3064 /* abort transfer */
3065 smtpquit(m, mci, e);
3068 /* avoid bogus error msg */
3071 /* temp or permanent failure? */
3072 rcode = (*p == '4') ? EX_TEMPFAIL
3074 mci_setstat(mci, rcode, enhsc, p);
3077 ** hack to get the error message into
3078 ** the envelope (done in giveresponse())
3081 (void) sm_strlcpy(SmtpError, p,
3084 QuickAbort = saveQuickAbort;
3085 SuprErrs = saveSuprErrs;
3086 if (DONE_STARTTLS(mci->mci_flags) &&
3087 mci->mci_state != MCIS_CLOSED)
3089 SET_HELO(mci->mci_flags);
3090 mci->mci_flags &= ~MCIF_EXTENS;
3094 # endif /* STARTTLS */
3096 /* if other server supports authentication let's authenticate */
3097 if (mci->mci_state != MCIS_CLOSED &&
3098 mci->mci_saslcap != NULL &&
3099 !DONE_AUTH(mci->mci_flags) && !iscltflgset(e, D_NOAUTH))
3101 /* Should we require some minimum authentication? */
3102 if ((ret = smtpauth(m, mci, e)) == EX_OK)
3105 sasl_ssf_t *ssf = NULL;
3107 /* Get security strength (features) */
3108 result = sasl_getprop(mci->mci_conn, SASL_SSF,
3110 (const void **) &ssf);
3111 # else /* SASL >= 20000 */
3113 # endif /* SASL >= 20000 */
3117 sm_syslog(LOG_INFO, NOQID,
3118 "AUTH=client, relay=%.100s, mech=%.16s, bits=%d",
3120 macvalue(macid("{auth_type}"), e),
3121 result == SASL_OK ? *ssf : 0);
3124 ** Only switch to encrypted connection
3125 ** if a security layer has been negotiated
3128 if (result == SASL_OK && *ssf > 0)
3133 ** Convert I/O layer to use SASL.
3134 ** If the call fails, the connection
3138 tmo = DATA_PROGRESS_TIMEOUT * 1000;
3139 if (sfdcsasl(&mci->mci_in,
3141 mci->mci_conn, tmo) == 0)
3143 mci->mci_flags &= ~MCIF_EXTENS;
3144 mci->mci_flags |= MCIF_AUTHACT|
3148 syserr("AUTH TLS switch failed in client");
3151 mci->mci_flags |= MCIF_AUTHACT;
3154 else if (ret == EX_TEMPFAIL)
3157 sm_syslog(LOG_ERR, NOQID,
3158 "AUTH=client, relay=%.100s, temporary failure, connection abort",
3160 smtpquit(m, mci, e);
3162 /* avoid bogus error msg */
3164 rcode = EX_TEMPFAIL;
3165 mci_setstat(mci, rcode, "4.3.0", p);
3168 ** hack to get the error message into
3169 ** the envelope (done in giveresponse())
3172 (void) sm_strlcpy(SmtpError,
3173 "Temporary AUTH failure",
3182 /* clear out per-message flags from connection structure */
3183 mci->mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
3185 if (bitset(EF_HAS8BIT, e->e_flags) &&
3186 !bitset(EF_DONT_MIME, e->e_flags) &&
3187 bitnset(M_7BITS, m->m_flags))
3188 mci->mci_flags |= MCIF_CVT8TO7;
3191 if (bitnset(M_MAKE8BIT, m->m_flags) &&
3192 !bitset(MCIF_7BIT, mci->mci_flags) &&
3193 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
3194 (sm_strcasecmp(p, "quoted-printable") == 0 ||
3195 sm_strcasecmp(p, "base64") == 0) &&
3196 (p = hvalue("Content-Type", e->e_header)) != NULL)
3198 /* may want to convert 7 -> 8 */
3199 /* XXX should really parse it here -- and use a class XXX */
3200 if (sm_strncasecmp(p, "text/plain", 10) == 0 &&
3201 (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
3202 mci->mci_flags |= MCIF_CVT7TO8;
3204 #endif /* MIME7TO8 */
3208 sm_dprintf("openmailer: ");
3209 mci_dump(sm_debug_file(), mci, false);
3212 #if _FFR_CLIENT_SIZE
3214 ** See if we know the maximum size and
3215 ** abort if the message is too big.
3217 ** NOTE: _FFR_CLIENT_SIZE is untested.
3220 if (bitset(MCIF_SIZE, mci->mci_flags) &&
3221 mci->mci_maxsize > 0 &&
3222 e->e_msgsize > mci->mci_maxsize)
3224 e->e_flags |= EF_NO_BODY_RETN;
3225 if (bitnset(M_LOCALMAILER, m->m_flags))
3226 e->e_status = "5.2.3";
3228 e->e_status = "5.3.4";
3230 usrerrenh(e->e_status,
3231 "552 Message is too large; %ld bytes max",
3235 /* Need an e_message for error */
3236 (void) sm_snprintf(SmtpError, sizeof SmtpError,
3237 "Message is too large; %ld bytes max",
3241 #endif /* _FFR_CLIENT_SIZE */
3243 if (mci->mci_state != MCIS_OPEN)
3245 /* couldn't open the mailer */
3246 rcode = mci->mci_exitstat;
3247 errno = mci->mci_errno;
3248 SM_SET_H_ERRNO(mci->mci_herrno);
3251 /* shouldn't happen */
3252 syserr("554 5.3.5 deliver: mci=%lx rcode=%d errno=%d state=%d sig=%s",
3253 (unsigned long) mci, rcode, errno,
3254 mci->mci_state, firstsig);
3255 mci_dump_all(smioout, true);
3256 rcode = EX_SOFTWARE;
3258 else if (nummxhosts > hostnum)
3260 /* try next MX site */
3269 ** Format and send message.
3274 ok = putfromline(mci, e);
3276 ok = (*e->e_puthdr)(mci, e->e_header, e, M87F_OUTER);
3278 ok = (*e->e_putbody)(mci, e, NULL);
3281 ** Ignore an I/O error that was caused by EPIPE.
3282 ** Some broken mailers don't read the entire body
3283 ** but just exit() thus causing an I/O error.
3286 if (!ok && (sm_io_error(mci->mci_out) && errno == EPIPE))
3289 /* (always) get the exit status */
3290 rcode = endmailer(mci, e, pv);
3292 rcode = EX_TEMPFAIL;
3293 if (rcode == EX_TEMPFAIL && SmtpError[0] == '\0')
3296 ** Need an e_message for mailq display.
3297 ** We set SmtpError as
3300 (void) sm_snprintf(SmtpError, sizeof SmtpError,
3301 "%s mailer (%s) exited with EX_TEMPFAIL",
3302 m->m_name, m->m_mailer);
3308 ** Send the MAIL FROM: protocol
3311 /* XXX this isn't pipelined... */
3312 rcode = smtpmailfrom(m, mci, e);
3317 ADDRESS *volatile pchain;
3318 # endif /* PIPELINING */
3320 /* send the recipient list */
3322 mci->mci_retryrcpt = false;
3323 mci->mci_tolist = tobuf;
3326 mci->mci_nextaddr = NULL;
3327 # endif /* PIPELINING */
3329 for (to = tochain; to != NULL; to = to->q_tchain)
3331 if (!QS_IS_UNMARKED(to->q_state))
3334 /* mark recipient state as "ok so far" */
3335 to->q_state = QS_OK;
3336 e->e_to = to->q_paddr;
3338 i = rscheck("tls_rcpt", to->q_user, NULL, e,
3339 RSF_RMCOMM|RSF_COUNT, 3,
3340 mci->mci_host, e->e_id);
3343 markfailure(e, to, mci, i, false);
3344 giveresponse(i, to->q_status, m, mci,
3345 ctladdr, xstart, e, to);
3346 if (i == EX_TEMPFAIL)
3348 mci->mci_retryrcpt = true;
3349 to->q_state = QS_RETRY;
3353 # endif /* STARTTLS */
3355 i = smtprcpt(to, m, mci, e, ctladdr, xstart);
3358 bitset(MCIF_PIPELINED, mci->mci_flags))
3361 ** Add new element to list of
3362 ** recipients for pipelining.
3365 to->q_pchain = NULL;
3366 if (mci->mci_nextaddr == NULL)
3367 mci->mci_nextaddr = to;
3372 pchain->q_pchain = to;
3373 pchain = pchain->q_pchain;
3376 # endif /* PIPELINING */
3379 markfailure(e, to, mci, i, false);
3380 giveresponse(i, to->q_status, m, mci,
3381 ctladdr, xstart, e, to);
3382 if (i == EX_TEMPFAIL)
3383 to->q_state = QS_RETRY;
3387 /* No recipients in list and no missing responses? */
3388 if (tobuf[0] == '\0'
3390 && mci->mci_nextaddr == NULL
3391 # endif /* PIPELINING */
3396 if (bitset(MCIF_CACHED, mci->mci_flags))
3397 smtprset(m, mci, e);
3401 e->e_to = tobuf + 1;
3402 rcode = smtpdata(m, mci, e, ctladdr, xstart);
3405 if (rcode == EX_TEMPFAIL && nummxhosts > hostnum)
3407 /* try next MX site */
3412 if (ConfigLevel < 2)
3413 _res.options |= RES_DEFNAMES | RES_DNSRCH; /* XXX */
3414 #endif /* NAMED_BIND */
3417 checkfds("after delivery");
3420 ** Do final status disposal.
3421 ** We check for something in tobuf for the SMTP case.
3422 ** If we got a temporary failure, arrange to queue the
3427 if (bitnset(M_LMTP, m->m_flags))
3435 anyok = rcode == EX_OK;
3437 for (to = tochain; to != NULL; to = to->q_tchain)
3439 /* see if address already marked */
3440 if (!QS_IS_OK(to->q_state))
3443 /* if running LMTP, get the status for each address */
3444 if (bitnset(M_LMTP, m->m_flags))
3446 if (lmtp_rcode == EX_OK)
3447 rcode = smtpgetstat(m, mci, e);
3450 strsize += sm_strlcat2(tobuf + strsize, ",",
3452 tobufsize - strsize);
3453 SM_ASSERT(strsize < tobufsize);
3458 e->e_to = to->q_paddr;
3459 markfailure(e, to, mci, rcode, true);
3460 giveresponse(rcode, to->q_status, m, mci,
3461 ctladdr, xstart, e, to);
3462 e->e_to = tobuf + 1;
3468 /* mark bad addresses */
3471 if (goodmxfound && rcode == EX_NOHOST)
3472 rcode = EX_TEMPFAIL;
3473 markfailure(e, to, mci, rcode, true);
3478 /* successful delivery */
3479 to->q_state = QS_SENT;
3480 to->q_statdate = curtime();
3484 ** Checkpoint the send list every few addresses
3487 if (CheckpointInterval > 0 && e->e_nsent >= CheckpointInterval)
3489 queueup(e, false, false);
3493 if (bitnset(M_LOCALMAILER, m->m_flags) &&
3494 bitset(QPINGONSUCCESS, to->q_flags))
3496 to->q_flags |= QDELIVERED;
3497 to->q_status = "2.1.5";
3498 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3499 "%s... Successfully delivered\n",
3502 else if (bitset(QPINGONSUCCESS, to->q_flags) &&
3503 bitset(QPRIMARY, to->q_flags) &&
3504 !bitset(MCIF_DSN, mci->mci_flags))
3506 to->q_flags |= QRELAYED;
3507 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3508 "%s... relayed; expect no further notifications\n",
3511 else if (IS_DLVR_NOTIFY(e) &&
3512 !bitset(MCIF_DLVR_BY, mci->mci_flags) &&
3513 bitset(QPRIMARY, to->q_flags) &&
3514 (!bitset(QHASNOTIFY, to->q_flags) ||
3515 bitset(QPINGONSUCCESS, to->q_flags) ||
3516 bitset(QPINGONFAILURE, to->q_flags) ||
3517 bitset(QPINGONDELAY, to->q_flags)))
3519 /* RFC 2852, 4.1.4.2: no NOTIFY, or not NEVER */
3520 to->q_flags |= QBYNRELAY;
3521 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3522 "%s... Deliver-by notify: relayed\n",
3525 else if (IS_DLVR_TRACE(e) &&
3526 (!bitset(QHASNOTIFY, to->q_flags) ||
3527 bitset(QPINGONSUCCESS, to->q_flags) ||
3528 bitset(QPINGONFAILURE, to->q_flags) ||
3529 bitset(QPINGONDELAY, to->q_flags)) &&
3530 bitset(QPRIMARY, to->q_flags))
3532 /* RFC 2852, 4.1.4: no NOTIFY, or not NEVER */
3533 to->q_flags |= QBYTRACE;
3534 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3535 "%s... Deliver-By trace: relayed\n",
3540 if (bitnset(M_LMTP, m->m_flags))
3543 ** Global information applies to the last recipient only;
3544 ** clear it out to avoid bogus errors.
3548 e->e_statmsg = NULL;
3550 /* reset the mci state for the next transaction */
3552 (mci->mci_state == MCIS_MAIL ||
3553 mci->mci_state == MCIS_RCPT ||
3554 mci->mci_state == MCIS_DATA))
3556 mci->mci_state = MCIS_OPEN;
3557 SmtpPhase = mci->mci_phase = "idle";
3558 sm_setproctitle(true, e, "%s: %s", CurHostName,
3563 if (tobuf[0] != '\0')
3565 giveresponse(rcode, NULL, m, mci, ctladdr, xstart, e, tochain);
3568 ** This code is disabled for now because I am not
3569 ** sure that copying status from the first recipient
3570 ** to all non-status'ed recipients is a good idea.
3573 if (tochain->q_message != NULL &&
3574 !bitnset(M_LMTP, m->m_flags) && rcode != EX_OK)
3576 for (to = tochain->q_tchain; to != NULL;
3579 /* see if address already marked */
3580 if (QS_IS_QUEUEUP(to->q_state) &&
3581 to->q_message == NULL)
3582 to->q_message = sm_rpool_strdup_x(e->e_rpool,
3583 tochain->q_message);
3589 markstats(e, tochain, STATS_NORMAL);
3590 mci_store_persistent(mci);
3592 /* Some recipients were tempfailed, try them on the next host */
3593 if (mci != NULL && mci->mci_retryrcpt && nummxhosts > hostnum)
3595 /* try next MX site */
3599 /* now close the connection */
3600 if (clever && mci != NULL && mci->mci_state != MCIS_CLOSED &&
3601 !bitset(MCIF_CACHED, mci->mci_flags))
3602 smtpquit(m, mci, e);
3609 ** Restore state and return.
3614 /* make absolutely certain 0, 1, and 2 are in use */
3615 (void) sm_snprintf(wbuf, sizeof wbuf,
3616 "%s... end of deliver(%s)",
3617 e->e_to == NULL ? "NO-TO-LIST"
3618 : shortenstring(e->e_to,
3627 ** It was originally necessary to set macro 'g' to NULL
3628 ** because it previously pointed to an auto buffer.
3629 ** We don't do this any more, so this may be unnecessary.
3632 macdefine(&e->e_macro, A_PERM, 'g', (char *) NULL);
3640 ** MARKFAILURE -- mark a failure on a specific address.
3643 ** e -- the envelope we are sending.
3644 ** q -- the address to mark.
3645 ** mci -- mailer connection information.
3646 ** rcode -- the code signifying the particular failure.
3647 ** ovr -- override an existing code?
3653 ** marks the address (and possibly the envelope) with the
3654 ** failure so that an error will be returned or
3655 ** the message will be queued, as appropriate.
3659 markfailure(e, q, mci, rcode, ovr)
3660 register ENVELOPE *e;
3661 register ADDRESS *q;
3666 int save_errno = errno;
3667 char *status = NULL;
3668 char *rstatus = NULL;
3678 q->q_state = QS_QUEUEUP;
3682 q->q_state = QS_BADADDR;
3686 /* find most specific error code possible */
3687 if (mci != NULL && mci->mci_status != NULL)
3689 status = sm_rpool_strdup_x(e->e_rpool, mci->mci_status);
3690 if (mci->mci_rstatus != NULL)
3691 rstatus = sm_rpool_strdup_x(e->e_rpool,
3696 else if (e->e_status != NULL)
3698 status = e->e_status;
3727 case EX_UNAVAILABLE:
3747 if (status != NULL && *status != '\0' && (ovr || q->q_status == NULL ||
3748 *q->q_status == '\0' || *q->q_status < *status))
3750 q->q_status = status;
3751 q->q_rstatus = rstatus;
3753 if (rcode != EX_OK && q->q_rstatus == NULL &&
3754 q->q_mailer != NULL && q->q_mailer->m_diagtype != NULL &&
3755 sm_strcasecmp(q->q_mailer->m_diagtype, "X-UNIX") == 0)
3759 (void) sm_snprintf(buf, sizeof buf, "%d", rcode);
3760 q->q_rstatus = sm_rpool_strdup_x(e->e_rpool, buf);
3763 q->q_statdate = curtime();
3764 if (CurHostName != NULL && CurHostName[0] != '\0' &&
3765 mci != NULL && !bitset(M_LOCALMAILER, mci->mci_flags))
3766 q->q_statmta = sm_rpool_strdup_x(e->e_rpool, CurHostName);
3772 ** ENDMAILER -- Wait for mailer to terminate.
3774 ** We should never get fatal errors (e.g., segmentation
3775 ** violation), so we report those specially. For other
3776 ** errors, we choose a status message (into statmsg),
3777 ** and if it represents an error, we print it.
3780 ** mci -- the mailer connection info.
3781 ** e -- the current envelope.
3782 ** pv -- the parameter vector that invoked the mailer
3783 ** (for error messages).
3786 ** exit code of mailer.
3792 static jmp_buf EndWaitTimeout;
3795 endwaittimeout(ignore)
3799 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3800 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3805 longjmp(EndWaitTimeout, 1);
3809 endmailer(mci, e, pv)
3811 register ENVELOPE *e;
3815 int save_errno = errno;
3817 SM_EVENT *ev = NULL;
3820 mci_unlock_host(mci);
3822 /* close output to mailer */
3823 if (mci->mci_out != NULL)
3825 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
3826 mci->mci_out = NULL;
3829 /* copy any remaining input to transcript */
3830 if (mci->mci_in != NULL && mci->mci_state != MCIS_ERROR &&
3833 while (sfgets(buf, sizeof buf, mci->mci_in,
3834 TimeOuts.to_quit, "Draining Input") != NULL)
3835 (void) sm_io_fputs(e->e_xfp, SM_TIME_DEFAULT, buf);
3839 /* close SASL connection */
3840 if (bitset(MCIF_AUTHACT, mci->mci_flags))
3842 sasl_dispose(&mci->mci_conn);
3843 mci->mci_flags &= ~MCIF_AUTHACT;
3849 (void) endtlsclt(mci);
3850 #endif /* STARTTLS */
3852 /* now close the input */
3853 if (mci->mci_in != NULL)
3855 (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT);
3858 mci->mci_state = MCIS_CLOSED;
3862 /* in the IPC case there is nothing to wait for */
3863 if (mci->mci_pid == 0)
3866 /* put a timeout around the wait */
3867 if (mci->mci_mailer->m_wait > 0)
3869 if (setjmp(EndWaitTimeout) == 0)
3870 ev = sm_setevent(mci->mci_mailer->m_wait,
3874 syserr("endmailer %s: wait timeout (%ld)",
3875 mci->mci_mailer->m_name,
3876 (long) mci->mci_mailer->m_wait);
3881 /* wait for the mailer process, collect status */
3882 st = waitfor(mci->mci_pid);
3890 syserr("endmailer %s: wait", mci->mci_mailer->m_name);
3896 /* normal death -- return status */
3897 return (WEXITSTATUS(st));
3900 /* it died a horrid death */
3901 syserr("451 4.3.0 mailer %s died with signal %d%s",
3902 mci->mci_mailer->m_name, WTERMSIG(st),
3903 WCOREDUMP(st) ? " (core dumped)" :
3904 (WIFSTOPPED(st) ? " (stopped)" : ""));
3906 /* log the arguments */
3907 if (pv != NULL && e->e_xfp != NULL)
3911 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "Arguments:");
3912 for (av = pv; *av != NULL; av++)
3913 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, " %s",
3915 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "\n");
3918 ExitStat = EX_TEMPFAIL;
3922 ** GIVERESPONSE -- Interpret an error response from a mailer
3925 ** status -- the status code from the mailer (high byte
3926 ** only; core dumps must have been taken care of
3928 ** dsn -- the DSN associated with the address, if any.
3929 ** m -- the mailer info for this mailer.
3930 ** mci -- the mailer connection info -- can be NULL if the
3931 ** response is given before the connection is made.
3932 ** ctladdr -- the controlling address for the recipient
3934 ** xstart -- the transaction start time, for computing
3935 ** transaction delays.
3936 ** e -- the current envelope.
3937 ** to -- the current recipient (NULL if none).
3943 ** Errors may be incremented.
3944 ** ExitStat may be set.
3948 giveresponse(status, dsn, m, mci, ctladdr, xstart, e, to)
3958 register const char *statmsg;
3961 bool usestat = false;
3962 char dsnbuf[ENHSCLEN];
3968 syserr("giveresponse: null envelope");
3974 ** Compute status message from code.
3977 exmsg = sm_sysexmsg(status);
3980 statmsg = "250 2.0.0 Sent";
3981 if (e->e_statmsg != NULL)
3983 (void) sm_snprintf(buf, sizeof buf, "%s (%s)",
3985 shortenstring(e->e_statmsg, 403));
3989 else if (exmsg == NULL)
3991 (void) sm_snprintf(buf, sizeof buf,
3992 "554 5.3.0 unknown mailer error %d",
3994 status = EX_UNAVAILABLE;
3998 else if (status == EX_TEMPFAIL)
4002 (void) sm_strlcpy(bp, exmsg + 1, SPACELEFT(buf, bp));
4005 if (h_errno == TRY_AGAIN)
4006 statmsg = sm_errstring(h_errno + E_DNSBASE);
4008 #endif /* NAMED_BIND */
4011 statmsg = sm_errstring(errnum);
4013 statmsg = SmtpError;
4015 if (statmsg != NULL && statmsg[0] != '\0')
4020 case ENETDOWN: /* Network is down */
4021 #endif /* ENETDOWN */
4023 case ENETUNREACH: /* Network is unreachable */
4024 #endif /* ENETUNREACH */
4026 case ENETRESET: /* Network dropped connection on reset */
4027 #endif /* ENETRESET */
4029 case ECONNABORTED: /* Software caused connection abort */
4030 #endif /* ECONNABORTED */
4032 case EHOSTDOWN: /* Host is down */
4033 #endif /* EHOSTDOWN */
4035 case EHOSTUNREACH: /* No route to host */
4036 #endif /* EHOSTUNREACH */
4037 if (mci != NULL && mci->mci_host != NULL)
4039 (void) sm_strlcpyn(bp,
4047 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ": ",
4054 else if (status == EX_NOHOST && h_errno != 0)
4056 statmsg = sm_errstring(h_errno + E_DNSBASE);
4057 (void) sm_snprintf(buf, sizeof buf, "%s (%s)", exmsg + 1,
4062 #endif /* NAMED_BIND */
4066 if (*statmsg++ == ':' && errnum != 0)
4068 (void) sm_snprintf(buf, sizeof buf, "%s: %s", statmsg,
4069 sm_errstring(errnum));
4073 else if (bitnset(M_LMTP, m->m_flags) && e->e_statmsg != NULL)
4075 (void) sm_snprintf(buf, sizeof buf, "%s (%s)", statmsg,
4076 shortenstring(e->e_statmsg, 403));
4083 ** Print the message as appropriate
4086 if (status == EX_OK || status == EX_TEMPFAIL)
4088 extern char MsgBuf[];
4090 if ((off = isenhsc(statmsg + 4, ' ')) > 0)
4094 (void) sm_snprintf(dsnbuf, sizeof dsnbuf,
4095 "%.*s", off, statmsg + 4);
4104 message("%s", statmsg + off);
4105 if (status == EX_TEMPFAIL && e->e_xfp != NULL)
4106 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s\n",
4111 char mbuf[ENHSCLEN + 4];
4114 if ((off = isenhsc(statmsg + 4, ' ')) > 0 &&
4115 off < sizeof mbuf - 4)
4119 (void) sm_snprintf(dsnbuf, sizeof dsnbuf,
4120 "%.*s", off, statmsg + 4);
4125 /* copy only part of statmsg to mbuf */
4126 (void) sm_strlcpy(mbuf, statmsg, off);
4127 (void) sm_strlcat(mbuf, " %s", sizeof mbuf);
4132 (void) sm_snprintf(mbuf, sizeof mbuf, "%.3s %%s",
4136 usrerr(mbuf, &statmsg[off]);
4141 ** Log a record of the transaction. Compute the new
4142 ** ExitStat -- if we already had an error, stick with
4146 if (OpMode != MD_VERIFY && !bitset(EF_VRFYONLY, e->e_flags) &&
4147 LogLevel > ((status == EX_TEMPFAIL) ? 8 : (status == EX_OK) ? 7 : 6))
4148 logdelivery(m, mci, dsn, statmsg + off, ctladdr, xstart, e);
4151 sm_dprintf("giveresponse: status=%d, dsn=%s, e->e_message=%s, errnum=%d\n",
4153 dsn == NULL ? "<NULL>" : dsn,
4154 e->e_message == NULL ? "<NULL>" : e->e_message,
4157 if (status != EX_TEMPFAIL)
4159 if (status != EX_OK && (status != EX_TEMPFAIL || e->e_message == NULL))
4160 e->e_message = sm_rpool_strdup_x(e->e_rpool, statmsg + off);
4161 if (status != EX_OK && to != NULL && to->q_message == NULL)
4163 if (!usestat && e->e_message != NULL)
4164 to->q_message = sm_rpool_strdup_x(e->e_rpool,
4167 to->q_message = sm_rpool_strdup_x(e->e_rpool,
4174 ** LOGDELIVERY -- log the delivery in the system log
4176 ** Care is taken to avoid logging lines that are too long, because
4177 ** some versions of syslog have an unfortunate proclivity for core
4178 ** dumping. This is a hack, to be sure, that is at best empirical.
4181 ** m -- the mailer info. Can be NULL for initial queue.
4182 ** mci -- the mailer connection info -- can be NULL if the
4183 ** log is occurring when no connection is active.
4184 ** dsn -- the DSN attached to the status.
4185 ** status -- the message to print for the status.
4186 ** ctladdr -- the controlling address for the to list.
4187 ** xstart -- the transaction start time, used for
4188 ** computing transaction delay.
4189 ** e -- the current envelope.
4199 logdelivery(m, mci, dsn, status, ctladdr, xstart, e)
4206 register ENVELOPE *e;
4211 time_t now = curtime();
4214 #if (SYSLOG_BUFSIZE) >= 256
4215 /* ctladdr: max 106 bytes */
4217 if (ctladdr != NULL)
4219 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", ctladdr=",
4220 shortenstring(ctladdr->q_paddr, 83));
4222 if (bitset(QGOODUID, ctladdr->q_flags))
4224 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
4225 (int) ctladdr->q_uid,
4226 (int) ctladdr->q_gid);
4231 /* delay & xdelay: max 41 bytes */
4232 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", delay=",
4233 pintvl(now - e->e_ctime, true));
4236 if (xstart != (time_t) 0)
4238 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=",
4239 pintvl(now - xstart, true));
4243 /* mailer: assume about 19 bytes (max 10 byte mailer name) */
4246 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=",
4251 /* pri: changes with each delivery attempt */
4252 (void) sm_snprintf(bp, SPACELEFT(buf, bp), ", pri=%ld",
4256 /* relay: max 66 bytes for IPv4 addresses */
4257 if (mci != NULL && mci->mci_host != NULL)
4259 extern SOCKADDR CurHostAddr;
4261 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", relay=",
4262 shortenstring(mci->mci_host, 40));
4265 if (CurHostAddr.sa.sa_family != 0)
4267 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " [%s]",
4268 anynet_ntoa(&CurHostAddr));
4271 else if (strcmp(status, "quarantined") == 0)
4273 if (e->e_quarmsg != NULL)
4274 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4276 shortenstring(e->e_quarmsg, 40));
4278 else if (strcmp(status, "queued") != 0)
4280 p = macvalue('h', e);
4281 if (p != NULL && p[0] != '\0')
4283 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4284 ", relay=%s", shortenstring(p, 40));
4290 if (dsn != NULL && *dsn != '\0')
4292 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", dsn=",
4293 shortenstring(dsn, ENHSCLEN));
4299 if (e->e_ntries >= 0)
4301 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4302 ", ntries=%d", e->e_ntries + 1);
4305 #endif /* _FFR_LOG_NTRIES */
4307 # define STATLEN (((SYSLOG_BUFSIZE) - 100) / 4)
4311 # endif /* (STATLEN) < 63 */
4312 # if (STATLEN) > 203
4314 # define STATLEN 203
4315 # endif /* (STATLEN) > 203 */
4317 /* stat: max 210 bytes */
4318 if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
4320 /* desperation move -- truncate data */
4321 bp = buf + sizeof buf - ((STATLEN) + 17);
4322 (void) sm_strlcpy(bp, "...", SPACELEFT(buf, bp));
4326 (void) sm_strlcpy(bp, ", stat=", SPACELEFT(buf, bp));
4329 (void) sm_strlcpy(bp, shortenstring(status, STATLEN),
4330 SPACELEFT(buf, bp));
4332 /* id, to: max 13 + TOBUFSIZE bytes */
4333 l = SYSLOG_BUFSIZE - 100 - strlen(buf);
4336 p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
4337 while (strlen(p) >= l)
4341 for (q = p + l; q > p; q--)
4348 sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]%s",
4349 (int) (++q - p), p, buf);
4352 sm_syslog(LOG_INFO, e->e_id, "to=%.*s%s", l, p, buf);
4354 #else /* (SYSLOG_BUFSIZE) >= 256 */
4356 l = SYSLOG_BUFSIZE - 85;
4359 p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
4360 while (strlen(p) >= l)
4364 for (q = p + l; q > p; q--)
4372 sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]",
4373 (int) (++q - p), p);
4376 sm_syslog(LOG_INFO, e->e_id, "to=%.*s", l, p);
4378 if (ctladdr != NULL)
4381 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "ctladdr=",
4382 shortenstring(ctladdr->q_paddr, 83));
4384 if (bitset(QGOODUID, ctladdr->q_flags))
4386 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
4387 ctladdr->q_uid, ctladdr->q_gid);
4390 sm_syslog(LOG_INFO, e->e_id, "%s", buf);
4393 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "delay=",
4394 pintvl(now - e->e_ctime, true));
4396 if (xstart != (time_t) 0)
4398 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=",
4399 pintvl(now - xstart, true));
4405 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=",
4409 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
4413 if (mci != NULL && mci->mci_host != NULL)
4415 extern SOCKADDR CurHostAddr;
4417 (void) sm_snprintf(bp, SPACELEFT(buf, bp), "relay=%.100s",
4421 if (CurHostAddr.sa.sa_family != 0)
4422 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4424 anynet_ntoa(&CurHostAddr));
4426 else if (strcmp(status, "quarantined") == 0)
4428 if (e->e_quarmsg != NULL)
4429 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4430 ", quarantine=%.100s",
4433 else if (strcmp(status, "queued") != 0)
4435 p = macvalue('h', e);
4436 if (p != NULL && p[0] != '\0')
4437 (void) sm_snprintf(buf, sizeof buf, "relay=%.100s", p);
4440 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
4442 sm_syslog(LOG_INFO, e->e_id, "stat=%s", shortenstring(status, 63));
4443 #endif /* (SYSLOG_BUFSIZE) >= 256 */
4446 ** PUTFROMLINE -- output a UNIX-style from line (or whatever)
4448 ** This can be made an arbitrary message separator by changing $l
4450 ** One of the ugliest hacks seen by human eyes is contained herein:
4451 ** UUCP wants those stupid "remote from <host>" lines. Why oh why
4452 ** does a well-meaning programmer such as myself have to deal with
4453 ** this kind of antique garbage????
4456 ** mci -- the connection information.
4457 ** e -- the envelope.
4460 ** true iff line was written successfully
4463 ** outputs some text to fp.
4471 char *template = UnixFromLine;
4475 if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
4478 mci->mci_flags |= MCIF_INHEADER;
4480 if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
4484 expand("\201g", buf, sizeof buf, e);
4485 bang = strchr(buf, '!');
4489 char hname[MAXNAME];
4492 ** If we can construct a UUCP path, do so
4495 at = strrchr(buf, '@');
4498 expand("\201k", hname, sizeof hname, e);
4503 (void) sm_snprintf(xbuf, sizeof xbuf,
4504 "From %.800s \201d remote from %.100s\n",
4510 (void) sm_snprintf(xbuf, sizeof xbuf,
4511 "From %.800s \201d remote from %.100s\n",
4516 expand(template, buf, sizeof buf, e);
4517 return putxline(buf, strlen(buf), mci, PXLF_HEADER);
4521 ** PUTBODY -- put the body of a message.
4524 ** mci -- the connection information.
4525 ** e -- the envelope to put out.
4526 ** separator -- if non-NULL, a message separator that must
4527 ** not be permitted in the resulting message.
4530 ** true iff message was written successfully
4533 ** The message is written onto fp.
4536 /* values for output state variable */
4537 #define OSTATE_HEAD 0 /* at beginning of line */
4538 #define OSTATE_CR 1 /* read a carriage return */
4539 #define OSTATE_INLINE 2 /* putting rest of line */
4542 putbody(mci, e, separator)
4544 register ENVELOPE *e;
4552 char *boundaries[MAXMIMENESTING + 1];
4553 #endif /* MIME8TO7 */
4556 ** Output the body of the message
4559 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
4561 char *df = queuename(e, DATAFL_LETTER);
4563 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df,
4564 SM_IO_RDONLY_B, NULL);
4565 if (e->e_dfp == NULL)
4567 char *msg = "!putbody: Cannot open %s for %s from %s";
4569 if (errno == ENOENT)
4571 syserr(msg, df, e->e_to, e->e_from.q_paddr);
4575 if (e->e_dfp == NULL)
4577 if (bitset(MCIF_INHEADER, mci->mci_flags))
4579 if (!putline("", mci))
4581 mci->mci_flags &= ~MCIF_INHEADER;
4583 if (!putline("<<< No Message Collected >>>", mci))
4588 if (e->e_dfino == (ino_t) 0)
4592 if (fstat(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), &stbuf)
4597 e->e_dfdev = stbuf.st_dev;
4598 e->e_dfino = stbuf.st_ino;
4602 /* paranoia: the data file should always be in a rewound state */
4603 (void) bfrewind(e->e_dfp);
4605 /* simulate an I/O timeout when used as source */
4610 if (bitset(MCIF_CVT8TO7, mci->mci_flags))
4613 ** Do 8 to 7 bit MIME conversion.
4616 /* make sure it looks like a MIME message */
4617 if (hvalue("MIME-Version", e->e_header) == NULL &&
4618 !putline("MIME-Version: 1.0", mci))
4621 if (hvalue("Content-Type", e->e_header) == NULL)
4623 (void) sm_snprintf(buf, sizeof buf,
4624 "Content-Type: text/plain; charset=%s",
4626 if (!putline(buf, mci))
4630 /* now do the hard work */
4631 boundaries[0] = NULL;
4632 mci->mci_flags |= MCIF_INHEADER;
4633 if (mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER, 0) ==
4638 else if (bitset(MCIF_CVT7TO8, mci->mci_flags))
4640 if (!mime7to8(mci, e->e_header, e))
4643 # endif /* MIME7TO8 */
4644 else if (MaxMimeHeaderLength > 0 || MaxMimeFieldLength > 0)
4646 bool oldsuprerrs = SuprErrs;
4648 /* Use mime8to7 to check multipart for MIME header overflows */
4649 boundaries[0] = NULL;
4650 mci->mci_flags |= MCIF_INHEADER;
4653 ** If EF_DONT_MIME is set, we have a broken MIME message
4654 ** and don't want to generate a new bounce message whose
4655 ** body propagates the broken MIME. We can't just not call
4656 ** mime8to7() as is done above since we need the security
4657 ** checks. The best we can do is suppress the errors.
4660 if (bitset(EF_DONT_MIME, e->e_flags))
4663 if (mime8to7(mci, e->e_header, e, boundaries,
4664 M87F_OUTER|M87F_NO8TO7, 0) == SM_IO_EOF)
4667 /* restore SuprErrs */
4668 SuprErrs = oldsuprerrs;
4671 #endif /* MIME8TO7 */
4683 if (bitset(MCIF_INHEADER, mci->mci_flags))
4685 if (!putline("", mci))
4687 mci->mci_flags &= ~MCIF_INHEADER;
4690 /* determine end of buffer; allow for short mailer lines */
4691 buflim = &buf[sizeof buf - 1];
4692 if (mci->mci_mailer->m_linelimit > 0 &&
4693 mci->mci_mailer->m_linelimit < sizeof buf - 1)
4694 buflim = &buf[mci->mci_mailer->m_linelimit - 1];
4696 /* copy temp file to output with mapping */
4697 ostate = OSTATE_HEAD;
4700 while (!sm_io_error(mci->mci_out) && !dead)
4704 else if ((c = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT))
4707 if (bitset(MCIF_7BIT, mci->mci_flags))
4714 mci->mci_mailer->m_flags))
4716 if (c != '\r' && c != '\n' && bp < buflim)
4722 /* check beginning of line for special cases */
4726 if (buf[0] == 'F' &&
4727 bitnset(M_ESCFROM, mci->mci_mailer->m_flags)
4728 && strncmp(buf, "From ", 5) == 0)
4732 if (buf[0] == '-' && buf[1] == '-' &&
4735 /* possible separator */
4736 int sl = strlen(separator);
4738 if (strncmp(&buf[2], separator, sl)
4742 if (buf[0] == '.' &&
4743 bitnset(M_XDOT, mci->mci_mailer->m_flags))
4748 /* now copy out saved line */
4749 if (TrafficLogFile != NULL)
4751 (void) sm_io_fprintf(TrafficLogFile,
4755 if (padc != SM_IO_EOF)
4756 (void) sm_io_putc(TrafficLogFile,
4759 for (xp = buf; xp < bp; xp++)
4760 (void) sm_io_putc(TrafficLogFile,
4762 (unsigned char) *xp);
4764 (void) sm_io_fputs(TrafficLogFile,
4766 mci->mci_mailer->m_eol);
4768 if (padc != SM_IO_EOF)
4770 if (sm_io_putc(mci->mci_out,
4771 SM_TIME_DEFAULT, padc)
4779 for (xp = buf; xp < bp; xp++)
4781 if (sm_io_putc(mci->mci_out,
4783 (unsigned char) *xp)
4794 if (sm_io_fputs(mci->mci_out,
4796 mci->mci_mailer->m_eol)
4806 SM_ASSERT(pbp < peekbuf +
4814 /* determine next state */
4816 ostate = OSTATE_HEAD;
4820 ostate = OSTATE_INLINE;
4827 if (sm_io_fputs(mci->mci_out,
4829 mci->mci_mailer->m_eol)
4833 if (TrafficLogFile != NULL)
4835 (void) sm_io_fputs(TrafficLogFile,
4837 mci->mci_mailer->m_eol);
4839 ostate = OSTATE_HEAD;
4843 /* had a naked carriage return */
4844 SM_ASSERT(pbp < peekbuf + sizeof(peekbuf));
4847 ostate = OSTATE_INLINE;
4858 mci->mci_mailer->m_flags))
4861 if (mci->mci_mailer->m_linelimit > 0 &&
4862 pos >= mci->mci_mailer->m_linelimit - 1 &&
4867 /* check next character for EOL */
4870 else if ((d = sm_io_getc(e->e_dfp,
4874 SM_ASSERT(pbp < peekbuf +
4879 if (d == '\n' || d == SM_IO_EOF)
4881 if (TrafficLogFile != NULL)
4882 (void) sm_io_putc(TrafficLogFile,
4885 if (sm_io_putc(mci->mci_out,
4897 if (sm_io_putc(mci->mci_out,
4898 SM_TIME_DEFAULT, '!')
4900 sm_io_fputs(mci->mci_out,
4902 mci->mci_mailer->m_eol)
4909 if (TrafficLogFile != NULL)
4911 (void) sm_io_fprintf(TrafficLogFile,
4914 mci->mci_mailer->m_eol);
4916 ostate = OSTATE_HEAD;
4917 SM_ASSERT(pbp < peekbuf +
4924 if (TrafficLogFile != NULL)
4925 (void) sm_io_fputs(TrafficLogFile,
4927 mci->mci_mailer->m_eol);
4928 if (sm_io_fputs(mci->mci_out,
4930 mci->mci_mailer->m_eol)
4934 ostate = OSTATE_HEAD;
4938 if (TrafficLogFile != NULL)
4939 (void) sm_io_putc(TrafficLogFile,
4942 if (sm_io_putc(mci->mci_out,
4951 ostate = OSTATE_INLINE;
4957 /* make sure we are at the beginning of a line */
4960 if (TrafficLogFile != NULL)
4962 for (xp = buf; xp < bp; xp++)
4963 (void) sm_io_putc(TrafficLogFile,
4965 (unsigned char) *xp);
4967 for (xp = buf; xp < bp; xp++)
4969 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT,
4970 (unsigned char) *xp)
4979 if (!dead && pos > 0)
4981 if (TrafficLogFile != NULL)
4982 (void) sm_io_fputs(TrafficLogFile,
4984 mci->mci_mailer->m_eol);
4985 if (sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT,
4986 mci->mci_mailer->m_eol) == SM_IO_EOF)
4991 if (sm_io_error(e->e_dfp))
4993 syserr("putbody: %s/%cf%s: read error",
4994 qid_printqueue(e->e_dfqgrp, e->e_dfqdir),
4995 DATAFL_LETTER, e->e_id);
4996 ExitStat = EX_IOERR;
5002 ** Since mailfile() uses e_dfp in a child process,
5003 ** the file offset in the stdio library for the
5004 ** parent process will not agree with the in-kernel
5005 ** file offset since the file descriptor is shared
5006 ** between the processes. Therefore, it is vital
5007 ** that the file always be rewound. This forces the
5008 ** kernel offset (lseek) and stdio library (ftell)
5013 if (e->e_dfp != NULL)
5014 (void) bfrewind(e->e_dfp);
5016 /* some mailers want extra blank line at end of message */
5017 if (!dead && bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
5018 buf[0] != '\0' && buf[0] != '\n')
5020 if (!putline("", mci))
5025 (sm_io_flush(mci->mci_out, SM_TIME_DEFAULT) == SM_IO_EOF ||
5026 (sm_io_error(mci->mci_out) && errno != EPIPE)))
5029 syserr("putbody: write error");
5030 ExitStat = EX_IOERR;
5035 return !dead && !ioerr;
5042 ** MAILFILE -- Send a message to a file.
5044 ** If the file has the set-user-ID/set-group-ID bits set, but NO
5045 ** execute bits, sendmail will try to become the owner of that file
5046 ** rather than the real user. Obviously, this only works if
5047 ** sendmail runs as root.
5049 ** This could be done as a subordinate mailer, except that it
5050 ** is used implicitly to save messages in ~/dead.letter. We
5051 ** view this as being sufficiently important as to include it
5052 ** here. For example, if the system is dying, we shouldn't have
5053 ** to create another process plus some pipes to save the message.
5056 ** filename -- the name of the file to send to.
5057 ** mailer -- mailer definition for recipient -- if NULL,
5059 ** ctladdr -- the controlling address header -- includes
5060 ** the userid/groupid to be when sending.
5061 ** sfflags -- flags for opening.
5062 ** e -- the current envelope.
5065 ** The exit code associated with the operation.
5071 # define RETURN(st) exit(st);
5073 static jmp_buf CtxMailfileTimeout;
5076 mailfile(filename, mailer, ctladdr, sfflags, e)
5077 char *volatile filename;
5078 MAILER *volatile mailer;
5080 volatile long sfflags;
5081 register ENVELOPE *e;
5083 register SM_FILE_T *f;
5084 register pid_t pid = -1;
5088 bool suidwarn = geteuid() == 0;
5090 char *volatile realfile;
5092 char buf[MAXPATHLEN];
5093 char targetfile[MAXPATHLEN];
5097 sm_dprintf("mailfile %s\n ctladdr=", filename);
5098 printaddr(sm_debug_file(), ctladdr, false);
5102 mailer = FileMailer;
5104 if (e->e_xfp != NULL)
5105 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
5108 ** Special case /dev/null. This allows us to restrict file
5109 ** delivery to regular files only.
5112 if (sm_path_isdevnull(filename))
5115 /* check for 8-bit available */
5116 if (bitset(EF_HAS8BIT, e->e_flags) &&
5117 bitnset(M_7BITS, mailer->m_flags) &&
5118 (bitset(EF_DONT_MIME, e->e_flags) ||
5119 !(bitset(MM_MIME8BIT, MimeMode) ||
5120 (bitset(EF_IS_MIME, e->e_flags) &&
5121 bitset(MM_CVTMIME, MimeMode)))))
5123 e->e_status = "5.6.3";
5124 usrerrenh(e->e_status,
5125 "554 Cannot send 8-bit data to 7-bit destination");
5130 /* Find the actual file */
5131 if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0')
5133 len = strlen(SafeFileEnv);
5135 if (strncmp(SafeFileEnv, filename, len) == 0)
5138 if (len + strlen(filename) + 1 >= sizeof targetfile)
5140 syserr("mailfile: filename too long (%s/%s)",
5141 SafeFileEnv, filename);
5142 return EX_CANTCREAT;
5144 (void) sm_strlcpy(targetfile, SafeFileEnv, sizeof targetfile);
5145 realfile = targetfile + len;
5146 if (*filename == '/')
5148 if (*filename != '\0')
5150 /* paranoia: trailing / should be removed in readcf */
5151 if (targetfile[len - 1] != '/')
5152 (void) sm_strlcat(targetfile,
5153 "/", sizeof targetfile);
5154 (void) sm_strlcat(targetfile, filename,
5158 else if (mailer->m_rootdir != NULL)
5160 expand(mailer->m_rootdir, targetfile, sizeof targetfile, e);
5161 len = strlen(targetfile);
5163 if (strncmp(targetfile, filename, len) == 0)
5166 if (len + strlen(filename) + 1 >= sizeof targetfile)
5168 syserr("mailfile: filename too long (%s/%s)",
5169 targetfile, filename);
5170 return EX_CANTCREAT;
5172 realfile = targetfile + len;
5173 if (targetfile[len - 1] != '/')
5174 (void) sm_strlcat(targetfile, "/", sizeof targetfile);
5175 if (*filename == '/')
5176 (void) sm_strlcat(targetfile, filename + 1,
5179 (void) sm_strlcat(targetfile, filename,
5184 if (sm_strlcpy(targetfile, filename, sizeof targetfile) >=
5187 syserr("mailfile: filename too long (%s)", filename);
5188 return EX_CANTCREAT;
5190 realfile = targetfile;
5194 ** Fork so we can change permissions here.
5195 ** Note that we MUST use fork, not vfork, because of
5196 ** the complications of calling subroutines, etc.
5201 ** Dispose of SIGCHLD signal catchers that may be laying
5202 ** around so that the waitfor() below will get it.
5205 (void) sm_signal(SIGCHLD, SIG_DFL);
5213 /* child -- actually write to file */
5217 volatile int oflags = O_WRONLY|O_APPEND;
5219 /* Reset global flags */
5220 RestartRequest = NULL;
5221 RestartWorkGroup = false;
5222 ShutdownRequest = NULL;
5224 CurrentPid = getpid();
5226 if (e->e_lockfp != NULL)
5230 fd = sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL);
5231 /* SM_ASSERT(fd >= 0); */
5236 (void) sm_signal(SIGINT, SIG_DFL);
5237 (void) sm_signal(SIGHUP, SIG_DFL);
5238 (void) sm_signal(SIGTERM, SIG_DFL);
5239 (void) umask(OldUmask);
5243 if (setjmp(CtxMailfileTimeout) != 0)
5245 RETURN(EX_TEMPFAIL);
5248 if (TimeOuts.to_fileopen > 0)
5249 ev = sm_setevent(TimeOuts.to_fileopen, mailfiletimeout,
5254 /* check file mode to see if set-user-ID */
5255 if (stat(targetfile, &stb) < 0)
5260 /* limit the errors to those actually caused in the child */
5264 /* Allow alias expansions to use the S_IS{U,G}ID bits */
5265 if ((ctladdr != NULL && !bitset(QALIAS, ctladdr->q_flags)) ||
5266 bitset(SFF_RUNASREALUID, sfflags))
5268 /* ignore set-user-ID and set-group-ID bits */
5269 mode &= ~(S_ISGID|S_ISUID);
5271 sm_dprintf("mailfile: ignoring set-user-ID/set-group-ID bits\n");
5274 /* we have to open the data file BEFORE setuid() */
5275 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
5277 char *df = queuename(e, DATAFL_LETTER);
5279 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df,
5280 SM_IO_RDONLY_B, NULL);
5281 if (e->e_dfp == NULL)
5283 syserr("mailfile: Cannot open %s for %s from %s",
5284 df, e->e_to, e->e_from.q_paddr);
5288 /* select a new user to run as */
5289 if (!bitset(SFF_RUNASREALUID, sfflags))
5291 if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
5293 RealUserName = NULL;
5294 if (mailer->m_uid == NO_UID)
5297 RealUid = mailer->m_uid;
5298 if (RunAsUid != 0 && RealUid != RunAsUid)
5300 /* Only root can change the uid */
5301 syserr("mailfile: insufficient privileges to change uid, RunAsUid=%d, RealUid=%d",
5302 (int) RunAsUid, (int) RealUid);
5303 RETURN(EX_TEMPFAIL);
5306 else if (bitset(S_ISUID, mode))
5308 RealUserName = NULL;
5309 RealUid = stb.st_uid;
5311 else if (ctladdr != NULL && ctladdr->q_uid != 0)
5313 if (ctladdr->q_ruser != NULL)
5314 RealUserName = ctladdr->q_ruser;
5316 RealUserName = ctladdr->q_user;
5317 RealUid = ctladdr->q_uid;
5319 else if (mailer != NULL && mailer->m_uid != NO_UID)
5321 RealUserName = DefUser;
5322 RealUid = mailer->m_uid;
5326 RealUserName = DefUser;
5330 /* select a new group to run as */
5331 if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
5333 if (mailer->m_gid == NO_GID)
5336 RealGid = mailer->m_gid;
5337 if (RunAsUid != 0 &&
5338 (RealGid != getgid() ||
5339 RealGid != getegid()))
5341 /* Only root can change the gid */
5342 syserr("mailfile: insufficient privileges to change gid, RealGid=%d, RunAsUid=%d, gid=%d, egid=%d",
5343 (int) RealGid, (int) RunAsUid,
5344 (int) getgid(), (int) getegid());
5345 RETURN(EX_TEMPFAIL);
5348 else if (bitset(S_ISGID, mode))
5349 RealGid = stb.st_gid;
5350 else if (ctladdr != NULL &&
5351 ctladdr->q_uid == DefUid &&
5352 ctladdr->q_gid == 0)
5355 ** Special case: This means it is an
5356 ** alias and we should act as DefaultUser.
5357 ** See alias()'s comments.
5361 RealUserName = DefUser;
5363 else if (ctladdr != NULL && ctladdr->q_uid != 0)
5364 RealGid = ctladdr->q_gid;
5365 else if (mailer != NULL && mailer->m_gid != NO_GID)
5366 RealGid = mailer->m_gid;
5372 if (!bitset(SFF_ROOTOK, sfflags))
5380 /* set group id list (needs /etc/group access) */
5381 if (RealUserName != NULL && !DontInitGroups)
5383 if (initgroups(RealUserName, RealGid) == -1 && suidwarn)
5385 syserr("mailfile: initgroups(%s, %d) failed",
5386 RealUserName, RealGid);
5387 RETURN(EX_TEMPFAIL);
5394 gidset[0] = RealGid;
5395 if (setgroups(1, gidset) == -1 && suidwarn)
5397 syserr("mailfile: setgroups() failed");
5398 RETURN(EX_TEMPFAIL);
5403 ** If you have a safe environment, go into it.
5406 if (realfile != targetfile)
5413 sm_dprintf("mailfile: chroot %s\n", targetfile);
5414 if (chroot(targetfile) < 0)
5416 syserr("mailfile: Cannot chroot(%s)",
5418 RETURN(EX_CANTCREAT);
5424 sm_dprintf("mailfile: deliver to %s\n", realfile);
5428 syserr("mailfile: cannot chdir(/)");
5429 RETURN(EX_CANTCREAT);
5432 /* now reset the group and user ids */
5434 sm_mbdb_terminate();
5435 if (setgid(RealGid) < 0 && suidwarn)
5437 syserr("mailfile: setgid(%ld) failed", (long) RealGid);
5438 RETURN(EX_TEMPFAIL);
5440 vendor_set_uid(RealUid);
5441 if (setuid(RealUid) < 0 && suidwarn)
5443 syserr("mailfile: setuid(%ld) failed", (long) RealUid);
5444 RETURN(EX_TEMPFAIL);
5448 sm_dprintf("mailfile: running as r/euid=%d/%d, r/egid=%d/%d\n",
5449 (int) getuid(), (int) geteuid(),
5450 (int) getgid(), (int) getegid());
5453 /* move into some "safe" directory */
5454 if (mailer->m_execdir != NULL)
5458 for (p = mailer->m_execdir; p != NULL; p = q)
5463 expand(p, buf, sizeof buf, e);
5467 sm_dprintf("mailfile: trydir %s\n",
5469 if (buf[0] != '\0' && chdir(buf) >= 0)
5475 ** Recheck the file after we have assumed the ID of the
5476 ** delivery user to make sure we can deliver to it as
5477 ** that user. This is necessary if sendmail is running
5478 ** as root and the file is on an NFS mount which treats
5483 if (bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
5484 err = stat(realfile, &stb);
5486 err = lstat(realfile, &stb);
5487 #else /* HASLSTAT */
5488 err = stat(realfile, &stb);
5489 #endif /* HASLSTAT */
5493 stb.st_mode = ST_MODE_NOFILE;
5495 oflags |= O_CREAT|O_EXCL;
5497 else if (bitset(S_IXUSR|S_IXGRP|S_IXOTH, mode) ||
5498 (!bitnset(DBS_FILEDELIVERYTOHARDLINK,
5499 DontBlameSendmail) &&
5500 stb.st_nlink != 1) ||
5501 (realfile != targetfile && !S_ISREG(mode)))
5506 if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
5507 sfflags |= SFF_NOSLINK;
5508 if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
5509 sfflags |= SFF_NOHLINK;
5510 sfflags &= ~SFF_OPENASROOT;
5511 f = safefopen(realfile, oflags, mode, sfflags);
5514 if (transienterror(errno))
5516 usrerr("454 4.3.0 cannot open %s: %s",
5517 shortenstring(realfile, MAXSHORTSTR),
5518 sm_errstring(errno));
5519 RETURN(EX_TEMPFAIL);
5523 usrerr("554 5.3.0 cannot open %s: %s",
5524 shortenstring(realfile, MAXSHORTSTR),
5525 sm_errstring(errno));
5526 RETURN(EX_CANTCREAT);
5529 if (filechanged(realfile, sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5532 syserr("554 5.3.0 file changed after open");
5533 RETURN(EX_CANTCREAT);
5535 if (fstat(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), &stb) < 0)
5537 syserr("554 5.3.0 cannot fstat %s",
5538 sm_errstring(errno));
5539 RETURN(EX_CANTCREAT);
5542 curoff = stb.st_size;
5547 memset(&mcibuf, '\0', sizeof mcibuf);
5548 mcibuf.mci_mailer = mailer;
5550 if (bitnset(M_7BITS, mailer->m_flags))
5551 mcibuf.mci_flags |= MCIF_7BIT;
5553 /* clear out per-message flags from connection structure */
5554 mcibuf.mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
5556 if (bitset(EF_HAS8BIT, e->e_flags) &&
5557 !bitset(EF_DONT_MIME, e->e_flags) &&
5558 bitnset(M_7BITS, mailer->m_flags))
5559 mcibuf.mci_flags |= MCIF_CVT8TO7;
5562 if (bitnset(M_MAKE8BIT, mailer->m_flags) &&
5563 !bitset(MCIF_7BIT, mcibuf.mci_flags) &&
5564 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
5565 (sm_strcasecmp(p, "quoted-printable") == 0 ||
5566 sm_strcasecmp(p, "base64") == 0) &&
5567 (p = hvalue("Content-Type", e->e_header)) != NULL)
5569 /* may want to convert 7 -> 8 */
5570 /* XXX should really parse it here -- and use a class XXX */
5571 if (sm_strncasecmp(p, "text/plain", 10) == 0 &&
5572 (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
5573 mcibuf.mci_flags |= MCIF_CVT7TO8;
5575 #endif /* MIME7TO8 */
5577 if (!putfromline(&mcibuf, e) ||
5578 !(*e->e_puthdr)(&mcibuf, e->e_header, e, M87F_OUTER) ||
5579 !(*e->e_putbody)(&mcibuf, e, NULL) ||
5580 !putline("\n", &mcibuf) ||
5581 (sm_io_flush(f, SM_TIME_DEFAULT) != 0 ||
5582 (SuperSafe != SAFE_NO &&
5583 fsync(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL)) < 0) ||
5588 (void) ftruncate(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5590 #endif /* !NOFTRUNCATE */
5593 /* reset ISUID & ISGID bits for paranoid systems */
5595 (void) fchmod(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5597 #else /* HASFCHMOD */
5598 (void) chmod(filename, (MODE_T) mode);
5599 #endif /* HASFCHMOD */
5600 if (sm_io_close(f, SM_TIME_DEFAULT) < 0)
5602 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
5603 (void) setuid(RealUid);
5609 /* parent -- wait for exit status */
5615 syserr("mailfile: %s: wait", mailer->m_name);
5621 return (WEXITSTATUS(st));
5625 syserr("mailfile: %s: child died on signal %d",
5626 mailer->m_name, st);
5627 return EX_UNAVAILABLE;
5631 return EX_UNAVAILABLE; /* avoid compiler warning on IRIX */
5635 mailfiletimeout(ignore)
5639 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
5640 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
5645 longjmp(CtxMailfileTimeout, 1);
5648 ** HOSTSIGNATURE -- return the "signature" for a host.
5650 ** The signature describes how we are going to send this -- it
5651 ** can be just the hostname (for non-Internet hosts) or can be
5652 ** an ordered list of MX hosts.
5655 ** m -- the mailer describing this host.
5656 ** host -- the host name.
5659 ** The signature for this host.
5662 ** Can tweak the symbol table.
5665 #define MAXHOSTSIGNATURE 8192 /* max len of hostsignature */
5668 hostsignature(m, host)
5684 int oldoptions = _res.options;
5685 char *mxhosts[MAXMXHOSTS + 1];
5686 unsigned short mxprefs[MAXMXHOSTS + 1];
5687 #endif /* NAMED_BIND */
5690 sm_dprintf("hostsignature(%s)\n", host);
5693 ** If local delivery (and not remote), just return a constant.
5696 if (bitnset(M_LOCALMAILER, m->m_flags) &&
5697 strcmp(m->m_mailer, "[IPC]") != 0 &&
5698 !(m->m_argv[0] != NULL && strcmp(m->m_argv[0], "TCP") == 0))
5701 /* an empty host does not have MX records */
5706 ** Check to see if this uses IPC -- if not, it can't have MX records.
5709 if (strcmp(m->m_mailer, "[IPC]") != 0 ||
5710 CurEnv->e_sendmode == SM_DEFER)
5712 /* just an ordinary mailer or deferred mode */
5716 else if (m->m_argv[0] != NULL &&
5717 strcmp(m->m_argv[0], "FILE") == 0)
5719 /* rendezvous in the file system, no MX records */
5722 #endif /* NETUNIX */
5725 ** Look it up in the symbol table.
5729 s = stab(host, ST_HOSTSIG, ST_ENTER);
5730 if (s->s_hostsig.hs_sig != NULL)
5732 if (s->s_hostsig.hs_exp >= now)
5735 sm_dprintf("hostsignature(): stab(%s) found %s\n", host,
5736 s->s_hostsig.hs_sig);
5737 return s->s_hostsig.hs_sig;
5740 /* signature is expired: clear it */
5741 sm_free(s->s_hostsig.hs_sig);
5742 s->s_hostsig.hs_sig = NULL;
5745 /* set default TTL */
5746 s->s_hostsig.hs_exp = now + SM_DEFAULT_TTL;
5749 ** Not already there or expired -- create a signature.
5753 if (ConfigLevel < 2)
5754 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */
5756 for (hp = host; hp != NULL; hp = endp)
5761 endp = strchr(hp + 1, ']');
5763 endp = strpbrk(endp + 1, ":,");
5766 endp = strpbrk(hp, ":,");
5767 #else /* NETINET6 */
5768 endp = strpbrk(hp, ":,");
5769 #endif /* NETINET6 */
5776 if (bitnset(M_NOMX, m->m_flags))
5778 /* skip MX lookups */
5787 nmx = getmxrr(hp, mxhosts, mxprefs, true, &rcode, true,
5794 /* update the connection info for this host */
5796 mci = mci_get(hp, m);
5797 mci->mci_errno = save_errno;
5798 mci->mci_herrno = h_errno;
5799 mci->mci_lastuse = now;
5800 if (rcode == EX_NOHOST)
5801 mci_setstat(mci, rcode, "5.1.2",
5802 "550 Host unknown");
5804 mci_setstat(mci, rcode, NULL, NULL);
5806 /* use the original host name as signature */
5811 sm_dprintf("hostsignature(): getmxrr() returned %d, mxhosts[0]=%s\n",
5815 ** Set new TTL: we use only one!
5816 ** We could try to use the minimum instead.
5819 s->s_hostsig.hs_exp = now + SM_MIN(ttl, SM_DEFAULT_TTL);
5823 for (i = 0; i < nmx; i++)
5824 len += strlen(mxhosts[i]) + 1;
5825 if (s->s_hostsig.hs_sig != NULL)
5826 len += strlen(s->s_hostsig.hs_sig) + 1;
5827 if (len < 0 || len >= MAXHOSTSIGNATURE)
5829 sm_syslog(LOG_WARNING, NOQID, "hostsignature for host '%s' exceeds maxlen (%d): %d",
5830 host, MAXHOSTSIGNATURE, len);
5831 len = MAXHOSTSIGNATURE;
5833 p = sm_pmalloc_x(len);
5834 if (s->s_hostsig.hs_sig != NULL)
5836 (void) sm_strlcpy(p, s->s_hostsig.hs_sig, len);
5837 sm_free(s->s_hostsig.hs_sig); /* XXX */
5838 s->s_hostsig.hs_sig = p;
5845 s->s_hostsig.hs_sig = p;
5846 for (i = 0; i < nmx; i++)
5848 hl = strlen(mxhosts[i]);
5849 if (len - 1 < hl || len <= 1)
5851 /* force to drop out of outer loop */
5857 if (mxprefs[i] == mxprefs[i - 1])
5863 (void) sm_strlcpy(p, mxhosts[i], len);
5869 ** break out of loop if len exceeded MAXHOSTSIGNATURE
5870 ** because we won't have more space for further hosts
5871 ** anyway (separated by : in the .cf file).
5880 makelower(s->s_hostsig.hs_sig);
5881 if (ConfigLevel < 2)
5882 _res.options = oldoptions;
5883 #else /* NAMED_BIND */
5884 /* not using BIND -- the signature is just the host name */
5886 ** 'host' points to storage that will be freed after we are
5887 ** done processing the current envelope, so we copy it.
5889 s->s_hostsig.hs_sig = sm_pstrdup_x(host);
5890 #endif /* NAMED_BIND */
5892 sm_dprintf("hostsignature(%s) = %s\n", host, s->s_hostsig.hs_sig);
5893 return s->s_hostsig.hs_sig;
5896 ** PARSE_HOSTSIGNATURE -- parse the "signature" and return MX host array.
5898 ** The signature describes how we are going to send this -- it
5899 ** can be just the hostname (for non-Internet hosts) or can be
5900 ** an ordered list of MX hosts which must be randomized for equal
5901 ** MX preference values.
5904 ** sig -- the host signature.
5905 ** mxhosts -- array to populate.
5906 ** mailer -- mailer.
5909 ** The number of hosts inserted into mxhosts array.
5912 ** Randomizes equal MX preference hosts in mxhosts.
5916 parse_hostsignature(sig, mxhosts, mailer)
5921 unsigned short curpref = 0;
5922 int nmx = 0, i, j; /* NOTE: i, j, and nmx must have same type */
5924 unsigned short prefer[MAXMXHOSTS];
5925 long rndm[MAXMXHOSTS];
5927 for (hp = sig; hp != NULL; hp = endp)
5934 endp = strchr(hp + 1, ']');
5936 endp = strpbrk(endp + 1, ":,");
5939 endp = strpbrk(hp, ":,");
5940 #else /* NETINET6 */
5941 endp = strpbrk(hp, ":,");
5942 #endif /* NETINET6 */
5950 prefer[nmx] = curpref;
5951 if (mci_match(hp, mailer))
5954 rndm[nmx] = get_random();
5959 ** Since we don't have the original MX prefs,
5960 ** make our own. If the separator is a ':', that
5961 ** means the preference for the next host will be
5962 ** higher than this one, so simply increment curpref.
5970 if (++nmx >= MAXMXHOSTS)
5974 /* sort the records using the random factor for equal preferences */
5975 for (i = 0; i < nmx; i++)
5977 for (j = i + 1; j < nmx; j++)
5980 ** List is already sorted by MX preference, only
5981 ** need to look for equal preference MX records
5984 if (prefer[i] < prefer[j])
5987 if (prefer[i] > prefer[j] ||
5988 (prefer[i] == prefer[j] && rndm[i] > rndm[j]))
5990 register unsigned short tempp;
5991 register long tempr;
5992 register char *temp1;
5995 prefer[i] = prefer[j];
5998 mxhosts[i] = mxhosts[j];
6010 static SSL_CTX *clt_ctx = NULL;
6011 static bool tls_ok_clt = true;
6014 ** SETCLTTLS -- client side TLS: allow/disallow.
6017 ** tls_ok -- should tls be done?
6023 ** sets tls_ok_clt (static variable in this module)
6030 tls_ok_clt = tls_ok;
6034 ** INITCLTTLS -- initialize client side TLS
6037 ** tls_ok -- should tls initialization be done?
6043 ** sets tls_ok_clt (static variable in this module)
6052 tls_ok_clt = tls_ok;
6055 if (clt_ctx != NULL)
6056 return true; /* already done */
6057 tls_ok_clt = inittls(&clt_ctx, TLS_I_CLT, false, CltCertFile,
6058 CltKeyFile, CACertPath, CACertFile, DHParams);
6063 ** STARTTLS -- try to start secure connection (client side)
6067 ** mci -- the mailer connection info.
6068 ** e -- the envelope.
6072 ** (maybe this should be some other code than EX_
6073 ** that denotes which stage failed.)
6085 SSL *clt_ssl = NULL;
6088 if (clt_ctx == NULL && !initclttls(true))
6090 smtpmessage("STARTTLS", m, mci);
6093 smtpresult = reply(m, mci, e, TimeOuts.to_starttls, NULL, NULL,
6096 /* check return code from server */
6097 if (REPLYTYPE(smtpresult) == 4)
6099 if (smtpresult == 501)
6101 if (smtpresult == -1)
6104 /* not an expected reply but we have to deal with it */
6105 if (REPLYTYPE(smtpresult) == 5)
6106 return EX_UNAVAILABLE;
6107 if (smtpresult != 220)
6111 sm_syslog(LOG_INFO, NOQID, "STARTTLS=client, start=ok");
6113 /* start connection */
6114 if ((clt_ssl = SSL_new(clt_ctx)) == NULL)
6118 sm_syslog(LOG_ERR, NOQID,
6119 "STARTTLS=client, error: SSL_new failed");
6121 tlslogerr("client");
6126 rfd = sm_io_getinfo(mci->mci_in, SM_IO_WHAT_FD, NULL);
6127 wfd = sm_io_getinfo(mci->mci_out, SM_IO_WHAT_FD, NULL);
6129 /* SSL_clear(clt_ssl); ? */
6130 if (rfd < 0 || wfd < 0 ||
6131 (result = SSL_set_rfd(clt_ssl, rfd)) != 1 ||
6132 (result = SSL_set_wfd(clt_ssl, wfd)) != 1)
6136 sm_syslog(LOG_ERR, NOQID,
6137 "STARTTLS=client, error: SSL_set_xfd failed=%d",
6140 tlslogerr("client");
6144 SSL_set_connect_state(clt_ssl);
6145 tlsstart = curtime();
6148 if ((result = SSL_connect(clt_ssl)) <= 0)
6152 ssl_err = SSL_get_error(clt_ssl, result);
6153 i = tls_retry(clt_ssl, rfd, wfd, tlsstart,
6154 TimeOuts.to_starttls, ssl_err, "client");
6160 sm_syslog(LOG_WARNING, NOQID,
6161 "STARTTLS=client, error: connect failed=%d, SSL_error=%d, errno=%d, retry=%d",
6162 result, ssl_err, errno, i);
6164 tlslogerr("client");
6171 mci->mci_ssl = clt_ssl;
6172 result = tls_get_info(mci->mci_ssl, false, mci->mci_host,
6173 &mci->mci_macro, true);
6175 /* switch to use TLS... */
6176 if (sfdctls(&mci->mci_in, &mci->mci_out, mci->mci_ssl) == 0)
6185 ** ENDTLSCLT -- shutdown secure connection (client side)
6188 ** mci -- the mailer connection info.
6200 if (!bitset(MCIF_TLSACT, mci->mci_flags))
6202 r = endtls(mci->mci_ssl, "client");
6203 mci->mci_flags &= ~MCIF_TLSACT;
6206 # endif /* STARTTLS */
6207 # if STARTTLS || SASL
6209 ** ISCLTFLGSET -- check whether client flag is set.
6213 ** flag -- flag to check in {client_flags}
6216 ** true iff flag is set.
6220 iscltflgset(e, flag)
6226 p = macvalue(macid("{client_flags}"), e);
6229 for (; *p != '\0'; p++)
6231 /* look for just this one flag */
6232 if (*p == (char) flag)
6237 # endif /* STARTTLS || SASL */