1 /*
2 * Copyright (c) 1998-2003, 2006 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
16 SM_RCSID("@(#)$Id: recipient.c,v 8.351 2013-11-22 20:51:56 ca Exp $")
17
18 #include <sm/sendmail.h>
19 #if _FFR_8BITENVADDR
20 # include <sm/ixlen.h>
21 #endif
22
23 static void includetimeout __P((int));
24 static ADDRESS *self_reference __P((ADDRESS *));
25 static int sortexpensive __P((ADDRESS *, ADDRESS *));
26 static int sortbysignature __P((ADDRESS *, ADDRESS *));
27 static int sorthost __P((ADDRESS *, ADDRESS *));
28
29 typedef int sortfn_t __P((ADDRESS *, ADDRESS *));
30
31 /*
32 ** SORTHOST -- strcmp()-like func for host portion of an ADDRESS
33 **
34 ** Parameters:
35 ** xx -- first ADDRESS
36 ** yy -- second ADDRESS
37 **
38 ** Returns:
39 ** <0 when xx->q_host is less than yy->q_host
40 ** >0 when xx->q_host is greater than yy->q_host
41 ** 0 when equal
42 */
43
44 static int
sorthost(xx,yy)45 sorthost(xx, yy)
46 register ADDRESS *xx;
47 register ADDRESS *yy;
48 {
49 #if _FFR_HOST_SORT_REVERSE
50 /* XXX maybe compare hostnames from the end? */
51 return sm_strrevcasecmp(xx->q_host, yy->q_host);
52 #else
53 return sm_strcasecmp(xx->q_host, yy->q_host);
54 #endif
55 }
56
57 /*
58 ** SORTEXPENSIVE -- strcmp()-like func for expensive mailers
59 **
60 ** The mailer has been noted already as "expensive" for 'xx'. This
61 ** will give a result relative to 'yy'. Expensive mailers get rated
62 ** "greater than" non-expensive mailers because during the delivery phase
63 ** it will get queued -- no use it getting in the way of less expensive
64 ** recipients. We avoid an MX RR lookup when both 'xx' and 'yy' are
65 ** expensive since an MX RR lookup happens when extracted from the queue
66 ** later.
67 **
68 ** Parameters:
69 ** xx -- first ADDRESS
70 ** yy -- second ADDRESS
71 **
72 ** Returns:
73 ** <0 when xx->q_host is less than yy->q_host and both are
74 ** expensive
75 ** >0 when xx->q_host is greater than yy->q_host, or when
76 ** 'yy' is non-expensive
77 ** 0 when equal (by expense and q_host)
78 */
79
80 static int
sortexpensive(xx,yy)81 sortexpensive(xx, yy)
82 ADDRESS *xx;
83 ADDRESS *yy;
84 {
85 if (!bitnset(M_EXPENSIVE, yy->q_mailer->m_flags))
86 return 1; /* xx should go later */
87 #if _FFR_HOST_SORT_REVERSE
88 /* XXX maybe compare hostnames from the end? */
89 return sm_strrevcasecmp(xx->q_host, yy->q_host);
90 #else
91 return sm_strcasecmp(xx->q_host, yy->q_host);
92 #endif
93 }
94
95 /*
96 ** SORTBYSIGNATURE -- a strcmp()-like func for q_mailer and q_host in ADDRESS
97 **
98 ** Parameters:
99 ** xx -- first ADDRESS
100 ** yy -- second ADDRESS
101 **
102 ** Returns:
103 ** 0 when the "signature"'s are same
104 ** <0 when xx->q_signature is less than yy->q_signature
105 ** >0 when xx->q_signature is greater than yy->q_signature
106 **
107 ** Side Effect:
108 ** May set ADDRESS pointer for q_signature if not already set.
109 */
110
111 static int
sortbysignature(xx,yy)112 sortbysignature(xx, yy)
113 ADDRESS *xx;
114 ADDRESS *yy;
115 {
116 register int ret;
117
118 /* Let's avoid redoing the signature over and over again */
119 if (xx->q_signature == NULL)
120 xx->q_signature = hostsignature(xx->q_mailer, xx->q_host, xx->q_flags & QSECURE);
121 if (yy->q_signature == NULL)
122 yy->q_signature = hostsignature(yy->q_mailer, yy->q_host, yy->q_flags & QSECURE);
123 ret = strcmp(xx->q_signature, yy->q_signature);
124
125 /*
126 ** If the two signatures are the same then we will return a sort
127 ** value based on 'q_user'. But note that we have reversed xx and yy
128 ** on purpose. This additional compare helps reduce the number of
129 ** sameaddr() calls and loops in recipient() for the case when
130 ** the rcpt list has been provided already in-order.
131 */
132
133 if (ret == 0)
134 return strcmp(yy->q_user, xx->q_user);
135 else
136 return ret;
137 }
138
139 /*
140 ** SENDTOLIST -- Designate a send list.
141 **
142 ** The parameter is a comma-separated list of people to send to.
143 ** This routine arranges to send to all of them.
144 **
145 ** Parameters:
146 ** list -- the send list.
147 ** ctladdr -- the address template for the person to
148 ** send to -- effective uid/gid are important.
149 ** This is typically the alias that caused this
150 ** expansion.
151 ** sendq -- a pointer to the head of a queue to put
152 ** these people into.
153 ** aliaslevel -- the current alias nesting depth -- to
154 ** diagnose loops.
155 ** e -- the envelope in which to add these recipients.
156 **
157 ** Returns:
158 ** The number of addresses actually on the list.
159 */
160
161 /* q_flags bits inherited from ctladdr */
162 #define QINHERITEDBITS (QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY|QHASNOTIFY)
163
164 int
sendtolist(list,ctladdr,sendq,aliaslevel,e)165 sendtolist(list, ctladdr, sendq, aliaslevel, e)
166 char *list;
167 ADDRESS *ctladdr;
168 ADDRESS **sendq;
169 int aliaslevel;
170 register ENVELOPE *e;
171 {
172 register char *p;
173 register ADDRESS *SM_NONVOLATILE al; /* list of addresses to send to */
174 SM_NONVOLATILE char delimiter; /* the address delimiter */
175 SM_NONVOLATILE int naddrs;
176 SM_NONVOLATILE int i;
177 char *endp;
178 char *oldto = e->e_to;
179 char *SM_NONVOLATILE bufp;
180 char buf[MAXNAME + 1]; /* EAI: ok, uses bufp dynamically expanded */
181
182 if (list == NULL)
183 {
184 syserr("sendtolist: null list");
185 return 0;
186 }
187
188 if (tTd(25, 1))
189 {
190 sm_dprintf("sendto: %s\n ctladdr=", list);
191 printaddr(sm_debug_file(), ctladdr, false);
192 }
193
194 /* heuristic to determine old versus new style addresses */
195 if (ctladdr == NULL &&
196 (strchr(list, ',') != NULL || strchr(list, ';') != NULL ||
197 strchr(list, '<') != NULL || strchr(list, '(') != NULL))
198 e->e_flags &= ~EF_OLDSTYLE;
199 delimiter = ' ';
200 if (!bitset(EF_OLDSTYLE, e->e_flags) || ctladdr != NULL)
201 delimiter = ',';
202
203 al = NULL;
204 naddrs = 0;
205
206 /* make sure we have enough space to copy the string */
207 i = strlen(list) + 1;
208 if (i <= sizeof(buf))
209 {
210 bufp = buf;
211 i = sizeof(buf);
212 }
213 else
214 bufp = sm_malloc_x(i);
215 endp = bufp + i;
216
217 SM_TRY
218 {
219 (void) sm_strlcpy(bufp, denlstring(list, false, true), i);
220
221 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r");
222 for (p = bufp; *p != '\0'; )
223 {
224 auto char *delimptr;
225 register ADDRESS *a;
226
227 SM_ASSERT(p < endp);
228
229 /* parse the address */
230 while ((SM_ISSPACE(*p)) || *p == ',')
231 p++;
232 SM_ASSERT(p < endp);
233 /* XXX p must be [i] */
234 a = parseaddr(p, NULLADDR, RF_COPYALL, delimiter,
235 &delimptr, e, true);
236 p = delimptr;
237 SM_ASSERT(p < endp);
238 if (a == NULL)
239 continue;
240 a->q_next = al;
241 a->q_alias = ctladdr;
242
243 /* arrange to inherit attributes from parent */
244 if (ctladdr != NULL)
245 {
246 ADDRESS *b;
247
248 /* self reference test */
249 if (sameaddr(ctladdr, a))
250 {
251 if (tTd(27, 5))
252 {
253 sm_dprintf("sendtolist: QSELFREF ");
254 printaddr(sm_debug_file(), ctladdr, false);
255 }
256 ctladdr->q_flags |= QSELFREF;
257 }
258
259 /* check for address loops */
260 b = self_reference(a);
261 if (b != NULL)
262 {
263 b->q_flags |= QSELFREF;
264 if (tTd(27, 5))
265 {
266 sm_dprintf("sendtolist: QSELFREF ");
267 printaddr(sm_debug_file(), b, false);
268 }
269 if (a != b)
270 {
271 if (tTd(27, 5))
272 {
273 sm_dprintf("sendtolist: QS_DONTSEND ");
274 printaddr(sm_debug_file(), a, false);
275 }
276 a->q_state = QS_DONTSEND;
277 b->q_flags |= a->q_flags & QNOTREMOTE;
278 continue;
279 }
280 }
281
282 /* full name */
283 if (a->q_fullname == NULL)
284 a->q_fullname = ctladdr->q_fullname;
285
286 /* various flag bits */
287 a->q_flags &= ~QINHERITEDBITS;
288 a->q_flags |= ctladdr->q_flags & QINHERITEDBITS;
289
290 /* DSN recipient information */
291 a->q_finalrcpt = ctladdr->q_finalrcpt;
292 a->q_orcpt = ctladdr->q_orcpt;
293 }
294
295 al = a;
296 }
297
298 /* arrange to send to everyone on the local send list */
299 while (al != NULL)
300 {
301 register ADDRESS *a = al;
302
303 al = a->q_next;
304 a = recipient(a, sendq, aliaslevel, e);
305 naddrs++;
306 }
307 }
308 SM_FINALLY
309 {
310 e->e_to = oldto;
311 if (bufp != buf)
312 sm_free(bufp);
313 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
314 }
315 SM_END_TRY
316 return naddrs;
317 }
318
319 #if MILTER
320 /*
321 ** REMOVEFROMLIST -- Remove addresses from a send list.
322 **
323 ** The parameter is a comma-separated list of recipients to remove.
324 ** Note that it only deletes matching addresses. If those addresses
325 ** have been expanded already in the sendq, it won't mark the
326 ** expanded recipients as QS_REMOVED.
327 **
328 ** Parameters:
329 ** list -- the list to remove.
330 ** sendq -- a pointer to the head of a queue to remove
331 ** these addresses from.
332 ** e -- the envelope in which to remove these recipients.
333 **
334 ** Returns:
335 ** The number of addresses removed from the list.
336 **
337 */
338
339 int
removefromlist(list,sendq,e)340 removefromlist(list, sendq, e)
341 char *list;
342 ADDRESS **sendq;
343 ENVELOPE *e;
344 {
345 SM_NONVOLATILE char delimiter; /* the address delimiter */
346 SM_NONVOLATILE int naddrs;
347 SM_NONVOLATILE int i;
348 char *p;
349 char *oldto = e->e_to;
350 char *SM_NONVOLATILE bufp;
351 char buf[MAXNAME + 1]; /* EAI: ok, uses bufp dynamically expanded */
352
353 if (list == NULL)
354 {
355 syserr("removefromlist: null list");
356 return 0;
357 }
358
359 if (tTd(25, 1))
360 sm_dprintf("removefromlist: %s\n", list);
361
362 /* heuristic to determine old versus new style addresses */
363 if (strchr(list, ',') != NULL || strchr(list, ';') != NULL ||
364 strchr(list, '<') != NULL || strchr(list, '(') != NULL)
365 e->e_flags &= ~EF_OLDSTYLE;
366 delimiter = ' ';
367 if (!bitset(EF_OLDSTYLE, e->e_flags))
368 delimiter = ',';
369
370 naddrs = 0;
371
372 /* make sure we have enough space to copy the string */
373 i = strlen(list) + 1;
374 if (i <= sizeof(buf))
375 {
376 bufp = buf;
377 i = sizeof(buf);
378 }
379 else
380 bufp = sm_malloc_x(i);
381
382 SM_TRY
383 {
384 (void) sm_strlcpy(bufp, denlstring(list, false, true), i);
385
386 # if _FFR_ADDR_TYPE_MODES
387 if (AddrTypeModes)
388 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"),
389 "e r d");
390 else
391 # endif /* _FFR_ADDR_TYPE_MODES */
392 /* "else" in #if code above */
393 {
394 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"),
395 "e r");
396 }
397 for (p = bufp; *p != '\0'; )
398 {
399 ADDRESS a; /* parsed address to be removed */
400 ADDRESS *q;
401 ADDRESS **pq;
402 char *delimptr;
403
404 /* parse the address */
405 while ((SM_ISSPACE(*p)) || *p == ',')
406 p++;
407 /* XXX p must be [i] */
408 if (parseaddr(p, &a, RF_COPYALL|RF_RM_ADDR,
409 delimiter, &delimptr, e, true) == NULL)
410 {
411 p = delimptr;
412 continue;
413 }
414 p = delimptr;
415 for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
416 {
417 if (!QS_IS_DEAD(q->q_state) &&
418 (sameaddr(q, &a) ||
419 strcmp(q->q_paddr, a.q_paddr) == 0))
420 {
421 if (tTd(25, 5))
422 {
423 sm_dprintf("removefromlist: QS_REMOVED ");
424 printaddr(sm_debug_file(), &a, false);
425 }
426 q->q_state = QS_REMOVED;
427 naddrs++;
428 break;
429 }
430 }
431 }
432 }
433 SM_FINALLY
434 {
435 e->e_to = oldto;
436 if (bufp != buf)
437 sm_free(bufp);
438 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
439 }
440 SM_END_TRY
441 return naddrs;
442 }
443 #endif /* MILTER */
444
445 /*
446 ** RECIPIENT -- Designate a message recipient
447 ** Saves the named person for future mailing (after some checks).
448 **
449 ** Parameters:
450 ** new -- the (preparsed) address header for the recipient.
451 ** sendq -- a pointer to the head of a queue to put the
452 ** recipient in. Duplicate suppression is done
453 ** in this queue.
454 ** aliaslevel -- the current alias nesting depth.
455 ** e -- the current envelope.
456 **
457 ** Returns:
458 ** The actual address in the queue. This will be "a" if
459 ** the address is not a duplicate, else the original address.
460 **
461 */
462
463 ADDRESS *
recipient(new,sendq,aliaslevel,e)464 recipient(new, sendq, aliaslevel, e)
465 register ADDRESS *new;
466 register ADDRESS **sendq;
467 int aliaslevel;
468 register ENVELOPE *e;
469 {
470 register ADDRESS *q;
471 ADDRESS **pq;
472 ADDRESS **prev;
473 register struct mailer *m;
474 register char *p;
475 int i, buflen;
476 bool quoted; /* set if the addr has a quote bit */
477 bool insert;
478 int findusercount;
479 bool initialdontsend;
480 char *buf;
481 char buf0[MAXNAME + 1]; /* EAI: ok, uses bufp dynamically expanded */
482 /* unquoted image of the user name */
483 sortfn_t *sortfn;
484
485 p = NULL;
486 quoted = false;
487 insert = false;
488 findusercount = 0;
489 initialdontsend = QS_IS_DEAD(new->q_state);
490 e->e_to = new->q_paddr;
491 m = new->q_mailer;
492 errno = 0;
493 if (aliaslevel == 0)
494 new->q_flags |= QPRIMARY;
495 if (tTd(26, 1))
496 {
497 sm_dprintf("\nrecipient (%d): ", aliaslevel);
498 printaddr(sm_debug_file(), new, false);
499 }
500
501 /* if this is primary, use it as original recipient */
502 if (new->q_alias == NULL)
503 {
504 if (e->e_origrcpt == NULL)
505 e->e_origrcpt = new->q_paddr;
506 else if (e->e_origrcpt != new->q_paddr)
507 e->e_origrcpt = "";
508 }
509
510 /* find parent recipient for finalrcpt and orcpt */
511 for (q = new; q->q_alias != NULL; q = q->q_alias)
512 continue;
513
514 /* find final recipient DSN address */
515 if (new->q_finalrcpt == NULL &&
516 e->e_from.q_mailer != NULL)
517 {
518 char frbuf[MAXLINE];
519
520 p = e->e_from.q_mailer->m_addrtype;
521 if (p == NULL)
522 p = "rfc822";
523 #if USE_EAI
524 if (SM_STRCASEEQ(p, "rfc822") &&
525 !addr_is_ascii(q->q_user))
526 p = "utf-8";
527 #endif
528 if (sm_strcasecmp(p, "rfc822") != 0)
529 {
530 (void) sm_snprintf(frbuf, sizeof(frbuf), "%s; %.800s",
531 q->q_mailer->m_addrtype,
532 q->q_user);
533 }
534 else if (strchr(q->q_user, '@') != NULL)
535 {
536 (void) sm_snprintf(frbuf, sizeof(frbuf), "%s; %.800s",
537 p, q->q_user);
538 }
539 else if (strchr(q->q_paddr, '@') != NULL)
540 {
541 char *qp;
542 bool b;
543
544 qp = q->q_paddr;
545
546 /* strip brackets from address */
547 b = false;
548 if (*qp == '<')
549 {
550 b = qp[strlen(qp) - 1] == '>';
551 if (b)
552 qp[strlen(qp) - 1] = '\0';
553 qp++;
554 }
555 (void) sm_snprintf(frbuf, sizeof(frbuf), "%s; %.800s",
556 p, qp);
557
558 /* undo damage */
559 if (b)
560 qp[strlen(qp)] = '>';
561 }
562 else
563 {
564 (void) sm_snprintf(frbuf, sizeof(frbuf),
565 "%s; %.700s@%.100s",
566 p, q->q_user, MyHostName);
567 }
568 new->q_finalrcpt = sm_rpool_strdup_x(e->e_rpool, frbuf);
569 }
570
571 #if _FFR_GEN_ORCPT
572 /* set ORCPT DSN arg if not already set */
573 if (new->q_orcpt == NULL)
574 {
575 /* check for an existing ORCPT */
576 if (q->q_orcpt != NULL)
577 new->q_orcpt = q->q_orcpt;
578 else
579 {
580 /* make our own */
581 bool b = false;
582 char *qp;
583 char obuf[MAXLINE];
584
585 if (e->e_from.q_mailer != NULL)
586 p = e->e_from.q_mailer->m_addrtype;
587 if (p == NULL)
588 p = "rfc822";
589 (void) sm_strlcpyn(obuf, sizeof(obuf), 2, p, ";");
590
591 qp = q->q_paddr;
592
593 /* FFR: Needs to strip comments from stdin addrs */
594
595 /* strip brackets from address */
596 if (*qp == '<')
597 {
598 b = qp[strlen(qp) - 1] == '>';
599 if (b)
600 qp[strlen(qp) - 1] = '\0';
601 qp++;
602 }
603
604 p = xtextify(denlstring(qp, true, false), "=");
605
606 if (sm_strlcat(obuf, p, sizeof(obuf)) >= sizeof(obuf))
607 {
608 /* if too big, don't use it */
609 obuf[0] = '\0';
610 }
611
612 /* undo damage */
613 if (b)
614 qp[strlen(qp)] = '>';
615
616 if (obuf[0] != '\0')
617 new->q_orcpt =
618 sm_rpool_strdup_x(e->e_rpool, obuf);
619 }
620 }
621 #endif /* _FFR_GEN_ORCPT */
622
623 /* break aliasing loops */
624 if (aliaslevel > MaxAliasRecursion)
625 {
626 new->q_state = QS_BADADDR;
627 new->q_status = "5.4.6";
628 if (new->q_alias != NULL)
629 {
630 new->q_alias->q_state = QS_BADADDR;
631 new->q_alias->q_status = "5.4.6";
632 }
633 if ((SuprErrs || !LogUsrErrs) && LogLevel > 0)
634 {
635 sm_syslog(LOG_ERR, e->e_id,
636 "aliasing/forwarding loop broken: %s (%d aliases deep; %d max)",
637 FileName != NULL ? FileName : "", aliaslevel,
638 MaxAliasRecursion);
639 }
640 usrerrenh(new->q_status,
641 "554 aliasing/forwarding loop broken (%d aliases deep; %d max)",
642 aliaslevel, MaxAliasRecursion);
643 return new;
644 }
645
646 /*
647 ** Finish setting up address structure.
648 */
649
650 /* get unquoted user for file, program or user.name check */
651 i = strlen(new->q_user);
652 if (i >= sizeof(buf0))
653 {
654 buflen = i + 1;
655 buf = xalloc(buflen);
656 }
657 else
658 {
659 buf = buf0;
660 buflen = sizeof(buf0);
661 }
662 (void) sm_strlcpy(buf, new->q_user, buflen);
663 for (p = buf; *p != '\0' && !quoted; p++)
664 {
665 if (*p == '\\')
666 quoted = true;
667 }
668 stripquotes(buf);
669
670 /* check for direct mailing to restricted mailers */
671 if (m == ProgMailer)
672 {
673 if (new->q_alias == NULL || UseMSP ||
674 bitset(EF_UNSAFE, e->e_flags))
675 {
676 new->q_state = QS_BADADDR;
677 new->q_status = "5.7.1";
678 usrerrenh(new->q_status,
679 "550 Cannot mail directly to programs");
680 }
681 else if (bitset(QBOGUSSHELL, new->q_alias->q_flags))
682 {
683 new->q_state = QS_BADADDR;
684 new->q_status = "5.7.1";
685 if (new->q_alias->q_ruser == NULL)
686 usrerrenh(new->q_status,
687 "550 UID %ld is an unknown user: cannot mail to programs",
688 (long) new->q_alias->q_uid);
689 else
690 usrerrenh(new->q_status,
691 "550 User %s@%s doesn't have a valid shell for mailing to programs",
692 new->q_alias->q_ruser, MyHostName);
693 }
694 else if (bitset(QUNSAFEADDR, new->q_alias->q_flags))
695 {
696 new->q_state = QS_BADADDR;
697 new->q_status = "5.7.1";
698 new->q_rstatus = "550 Unsafe for mailing to programs";
699 usrerrenh(new->q_status,
700 "550 Address %s is unsafe for mailing to programs",
701 new->q_alias->q_paddr);
702 }
703 }
704
705 /*
706 ** Look up this person in the recipient list.
707 ** If they are there already, return, otherwise continue.
708 ** If the list is empty, just add it. Notice the cute
709 ** hack to make from addresses suppress things correctly:
710 ** the QS_DUPLICATE state will be set in the send list.
711 ** [Please note: the emphasis is on "hack."]
712 */
713
714 prev = NULL;
715
716 /*
717 ** If this message is going to the queue or FastSplit is set
718 ** and it is the first try and the envelope hasn't split, then we
719 ** avoid doing an MX RR lookup now because one will be done when the
720 ** message is extracted from the queue later. It can go to the queue
721 ** because all messages are going to the queue or this mailer of
722 ** the current recipient is marked expensive.
723 */
724
725 if (UseMSP || WILL_BE_QUEUED(e->e_sendmode) ||
726 (!bitset(EF_SPLIT, e->e_flags) && e->e_ntries == 0 &&
727 FastSplit > 0))
728 sortfn = sorthost;
729 else if (NoConnect && bitnset(M_EXPENSIVE, new->q_mailer->m_flags))
730 sortfn = sortexpensive;
731 else
732 sortfn = sortbysignature;
733
734 for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
735 {
736 /*
737 ** If address is "less than" it should be inserted now.
738 ** If address is "greater than" current comparison it'll
739 ** insert later in the list; so loop again (if possible).
740 ** If address is "equal" (different equal than sameaddr()
741 ** call) then check if sameaddr() will be true.
742 ** Because this list is now sorted, it'll mean fewer
743 ** comparisons and fewer loops which is important for more
744 ** recipients.
745 */
746
747 i = (*sortfn)(new, q);
748 if (i == 0) /* equal */
749 {
750 /*
751 ** Sortbysignature() has said that the two have
752 ** equal MX RR's and the same user. Calling sameaddr()
753 ** now checks if the two hosts are as identical as the
754 ** MX RR's are (which might not be the case)
755 ** before saying these are the identical addresses.
756 */
757
758 if (sameaddr(q, new) &&
759 (bitset(QRCPTOK, q->q_flags) ||
760 !bitset(QPRIMARY, q->q_flags)))
761 {
762 if (tTd(26, 1))
763 {
764 sm_dprintf("%s in sendq: ",
765 new->q_paddr);
766 printaddr(sm_debug_file(), q, false);
767 }
768 if (!bitset(QPRIMARY, q->q_flags))
769 {
770 if (!QS_IS_DEAD(new->q_state))
771 message("duplicate suppressed");
772 else
773 q->q_state = QS_DUPLICATE;
774 q->q_flags |= new->q_flags;
775 }
776 else if (bitset(QSELFREF, q->q_flags)
777 || q->q_state == QS_REMOVED)
778 {
779 /*
780 ** If an earlier milter removed the
781 ** address, a later one can still add
782 ** it back.
783 */
784
785 q->q_state = new->q_state;
786 q->q_flags |= new->q_flags;
787 }
788 new = q;
789 goto done;
790 }
791 }
792 else if (i < 0) /* less than */
793 {
794 insert = true;
795 break;
796 }
797 prev = pq;
798 }
799
800 /* pq should point to an address, never NULL */
801 SM_ASSERT(pq != NULL);
802
803 /* add address on list */
804 if (insert)
805 {
806 /*
807 ** insert before 'pq'. Only possible when at least 1
808 ** ADDRESS is in the list already.
809 */
810
811 new->q_next = *pq;
812 if (prev == NULL)
813 *sendq = new; /* To be the first ADDRESS */
814 else
815 (*prev)->q_next = new;
816 }
817 else
818 {
819 /*
820 ** Place in list at current 'pq' position. Possible
821 ** when there are 0 or more ADDRESS's in the list.
822 */
823
824 new->q_next = NULL;
825 *pq = new;
826 }
827
828 /* added a new address: clear split flag */
829 e->e_flags &= ~EF_SPLIT;
830
831 /*
832 ** Alias the name and handle special mailer types.
833 */
834
835 trylocaluser:
836 if (tTd(29, 7))
837 {
838 sm_dprintf("at trylocaluser: ");
839 printaddr(sm_debug_file(), new, false);
840 }
841
842 if (!QS_IS_OK(new->q_state))
843 {
844 if (QS_IS_UNDELIVERED(new->q_state))
845 e->e_nrcpts++;
846 goto testselfdestruct;
847 }
848
849 if (m == InclMailer)
850 {
851 new->q_state = QS_INCLUDED;
852 if (new->q_alias == NULL || UseMSP ||
853 bitset(EF_UNSAFE, e->e_flags))
854 {
855 new->q_state = QS_BADADDR;
856 new->q_status = "5.7.1";
857 usrerrenh(new->q_status,
858 "550 Cannot mail directly to :include:s");
859 }
860 else
861 {
862 int ret;
863
864 message("including file %s", new->q_user);
865 ret = include(new->q_user, false, new,
866 sendq, aliaslevel, e);
867 if (transienterror(ret))
868 {
869 if (LogLevel > 2)
870 sm_syslog(LOG_ERR, e->e_id,
871 "include %s: transient error: %s",
872 shortenstring(new->q_user,
873 MAXSHORTSTR),
874 sm_errstring(ret));
875 new->q_state = QS_QUEUEUP;
876 usrerr("451 4.2.4 Cannot open %s: %s",
877 shortenstring(new->q_user,
878 MAXSHORTSTR),
879 sm_errstring(ret));
880 }
881 else if (ret != 0)
882 {
883 new->q_state = QS_BADADDR;
884 new->q_status = "5.2.4";
885 usrerrenh(new->q_status,
886 "550 Cannot open %s: %s",
887 shortenstring(new->q_user,
888 MAXSHORTSTR),
889 sm_errstring(ret));
890 }
891 }
892 }
893 else if (m == FileMailer)
894 {
895 /* check if allowed */
896 if (new->q_alias == NULL || UseMSP ||
897 bitset(EF_UNSAFE, e->e_flags))
898 {
899 new->q_state = QS_BADADDR;
900 new->q_status = "5.7.1";
901 usrerrenh(new->q_status,
902 "550 Cannot mail directly to files");
903 }
904 else if (bitset(QBOGUSSHELL, new->q_alias->q_flags))
905 {
906 new->q_state = QS_BADADDR;
907 new->q_status = "5.7.1";
908 if (new->q_alias->q_ruser == NULL)
909 usrerrenh(new->q_status,
910 "550 UID %ld is an unknown user: cannot mail to files",
911 (long) new->q_alias->q_uid);
912 else
913 usrerrenh(new->q_status,
914 "550 User %s@%s doesn't have a valid shell for mailing to files",
915 new->q_alias->q_ruser, MyHostName);
916 }
917 else if (bitset(QUNSAFEADDR, new->q_alias->q_flags))
918 {
919 new->q_state = QS_BADADDR;
920 new->q_status = "5.7.1";
921 new->q_rstatus = "550 Unsafe for mailing to files";
922 usrerrenh(new->q_status,
923 "550 Address %s is unsafe for mailing to files",
924 new->q_alias->q_paddr);
925 }
926 }
927
928 /* try aliasing */
929 if (!quoted && QS_IS_OK(new->q_state) &&
930 bitnset(M_ALIASABLE, m->m_flags))
931 alias(new, sendq, aliaslevel, e);
932
933 #if USERDB
934 /* if not aliased, look it up in the user database */
935 if (!bitset(QNOTREMOTE, new->q_flags) &&
936 QS_IS_SENDABLE(new->q_state) &&
937 bitnset(M_CHECKUDB, m->m_flags))
938 {
939 if (udbexpand(new, sendq, aliaslevel, e) == EX_TEMPFAIL)
940 {
941 new->q_state = QS_QUEUEUP;
942 if (e->e_message == NULL)
943 e->e_message = sm_rpool_strdup_x(e->e_rpool,
944 "Deferred: user database error");
945 if (new->q_message == NULL)
946 new->q_message = "Deferred: user database error";
947 if (LogLevel > 8)
948 sm_syslog(LOG_INFO, e->e_id,
949 "deferred: udbexpand: %s",
950 sm_errstring(errno));
951 message("queued (user database error): %s",
952 sm_errstring(errno));
953 e->e_nrcpts++;
954 goto testselfdestruct;
955 }
956 }
957 #endif /* USERDB */
958
959 /*
960 ** If we have a level two config file, then pass the name through
961 ** Ruleset 5 before sending it off. Ruleset 5 has the right
962 ** to rewrite it to another mailer. This gives us a hook
963 ** after local aliasing has been done.
964 */
965
966 if (tTd(29, 5))
967 {
968 sm_dprintf("recipient: testing local? cl=%d, rr5=%p\n\t",
969 ConfigLevel, (void *)RewriteRules[5]);
970 printaddr(sm_debug_file(), new, false);
971 }
972 if (ConfigLevel >= 2 && RewriteRules[5] != NULL &&
973 bitnset(M_TRYRULESET5, m->m_flags) &&
974 !bitset(QNOTREMOTE, new->q_flags) &&
975 QS_IS_OK(new->q_state))
976 {
977 maplocaluser(new, sendq, aliaslevel + 1, e);
978 }
979
980 /*
981 ** If it didn't get rewritten to another mailer, go ahead
982 ** and deliver it.
983 */
984
985 if (QS_IS_OK(new->q_state) &&
986 bitnset(M_HASPWENT, m->m_flags))
987 {
988 auto bool fuzzy;
989 SM_MBDB_T user;
990 int status;
991
992 /* warning -- finduser may trash buf */
993 status = finduser(buf, &fuzzy, &user);
994 switch (status)
995 {
996 case EX_TEMPFAIL:
997 new->q_state = QS_QUEUEUP;
998 new->q_status = "4.5.2";
999 giveresponse(EX_TEMPFAIL, new->q_status, m, NULL,
1000 new->q_alias, (time_t) 0, e, new);
1001 break;
1002 default:
1003 new->q_state = QS_BADADDR;
1004 new->q_status = "5.1.1";
1005 new->q_rstatus = "550 5.1.1 User unknown";
1006 giveresponse(EX_NOUSER, new->q_status, m, NULL,
1007 new->q_alias, (time_t) 0, e, new);
1008 break;
1009 case EX_OK:
1010 if (fuzzy)
1011 {
1012 /* name was a fuzzy match */
1013 new->q_user = sm_rpool_strdup_x(e->e_rpool,
1014 user.mbdb_name);
1015 if (findusercount++ > 3)
1016 {
1017 new->q_state = QS_BADADDR;
1018 new->q_status = "5.4.6";
1019 usrerrenh(new->q_status,
1020 "554 aliasing/forwarding loop for %s broken",
1021 user.mbdb_name);
1022 goto done;
1023 }
1024
1025 /* see if it aliases */
1026 (void) sm_strlcpy(buf, user.mbdb_name, buflen);
1027 goto trylocaluser;
1028 }
1029 if (*user.mbdb_homedir == '\0')
1030 new->q_home = NULL;
1031 else if (strcmp(user.mbdb_homedir, "/") == 0)
1032 new->q_home = "";
1033 else
1034 new->q_home = sm_rpool_strdup_x(e->e_rpool,
1035 user.mbdb_homedir);
1036 if (user.mbdb_uid != SM_NO_UID)
1037 {
1038 new->q_uid = user.mbdb_uid;
1039 new->q_gid = user.mbdb_gid;
1040 new->q_flags |= QGOODUID;
1041 }
1042 new->q_ruser = sm_rpool_strdup_x(e->e_rpool,
1043 user.mbdb_name);
1044 if (user.mbdb_fullname[0] != '\0')
1045 new->q_fullname = sm_rpool_strdup_x(e->e_rpool,
1046 user.mbdb_fullname);
1047 if (!usershellok(user.mbdb_name, user.mbdb_shell))
1048 {
1049 new->q_flags |= QBOGUSSHELL;
1050 }
1051 if (bitset(EF_VRFYONLY, e->e_flags))
1052 {
1053 /* don't do any more now */
1054 new->q_state = QS_VERIFIED;
1055 }
1056 else if (!quoted)
1057 forward(new, sendq, aliaslevel, e);
1058 }
1059 }
1060 if (!QS_IS_DEAD(new->q_state))
1061 e->e_nrcpts++;
1062
1063 testselfdestruct:
1064 new->q_flags |= QTHISPASS;
1065 if (tTd(26, 8))
1066 {
1067 sm_dprintf("testselfdestruct: ");
1068 printaddr(sm_debug_file(), new, false);
1069 if (tTd(26, 10))
1070 {
1071 sm_dprintf("SENDQ:\n");
1072 printaddr(sm_debug_file(), *sendq, true);
1073 sm_dprintf("----\n");
1074 }
1075 }
1076 if (new->q_alias == NULL && new != &e->e_from &&
1077 QS_IS_DEAD(new->q_state))
1078 {
1079 for (q = *sendq; q != NULL; q = q->q_next)
1080 {
1081 if (!QS_IS_DEAD(q->q_state))
1082 break;
1083 }
1084 if (q == NULL)
1085 {
1086 new->q_state = QS_BADADDR;
1087 new->q_status = "5.4.6";
1088 usrerrenh(new->q_status,
1089 "554 aliasing/forwarding loop broken");
1090 }
1091 }
1092
1093 done:
1094 new->q_flags |= QTHISPASS;
1095 if (buf != buf0)
1096 sm_free(buf); /* XXX leak if above code raises exception */
1097
1098 /*
1099 ** If we are at the top level, check to see if this has
1100 ** expanded to exactly one address. If so, it can inherit
1101 ** the primaryness of the address.
1102 **
1103 ** While we're at it, clear the QTHISPASS bits.
1104 */
1105
1106 if (aliaslevel == 0)
1107 {
1108 int nrcpts = 0;
1109 ADDRESS *only = NULL;
1110
1111 for (q = *sendq; q != NULL; q = q->q_next)
1112 {
1113 if (bitset(QTHISPASS, q->q_flags) &&
1114 QS_IS_SENDABLE(q->q_state))
1115 {
1116 nrcpts++;
1117 only = q;
1118 }
1119 q->q_flags &= ~QTHISPASS;
1120 }
1121 if (nrcpts == 1)
1122 {
1123 /* check to see if this actually got a new owner */
1124 q = only;
1125 while ((q = q->q_alias) != NULL)
1126 {
1127 if (q->q_owner != NULL)
1128 break;
1129 }
1130 if (q == NULL)
1131 only->q_flags |= QPRIMARY;
1132 }
1133 else if (!initialdontsend && nrcpts > 0)
1134 {
1135 /* arrange for return receipt */
1136 e->e_flags |= EF_SENDRECEIPT;
1137 new->q_flags |= QEXPANDED;
1138 if (e->e_xfp != NULL &&
1139 bitset(QPINGONSUCCESS, new->q_flags))
1140 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
1141 "%s... expanded to multiple addresses\n",
1142 new->q_paddr);
1143 }
1144 }
1145 new->q_flags |= QRCPTOK;
1146 (void) sm_snprintf(buf0, sizeof(buf0), "%d", e->e_nrcpts);
1147 macdefine(&e->e_macro, A_TEMP, macid("{nrcpts}"), buf0);
1148 return new;
1149 }
1150
1151 /*
1152 ** FINDUSER -- find the password entry for a user.
1153 **
1154 ** This looks a lot like getpwnam, except that it may want to
1155 ** do some fancier pattern matching in /etc/passwd.
1156 **
1157 ** This routine contains most of the time of many sendmail runs.
1158 ** It deserves to be optimized.
1159 **
1160 ** Parameters:
1161 ** name -- the name to match against.
1162 ** fuzzyp -- an outarg that is set to true if this entry
1163 ** was found using the fuzzy matching algorithm;
1164 ** set to false otherwise.
1165 ** user -- structure to fill in if user is found
1166 **
1167 ** Returns:
1168 ** On success, fill in *user, set *fuzzyp and return EX_OK.
1169 ** If the user was not found, return EX_NOUSER.
1170 ** On error, return EX_TEMPFAIL or EX_OSERR.
1171 **
1172 ** Side Effects:
1173 ** may modify name.
1174 */
1175
1176 int
finduser(name,fuzzyp,user)1177 finduser(name, fuzzyp, user)
1178 char *name;
1179 bool *fuzzyp;
1180 SM_MBDB_T *user;
1181 {
1182 #if MATCHGECOS
1183 register struct passwd *pw;
1184 #endif
1185 register char *p;
1186 bool tryagain;
1187 int status;
1188
1189 if (tTd(29, 4))
1190 sm_dprintf("finduser(%s): ", name);
1191
1192 *fuzzyp = false;
1193
1194 #if HESIOD && !HESIOD_ALLOW_NUMERIC_LOGIN
1195 /* DEC Hesiod getpwnam accepts numeric strings -- short circuit it */
1196 for (p = name; *p != '\0'; p++)
1197 if (!isascii(*p) || !isdigit(*p))
1198 break;
1199 if (*p == '\0')
1200 {
1201 if (tTd(29, 4))
1202 sm_dprintf("failed (numeric input)\n");
1203 return EX_NOUSER;
1204 }
1205 #endif /* HESIOD && !HESIOD_ALLOW_NUMERIC_LOGIN */
1206
1207 /* look up this login name using fast path */
1208 status = sm_mbdb_lookup(name, user);
1209 if (status != EX_NOUSER)
1210 {
1211 if (tTd(29, 4))
1212 sm_dprintf("%s (non-fuzzy)\n", sm_strexit(status));
1213 return status;
1214 }
1215
1216 /* try mapping it to lower case */
1217 tryagain = false;
1218 for (p = name; *p != '\0'; p++)
1219 {
1220 if (isascii(*p) && isupper(*p))
1221 {
1222 *p = tolower(*p);
1223 tryagain = true;
1224 }
1225 }
1226 if (tryagain && (status = sm_mbdb_lookup(name, user)) != EX_NOUSER)
1227 {
1228 if (tTd(29, 4))
1229 sm_dprintf("%s (lower case)\n", sm_strexit(status));
1230 *fuzzyp = true;
1231 return status;
1232 }
1233
1234 #if MATCHGECOS
1235 /* see if fuzzy matching allowed */
1236 if (!MatchGecos)
1237 {
1238 if (tTd(29, 4))
1239 sm_dprintf("not found (fuzzy disabled)\n");
1240 return EX_NOUSER;
1241 }
1242
1243 /* search for a matching full name instead */
1244 for (p = name; *p != '\0'; p++)
1245 {
1246 if (*p == (SpaceSub & 0177) || *p == '_')
1247 *p = ' ';
1248 }
1249 (void) setpwent();
1250 while ((pw = getpwent()) != NULL)
1251 {
1252 char buf[MAXNAME + 1]; /* EAI: ok: for pw_gecos */
1253
1254 # if 0
1255 if (SM_STRCASEEQ(pw->pw_name, name))
1256 {
1257 if (tTd(29, 4))
1258 sm_dprintf("found (case wrapped)\n");
1259 break;
1260 }
1261 # endif /* 0 */
1262
1263 sm_pwfullname(pw->pw_gecos, pw->pw_name, buf, sizeof(buf));
1264 if (strchr(buf, ' ') != NULL && SM_STRCASEEQ(buf, name))
1265 {
1266 if (tTd(29, 4))
1267 sm_dprintf("fuzzy matches %s\n", pw->pw_name);
1268 message("sending to login name %s", pw->pw_name);
1269 break;
1270 }
1271 }
1272 if (pw != NULL)
1273 *fuzzyp = true;
1274 else if (tTd(29, 4))
1275 sm_dprintf("no fuzzy match found\n");
1276 # if DEC_OSF_BROKEN_GETPWENT /* DEC OSF/1 3.2 or earlier */
1277 endpwent();
1278 # endif
1279 if (pw == NULL)
1280 return EX_NOUSER;
1281 sm_mbdb_frompw(user, pw);
1282 return EX_OK;
1283 #else /* MATCHGECOS */
1284 if (tTd(29, 4))
1285 sm_dprintf("not found (fuzzy disabled)\n");
1286 return EX_NOUSER;
1287 #endif /* MATCHGECOS */
1288 }
1289
1290 /*
1291 ** WRITABLE -- predicate returning if the file is writable.
1292 **
1293 ** This routine must duplicate the algorithm in sys/fio.c.
1294 ** Unfortunately, we cannot use the access call since we
1295 ** won't necessarily be the real uid when we try to
1296 ** actually open the file.
1297 **
1298 ** Notice that ANY file with ANY execute bit is automatically
1299 ** not writable. This is also enforced by mailfile.
1300 **
1301 ** Parameters:
1302 ** filename -- the file name to check.
1303 ** ctladdr -- the controlling address for this file.
1304 ** flags -- SFF_* flags to control the function.
1305 **
1306 ** Returns:
1307 ** true -- if we will be able to write this file.
1308 ** false -- if we cannot write this file.
1309 **
1310 ** Side Effects:
1311 ** none.
1312 */
1313
1314 bool
writable(filename,ctladdr,flags)1315 writable(filename, ctladdr, flags)
1316 char *filename;
1317 ADDRESS *ctladdr;
1318 long flags;
1319 {
1320 uid_t euid = 0;
1321 gid_t egid = 0;
1322 char *user = NULL;
1323
1324 if (tTd(44, 5))
1325 sm_dprintf("writable(%s, 0x%lx)\n", filename, flags);
1326
1327 /*
1328 ** File does exist -- check that it is writable.
1329 */
1330
1331 if (geteuid() != 0)
1332 {
1333 euid = geteuid();
1334 egid = getegid();
1335 user = NULL;
1336 }
1337 else if (ctladdr != NULL)
1338 {
1339 euid = ctladdr->q_uid;
1340 egid = ctladdr->q_gid;
1341 user = ctladdr->q_user;
1342 }
1343 else if (bitset(SFF_RUNASREALUID, flags))
1344 {
1345 euid = RealUid;
1346 egid = RealGid;
1347 user = RealUserName;
1348 }
1349 else if (FileMailer != NULL && !bitset(SFF_ROOTOK, flags))
1350 {
1351 if (FileMailer->m_uid == NO_UID)
1352 {
1353 euid = DefUid;
1354 user = DefUser;
1355 }
1356 else
1357 {
1358 euid = FileMailer->m_uid;
1359 user = NULL;
1360 }
1361 if (FileMailer->m_gid == NO_GID)
1362 egid = DefGid;
1363 else
1364 egid = FileMailer->m_gid;
1365 }
1366 else
1367 {
1368 euid = egid = 0;
1369 user = NULL;
1370 }
1371 if (!bitset(SFF_ROOTOK, flags))
1372 {
1373 if (euid == 0)
1374 {
1375 euid = DefUid;
1376 user = DefUser;
1377 }
1378 if (egid == 0)
1379 egid = DefGid;
1380 }
1381 if (geteuid() == 0 &&
1382 (ctladdr == NULL || !bitset(QGOODUID, ctladdr->q_flags)))
1383 flags |= SFF_SETUIDOK;
1384
1385 if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
1386 flags |= SFF_NOSLINK;
1387 if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
1388 flags |= SFF_NOHLINK;
1389
1390 errno = safefile(filename, euid, egid, user, flags, S_IWRITE, NULL);
1391 return errno == 0;
1392 }
1393
1394 /*
1395 ** INCLUDE -- handle :include: specification.
1396 **
1397 ** Parameters:
1398 ** fname -- filename to include.
1399 ** forwarding -- if true, we are reading a .forward file.
1400 ** if false, it's a :include: file.
1401 ** ctladdr -- address template to use to fill in these
1402 ** addresses -- effective user/group id are
1403 ** the important things.
1404 ** sendq -- a pointer to the head of the send queue
1405 ** to put these addresses in.
1406 ** aliaslevel -- the alias nesting depth.
1407 ** e -- the current envelope.
1408 **
1409 ** Returns:
1410 ** open error status
1411 **
1412 ** Side Effects:
1413 ** reads the :include: file and sends to everyone
1414 ** listed in that file.
1415 **
1416 ** Security Note:
1417 ** If you have restricted chown (that is, you can't
1418 ** give a file away), it is reasonable to allow programs
1419 ** and files called from this :include: file to be to be
1420 ** run as the owner of the :include: file. This is bogus
1421 ** if there is any chance of someone giving away a file.
1422 ** We assume that pre-POSIX systems can give away files.
1423 **
1424 ** There is an additional restriction that if you
1425 ** forward to a :include: file, it will not take on
1426 ** the ownership of the :include: file. This may not
1427 ** be necessary, but shouldn't hurt.
1428 */
1429
1430 static jmp_buf CtxIncludeTimeout;
1431
1432 int
include(fname,forwarding,ctladdr,sendq,aliaslevel,e)1433 include(fname, forwarding, ctladdr, sendq, aliaslevel, e)
1434 char *fname;
1435 bool forwarding;
1436 ADDRESS *ctladdr;
1437 ADDRESS **sendq;
1438 int aliaslevel;
1439 ENVELOPE *e;
1440 {
1441 SM_FILE_T *volatile fp = NULL;
1442 char *oldto = e->e_to;
1443 char *oldfilename = FileName;
1444 int oldlinenumber = LineNumber;
1445 register SM_EVENT *ev = NULL;
1446 int nincludes;
1447 int mode;
1448 volatile bool maxreached = false;
1449 register ADDRESS *ca;
1450 volatile uid_t saveduid;
1451 volatile gid_t savedgid;
1452 volatile uid_t uid;
1453 volatile gid_t gid;
1454 char *volatile user;
1455 int rval = 0;
1456 volatile long sfflags = SFF_REGONLY;
1457 register char *p;
1458 bool safechown = false;
1459 volatile bool safedir = false;
1460 struct stat st;
1461 char buf[MAXLINE];
1462
1463 if (tTd(27, 2))
1464 sm_dprintf("include(%s)\n", fname);
1465 if (tTd(27, 4))
1466 sm_dprintf(" ruid=%ld euid=%ld\n",
1467 (long) getuid(), (long) geteuid());
1468 if (tTd(27, 14))
1469 {
1470 sm_dprintf("ctladdr ");
1471 printaddr(sm_debug_file(), ctladdr, false);
1472 }
1473
1474 if (tTd(27, 9))
1475 sm_dprintf("include: old uid = %ld/%ld\n",
1476 (long) getuid(), (long) geteuid());
1477
1478 if (forwarding)
1479 {
1480 sfflags |= SFF_MUSTOWN|SFF_ROOTOK;
1481 if (!bitnset(DBS_GROUPWRITABLEFORWARDFILE, DontBlameSendmail))
1482 sfflags |= SFF_NOGWFILES;
1483 if (!bitnset(DBS_WORLDWRITABLEFORWARDFILE, DontBlameSendmail))
1484 sfflags |= SFF_NOWWFILES;
1485 }
1486 else
1487 {
1488 if (!bitnset(DBS_GROUPWRITABLEINCLUDEFILE, DontBlameSendmail))
1489 sfflags |= SFF_NOGWFILES;
1490 if (!bitnset(DBS_WORLDWRITABLEINCLUDEFILE, DontBlameSendmail))
1491 sfflags |= SFF_NOWWFILES;
1492 }
1493
1494 /*
1495 ** If RunAsUser set, won't be able to run programs as user
1496 ** so mark them as unsafe unless the administrator knows better.
1497 */
1498
1499 if ((geteuid() != 0 || RunAsUid != 0) &&
1500 !bitnset(DBS_NONROOTSAFEADDR, DontBlameSendmail))
1501 {
1502 if (tTd(27, 4))
1503 sm_dprintf("include: not safe (euid=%ld, RunAsUid=%ld)\n",
1504 (long) geteuid(), (long) RunAsUid);
1505 ctladdr->q_flags |= QUNSAFEADDR;
1506 }
1507
1508 ca = getctladdr(ctladdr);
1509 if (ca == NULL ||
1510 (ca->q_uid == DefUid && ca->q_gid == 0))
1511 {
1512 uid = DefUid;
1513 gid = DefGid;
1514 user = DefUser;
1515 }
1516 else
1517 {
1518 uid = ca->q_uid;
1519 gid = ca->q_gid;
1520 user = ca->q_user;
1521 }
1522 #if MAILER_SETUID_METHOD != USE_SETUID
1523 saveduid = geteuid();
1524 savedgid = getegid();
1525 if (saveduid == 0)
1526 {
1527 if (!DontInitGroups)
1528 {
1529 if (initgroups(user, gid) == -1)
1530 {
1531 rval = EAGAIN;
1532 syserr("include: initgroups(%s, %ld) failed",
1533 user, (long) gid);
1534 goto resetuid;
1535 }
1536 }
1537 else
1538 {
1539 GIDSET_T gidset[1];
1540
1541 gidset[0] = gid;
1542 if (setgroups(1, gidset) == -1)
1543 {
1544 rval = EAGAIN;
1545 syserr("include: setgroups() failed");
1546 goto resetuid;
1547 }
1548 }
1549
1550 if (gid != 0 && setgid(gid) < -1)
1551 {
1552 rval = EAGAIN;
1553 syserr("setgid(%ld) failure", (long) gid);
1554 goto resetuid;
1555 }
1556 if (uid != 0)
1557 {
1558 # if MAILER_SETUID_METHOD == USE_SETEUID
1559 if (seteuid(uid) < 0)
1560 {
1561 rval = EAGAIN;
1562 syserr("seteuid(%ld) failure (real=%ld, eff=%ld)",
1563 (long) uid, (long) getuid(), (long) geteuid());
1564 goto resetuid;
1565 }
1566 # endif /* MAILER_SETUID_METHOD == USE_SETEUID */
1567 # if MAILER_SETUID_METHOD == USE_SETREUID
1568 if (setreuid(0, uid) < 0)
1569 {
1570 rval = EAGAIN;
1571 syserr("setreuid(0, %ld) failure (real=%ld, eff=%ld)",
1572 (long) uid, (long) getuid(), (long) geteuid());
1573 goto resetuid;
1574 }
1575 # endif /* MAILER_SETUID_METHOD == USE_SETREUID */
1576 }
1577 }
1578 #endif /* MAILER_SETUID_METHOD != USE_SETUID */
1579
1580 if (tTd(27, 9))
1581 sm_dprintf("include: new uid = %ld/%ld\n",
1582 (long) getuid(), (long) geteuid());
1583
1584 /*
1585 ** If home directory is remote mounted but server is down,
1586 ** this can hang or give errors; use a timeout to avoid this
1587 */
1588
1589 if (setjmp(CtxIncludeTimeout) != 0)
1590 {
1591 ctladdr->q_state = QS_QUEUEUP;
1592 errno = 0;
1593
1594 /* return pseudo-error code */
1595 rval = E_SM_OPENTIMEOUT;
1596 goto resetuid;
1597 }
1598 if (TimeOuts.to_fileopen > 0)
1599 ev = sm_setevent(TimeOuts.to_fileopen, includetimeout, 0);
1600 else
1601 ev = NULL;
1602
1603
1604 /* check for writable parent directory */
1605 p = strrchr(fname, '/');
1606 if (p != NULL)
1607 {
1608 int ret;
1609
1610 *p = '\0';
1611 ret = safedirpath(fname, uid, gid, user,
1612 sfflags|SFF_SAFEDIRPATH, 0, 0);
1613 if (ret == 0)
1614 {
1615 /* in safe directory: relax chown & link rules */
1616 safedir = true;
1617 sfflags |= SFF_NOPATHCHECK;
1618 }
1619 else
1620 {
1621 if (bitnset((forwarding ?
1622 DBS_FORWARDFILEINUNSAFEDIRPATH :
1623 DBS_INCLUDEFILEINUNSAFEDIRPATH),
1624 DontBlameSendmail))
1625 sfflags |= SFF_NOPATHCHECK;
1626 else if (bitnset((forwarding ?
1627 DBS_FORWARDFILEINGROUPWRITABLEDIRPATH :
1628 DBS_INCLUDEFILEINGROUPWRITABLEDIRPATH),
1629 DontBlameSendmail) &&
1630 ret == E_SM_GWDIR)
1631 {
1632 setbitn(DBS_GROUPWRITABLEDIRPATHSAFE,
1633 DontBlameSendmail);
1634 ret = safedirpath(fname, uid, gid, user,
1635 sfflags|SFF_SAFEDIRPATH,
1636 0, 0);
1637 clrbitn(DBS_GROUPWRITABLEDIRPATHSAFE,
1638 DontBlameSendmail);
1639 if (ret == 0)
1640 sfflags |= SFF_NOPATHCHECK;
1641 else
1642 sfflags |= SFF_SAFEDIRPATH;
1643 }
1644 else
1645 sfflags |= SFF_SAFEDIRPATH;
1646 if (ret > E_PSEUDOBASE &&
1647 !bitnset((forwarding ?
1648 DBS_FORWARDFILEINUNSAFEDIRPATHSAFE :
1649 DBS_INCLUDEFILEINUNSAFEDIRPATHSAFE),
1650 DontBlameSendmail))
1651 {
1652 if (LogLevel > 11)
1653 sm_syslog(LOG_INFO, e->e_id,
1654 "%s: unsafe directory path, marked unsafe",
1655 shortenstring(fname, MAXSHORTSTR));
1656 ctladdr->q_flags |= QUNSAFEADDR;
1657 }
1658 }
1659 *p = '/';
1660 }
1661
1662 /* allow links only in unwritable directories */
1663 if (!safedir &&
1664 !bitnset((forwarding ?
1665 DBS_LINKEDFORWARDFILEINWRITABLEDIR :
1666 DBS_LINKEDINCLUDEFILEINWRITABLEDIR),
1667 DontBlameSendmail))
1668 sfflags |= SFF_NOLINK;
1669
1670 rval = safefile(fname, uid, gid, user, sfflags, S_IREAD, &st);
1671 if (rval != 0)
1672 {
1673 /* don't use this :include: file */
1674 if (tTd(27, 4))
1675 sm_dprintf("include: not safe (uid=%ld): %s\n",
1676 (long) uid, sm_errstring(rval));
1677 }
1678 else if ((fp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, fname,
1679 SM_IO_RDONLY, NULL)) == NULL)
1680 {
1681 rval = errno;
1682 if (tTd(27, 4))
1683 sm_dprintf("include: open: %s\n", sm_errstring(rval));
1684 }
1685 else if (filechanged(fname, sm_io_getinfo(fp,SM_IO_WHAT_FD, NULL), &st))
1686 {
1687 rval = E_SM_FILECHANGE;
1688 if (tTd(27, 4))
1689 sm_dprintf("include: file changed after open\n");
1690 }
1691 if (ev != NULL)
1692 sm_clrevent(ev);
1693
1694 resetuid:
1695
1696 #if HASSETREUID || USESETEUID
1697 if (saveduid == 0)
1698 {
1699 if (uid != 0)
1700 {
1701 # if USESETEUID
1702 if (seteuid(0) < 0)
1703 syserr("!seteuid(0) failure (real=%ld, eff=%ld)",
1704 (long) getuid(), (long) geteuid());
1705 # else /* USESETEUID */
1706 if (setreuid(-1, 0) < 0)
1707 syserr("!setreuid(-1, 0) failure (real=%ld, eff=%ld)",
1708 (long) getuid(), (long) geteuid());
1709 if (setreuid(RealUid, 0) < 0)
1710 syserr("!setreuid(%ld, 0) failure (real=%ld, eff=%ld)",
1711 (long) RealUid, (long) getuid(),
1712 (long) geteuid());
1713 # endif /* USESETEUID */
1714 }
1715 if (setgid(savedgid) < 0)
1716 syserr("!setgid(%ld) failure (real=%ld eff=%ld)",
1717 (long) savedgid, (long) getgid(),
1718 (long) getegid());
1719 }
1720 #endif /* HASSETREUID || USESETEUID */
1721
1722 if (tTd(27, 9))
1723 sm_dprintf("include: reset uid = %ld/%ld\n",
1724 (long) getuid(), (long) geteuid());
1725
1726 if (rval == E_SM_OPENTIMEOUT)
1727 usrerr("451 4.4.1 open timeout on %s", fname);
1728
1729 if (fp == NULL)
1730 return rval;
1731
1732 if (fstat(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), &st) < 0)
1733 {
1734 rval = errno;
1735 syserr("Cannot fstat %s!", fname);
1736 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1737 return rval;
1738 }
1739
1740 /* if path was writable, check to avoid file giveaway tricks */
1741 safechown = chownsafe(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), safedir);
1742 if (tTd(27, 6))
1743 sm_dprintf("include: parent of %s is %s, chown is %ssafe\n",
1744 fname, safedir ? "safe" : "dangerous",
1745 safechown ? "" : "un");
1746
1747 /* if no controlling user or coming from an alias delivery */
1748 if (safechown &&
1749 (ca == NULL ||
1750 (ca->q_uid == DefUid && ca->q_gid == 0)))
1751 {
1752 ctladdr->q_uid = st.st_uid;
1753 ctladdr->q_gid = st.st_gid;
1754 ctladdr->q_flags |= QGOODUID;
1755 }
1756 if (ca != NULL && ca->q_uid == st.st_uid)
1757 {
1758 /* optimization -- avoid getpwuid if we already have info */
1759 ctladdr->q_flags |= ca->q_flags & QBOGUSSHELL;
1760 ctladdr->q_ruser = ca->q_ruser;
1761 }
1762 else if (!forwarding)
1763 {
1764 register struct passwd *pw;
1765
1766 pw = sm_getpwuid(st.st_uid);
1767 if (pw == NULL)
1768 {
1769 ctladdr->q_uid = st.st_uid;
1770 ctladdr->q_flags |= QBOGUSSHELL;
1771 }
1772 else
1773 {
1774 char *sh;
1775
1776 ctladdr->q_ruser = sm_rpool_strdup_x(e->e_rpool,
1777 pw->pw_name);
1778 if (safechown)
1779 sh = pw->pw_shell;
1780 else
1781 sh = "/SENDMAIL/ANY/SHELL/";
1782 if (!usershellok(pw->pw_name, sh))
1783 {
1784 if (LogLevel > 11)
1785 sm_syslog(LOG_INFO, e->e_id,
1786 "%s: user %s has bad shell %s, marked %s",
1787 shortenstring(fname,
1788 MAXSHORTSTR),
1789 pw->pw_name, sh,
1790 safechown ? "bogus" : "unsafe");
1791 if (safechown)
1792 ctladdr->q_flags |= QBOGUSSHELL;
1793 else
1794 ctladdr->q_flags |= QUNSAFEADDR;
1795 }
1796 }
1797 }
1798
1799 if (bitset(EF_VRFYONLY, e->e_flags))
1800 {
1801 /* don't do any more now */
1802 ctladdr->q_state = QS_VERIFIED;
1803 e->e_nrcpts++;
1804 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1805 return rval;
1806 }
1807
1808 /*
1809 ** Check to see if some bad guy can write this file
1810 **
1811 ** Group write checking could be more clever, e.g.,
1812 ** guessing as to which groups are actually safe ("sys"
1813 ** may be; "user" probably is not).
1814 */
1815
1816 mode = S_IWOTH;
1817 if (!bitnset((forwarding ?
1818 DBS_GROUPWRITABLEFORWARDFILESAFE :
1819 DBS_GROUPWRITABLEINCLUDEFILESAFE),
1820 DontBlameSendmail))
1821 mode |= S_IWGRP;
1822
1823 if (bitset(mode, st.st_mode))
1824 {
1825 if (tTd(27, 6))
1826 sm_dprintf("include: %s is %s writable, marked unsafe\n",
1827 shortenstring(fname, MAXSHORTSTR),
1828 bitset(S_IWOTH, st.st_mode) ? "world"
1829 : "group");
1830 if (LogLevel > 11)
1831 sm_syslog(LOG_INFO, e->e_id,
1832 "%s: %s writable %s file, marked unsafe",
1833 shortenstring(fname, MAXSHORTSTR),
1834 bitset(S_IWOTH, st.st_mode) ? "world" : "group",
1835 forwarding ? "forward" : ":include:");
1836 ctladdr->q_flags |= QUNSAFEADDR;
1837 }
1838
1839 /* read the file -- each line is a comma-separated list. */
1840 FileName = fname;
1841 LineNumber = 0;
1842 ctladdr->q_flags &= ~QSELFREF;
1843 nincludes = 0;
1844 while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0 &&
1845 !maxreached)
1846 {
1847 fixcrlf(buf, true);
1848 LineNumber++;
1849 if (buf[0] == '#' || buf[0] == '\0')
1850 continue;
1851
1852 /* <sp>#@# introduces a comment anywhere */
1853 /* for Japanese character sets */
1854 for (p = buf; (p = strchr(++p, '#')) != NULL; )
1855 {
1856 if (p[1] == '@' && p[2] == '#' &&
1857 isascii(p[-1]) && isspace(p[-1]) &&
1858 (p[3] == '\0' || (SM_ISSPACE(p[3]))))
1859 {
1860 --p;
1861 while (p > buf && isascii(p[-1]) &&
1862 isspace(p[-1]))
1863 --p;
1864 p[0] = '\0';
1865 break;
1866 }
1867 }
1868 if (buf[0] == '\0')
1869 continue;
1870
1871 e->e_to = NULL;
1872 message("%s to %s",
1873 forwarding ? "forwarding" : "sending", buf);
1874 if (forwarding && LogLevel > 10)
1875 sm_syslog(LOG_INFO, e->e_id,
1876 "forward %.200s => %s",
1877 oldto, shortenstring(buf, MAXSHORTSTR));
1878
1879 nincludes += sendtolist(buf, ctladdr, sendq, aliaslevel + 1, e);
1880
1881 if (forwarding &&
1882 MaxForwardEntries > 0 &&
1883 nincludes >= MaxForwardEntries)
1884 {
1885 /* just stop reading and processing further entries */
1886 #if 0
1887 /* additional: (?) */
1888 ctladdr->q_state = QS_DONTSEND;
1889 #endif /* 0 */
1890
1891 syserr("Attempt to forward to more than %d addresses (in %s)!",
1892 MaxForwardEntries, fname);
1893 maxreached = true;
1894 }
1895 }
1896
1897 if (sm_io_error(fp) && tTd(27, 3))
1898 sm_dprintf("include: read error: %s\n", sm_errstring(errno));
1899 if (nincludes > 0 && !bitset(QSELFREF, ctladdr->q_flags))
1900 {
1901 if (aliaslevel <= MaxAliasRecursion ||
1902 ctladdr->q_state != QS_BADADDR)
1903 {
1904 ctladdr->q_state = QS_DONTSEND;
1905 if (tTd(27, 5))
1906 {
1907 sm_dprintf("include: QS_DONTSEND ");
1908 printaddr(sm_debug_file(), ctladdr, false);
1909 }
1910 }
1911 }
1912
1913 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1914 FileName = oldfilename;
1915 LineNumber = oldlinenumber;
1916 e->e_to = oldto;
1917 return rval;
1918 }
1919
1920 static void
includetimeout(ignore)1921 includetimeout(ignore)
1922 int ignore;
1923 {
1924 /*
1925 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
1926 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
1927 ** DOING.
1928 */
1929
1930 errno = ETIMEDOUT;
1931 longjmp(CtxIncludeTimeout, 1);
1932 }
1933
1934 /*
1935 ** SENDTOARGV -- send to an argument vector.
1936 **
1937 ** Parameters:
1938 ** argv -- argument vector to send to.
1939 ** e -- the current envelope.
1940 **
1941 ** Returns:
1942 ** none.
1943 **
1944 ** Side Effects:
1945 ** puts all addresses on the argument vector onto the
1946 ** send queue.
1947 */
1948
1949 void
sendtoargv(argv,e)1950 sendtoargv(argv, e)
1951 register char **argv;
1952 register ENVELOPE *e;
1953 {
1954 register char *p;
1955
1956 #if USE_EAI
1957 if (!e->e_smtputf8)
1958 {
1959 char **av;
1960
1961 av = argv;
1962 while ((p = *av++) != NULL)
1963 {
1964 if (!addr_is_ascii(p))
1965 {
1966 e->e_smtputf8 = true;
1967 break;
1968 }
1969 }
1970 }
1971 #endif /* USE_EAI */
1972
1973 while ((p = *argv++) != NULL)
1974 {
1975 #if USE_EAI
1976 if (e->e_smtputf8)
1977 {
1978 int len = 0;
1979
1980 if (!SMTPUTF8 && !asciistr(p))
1981 {
1982 usrerr("non-ASCII recipient address %s requires SMTPUTF8",
1983 p);
1984 finis(false, true, EX_USAGE);
1985 }
1986 p = quote_internal_chars(p, NULL, &len, NULL);
1987 }
1988 #endif /* USE_EAI */
1989 (void) sendtolist(p, NULLADDR, &e->e_sendqueue, 0, e);
1990 }
1991 }
1992
1993 /*
1994 ** GETCTLADDR -- get controlling address from an address header.
1995 **
1996 ** If none, get one corresponding to the effective userid.
1997 **
1998 ** Parameters:
1999 ** a -- the address to find the controller of.
2000 **
2001 ** Returns:
2002 ** the controlling address.
2003 */
2004
2005 ADDRESS *
getctladdr(a)2006 getctladdr(a)
2007 register ADDRESS *a;
2008 {
2009 while (a != NULL && !bitset(QGOODUID, a->q_flags))
2010 a = a->q_alias;
2011 return a;
2012 }
2013
2014 /*
2015 ** SELF_REFERENCE -- check to see if an address references itself
2016 **
2017 ** The check is done through a chain of aliases. If it is part of
2018 ** a loop, break the loop at the "best" address, that is, the one
2019 ** that exists as a real user.
2020 **
2021 ** This is to handle the case of:
2022 ** awc: Andrew.Chang
2023 ** Andrew.Chang: awc@mail.server
2024 ** which is a problem only on mail.server.
2025 **
2026 ** Parameters:
2027 ** a -- the address to check.
2028 **
2029 ** Returns:
2030 ** The address that should be retained.
2031 */
2032
2033 static ADDRESS *
self_reference(a)2034 self_reference(a)
2035 ADDRESS *a;
2036 {
2037 ADDRESS *b; /* top entry in self ref loop */
2038 ADDRESS *c; /* entry that point to a real mail box */
2039
2040 if (tTd(27, 1))
2041 sm_dprintf("self_reference(%s)\n", a->q_paddr);
2042
2043 for (b = a->q_alias; b != NULL; b = b->q_alias)
2044 {
2045 if (sameaddr(a, b))
2046 break;
2047 }
2048
2049 if (b == NULL)
2050 {
2051 if (tTd(27, 1))
2052 sm_dprintf("\t... no self ref\n");
2053 return NULL;
2054 }
2055
2056 /*
2057 ** Pick the first address that resolved to a real mail box
2058 ** i.e has a mbdb entry. The returned value will be marked
2059 ** QSELFREF in recipient(), which in turn will disable alias()
2060 ** from marking it as QS_IS_DEAD(), which mean it will be used
2061 ** as a deliverable address.
2062 **
2063 ** The 2 key thing to note here are:
2064 ** 1) we are in a recursive call sequence:
2065 ** alias->sendtolist->recipient->alias
2066 ** 2) normally, when we return back to alias(), the address
2067 ** will be marked QS_EXPANDED, since alias() assumes the
2068 ** expanded form will be used instead of the current address.
2069 ** This behaviour is turned off if the address is marked
2070 ** QSELFREF. We set QSELFREF when we return to recipient().
2071 */
2072
2073 c = a;
2074 while (c != NULL)
2075 {
2076 if (tTd(27, 10))
2077 sm_dprintf(" %s", c->q_user);
2078 if (bitnset(M_HASPWENT, c->q_mailer->m_flags))
2079 {
2080 SM_MBDB_T user;
2081
2082 if (tTd(27, 2))
2083 sm_dprintf("\t... getpwnam(%s)... ", c->q_user);
2084 if (sm_mbdb_lookup(c->q_user, &user) == EX_OK)
2085 {
2086 if (tTd(27, 2))
2087 sm_dprintf("found\n");
2088
2089 /* ought to cache results here */
2090 if (sameaddr(b, c))
2091 return b;
2092 else
2093 return c;
2094 }
2095 if (tTd(27, 2))
2096 sm_dprintf("failed\n");
2097 }
2098 else
2099 {
2100 /* if local delivery, compare usernames */
2101 if (bitnset(M_LOCALMAILER, c->q_mailer->m_flags) &&
2102 b->q_mailer == c->q_mailer)
2103 {
2104 if (tTd(27, 2))
2105 sm_dprintf("\t... local match (%s)\n",
2106 c->q_user);
2107 if (sameaddr(b, c))
2108 return b;
2109 else
2110 return c;
2111 }
2112 }
2113 if (tTd(27, 10))
2114 sm_dprintf("\n");
2115 c = c->q_alias;
2116 }
2117
2118 if (tTd(27, 1))
2119 sm_dprintf("\t... cannot break loop for \"%s\"\n", a->q_paddr);
2120
2121 return NULL;
2122 }
2123