2 * Copyright (c) 1998-2002 Sendmail, Inc. and its suppliers.
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.
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.
16 SM_RCSID("@(#)$Id: recipient.c,v 8.330.2.1 2002/08/27 20:21:02 gshapiro Exp $")
18 static void includetimeout __P((void));
19 static ADDRESS *self_reference __P((ADDRESS *));
20 static int sortexpensive __P((ADDRESS *, ADDRESS *));
21 static int sortbysignature __P((ADDRESS *, ADDRESS *));
22 static int sorthost __P((ADDRESS *, ADDRESS *));
24 typedef int sortfn_t __P((ADDRESS *, ADDRESS *));
27 ** SORTHOST -- strcmp()-like func for host portion of an ADDRESS
30 ** xx -- first ADDRESS
31 ** yy -- second ADDRESS
34 ** <0 when xx->q_host is less than yy->q_host
35 ** >0 when xx->q_host is greater than yy->q_host
44 #if _FFR_HOST_SORT_REVERSE
45 /* XXX maybe compare hostnames from the end? */
46 return sm_strrevcasecmp(xx->q_host, yy->q_host);
47 #else /* _FFR_HOST_SORT_REVERSE */
48 return sm_strcasecmp(xx->q_host, yy->q_host);
49 #endif /* _FFR_HOST_SORT_REVERSE */
53 ** SORTEXPENSIVE -- strcmp()-like func for expensive mailers
55 ** The mailer has been noted already as "expensive" for 'xx'. This
56 ** will give a result relative to 'yy'. Expensive mailers get rated
57 ** "greater than" non-expensive mailers because during the delivery phase
58 ** it will get queued -- no use it getting in the way of less expensive
59 ** recipients. We avoid an MX RR lookup when both 'xx' and 'yy' are
60 ** expensive since an MX RR lookup happens when extracted from the queue
64 ** xx -- first ADDRESS
65 ** yy -- second ADDRESS
68 ** <0 when xx->q_host is less than yy->q_host and both are
70 ** >0 when xx->q_host is greater than yy->q_host, or when
71 ** 'yy' is non-expensive
72 ** 0 when equal (by expense and q_host)
80 if (!bitnset(M_EXPENSIVE, yy->q_mailer->m_flags))
81 return 1; /* xx should go later */
82 #if _FFR_HOST_SORT_REVERSE
83 /* XXX maybe compare hostnames from the end? */
84 return sm_strrevcasecmp(xx->q_host, yy->q_host);
85 #else /* _FFR_HOST_SORT_REVERSE */
86 return sm_strcasecmp(xx->q_host, yy->q_host);
87 #endif /* _FFR_HOST_SORT_REVERSE */
91 ** SORTBYSIGNATURE -- a strcmp()-like func for q_mailer and q_host in ADDRESS
94 ** xx -- first ADDRESS
95 ** yy -- second ADDRESS
98 ** 0 when the "signature"'s are same
99 ** <0 when xx->q_signature is less than yy->q_signature
100 ** >0 when xx->q_signature is greater than yy->q_signature
103 ** May set ADDRESS pointer for q_signature if not already set.
107 sortbysignature(xx, yy)
113 /* Let's avoid redoing the signature over and over again */
114 if (xx->q_signature == NULL)
115 xx->q_signature = hostsignature(xx->q_mailer, xx->q_host);
116 if (yy->q_signature == NULL)
117 yy->q_signature = hostsignature(yy->q_mailer, yy->q_host);
118 ret = strcmp(xx->q_signature, yy->q_signature);
121 ** If the two signatures are the same then we will return a sort
122 ** value based on 'q_user'. But note that we have reversed xx and yy
123 ** on purpose. This additional compare helps reduce the number of
124 ** sameaddr() calls and loops in recipient() for the case when
125 ** the rcpt list has been provided already in-order.
129 return strcmp(yy->q_user, xx->q_user);
135 ** SENDTOLIST -- Designate a send list.
137 ** The parameter is a comma-separated list of people to send to.
138 ** This routine arranges to send to all of them.
141 ** list -- the send list.
142 ** ctladdr -- the address template for the person to
143 ** send to -- effective uid/gid are important.
144 ** This is typically the alias that caused this
146 ** sendq -- a pointer to the head of a queue to put
147 ** these people into.
148 ** aliaslevel -- the current alias nesting depth -- to
150 ** e -- the envelope in which to add these recipients.
153 ** The number of addresses actually on the list.
156 /* q_flags bits inherited from ctladdr */
157 #define QINHERITEDBITS (QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY|QHASNOTIFY)
160 sendtolist(list, ctladdr, sendq, aliaslevel, e)
165 register ENVELOPE *e;
168 register ADDRESS *SM_NONVOLATILE al; /* list of addresses to send to */
169 SM_NONVOLATILE char delimiter; /* the address delimiter */
170 SM_NONVOLATILE int naddrs;
171 SM_NONVOLATILE int i;
172 char *oldto = e->e_to;
173 char *SM_NONVOLATILE bufp;
174 char buf[MAXNAME + 1];
178 syserr("sendtolist: null list");
184 sm_dprintf("sendto: %s\n ctladdr=", list);
185 printaddr(ctladdr, false);
188 /* heuristic to determine old versus new style addresses */
189 if (ctladdr == NULL &&
190 (strchr(list, ',') != NULL || strchr(list, ';') != NULL ||
191 strchr(list, '<') != NULL || strchr(list, '(') != NULL))
192 e->e_flags &= ~EF_OLDSTYLE;
194 if (!bitset(EF_OLDSTYLE, e->e_flags) || ctladdr != NULL)
200 /* make sure we have enough space to copy the string */
201 i = strlen(list) + 1;
208 bufp = sm_malloc_x(i);
212 (void) sm_strlcpy(bufp, denlstring(list, false, true), i);
214 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r");
215 for (p = bufp; *p != '\0'; )
220 /* parse the address */
221 while ((isascii(*p) && isspace(*p)) || *p == ',')
223 a = parseaddr(p, NULLADDR, RF_COPYALL, delimiter,
229 a->q_alias = ctladdr;
231 /* arrange to inherit attributes from parent */
236 /* self reference test */
237 if (sameaddr(ctladdr, a))
241 sm_dprintf("sendtolist: QSELFREF ");
242 printaddr(ctladdr, false);
244 ctladdr->q_flags |= QSELFREF;
247 /* check for address loops */
248 b = self_reference(a);
251 b->q_flags |= QSELFREF;
254 sm_dprintf("sendtolist: QSELFREF ");
261 sm_dprintf("sendtolist: QS_DONTSEND ");
264 a->q_state = QS_DONTSEND;
265 b->q_flags |= a->q_flags & QNOTREMOTE;
271 if (a->q_fullname == NULL)
272 a->q_fullname = ctladdr->q_fullname;
274 /* various flag bits */
275 a->q_flags &= ~QINHERITEDBITS;
276 a->q_flags |= ctladdr->q_flags & QINHERITEDBITS;
278 /* DSN recipient information */
279 a->q_finalrcpt = ctladdr->q_finalrcpt;
280 a->q_orcpt = ctladdr->q_orcpt;
286 /* arrange to send to everyone on the local send list */
289 register ADDRESS *a = al;
292 a = recipient(a, sendq, aliaslevel, e);
301 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
308 ** REMOVEFROMLIST -- Remove addresses from a send list.
310 ** The parameter is a comma-separated list of recipients to remove.
311 ** Note that it only deletes matching addresses. If those addresses
312 ** have been expanded already in the sendq, it won't mark the
313 ** expanded recipients as QS_REMOVED.
316 ** list -- the list to remove.
317 ** sendq -- a pointer to the head of a queue to remove
318 ** these addresses from.
319 ** e -- the envelope in which to remove these recipients.
322 ** The number of addresses removed from the list.
327 removefromlist(list, sendq, e)
332 SM_NONVOLATILE char delimiter; /* the address delimiter */
333 SM_NONVOLATILE int naddrs;
334 SM_NONVOLATILE int i;
336 char *oldto = e->e_to;
337 char *SM_NONVOLATILE bufp;
338 char buf[MAXNAME + 1];
342 syserr("removefromlist: null list");
347 sm_dprintf("removefromlist: %s\n", list);
349 /* heuristic to determine old versus new style addresses */
350 if (strchr(list, ',') != NULL || strchr(list, ';') != NULL ||
351 strchr(list, '<') != NULL || strchr(list, '(') != NULL)
352 e->e_flags &= ~EF_OLDSTYLE;
354 if (!bitset(EF_OLDSTYLE, e->e_flags))
359 /* make sure we have enough space to copy the string */
360 i = strlen(list) + 1;
367 bufp = sm_malloc_x(i);
371 (void) sm_strlcpy(bufp, denlstring(list, false, true), i);
373 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r");
374 for (p = bufp; *p != '\0'; )
376 ADDRESS a; /* parsed address to be removed */
381 /* parse the address */
382 while ((isascii(*p) && isspace(*p)) || *p == ',')
384 if (parseaddr(p, &a, RF_COPYALL,
385 delimiter, &delimptr, e, true) == NULL)
391 for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
393 if (!QS_IS_DEAD(q->q_state) &&
398 sm_dprintf("removefromlist: QS_REMOVED ");
399 printaddr(&a, false);
401 q->q_state = QS_REMOVED;
413 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
420 ** RECIPIENT -- Designate a message recipient
422 ** Saves the named person for future mailing.
425 ** new -- the (preparsed) address header for the recipient.
426 ** sendq -- a pointer to the head of a queue to put the
427 ** recipient in. Duplicate suppression is done
429 ** aliaslevel -- the current alias nesting depth.
430 ** e -- the current envelope.
433 ** The actual address in the queue. This will be "a" if
434 ** the address is not a duplicate, else the original address.
439 recipient(new, sendq, aliaslevel, e)
440 register ADDRESS *new;
441 register ADDRESS **sendq;
443 register ENVELOPE *e;
448 register struct mailer *m;
451 bool quoted; /* set if the addr has a quote bit */
454 bool initialdontsend;
456 char buf0[MAXNAME + 1]; /* unquoted image of the user name */
463 initialdontsend = QS_IS_DEAD(new->q_state);
464 e->e_to = new->q_paddr;
468 new->q_flags |= QPRIMARY;
471 sm_dprintf("\nrecipient (%d): ", aliaslevel);
472 printaddr(new, false);
475 /* if this is primary, use it as original recipient */
476 if (new->q_alias == NULL)
478 if (e->e_origrcpt == NULL)
479 e->e_origrcpt = new->q_paddr;
480 else if (e->e_origrcpt != new->q_paddr)
484 /* find parent recipient for finalrcpt and orcpt */
485 for (q = new; q->q_alias != NULL; q = q->q_alias)
488 /* find final recipient DSN address */
489 if (new->q_finalrcpt == NULL &&
490 e->e_from.q_mailer != NULL)
494 p = e->e_from.q_mailer->m_addrtype;
497 if (sm_strcasecmp(p, "rfc822") != 0)
499 (void) sm_snprintf(frbuf, sizeof frbuf, "%s; %.800s",
500 q->q_mailer->m_addrtype,
503 else if (strchr(q->q_user, '@') != NULL)
505 (void) sm_snprintf(frbuf, sizeof frbuf, "%s; %.800s",
508 else if (strchr(q->q_paddr, '@') != NULL)
515 /* strip brackets from address */
519 b = qp[strlen(qp) - 1] == '>';
521 qp[strlen(qp) - 1] = '\0';
524 (void) sm_snprintf(frbuf, sizeof frbuf, "%s; %.800s",
529 qp[strlen(qp)] = '>';
533 (void) sm_snprintf(frbuf, sizeof frbuf,
535 p, q->q_user, MyHostName);
537 new->q_finalrcpt = sm_rpool_strdup_x(e->e_rpool, frbuf);
541 /* set ORCPT DSN arg if not already set */
542 if (new->q_orcpt == NULL)
544 /* check for an existing ORCPT */
545 if (q->q_orcpt != NULL)
546 new->q_orcpt = q->q_orcpt;
554 if (e->e_from.q_mailer != NULL)
555 p = e->e_from.q_mailer->m_addrtype;
558 (void) sm_strlcpyn(obuf, sizeof obuf, 2, p, ";");
562 /* FFR: Needs to strip comments from stdin addrs */
564 /* strip brackets from address */
567 b = qp[strlen(qp) - 1] == '>';
569 qp[strlen(qp) - 1] = '\0';
573 p = xtextify(denlstring(qp, true, false), NULL);
575 if (sm_strlcat(obuf, p, sizeof obuf) >= sizeof obuf)
577 /* if too big, don't use it */
583 qp[strlen(qp)] = '>';
587 sm_rpool_strdup_x(e->e_rpool, obuf);
590 #endif /* _FFR_GEN_ORCPT */
592 /* break aliasing loops */
593 if (aliaslevel > MaxAliasRecursion)
595 new->q_state = QS_BADADDR;
596 new->q_status = "5.4.6";
597 usrerrenh(new->q_status,
598 "554 aliasing/forwarding loop broken (%d aliases deep; %d max)",
599 aliaslevel, MaxAliasRecursion);
604 ** Finish setting up address structure.
607 /* get unquoted user for file, program or user.name check */
608 i = strlen(new->q_user);
609 if (i >= sizeof buf0)
612 buf = xalloc(buflen);
617 buflen = sizeof buf0;
619 (void) sm_strlcpy(buf, new->q_user, buflen);
620 for (p = buf; *p != '\0' && !quoted; p++)
627 /* check for direct mailing to restricted mailers */
630 if (new->q_alias == NULL || UseMSP ||
631 bitset(EF_UNSAFE, e->e_flags))
633 new->q_state = QS_BADADDR;
634 new->q_status = "5.7.1";
635 usrerrenh(new->q_status,
636 "550 Cannot mail directly to programs");
638 else if (bitset(QBOGUSSHELL, new->q_alias->q_flags))
640 new->q_state = QS_BADADDR;
641 new->q_status = "5.7.1";
642 if (new->q_alias->q_ruser == NULL)
643 usrerrenh(new->q_status,
644 "550 UID %d is an unknown user: cannot mail to programs",
645 new->q_alias->q_uid);
647 usrerrenh(new->q_status,
648 "550 User %s@%s doesn't have a valid shell for mailing to programs",
649 new->q_alias->q_ruser, MyHostName);
651 else if (bitset(QUNSAFEADDR, new->q_alias->q_flags))
653 new->q_state = QS_BADADDR;
654 new->q_status = "5.7.1";
655 new->q_rstatus = "550 Unsafe for mailing to programs";
656 usrerrenh(new->q_status,
657 "550 Address %s is unsafe for mailing to programs",
658 new->q_alias->q_paddr);
663 ** Look up this person in the recipient list.
664 ** If they are there already, return, otherwise continue.
665 ** If the list is empty, just add it. Notice the cute
666 ** hack to make from addresses suppress things correctly:
667 ** the QS_DUPLICATE state will be set in the send list.
668 ** [Please note: the emphasis is on "hack."]
674 ** If this message is going to the queue or FastSplit is set
675 ** and it is the first try and the envelope hasn't split, then we
676 ** avoid doing an MX RR lookup now because one will be done when the
677 ** message is extracted from the queue later. It can go to the queue
678 ** because all messages are going to the queue or this mailer of
679 ** the current recipient is marked expensive.
682 if (UseMSP || WILL_BE_QUEUED(e->e_sendmode) ||
683 (!bitset(EF_SPLIT, e->e_flags) && e->e_ntries == 0 &&
686 else if (NoConnect && bitnset(M_EXPENSIVE, new->q_mailer->m_flags))
687 sortfn = sortexpensive;
689 sortfn = sortbysignature;
691 for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
694 ** If address is "less than" it should be inserted now.
695 ** If address is "greater than" current comparison it'll
696 ** insert later in the list; so loop again (if possible).
697 ** If address is "equal" (different equal than sameaddr()
698 ** call) then check if sameaddr() will be true.
699 ** Because this list is now sorted, it'll mean fewer
700 ** comparisons and fewer loops which is important for more
704 i = (*sortfn)(new, q);
705 if (i == 0) /* equal */
708 ** Sortbysignature() has said that the two have
709 ** equal MX RR's and the same user. Calling sameaddr()
710 ** now checks if the two hosts are as identical as the
711 ** MX RR's are (which might not be the case)
712 ** before saying these are the identical addresses.
715 if (sameaddr(q, new) &&
716 (bitset(QRCPTOK, q->q_flags) ||
717 !bitset(QPRIMARY, q->q_flags)))
721 sm_dprintf("%s in sendq: ",
725 if (!bitset(QPRIMARY, q->q_flags))
727 if (!QS_IS_DEAD(new->q_state))
728 message("duplicate suppressed");
730 q->q_state = QS_DUPLICATE;
731 q->q_flags |= new->q_flags;
733 else if (bitset(QSELFREF, q->q_flags)
734 || q->q_state == QS_REMOVED)
737 ** If an earlier milter removed the
738 ** address, a later one can still add
742 q->q_state = new->q_state;
743 q->q_flags |= new->q_flags;
749 else if (i < 0) /* less than */
757 /* pq should point to an address, never NULL */
758 SM_ASSERT(pq != NULL);
760 /* add address on list */
764 ** insert before 'pq'. Only possible when at least 1
765 ** ADDRESS is in the list already.
770 *sendq = new; /* To be the first ADDRESS */
772 (*prev)->q_next = new;
777 ** Place in list at current 'pq' position. Possible
778 ** when there are 0 or more ADDRESS's in the list.
785 /* added a new address: clear split flag */
786 e->e_flags &= ~EF_SPLIT;
789 ** Alias the name and handle special mailer types.
795 sm_dprintf("at trylocaluser: ");
796 printaddr(new, false);
799 if (!QS_IS_OK(new->q_state))
801 if (QS_IS_UNDELIVERED(new->q_state))
803 goto testselfdestruct;
808 new->q_state = QS_INCLUDED;
809 if (new->q_alias == NULL || UseMSP ||
810 bitset(EF_UNSAFE, e->e_flags))
812 new->q_state = QS_BADADDR;
813 new->q_status = "5.7.1";
814 usrerrenh(new->q_status,
815 "550 Cannot mail directly to :include:s");
821 message("including file %s", new->q_user);
822 ret = include(new->q_user, false, new,
823 sendq, aliaslevel, e);
824 if (transienterror(ret))
827 sm_syslog(LOG_ERR, e->e_id,
828 "include %s: transient error: %s",
829 shortenstring(new->q_user,
832 new->q_state = QS_QUEUEUP;
833 usrerr("451 4.2.4 Cannot open %s: %s",
834 shortenstring(new->q_user,
840 new->q_state = QS_BADADDR;
841 new->q_status = "5.2.4";
842 usrerrenh(new->q_status,
843 "550 Cannot open %s: %s",
844 shortenstring(new->q_user,
850 else if (m == FileMailer)
852 /* check if allowed */
853 if (new->q_alias == NULL || UseMSP ||
854 bitset(EF_UNSAFE, e->e_flags))
856 new->q_state = QS_BADADDR;
857 new->q_status = "5.7.1";
858 usrerrenh(new->q_status,
859 "550 Cannot mail directly to files");
861 else if (bitset(QBOGUSSHELL, new->q_alias->q_flags))
863 new->q_state = QS_BADADDR;
864 new->q_status = "5.7.1";
865 if (new->q_alias->q_ruser == NULL)
866 usrerrenh(new->q_status,
867 "550 UID %d is an unknown user: cannot mail to files",
868 new->q_alias->q_uid);
870 usrerrenh(new->q_status,
871 "550 User %s@%s doesn't have a valid shell for mailing to files",
872 new->q_alias->q_ruser, MyHostName);
874 else if (bitset(QUNSAFEADDR, new->q_alias->q_flags))
876 new->q_state = QS_BADADDR;
877 new->q_status = "5.7.1";
878 new->q_rstatus = "550 Unsafe for mailing to files";
879 usrerrenh(new->q_status,
880 "550 Address %s is unsafe for mailing to files",
881 new->q_alias->q_paddr);
886 if (!quoted && QS_IS_OK(new->q_state) &&
887 bitnset(M_ALIASABLE, m->m_flags))
888 alias(new, sendq, aliaslevel, e);
891 /* if not aliased, look it up in the user database */
892 if (!bitset(QNOTREMOTE, new->q_flags) &&
893 QS_IS_SENDABLE(new->q_state) &&
894 bitnset(M_CHECKUDB, m->m_flags))
896 if (udbexpand(new, sendq, aliaslevel, e) == EX_TEMPFAIL)
898 new->q_state = QS_QUEUEUP;
899 if (e->e_message == NULL)
900 e->e_message = "Deferred: user database error";
901 if (new->q_message == NULL)
902 new->q_message = "Deferred: user database error";
904 sm_syslog(LOG_INFO, e->e_id,
905 "deferred: udbexpand: %s",
906 sm_errstring(errno));
907 message("queued (user database error): %s",
908 sm_errstring(errno));
910 goto testselfdestruct;
916 ** If we have a level two config file, then pass the name through
917 ** Ruleset 5 before sending it off. Ruleset 5 has the right
918 ** to rewrite it to another mailer. This gives us a hook
919 ** after local aliasing has been done.
924 sm_dprintf("recipient: testing local? cl=%d, rr5=%p\n\t",
925 ConfigLevel, RewriteRules[5]);
926 printaddr(new, false);
928 if (ConfigLevel >= 2 && RewriteRules[5] != NULL &&
929 bitnset(M_TRYRULESET5, m->m_flags) &&
930 !bitset(QNOTREMOTE, new->q_flags) &&
931 QS_IS_OK(new->q_state))
933 maplocaluser(new, sendq, aliaslevel + 1, e);
937 ** If it didn't get rewritten to another mailer, go ahead
941 if (QS_IS_OK(new->q_state) &&
942 bitnset(M_HASPWENT, m->m_flags))
948 /* warning -- finduser may trash buf */
949 status = finduser(buf, &fuzzy, &user);
953 new->q_state = QS_QUEUEUP;
954 new->q_status = "4.5.2";
955 giveresponse(EX_TEMPFAIL, new->q_status, m, NULL,
956 new->q_alias, (time_t) 0, e, new);
959 new->q_state = QS_BADADDR;
960 new->q_status = "5.1.1";
961 new->q_rstatus = "550 5.1.1 User unknown";
962 giveresponse(EX_NOUSER, new->q_status, m, NULL,
963 new->q_alias, (time_t) 0, e, new);
968 /* name was a fuzzy match */
969 new->q_user = sm_rpool_strdup_x(e->e_rpool,
971 if (findusercount++ > 3)
973 new->q_state = QS_BADADDR;
974 new->q_status = "5.4.6";
975 usrerrenh(new->q_status,
976 "554 aliasing/forwarding loop for %s broken",
981 /* see if it aliases */
982 (void) sm_strlcpy(buf, user.mbdb_name, buflen);
985 if (*user.mbdb_homedir == '\0')
987 else if (strcmp(user.mbdb_homedir, "/") == 0)
990 new->q_home = sm_rpool_strdup_x(e->e_rpool,
992 if (user.mbdb_uid != SM_NO_UID)
994 new->q_uid = user.mbdb_uid;
995 new->q_gid = user.mbdb_gid;
996 new->q_flags |= QGOODUID;
998 new->q_ruser = sm_rpool_strdup_x(e->e_rpool,
1000 if (user.mbdb_fullname[0] != '\0')
1001 new->q_fullname = sm_rpool_strdup_x(e->e_rpool,
1002 user.mbdb_fullname);
1003 if (!usershellok(user.mbdb_name, user.mbdb_shell))
1005 new->q_flags |= QBOGUSSHELL;
1007 if (bitset(EF_VRFYONLY, e->e_flags))
1009 /* don't do any more now */
1010 new->q_state = QS_VERIFIED;
1013 forward(new, sendq, aliaslevel, e);
1016 if (!QS_IS_DEAD(new->q_state))
1020 new->q_flags |= QTHISPASS;
1023 sm_dprintf("testselfdestruct: ");
1024 printaddr(new, false);
1027 sm_dprintf("SENDQ:\n");
1028 printaddr(*sendq, true);
1029 sm_dprintf("----\n");
1032 if (new->q_alias == NULL && new != &e->e_from &&
1033 QS_IS_DEAD(new->q_state))
1035 for (q = *sendq; q != NULL; q = q->q_next)
1037 if (!QS_IS_DEAD(q->q_state))
1042 new->q_state = QS_BADADDR;
1043 new->q_status = "5.4.6";
1044 usrerrenh(new->q_status,
1045 "554 aliasing/forwarding loop broken");
1050 new->q_flags |= QTHISPASS;
1052 sm_free(buf); /* XXX leak if above code raises exception */
1055 ** If we are at the top level, check to see if this has
1056 ** expanded to exactly one address. If so, it can inherit
1057 ** the primaryness of the address.
1059 ** While we're at it, clear the QTHISPASS bits.
1062 if (aliaslevel == 0)
1065 ADDRESS *only = NULL;
1067 for (q = *sendq; q != NULL; q = q->q_next)
1069 if (bitset(QTHISPASS, q->q_flags) &&
1070 QS_IS_SENDABLE(q->q_state))
1075 q->q_flags &= ~QTHISPASS;
1079 /* check to see if this actually got a new owner */
1081 while ((q = q->q_alias) != NULL)
1083 if (q->q_owner != NULL)
1087 only->q_flags |= QPRIMARY;
1089 else if (!initialdontsend && nrcpts > 0)
1091 /* arrange for return receipt */
1092 e->e_flags |= EF_SENDRECEIPT;
1093 new->q_flags |= QEXPANDED;
1094 if (e->e_xfp != NULL &&
1095 bitset(QPINGONSUCCESS, new->q_flags))
1096 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
1097 "%s... expanded to multiple addresses\n",
1101 new->q_flags |= QRCPTOK;
1102 (void) sm_snprintf(buf0, sizeof buf0, "%d", e->e_nrcpts);
1103 macdefine(&e->e_macro, A_TEMP, macid("{nrcpts}"), buf0);
1107 ** FINDUSER -- find the password entry for a user.
1109 ** This looks a lot like getpwnam, except that it may want to
1110 ** do some fancier pattern matching in /etc/passwd.
1112 ** This routine contains most of the time of many sendmail runs.
1113 ** It deserves to be optimized.
1116 ** name -- the name to match against.
1117 ** fuzzyp -- an outarg that is set to true if this entry
1118 ** was found using the fuzzy matching algorithm;
1119 ** set to false otherwise.
1120 ** user -- structure to fill in if user is found
1123 ** On success, fill in *user, set *fuzzyp and return EX_OK.
1124 ** If the user was not found, return EX_NOUSER.
1125 ** On error, return EX_TEMPFAIL or EX_OSERR.
1132 finduser(name, fuzzyp, user)
1138 register struct passwd *pw;
1139 #endif /* MATCHGECOS */
1145 sm_dprintf("finduser(%s): ", name);
1150 /* DEC Hesiod getpwnam accepts numeric strings -- short circuit it */
1151 for (p = name; *p != '\0'; p++)
1152 if (!isascii(*p) || !isdigit(*p))
1157 sm_dprintf("failed (numeric input)\n");
1162 /* look up this login name using fast path */
1163 status = sm_mbdb_lookup(name, user);
1164 if (status != EX_NOUSER)
1167 sm_dprintf("%s (non-fuzzy)\n", sm_strexit(status));
1171 /* try mapping it to lower case */
1173 for (p = name; *p != '\0'; p++)
1175 if (isascii(*p) && isupper(*p))
1181 if (tryagain && (status = sm_mbdb_lookup(name, user)) != EX_NOUSER)
1184 sm_dprintf("%s (lower case)\n", sm_strexit(status));
1190 /* see if fuzzy matching allowed */
1194 sm_dprintf("not found (fuzzy disabled)\n");
1198 /* search for a matching full name instead */
1199 for (p = name; *p != '\0'; p++)
1201 if (*p == (SpaceSub & 0177) || *p == '_')
1205 while ((pw = getpwent()) != NULL)
1207 char buf[MAXNAME + 1];
1210 if (sm_strcasecmp(pw->pw_name, name) == 0)
1213 sm_dprintf("found (case wrapped)\n");
1218 sm_pwfullname(pw->pw_gecos, pw->pw_name, buf, sizeof buf);
1219 if (strchr(buf, ' ') != NULL && sm_strcasecmp(buf, name) == 0)
1222 sm_dprintf("fuzzy matches %s\n", pw->pw_name);
1223 message("sending to login name %s", pw->pw_name);
1229 else if (tTd(29, 4))
1230 sm_dprintf("no fuzzy match found\n");
1231 # if DEC_OSF_BROKEN_GETPWENT /* DEC OSF/1 3.2 or earlier */
1233 # endif /* DEC_OSF_BROKEN_GETPWENT */
1236 sm_mbdb_frompw(user, pw);
1238 #else /* MATCHGECOS */
1240 sm_dprintf("not found (fuzzy disabled)\n");
1242 #endif /* MATCHGECOS */
1245 ** WRITABLE -- predicate returning if the file is writable.
1247 ** This routine must duplicate the algorithm in sys/fio.c.
1248 ** Unfortunately, we cannot use the access call since we
1249 ** won't necessarily be the real uid when we try to
1250 ** actually open the file.
1252 ** Notice that ANY file with ANY execute bit is automatically
1253 ** not writable. This is also enforced by mailfile.
1256 ** filename -- the file name to check.
1257 ** ctladdr -- the controlling address for this file.
1258 ** flags -- SFF_* flags to control the function.
1261 ** true -- if we will be able to write this file.
1262 ** false -- if we cannot write this file.
1269 writable(filename, ctladdr, flags)
1279 sm_dprintf("writable(%s, 0x%lx)\n", filename, flags);
1282 ** File does exist -- check that it is writable.
1291 else if (ctladdr != NULL)
1293 euid = ctladdr->q_uid;
1294 egid = ctladdr->q_gid;
1295 user = ctladdr->q_user;
1297 else if (bitset(SFF_RUNASREALUID, flags))
1301 user = RealUserName;
1303 else if (FileMailer != NULL && !bitset(SFF_ROOTOK, flags))
1305 euid = FileMailer->m_uid;
1306 egid = FileMailer->m_gid;
1314 if (!bitset(SFF_ROOTOK, flags))
1324 if (geteuid() == 0 &&
1325 (ctladdr == NULL || !bitset(QGOODUID, ctladdr->q_flags)))
1326 flags |= SFF_SETUIDOK;
1328 if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
1329 flags |= SFF_NOSLINK;
1330 if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
1331 flags |= SFF_NOHLINK;
1333 errno = safefile(filename, euid, egid, user, flags, S_IWRITE, NULL);
1337 ** INCLUDE -- handle :include: specification.
1340 ** fname -- filename to include.
1341 ** forwarding -- if true, we are reading a .forward file.
1342 ** if false, it's a :include: file.
1343 ** ctladdr -- address template to use to fill in these
1344 ** addresses -- effective user/group id are
1345 ** the important things.
1346 ** sendq -- a pointer to the head of the send queue
1347 ** to put these addresses in.
1348 ** aliaslevel -- the alias nesting depth.
1349 ** e -- the current envelope.
1352 ** open error status
1355 ** reads the :include: file and sends to everyone
1356 ** listed in that file.
1359 ** If you have restricted chown (that is, you can't
1360 ** give a file away), it is reasonable to allow programs
1361 ** and files called from this :include: file to be to be
1362 ** run as the owner of the :include: file. This is bogus
1363 ** if there is any chance of someone giving away a file.
1364 ** We assume that pre-POSIX systems can give away files.
1366 ** There is an additional restriction that if you
1367 ** forward to a :include: file, it will not take on
1368 ** the ownership of the :include: file. This may not
1369 ** be necessary, but shouldn't hurt.
1372 static jmp_buf CtxIncludeTimeout;
1375 include(fname, forwarding, ctladdr, sendq, aliaslevel, e)
1383 SM_FILE_T *volatile fp = NULL;
1384 char *oldto = e->e_to;
1385 char *oldfilename = FileName;
1386 int oldlinenumber = LineNumber;
1387 register SM_EVENT *ev = NULL;
1390 volatile bool maxreached = false;
1391 register ADDRESS *ca;
1392 volatile uid_t saveduid;
1393 volatile gid_t savedgid;
1396 char *volatile user;
1398 volatile long sfflags = SFF_REGONLY;
1400 bool safechown = false;
1401 volatile bool safedir = false;
1406 sm_dprintf("include(%s)\n", fname);
1408 sm_dprintf(" ruid=%d euid=%d\n",
1409 (int) getuid(), (int) geteuid());
1412 sm_dprintf("ctladdr ");
1413 printaddr(ctladdr, false);
1417 sm_dprintf("include: old uid = %d/%d\n",
1418 (int) getuid(), (int) geteuid());
1422 sfflags |= SFF_MUSTOWN|SFF_ROOTOK;
1423 if (!bitnset(DBS_GROUPWRITABLEFORWARDFILE, DontBlameSendmail))
1424 sfflags |= SFF_NOGWFILES;
1425 if (!bitnset(DBS_WORLDWRITABLEFORWARDFILE, DontBlameSendmail))
1426 sfflags |= SFF_NOWWFILES;
1430 if (!bitnset(DBS_GROUPWRITABLEINCLUDEFILE, DontBlameSendmail))
1431 sfflags |= SFF_NOGWFILES;
1432 if (!bitnset(DBS_WORLDWRITABLEINCLUDEFILE, DontBlameSendmail))
1433 sfflags |= SFF_NOWWFILES;
1437 ** If RunAsUser set, won't be able to run programs as user
1438 ** so mark them as unsafe unless the administrator knows better.
1441 if ((geteuid() != 0 || RunAsUid != 0) &&
1442 !bitnset(DBS_NONROOTSAFEADDR, DontBlameSendmail))
1445 sm_dprintf("include: not safe (euid=%d, RunAsUid=%d)\n",
1446 (int) geteuid(), (int) RunAsUid);
1447 ctladdr->q_flags |= QUNSAFEADDR;
1450 ca = getctladdr(ctladdr);
1452 (ca->q_uid == DefUid && ca->q_gid == 0))
1464 #if MAILER_SETUID_METHOD != USE_SETUID
1465 saveduid = geteuid();
1466 savedgid = getegid();
1469 if (!DontInitGroups)
1471 if (initgroups(user, gid) == -1)
1474 syserr("include: initgroups(%s, %d) failed",
1484 if (setgroups(1, gidset) == -1)
1487 syserr("include: setgroups() failed");
1492 if (gid != 0 && setgid(gid) < -1)
1495 syserr("setgid(%d) failure", gid);
1500 # if MAILER_SETUID_METHOD == USE_SETEUID
1501 if (seteuid(uid) < 0)
1504 syserr("seteuid(%d) failure (real=%d, eff=%d)",
1505 uid, (int) getuid(), (int) geteuid());
1508 # endif /* MAILER_SETUID_METHOD == USE_SETEUID */
1509 # if MAILER_SETUID_METHOD == USE_SETREUID
1510 if (setreuid(0, uid) < 0)
1513 syserr("setreuid(0, %d) failure (real=%d, eff=%d)",
1514 uid, (int) getuid(), (int) geteuid());
1517 # endif /* MAILER_SETUID_METHOD == USE_SETREUID */
1520 #endif /* MAILER_SETUID_METHOD != USE_SETUID */
1523 sm_dprintf("include: new uid = %d/%d\n",
1524 (int) getuid(), (int) geteuid());
1527 ** If home directory is remote mounted but server is down,
1528 ** this can hang or give errors; use a timeout to avoid this
1531 if (setjmp(CtxIncludeTimeout) != 0)
1533 ctladdr->q_state = QS_QUEUEUP;
1536 /* return pseudo-error code */
1537 rval = E_SM_OPENTIMEOUT;
1540 if (TimeOuts.to_fileopen > 0)
1541 ev = sm_setevent(TimeOuts.to_fileopen, includetimeout, 0);
1546 /* check for writable parent directory */
1547 p = strrchr(fname, '/');
1553 ret = safedirpath(fname, uid, gid, user,
1554 sfflags|SFF_SAFEDIRPATH, 0, 0);
1557 /* in safe directory: relax chown & link rules */
1559 sfflags |= SFF_NOPATHCHECK;
1563 if (bitnset((forwarding ?
1564 DBS_FORWARDFILEINUNSAFEDIRPATH :
1565 DBS_INCLUDEFILEINUNSAFEDIRPATH),
1567 sfflags |= SFF_NOPATHCHECK;
1568 else if (bitnset((forwarding ?
1569 DBS_FORWARDFILEINGROUPWRITABLEDIRPATH :
1570 DBS_INCLUDEFILEINGROUPWRITABLEDIRPATH),
1571 DontBlameSendmail) &&
1574 setbitn(DBS_GROUPWRITABLEDIRPATHSAFE,
1576 ret = safedirpath(fname, uid, gid, user,
1577 sfflags|SFF_SAFEDIRPATH,
1579 clrbitn(DBS_GROUPWRITABLEDIRPATHSAFE,
1582 sfflags |= SFF_NOPATHCHECK;
1584 sfflags |= SFF_SAFEDIRPATH;
1587 sfflags |= SFF_SAFEDIRPATH;
1588 if (ret > E_PSEUDOBASE &&
1589 !bitnset((forwarding ?
1590 DBS_FORWARDFILEINUNSAFEDIRPATHSAFE :
1591 DBS_INCLUDEFILEINUNSAFEDIRPATHSAFE),
1595 sm_syslog(LOG_INFO, e->e_id,
1596 "%s: unsafe directory path, marked unsafe",
1597 shortenstring(fname, MAXSHORTSTR));
1598 ctladdr->q_flags |= QUNSAFEADDR;
1604 /* allow links only in unwritable directories */
1606 !bitnset((forwarding ?
1607 DBS_LINKEDFORWARDFILEINWRITABLEDIR :
1608 DBS_LINKEDINCLUDEFILEINWRITABLEDIR),
1610 sfflags |= SFF_NOLINK;
1612 rval = safefile(fname, uid, gid, user, sfflags, S_IREAD, &st);
1615 /* don't use this :include: file */
1617 sm_dprintf("include: not safe (uid=%d): %s\n",
1618 (int) uid, sm_errstring(rval));
1620 else if ((fp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, fname,
1621 SM_IO_RDONLY, NULL)) == NULL)
1625 sm_dprintf("include: open: %s\n", sm_errstring(rval));
1627 else if (filechanged(fname, sm_io_getinfo(fp,SM_IO_WHAT_FD, NULL), &st))
1629 rval = E_SM_FILECHANGE;
1631 sm_dprintf("include: file changed after open\n");
1638 #if HASSETREUID || USESETEUID
1645 syserr("!seteuid(0) failure (real=%d, eff=%d)",
1646 (int) getuid(), (int) geteuid());
1647 # else /* USESETEUID */
1648 if (setreuid(-1, 0) < 0)
1649 syserr("!setreuid(-1, 0) failure (real=%d, eff=%d)",
1650 (int) getuid(), (int) geteuid());
1651 if (setreuid(RealUid, 0) < 0)
1652 syserr("!setreuid(%d, 0) failure (real=%d, eff=%d)",
1653 (int) RealUid, (int) getuid(),
1655 # endif /* USESETEUID */
1657 if (setgid(savedgid) < 0)
1658 syserr("!setgid(%d) failure (real=%d eff=%d)",
1659 (int) savedgid, (int) getgid(),
1662 #endif /* HASSETREUID || USESETEUID */
1665 sm_dprintf("include: reset uid = %d/%d\n",
1666 (int) getuid(), (int) geteuid());
1668 if (rval == E_SM_OPENTIMEOUT)
1669 usrerr("451 4.4.1 open timeout on %s", fname);
1674 if (fstat(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), &st) < 0)
1677 syserr("Cannot fstat %s!", fname);
1678 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1682 /* if path was writable, check to avoid file giveaway tricks */
1683 safechown = chownsafe(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), safedir);
1685 sm_dprintf("include: parent of %s is %s, chown is %ssafe\n",
1686 fname, safedir ? "safe" : "dangerous",
1687 safechown ? "" : "un");
1689 /* if no controlling user or coming from an alias delivery */
1692 (ca->q_uid == DefUid && ca->q_gid == 0)))
1694 ctladdr->q_uid = st.st_uid;
1695 ctladdr->q_gid = st.st_gid;
1696 ctladdr->q_flags |= QGOODUID;
1698 if (ca != NULL && ca->q_uid == st.st_uid)
1700 /* optimization -- avoid getpwuid if we already have info */
1701 ctladdr->q_flags |= ca->q_flags & QBOGUSSHELL;
1702 ctladdr->q_ruser = ca->q_ruser;
1704 else if (!forwarding)
1706 register struct passwd *pw;
1708 pw = sm_getpwuid(st.st_uid);
1711 ctladdr->q_uid = st.st_uid;
1712 ctladdr->q_flags |= QBOGUSSHELL;
1718 ctladdr->q_ruser = sm_rpool_strdup_x(e->e_rpool,
1723 sh = "/SENDMAIL/ANY/SHELL/";
1724 if (!usershellok(pw->pw_name, sh))
1727 sm_syslog(LOG_INFO, e->e_id,
1728 "%s: user %s has bad shell %s, marked %s",
1729 shortenstring(fname,
1732 safechown ? "bogus" : "unsafe");
1734 ctladdr->q_flags |= QBOGUSSHELL;
1736 ctladdr->q_flags |= QUNSAFEADDR;
1741 if (bitset(EF_VRFYONLY, e->e_flags))
1743 /* don't do any more now */
1744 ctladdr->q_state = QS_VERIFIED;
1746 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1751 ** Check to see if some bad guy can write this file
1753 ** Group write checking could be more clever, e.g.,
1754 ** guessing as to which groups are actually safe ("sys"
1755 ** may be; "user" probably is not).
1759 if (!bitnset((forwarding ?
1760 DBS_GROUPWRITABLEFORWARDFILESAFE :
1761 DBS_GROUPWRITABLEINCLUDEFILESAFE),
1765 if (bitset(mode, st.st_mode))
1768 sm_dprintf("include: %s is %s writable, marked unsafe\n",
1769 shortenstring(fname, MAXSHORTSTR),
1770 bitset(S_IWOTH, st.st_mode) ? "world"
1773 sm_syslog(LOG_INFO, e->e_id,
1774 "%s: %s writable %s file, marked unsafe",
1775 shortenstring(fname, MAXSHORTSTR),
1776 bitset(S_IWOTH, st.st_mode) ? "world" : "group",
1777 forwarding ? "forward" : ":include:");
1778 ctladdr->q_flags |= QUNSAFEADDR;
1781 /* read the file -- each line is a comma-separated list. */
1784 ctladdr->q_flags &= ~QSELFREF;
1786 while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, sizeof buf) != NULL &&
1791 if (buf[0] == '#' || buf[0] == '\0')
1794 /* <sp>#@# introduces a comment anywhere */
1795 /* for Japanese character sets */
1796 for (p = buf; (p = strchr(++p, '#')) != NULL; )
1798 if (p[1] == '@' && p[2] == '#' &&
1799 isascii(p[-1]) && isspace(p[-1]) &&
1800 (p[3] == '\0' || (isascii(p[3]) && isspace(p[3]))))
1803 while (p > buf && isascii(p[-1]) &&
1815 forwarding ? "forwarding" : "sending", buf);
1816 if (forwarding && LogLevel > 10)
1817 sm_syslog(LOG_INFO, e->e_id,
1818 "forward %.200s => %s",
1819 oldto, shortenstring(buf, MAXSHORTSTR));
1821 nincludes += sendtolist(buf, ctladdr, sendq, aliaslevel + 1, e);
1824 MaxForwardEntries > 0 &&
1825 nincludes >= MaxForwardEntries)
1827 /* just stop reading and processing further entries */
1829 /* additional: (?) */
1830 ctladdr->q_state = QS_DONTSEND;
1833 syserr("Attempt to forward to more than %d addresses (in %s)!",
1834 MaxForwardEntries, fname);
1839 if (sm_io_error(fp) && tTd(27, 3))
1840 sm_dprintf("include: read error: %s\n", sm_errstring(errno));
1841 if (nincludes > 0 && !bitset(QSELFREF, ctladdr->q_flags))
1845 sm_dprintf("include: QS_DONTSEND ");
1846 printaddr(ctladdr, false);
1848 ctladdr->q_state = QS_DONTSEND;
1851 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1852 FileName = oldfilename;
1853 LineNumber = oldlinenumber;
1862 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
1863 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
1868 longjmp(CtxIncludeTimeout, 1);
1871 ** SENDTOARGV -- send to an argument vector.
1874 ** argv -- argument vector to send to.
1875 ** e -- the current envelope.
1881 ** puts all addresses on the argument vector onto the
1887 register char **argv;
1888 register ENVELOPE *e;
1892 while ((p = *argv++) != NULL)
1893 (void) sendtolist(p, NULLADDR, &e->e_sendqueue, 0, e);
1896 ** GETCTLADDR -- get controlling address from an address header.
1898 ** If none, get one corresponding to the effective userid.
1901 ** a -- the address to find the controller of.
1904 ** the controlling address.
1909 register ADDRESS *a;
1911 while (a != NULL && !bitset(QGOODUID, a->q_flags))
1916 ** SELF_REFERENCE -- check to see if an address references itself
1918 ** The check is done through a chain of aliases. If it is part of
1919 ** a loop, break the loop at the "best" address, that is, the one
1920 ** that exists as a real user.
1922 ** This is to handle the case of:
1923 ** awc: Andrew.Chang
1924 ** Andrew.Chang: awc@mail.server
1925 ** which is a problem only on mail.server.
1928 ** a -- the address to check.
1931 ** The address that should be retained.
1938 ADDRESS *b; /* top entry in self ref loop */
1939 ADDRESS *c; /* entry that point to a real mail box */
1942 sm_dprintf("self_reference(%s)\n", a->q_paddr);
1944 for (b = a->q_alias; b != NULL; b = b->q_alias)
1953 sm_dprintf("\t... no self ref\n");
1958 ** Pick the first address that resolved to a real mail box
1959 ** i.e has a mbdb entry. The returned value will be marked
1960 ** QSELFREF in recipient(), which in turn will disable alias()
1961 ** from marking it as QS_IS_DEAD(), which mean it will be used
1962 ** as a deliverable address.
1964 ** The 2 key thing to note here are:
1965 ** 1) we are in a recursive call sequence:
1966 ** alias->sendtolist->recipient->alias
1967 ** 2) normally, when we return back to alias(), the address
1968 ** will be marked QS_EXPANDED, since alias() assumes the
1969 ** expanded form will be used instead of the current address.
1970 ** This behaviour is turned off if the address is marked
1971 ** QSELFREF. We set QSELFREF when we return to recipient().
1978 sm_dprintf(" %s", c->q_user);
1979 if (bitnset(M_HASPWENT, c->q_mailer->m_flags))
1984 sm_dprintf("\t... getpwnam(%s)... ", c->q_user);
1985 if (sm_mbdb_lookup(c->q_user, &user) == EX_OK)
1988 sm_dprintf("found\n");
1990 /* ought to cache results here */
1997 sm_dprintf("failed\n");
2001 /* if local delivery, compare usernames */
2002 if (bitnset(M_LOCALMAILER, c->q_mailer->m_flags) &&
2003 b->q_mailer == c->q_mailer)
2006 sm_dprintf("\t... local match (%s)\n",
2020 sm_dprintf("\t... cannot break loop for \"%s\"\n", a->q_paddr);