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.2 2003/09/16 19:56:25 ca 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;
173 char *oldto = e->e_to;
174 char *SM_NONVOLATILE bufp;
175 char buf[MAXNAME + 1];
179 syserr("sendtolist: null list");
185 sm_dprintf("sendto: %s\n ctladdr=", list);
186 printaddr(ctladdr, false);
189 /* heuristic to determine old versus new style addresses */
190 if (ctladdr == NULL &&
191 (strchr(list, ',') != NULL || strchr(list, ';') != NULL ||
192 strchr(list, '<') != NULL || strchr(list, '(') != NULL))
193 e->e_flags &= ~EF_OLDSTYLE;
195 if (!bitset(EF_OLDSTYLE, e->e_flags) || ctladdr != NULL)
201 /* make sure we have enough space to copy the string */
202 i = strlen(list) + 1;
209 bufp = sm_malloc_x(i);
214 (void) sm_strlcpy(bufp, denlstring(list, false, true), i);
216 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r");
217 for (p = bufp; *p != '\0'; )
224 /* parse the address */
225 while ((isascii(*p) && isspace(*p)) || *p == ',')
228 a = parseaddr(p, NULLADDR, RF_COPYALL, delimiter,
235 a->q_alias = ctladdr;
237 /* arrange to inherit attributes from parent */
242 /* self reference test */
243 if (sameaddr(ctladdr, a))
247 sm_dprintf("sendtolist: QSELFREF ");
248 printaddr(ctladdr, false);
250 ctladdr->q_flags |= QSELFREF;
253 /* check for address loops */
254 b = self_reference(a);
257 b->q_flags |= QSELFREF;
260 sm_dprintf("sendtolist: QSELFREF ");
267 sm_dprintf("sendtolist: QS_DONTSEND ");
270 a->q_state = QS_DONTSEND;
271 b->q_flags |= a->q_flags & QNOTREMOTE;
277 if (a->q_fullname == NULL)
278 a->q_fullname = ctladdr->q_fullname;
280 /* various flag bits */
281 a->q_flags &= ~QINHERITEDBITS;
282 a->q_flags |= ctladdr->q_flags & QINHERITEDBITS;
284 /* DSN recipient information */
285 a->q_finalrcpt = ctladdr->q_finalrcpt;
286 a->q_orcpt = ctladdr->q_orcpt;
292 /* arrange to send to everyone on the local send list */
295 register ADDRESS *a = al;
298 a = recipient(a, sendq, aliaslevel, e);
307 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
314 ** REMOVEFROMLIST -- Remove addresses from a send list.
316 ** The parameter is a comma-separated list of recipients to remove.
317 ** Note that it only deletes matching addresses. If those addresses
318 ** have been expanded already in the sendq, it won't mark the
319 ** expanded recipients as QS_REMOVED.
322 ** list -- the list to remove.
323 ** sendq -- a pointer to the head of a queue to remove
324 ** these addresses from.
325 ** e -- the envelope in which to remove these recipients.
328 ** The number of addresses removed from the list.
333 removefromlist(list, sendq, e)
338 SM_NONVOLATILE char delimiter; /* the address delimiter */
339 SM_NONVOLATILE int naddrs;
340 SM_NONVOLATILE int i;
342 char *oldto = e->e_to;
343 char *SM_NONVOLATILE bufp;
344 char buf[MAXNAME + 1];
348 syserr("removefromlist: null list");
353 sm_dprintf("removefromlist: %s\n", list);
355 /* heuristic to determine old versus new style addresses */
356 if (strchr(list, ',') != NULL || strchr(list, ';') != NULL ||
357 strchr(list, '<') != NULL || strchr(list, '(') != NULL)
358 e->e_flags &= ~EF_OLDSTYLE;
360 if (!bitset(EF_OLDSTYLE, e->e_flags))
365 /* make sure we have enough space to copy the string */
366 i = strlen(list) + 1;
373 bufp = sm_malloc_x(i);
377 (void) sm_strlcpy(bufp, denlstring(list, false, true), i);
379 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r");
380 for (p = bufp; *p != '\0'; )
382 ADDRESS a; /* parsed address to be removed */
387 /* parse the address */
388 while ((isascii(*p) && isspace(*p)) || *p == ',')
390 if (parseaddr(p, &a, RF_COPYALL,
391 delimiter, &delimptr, e, true) == NULL)
397 for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
399 if (!QS_IS_DEAD(q->q_state) &&
404 sm_dprintf("removefromlist: QS_REMOVED ");
405 printaddr(&a, false);
407 q->q_state = QS_REMOVED;
419 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
426 ** RECIPIENT -- Designate a message recipient
428 ** Saves the named person for future mailing.
431 ** new -- the (preparsed) address header for the recipient.
432 ** sendq -- a pointer to the head of a queue to put the
433 ** recipient in. Duplicate suppression is done
435 ** aliaslevel -- the current alias nesting depth.
436 ** e -- the current envelope.
439 ** The actual address in the queue. This will be "a" if
440 ** the address is not a duplicate, else the original address.
445 recipient(new, sendq, aliaslevel, e)
446 register ADDRESS *new;
447 register ADDRESS **sendq;
449 register ENVELOPE *e;
454 register struct mailer *m;
457 bool quoted; /* set if the addr has a quote bit */
460 bool initialdontsend;
462 char buf0[MAXNAME + 1]; /* unquoted image of the user name */
469 initialdontsend = QS_IS_DEAD(new->q_state);
470 e->e_to = new->q_paddr;
474 new->q_flags |= QPRIMARY;
477 sm_dprintf("\nrecipient (%d): ", aliaslevel);
478 printaddr(new, false);
481 /* if this is primary, use it as original recipient */
482 if (new->q_alias == NULL)
484 if (e->e_origrcpt == NULL)
485 e->e_origrcpt = new->q_paddr;
486 else if (e->e_origrcpt != new->q_paddr)
490 /* find parent recipient for finalrcpt and orcpt */
491 for (q = new; q->q_alias != NULL; q = q->q_alias)
494 /* find final recipient DSN address */
495 if (new->q_finalrcpt == NULL &&
496 e->e_from.q_mailer != NULL)
500 p = e->e_from.q_mailer->m_addrtype;
503 if (sm_strcasecmp(p, "rfc822") != 0)
505 (void) sm_snprintf(frbuf, sizeof frbuf, "%s; %.800s",
506 q->q_mailer->m_addrtype,
509 else if (strchr(q->q_user, '@') != NULL)
511 (void) sm_snprintf(frbuf, sizeof frbuf, "%s; %.800s",
514 else if (strchr(q->q_paddr, '@') != NULL)
521 /* strip brackets from address */
525 b = qp[strlen(qp) - 1] == '>';
527 qp[strlen(qp) - 1] = '\0';
530 (void) sm_snprintf(frbuf, sizeof frbuf, "%s; %.800s",
535 qp[strlen(qp)] = '>';
539 (void) sm_snprintf(frbuf, sizeof frbuf,
541 p, q->q_user, MyHostName);
543 new->q_finalrcpt = sm_rpool_strdup_x(e->e_rpool, frbuf);
547 /* set ORCPT DSN arg if not already set */
548 if (new->q_orcpt == NULL)
550 /* check for an existing ORCPT */
551 if (q->q_orcpt != NULL)
552 new->q_orcpt = q->q_orcpt;
560 if (e->e_from.q_mailer != NULL)
561 p = e->e_from.q_mailer->m_addrtype;
564 (void) sm_strlcpyn(obuf, sizeof obuf, 2, p, ";");
568 /* FFR: Needs to strip comments from stdin addrs */
570 /* strip brackets from address */
573 b = qp[strlen(qp) - 1] == '>';
575 qp[strlen(qp) - 1] = '\0';
579 p = xtextify(denlstring(qp, true, false), NULL);
581 if (sm_strlcat(obuf, p, sizeof obuf) >= sizeof obuf)
583 /* if too big, don't use it */
589 qp[strlen(qp)] = '>';
593 sm_rpool_strdup_x(e->e_rpool, obuf);
596 #endif /* _FFR_GEN_ORCPT */
598 /* break aliasing loops */
599 if (aliaslevel > MaxAliasRecursion)
601 new->q_state = QS_BADADDR;
602 new->q_status = "5.4.6";
603 usrerrenh(new->q_status,
604 "554 aliasing/forwarding loop broken (%d aliases deep; %d max)",
605 aliaslevel, MaxAliasRecursion);
610 ** Finish setting up address structure.
613 /* get unquoted user for file, program or user.name check */
614 i = strlen(new->q_user);
615 if (i >= sizeof buf0)
618 buf = xalloc(buflen);
623 buflen = sizeof buf0;
625 (void) sm_strlcpy(buf, new->q_user, buflen);
626 for (p = buf; *p != '\0' && !quoted; p++)
633 /* check for direct mailing to restricted mailers */
636 if (new->q_alias == NULL || UseMSP ||
637 bitset(EF_UNSAFE, e->e_flags))
639 new->q_state = QS_BADADDR;
640 new->q_status = "5.7.1";
641 usrerrenh(new->q_status,
642 "550 Cannot mail directly to programs");
644 else if (bitset(QBOGUSSHELL, new->q_alias->q_flags))
646 new->q_state = QS_BADADDR;
647 new->q_status = "5.7.1";
648 if (new->q_alias->q_ruser == NULL)
649 usrerrenh(new->q_status,
650 "550 UID %d is an unknown user: cannot mail to programs",
651 new->q_alias->q_uid);
653 usrerrenh(new->q_status,
654 "550 User %s@%s doesn't have a valid shell for mailing to programs",
655 new->q_alias->q_ruser, MyHostName);
657 else if (bitset(QUNSAFEADDR, new->q_alias->q_flags))
659 new->q_state = QS_BADADDR;
660 new->q_status = "5.7.1";
661 new->q_rstatus = "550 Unsafe for mailing to programs";
662 usrerrenh(new->q_status,
663 "550 Address %s is unsafe for mailing to programs",
664 new->q_alias->q_paddr);
669 ** Look up this person in the recipient list.
670 ** If they are there already, return, otherwise continue.
671 ** If the list is empty, just add it. Notice the cute
672 ** hack to make from addresses suppress things correctly:
673 ** the QS_DUPLICATE state will be set in the send list.
674 ** [Please note: the emphasis is on "hack."]
680 ** If this message is going to the queue or FastSplit is set
681 ** and it is the first try and the envelope hasn't split, then we
682 ** avoid doing an MX RR lookup now because one will be done when the
683 ** message is extracted from the queue later. It can go to the queue
684 ** because all messages are going to the queue or this mailer of
685 ** the current recipient is marked expensive.
688 if (UseMSP || WILL_BE_QUEUED(e->e_sendmode) ||
689 (!bitset(EF_SPLIT, e->e_flags) && e->e_ntries == 0 &&
692 else if (NoConnect && bitnset(M_EXPENSIVE, new->q_mailer->m_flags))
693 sortfn = sortexpensive;
695 sortfn = sortbysignature;
697 for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
700 ** If address is "less than" it should be inserted now.
701 ** If address is "greater than" current comparison it'll
702 ** insert later in the list; so loop again (if possible).
703 ** If address is "equal" (different equal than sameaddr()
704 ** call) then check if sameaddr() will be true.
705 ** Because this list is now sorted, it'll mean fewer
706 ** comparisons and fewer loops which is important for more
710 i = (*sortfn)(new, q);
711 if (i == 0) /* equal */
714 ** Sortbysignature() has said that the two have
715 ** equal MX RR's and the same user. Calling sameaddr()
716 ** now checks if the two hosts are as identical as the
717 ** MX RR's are (which might not be the case)
718 ** before saying these are the identical addresses.
721 if (sameaddr(q, new) &&
722 (bitset(QRCPTOK, q->q_flags) ||
723 !bitset(QPRIMARY, q->q_flags)))
727 sm_dprintf("%s in sendq: ",
731 if (!bitset(QPRIMARY, q->q_flags))
733 if (!QS_IS_DEAD(new->q_state))
734 message("duplicate suppressed");
736 q->q_state = QS_DUPLICATE;
737 q->q_flags |= new->q_flags;
739 else if (bitset(QSELFREF, q->q_flags)
740 || q->q_state == QS_REMOVED)
743 ** If an earlier milter removed the
744 ** address, a later one can still add
748 q->q_state = new->q_state;
749 q->q_flags |= new->q_flags;
755 else if (i < 0) /* less than */
763 /* pq should point to an address, never NULL */
764 SM_ASSERT(pq != NULL);
766 /* add address on list */
770 ** insert before 'pq'. Only possible when at least 1
771 ** ADDRESS is in the list already.
776 *sendq = new; /* To be the first ADDRESS */
778 (*prev)->q_next = new;
783 ** Place in list at current 'pq' position. Possible
784 ** when there are 0 or more ADDRESS's in the list.
791 /* added a new address: clear split flag */
792 e->e_flags &= ~EF_SPLIT;
795 ** Alias the name and handle special mailer types.
801 sm_dprintf("at trylocaluser: ");
802 printaddr(new, false);
805 if (!QS_IS_OK(new->q_state))
807 if (QS_IS_UNDELIVERED(new->q_state))
809 goto testselfdestruct;
814 new->q_state = QS_INCLUDED;
815 if (new->q_alias == NULL || UseMSP ||
816 bitset(EF_UNSAFE, e->e_flags))
818 new->q_state = QS_BADADDR;
819 new->q_status = "5.7.1";
820 usrerrenh(new->q_status,
821 "550 Cannot mail directly to :include:s");
827 message("including file %s", new->q_user);
828 ret = include(new->q_user, false, new,
829 sendq, aliaslevel, e);
830 if (transienterror(ret))
833 sm_syslog(LOG_ERR, e->e_id,
834 "include %s: transient error: %s",
835 shortenstring(new->q_user,
838 new->q_state = QS_QUEUEUP;
839 usrerr("451 4.2.4 Cannot open %s: %s",
840 shortenstring(new->q_user,
846 new->q_state = QS_BADADDR;
847 new->q_status = "5.2.4";
848 usrerrenh(new->q_status,
849 "550 Cannot open %s: %s",
850 shortenstring(new->q_user,
856 else if (m == FileMailer)
858 /* check if allowed */
859 if (new->q_alias == NULL || UseMSP ||
860 bitset(EF_UNSAFE, e->e_flags))
862 new->q_state = QS_BADADDR;
863 new->q_status = "5.7.1";
864 usrerrenh(new->q_status,
865 "550 Cannot mail directly to files");
867 else if (bitset(QBOGUSSHELL, new->q_alias->q_flags))
869 new->q_state = QS_BADADDR;
870 new->q_status = "5.7.1";
871 if (new->q_alias->q_ruser == NULL)
872 usrerrenh(new->q_status,
873 "550 UID %d is an unknown user: cannot mail to files",
874 new->q_alias->q_uid);
876 usrerrenh(new->q_status,
877 "550 User %s@%s doesn't have a valid shell for mailing to files",
878 new->q_alias->q_ruser, MyHostName);
880 else if (bitset(QUNSAFEADDR, new->q_alias->q_flags))
882 new->q_state = QS_BADADDR;
883 new->q_status = "5.7.1";
884 new->q_rstatus = "550 Unsafe for mailing to files";
885 usrerrenh(new->q_status,
886 "550 Address %s is unsafe for mailing to files",
887 new->q_alias->q_paddr);
892 if (!quoted && QS_IS_OK(new->q_state) &&
893 bitnset(M_ALIASABLE, m->m_flags))
894 alias(new, sendq, aliaslevel, e);
897 /* if not aliased, look it up in the user database */
898 if (!bitset(QNOTREMOTE, new->q_flags) &&
899 QS_IS_SENDABLE(new->q_state) &&
900 bitnset(M_CHECKUDB, m->m_flags))
902 if (udbexpand(new, sendq, aliaslevel, e) == EX_TEMPFAIL)
904 new->q_state = QS_QUEUEUP;
905 if (e->e_message == NULL)
906 e->e_message = "Deferred: user database error";
907 if (new->q_message == NULL)
908 new->q_message = "Deferred: user database error";
910 sm_syslog(LOG_INFO, e->e_id,
911 "deferred: udbexpand: %s",
912 sm_errstring(errno));
913 message("queued (user database error): %s",
914 sm_errstring(errno));
916 goto testselfdestruct;
922 ** If we have a level two config file, then pass the name through
923 ** Ruleset 5 before sending it off. Ruleset 5 has the right
924 ** to rewrite it to another mailer. This gives us a hook
925 ** after local aliasing has been done.
930 sm_dprintf("recipient: testing local? cl=%d, rr5=%p\n\t",
931 ConfigLevel, RewriteRules[5]);
932 printaddr(new, false);
934 if (ConfigLevel >= 2 && RewriteRules[5] != NULL &&
935 bitnset(M_TRYRULESET5, m->m_flags) &&
936 !bitset(QNOTREMOTE, new->q_flags) &&
937 QS_IS_OK(new->q_state))
939 maplocaluser(new, sendq, aliaslevel + 1, e);
943 ** If it didn't get rewritten to another mailer, go ahead
947 if (QS_IS_OK(new->q_state) &&
948 bitnset(M_HASPWENT, m->m_flags))
954 /* warning -- finduser may trash buf */
955 status = finduser(buf, &fuzzy, &user);
959 new->q_state = QS_QUEUEUP;
960 new->q_status = "4.5.2";
961 giveresponse(EX_TEMPFAIL, new->q_status, m, NULL,
962 new->q_alias, (time_t) 0, e, new);
965 new->q_state = QS_BADADDR;
966 new->q_status = "5.1.1";
967 new->q_rstatus = "550 5.1.1 User unknown";
968 giveresponse(EX_NOUSER, new->q_status, m, NULL,
969 new->q_alias, (time_t) 0, e, new);
974 /* name was a fuzzy match */
975 new->q_user = sm_rpool_strdup_x(e->e_rpool,
977 if (findusercount++ > 3)
979 new->q_state = QS_BADADDR;
980 new->q_status = "5.4.6";
981 usrerrenh(new->q_status,
982 "554 aliasing/forwarding loop for %s broken",
987 /* see if it aliases */
988 (void) sm_strlcpy(buf, user.mbdb_name, buflen);
991 if (*user.mbdb_homedir == '\0')
993 else if (strcmp(user.mbdb_homedir, "/") == 0)
996 new->q_home = sm_rpool_strdup_x(e->e_rpool,
998 if (user.mbdb_uid != SM_NO_UID)
1000 new->q_uid = user.mbdb_uid;
1001 new->q_gid = user.mbdb_gid;
1002 new->q_flags |= QGOODUID;
1004 new->q_ruser = sm_rpool_strdup_x(e->e_rpool,
1006 if (user.mbdb_fullname[0] != '\0')
1007 new->q_fullname = sm_rpool_strdup_x(e->e_rpool,
1008 user.mbdb_fullname);
1009 if (!usershellok(user.mbdb_name, user.mbdb_shell))
1011 new->q_flags |= QBOGUSSHELL;
1013 if (bitset(EF_VRFYONLY, e->e_flags))
1015 /* don't do any more now */
1016 new->q_state = QS_VERIFIED;
1019 forward(new, sendq, aliaslevel, e);
1022 if (!QS_IS_DEAD(new->q_state))
1026 new->q_flags |= QTHISPASS;
1029 sm_dprintf("testselfdestruct: ");
1030 printaddr(new, false);
1033 sm_dprintf("SENDQ:\n");
1034 printaddr(*sendq, true);
1035 sm_dprintf("----\n");
1038 if (new->q_alias == NULL && new != &e->e_from &&
1039 QS_IS_DEAD(new->q_state))
1041 for (q = *sendq; q != NULL; q = q->q_next)
1043 if (!QS_IS_DEAD(q->q_state))
1048 new->q_state = QS_BADADDR;
1049 new->q_status = "5.4.6";
1050 usrerrenh(new->q_status,
1051 "554 aliasing/forwarding loop broken");
1056 new->q_flags |= QTHISPASS;
1058 sm_free(buf); /* XXX leak if above code raises exception */
1061 ** If we are at the top level, check to see if this has
1062 ** expanded to exactly one address. If so, it can inherit
1063 ** the primaryness of the address.
1065 ** While we're at it, clear the QTHISPASS bits.
1068 if (aliaslevel == 0)
1071 ADDRESS *only = NULL;
1073 for (q = *sendq; q != NULL; q = q->q_next)
1075 if (bitset(QTHISPASS, q->q_flags) &&
1076 QS_IS_SENDABLE(q->q_state))
1081 q->q_flags &= ~QTHISPASS;
1085 /* check to see if this actually got a new owner */
1087 while ((q = q->q_alias) != NULL)
1089 if (q->q_owner != NULL)
1093 only->q_flags |= QPRIMARY;
1095 else if (!initialdontsend && nrcpts > 0)
1097 /* arrange for return receipt */
1098 e->e_flags |= EF_SENDRECEIPT;
1099 new->q_flags |= QEXPANDED;
1100 if (e->e_xfp != NULL &&
1101 bitset(QPINGONSUCCESS, new->q_flags))
1102 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
1103 "%s... expanded to multiple addresses\n",
1107 new->q_flags |= QRCPTOK;
1108 (void) sm_snprintf(buf0, sizeof buf0, "%d", e->e_nrcpts);
1109 macdefine(&e->e_macro, A_TEMP, macid("{nrcpts}"), buf0);
1113 ** FINDUSER -- find the password entry for a user.
1115 ** This looks a lot like getpwnam, except that it may want to
1116 ** do some fancier pattern matching in /etc/passwd.
1118 ** This routine contains most of the time of many sendmail runs.
1119 ** It deserves to be optimized.
1122 ** name -- the name to match against.
1123 ** fuzzyp -- an outarg that is set to true if this entry
1124 ** was found using the fuzzy matching algorithm;
1125 ** set to false otherwise.
1126 ** user -- structure to fill in if user is found
1129 ** On success, fill in *user, set *fuzzyp and return EX_OK.
1130 ** If the user was not found, return EX_NOUSER.
1131 ** On error, return EX_TEMPFAIL or EX_OSERR.
1138 finduser(name, fuzzyp, user)
1144 register struct passwd *pw;
1145 #endif /* MATCHGECOS */
1151 sm_dprintf("finduser(%s): ", name);
1156 /* DEC Hesiod getpwnam accepts numeric strings -- short circuit it */
1157 for (p = name; *p != '\0'; p++)
1158 if (!isascii(*p) || !isdigit(*p))
1163 sm_dprintf("failed (numeric input)\n");
1168 /* look up this login name using fast path */
1169 status = sm_mbdb_lookup(name, user);
1170 if (status != EX_NOUSER)
1173 sm_dprintf("%s (non-fuzzy)\n", sm_strexit(status));
1177 /* try mapping it to lower case */
1179 for (p = name; *p != '\0'; p++)
1181 if (isascii(*p) && isupper(*p))
1187 if (tryagain && (status = sm_mbdb_lookup(name, user)) != EX_NOUSER)
1190 sm_dprintf("%s (lower case)\n", sm_strexit(status));
1196 /* see if fuzzy matching allowed */
1200 sm_dprintf("not found (fuzzy disabled)\n");
1204 /* search for a matching full name instead */
1205 for (p = name; *p != '\0'; p++)
1207 if (*p == (SpaceSub & 0177) || *p == '_')
1211 while ((pw = getpwent()) != NULL)
1213 char buf[MAXNAME + 1];
1216 if (sm_strcasecmp(pw->pw_name, name) == 0)
1219 sm_dprintf("found (case wrapped)\n");
1224 sm_pwfullname(pw->pw_gecos, pw->pw_name, buf, sizeof buf);
1225 if (strchr(buf, ' ') != NULL && sm_strcasecmp(buf, name) == 0)
1228 sm_dprintf("fuzzy matches %s\n", pw->pw_name);
1229 message("sending to login name %s", pw->pw_name);
1235 else if (tTd(29, 4))
1236 sm_dprintf("no fuzzy match found\n");
1237 # if DEC_OSF_BROKEN_GETPWENT /* DEC OSF/1 3.2 or earlier */
1239 # endif /* DEC_OSF_BROKEN_GETPWENT */
1242 sm_mbdb_frompw(user, pw);
1244 #else /* MATCHGECOS */
1246 sm_dprintf("not found (fuzzy disabled)\n");
1248 #endif /* MATCHGECOS */
1251 ** WRITABLE -- predicate returning if the file is writable.
1253 ** This routine must duplicate the algorithm in sys/fio.c.
1254 ** Unfortunately, we cannot use the access call since we
1255 ** won't necessarily be the real uid when we try to
1256 ** actually open the file.
1258 ** Notice that ANY file with ANY execute bit is automatically
1259 ** not writable. This is also enforced by mailfile.
1262 ** filename -- the file name to check.
1263 ** ctladdr -- the controlling address for this file.
1264 ** flags -- SFF_* flags to control the function.
1267 ** true -- if we will be able to write this file.
1268 ** false -- if we cannot write this file.
1275 writable(filename, ctladdr, flags)
1285 sm_dprintf("writable(%s, 0x%lx)\n", filename, flags);
1288 ** File does exist -- check that it is writable.
1297 else if (ctladdr != NULL)
1299 euid = ctladdr->q_uid;
1300 egid = ctladdr->q_gid;
1301 user = ctladdr->q_user;
1303 else if (bitset(SFF_RUNASREALUID, flags))
1307 user = RealUserName;
1309 else if (FileMailer != NULL && !bitset(SFF_ROOTOK, flags))
1311 euid = FileMailer->m_uid;
1312 egid = FileMailer->m_gid;
1320 if (!bitset(SFF_ROOTOK, flags))
1330 if (geteuid() == 0 &&
1331 (ctladdr == NULL || !bitset(QGOODUID, ctladdr->q_flags)))
1332 flags |= SFF_SETUIDOK;
1334 if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
1335 flags |= SFF_NOSLINK;
1336 if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
1337 flags |= SFF_NOHLINK;
1339 errno = safefile(filename, euid, egid, user, flags, S_IWRITE, NULL);
1343 ** INCLUDE -- handle :include: specification.
1346 ** fname -- filename to include.
1347 ** forwarding -- if true, we are reading a .forward file.
1348 ** if false, it's a :include: file.
1349 ** ctladdr -- address template to use to fill in these
1350 ** addresses -- effective user/group id are
1351 ** the important things.
1352 ** sendq -- a pointer to the head of the send queue
1353 ** to put these addresses in.
1354 ** aliaslevel -- the alias nesting depth.
1355 ** e -- the current envelope.
1358 ** open error status
1361 ** reads the :include: file and sends to everyone
1362 ** listed in that file.
1365 ** If you have restricted chown (that is, you can't
1366 ** give a file away), it is reasonable to allow programs
1367 ** and files called from this :include: file to be to be
1368 ** run as the owner of the :include: file. This is bogus
1369 ** if there is any chance of someone giving away a file.
1370 ** We assume that pre-POSIX systems can give away files.
1372 ** There is an additional restriction that if you
1373 ** forward to a :include: file, it will not take on
1374 ** the ownership of the :include: file. This may not
1375 ** be necessary, but shouldn't hurt.
1378 static jmp_buf CtxIncludeTimeout;
1381 include(fname, forwarding, ctladdr, sendq, aliaslevel, e)
1389 SM_FILE_T *volatile fp = NULL;
1390 char *oldto = e->e_to;
1391 char *oldfilename = FileName;
1392 int oldlinenumber = LineNumber;
1393 register SM_EVENT *ev = NULL;
1396 volatile bool maxreached = false;
1397 register ADDRESS *ca;
1398 volatile uid_t saveduid;
1399 volatile gid_t savedgid;
1402 char *volatile user;
1404 volatile long sfflags = SFF_REGONLY;
1406 bool safechown = false;
1407 volatile bool safedir = false;
1412 sm_dprintf("include(%s)\n", fname);
1414 sm_dprintf(" ruid=%d euid=%d\n",
1415 (int) getuid(), (int) geteuid());
1418 sm_dprintf("ctladdr ");
1419 printaddr(ctladdr, false);
1423 sm_dprintf("include: old uid = %d/%d\n",
1424 (int) getuid(), (int) geteuid());
1428 sfflags |= SFF_MUSTOWN|SFF_ROOTOK;
1429 if (!bitnset(DBS_GROUPWRITABLEFORWARDFILE, DontBlameSendmail))
1430 sfflags |= SFF_NOGWFILES;
1431 if (!bitnset(DBS_WORLDWRITABLEFORWARDFILE, DontBlameSendmail))
1432 sfflags |= SFF_NOWWFILES;
1436 if (!bitnset(DBS_GROUPWRITABLEINCLUDEFILE, DontBlameSendmail))
1437 sfflags |= SFF_NOGWFILES;
1438 if (!bitnset(DBS_WORLDWRITABLEINCLUDEFILE, DontBlameSendmail))
1439 sfflags |= SFF_NOWWFILES;
1443 ** If RunAsUser set, won't be able to run programs as user
1444 ** so mark them as unsafe unless the administrator knows better.
1447 if ((geteuid() != 0 || RunAsUid != 0) &&
1448 !bitnset(DBS_NONROOTSAFEADDR, DontBlameSendmail))
1451 sm_dprintf("include: not safe (euid=%d, RunAsUid=%d)\n",
1452 (int) geteuid(), (int) RunAsUid);
1453 ctladdr->q_flags |= QUNSAFEADDR;
1456 ca = getctladdr(ctladdr);
1458 (ca->q_uid == DefUid && ca->q_gid == 0))
1470 #if MAILER_SETUID_METHOD != USE_SETUID
1471 saveduid = geteuid();
1472 savedgid = getegid();
1475 if (!DontInitGroups)
1477 if (initgroups(user, gid) == -1)
1480 syserr("include: initgroups(%s, %d) failed",
1490 if (setgroups(1, gidset) == -1)
1493 syserr("include: setgroups() failed");
1498 if (gid != 0 && setgid(gid) < -1)
1501 syserr("setgid(%d) failure", gid);
1506 # if MAILER_SETUID_METHOD == USE_SETEUID
1507 if (seteuid(uid) < 0)
1510 syserr("seteuid(%d) failure (real=%d, eff=%d)",
1511 uid, (int) getuid(), (int) geteuid());
1514 # endif /* MAILER_SETUID_METHOD == USE_SETEUID */
1515 # if MAILER_SETUID_METHOD == USE_SETREUID
1516 if (setreuid(0, uid) < 0)
1519 syserr("setreuid(0, %d) failure (real=%d, eff=%d)",
1520 uid, (int) getuid(), (int) geteuid());
1523 # endif /* MAILER_SETUID_METHOD == USE_SETREUID */
1526 #endif /* MAILER_SETUID_METHOD != USE_SETUID */
1529 sm_dprintf("include: new uid = %d/%d\n",
1530 (int) getuid(), (int) geteuid());
1533 ** If home directory is remote mounted but server is down,
1534 ** this can hang or give errors; use a timeout to avoid this
1537 if (setjmp(CtxIncludeTimeout) != 0)
1539 ctladdr->q_state = QS_QUEUEUP;
1542 /* return pseudo-error code */
1543 rval = E_SM_OPENTIMEOUT;
1546 if (TimeOuts.to_fileopen > 0)
1547 ev = sm_setevent(TimeOuts.to_fileopen, includetimeout, 0);
1552 /* check for writable parent directory */
1553 p = strrchr(fname, '/');
1559 ret = safedirpath(fname, uid, gid, user,
1560 sfflags|SFF_SAFEDIRPATH, 0, 0);
1563 /* in safe directory: relax chown & link rules */
1565 sfflags |= SFF_NOPATHCHECK;
1569 if (bitnset((forwarding ?
1570 DBS_FORWARDFILEINUNSAFEDIRPATH :
1571 DBS_INCLUDEFILEINUNSAFEDIRPATH),
1573 sfflags |= SFF_NOPATHCHECK;
1574 else if (bitnset((forwarding ?
1575 DBS_FORWARDFILEINGROUPWRITABLEDIRPATH :
1576 DBS_INCLUDEFILEINGROUPWRITABLEDIRPATH),
1577 DontBlameSendmail) &&
1580 setbitn(DBS_GROUPWRITABLEDIRPATHSAFE,
1582 ret = safedirpath(fname, uid, gid, user,
1583 sfflags|SFF_SAFEDIRPATH,
1585 clrbitn(DBS_GROUPWRITABLEDIRPATHSAFE,
1588 sfflags |= SFF_NOPATHCHECK;
1590 sfflags |= SFF_SAFEDIRPATH;
1593 sfflags |= SFF_SAFEDIRPATH;
1594 if (ret > E_PSEUDOBASE &&
1595 !bitnset((forwarding ?
1596 DBS_FORWARDFILEINUNSAFEDIRPATHSAFE :
1597 DBS_INCLUDEFILEINUNSAFEDIRPATHSAFE),
1601 sm_syslog(LOG_INFO, e->e_id,
1602 "%s: unsafe directory path, marked unsafe",
1603 shortenstring(fname, MAXSHORTSTR));
1604 ctladdr->q_flags |= QUNSAFEADDR;
1610 /* allow links only in unwritable directories */
1612 !bitnset((forwarding ?
1613 DBS_LINKEDFORWARDFILEINWRITABLEDIR :
1614 DBS_LINKEDINCLUDEFILEINWRITABLEDIR),
1616 sfflags |= SFF_NOLINK;
1618 rval = safefile(fname, uid, gid, user, sfflags, S_IREAD, &st);
1621 /* don't use this :include: file */
1623 sm_dprintf("include: not safe (uid=%d): %s\n",
1624 (int) uid, sm_errstring(rval));
1626 else if ((fp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, fname,
1627 SM_IO_RDONLY, NULL)) == NULL)
1631 sm_dprintf("include: open: %s\n", sm_errstring(rval));
1633 else if (filechanged(fname, sm_io_getinfo(fp,SM_IO_WHAT_FD, NULL), &st))
1635 rval = E_SM_FILECHANGE;
1637 sm_dprintf("include: file changed after open\n");
1644 #if HASSETREUID || USESETEUID
1651 syserr("!seteuid(0) failure (real=%d, eff=%d)",
1652 (int) getuid(), (int) geteuid());
1653 # else /* USESETEUID */
1654 if (setreuid(-1, 0) < 0)
1655 syserr("!setreuid(-1, 0) failure (real=%d, eff=%d)",
1656 (int) getuid(), (int) geteuid());
1657 if (setreuid(RealUid, 0) < 0)
1658 syserr("!setreuid(%d, 0) failure (real=%d, eff=%d)",
1659 (int) RealUid, (int) getuid(),
1661 # endif /* USESETEUID */
1663 if (setgid(savedgid) < 0)
1664 syserr("!setgid(%d) failure (real=%d eff=%d)",
1665 (int) savedgid, (int) getgid(),
1668 #endif /* HASSETREUID || USESETEUID */
1671 sm_dprintf("include: reset uid = %d/%d\n",
1672 (int) getuid(), (int) geteuid());
1674 if (rval == E_SM_OPENTIMEOUT)
1675 usrerr("451 4.4.1 open timeout on %s", fname);
1680 if (fstat(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), &st) < 0)
1683 syserr("Cannot fstat %s!", fname);
1684 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1688 /* if path was writable, check to avoid file giveaway tricks */
1689 safechown = chownsafe(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), safedir);
1691 sm_dprintf("include: parent of %s is %s, chown is %ssafe\n",
1692 fname, safedir ? "safe" : "dangerous",
1693 safechown ? "" : "un");
1695 /* if no controlling user or coming from an alias delivery */
1698 (ca->q_uid == DefUid && ca->q_gid == 0)))
1700 ctladdr->q_uid = st.st_uid;
1701 ctladdr->q_gid = st.st_gid;
1702 ctladdr->q_flags |= QGOODUID;
1704 if (ca != NULL && ca->q_uid == st.st_uid)
1706 /* optimization -- avoid getpwuid if we already have info */
1707 ctladdr->q_flags |= ca->q_flags & QBOGUSSHELL;
1708 ctladdr->q_ruser = ca->q_ruser;
1710 else if (!forwarding)
1712 register struct passwd *pw;
1714 pw = sm_getpwuid(st.st_uid);
1717 ctladdr->q_uid = st.st_uid;
1718 ctladdr->q_flags |= QBOGUSSHELL;
1724 ctladdr->q_ruser = sm_rpool_strdup_x(e->e_rpool,
1729 sh = "/SENDMAIL/ANY/SHELL/";
1730 if (!usershellok(pw->pw_name, sh))
1733 sm_syslog(LOG_INFO, e->e_id,
1734 "%s: user %s has bad shell %s, marked %s",
1735 shortenstring(fname,
1738 safechown ? "bogus" : "unsafe");
1740 ctladdr->q_flags |= QBOGUSSHELL;
1742 ctladdr->q_flags |= QUNSAFEADDR;
1747 if (bitset(EF_VRFYONLY, e->e_flags))
1749 /* don't do any more now */
1750 ctladdr->q_state = QS_VERIFIED;
1752 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1757 ** Check to see if some bad guy can write this file
1759 ** Group write checking could be more clever, e.g.,
1760 ** guessing as to which groups are actually safe ("sys"
1761 ** may be; "user" probably is not).
1765 if (!bitnset((forwarding ?
1766 DBS_GROUPWRITABLEFORWARDFILESAFE :
1767 DBS_GROUPWRITABLEINCLUDEFILESAFE),
1771 if (bitset(mode, st.st_mode))
1774 sm_dprintf("include: %s is %s writable, marked unsafe\n",
1775 shortenstring(fname, MAXSHORTSTR),
1776 bitset(S_IWOTH, st.st_mode) ? "world"
1779 sm_syslog(LOG_INFO, e->e_id,
1780 "%s: %s writable %s file, marked unsafe",
1781 shortenstring(fname, MAXSHORTSTR),
1782 bitset(S_IWOTH, st.st_mode) ? "world" : "group",
1783 forwarding ? "forward" : ":include:");
1784 ctladdr->q_flags |= QUNSAFEADDR;
1787 /* read the file -- each line is a comma-separated list. */
1790 ctladdr->q_flags &= ~QSELFREF;
1792 while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, sizeof buf) != NULL &&
1797 if (buf[0] == '#' || buf[0] == '\0')
1800 /* <sp>#@# introduces a comment anywhere */
1801 /* for Japanese character sets */
1802 for (p = buf; (p = strchr(++p, '#')) != NULL; )
1804 if (p[1] == '@' && p[2] == '#' &&
1805 isascii(p[-1]) && isspace(p[-1]) &&
1806 (p[3] == '\0' || (isascii(p[3]) && isspace(p[3]))))
1809 while (p > buf && isascii(p[-1]) &&
1821 forwarding ? "forwarding" : "sending", buf);
1822 if (forwarding && LogLevel > 10)
1823 sm_syslog(LOG_INFO, e->e_id,
1824 "forward %.200s => %s",
1825 oldto, shortenstring(buf, MAXSHORTSTR));
1827 nincludes += sendtolist(buf, ctladdr, sendq, aliaslevel + 1, e);
1830 MaxForwardEntries > 0 &&
1831 nincludes >= MaxForwardEntries)
1833 /* just stop reading and processing further entries */
1835 /* additional: (?) */
1836 ctladdr->q_state = QS_DONTSEND;
1839 syserr("Attempt to forward to more than %d addresses (in %s)!",
1840 MaxForwardEntries, fname);
1845 if (sm_io_error(fp) && tTd(27, 3))
1846 sm_dprintf("include: read error: %s\n", sm_errstring(errno));
1847 if (nincludes > 0 && !bitset(QSELFREF, ctladdr->q_flags))
1851 sm_dprintf("include: QS_DONTSEND ");
1852 printaddr(ctladdr, false);
1854 ctladdr->q_state = QS_DONTSEND;
1857 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1858 FileName = oldfilename;
1859 LineNumber = oldlinenumber;
1868 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
1869 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
1874 longjmp(CtxIncludeTimeout, 1);
1877 ** SENDTOARGV -- send to an argument vector.
1880 ** argv -- argument vector to send to.
1881 ** e -- the current envelope.
1887 ** puts all addresses on the argument vector onto the
1893 register char **argv;
1894 register ENVELOPE *e;
1898 while ((p = *argv++) != NULL)
1899 (void) sendtolist(p, NULLADDR, &e->e_sendqueue, 0, e);
1902 ** GETCTLADDR -- get controlling address from an address header.
1904 ** If none, get one corresponding to the effective userid.
1907 ** a -- the address to find the controller of.
1910 ** the controlling address.
1915 register ADDRESS *a;
1917 while (a != NULL && !bitset(QGOODUID, a->q_flags))
1922 ** SELF_REFERENCE -- check to see if an address references itself
1924 ** The check is done through a chain of aliases. If it is part of
1925 ** a loop, break the loop at the "best" address, that is, the one
1926 ** that exists as a real user.
1928 ** This is to handle the case of:
1929 ** awc: Andrew.Chang
1930 ** Andrew.Chang: awc@mail.server
1931 ** which is a problem only on mail.server.
1934 ** a -- the address to check.
1937 ** The address that should be retained.
1944 ADDRESS *b; /* top entry in self ref loop */
1945 ADDRESS *c; /* entry that point to a real mail box */
1948 sm_dprintf("self_reference(%s)\n", a->q_paddr);
1950 for (b = a->q_alias; b != NULL; b = b->q_alias)
1959 sm_dprintf("\t... no self ref\n");
1964 ** Pick the first address that resolved to a real mail box
1965 ** i.e has a mbdb entry. The returned value will be marked
1966 ** QSELFREF in recipient(), which in turn will disable alias()
1967 ** from marking it as QS_IS_DEAD(), which mean it will be used
1968 ** as a deliverable address.
1970 ** The 2 key thing to note here are:
1971 ** 1) we are in a recursive call sequence:
1972 ** alias->sendtolist->recipient->alias
1973 ** 2) normally, when we return back to alias(), the address
1974 ** will be marked QS_EXPANDED, since alias() assumes the
1975 ** expanded form will be used instead of the current address.
1976 ** This behaviour is turned off if the address is marked
1977 ** QSELFREF. We set QSELFREF when we return to recipient().
1984 sm_dprintf(" %s", c->q_user);
1985 if (bitnset(M_HASPWENT, c->q_mailer->m_flags))
1990 sm_dprintf("\t... getpwnam(%s)... ", c->q_user);
1991 if (sm_mbdb_lookup(c->q_user, &user) == EX_OK)
1994 sm_dprintf("found\n");
1996 /* ought to cache results here */
2003 sm_dprintf("failed\n");
2007 /* if local delivery, compare usernames */
2008 if (bitnset(M_LOCALMAILER, c->q_mailer->m_flags) &&
2009 b->q_mailer == c->q_mailer)
2012 sm_dprintf("\t... local match (%s)\n",
2026 sm_dprintf("\t... cannot break loop for \"%s\"\n", a->q_paddr);