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