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