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