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