2 * Copyright (c) 1998-2003 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.940.2.19 2003/09/03 19:58:26 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 void markfailure __P((ENVELOPE *, ADDRESS *, MCI *, int, bool));
32 static int deliver __P((ENVELOPE *, ADDRESS *));
33 static void dup_queue_file __P((ENVELOPE *, ENVELOPE *, int));
34 static void mailfiletimeout __P((void));
35 static int parse_hostsignature __P((char *, char **, MAILER *));
36 static void sendenvelope __P((ENVELOPE *, int));
37 extern MCI *mci_new __P((SM_RPOOL_T *));
38 static int coloncmp __P((const char *, const char *));
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(&e->e_from, false);
127 sm_dprintf("\te_flags = ");
129 sm_dprintf("sendqueue:\n");
130 printaddr(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(&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(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 ");
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 ");
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;
363 else if (QueueMode != QM_QUARANTINE &&
364 e->e_quarmsg != NULL)
367 sm_dprintf(" ... quarantine: %s\n",
369 q->q_state = QS_QUEUEUP;
372 #endif /* _FFR_QUARANTINE */
376 sm_dprintf(" ... deliverable\n");
377 somedeliveries = true;
381 if (owner != NULL && otherowners > 0)
384 ** Split this envelope into two.
387 ee = (ENVELOPE *) sm_rpool_malloc_x(e->e_rpool,
390 ee->e_message = NULL;
395 sm_dprintf("sendall: split %s into %s, owner = \"%s\", otherowners = %d\n",
396 e->e_id, ee->e_id, owner,
399 ee->e_header = copyheader(e->e_header, ee->e_rpool);
400 ee->e_sendqueue = copyqueue(e->e_sendqueue,
402 ee->e_errorqueue = copyqueue(e->e_errorqueue,
404 ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS|EF_SENDRECEIPT|EF_RET_PARAM);
405 ee->e_flags |= EF_NORECEIPT;
406 setsender(owner, ee, NULL, '\0', true);
409 sm_dprintf("sendall(split): QS_SENDER ");
410 printaddr(&ee->e_from, false);
412 ee->e_from.q_state = QS_SENDER;
416 ee->e_qgrp = e->e_qgrp;
417 ee->e_qdir = e->e_qdir;
418 ee->e_errormode = EM_MAIL;
419 ee->e_sibling = splitenv;
420 ee->e_statmsg = NULL;
422 if (e->e_quarmsg != NULL)
423 ee->e_quarmsg = sm_rpool_strdup_x(ee->e_rpool,
425 #endif /* _FFR_QUARANTINE */
428 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
430 if (q->q_owner == owner)
432 q->q_state = QS_CLONED;
434 sm_dprintf("\t... stripping %s from original envelope\n",
438 for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
440 if (q->q_owner != owner)
442 q->q_state = QS_CLONED;
444 sm_dprintf("\t... dropping %s from cloned envelope\n",
449 /* clear DSN parameters */
450 q->q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS);
451 q->q_flags |= DefaultNotify & ~QPINGONSUCCESS;
453 sm_dprintf("\t... moving %s to cloned envelope\n",
458 if (mode != SM_VERIFY && bitset(EF_HAS_DF, e->e_flags))
459 dup_queue_file(e, ee, DATAFL_LETTER);
462 ** Give the split envelope access to the parent
463 ** transcript file for errors obtained while
464 ** processing the recipients (done before the
465 ** envelope splitting).
468 if (e->e_xfp != NULL)
469 ee->e_xfp = sm_io_dup(e->e_xfp);
471 /* failed to dup e->e_xfp, start a new transcript */
472 if (ee->e_xfp == NULL)
475 if (mode != SM_VERIFY && LogLevel > 4)
476 sm_syslog(LOG_INFO, e->e_id,
477 "%s: clone: owner=%s",
484 setsender(owner, e, NULL, '\0', true);
487 sm_dprintf("sendall(owner): QS_SENDER ");
488 printaddr(&e->e_from, false);
490 e->e_from.q_state = QS_SENDER;
491 e->e_errormode = EM_MAIL;
492 e->e_flags |= EF_NORECEIPT;
493 e->e_flags &= ~EF_FATALERRS;
496 /* if nothing to be delivered, just queue up everything */
497 if (!somedeliveries && !WILL_BE_QUEUED(mode) &&
503 sm_dprintf("No deliveries: auto-queuing\n");
507 /* treat this as a delivery in terms of counting tries */
511 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
519 if ((WILL_BE_QUEUED(mode) || mode == SM_FORK ||
520 (mode != SM_VERIFY && SuperSafe == SAFE_REALLY)) &&
521 (!bitset(EF_INQUEUE, e->e_flags) || splitenv != NULL))
526 ** Be sure everything is instantiated in the queue.
527 ** Split envelopes first in case the machine crashes.
528 ** If the original were done first, we may lose
534 #else /* !HASFLOCK */
535 msync = mode == SM_FORK;
536 #endif /* !HASFLOCK */
538 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
539 queueup(ee, WILL_BE_QUEUED(mode), msync);
540 queueup(e, WILL_BE_QUEUED(mode), msync);
544 checkfds("after envelope splitting");
547 ** If we belong in background, fork now.
552 sm_dprintf("sendall: final mode = %c\n", mode);
555 sm_dprintf("\n================ Final Send Queue(s) =====================\n");
556 sm_dprintf("\n *** Envelope %s, e_from=%s ***\n",
557 e->e_id, e->e_from.q_paddr);
558 printaddr(e->e_sendqueue, true);
559 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
561 sm_dprintf("\n *** Envelope %s, e_from=%s ***\n",
562 ee->e_id, ee->e_from.q_paddr);
563 printaddr(ee->e_sendqueue, true);
565 sm_dprintf("==========================================================\n\n");
578 #endif /* HASFLOCK */
580 e->e_flags |= EF_INQUEUE;
581 dropenvelope(e, splitenv != NULL, true);
582 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
584 if (ee->e_nrcpts > 0)
585 ee->e_flags |= EF_INQUEUE;
586 dropenvelope(ee, false, true);
591 if (e->e_xfp != NULL)
592 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
596 ** Since fcntl locking has the interesting semantic that
597 ** the lock is owned by a process, not by an open file
598 ** descriptor, we have to flush this to the queue, and
599 ** then restart from scratch in the child.
603 /* save id for future use */
606 /* now drop the envelope in the parent */
607 e->e_flags |= EF_INQUEUE;
608 dropenvelope(e, splitenv != NULL, false);
610 /* arrange to reacquire lock after fork */
614 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
616 /* save id for future use */
617 char *qid = ee->e_id;
619 /* drop envelope in parent */
620 ee->e_flags |= EF_INQUEUE;
621 dropenvelope(ee, false, false);
623 /* and save qid for reacquisition */
626 #endif /* !HASFLOCK */
629 ** Since the delivery may happen in a child and the parent
630 ** does not wait, the parent may close the maps thereby
631 ** removing any shared memory used by the map. Therefore,
632 ** close the maps now so the child will dynamically open
633 ** them if necessary.
641 syserr("deliver: fork 1");
646 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
649 #endif /* HASFLOCK */
654 /* be sure we leave the temp files to our child */
655 /* close any random open files in the envelope */
657 if (e->e_dfp != NULL)
658 (void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
660 e->e_flags &= ~EF_HAS_DF;
662 /* can't call unlockqueue to avoid unlink of xfp */
663 if (e->e_lockfp != NULL)
664 (void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT);
666 syserr("%s: sendall: null lockfp", e->e_id);
668 #endif /* HASFLOCK */
670 /* make sure the parent doesn't own the envelope */
674 /* catch intermediate zombie */
676 #endif /* USE_DOUBLE_FORK */
680 /* Reset global flags */
681 RestartRequest = NULL;
682 RestartWorkGroup = false;
683 ShutdownRequest = NULL;
687 ** Initialize exception stack and default exception
688 ** handler for child process.
691 sm_exc_newthread(fatal_error);
694 ** Since we have accepted responsbility for the message,
695 ** change the SIGTERM handler. intsig() (the old handler)
696 ** would remove the envelope if this was a command line
697 ** message submission.
700 (void) sm_signal(SIGTERM, SIG_DFL);
703 /* double fork to avoid zombies */
708 #endif /* USE_DOUBLE_FORK */
710 CurrentPid = getpid();
712 /* be sure we are immune from the terminal */
716 /* prevent parent from waiting if there was an error */
720 syserr("deliver: fork 2");
722 e->e_flags |= EF_INQUEUE;
725 #endif /* HASFLOCK */
726 finis(true, true, ExitStat);
729 /* be sure to give error messages in child */
733 ** Close any cached connections.
735 ** We don't send the QUIT protocol because the parent
736 ** still knows about the connection.
738 ** This should only happen when delivering an error
742 mci_flush(false, NULL);
749 ** Now reacquire and run the various queue files.
752 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
754 ENVELOPE *sibling = ee->e_sibling;
756 (void) dowork(ee->e_qgrp, ee->e_qdir, ee->e_id,
758 ee->e_sibling = sibling;
760 (void) dowork(e->e_qgrp, e->e_qdir, e->e_id,
762 finis(true, true, ExitStat);
763 #endif /* HASFLOCK */
766 sendenvelope(e, mode);
767 dropenvelope(e, true, true);
768 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
771 if (mode != SM_VERIFY)
773 sendenvelope(ee, mode);
774 dropenvelope(ee, true, true);
778 Verbose = oldverbose;
780 finis(true, true, ExitStat);
784 sendenvelope(e, mode)
785 register ENVELOPE *e;
792 sm_dprintf("sendenvelope(%s) e_flags=0x%lx\n",
793 e->e_id == NULL ? "[NOQUEUE]" : e->e_id,
796 sm_syslog(LOG_DEBUG, e->e_id,
797 "sendenvelope, flags=0x%lx",
801 ** If we have had global, fatal errors, don't bother sending
802 ** the message at all if we are in SMTP mode. Local errors
803 ** (e.g., a single address failing) will still cause the other
804 ** addresses to be sent.
807 if (bitset(EF_FATALERRS, e->e_flags) &&
808 (OpMode == MD_SMTP || OpMode == MD_DAEMON))
810 e->e_flags |= EF_CLRQUEUE;
815 ** Don't attempt deliveries if we want to bounce now
816 ** or if deliver-by time is exceeded.
819 if (!bitset(EF_RESPONSE, e->e_flags) &&
820 (TimeOuts.to_q_return[e->e_timeoutclass] == NOW ||
821 (IS_DLVR_RETURN(e) && e->e_deliver_by > 0 &&
822 curtime() > e->e_ctime + e->e_deliver_by)))
826 ** Run through the list and send everything.
828 ** Set EF_GLOBALERRS so that error messages during delivery
829 ** result in returned mail.
833 e->e_flags |= EF_GLOBALERRS;
835 macdefine(&e->e_macro, A_PERM, macid("{envid}"), e->e_envid);
836 macdefine(&e->e_macro, A_PERM, macid("{bodytype}"), e->e_bodytype);
839 if (!bitset(EF_SPLIT, e->e_flags))
845 ** Save old sibling and set it to NULL to avoid
846 ** queueing up the same envelopes again.
847 ** This requires that envelopes in that list have
848 ** been take care of before (or at some other place).
851 oldsib = e->e_sibling;
853 if (!split_by_recipient(e) &&
854 bitset(EF_FATALERRS, e->e_flags))
856 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
857 e->e_flags |= EF_CLRQUEUE;
860 for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
861 queueup(ee, false, true);
864 for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
866 /* now unlock the job */
870 /* this envelope is marked unused */
871 if (ee->e_dfp != NULL)
873 (void) sm_io_close(ee->e_dfp, SM_TIME_DEFAULT);
877 ee->e_flags &= ~EF_HAS_DF;
879 e->e_sibling = oldsib;
882 /* now run through the queue */
883 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
886 char wbuf[MAXNAME + 20];
888 (void) sm_snprintf(wbuf, sizeof wbuf, "sendall(%.*s)",
889 MAXNAME, q->q_paddr);
892 if (mode == SM_VERIFY)
894 e->e_to = q->q_paddr;
895 if (QS_IS_SENDABLE(q->q_state))
897 if (q->q_host != NULL && q->q_host[0] != '\0')
898 message("deliverable: mailer %s, host %s, user %s",
903 message("deliverable: mailer %s, user %s",
908 else if (QS_IS_OK(q->q_state))
911 ** Checkpoint the send list every few addresses
914 if (CheckpointInterval > 0 &&
915 e->e_nsent >= CheckpointInterval)
917 queueup(e, false, false);
920 (void) deliver(e, q);
926 e->e_dtime = curtime();
931 checkfd012("end of sendenvelope");
935 #if REQUIRES_DIR_FSYNC
937 ** SYNC_DIR -- fsync a directory based on a filename
940 ** filename -- path of file
948 sync_dir(filename, panic)
954 char dir[MAXPATHLEN];
956 #if _FFR_REQ_DIR_FSYNC_OPT
957 if (!RequiresDirfsync)
959 #endif /* _FFR_REQ_DIR_FSYNC_OPT */
961 /* filesystems which require the directory be synced */
962 dirp = strrchr(filename, '/');
965 if (sm_strlcpy(dir, filename, sizeof dir) >= sizeof dir)
967 dir[dirp - filename] = '\0';
972 dirfd = open(dirp, O_RDONLY, 0700);
974 sm_syslog(LOG_INFO, NOQID, "sync_dir: %s: fsync(%d)",
978 if (fsync(dirfd) < 0)
981 syserr("!sync_dir: cannot fsync directory %s",
983 else if (LogLevel > 1)
984 sm_syslog(LOG_ERR, NOQID,
985 "sync_dir: cannot fsync directory %s: %s",
986 dirp, sm_errstring(errno));
991 #endif /* REQUIRES_DIR_FSYNC */
993 ** DUP_QUEUE_FILE -- duplicate a queue file into a split queue
996 ** e -- the existing envelope
997 ** ee -- the new envelope
998 ** type -- the queue file type (e.g., DATAFL_LETTER)
1005 dup_queue_file(e, ee, type)
1009 char f1buf[MAXPATHLEN], f2buf[MAXPATHLEN];
1015 ** Make sure both are in the same directory.
1018 (void) sm_strlcpy(f1buf, queuename(e, type), sizeof f1buf);
1019 (void) sm_strlcpy(f2buf, queuename(ee, type), sizeof f2buf);
1021 /* Force the df to disk if it's not there yet */
1022 if (type == DATAFL_LETTER && e->e_dfp != NULL &&
1023 sm_io_setinfo(e->e_dfp, SM_BF_COMMIT, NULL) < 0 &&
1026 syserr("!dup_queue_file: can't commit %s", f1buf);
1030 if (link(f1buf, f2buf) < 0)
1032 int save_errno = errno;
1034 syserr("sendall: link(%s, %s)", f1buf, f2buf);
1035 if (save_errno == EEXIST)
1037 if (unlink(f2buf) < 0)
1039 syserr("!sendall: unlink(%s): permanent",
1043 if (link(f1buf, f2buf) < 0)
1045 syserr("!sendall: link(%s, %s): permanent",
1051 SYNC_DIR(f2buf, true);
1054 ** DOFORK -- do a fork, retrying a couple of times on failure.
1056 ** This MUST be a macro, since after a vfork we are running
1057 ** two processes on the same stack!!!
1063 ** From a macro??? You've got to be kidding!
1066 ** Modifies the ==> LOCAL <== variable 'pid', leaving:
1067 ** pid of child in parent, zero in child.
1068 ** -1 on unrecoverable error.
1071 ** I'm awfully sorry this looks so awful. That's
1072 ** vfork for you.....
1075 #define NFORKTRIES 5
1081 #define DOFORK(fORKfN) \
1085 for (i = NFORKTRIES; --i >= 0; )\
1091 (void) sleep((unsigned) NFORKTRIES - i);\
1095 ** DOFORK -- simple fork interface to DOFORK.
1101 ** pid of child in parent.
1106 ** returns twice, once in parent and once in child.
1112 register pid_t pid = -1;
1119 ** COLONCMP -- compare host-signatures up to first ':' or EOS
1121 ** This takes two strings which happen to be host-signatures and
1122 ** compares them. If the lowest preference portions of the MX-RR's
1123 ** match (up to ':' or EOS, whichever is first), then we have
1124 ** match. This is used for coattail-piggybacking messages during
1125 ** message delivery.
1126 ** If the signatures are the same up to the first ':' the remainder of
1127 ** the signatures are then compared with a normal strcmp(). This saves
1128 ** re-examining the first part of the signatures.
1131 ** a - first host-signature
1132 ** b - second host-signature
1135 ** HS_MATCH_NO -- no "match".
1136 ** HS_MATCH_FIRST -- "match" for the first MX preference
1137 ** (up to the first colon (':')).
1138 ** HS_MATCH_FULL -- match for the entire MX record.
1144 #define HS_MATCH_NO 0
1145 #define HS_MATCH_FIRST 1
1146 #define HS_MATCH_FULL 2
1150 register const char *a;
1151 register const char *b;
1153 int ret = HS_MATCH_NO;
1158 /* Need to account for IPv6 bracketed addresses */
1161 else if (*a == ']' && braclev > 0)
1163 else if (*a == ':' && braclev <= 0)
1165 ret = HS_MATCH_FIRST;
1169 else if (*a == '\0')
1170 return HS_MATCH_FULL; /* a full match */
1173 if (ret == HS_MATCH_NO &&
1175 ((*a == '\0' && *(b - 1) == ':') ||
1176 (*a == ':' && *(b - 1) == '\0')))
1177 return HS_MATCH_FIRST;
1178 if (ret == HS_MATCH_FIRST && strcmp(a, b) == 0)
1179 return HS_MATCH_FULL;
1184 ** DELIVER -- Deliver a message to a list of addresses.
1186 ** This routine delivers to everyone on the same host as the
1187 ** user on the head of the list. It is clever about mailers
1188 ** that don't handle multiple users. It is NOT guaranteed
1189 ** that it will deliver to all these addresses however -- so
1190 ** deliver should be called once for each address on the
1192 ** Deliver tries to be as opportunistic as possible about piggybacking
1193 ** messages. Some definitions to make understanding easier follow below.
1194 ** Piggybacking occurs when an existing connection to a mail host can
1195 ** be used to send the same message to more than one recipient at the
1196 ** same time. So "no piggybacking" means one message for one recipient
1197 ** per connection. "Intentional piggybacking" happens when the
1198 ** recipients' host address (not the mail host address) is used to
1199 ** attempt piggybacking. Recipients with the same host address
1200 ** have the same mail host. "Coincidental piggybacking" relies on
1201 ** piggybacking based on all the mail host addresses in the MX-RR. This
1202 ** is "coincidental" in the fact it could not be predicted until the
1203 ** MX Resource Records for the hosts were obtained and examined. For
1204 ** example (preference order and equivalence is important, not values):
1205 ** domain1 IN MX 10 mxhost-A
1206 ** IN MX 20 mxhost-B
1207 ** domain2 IN MX 4 mxhost-A
1209 ** Domain1 and domain2 can piggyback the same message to mxhost-A or
1210 ** mxhost-B (if mxhost-A cannot be reached).
1211 ** "Coattail piggybacking" relaxes the strictness of "coincidental
1212 ** piggybacking" in the hope that most significant (lowest value)
1213 ** MX preference host(s) can create more piggybacking. For example
1214 ** (again, preference order and equivalence is important, not values):
1215 ** domain3 IN MX 100 mxhost-C
1216 ** IN MX 100 mxhost-D
1217 ** IN MX 200 mxhost-E
1218 ** domain4 IN MX 50 mxhost-C
1219 ** IN MX 50 mxhost-D
1220 ** IN MX 80 mxhost-F
1221 ** A message for domain3 and domain4 can piggyback to mxhost-C if mxhost-C
1222 ** is available. Same with mxhost-D because in both RR's the preference
1223 ** value is the same as mxhost-C, respectively.
1224 ** So deliver attempts coattail piggybacking when possible. If the
1225 ** first MX preference level hosts cannot be used then the piggybacking
1226 ** reverts to coincidental piggybacking. Using the above example you
1227 ** cannot deliver to mxhost-F for domain3 regardless of preference value.
1228 ** ("Coattail" from "riding on the coattails of your predecessor" meaning
1229 ** gaining benefit from a predecessor effort with no or little addition
1230 ** effort. The predecessor here being the preceding MX RR).
1233 ** e -- the envelope to deliver.
1234 ** firstto -- head of the address list to deliver to.
1237 ** zero -- successfully delivered.
1238 ** else -- some failure, see ExitStat for more info.
1241 ** The standard input is passed off to someone.
1246 #endif /* ! NO_UID */
1249 #endif /* ! NO_GID */
1253 register ENVELOPE *e;
1256 char *host; /* host being sent to */
1257 char *user; /* user being sent to */
1259 register char **mvp;
1261 register MAILER *m; /* mailer for this recipient */
1262 ADDRESS *volatile ctladdr;
1263 #if HASSETUSERCONTEXT
1264 ADDRESS *volatile contextaddr = NULL;
1265 #endif /* HASSETUSERCONTEXT */
1266 register MCI *volatile mci;
1267 register ADDRESS *SM_NONVOLATILE to = firstto;
1268 volatile bool clever = false; /* running user smtp to this mailer */
1269 ADDRESS *volatile tochain = NULL; /* users chain in this mailer call */
1270 int rcode; /* response code */
1271 SM_NONVOLATILE int lmtp_rcode = EX_OK;
1272 SM_NONVOLATILE int nummxhosts = 0; /* number of MX hosts available */
1273 SM_NONVOLATILE int hostnum = 0; /* current MX host index */
1274 char *firstsig; /* signature of firstto */
1275 volatile pid_t pid = -1;
1276 char *volatile curhost;
1277 SM_NONVOLATILE unsigned short port = 0;
1278 SM_NONVOLATILE time_t enough = 0;
1280 char *SM_NONVOLATILE mux_path = NULL; /* path to UNIX domain socket */
1281 #endif /* NETUNIX */
1284 bool anyok; /* at least one address was OK */
1285 SM_NONVOLATILE bool goodmxfound = false; /* at least one MX was OK */
1289 #endif /* _FFR_QUARANTINE */
1293 static int tobufsize = 0;
1294 static char *tobuf = NULL;
1295 char *rpath; /* translated return path */
1298 char *mxhosts[MAXMXHOSTS + 1];
1299 char *pv[MAXPV + 1];
1300 char buf[MAXNAME + 1];
1301 char cbuf[MAXPATHLEN];
1304 if (!QS_IS_OK(to->q_state))
1307 suidwarn = geteuid() == 0;
1311 CurEnv = e; /* just in case */
1312 e->e_statmsg = NULL;
1313 SmtpError[0] = '\0';
1317 sm_dprintf("\n--deliver, id=%s, mailer=%s, host=`%s', first user=`%s'\n",
1318 e->e_id, m->m_name, host, to->q_user);
1320 printopenfds(false);
1323 ** Clear {client_*} macros if this is a bounce message to
1324 ** prevent rejection by check_compat ruleset.
1327 if (bitset(EF_RESPONSE, e->e_flags))
1329 macdefine(&e->e_macro, A_PERM, macid("{client_name}"), "");
1330 macdefine(&e->e_macro, A_PERM, macid("{client_addr}"), "");
1331 macdefine(&e->e_macro, A_PERM, macid("{client_port}"), "");
1332 macdefine(&e->e_macro, A_PERM, macid("{client_resolve}"), "");
1337 ADDRESS *skip_back = NULL;
1340 ** Do initial argv setup.
1341 ** Insert the mailer name. Notice that $x expansion is
1342 ** NOT done on the mailer name. Then, if the mailer has
1343 ** a picky -f flag, we insert it as appropriate. This
1344 ** code does not check for 'pv' overflow; this places a
1345 ** manifest lower limit of 4 for MAXPV.
1346 ** The from address rewrite is expected to make
1347 ** the address relative to the other end.
1350 /* rewrite from address, using rewriting rules */
1352 if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags))
1355 p = e->e_from.q_paddr;
1356 rpath = remotename(p, m, RF_SENDERADDR|RF_CANONICAL, &rcode, e);
1357 if (strlen(rpath) > MAXSHORTSTR)
1359 rpath = shortenstring(rpath, MAXSHORTSTR);
1361 /* avoid bogus errno */
1363 syserr("remotename: huge return path %s", rpath);
1365 rpath = sm_rpool_strdup_x(e->e_rpool, rpath);
1366 macdefine(&e->e_macro, A_PERM, 'g', rpath);
1367 macdefine(&e->e_macro, A_PERM, 'h', host);
1370 *pvp++ = m->m_argv[0];
1372 /* insert -f or -r flag as appropriate */
1374 (bitnset(M_FOPT, m->m_flags) ||
1375 bitnset(M_ROPT, m->m_flags)))
1377 if (bitnset(M_FOPT, m->m_flags))
1385 ** Append the other fixed parts of the argv. These run
1386 ** up to the first entry containing "$u". There can only
1387 ** be one of these, and there are only a few more slots
1388 ** in the pv after it.
1391 for (mvp = m->m_argv; (p = *++mvp) != NULL; )
1393 /* can't use strchr here because of sign extension problems */
1396 if ((*p++ & 0377) == MACROEXPAND)
1406 /* this entry is safe -- go ahead and process it */
1407 expand(*mvp, buf, sizeof buf, e);
1408 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1409 if (pvp >= &pv[MAXPV - 3])
1411 syserr("554 5.3.5 Too many parameters to %s before $u",
1419 ** If we have no substitution for the user name in the argument
1420 ** list, we know that we must supply the names otherwise -- and
1421 ** SMTP is the answer!!
1426 /* running LMTP or SMTP */
1430 else if (bitnset(M_LMTP, m->m_flags))
1432 /* not running LMTP */
1433 sm_syslog(LOG_ERR, NULL,
1434 "Warning: mailer %s: LMTP flag (F=z) turned off",
1436 clrbitn(M_LMTP, m->m_flags);
1440 ** At this point *mvp points to the argument with $u. We
1441 ** run through our address list and append all the addresses
1442 ** we can. If we run out of space, do not fret! We can
1443 ** always send another copy later.
1450 if (firstto->q_signature == NULL)
1451 firstto->q_signature = hostsignature(firstto->q_mailer,
1453 firstsig = firstto->q_signature;
1455 for (; to != NULL; to = to->q_next)
1457 /* avoid sending multiple recipients to dumb mailers */
1458 if (tochain != NULL && !bitnset(M_MUSER, m->m_flags))
1461 /* if already sent or not for this host, don't send */
1462 if (!QS_IS_OK(to->q_state)) /* already sent; look at next */
1466 ** Must be same mailer to keep grouping rcpts.
1467 ** If mailers don't match: continue; sendqueue is not
1468 ** sorted by mailers, so don't break;
1471 if (to->q_mailer != firstto->q_mailer)
1474 if (to->q_signature == NULL) /* for safety */
1475 to->q_signature = hostsignature(to->q_mailer,
1479 ** This is for coincidental and tailcoat piggybacking messages
1480 ** to the same mail host. While the signatures are identical
1481 ** (that's the MX-RR's are identical) we can do coincidental
1482 ** piggybacking. We try hard for coattail piggybacking
1483 ** with the same mail host when the next recipient has the
1484 ** same host at lowest preference. It may be that this
1485 ** won't work out, so 'skip_back' is maintained if a backup
1486 ** to coincidental piggybacking or full signature must happen.
1489 ret = firstto == to ? HS_MATCH_FULL :
1490 coloncmp(to->q_signature, firstsig);
1491 if (ret == HS_MATCH_FULL)
1493 else if (ret == HS_MATCH_NO)
1498 /* avoid overflowing tobuf */
1499 strsize += strlen(to->q_paddr) + 1;
1500 if (strsize > TOBUFSIZE)
1504 if (++rcptcount > to->q_mailer->m_maxrcpt)
1509 sm_dprintf("\nsend to ");
1510 printaddr(to, false);
1513 /* compute effective uid/gid when sending */
1514 if (bitnset(M_RUNASRCPT, to->q_mailer->m_flags))
1515 # if HASSETUSERCONTEXT
1516 contextaddr = ctladdr = getctladdr(to);
1517 # else /* HASSETUSERCONTEXT */
1518 ctladdr = getctladdr(to);
1519 # endif /* HASSETUSERCONTEXT */
1523 sm_dprintf("ctladdr=");
1524 printaddr(ctladdr, false);
1528 e->e_to = to->q_paddr;
1531 ** Check to see that these people are allowed to
1532 ** talk to each other.
1533 ** Check also for overflow of e_msgsize.
1536 if (m->m_maxsize != 0 &&
1537 (e->e_msgsize > m->m_maxsize || e->e_msgsize < 0))
1539 e->e_flags |= EF_NO_BODY_RETN;
1540 if (bitnset(M_LOCALMAILER, to->q_mailer->m_flags))
1541 to->q_status = "5.2.3";
1543 to->q_status = "5.3.4";
1545 /* set to->q_rstatus = NULL; or to the following? */
1546 usrerrenh(to->q_status,
1547 "552 Message is too large; %ld bytes max",
1549 markfailure(e, to, NULL, EX_UNAVAILABLE, false);
1550 giveresponse(EX_UNAVAILABLE, to->q_status, m,
1551 NULL, ctladdr, xstart, e, to);
1557 /* do config file checking of compatibility */
1559 quarantine = (e->e_quarmsg != NULL);
1560 #endif /* _FFR_QUARANTINE */
1561 rcode = rscheck("check_compat", e->e_from.q_paddr, to->q_paddr,
1562 e, RSF_RMCOMM|RSF_COUNT, 3, NULL,
1566 /* do in-code checking if not discarding */
1567 if (!bitset(EF_DISCARD, e->e_flags))
1569 rcode = checkcompat(to, e);
1575 markfailure(e, to, NULL, rcode, ovr);
1576 giveresponse(rcode, to->q_status, m,
1577 NULL, ctladdr, xstart, e, to);
1581 if (!quarantine && e->e_quarmsg != NULL)
1584 ** check_compat or checkcompat() has tried
1585 ** to quarantine but that isn't supported.
1586 ** Revert the attempt.
1589 e->e_quarmsg = NULL;
1590 macdefine(&e->e_macro, A_PERM,
1591 macid("{quarantine}"), "");
1593 #endif /* _FFR_QUARANTINE */
1594 if (bitset(EF_DISCARD, e->e_flags))
1598 sm_dprintf("deliver: discarding recipient ");
1599 printaddr(to, false);
1602 /* pretend the message was sent */
1603 /* XXX should we log something here? */
1604 to->q_state = QS_DISCARDED;
1607 ** Remove discard bit to prevent discard of
1608 ** future recipients. This is safe because the
1609 ** true "global discard" has been handled before
1613 e->e_flags &= ~EF_DISCARD;
1618 ** Strip quote bits from names if the mailer is dumb
1622 if (bitnset(M_STRIPQ, m->m_flags))
1627 #if _FFR_STRIPBACKSL
1629 ** Strip one leading backslash if requested and the
1630 ** next character is alphanumerical (the latter can
1631 ** probably relaxed a bit, see RFC2821).
1634 if (bitnset(M_STRIPBACKSL, m->m_flags) && user[0] == '\\')
1635 stripbackslash(user);
1636 #endif /* _FFR_STRIPBACKSL */
1638 /* hack attack -- delivermail compatibility */
1639 if (m == ProgMailer && *user == '|')
1643 ** If an error message has already been given, don't
1644 ** bother to send to this address.
1646 ** >>>>>>>>>> This clause assumes that the local mailer
1647 ** >> NOTE >> cannot do any further aliasing; that
1648 ** >>>>>>>>>> function is subsumed by sendmail.
1651 if (!QS_IS_OK(to->q_state))
1655 ** See if this user name is "special".
1656 ** If the user name has a slash in it, assume that this
1657 ** is a file -- send it off without further ado. Note
1658 ** that this type of addresses is not processed along
1659 ** with the others, so we fudge on the To person.
1662 if (strcmp(m->m_mailer, "[FILE]") == 0)
1664 macdefine(&e->e_macro, A_PERM, 'u', user);
1666 if (p == NULL && ctladdr != NULL)
1667 p = ctladdr->q_home;
1668 macdefine(&e->e_macro, A_PERM, 'z', p);
1669 expand(m->m_argv[1], buf, sizeof buf, e);
1670 if (strlen(buf) > 0)
1671 rcode = mailfile(buf, m, ctladdr, SFF_CREAT, e);
1674 syserr("empty filename specification for mailer %s",
1678 giveresponse(rcode, to->q_status, m, NULL,
1679 ctladdr, xstart, e, to);
1680 markfailure(e, to, NULL, rcode, true);
1684 to->q_state = QS_SENT;
1685 if (bitnset(M_LOCALMAILER, m->m_flags) &&
1686 bitset(QPINGONSUCCESS, to->q_flags))
1688 to->q_flags |= QDELIVERED;
1689 to->q_status = "2.1.5";
1690 (void) sm_io_fprintf(e->e_xfp,
1692 "%s... Successfully delivered\n",
1696 to->q_statdate = curtime();
1697 markstats(e, to, STATS_NORMAL);
1702 ** Address is verified -- add this user to mailer
1703 ** argv, and add it to the print list of recipients.
1706 /* link together the chain of recipients */
1707 to->q_tchain = tochain;
1709 e->e_to = "[CHAIN]";
1711 macdefine(&e->e_macro, A_PERM, 'u', user); /* to user */
1713 if (p == NULL && ctladdr != NULL)
1714 p = ctladdr->q_home;
1715 macdefine(&e->e_macro, A_PERM, 'z', p); /* user's home */
1717 /* set the ${dsn_notify} macro if applicable */
1718 if (bitset(QHASNOTIFY, to->q_flags))
1720 char notify[MAXLINE];
1723 if (bitset(QPINGONSUCCESS, to->q_flags))
1724 (void) sm_strlcat(notify, "SUCCESS,",
1726 if (bitset(QPINGONFAILURE, to->q_flags))
1727 (void) sm_strlcat(notify, "FAILURE,",
1729 if (bitset(QPINGONDELAY, to->q_flags))
1730 (void) sm_strlcat(notify, "DELAY,",
1733 /* Set to NEVER or drop trailing comma */
1734 if (notify[0] == '\0')
1735 (void) sm_strlcat(notify, "NEVER",
1738 notify[strlen(notify) - 1] = '\0';
1740 macdefine(&e->e_macro, A_TEMP,
1741 macid("{dsn_notify}"), notify);
1744 macdefine(&e->e_macro, A_PERM,
1745 macid("{dsn_notify}"), NULL);
1748 ** Expand out this user into argument list.
1753 expand(*mvp, buf, sizeof buf, e);
1754 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1755 if (pvp >= &pv[MAXPV - 2])
1757 /* allow some space for trailing parms */
1763 /* see if any addresses still exist */
1764 if (tochain == NULL)
1770 /* print out messages as full list */
1772 for (to = tochain; to != NULL; to = to->q_tchain)
1773 strsize += strlen(to->q_paddr) + 1;
1774 if (strsize < TOBUFSIZE)
1775 strsize = TOBUFSIZE;
1776 if (strsize > tobufsize)
1779 tobuf = sm_pmalloc_x(strsize);
1780 tobufsize = strsize;
1784 for (to = tochain; to != NULL; to = to->q_tchain)
1786 (void) sm_strlcpyn(p, tobufsize - (p - tobuf), 2,
1790 e->e_to = tobuf + 1;
1793 ** Fill out any parameters after the $u parameter.
1798 while (*++mvp != NULL)
1800 expand(*mvp, buf, sizeof buf, e);
1801 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1802 if (pvp >= &pv[MAXPV])
1803 syserr("554 5.3.0 deliver: pv overflow after $u for %s",
1811 ** The argument vector gets built, pipes
1812 ** are created as necessary, and we fork & exec as
1814 ** If we are running SMTP, we just need to clean up.
1817 /* XXX this seems a bit wierd */
1818 if (ctladdr == NULL && m != ProgMailer && m != FileMailer &&
1819 bitset(QGOODUID, e->e_from.q_flags))
1820 ctladdr = &e->e_from;
1823 if (ConfigLevel < 2)
1824 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */
1825 #endif /* NAMED_BIND */
1829 sm_dprintf("openmailer:");
1837 ** Deal with the special case of mail handled through an IPC
1839 ** In this case we don't actually fork. We must be
1840 ** running SMTP for this to work. We will return a
1841 ** zero pid to indicate that we are running IPC.
1842 ** We also handle a debug version that just talks to stdin/out.
1853 /* make absolutely certain 0, 1, and 2 are in use */
1854 (void) sm_snprintf(wbuf, sizeof wbuf, "%s... openmailer(%s)",
1855 shortenstring(e->e_to, MAXSHORTSTR),
1861 /* check for 8-bit available */
1862 if (bitset(EF_HAS8BIT, e->e_flags) &&
1863 bitnset(M_7BITS, m->m_flags) &&
1864 (bitset(EF_DONT_MIME, e->e_flags) ||
1865 !(bitset(MM_MIME8BIT, MimeMode) ||
1866 (bitset(EF_IS_MIME, e->e_flags) &&
1867 bitset(MM_CVTMIME, MimeMode)))))
1869 e->e_status = "5.6.3";
1870 usrerrenh(e->e_status,
1871 "554 Cannot send 8-bit data to 7-bit destination");
1877 checkfds("before delivery");
1879 /* check for Local Person Communication -- not for mortals!!! */
1880 if (strcmp(m->m_mailer, "[LPC]") == 0)
1885 /* flush any expired connections */
1886 (void) mci_scan(NULL);
1888 /* try to get a cached connection or just a slot */
1889 mci = mci_get(m->m_name, m);
1890 if (mci->mci_host == NULL)
1891 mci->mci_host = m->m_name;
1892 CurHostName = mci->mci_host;
1893 if (mci->mci_state != MCIS_CLOSED)
1895 message("Using cached SMTP/LPC connection for %s...",
1897 mci->mci_deliveries++;
1903 mci = mci_new(e->e_rpool);
1905 mci->mci_in = smioin;
1906 mci->mci_out = smioout;
1907 mci->mci_mailer = m;
1908 mci->mci_host = m->m_name;
1911 mci->mci_state = MCIS_OPENING;
1915 mci->mci_state = MCIS_OPEN;
1916 #else /* _FFR_CACHE_LPC */
1917 mci = mci_new(e->e_rpool);
1918 mci->mci_in = smioin;
1919 mci->mci_out = smioout;
1920 mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1921 mci->mci_mailer = m;
1922 #endif /* _FFR_CACHE_LPC */
1924 else if (strcmp(m->m_mailer, "[IPC]") == 0)
1928 if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0')
1930 syserr("null destination for %s mailer", m->m_mailer);
1936 if (strcmp(pv[0], "FILE") == 0)
1938 curhost = CurHostName = "localhost";
1942 # endif /* NETUNIX */
1944 CurHostName = pv[1];
1945 curhost = hostsignature(m, pv[1]);
1948 if (curhost == NULL || curhost[0] == '\0')
1950 syserr("null host signature for %s", pv[1]);
1957 syserr("554 5.3.5 non-clever IPC");
1964 # endif /* NETUNIX */
1967 port = htons((unsigned short) atoi(pv[2]));
1970 # ifdef NO_GETSERVBYNAME
1971 syserr("Invalid port number: %s", pv[2]);
1972 # else /* NO_GETSERVBYNAME */
1973 struct servent *sp = getservbyname(pv[2], "tcp");
1976 syserr("Service %s unknown", pv[2]);
1979 # endif /* NO_GETSERVBYNAME */
1983 nummxhosts = parse_hostsignature(curhost, mxhosts, m);
1984 if (TimeOuts.to_aconnect > 0)
1985 enough = curtime() + TimeOuts.to_aconnect;
1987 while (hostnum < nummxhosts)
1991 static char hostbuf[MAXNAME + 1];
1994 if (*mxhosts[hostnum] == '[')
1996 endp = strchr(mxhosts[hostnum] + 1, ']');
1998 endp = strpbrk(endp + 1, ":,");
2001 endp = strpbrk(mxhosts[hostnum], ":,");
2002 # else /* NETINET6 */
2003 endp = strpbrk(mxhosts[hostnum], ":,");
2004 # endif /* NETINET6 */
2011 if (hostnum == 1 && skip_back != NULL)
2014 ** Coattail piggybacking is no longer an
2015 ** option with the mail host next to be tried
2016 ** no longer the lowest MX preference
2017 ** (hostnum == 1 meaning we're on the second
2018 ** preference). We do not try to coattail
2019 ** piggyback more than the first MX preference.
2020 ** Revert 'tochain' to last location for
2021 ** coincidental piggybacking. This works this
2022 ** easily because the q_tchain kept getting
2023 ** added to the top of the linked list.
2026 tochain = skip_back;
2029 if (*mxhosts[hostnum] == '\0')
2031 syserr("deliver: null host name in signature");
2037 (void) sm_strlcpy(hostbuf, mxhosts[hostnum],
2043 /* see if we already know that this host is fried */
2044 CurHostName = hostbuf;
2045 mci = mci_get(hostbuf, m);
2046 if (mci->mci_state != MCIS_CLOSED)
2052 sm_dprintf("openmailer: ");
2053 mci_dump(mci, false);
2055 CurHostName = mci->mci_host;
2056 if (bitnset(M_LMTP, m->m_flags))
2058 else if (bitset(MCIF_ESMTP, mci->mci_flags))
2062 message("Using cached %sMTP connection to %s via %s...",
2063 type, hostbuf, m->m_name);
2064 mci->mci_deliveries++;
2067 mci->mci_mailer = m;
2068 if (mci->mci_exitstat != EX_OK)
2070 if (mci->mci_exitstat == EX_TEMPFAIL)
2075 if (mci_lock_host(mci) != EX_OK)
2077 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2082 /* try the connection */
2083 sm_setproctitle(true, e, "%s %s: %s",
2085 hostbuf, "user open");
2087 if (mux_path != NULL)
2089 message("Connecting to %s via %s...",
2090 mux_path, m->m_name);
2091 i = makeconnection_ds((char *) mux_path, mci);
2094 # endif /* NETUNIX */
2097 message("Connecting to %s via %s...",
2098 hostbuf, m->m_name);
2100 message("Connecting to %s port %d via %s...",
2101 hostbuf, ntohs(port),
2103 i = makeconnection(hostbuf, port, mci, e,
2106 mci->mci_errno = errno;
2107 mci->mci_lastuse = curtime();
2108 mci->mci_deliveries = 0;
2109 mci->mci_exitstat = i;
2111 mci->mci_herrno = h_errno;
2112 # endif /* NAMED_BIND */
2115 ** Have we tried long enough to get a connection?
2116 ** If yes, skip to the fallback MX hosts
2120 if (enough > 0 && mci->mci_lastuse >= enough)
2124 extern int NumFallBackMXHosts;
2125 # else /* NAMED_BIND */
2126 const int NumFallBackMXHosts = 0;
2127 # endif /* NAMED_BIND */
2129 if (hostnum < nummxhosts && LogLevel > 9)
2130 sm_syslog(LOG_INFO, e->e_id,
2131 "Timeout.to_aconnect occurred before exhausting all addresses");
2133 /* turn off timeout if fallback available */
2134 if (NumFallBackMXHosts > 0)
2137 /* skip to a fallback MX host */
2138 h = nummxhosts - NumFallBackMXHosts;
2145 markstats(e, firstto, STATS_CONNECT);
2146 mci->mci_state = MCIS_OPENING;
2148 if (TrafficLogFile != NULL)
2149 (void) sm_io_fprintf(TrafficLogFile,
2151 "%05d === CONNECT %s\n",
2159 sm_dprintf("openmailer: makeconnection => stat=%d, errno=%d\n",
2161 if (i == EX_TEMPFAIL)
2163 mci_unlock_host(mci);
2166 /* enter status of this host */
2169 /* should print some message here for -v mode */
2173 syserr("deliver: no host name");
2174 rcode = EX_SOFTWARE;
2181 /* flush any expired connections */
2182 (void) mci_scan(NULL);
2185 if (bitnset(M_LMTP, m->m_flags))
2187 /* try to get a cached connection */
2188 mci = mci_get(m->m_name, m);
2189 if (mci->mci_host == NULL)
2190 mci->mci_host = m->m_name;
2191 CurHostName = mci->mci_host;
2192 if (mci->mci_state != MCIS_CLOSED)
2194 message("Using cached LMTP connection for %s...",
2196 mci->mci_deliveries++;
2201 /* announce the connection to verbose listeners */
2202 if (host == NULL || host[0] == '\0')
2203 message("Connecting to %s...", m->m_name);
2205 message("Connecting to %s via %s...", host, m->m_name);
2206 if (TrafficLogFile != NULL)
2210 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
2211 "%05d === EXEC", (int) CurrentPid);
2212 for (av = pv; *av != NULL; av++)
2213 (void) sm_io_fprintf(TrafficLogFile,
2214 SM_TIME_DEFAULT, " %s",
2216 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
2221 checkfd012("before creating mail pipe");
2224 /* create a pipe to shove the mail through */
2225 if (pipe(mpvect) < 0)
2227 syserr("%s... openmailer(%s): pipe (to mailer)",
2228 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
2230 sm_dprintf("openmailer: NULL\n");
2236 /* make sure we didn't get one of the standard I/O files */
2237 if (mpvect[0] < 3 || mpvect[1] < 3)
2239 syserr("%s... openmailer(%s): bogus mpvect %d %d",
2240 shortenstring(e->e_to, MAXSHORTSTR), m->m_name,
2241 mpvect[0], mpvect[1]);
2244 sm_dprintf("openmailer: NULL\n");
2249 /* make sure system call isn't dead meat */
2250 checkfdopen(mpvect[0], "mpvect[0]");
2251 checkfdopen(mpvect[1], "mpvect[1]");
2252 if (mpvect[0] == mpvect[1] ||
2253 (e->e_lockfp != NULL &&
2254 (mpvect[0] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD,
2256 mpvect[1] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD,
2259 if (e->e_lockfp == NULL)
2260 syserr("%s... openmailer(%s): overlapping mpvect %d %d",
2261 shortenstring(e->e_to, MAXSHORTSTR),
2262 m->m_name, mpvect[0], mpvect[1]);
2264 syserr("%s... openmailer(%s): overlapping mpvect %d %d, lockfp = %d",
2265 shortenstring(e->e_to, MAXSHORTSTR),
2266 m->m_name, mpvect[0], mpvect[1],
2267 sm_io_getinfo(e->e_lockfp,
2268 SM_IO_WHAT_FD, NULL));
2272 /* create a return pipe */
2273 if (pipe(rpvect) < 0)
2275 syserr("%s... openmailer(%s): pipe (from mailer)",
2276 shortenstring(e->e_to, MAXSHORTSTR),
2278 (void) close(mpvect[0]);
2279 (void) close(mpvect[1]);
2281 sm_dprintf("openmailer: NULL\n");
2286 checkfdopen(rpvect[0], "rpvect[0]");
2287 checkfdopen(rpvect[1], "rpvect[1]");
2291 ** Actually fork the mailer process.
2292 ** DOFORK is clever about retrying.
2294 ** Dispose of SIGCHLD signal catchers that may be laying
2295 ** around so that endmailer will get it.
2298 if (e->e_xfp != NULL) /* for debugging */
2299 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
2300 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2301 (void) sm_signal(SIGCHLD, SIG_DFL);
2305 /* pid is set by DOFORK */
2310 syserr("%s... openmailer(%s): cannot fork",
2311 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
2312 (void) close(mpvect[0]);
2313 (void) close(mpvect[1]);
2314 (void) close(rpvect[0]);
2315 (void) close(rpvect[1]);
2317 sm_dprintf("openmailer: NULL\n");
2326 int new_euid = NO_UID;
2327 int new_ruid = NO_UID;
2328 int new_gid = NO_GID;
2331 extern int DtableSize;
2333 CurrentPid = getpid();
2335 /* clear the events to turn off SIGALRMs */
2338 /* Reset global flags */
2339 RestartRequest = NULL;
2340 RestartWorkGroup = false;
2341 ShutdownRequest = NULL;
2344 if (e->e_lockfp != NULL)
2345 (void) close(sm_io_getinfo(e->e_lockfp,
2349 /* child -- set up input & exec mailer */
2350 (void) sm_signal(SIGALRM, sm_signal_noop);
2351 (void) sm_signal(SIGCHLD, SIG_DFL);
2352 (void) sm_signal(SIGHUP, SIG_IGN);
2353 (void) sm_signal(SIGINT, SIG_IGN);
2354 (void) sm_signal(SIGTERM, SIG_DFL);
2356 (void) sm_signal(SIGUSR1, sm_signal_noop);
2357 # endif /* SIGUSR1 */
2359 if (m != FileMailer || stat(tochain->q_user, &stb) < 0)
2362 # if HASSETUSERCONTEXT
2364 ** Set user resources.
2367 if (contextaddr != NULL)
2372 if (contextaddr->q_ruser != NULL)
2373 pwd = sm_getpwnam(contextaddr->q_ruser);
2375 pwd = sm_getpwnam(contextaddr->q_user);
2376 sucflags = LOGIN_SETRESOURCES|LOGIN_SETPRIORITY;
2378 sucflags |= LOGIN_SETMAC;
2379 #endif /* LOGIN_SETMAC */
2381 setusercontext(NULL, pwd, pwd->pw_uid,
2385 syserr("openmailer: setusercontext() failed");
2389 # endif /* HASSETUSERCONTEXT */
2392 /* tweak niceness */
2394 (void) nice(m->m_nice);
2395 #endif /* HASNICE */
2397 /* reset group id */
2398 if (bitnset(M_SPECIFIC_UID, m->m_flags))
2400 else if (bitset(S_ISGID, stb.st_mode))
2401 new_gid = stb.st_gid;
2402 else if (ctladdr != NULL && ctladdr->q_gid != 0)
2404 if (!DontInitGroups)
2406 user = ctladdr->q_ruser;
2408 user = ctladdr->q_user;
2410 if (initgroups(user,
2411 ctladdr->q_gid) == -1
2414 syserr("openmailer: initgroups(%s, %d) failed",
2415 user, ctladdr->q_gid);
2423 gidset[0] = ctladdr->q_gid;
2424 if (setgroups(1, gidset) == -1
2427 syserr("openmailer: setgroups() failed");
2431 new_gid = ctladdr->q_gid;
2435 if (!DontInitGroups)
2438 if (initgroups(DefUser, DefGid) == -1 &&
2441 syserr("openmailer: initgroups(%s, %d) failed",
2451 if (setgroups(1, gidset) == -1
2454 syserr("openmailer: setgroups() failed");
2463 if (new_gid != NO_GID)
2465 if (RunAsUid != 0 &&
2466 bitnset(M_SPECIFIC_UID, m->m_flags) &&
2467 new_gid != getgid() &&
2468 new_gid != getegid())
2470 /* Only root can change the gid */
2471 syserr("openmailer: insufficient privileges to change gid, RunAsUid=%d, new_gid=%d, gid=%d, egid=%d",
2472 (int) RunAsUid, (int) new_gid,
2473 (int) getgid(), (int) getegid());
2477 if (setgid(new_gid) < 0 && suidwarn)
2479 syserr("openmailer: setgid(%ld) failed",
2485 /* change root to some "safe" directory */
2486 if (m->m_rootdir != NULL)
2488 expand(m->m_rootdir, cbuf, sizeof cbuf, e);
2490 sm_dprintf("openmailer: chroot %s\n",
2492 if (chroot(cbuf) < 0)
2494 syserr("openmailer: Cannot chroot(%s)",
2500 syserr("openmailer: cannot chdir(/)");
2507 sm_mbdb_terminate();
2508 if (bitnset(M_SPECIFIC_UID, m->m_flags))
2510 new_euid = m->m_uid;
2513 ** Undo the effects of the uid change in main
2514 ** for signal handling. The real uid may
2515 ** be used by mailer in adding a "From "
2519 if (RealUid != 0 && RealUid != getuid())
2521 # if MAILER_SETUID_METHOD == USE_SETEUID
2523 if (setreuid(RealUid, geteuid()) < 0)
2525 syserr("openmailer: setreuid(%d, %d) failed",
2526 (int) RealUid, (int) geteuid());
2529 # endif /* HASSETREUID */
2530 # endif /* MAILER_SETUID_METHOD == USE_SETEUID */
2531 # if MAILER_SETUID_METHOD == USE_SETREUID
2533 # endif /* MAILER_SETUID_METHOD == USE_SETREUID */
2536 else if (bitset(S_ISUID, stb.st_mode))
2537 new_ruid = stb.st_uid;
2538 else if (ctladdr != NULL && ctladdr->q_uid != 0)
2539 new_ruid = ctladdr->q_uid;
2540 else if (m->m_uid != 0)
2541 new_ruid = m->m_uid;
2545 # if _FFR_USE_SETLOGIN
2546 /* run disconnected from terminal and set login name */
2547 if (setsid() >= 0 &&
2548 ctladdr != NULL && ctladdr->q_uid != 0 &&
2549 new_euid == ctladdr->q_uid)
2553 pwd = sm_getpwuid(ctladdr->q_uid);
2554 if (pwd != NULL && suidwarn)
2555 (void) setlogin(pwd->pw_name);
2558 # endif /* _FFR_USE_SETLOGIN */
2560 if (new_euid != NO_UID)
2562 if (RunAsUid != 0 && new_euid != RunAsUid)
2564 /* Only root can change the uid */
2565 syserr("openmailer: insufficient privileges to change uid, new_euid=%d, RunAsUid=%d",
2566 (int) new_euid, (int) RunAsUid);
2570 vendor_set_uid(new_euid);
2571 # if MAILER_SETUID_METHOD == USE_SETEUID
2572 if (seteuid(new_euid) < 0 && suidwarn)
2574 syserr("openmailer: seteuid(%ld) failed",
2578 # endif /* MAILER_SETUID_METHOD == USE_SETEUID */
2579 # if MAILER_SETUID_METHOD == USE_SETREUID
2580 if (setreuid(new_ruid, new_euid) < 0 && suidwarn)
2582 syserr("openmailer: setreuid(%ld, %ld) failed",
2583 (long) new_ruid, (long) new_euid);
2586 # endif /* MAILER_SETUID_METHOD == USE_SETREUID */
2587 # if MAILER_SETUID_METHOD == USE_SETUID
2588 if (new_euid != geteuid() && setuid(new_euid) < 0 && suidwarn)
2590 syserr("openmailer: setuid(%ld) failed",
2594 # endif /* MAILER_SETUID_METHOD == USE_SETUID */
2596 else if (new_ruid != NO_UID)
2598 vendor_set_uid(new_ruid);
2599 if (setuid(new_ruid) < 0 && suidwarn)
2601 syserr("openmailer: setuid(%ld) failed",
2608 sm_dprintf("openmailer: running as r/euid=%d/%d, r/egid=%d/%d\n",
2609 (int) getuid(), (int) geteuid(),
2610 (int) getgid(), (int) getegid());
2612 /* move into some "safe" directory */
2613 if (m->m_execdir != NULL)
2617 for (p = m->m_execdir; p != NULL; p = q)
2622 expand(p, cbuf, sizeof cbuf, e);
2626 sm_dprintf("openmailer: trydir %s\n",
2628 if (cbuf[0] != '\0' &&
2634 /* Check safety of program to be run */
2635 sff = SFF_ROOTOK|SFF_EXECOK;
2636 if (!bitnset(DBS_RUNWRITABLEPROGRAM,
2638 sff |= SFF_NOGWFILES|SFF_NOWWFILES;
2639 if (bitnset(DBS_RUNPROGRAMINUNSAFEDIRPATH,
2641 sff |= SFF_NOPATHCHECK;
2643 sff |= SFF_SAFEDIRPATH;
2644 ret = safefile(m->m_mailer, getuid(), getgid(),
2645 user, sff, 0, NULL);
2647 sm_syslog(LOG_INFO, e->e_id,
2648 "Warning: program %s unsafe: %s",
2649 m->m_mailer, sm_errstring(ret));
2651 /* arrange to filter std & diag output of command */
2652 (void) close(rpvect[0]);
2653 if (dup2(rpvect[1], STDOUT_FILENO) < 0)
2655 syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
2656 shortenstring(e->e_to, MAXSHORTSTR),
2657 m->m_name, rpvect[1]);
2660 (void) close(rpvect[1]);
2662 if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
2664 syserr("%s... openmailer(%s): cannot dup stdout for stderr",
2665 shortenstring(e->e_to, MAXSHORTSTR),
2670 /* arrange to get standard input */
2671 (void) close(mpvect[1]);
2672 if (dup2(mpvect[0], STDIN_FILENO) < 0)
2674 syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
2675 shortenstring(e->e_to, MAXSHORTSTR),
2676 m->m_name, mpvect[0]);
2679 (void) close(mpvect[0]);
2681 /* arrange for all the files to be closed */
2682 for (i = 3; i < DtableSize; i++)
2686 if ((j = fcntl(i, F_GETFD, 0)) != -1)
2687 (void) fcntl(i, F_SETFD,
2691 # if !_FFR_USE_SETLOGIN
2692 /* run disconnected from terminal */
2694 # endif /* !_FFR_USE_SETLOGIN */
2696 /* try to execute the mailer */
2697 (void) execve(m->m_mailer, (ARGV_T) pv,
2698 (ARGV_T) UserEnviron);
2700 syserr("Cannot exec %s", m->m_mailer);
2701 if (bitnset(M_LOCALMAILER, m->m_flags) ||
2702 transienterror(save_errno))
2704 _exit(EX_UNAVAILABLE);
2708 ** Set up return value.
2716 ** Allocate from general heap, not
2717 ** envelope rpool, because this mci
2718 ** is going to be cached.
2721 mci = mci_new(NULL);
2726 ** Prevent a storage leak by allocating
2727 ** this from the envelope rpool.
2730 mci = mci_new(e->e_rpool);
2733 mci->mci_mailer = m;
2736 mci->mci_state = MCIS_OPENING;
2741 mci->mci_state = MCIS_OPEN;
2744 (void) close(mpvect[0]);
2745 mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2746 (void *) &(mpvect[1]), SM_IO_WRONLY,
2748 if (mci->mci_out == NULL)
2750 syserr("deliver: cannot create mailer output channel, fd=%d",
2752 (void) close(mpvect[1]);
2753 (void) close(rpvect[0]);
2754 (void) close(rpvect[1]);
2759 (void) close(rpvect[1]);
2760 mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2761 (void *) &(rpvect[0]), SM_IO_RDONLY,
2763 if (mci->mci_in == NULL)
2765 syserr("deliver: cannot create mailer input channel, fd=%d",
2767 (void) close(rpvect[0]);
2768 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
2769 mci->mci_out = NULL;
2776 ** If we are in SMTP opening state, send initial protocol.
2779 if (bitnset(M_7BITS, m->m_flags) &&
2780 (!clever || mci->mci_state == MCIS_OPENING))
2781 mci->mci_flags |= MCIF_7BIT;
2782 if (clever && mci->mci_state != MCIS_CLOSED)
2784 # if STARTTLS || SASL
2787 extern SOCKADDR CurHostAddr;
2788 # endif /* STARTTLS || SASL */
2791 # define DONE_AUTH(f) bitset(MCIF_AUTHACT, f)
2794 # define DONE_STARTTLS(f) bitset(MCIF_TLSACT, f)
2795 # endif /* STARTTLS */
2796 # define ONLY_HELO(f) bitset(MCIF_ONLY_EHLO, f)
2797 # define SET_HELO(f) f |= MCIF_ONLY_EHLO
2798 # define CLR_HELO(f) f &= ~MCIF_ONLY_EHLO
2800 # if STARTTLS || SASL
2801 /* don't use CurHostName, it is changed in many places */
2802 if (mci->mci_host != NULL)
2804 srvname = mci->mci_host;
2805 dotpos = strlen(srvname) - 1;
2808 if (srvname[dotpos] == '.')
2809 srvname[dotpos] = '\0';
2814 else if (mci->mci_mailer != NULL)
2816 srvname = mci->mci_mailer->m_name;
2825 /* don't set {server_name} to NULL or "": see getauth() */
2826 macdefine(&mci->mci_macro, A_TEMP, macid("{server_name}"),
2829 /* CurHostAddr is set by makeconnection() and mci_get() */
2830 if (CurHostAddr.sa.sa_family != 0)
2832 macdefine(&mci->mci_macro, A_TEMP,
2833 macid("{server_addr}"),
2834 anynet_ntoa(&CurHostAddr));
2836 else if (mci->mci_mailer != NULL)
2838 /* mailer name is unique, use it as address */
2839 macdefine(&mci->mci_macro, A_PERM,
2840 macid("{server_addr}"),
2841 mci->mci_mailer->m_name);
2845 /* don't set it to NULL or "": see getauth() */
2846 macdefine(&mci->mci_macro, A_PERM,
2847 macid("{server_addr}"), "0");
2850 /* undo change of srvname (mci->mci_host) */
2852 srvname[dotpos] = '.';
2854 reconnect: /* after switching to an encrypted connection */
2855 # endif /* STARTTLS || SASL */
2857 /* set the current connection information */
2860 mci->mci_saslcap = NULL;
2862 smtpinit(m, mci, e, ONLY_HELO(mci->mci_flags));
2863 CLR_HELO(mci->mci_flags);
2865 if (IS_DLVR_RETURN(e))
2868 ** Check whether other side can deliver e-mail
2872 if (!bitset(MCIF_DLVR_BY, mci->mci_flags))
2874 e->e_status = "5.4.7";
2875 usrerrenh(e->e_status,
2876 "554 Server does not support Deliver By");
2877 rcode = EX_UNAVAILABLE;
2880 if (e->e_deliver_by > 0 &&
2881 e->e_deliver_by - (curtime() - e->e_ctime) <
2884 e->e_status = "5.4.7";
2885 usrerrenh(e->e_status,
2886 "554 Message can't be delivered in time; %ld < %ld",
2887 e->e_deliver_by - (curtime() - e->e_ctime),
2889 rcode = EX_UNAVAILABLE;
2895 /* first TLS then AUTH to provide a security layer */
2896 if (mci->mci_state != MCIS_CLOSED &&
2897 !DONE_STARTTLS(mci->mci_flags))
2901 bool saveQuickAbort = QuickAbort;
2902 bool saveSuprErrs = SuprErrs;
2906 usetls = bitset(MCIF_TLS, mci->mci_flags);
2908 usetls = !iscltflgset(e, D_NOTLS);
2912 host = macvalue(macid("{server_name}"), e);
2916 if (rscheck("try_tls", host, NULL, e,
2917 RSF_RMCOMM, 7, host, NOQID) != EX_OK
2918 || Errors > olderrors)
2920 SuprErrs = saveSuprErrs;
2921 QuickAbort = saveQuickAbort;
2926 if ((rcode = starttls(m, mci, e)) == EX_OK)
2928 /* start again without STARTTLS */
2929 mci->mci_flags |= MCIF_TLSACT;
2936 ** TLS negotation failed, what to do?
2937 ** fall back to unencrypted connection
2938 ** or abort? How to decide?
2939 ** set a macro and call a ruleset.
2942 mci->mci_flags &= ~MCIF_TLS;
2958 /* everything else is a failure */
2961 rcode = EX_TEMPFAIL;
2963 macdefine(&e->e_macro, A_PERM,
2964 macid("{verify}"), s);
2968 macdefine(&e->e_macro, A_PERM,
2969 macid("{verify}"), "NONE");
2975 ** rcode == EX_SOFTWARE is special:
2976 ** the TLS negotation failed
2977 ** we have to drop the connection no matter what
2978 ** However, we call tls_server to give it the chance
2979 ** to log the problem and return an appropriate
2983 if (rscheck("tls_server",
2984 macvalue(macid("{verify}"), e),
2985 NULL, e, RSF_RMCOMM|RSF_COUNT, 5,
2986 host, NOQID) != EX_OK ||
2987 Errors > olderrors ||
2988 rcode == EX_SOFTWARE)
2990 char enhsc[ENHSCLEN];
2991 extern char MsgBuf[];
2993 if (ISSMTPCODE(MsgBuf) &&
2994 extenhsc(MsgBuf + 4, ' ', enhsc) > 0)
2996 p = sm_rpool_strdup_x(e->e_rpool,
3001 p = "403 4.7.0 server not authenticated.";
3002 (void) sm_strlcpy(enhsc, "4.7.0",
3005 SuprErrs = saveSuprErrs;
3006 QuickAbort = saveQuickAbort;
3008 if (rcode == EX_SOFTWARE)
3010 /* drop the connection */
3011 mci->mci_state = MCIS_QUITING;
3012 if (mci->mci_in != NULL)
3014 (void) sm_io_close(mci->mci_in,
3018 mci->mci_flags &= ~MCIF_TLSACT;
3019 (void) endmailer(mci, e, pv);
3023 /* abort transfer */
3024 smtpquit(m, mci, e);
3027 /* avoid bogus error msg */
3030 /* temp or permanent failure? */
3031 rcode = (*p == '4') ? EX_TEMPFAIL
3033 mci_setstat(mci, rcode, enhsc, p);
3036 ** hack to get the error message into
3037 ** the envelope (done in giveresponse())
3040 (void) sm_strlcpy(SmtpError, p,
3043 QuickAbort = saveQuickAbort;
3044 SuprErrs = saveSuprErrs;
3045 if (DONE_STARTTLS(mci->mci_flags) &&
3046 mci->mci_state != MCIS_CLOSED)
3048 SET_HELO(mci->mci_flags);
3049 mci->mci_flags &= ~MCIF_EXTENS;
3053 # endif /* STARTTLS */
3055 /* if other server supports authentication let's authenticate */
3056 if (mci->mci_state != MCIS_CLOSED &&
3057 mci->mci_saslcap != NULL &&
3058 !DONE_AUTH(mci->mci_flags) && !iscltflgset(e, D_NOAUTH))
3060 /* Should we require some minimum authentication? */
3061 if ((ret = smtpauth(m, mci, e)) == EX_OK)
3064 sasl_ssf_t *ssf = NULL;
3066 /* Get security strength (features) */
3067 result = sasl_getprop(mci->mci_conn, SASL_SSF,
3069 (const void **) &ssf);
3070 # else /* SASL >= 20000 */
3072 # endif /* SASL >= 20000 */
3076 sm_syslog(LOG_INFO, NOQID,
3077 "AUTH=client, relay=%.100s, mech=%.16s, bits=%d",
3079 macvalue(macid("{auth_type}"), e),
3080 result == SASL_OK ? *ssf : 0);
3083 ** Only switch to encrypted connection
3084 ** if a security layer has been negotiated
3087 if (result == SASL_OK && *ssf > 0)
3090 ** Convert I/O layer to use SASL.
3091 ** If the call fails, the connection
3095 if (sfdcsasl(&mci->mci_in,
3097 mci->mci_conn) == 0)
3099 mci->mci_flags &= ~MCIF_EXTENS;
3100 mci->mci_flags |= MCIF_AUTHACT|
3104 syserr("AUTH TLS switch failed in client");
3107 mci->mci_flags |= MCIF_AUTHACT;
3110 else if (ret == EX_TEMPFAIL)
3113 sm_syslog(LOG_ERR, NOQID,
3114 "AUTH=client, relay=%.100s, temporary failure, connection abort",
3116 smtpquit(m, mci, e);
3118 /* avoid bogus error msg */
3120 rcode = EX_TEMPFAIL;
3121 mci_setstat(mci, rcode, "4.7.1", p);
3124 ** hack to get the error message into
3125 ** the envelope (done in giveresponse())
3128 (void) sm_strlcpy(SmtpError,
3129 "Temporary AUTH failure",
3138 /* clear out per-message flags from connection structure */
3139 mci->mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
3141 if (bitset(EF_HAS8BIT, e->e_flags) &&
3142 !bitset(EF_DONT_MIME, e->e_flags) &&
3143 bitnset(M_7BITS, m->m_flags))
3144 mci->mci_flags |= MCIF_CVT8TO7;
3147 if (bitnset(M_MAKE8BIT, m->m_flags) &&
3148 !bitset(MCIF_7BIT, mci->mci_flags) &&
3149 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
3150 (sm_strcasecmp(p, "quoted-printable") == 0 ||
3151 sm_strcasecmp(p, "base64") == 0) &&
3152 (p = hvalue("Content-Type", e->e_header)) != NULL)
3154 /* may want to convert 7 -> 8 */
3155 /* XXX should really parse it here -- and use a class XXX */
3156 if (sm_strncasecmp(p, "text/plain", 10) == 0 &&
3157 (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
3158 mci->mci_flags |= MCIF_CVT7TO8;
3160 #endif /* MIME7TO8 */
3164 sm_dprintf("openmailer: ");
3165 mci_dump(mci, false);
3168 #if _FFR_CLIENT_SIZE
3170 ** See if we know the maximum size and
3171 ** abort if the message is too big.
3173 ** NOTE: _FFR_CLIENT_SIZE is untested.
3176 if (bitset(MCIF_SIZE, mci->mci_flags) &&
3177 mci->mci_maxsize > 0 &&
3178 e->e_msgsize > mci->mci_maxsize)
3180 e->e_flags |= EF_NO_BODY_RETN;
3181 if (bitnset(M_LOCALMAILER, m->m_flags))
3182 e->e_status = "5.2.3";
3184 e->e_status = "5.3.4";
3186 usrerrenh(e->e_status,
3187 "552 Message is too large; %ld bytes max",
3191 /* Need an e_message for error */
3192 (void) sm_snprintf(SmtpError, sizeof SmtpError,
3193 "Message is too large; %ld bytes max",
3197 #endif /* _FFR_CLIENT_SIZE */
3199 if (mci->mci_state != MCIS_OPEN)
3201 /* couldn't open the mailer */
3202 rcode = mci->mci_exitstat;
3203 errno = mci->mci_errno;
3204 SM_SET_H_ERRNO(mci->mci_herrno);
3207 /* shouldn't happen */
3208 syserr("554 5.3.5 deliver: mci=%lx rcode=%d errno=%d state=%d sig=%s",
3209 (unsigned long) mci, rcode, errno,
3210 mci->mci_state, firstsig);
3212 rcode = EX_SOFTWARE;
3214 else if (nummxhosts > hostnum)
3216 /* try next MX site */
3223 ** Format and send message.
3226 putfromline(mci, e);
3227 (*e->e_puthdr)(mci, e->e_header, e, M87F_OUTER);
3228 (*e->e_putbody)(mci, e, NULL);
3230 /* get the exit status */
3231 rcode = endmailer(mci, e, pv);
3232 if (rcode == EX_TEMPFAIL && SmtpError[0] == '\0')
3235 ** Need an e_message for mailq display.
3236 ** We set SmtpError as
3239 (void) sm_snprintf(SmtpError, sizeof SmtpError,
3240 "%s mailer (%s) exited with EX_TEMPFAIL",
3241 m->m_name, m->m_mailer);
3247 ** Send the MAIL FROM: protocol
3250 /* XXX this isn't pipelined... */
3251 rcode = smtpmailfrom(m, mci, e);
3256 ADDRESS *volatile pchain;
3257 # endif /* PIPELINING */
3259 /* send the recipient list */
3261 mci->mci_retryrcpt = false;
3262 mci->mci_tolist = tobuf;
3265 mci->mci_nextaddr = NULL;
3266 # endif /* PIPELINING */
3268 for (to = tochain; to != NULL; to = to->q_tchain)
3270 if (!QS_IS_UNMARKED(to->q_state))
3273 /* mark recipient state as "ok so far" */
3274 to->q_state = QS_OK;
3275 e->e_to = to->q_paddr;
3277 i = rscheck("tls_rcpt", to->q_user, NULL, e,
3278 RSF_RMCOMM|RSF_COUNT, 3,
3279 mci->mci_host, e->e_id);
3282 markfailure(e, to, mci, i, false);
3283 giveresponse(i, to->q_status, m, mci,
3284 ctladdr, xstart, e, to);
3285 if (i == EX_TEMPFAIL)
3287 mci->mci_retryrcpt = true;
3288 to->q_state = QS_RETRY;
3292 # endif /* STARTTLS */
3294 i = smtprcpt(to, m, mci, e, ctladdr, xstart);
3297 bitset(MCIF_PIPELINED, mci->mci_flags))
3300 ** Add new element to list of
3301 ** recipients for pipelining.
3304 to->q_pchain = NULL;
3305 if (mci->mci_nextaddr == NULL)
3306 mci->mci_nextaddr = to;
3311 pchain->q_pchain = to;
3312 pchain = pchain->q_pchain;
3315 # endif /* PIPELINING */
3318 markfailure(e, to, mci, i, false);
3319 giveresponse(i, to->q_status, m, mci,
3320 ctladdr, xstart, e, to);
3321 if (i == EX_TEMPFAIL)
3322 to->q_state = QS_RETRY;
3326 /* No recipients in list and no missing responses? */
3327 if (tobuf[0] == '\0'
3329 && mci->mci_nextaddr == NULL
3330 # endif /* PIPELINING */
3335 if (bitset(MCIF_CACHED, mci->mci_flags))
3336 smtprset(m, mci, e);
3340 e->e_to = tobuf + 1;
3341 rcode = smtpdata(m, mci, e, ctladdr, xstart);
3344 if (rcode == EX_TEMPFAIL && nummxhosts > hostnum)
3346 /* try next MX site */
3351 if (ConfigLevel < 2)
3352 _res.options |= RES_DEFNAMES | RES_DNSRCH; /* XXX */
3353 #endif /* NAMED_BIND */
3356 checkfds("after delivery");
3359 ** Do final status disposal.
3360 ** We check for something in tobuf for the SMTP case.
3361 ** If we got a temporary failure, arrange to queue the
3366 if (bitnset(M_LMTP, m->m_flags))
3374 anyok = rcode == EX_OK;
3376 for (to = tochain; to != NULL; to = to->q_tchain)
3378 /* see if address already marked */
3379 if (!QS_IS_OK(to->q_state))
3382 /* if running LMTP, get the status for each address */
3383 if (bitnset(M_LMTP, m->m_flags))
3385 if (lmtp_rcode == EX_OK)
3386 rcode = smtpgetstat(m, mci, e);
3389 strsize += sm_strlcat2(tobuf + strsize, ",",
3391 tobufsize - strsize);
3392 SM_ASSERT(strsize < tobufsize);
3397 e->e_to = to->q_paddr;
3398 markfailure(e, to, mci, rcode, true);
3399 giveresponse(rcode, to->q_status, m, mci,
3400 ctladdr, xstart, e, to);
3401 e->e_to = tobuf + 1;
3407 /* mark bad addresses */
3410 if (goodmxfound && rcode == EX_NOHOST)
3411 rcode = EX_TEMPFAIL;
3412 markfailure(e, to, mci, rcode, true);
3417 /* successful delivery */
3418 to->q_state = QS_SENT;
3419 to->q_statdate = curtime();
3423 ** Checkpoint the send list every few addresses
3426 if (CheckpointInterval > 0 && e->e_nsent >= CheckpointInterval)
3428 queueup(e, false, false);
3432 if (bitnset(M_LOCALMAILER, m->m_flags) &&
3433 bitset(QPINGONSUCCESS, to->q_flags))
3435 to->q_flags |= QDELIVERED;
3436 to->q_status = "2.1.5";
3437 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3438 "%s... Successfully delivered\n",
3441 else if (bitset(QPINGONSUCCESS, to->q_flags) &&
3442 bitset(QPRIMARY, to->q_flags) &&
3443 !bitset(MCIF_DSN, mci->mci_flags))
3445 to->q_flags |= QRELAYED;
3446 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3447 "%s... relayed; expect no further notifications\n",
3450 else if (IS_DLVR_NOTIFY(e) &&
3451 !bitset(MCIF_DLVR_BY, mci->mci_flags) &&
3452 bitset(QPRIMARY, to->q_flags) &&
3453 (!bitset(QHASNOTIFY, to->q_flags) ||
3454 bitset(QPINGONSUCCESS, to->q_flags) ||
3455 bitset(QPINGONFAILURE, to->q_flags) ||
3456 bitset(QPINGONDELAY, to->q_flags)))
3458 /* RFC 2852, 4.1.4.2: no NOTIFY, or not NEVER */
3459 to->q_flags |= QBYNRELAY;
3460 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3461 "%s... Deliver-by notify: relayed\n",
3464 else if (IS_DLVR_TRACE(e) &&
3465 (!bitset(QHASNOTIFY, to->q_flags) ||
3466 bitset(QPINGONSUCCESS, to->q_flags) ||
3467 bitset(QPINGONFAILURE, to->q_flags) ||
3468 bitset(QPINGONDELAY, to->q_flags)) &&
3469 bitset(QPRIMARY, to->q_flags))
3471 /* RFC 2852, 4.1.4: no NOTIFY, or not NEVER */
3472 to->q_flags |= QBYTRACE;
3473 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3474 "%s... Deliver-By trace: relayed\n",
3479 if (bitnset(M_LMTP, m->m_flags))
3482 ** Global information applies to the last recipient only;
3483 ** clear it out to avoid bogus errors.
3487 e->e_statmsg = NULL;
3489 /* reset the mci state for the next transaction */
3491 (mci->mci_state == MCIS_MAIL ||
3492 mci->mci_state == MCIS_RCPT ||
3493 mci->mci_state == MCIS_DATA))
3494 mci->mci_state = MCIS_OPEN;
3497 if (tobuf[0] != '\0')
3499 giveresponse(rcode, NULL, m, mci, ctladdr, xstart, e, tochain);
3502 ** This code is disabled for now because I am not
3503 ** sure that copying status from the first recipient
3504 ** to all non-status'ed recipients is a good idea.
3507 if (tochain->q_message != NULL &&
3508 !bitnset(M_LMTP, m->m_flags) && rcode != EX_OK)
3510 for (to = tochain->q_tchain; to != NULL;
3513 /* see if address already marked */
3514 if (QS_IS_QUEUEUP(to->q_state) &&
3515 to->q_message == NULL)
3516 to->q_message = sm_rpool_strdup_x(e->e_rpool,
3517 tochain->q_message);
3523 markstats(e, tochain, STATS_NORMAL);
3524 mci_store_persistent(mci);
3526 /* Some recipients were tempfailed, try them on the next host */
3527 if (mci != NULL && mci->mci_retryrcpt && nummxhosts > hostnum)
3529 /* try next MX site */
3533 /* now close the connection */
3534 if (clever && mci != NULL && mci->mci_state != MCIS_CLOSED &&
3535 !bitset(MCIF_CACHED, mci->mci_flags))
3536 smtpquit(m, mci, e);
3543 ** Restore state and return.
3548 /* make absolutely certain 0, 1, and 2 are in use */
3549 (void) sm_snprintf(wbuf, sizeof wbuf,
3550 "%s... end of deliver(%s)",
3551 e->e_to == NULL ? "NO-TO-LIST"
3552 : shortenstring(e->e_to,
3561 ** It was originally necessary to set macro 'g' to NULL
3562 ** because it previously pointed to an auto buffer.
3563 ** We don't do this any more, so this may be unnecessary.
3566 macdefine(&e->e_macro, A_PERM, 'g', (char *) NULL);
3574 ** MARKFAILURE -- mark a failure on a specific address.
3577 ** e -- the envelope we are sending.
3578 ** q -- the address to mark.
3579 ** mci -- mailer connection information.
3580 ** rcode -- the code signifying the particular failure.
3581 ** ovr -- override an existing code?
3587 ** marks the address (and possibly the envelope) with the
3588 ** failure so that an error will be returned or
3589 ** the message will be queued, as appropriate.
3593 markfailure(e, q, mci, rcode, ovr)
3594 register ENVELOPE *e;
3595 register ADDRESS *q;
3600 int save_errno = errno;
3601 char *status = NULL;
3602 char *rstatus = NULL;
3612 q->q_state = QS_QUEUEUP;
3616 q->q_state = QS_BADADDR;
3620 /* find most specific error code possible */
3621 if (mci != NULL && mci->mci_status != NULL)
3623 status = sm_rpool_strdup_x(e->e_rpool, mci->mci_status);
3624 if (mci->mci_rstatus != NULL)
3625 rstatus = sm_rpool_strdup_x(e->e_rpool,
3630 else if (e->e_status != NULL)
3632 status = e->e_status;
3661 case EX_UNAVAILABLE:
3681 if (status != NULL && *status != '\0' && (ovr || q->q_status == NULL ||
3682 *q->q_status == '\0' || *q->q_status < *status))
3684 q->q_status = status;
3685 q->q_rstatus = rstatus;
3687 if (rcode != EX_OK && q->q_rstatus == NULL &&
3688 q->q_mailer != NULL && q->q_mailer->m_diagtype != NULL &&
3689 sm_strcasecmp(q->q_mailer->m_diagtype, "X-UNIX") == 0)
3693 (void) sm_snprintf(buf, sizeof buf, "%d", rcode);
3694 q->q_rstatus = sm_rpool_strdup_x(e->e_rpool, buf);
3697 q->q_statdate = curtime();
3698 if (CurHostName != NULL && CurHostName[0] != '\0' &&
3699 mci != NULL && !bitset(M_LOCALMAILER, mci->mci_flags))
3700 q->q_statmta = sm_rpool_strdup_x(e->e_rpool, CurHostName);
3706 ** ENDMAILER -- Wait for mailer to terminate.
3708 ** We should never get fatal errors (e.g., segmentation
3709 ** violation), so we report those specially. For other
3710 ** errors, we choose a status message (into statmsg),
3711 ** and if it represents an error, we print it.
3714 ** mci -- the mailer connection info.
3715 ** e -- the current envelope.
3716 ** pv -- the parameter vector that invoked the mailer
3717 ** (for error messages).
3720 ** exit code of mailer.
3726 static jmp_buf EndWaitTimeout;
3732 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3733 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3738 longjmp(EndWaitTimeout, 1);
3742 endmailer(mci, e, pv)
3744 register ENVELOPE *e;
3748 int save_errno = errno;
3750 SM_EVENT *ev = NULL;
3753 mci_unlock_host(mci);
3755 /* close output to mailer */
3756 if (mci->mci_out != NULL)
3757 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
3759 /* copy any remaining input to transcript */
3760 if (mci->mci_in != NULL && mci->mci_state != MCIS_ERROR &&
3763 while (sfgets(buf, sizeof buf, mci->mci_in,
3764 TimeOuts.to_quit, "Draining Input") != NULL)
3765 (void) sm_io_fputs(e->e_xfp, SM_TIME_DEFAULT, buf);
3769 /* close SASL connection */
3770 if (bitset(MCIF_AUTHACT, mci->mci_flags))
3772 sasl_dispose(&mci->mci_conn);
3773 mci->mci_flags &= ~MCIF_AUTHACT;
3779 (void) endtlsclt(mci);
3780 #endif /* STARTTLS */
3782 /* now close the input */
3783 if (mci->mci_in != NULL)
3784 (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT);
3785 mci->mci_in = mci->mci_out = NULL;
3786 mci->mci_state = MCIS_CLOSED;
3790 /* in the IPC case there is nothing to wait for */
3791 if (mci->mci_pid == 0)
3794 /* put a timeout around the wait */
3795 if (mci->mci_mailer->m_wait > 0)
3797 if (setjmp(EndWaitTimeout) == 0)
3798 ev = sm_setevent(mci->mci_mailer->m_wait,
3802 syserr("endmailer %s: wait timeout (%ld)",
3803 mci->mci_mailer->m_name,
3804 (long) mci->mci_mailer->m_wait);
3809 /* wait for the mailer process, collect status */
3810 st = waitfor(mci->mci_pid);
3818 syserr("endmailer %s: wait", mci->mci_mailer->m_name);
3824 /* normal death -- return status */
3825 return (WEXITSTATUS(st));
3828 /* it died a horrid death */
3829 syserr("451 4.3.0 mailer %s died with signal %d%s",
3830 mci->mci_mailer->m_name, WTERMSIG(st),
3831 WCOREDUMP(st) ? " (core dumped)" :
3832 (WIFSTOPPED(st) ? " (stopped)" : ""));
3834 /* log the arguments */
3835 if (pv != NULL && e->e_xfp != NULL)
3839 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "Arguments:");
3840 for (av = pv; *av != NULL; av++)
3841 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, " %s",
3843 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "\n");
3846 ExitStat = EX_TEMPFAIL;
3850 ** GIVERESPONSE -- Interpret an error response from a mailer
3853 ** status -- the status code from the mailer (high byte
3854 ** only; core dumps must have been taken care of
3856 ** dsn -- the DSN associated with the address, if any.
3857 ** m -- the mailer info for this mailer.
3858 ** mci -- the mailer connection info -- can be NULL if the
3859 ** response is given before the connection is made.
3860 ** ctladdr -- the controlling address for the recipient
3862 ** xstart -- the transaction start time, for computing
3863 ** transaction delays.
3864 ** e -- the current envelope.
3865 ** to -- the current recipient (NULL if none).
3871 ** Errors may be incremented.
3872 ** ExitStat may be set.
3876 giveresponse(status, dsn, m, mci, ctladdr, xstart, e, to)
3886 register const char *statmsg;
3889 bool usestat = false;
3890 char dsnbuf[ENHSCLEN];
3895 syserr("giveresponse: null envelope");
3898 ** Compute status message from code.
3901 exmsg = sm_sysexmsg(status);
3904 statmsg = "250 2.0.0 Sent";
3905 if (e->e_statmsg != NULL)
3907 (void) sm_snprintf(buf, sizeof buf, "%s (%s)",
3909 shortenstring(e->e_statmsg, 403));
3913 else if (exmsg == NULL)
3915 (void) sm_snprintf(buf, sizeof buf,
3916 "554 5.3.0 unknown mailer error %d",
3918 status = EX_UNAVAILABLE;
3922 else if (status == EX_TEMPFAIL)
3926 (void) sm_strlcpy(bp, exmsg + 1, SPACELEFT(buf, bp));
3929 if (h_errno == TRY_AGAIN)
3930 statmsg = sm_errstring(h_errno + E_DNSBASE);
3932 #endif /* NAMED_BIND */
3935 statmsg = sm_errstring(errnum);
3937 statmsg = SmtpError;
3939 if (statmsg != NULL && statmsg[0] != '\0')
3944 case ENETDOWN: /* Network is down */
3945 #endif /* ENETDOWN */
3947 case ENETUNREACH: /* Network is unreachable */
3948 #endif /* ENETUNREACH */
3950 case ENETRESET: /* Network dropped connection on reset */
3951 #endif /* ENETRESET */
3953 case ECONNABORTED: /* Software caused connection abort */
3954 #endif /* ECONNABORTED */
3956 case EHOSTDOWN: /* Host is down */
3957 #endif /* EHOSTDOWN */
3959 case EHOSTUNREACH: /* No route to host */
3960 #endif /* EHOSTUNREACH */
3961 if (mci->mci_host != NULL)
3963 (void) sm_strlcpyn(bp,
3971 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ": ",
3978 else if (status == EX_NOHOST && h_errno != 0)
3980 statmsg = sm_errstring(h_errno + E_DNSBASE);
3981 (void) sm_snprintf(buf, sizeof buf, "%s (%s)", exmsg + 1,
3986 #endif /* NAMED_BIND */
3990 if (*statmsg++ == ':' && errnum != 0)
3992 (void) sm_snprintf(buf, sizeof buf, "%s: %s", statmsg,
3993 sm_errstring(errnum));
3997 else if (bitnset(M_LMTP, m->m_flags) && e->e_statmsg != NULL)
3999 (void) sm_snprintf(buf, sizeof buf, "%s (%s)", statmsg,
4000 shortenstring(e->e_statmsg, 403));
4007 ** Print the message as appropriate
4010 if (status == EX_OK || status == EX_TEMPFAIL)
4012 extern char MsgBuf[];
4014 if ((off = isenhsc(statmsg + 4, ' ')) > 0)
4018 (void) sm_snprintf(dsnbuf, sizeof dsnbuf,
4019 "%.*s", off, statmsg + 4);
4028 message("%s", statmsg + off);
4029 if (status == EX_TEMPFAIL && e->e_xfp != NULL)
4030 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s\n",
4035 char mbuf[ENHSCLEN + 4];
4038 if ((off = isenhsc(statmsg + 4, ' ')) > 0 &&
4039 off < sizeof mbuf - 4)
4043 (void) sm_snprintf(dsnbuf, sizeof dsnbuf,
4044 "%.*s", off, statmsg + 4);
4049 /* copy only part of statmsg to mbuf */
4050 (void) sm_strlcpy(mbuf, statmsg, off);
4051 (void) sm_strlcat(mbuf, " %s", sizeof mbuf);
4056 (void) sm_snprintf(mbuf, sizeof mbuf, "%.3s %%s",
4060 usrerr(mbuf, &statmsg[off]);
4065 ** Log a record of the transaction. Compute the new
4066 ** ExitStat -- if we already had an error, stick with
4070 if (OpMode != MD_VERIFY && !bitset(EF_VRFYONLY, e->e_flags) &&
4071 LogLevel > ((status == EX_TEMPFAIL) ? 8 : (status == EX_OK) ? 7 : 6))
4072 logdelivery(m, mci, dsn, statmsg + off, ctladdr, xstart, e);
4075 sm_dprintf("giveresponse: status=%d, dsn=%s, e->e_message=%s, errnum=%d\n",
4077 dsn == NULL ? "<NULL>" : dsn,
4078 e->e_message == NULL ? "<NULL>" : e->e_message,
4081 if (status != EX_TEMPFAIL)
4083 if (status != EX_OK && (status != EX_TEMPFAIL || e->e_message == NULL))
4084 e->e_message = sm_rpool_strdup_x(e->e_rpool, statmsg + off);
4085 if (status != EX_OK && to != NULL && to->q_message == NULL)
4087 if (!usestat && e->e_message != NULL)
4088 to->q_message = sm_rpool_strdup_x(e->e_rpool,
4091 to->q_message = sm_rpool_strdup_x(e->e_rpool,
4098 ** LOGDELIVERY -- log the delivery in the system log
4100 ** Care is taken to avoid logging lines that are too long, because
4101 ** some versions of syslog have an unfortunate proclivity for core
4102 ** dumping. This is a hack, to be sure, that is at best empirical.
4105 ** m -- the mailer info. Can be NULL for initial queue.
4106 ** mci -- the mailer connection info -- can be NULL if the
4107 ** log is occurring when no connection is active.
4108 ** dsn -- the DSN attached to the status.
4109 ** status -- the message to print for the status.
4110 ** ctladdr -- the controlling address for the to list.
4111 ** xstart -- the transaction start time, used for
4112 ** computing transaction delay.
4113 ** e -- the current envelope.
4123 logdelivery(m, mci, dsn, status, ctladdr, xstart, e)
4130 register ENVELOPE *e;
4135 time_t now = curtime();
4138 #if (SYSLOG_BUFSIZE) >= 256
4139 /* ctladdr: max 106 bytes */
4141 if (ctladdr != NULL)
4143 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", ctladdr=",
4144 shortenstring(ctladdr->q_paddr, 83));
4146 if (bitset(QGOODUID, ctladdr->q_flags))
4148 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
4149 (int) ctladdr->q_uid,
4150 (int) ctladdr->q_gid);
4155 /* delay & xdelay: max 41 bytes */
4156 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", delay=",
4157 pintvl(now - e->e_ctime, true));
4160 if (xstart != (time_t) 0)
4162 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=",
4163 pintvl(now - xstart, true));
4167 /* mailer: assume about 19 bytes (max 10 byte mailer name) */
4170 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=",
4175 /* pri: changes with each delivery attempt */
4176 (void) sm_snprintf(bp, SPACELEFT(buf, bp), ", pri=%ld",
4180 /* relay: max 66 bytes for IPv4 addresses */
4181 if (mci != NULL && mci->mci_host != NULL)
4183 extern SOCKADDR CurHostAddr;
4185 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", relay=",
4186 shortenstring(mci->mci_host, 40));
4189 if (CurHostAddr.sa.sa_family != 0)
4191 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " [%s]",
4192 anynet_ntoa(&CurHostAddr));
4196 else if (strcmp(status, "quarantined") == 0)
4198 if (e->e_quarmsg != NULL)
4199 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4201 shortenstring(e->e_quarmsg, 40));
4203 #endif /* _FFR_QUARANTINE */
4204 else if (strcmp(status, "queued") != 0)
4206 p = macvalue('h', e);
4207 if (p != NULL && p[0] != '\0')
4209 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4210 ", relay=%s", shortenstring(p, 40));
4216 if (dsn != NULL && *dsn != '\0')
4218 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", dsn=",
4219 shortenstring(dsn, ENHSCLEN));
4223 # define STATLEN (((SYSLOG_BUFSIZE) - 100) / 4)
4227 # endif /* (STATLEN) < 63 */
4228 # if (STATLEN) > 203
4230 # define STATLEN 203
4231 # endif /* (STATLEN) > 203 */
4233 /* stat: max 210 bytes */
4234 if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
4236 /* desperation move -- truncate data */
4237 bp = buf + sizeof buf - ((STATLEN) + 17);
4238 (void) sm_strlcpy(bp, "...", SPACELEFT(buf, bp));
4242 (void) sm_strlcpy(bp, ", stat=", SPACELEFT(buf, bp));
4245 (void) sm_strlcpy(bp, shortenstring(status, STATLEN),
4246 SPACELEFT(buf, bp));
4248 /* id, to: max 13 + TOBUFSIZE bytes */
4249 l = SYSLOG_BUFSIZE - 100 - strlen(buf);
4252 p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
4253 while (strlen(p) >= l)
4257 for (q = p + l; q > p; q--)
4264 sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]%s",
4265 (int) (++q - p), p, buf);
4268 sm_syslog(LOG_INFO, e->e_id, "to=%.*s%s", l, p, buf);
4270 #else /* (SYSLOG_BUFSIZE) >= 256 */
4272 l = SYSLOG_BUFSIZE - 85;
4275 p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
4276 while (strlen(p) >= l)
4280 for (q = p + l; q > p; q--)
4288 sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]",
4289 (int) (++q - p), p);
4292 sm_syslog(LOG_INFO, e->e_id, "to=%.*s", l, p);
4294 if (ctladdr != NULL)
4297 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "ctladdr=",
4298 shortenstring(ctladdr->q_paddr, 83));
4300 if (bitset(QGOODUID, ctladdr->q_flags))
4302 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
4303 ctladdr->q_uid, ctladdr->q_gid);
4306 sm_syslog(LOG_INFO, e->e_id, "%s", buf);
4309 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "delay=",
4310 pintvl(now - e->e_ctime, true));
4312 if (xstart != (time_t) 0)
4314 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=",
4315 pintvl(now - xstart, true));
4321 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=",
4325 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
4329 if (mci != NULL && mci->mci_host != NULL)
4331 extern SOCKADDR CurHostAddr;
4333 (void) sm_snprintf(bp, SPACELEFT(buf, bp), "relay=%.100s",
4337 if (CurHostAddr.sa.sa_family != 0)
4338 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4340 anynet_ntoa(&CurHostAddr));
4343 else if (strcmp(status, "quarantined") == 0)
4345 if (e->e_quarmsg != NULL)
4346 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4347 ", quarantine=%.100s",
4350 #endif /* _FFR_QUARANTINE */
4351 else if (strcmp(status, "queued") != 0)
4353 p = macvalue('h', e);
4354 if (p != NULL && p[0] != '\0')
4355 (void) sm_snprintf(buf, sizeof buf, "relay=%.100s", p);
4358 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
4360 sm_syslog(LOG_INFO, e->e_id, "stat=%s", shortenstring(status, 63));
4361 #endif /* (SYSLOG_BUFSIZE) >= 256 */
4364 ** PUTFROMLINE -- output a UNIX-style from line (or whatever)
4366 ** This can be made an arbitrary message separator by changing $l
4368 ** One of the ugliest hacks seen by human eyes is contained herein:
4369 ** UUCP wants those stupid "remote from <host>" lines. Why oh why
4370 ** does a well-meaning programmer such as myself have to deal with
4371 ** this kind of antique garbage????
4374 ** mci -- the connection information.
4375 ** e -- the envelope.
4381 ** outputs some text to fp.
4389 char *template = UnixFromLine;
4393 if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
4396 mci->mci_flags |= MCIF_INHEADER;
4398 if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
4402 expand("\201g", buf, sizeof buf, e);
4403 bang = strchr(buf, '!');
4407 char hname[MAXNAME];
4410 ** If we can construct a UUCP path, do so
4413 at = strrchr(buf, '@');
4416 expand("\201k", hname, sizeof hname, e);
4421 (void) sm_snprintf(xbuf, sizeof xbuf,
4422 "From %.800s \201d remote from %.100s\n",
4428 (void) sm_snprintf(xbuf, sizeof xbuf,
4429 "From %.800s \201d remote from %.100s\n",
4434 expand(template, buf, sizeof buf, e);
4435 putxline(buf, strlen(buf), mci, PXLF_HEADER);
4438 ** PUTBODY -- put the body of a message.
4441 ** mci -- the connection information.
4442 ** e -- the envelope to put out.
4443 ** separator -- if non-NULL, a message separator that must
4444 ** not be permitted in the resulting message.
4450 ** The message is written onto fp.
4453 /* values for output state variable */
4454 #define OS_HEAD 0 /* at beginning of line */
4455 #define OS_CR 1 /* read a carriage return */
4456 #define OS_INLINE 2 /* putting rest of line */
4459 putbody(mci, e, separator)
4461 register ENVELOPE *e;
4467 char *boundaries[MAXMIMENESTING + 1];
4468 #endif /* MIME8TO7 */
4471 ** Output the body of the message
4474 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
4476 char *df = queuename(e, DATAFL_LETTER);
4478 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df,
4479 SM_IO_RDONLY_B, NULL);
4480 if (e->e_dfp == NULL)
4482 char *msg = "!putbody: Cannot open %s for %s from %s";
4484 if (errno == ENOENT)
4486 syserr(msg, df, e->e_to, e->e_from.q_paddr);
4490 if (e->e_dfp == NULL)
4492 if (bitset(MCIF_INHEADER, mci->mci_flags))
4495 mci->mci_flags &= ~MCIF_INHEADER;
4497 putline("<<< No Message Collected >>>", mci);
4501 if (e->e_dfino == (ino_t) 0)
4505 if (fstat(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), &stbuf)
4510 e->e_dfdev = stbuf.st_dev;
4511 e->e_dfino = stbuf.st_ino;
4515 /* paranoia: the data file should always be in a rewound state */
4516 (void) bfrewind(e->e_dfp);
4519 if (bitset(MCIF_CVT8TO7, mci->mci_flags))
4522 ** Do 8 to 7 bit MIME conversion.
4525 /* make sure it looks like a MIME message */
4526 if (hvalue("MIME-Version", e->e_header) == NULL)
4527 putline("MIME-Version: 1.0", mci);
4529 if (hvalue("Content-Type", e->e_header) == NULL)
4531 (void) sm_snprintf(buf, sizeof buf,
4532 "Content-Type: text/plain; charset=%s",
4537 /* now do the hard work */
4538 boundaries[0] = NULL;
4539 mci->mci_flags |= MCIF_INHEADER;
4540 (void) mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER);
4543 else if (bitset(MCIF_CVT7TO8, mci->mci_flags))
4545 (void) mime7to8(mci, e->e_header, e);
4547 # endif /* MIME7TO8 */
4548 else if (MaxMimeHeaderLength > 0 || MaxMimeFieldLength > 0)
4550 bool oldsuprerrs = SuprErrs;
4552 /* Use mime8to7 to check multipart for MIME header overflows */
4553 boundaries[0] = NULL;
4554 mci->mci_flags |= MCIF_INHEADER;
4557 ** If EF_DONT_MIME is set, we have a broken MIME message
4558 ** and don't want to generate a new bounce message whose
4559 ** body propagates the broken MIME. We can't just not call
4560 ** mime8to7() as is done above since we need the security
4561 ** checks. The best we can do is suppress the errors.
4564 if (bitset(EF_DONT_MIME, e->e_flags))
4567 (void) mime8to7(mci, e->e_header, e, boundaries,
4568 M87F_OUTER|M87F_NO8TO7);
4570 /* restore SuprErrs */
4571 SuprErrs = oldsuprerrs;
4574 #endif /* MIME8TO7 */
4586 if (bitset(MCIF_INHEADER, mci->mci_flags))
4589 mci->mci_flags &= ~MCIF_INHEADER;
4592 /* determine end of buffer; allow for short mailer lines */
4593 buflim = &buf[sizeof buf - 1];
4594 if (mci->mci_mailer->m_linelimit > 0 &&
4595 mci->mci_mailer->m_linelimit < sizeof buf - 1)
4596 buflim = &buf[mci->mci_mailer->m_linelimit - 1];
4598 /* copy temp file to output with mapping */
4602 while (!sm_io_error(mci->mci_out) && !dead)
4606 else if ((c = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT))
4609 if (bitset(MCIF_7BIT, mci->mci_flags))
4616 mci->mci_mailer->m_flags))
4618 if (c != '\r' && c != '\n' && bp < buflim)
4624 /* check beginning of line for special cases */
4628 if (buf[0] == 'F' &&
4629 bitnset(M_ESCFROM, mci->mci_mailer->m_flags)
4630 && strncmp(buf, "From ", 5) == 0)
4634 if (buf[0] == '-' && buf[1] == '-' &&
4637 /* possible separator */
4638 int sl = strlen(separator);
4640 if (strncmp(&buf[2], separator, sl)
4644 if (buf[0] == '.' &&
4645 bitnset(M_XDOT, mci->mci_mailer->m_flags))
4650 /* now copy out saved line */
4651 if (TrafficLogFile != NULL)
4653 (void) sm_io_fprintf(TrafficLogFile,
4657 if (padc != SM_IO_EOF)
4658 (void) sm_io_putc(TrafficLogFile,
4661 for (xp = buf; xp < bp; xp++)
4662 (void) sm_io_putc(TrafficLogFile,
4664 (unsigned char) *xp);
4666 (void) sm_io_fputs(TrafficLogFile,
4668 mci->mci_mailer->m_eol);
4670 if (padc != SM_IO_EOF)
4672 if (sm_io_putc(mci->mci_out,
4673 SM_TIME_DEFAULT, padc)
4681 /* record progress for DATA timeout */
4682 DataProgress = true;
4686 for (xp = buf; xp < bp; xp++)
4688 if (sm_io_putc(mci->mci_out,
4690 (unsigned char) *xp)
4698 /* record progress for DATA timeout */
4699 DataProgress = true;
4706 if (sm_io_fputs(mci->mci_out,
4708 mci->mci_mailer->m_eol)
4713 /* record progress for DATA timeout */
4714 DataProgress = true;
4723 SM_ASSERT(pbp < peekbuf +
4731 /* determine next state */
4744 if (sm_io_fputs(mci->mci_out,
4746 mci->mci_mailer->m_eol)
4751 /* record progress for DATA timeout */
4752 DataProgress = true;
4755 if (TrafficLogFile != NULL)
4757 (void) sm_io_fputs(TrafficLogFile,
4759 mci->mci_mailer->m_eol);
4765 /* had a naked carriage return */
4766 SM_ASSERT(pbp < peekbuf + sizeof(peekbuf));
4780 mci->mci_mailer->m_flags))
4783 if (mci->mci_mailer->m_linelimit > 0 &&
4784 pos >= mci->mci_mailer->m_linelimit - 1 &&
4789 /* check next character for EOL */
4792 else if ((d = sm_io_getc(e->e_dfp,
4796 SM_ASSERT(pbp < peekbuf +
4801 if (d == '\n' || d == SM_IO_EOF)
4803 if (TrafficLogFile != NULL)
4804 (void) sm_io_putc(TrafficLogFile,
4807 if (sm_io_putc(mci->mci_out,
4817 /* record progress for DATA timeout */
4818 DataProgress = true;
4824 if (sm_io_putc(mci->mci_out,
4825 SM_TIME_DEFAULT, '!')
4827 sm_io_fputs(mci->mci_out,
4829 mci->mci_mailer->m_eol)
4837 /* record progress for DATA timeout */
4838 DataProgress = true;
4841 if (TrafficLogFile != NULL)
4843 (void) sm_io_fprintf(TrafficLogFile,
4846 mci->mci_mailer->m_eol);
4849 SM_ASSERT(pbp < peekbuf +
4856 if (TrafficLogFile != NULL)
4857 (void) sm_io_fputs(TrafficLogFile,
4859 mci->mci_mailer->m_eol);
4860 if (sm_io_fputs(mci->mci_out,
4862 mci->mci_mailer->m_eol)
4867 /* record progress for DATA timeout */
4868 DataProgress = true;
4875 if (TrafficLogFile != NULL)
4876 (void) sm_io_putc(TrafficLogFile,
4879 if (sm_io_putc(mci->mci_out,
4889 /* record progress for DATA timeout */
4890 DataProgress = true;
4899 /* make sure we are at the beginning of a line */
4902 if (TrafficLogFile != NULL)
4904 for (xp = buf; xp < bp; xp++)
4905 (void) sm_io_putc(TrafficLogFile,
4907 (unsigned char) *xp);
4909 for (xp = buf; xp < bp; xp++)
4911 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT,
4912 (unsigned char) *xp)
4920 /* record progress for DATA timeout */
4921 DataProgress = true;
4926 if (!dead && pos > 0)
4928 if (TrafficLogFile != NULL)
4929 (void) sm_io_fputs(TrafficLogFile,
4931 mci->mci_mailer->m_eol);
4932 (void) sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT,
4933 mci->mci_mailer->m_eol);
4935 /* record progress for DATA timeout */
4936 DataProgress = true;
4940 if (sm_io_error(e->e_dfp))
4942 syserr("putbody: %s/%cf%s: read error",
4943 qid_printqueue(e->e_dfqgrp, e->e_dfqdir),
4944 DATAFL_LETTER, e->e_id);
4945 ExitStat = EX_IOERR;
4950 ** Since mailfile() uses e_dfp in a child process,
4951 ** the file offset in the stdio library for the
4952 ** parent process will not agree with the in-kernel
4953 ** file offset since the file descriptor is shared
4954 ** between the processes. Therefore, it is vital
4955 ** that the file always be rewound. This forces the
4956 ** kernel offset (lseek) and stdio library (ftell)
4960 if (e->e_dfp != NULL)
4961 (void) bfrewind(e->e_dfp);
4963 /* some mailers want extra blank line at end of message */
4964 if (!dead && bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
4965 buf[0] != '\0' && buf[0] != '\n')
4968 (void) sm_io_flush(mci->mci_out, SM_TIME_DEFAULT);
4969 if (sm_io_error(mci->mci_out) && errno != EPIPE)
4971 syserr("putbody: write error");
4972 ExitStat = EX_IOERR;
4978 ** MAILFILE -- Send a message to a file.
4980 ** If the file has the set-user-ID/set-group-ID bits set, but NO
4981 ** execute bits, sendmail will try to become the owner of that file
4982 ** rather than the real user. Obviously, this only works if
4983 ** sendmail runs as root.
4985 ** This could be done as a subordinate mailer, except that it
4986 ** is used implicitly to save messages in ~/dead.letter. We
4987 ** view this as being sufficiently important as to include it
4988 ** here. For example, if the system is dying, we shouldn't have
4989 ** to create another process plus some pipes to save the message.
4992 ** filename -- the name of the file to send to.
4993 ** mailer -- mailer definition for recipient -- if NULL,
4995 ** ctladdr -- the controlling address header -- includes
4996 ** the userid/groupid to be when sending.
4997 ** sfflags -- flags for opening.
4998 ** e -- the current envelope.
5001 ** The exit code associated with the operation.
5007 # define RETURN(st) exit(st);
5009 static jmp_buf CtxMailfileTimeout;
5012 mailfile(filename, mailer, ctladdr, sfflags, e)
5013 char *volatile filename;
5014 MAILER *volatile mailer;
5016 volatile long sfflags;
5017 register ENVELOPE *e;
5019 register SM_FILE_T *f;
5020 register pid_t pid = -1;
5024 bool suidwarn = geteuid() == 0;
5026 char *volatile realfile;
5028 char buf[MAXPATHLEN];
5029 char targetfile[MAXPATHLEN];
5033 sm_dprintf("mailfile %s\n ctladdr=", filename);
5034 printaddr(ctladdr, false);
5038 mailer = FileMailer;
5040 if (e->e_xfp != NULL)
5041 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
5044 ** Special case /dev/null. This allows us to restrict file
5045 ** delivery to regular files only.
5048 if (sm_path_isdevnull(filename))
5051 /* check for 8-bit available */
5052 if (bitset(EF_HAS8BIT, e->e_flags) &&
5053 bitnset(M_7BITS, mailer->m_flags) &&
5054 (bitset(EF_DONT_MIME, e->e_flags) ||
5055 !(bitset(MM_MIME8BIT, MimeMode) ||
5056 (bitset(EF_IS_MIME, e->e_flags) &&
5057 bitset(MM_CVTMIME, MimeMode)))))
5059 e->e_status = "5.6.3";
5060 usrerrenh(e->e_status,
5061 "554 Cannot send 8-bit data to 7-bit destination");
5066 /* Find the actual file */
5067 if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0')
5069 len = strlen(SafeFileEnv);
5071 if (strncmp(SafeFileEnv, filename, len) == 0)
5074 if (len + strlen(filename) + 1 >= sizeof targetfile)
5076 syserr("mailfile: filename too long (%s/%s)",
5077 SafeFileEnv, filename);
5078 return EX_CANTCREAT;
5080 (void) sm_strlcpy(targetfile, SafeFileEnv, sizeof targetfile);
5081 realfile = targetfile + len;
5082 if (*filename == '/')
5084 if (*filename != '\0')
5086 /* paranoia: trailing / should be removed in readcf */
5087 if (targetfile[len - 1] != '/')
5088 (void) sm_strlcat(targetfile,
5089 "/", sizeof targetfile);
5090 (void) sm_strlcat(targetfile, filename,
5094 else if (mailer->m_rootdir != NULL)
5096 expand(mailer->m_rootdir, targetfile, sizeof targetfile, e);
5097 len = strlen(targetfile);
5099 if (strncmp(targetfile, filename, len) == 0)
5102 if (len + strlen(filename) + 1 >= sizeof targetfile)
5104 syserr("mailfile: filename too long (%s/%s)",
5105 targetfile, filename);
5106 return EX_CANTCREAT;
5108 realfile = targetfile + len;
5109 if (targetfile[len - 1] != '/')
5110 (void) sm_strlcat(targetfile, "/", sizeof targetfile);
5111 if (*filename == '/')
5112 (void) sm_strlcat(targetfile, filename + 1,
5115 (void) sm_strlcat(targetfile, filename,
5120 if (sm_strlcpy(targetfile, filename, sizeof targetfile) >=
5123 syserr("mailfile: filename too long (%s)", filename);
5124 return EX_CANTCREAT;
5126 realfile = targetfile;
5130 ** Fork so we can change permissions here.
5131 ** Note that we MUST use fork, not vfork, because of
5132 ** the complications of calling subroutines, etc.
5137 ** Dispose of SIGCHLD signal catchers that may be laying
5138 ** around so that the waitfor() below will get it.
5141 (void) sm_signal(SIGCHLD, SIG_DFL);
5149 /* child -- actually write to file */
5153 volatile int oflags = O_WRONLY|O_APPEND;
5155 /* Reset global flags */
5156 RestartRequest = NULL;
5157 RestartWorkGroup = false;
5158 ShutdownRequest = NULL;
5160 CurrentPid = getpid();
5162 if (e->e_lockfp != NULL)
5163 (void) close(sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD,
5166 (void) sm_signal(SIGINT, SIG_DFL);
5167 (void) sm_signal(SIGHUP, SIG_DFL);
5168 (void) sm_signal(SIGTERM, SIG_DFL);
5169 (void) umask(OldUmask);
5173 if (setjmp(CtxMailfileTimeout) != 0)
5175 RETURN(EX_TEMPFAIL);
5178 if (TimeOuts.to_fileopen > 0)
5179 ev = sm_setevent(TimeOuts.to_fileopen, mailfiletimeout,
5184 /* check file mode to see if set-user-ID */
5185 if (stat(targetfile, &stb) < 0)
5190 /* limit the errors to those actually caused in the child */
5194 /* Allow alias expansions to use the S_IS{U,G}ID bits */
5195 if ((ctladdr != NULL && !bitset(QALIAS, ctladdr->q_flags)) ||
5196 bitset(SFF_RUNASREALUID, sfflags))
5198 /* ignore set-user-ID and set-group-ID bits */
5199 mode &= ~(S_ISGID|S_ISUID);
5201 sm_dprintf("mailfile: ignoring set-user-ID/set-group-ID bits\n");
5204 /* we have to open the data file BEFORE setuid() */
5205 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
5207 char *df = queuename(e, DATAFL_LETTER);
5209 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df,
5210 SM_IO_RDONLY_B, NULL);
5211 if (e->e_dfp == NULL)
5213 syserr("mailfile: Cannot open %s for %s from %s",
5214 df, e->e_to, e->e_from.q_paddr);
5218 /* select a new user to run as */
5219 if (!bitset(SFF_RUNASREALUID, sfflags))
5221 if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
5223 RealUserName = NULL;
5224 RealUid = mailer->m_uid;
5225 if (RunAsUid != 0 && RealUid != RunAsUid)
5227 /* Only root can change the uid */
5228 syserr("mailfile: insufficient privileges to change uid, RunAsUid=%d, RealUid=%d",
5229 (int) RunAsUid, (int) RealUid);
5230 RETURN(EX_TEMPFAIL);
5233 else if (bitset(S_ISUID, mode))
5235 RealUserName = NULL;
5236 RealUid = stb.st_uid;
5238 else if (ctladdr != NULL && ctladdr->q_uid != 0)
5240 if (ctladdr->q_ruser != NULL)
5241 RealUserName = ctladdr->q_ruser;
5243 RealUserName = ctladdr->q_user;
5244 RealUid = ctladdr->q_uid;
5246 else if (mailer != NULL && mailer->m_uid != 0)
5248 RealUserName = DefUser;
5249 RealUid = mailer->m_uid;
5253 RealUserName = DefUser;
5257 /* select a new group to run as */
5258 if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
5260 RealGid = mailer->m_gid;
5261 if (RunAsUid != 0 &&
5262 (RealGid != getgid() ||
5263 RealGid != getegid()))
5265 /* Only root can change the gid */
5266 syserr("mailfile: insufficient privileges to change gid, RealGid=%d, RunAsUid=%d, gid=%d, egid=%d",
5267 (int) RealGid, (int) RunAsUid,
5268 (int) getgid(), (int) getegid());
5269 RETURN(EX_TEMPFAIL);
5272 else if (bitset(S_ISGID, mode))
5273 RealGid = stb.st_gid;
5274 else if (ctladdr != NULL &&
5275 ctladdr->q_uid == DefUid &&
5276 ctladdr->q_gid == 0)
5279 ** Special case: This means it is an
5280 ** alias and we should act as DefaultUser.
5281 ** See alias()'s comments.
5285 RealUserName = DefUser;
5287 else if (ctladdr != NULL && ctladdr->q_uid != 0)
5288 RealGid = ctladdr->q_gid;
5289 else if (mailer != NULL && mailer->m_gid != 0)
5290 RealGid = mailer->m_gid;
5296 if (!bitset(SFF_ROOTOK, sfflags))
5304 /* set group id list (needs /etc/group access) */
5305 if (RealUserName != NULL && !DontInitGroups)
5307 if (initgroups(RealUserName, RealGid) == -1 && suidwarn)
5309 syserr("mailfile: initgroups(%s, %d) failed",
5310 RealUserName, RealGid);
5311 RETURN(EX_TEMPFAIL);
5318 gidset[0] = RealGid;
5319 if (setgroups(1, gidset) == -1 && suidwarn)
5321 syserr("mailfile: setgroups() failed");
5322 RETURN(EX_TEMPFAIL);
5327 ** If you have a safe environment, go into it.
5330 if (realfile != targetfile)
5337 sm_dprintf("mailfile: chroot %s\n", targetfile);
5338 if (chroot(targetfile) < 0)
5340 syserr("mailfile: Cannot chroot(%s)",
5342 RETURN(EX_CANTCREAT);
5348 sm_dprintf("mailfile: deliver to %s\n", realfile);
5352 syserr("mailfile: cannot chdir(/)");
5353 RETURN(EX_CANTCREAT);
5356 /* now reset the group and user ids */
5358 sm_mbdb_terminate();
5359 if (setgid(RealGid) < 0 && suidwarn)
5361 syserr("mailfile: setgid(%ld) failed", (long) RealGid);
5362 RETURN(EX_TEMPFAIL);
5364 vendor_set_uid(RealUid);
5365 if (setuid(RealUid) < 0 && suidwarn)
5367 syserr("mailfile: setuid(%ld) failed", (long) RealUid);
5368 RETURN(EX_TEMPFAIL);
5372 sm_dprintf("mailfile: running as r/euid=%d/%d, r/egid=%d/%d\n",
5373 (int) getuid(), (int) geteuid(),
5374 (int) getgid(), (int) getegid());
5377 /* move into some "safe" directory */
5378 if (mailer->m_execdir != NULL)
5382 for (p = mailer->m_execdir; p != NULL; p = q)
5387 expand(p, buf, sizeof buf, e);
5391 sm_dprintf("mailfile: trydir %s\n",
5393 if (buf[0] != '\0' && chdir(buf) >= 0)
5399 ** Recheck the file after we have assumed the ID of the
5400 ** delivery user to make sure we can deliver to it as
5401 ** that user. This is necessary if sendmail is running
5402 ** as root and the file is on an NFS mount which treats
5407 if (bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
5408 err = stat(realfile, &stb);
5410 err = lstat(realfile, &stb);
5411 #else /* HASLSTAT */
5412 err = stat(realfile, &stb);
5413 #endif /* HASLSTAT */
5417 stb.st_mode = ST_MODE_NOFILE;
5419 oflags |= O_CREAT|O_EXCL;
5421 else if (bitset(S_IXUSR|S_IXGRP|S_IXOTH, mode) ||
5422 (!bitnset(DBS_FILEDELIVERYTOHARDLINK,
5423 DontBlameSendmail) &&
5424 stb.st_nlink != 1) ||
5425 (realfile != targetfile && !S_ISREG(mode)))
5430 if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
5431 sfflags |= SFF_NOSLINK;
5432 if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
5433 sfflags |= SFF_NOHLINK;
5434 sfflags &= ~SFF_OPENASROOT;
5435 f = safefopen(realfile, oflags, mode, sfflags);
5438 if (transienterror(errno))
5440 usrerr("454 4.3.0 cannot open %s: %s",
5441 shortenstring(realfile, MAXSHORTSTR),
5442 sm_errstring(errno));
5443 RETURN(EX_TEMPFAIL);
5447 usrerr("554 5.3.0 cannot open %s: %s",
5448 shortenstring(realfile, MAXSHORTSTR),
5449 sm_errstring(errno));
5450 RETURN(EX_CANTCREAT);
5453 if (filechanged(realfile, sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5456 syserr("554 5.3.0 file changed after open");
5457 RETURN(EX_CANTCREAT);
5459 if (fstat(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), &stb) < 0)
5461 syserr("554 5.3.0 cannot fstat %s",
5462 sm_errstring(errno));
5463 RETURN(EX_CANTCREAT);
5466 curoff = stb.st_size;
5471 memset(&mcibuf, '\0', sizeof mcibuf);
5472 mcibuf.mci_mailer = mailer;
5474 if (bitnset(M_7BITS, mailer->m_flags))
5475 mcibuf.mci_flags |= MCIF_7BIT;
5477 /* clear out per-message flags from connection structure */
5478 mcibuf.mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
5480 if (bitset(EF_HAS8BIT, e->e_flags) &&
5481 !bitset(EF_DONT_MIME, e->e_flags) &&
5482 bitnset(M_7BITS, mailer->m_flags))
5483 mcibuf.mci_flags |= MCIF_CVT8TO7;
5486 if (bitnset(M_MAKE8BIT, mailer->m_flags) &&
5487 !bitset(MCIF_7BIT, mcibuf.mci_flags) &&
5488 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
5489 (sm_strcasecmp(p, "quoted-printable") == 0 ||
5490 sm_strcasecmp(p, "base64") == 0) &&
5491 (p = hvalue("Content-Type", e->e_header)) != NULL)
5493 /* may want to convert 7 -> 8 */
5494 /* XXX should really parse it here -- and use a class XXX */
5495 if (sm_strncasecmp(p, "text/plain", 10) == 0 &&
5496 (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
5497 mcibuf.mci_flags |= MCIF_CVT7TO8;
5499 #endif /* MIME7TO8 */
5501 putfromline(&mcibuf, e);
5502 (*e->e_puthdr)(&mcibuf, e->e_header, e, M87F_OUTER);
5503 (*e->e_putbody)(&mcibuf, e, NULL);
5504 putline("\n", &mcibuf);
5505 if (sm_io_flush(f, SM_TIME_DEFAULT) != 0 ||
5506 (SuperSafe != SAFE_NO &&
5507 fsync(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL)) < 0) ||
5512 (void) ftruncate(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5514 #endif /* !NOFTRUNCATE */
5517 /* reset ISUID & ISGID bits for paranoid systems */
5519 (void) fchmod(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5521 #else /* HASFCHMOD */
5522 (void) chmod(filename, (MODE_T) mode);
5523 #endif /* HASFCHMOD */
5524 if (sm_io_close(f, SM_TIME_DEFAULT) < 0)
5526 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
5527 (void) setuid(RealUid);
5533 /* parent -- wait for exit status */
5539 syserr("mailfile: %s: wait", mailer->m_name);
5545 return (WEXITSTATUS(st));
5549 syserr("mailfile: %s: child died on signal %d",
5550 mailer->m_name, st);
5551 return EX_UNAVAILABLE;
5555 return EX_UNAVAILABLE; /* avoid compiler warning on IRIX */
5562 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
5563 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
5568 longjmp(CtxMailfileTimeout, 1);
5571 ** HOSTSIGNATURE -- return the "signature" for a host.
5573 ** The signature describes how we are going to send this -- it
5574 ** can be just the hostname (for non-Internet hosts) or can be
5575 ** an ordered list of MX hosts.
5578 ** m -- the mailer describing this host.
5579 ** host -- the host name.
5582 ** The signature for this host.
5585 ** Can tweak the symbol table.
5588 #define MAXHOSTSIGNATURE 8192 /* max len of hostsignature */
5591 hostsignature(m, host)
5607 int oldoptions = _res.options;
5608 char *mxhosts[MAXMXHOSTS + 1];
5609 unsigned short mxprefs[MAXMXHOSTS + 1];
5610 #endif /* NAMED_BIND */
5613 sm_dprintf("hostsignature(%s)\n", host);
5616 ** If local delivery (and not remote), just return a constant.
5619 if (bitnset(M_LOCALMAILER, m->m_flags) &&
5620 strcmp(m->m_mailer, "[IPC]") != 0 &&
5621 !(m->m_argv[0] != NULL && strcmp(m->m_argv[0], "TCP") == 0))
5625 ** Check to see if this uses IPC -- if not, it can't have MX records.
5628 if (strcmp(m->m_mailer, "[IPC]") != 0 ||
5629 CurEnv->e_sendmode == SM_DEFER)
5631 /* just an ordinary mailer or deferred mode */
5635 else if (m->m_argv[0] != NULL &&
5636 strcmp(m->m_argv[0], "FILE") == 0)
5638 /* rendezvous in the file system, no MX records */
5641 #endif /* NETUNIX */
5644 ** Look it up in the symbol table.
5648 s = stab(host, ST_HOSTSIG, ST_ENTER);
5649 if (s->s_hostsig.hs_sig != NULL)
5651 if (s->s_hostsig.hs_exp >= now)
5654 sm_dprintf("hostsignature(): stab(%s) found %s\n", host,
5655 s->s_hostsig.hs_sig);
5656 return s->s_hostsig.hs_sig;
5659 /* signature is expired: clear it */
5660 sm_free(s->s_hostsig.hs_sig);
5661 s->s_hostsig.hs_sig = NULL;
5664 /* set default TTL */
5665 s->s_hostsig.hs_exp = now + SM_DEFAULT_TTL;
5668 ** Not already there or expired -- create a signature.
5672 if (ConfigLevel < 2)
5673 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */
5675 for (hp = host; hp != NULL; hp = endp)
5680 endp = strchr(hp + 1, ']');
5682 endp = strpbrk(endp + 1, ":,");
5685 endp = strpbrk(hp, ":,");
5686 #else /* NETINET6 */
5687 endp = strpbrk(hp, ":,");
5688 #endif /* NETINET6 */
5695 if (bitnset(M_NOMX, m->m_flags))
5697 /* skip MX lookups */
5706 nmx = getmxrr(hp, mxhosts, mxprefs, true, &rcode, true,
5713 /* update the connection info for this host */
5715 mci = mci_get(hp, m);
5716 mci->mci_errno = save_errno;
5717 mci->mci_herrno = h_errno;
5718 mci->mci_lastuse = now;
5719 if (rcode == EX_NOHOST)
5720 mci_setstat(mci, rcode, "5.1.2",
5721 "550 Host unknown");
5723 mci_setstat(mci, rcode, NULL, NULL);
5725 /* use the original host name as signature */
5730 sm_dprintf("hostsignature(): getmxrr() returned %d, mxhosts[0]=%s\n",
5734 ** Set new TTL: we use only one!
5735 ** We could try to use the minimum instead.
5738 s->s_hostsig.hs_exp = now + SM_MIN(ttl, SM_DEFAULT_TTL);
5742 for (i = 0; i < nmx; i++)
5743 len += strlen(mxhosts[i]) + 1;
5744 if (s->s_hostsig.hs_sig != NULL)
5745 len += strlen(s->s_hostsig.hs_sig) + 1;
5746 if (len < 0 || len >= MAXHOSTSIGNATURE)
5748 sm_syslog(LOG_WARNING, NOQID, "hostsignature for host '%s' exceeds maxlen (%d): %d",
5749 host, MAXHOSTSIGNATURE, len);
5750 len = MAXHOSTSIGNATURE;
5752 p = sm_pmalloc_x(len);
5753 if (s->s_hostsig.hs_sig != NULL)
5755 (void) sm_strlcpy(p, s->s_hostsig.hs_sig, len);
5756 sm_free(s->s_hostsig.hs_sig); /* XXX */
5757 s->s_hostsig.hs_sig = p;
5764 s->s_hostsig.hs_sig = p;
5765 for (i = 0; i < nmx; i++)
5767 hl = strlen(mxhosts[i]);
5768 if (len - 1 < hl || len <= 1)
5770 /* force to drop out of outer loop */
5776 if (mxprefs[i] == mxprefs[i - 1])
5782 (void) sm_strlcpy(p, mxhosts[i], len);
5788 ** break out of loop if len exceeded MAXHOSTSIGNATURE
5789 ** because we won't have more space for further hosts
5790 ** anyway (separated by : in the .cf file).
5799 makelower(s->s_hostsig.hs_sig);
5800 if (ConfigLevel < 2)
5801 _res.options = oldoptions;
5802 #else /* NAMED_BIND */
5803 /* not using BIND -- the signature is just the host name */
5805 ** 'host' points to storage that will be freed after we are
5806 ** done processing the current envelope, so we copy it.
5808 s->s_hostsig.hs_sig = sm_pstrdup_x(host);
5809 #endif /* NAMED_BIND */
5811 sm_dprintf("hostsignature(%s) = %s\n", host, s->s_hostsig.hs_sig);
5812 return s->s_hostsig.hs_sig;
5815 ** PARSE_HOSTSIGNATURE -- parse the "signature" and return MX host array.
5817 ** The signature describes how we are going to send this -- it
5818 ** can be just the hostname (for non-Internet hosts) or can be
5819 ** an ordered list of MX hosts which must be randomized for equal
5820 ** MX preference values.
5823 ** sig -- the host signature.
5824 ** mxhosts -- array to populate.
5825 ** mailer -- mailer.
5828 ** The number of hosts inserted into mxhosts array.
5831 ** Randomizes equal MX preference hosts in mxhosts.
5835 parse_hostsignature(sig, mxhosts, mailer)
5840 unsigned short curpref = 0;
5841 int nmx = 0, i, j; /* NOTE: i, j, and nmx must have same type */
5843 unsigned short prefer[MAXMXHOSTS];
5844 long rndm[MAXMXHOSTS];
5846 for (hp = sig; hp != NULL; hp = endp)
5853 endp = strchr(hp + 1, ']');
5855 endp = strpbrk(endp + 1, ":,");
5858 endp = strpbrk(hp, ":,");
5859 #else /* NETINET6 */
5860 endp = strpbrk(hp, ":,");
5861 #endif /* NETINET6 */
5869 prefer[nmx] = curpref;
5870 if (mci_match(hp, mailer))
5873 rndm[nmx] = get_random();
5878 ** Since we don't have the original MX prefs,
5879 ** make our own. If the separator is a ':', that
5880 ** means the preference for the next host will be
5881 ** higher than this one, so simply increment curpref.
5889 if (++nmx >= MAXMXHOSTS)
5893 /* sort the records using the random factor for equal preferences */
5894 for (i = 0; i < nmx; i++)
5896 for (j = i + 1; j < nmx; j++)
5899 ** List is already sorted by MX preference, only
5900 ** need to look for equal preference MX records
5903 if (prefer[i] < prefer[j])
5906 if (prefer[i] > prefer[j] ||
5907 (prefer[i] == prefer[j] && rndm[i] > rndm[j]))
5909 register unsigned short tempp;
5910 register long tempr;
5911 register char *temp1;
5914 prefer[i] = prefer[j];
5917 mxhosts[i] = mxhosts[j];
5929 static SSL_CTX *clt_ctx = NULL;
5930 static bool tls_ok_clt = true;
5933 ** SETCLTTLS -- client side TLS: allow/disallow.
5936 ** tls_ok -- should tls be done?
5942 ** sets tls_ok_clt (static variable in this module)
5949 tls_ok_clt = tls_ok;
5953 ** INITCLTTLS -- initialize client side TLS
5956 ** tls_ok -- should tls initialization be done?
5962 ** sets tls_ok_clt (static variable in this module)
5971 tls_ok_clt = tls_ok;
5974 if (clt_ctx != NULL)
5975 return true; /* already done */
5976 tls_ok_clt = inittls(&clt_ctx, TLS_I_CLT, false, CltCertFile,
5977 CltKeyFile, CACertPath, CACertFile, DHParams);
5982 ** STARTTLS -- try to start secure connection (client side)
5986 ** mci -- the mailer connection info.
5987 ** e -- the envelope.
5991 ** (maybe this should be some other code than EX_
5992 ** that denotes which stage failed.)
6004 SSL *clt_ssl = NULL;
6007 if (clt_ctx == NULL && !initclttls(true))
6009 smtpmessage("STARTTLS", m, mci);
6012 smtpresult = reply(m, mci, e, TimeOuts.to_starttls, NULL, NULL);
6014 /* check return code from server */
6015 if (smtpresult == 454)
6017 if (smtpresult == 501)
6019 if (smtpresult == -1)
6021 if (smtpresult != 220)
6025 sm_syslog(LOG_INFO, NOQID, "STARTTLS=client, start=ok");
6027 /* start connection */
6028 if ((clt_ssl = SSL_new(clt_ctx)) == NULL)
6032 sm_syslog(LOG_ERR, NOQID,
6033 "STARTTLS=client, error: SSL_new failed");
6035 tlslogerr("client");
6040 rfd = sm_io_getinfo(mci->mci_in, SM_IO_WHAT_FD, NULL);
6041 wfd = sm_io_getinfo(mci->mci_out, SM_IO_WHAT_FD, NULL);
6043 /* SSL_clear(clt_ssl); ? */
6044 if (rfd < 0 || wfd < 0 ||
6045 (result = SSL_set_rfd(clt_ssl, rfd)) != 1 ||
6046 (result = SSL_set_wfd(clt_ssl, wfd)) != 1)
6050 sm_syslog(LOG_ERR, NOQID,
6051 "STARTTLS=client, error: SSL_set_xfd failed=%d",
6054 tlslogerr("client");
6058 SSL_set_connect_state(clt_ssl);
6059 tlsstart = curtime();
6062 if ((result = SSL_connect(clt_ssl)) <= 0)
6067 time_t now = curtime();
6070 /* what to do in this case? */
6071 i = SSL_get_error(clt_ssl, result);
6074 ** For SSL_ERROR_WANT_{READ,WRITE}:
6075 ** There is not a complete SSL record available yet
6076 ** or there is only a partial SSL record removed from
6077 ** the network (socket) buffer into the SSL buffer.
6078 ** The SSL_connect will only succeed when a full
6079 ** SSL record is available (assuming a "real" error
6080 ** doesn't happen). To handle when a "real" error
6081 ** does happen the select is set for exceptions too.
6082 ** The connection may be re-negotiated during this time
6083 ** so both read and write "want errors" need to be handled.
6084 ** A select() exception loops back so that a proper SSL
6085 ** error message can be gotten.
6088 left = TimeOuts.to_starttls - (now - tlsstart);
6089 timedout = left <= 0;
6096 if (!timedout && FD_SETSIZE > 0 &&
6097 (rfd >= FD_SETSIZE ||
6098 (i == SSL_ERROR_WANT_WRITE && wfd >= FD_SETSIZE)))
6102 sm_syslog(LOG_ERR, e->e_id,
6103 "STARTTLS=client, error: fd %d/%d too large",
6106 tlslogerr("client");
6111 if (!timedout && i == SSL_ERROR_WANT_READ)
6113 fd_set ssl_maskr, ssl_maskx;
6115 FD_ZERO(&ssl_maskr);
6116 FD_SET(rfd, &ssl_maskr);
6117 FD_ZERO(&ssl_maskx);
6118 FD_SET(rfd, &ssl_maskx);
6119 if (select(rfd + 1, &ssl_maskr, NULL, &ssl_maskx, &tv)
6123 if (!timedout && i == SSL_ERROR_WANT_WRITE)
6125 fd_set ssl_maskw, ssl_maskx;
6127 FD_ZERO(&ssl_maskw);
6128 FD_SET(wfd, &ssl_maskw);
6129 FD_ZERO(&ssl_maskx);
6130 FD_SET(rfd, &ssl_maskx);
6131 if (select(wfd + 1, NULL, &ssl_maskw, &ssl_maskx, &tv)
6137 sm_syslog(LOG_ERR, e->e_id,
6138 "STARTTLS=client, error: connect failed=%d, SSL_error=%d, timedout=%d, errno=%d",
6139 result, i, (int) timedout, errno);
6141 tlslogerr("client");
6148 mci->mci_ssl = clt_ssl;
6149 result = tls_get_info(mci->mci_ssl, false, mci->mci_host,
6150 &mci->mci_macro, true);
6152 /* switch to use TLS... */
6153 if (sfdctls(&mci->mci_in, &mci->mci_out, mci->mci_ssl) == 0)
6162 ** ENDTLSCLT -- shutdown secure connection (client side)
6165 ** mci -- the mailer connection info.
6177 if (!bitset(MCIF_TLSACT, mci->mci_flags))
6179 r = endtls(mci->mci_ssl, "client");
6180 mci->mci_flags &= ~MCIF_TLSACT;
6183 # endif /* STARTTLS */
6184 # if STARTTLS || SASL
6186 ** ISCLTFLGSET -- check whether client flag is set.
6190 ** flag -- flag to check in {client_flags}
6193 ** true iff flag is set.
6197 iscltflgset(e, flag)
6203 p = macvalue(macid("{client_flags}"), e);
6206 for (; *p != '\0'; p++)
6208 /* look for just this one flag */
6209 if (*p == (char) flag)
6214 # endif /* STARTTLS || SASL */