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