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