2 * Copyright (c) 1998-2003 Proofpoint, Inc. and its suppliers.
4 * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.
5 * Copyright (c) 1988, 1993
6 * The Regents of the University of California. All rights reserved.
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
16 SM_RCSID("@(#)$Id: alias.c,v 8.221 2013-11-22 20:51:54 ca Exp $")
18 #include <sm/sendmail.h>
21 # define ALIAS_SPEC_SEPARATORS " ,/:"
23 static MAP *AliasFileMap = NULL; /* the actual aliases.files map */
24 static int NAliasFileMaps; /* the number of entries in AliasFileMap */
26 static char *aliaslookup __P((char *, int *, char *));
29 ** ALIAS -- Compute aliases.
31 ** Scans the alias file for an alias for the given address.
32 ** If found, it arranges to deliver to the alias list instead.
33 ** Uses libdbm database if -DDBM.
36 ** a -- address to alias.
37 ** sendq -- a pointer to the head of the send queue
38 ** to put the aliases in.
39 ** aliaslevel -- the current alias nesting depth.
40 ** e -- the current envelope.
46 ** Aliases found are expanded.
49 ** It should complain about names that are aliased to
54 alias(a, sendq, aliaslevel, e)
62 auto int status = EX_OK;
63 char obuf[MAXNAME_I + 7];
66 sm_dprintf("alias(%s)\n", a->q_user);
68 /* don't realias already aliased names */
69 if (!QS_IS_OK(a->q_state))
80 ** If the map was unavailable, we will queue this message
81 ** until the map becomes available; otherwise, we could
82 ** bounce messages inappropriately.
85 #if _FFR_REDIRECTEMPTY
87 ** envelope <> can't be sent to mailing lists, only owner-
88 ** send spam of this type to owner- of the list
89 ** ---- to stop spam from going to mailing lists!
92 if (e->e_sender != NULL && *e->e_sender == '\0')
94 /* Look for owner of alias */
95 (void) sm_strlcpyn(obuf, sizeof(obuf), 2, "owner-", a->q_user);
96 if (aliaslookup(obuf, &status, a->q_host) != NULL)
99 sm_syslog(LOG_WARNING, e->e_id,
100 "possible spam from <> to list: %s, redirected to %s\n",
102 a->q_user = sm_rpool_strdup_x(e->e_rpool, obuf);
105 #endif /* _FFR_REDIRECTEMPTY */
107 p = aliaslookup(a->q_user, &status, a->q_host);
108 if (status == EX_TEMPFAIL || status == EX_UNAVAILABLE)
110 a->q_state = QS_QUEUEUP;
111 if (e->e_message == NULL)
112 e->e_message = sm_rpool_strdup_x(e->e_rpool,
113 "alias database unavailable");
115 /* XXX msg only per recipient? */
116 if (a->q_message == NULL)
117 a->q_message = "alias database unavailable";
125 ** Deliver to the target list.
129 sm_dprintf("%s (%s, %s) aliased to %s\n",
130 a->q_paddr, a->q_host, a->q_user, p);
131 if (bitset(EF_VRFYONLY, e->e_flags))
133 a->q_state = QS_VERIFIED;
136 message("aliased to %s", shortenstring(p, MAXSHORTSTR));
138 sm_syslog(LOG_INFO, e->e_id,
139 "alias %.100s => %s",
140 a->q_paddr, shortenstring(p, MAXSHORTSTR));
141 a->q_flags &= ~QSELFREF;
144 sm_dprintf("alias: QS_EXPANDED ");
145 printaddr(sm_debug_file(), a, false);
147 a->q_state = QS_EXPANDED;
150 ** Always deliver aliased items as the default user.
151 ** Setting q_gid to 0 forces deliver() to use DefUser
152 ** instead of the alias name for the call to initgroups().
157 a->q_fullname = NULL;
158 a->q_flags |= QGOODUID|QALIAS;
160 (void) sendtolist(p, a, sendq, aliaslevel + 1, e);
162 if (bitset(QSELFREF, a->q_flags) && QS_IS_EXPANDED(a->q_state))
166 ** Look for owner of alias
169 if (strncmp(a->q_user, "owner-", 6) == 0 ||
170 strlen(a->q_user) > sizeof(obuf) - 7)
171 (void) sm_strlcpy(obuf, "owner-owner", sizeof(obuf));
173 (void) sm_strlcpyn(obuf, sizeof(obuf), 2, "owner-", a->q_user);
174 owner = aliaslookup(obuf, &status, a->q_host);
178 /* reflect owner into envelope sender */
179 if (strpbrk(owner, ",:/|\"") != NULL)
181 a->q_owner = sm_rpool_strdup_x(e->e_rpool, owner);
183 /* announce delivery to this alias; NORECEIPT bit set later */
184 if (e->e_xfp != NULL)
185 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
186 "Message delivered to mailing list %s\n",
188 e->e_flags |= EF_SENDRECEIPT;
189 a->q_flags |= QDELIVERED|QEXPANDED;
193 ** ALIASLOOKUP -- look up a name in the alias file.
196 ** name -- the name to look up [i]
197 ** pstat -- a pointer to a place to put the status.
198 ** av -- argument for %1 expansion.
201 ** the value of name.
205 ** The return value will be trashed across calls.
209 aliaslookup(name, pstat, av)
214 static MAP *map = NULL;
216 #if _FFR_ALIAS_DETAIL
223 char buf[MAXNAME]; /* EAI:ok */
228 STAB *s = stab("aliases", ST_MAP, ST_FIND);
236 /* special case POstMastER -- always use lower case */
237 if (SM_STRCASEEQ(name, "postmaster"))
240 (void) dequote_internal_chars(name, buf, sizeof(buf));
243 #endif /* _FFR_8BITENVADDR */
245 #if _FFR_ALIAS_DETAIL
250 /* XXX '+' is hardwired here as delimiter! */
251 if (av != NULL && *av == '+')
254 #endif /* _FFR_ALIAS_DETAIL */
255 res = (*map->map_class->map_lookup)(map, name, argv, pstat);
257 /* map_lookup() does a map_rewrite(), so no quoting here */
263 ** SETALIAS -- set up an alias map
265 ** Called when reading configuration file.
268 ** spec -- the alias specification
284 sm_dprintf("setalias(%s)\n", spec);
286 for (p = spec; p != NULL; )
290 while (SM_ISSPACE(*p))
296 if (NAliasFileMaps >= MAXMAPSTACK)
298 syserr("Too many alias databases defined, %d max",
302 if (AliasFileMap == NULL)
304 (void) sm_strlcpy(buf, "aliases.files sequence",
306 AliasFileMap = makemapentry(buf);
307 if (AliasFileMap == NULL)
309 syserr("setalias: cannot create aliases.files map");
313 (void) sm_snprintf(buf, sizeof(buf), "Alias%d", NAliasFileMaps);
314 s = stab(buf, ST_MAP, ST_ENTER);
316 memset(map, '\0', sizeof(*map));
317 map->map_mname = s->s_name;
318 p = strpbrk(p, ALIAS_SPEC_SEPARATORS);
319 if (p != NULL && *p == SEPARATOR)
329 map->map_mflags = MF_INCLNULL;
332 /* find end of spec */
337 for (; *p != '\0'; p++)
340 ** Don't break into a quoted string.
341 ** Needed for ldap maps which use
342 ** commas in their specifications.
347 else if (*p == ',' && !quoted)
351 /* No more alias specifications follow */
359 sm_dprintf(" map %s:%s %s\n", class, s->s_name, spec);
362 s = stab(class, ST_MAPCLASS, ST_FIND);
365 syserr("setalias: unknown alias class %s", class);
367 else if (!bitset(MCF_ALIASOK, s->s_mapclass.map_cflags))
369 syserr("setalias: map class %s can't handle aliases",
374 map->map_class = &s->s_mapclass;
375 map->map_mflags |= MF_ALIAS;
376 if (map->map_class->map_parse(map, spec))
378 map->map_mflags |= MF_VALID;
379 AliasFileMap->map_stack[NAliasFileMaps++] = map;
386 ** ALIASWAIT -- wait for distinguished @:@ token to appear.
388 ** This can decide to reopen the alias file
391 ** map -- a pointer to the map descriptor for this alias file.
392 ** ext -- the filename extension (e.g., ".db") for the
394 ** isopen -- if set, the database is already open, and we
395 ** should check for validity; otherwise, we are
396 ** just checking to see if it should be created.
399 ** true -- if the database is open when we return.
400 ** false -- if the database is closed when we return.
404 aliaswait(map, ext, isopen)
409 bool attimeout = false;
412 char buf[MAXPATHLEN];
415 sm_dprintf("aliaswait(%s:%s), open=%d, wait=%d\n",
416 map->map_class->map_cname, map->map_file,
417 isopen, bitset(MF_ALIASWAIT, map->map_mflags));
418 if (bitset(MF_ALIASWAIT, map->map_mflags))
420 map->map_mflags |= MF_ALIASWAIT;
422 if (isopen && SafeAlias > 0)
425 unsigned int sleeptime = 2;
426 unsigned int loopcount = 0; /* only used for debugging */
427 time_t toolong = curtime() + SafeAlias;
430 map->map_class->map_lookup(map, "@", NULL, &st) == NULL)
432 if (curtime() > toolong)
440 ** Close and re-open the alias database in case
441 ** the one is mv'ed instead of cp'ed in.
447 sm_dprintf("aliaswait: sleeping for %u seconds (loopcount = %u)\n",
448 sleeptime, loopcount);
451 map->map_mflags |= MF_CLOSING;
452 map->map_class->map_close(map);
453 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING|MF_CHKED_CHGD);
454 (void) sleep(sleeptime);
458 isopen = map->map_class->map_open(map, O_RDONLY);
461 map->map_mflags &= ~MF_CHKED_CHGD;
463 /* see if we need to go into auto-rebuild mode */
464 if (!bitset(MCF_REBUILDABLE, map->map_class->map_cflags))
467 sm_dprintf("aliaswait: not rebuildable\n");
468 map->map_mflags &= ~MF_ALIASWAIT;
471 if (stat(map->map_file, &stb) < 0)
474 sm_dprintf("aliaswait: no source file\n");
475 map->map_mflags &= ~MF_ALIASWAIT;
478 mtime = stb.st_mtime;
479 if (sm_strlcpyn(buf, sizeof(buf), 2,
480 map->map_file, ext == NULL ? "" : ext) >= sizeof(buf))
483 sm_syslog(LOG_INFO, NOQID,
484 "alias database %s%s name too long",
485 map->map_file, ext == NULL ? "" : ext);
486 message("alias database %s%s name too long",
487 map->map_file, ext == NULL ? "" : ext);
490 if (stat(buf, &stb) < 0 || stb.st_mtime < mtime || attimeout)
493 sm_syslog(LOG_INFO, NOQID,
494 "alias database %s out of date", buf);
495 message("Warning: alias database %s out of date", buf);
497 map->map_mflags &= ~MF_ALIASWAIT;
501 ** REBUILDALIASES -- rebuild the alias database.
504 ** map -- the database to rebuild.
507 ** true if successful; false otherwise.
510 ** Reads the text version of the database, builds the map.
519 bool success = false;
520 long sff = SFF_OPENASROOT|SFF_REGONLY|SFF_NOLOCK;
521 sigfunc_t oldsigint, oldsigquit;
523 sigfunc_t oldsigtstp;
526 if (!bitset(MCF_REBUILDABLE, map->map_class->map_cflags))
529 if (!bitnset(DBS_LINKEDALIASFILEINWRITABLEDIR, DontBlameSendmail))
531 if (!bitnset(DBS_GROUPWRITABLEALIASFILE, DontBlameSendmail))
532 sff |= SFF_NOGWFILES;
533 if (!bitnset(DBS_WORLDWRITABLEALIASFILE, DontBlameSendmail))
534 sff |= SFF_NOWWFILES;
536 /* try to lock the source file */
537 if ((af = safefopen(map->map_file, O_RDWR, 0, sff)) == NULL)
541 if ((errno != EACCES && errno != EROFS) ||
542 (af = safefopen(map->map_file, O_RDONLY, 0, sff)) == NULL)
547 sm_dprintf("Can't open %s: %s\n",
548 map->map_file, sm_errstring(saveerr));
549 if (!bitset(MF_OPTIONAL, map->map_mflags))
550 message("newaliases: cannot open %s: %s",
551 map->map_file, sm_errstring(saveerr));
557 fstat(sm_io_getinfo(af, SM_IO_WHAT_FD, NULL), &stb) < 0 ||
558 bitset(S_IWUSR|S_IWGRP|S_IWOTH, stb.st_mode))
559 message("warning: cannot lock %s: %s",
560 map->map_file, sm_errstring(errno));
563 /* see if someone else is rebuilding the alias file */
565 !lockfile(sm_io_getinfo(af, SM_IO_WHAT_FD, NULL), map->map_file,
566 NULL, LOCK_EX|LOCK_NB))
568 /* yes, they are -- wait until done */
569 message("Alias file %s is locked (maybe being rebuilt)",
571 if (OpMode != MD_INITALIAS)
573 /* wait for other rebuild to complete */
574 (void) lockfile(sm_io_getinfo(af, SM_IO_WHAT_FD, NULL),
575 map->map_file, NULL, LOCK_EX);
577 (void) sm_io_close(af, SM_TIME_DEFAULT);
582 oldsigint = sm_signal(SIGINT, SIG_IGN);
583 oldsigquit = sm_signal(SIGQUIT, SIG_IGN);
585 oldsigtstp = sm_signal(SIGTSTP, SIG_IGN);
588 if (map->map_class->map_open(map, O_RDWR))
592 sm_syslog(LOG_NOTICE, NOQID,
593 "alias database %s rebuilt by %s",
594 map->map_file, username());
596 map->map_mflags |= MF_OPEN|MF_WRITABLE;
597 map->map_pid = CurrentPid;
598 readaliases(map, af, true, true);
604 sm_dprintf("Can't create database for %s: %s\n",
605 map->map_file, sm_errstring(errno));
606 syserr("Cannot create database for alias file %s",
610 /* close the file, thus releasing locks */
611 (void) sm_io_close(af, SM_TIME_DEFAULT);
613 /* add distinguished entries and close the database */
614 if (bitset(MF_OPEN, map->map_mflags))
621 sl = tTdlevel(78) - 100;
622 sm_dprintf("rebuildaliases: sleep=%d, file=%s\n",
625 sm_dprintf("rebuildaliases: done\n");
628 map->map_mflags |= MF_CLOSING;
629 map->map_class->map_close(map);
630 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
633 /* restore the old signals */
634 (void) sm_signal(SIGINT, oldsigint);
635 (void) sm_signal(SIGQUIT, oldsigquit);
637 (void) sm_signal(SIGTSTP, oldsigtstp);
643 ** CONTLINE -- handle potential continuation line
646 ** fp -- file to read
647 ** line -- current line
650 ** pointer to end of current line if there is a continuation line
654 ** Modifies line if it is a continuation line
657 static char *contline __P((SM_FILE_T *, char *));
666 if ((p = strchr(line, '\n')) != NULL && p > line && p[-1] == '\\')
673 c = sm_io_getc(fp, SM_TIME_DEFAULT);
675 (void) sm_io_ungetc(fp, SM_TIME_DEFAULT, c);
676 if (c == ' ' || c == '\t')
682 if (nlp > p && nlp[-1] == '\n')
690 ** READALIASES -- read and process the alias file.
692 ** This routine implements the part of initaliases that occurs
693 ** when we are not going to use the DBM stuff.
696 ** map -- the alias database descriptor.
697 ** af -- file to read the aliases from.
698 ** announcestats -- announce statistics regarding number of
699 ** aliases, longest alias, etc.
700 ** logstats -- lot the same info.
706 ** Reads aliasfile into the symbol table.
707 ** Optionally, builds the .dir & .pag files.
711 readaliases(map, af, announcestats, logstats)
720 long naliases, bytes, longest;
725 char lhsbuf[MAXNAME]; /* EAI:ok */
731 ** Read and interpret lines
734 FileName = map->map_file;
736 naliases = bytes = longest = 0;
740 while (sm_io_fgets(af, SM_TIME_DEFAULT, lbuf, sizeof(lbuf)) >= 0)
742 int lhssize, rhssize;
748 /* XXX what if line="a\\" ? */
751 while ((newp = contline(af, line)) != NULL)
754 if ((c = sm_io_fgets(af, SM_TIME_DEFAULT, p,
755 SPACELEFT(lbuf, p))) < 0)
762 if (SMTP_UTF8 || EightBitAddrOK)
766 line = quote_internal_chars(lbuf, NULL, &len, NULL);
770 /* "else" in #if code above */
773 p = strchr(line, '\n');
776 else if (!sm_io_eof(af))
782 syserr("554 5.3.0 alias line too long");
788 /* flush to end of "virtual" line */
789 while ((c = sm_io_getc(af, SM_TIME_DEFAULT)) !=
790 SM_IO_EOF && c != '\n')
794 cl = ('\\' == prev && '\n' == c);
797 c = sm_io_getc(af, SM_TIME_DEFAULT);
799 (void) sm_io_ungetc(af, SM_TIME_DEFAULT, c);
800 cl = (c == ' ' || c == '\t');
817 syserr("554 5.3.5 Non-continuation line starts with space");
825 ** Find the colon separator, and parse the address.
826 ** It should resolve to a local name -- this will
827 ** be checked later (we want to optionally do
828 ** parsing of the RHS first to maximize error
832 for (p = line; *p != '\0' && *p != ':' && *p != '\n'; p++)
836 syserr("554 5.3.5 missing colon");
839 /* XXX line must be [i] */
840 if (parseaddr(line, &al, RF_COPYALL, ':', NULL, CurEnv, true)
843 syserr("554 5.3.5 %.40s... illegal alias name", line);
849 ** 'al' is the internal form of the LHS address.
850 ** 'p' points to the text of the RHS.
853 while (SM_ISSPACE(*p))
860 if (nlp > p && nlp[-1] == '\n')
865 /* do parsing & compression of addresses */
870 while ((SM_ISSPACE(*p)) || *p == ',')
874 /* XXX p must be [i] */
875 if (parseaddr(p, &bl, RF_COPYNONE, ',',
876 &delimptr, CurEnv, true)
878 usrerr("553 5.3.5 %s... bad address", p);
891 if (!bitnset(M_ALIASABLE, al.q_mailer->m_flags))
893 syserr("554 5.3.5 %s... cannot alias non-local names",
899 ** Insert alias into symbol table or database file.
901 ** Special case pOStmaStER -- always make it lower case.
904 if (SM_STRCASEEQ(al.q_user, "postmaster"))
905 makelower_a(&al.q_user, CurEnv->e_rpool);
907 lhssize = strlen(al.q_user);
908 rhssize = strlen(rhs);
911 /* is RHS empty (just spaces)? */
913 while (SM_ISSPACE(*p))
916 if (rhssize == 0 || *p == '\0')
918 syserr("554 5.3.5 %.40s... missing value for alias",
924 if (SMTP_UTF8 || EightBitAddrOK)
926 dequote_internal_chars(al.q_user, lhsbuf, sizeof(lhsbuf));
927 dequote_internal_chars(rhs, rhsbuf, sizeof(rhsbuf));
928 map->map_class->map_store(map, lhsbuf, rhsbuf);
932 /* "else" in #if code above */
933 map->map_class->map_store(map, al.q_user, rhs);
937 bytes += lhssize + rhssize;
938 if (rhssize > longest)
945 if (Verbose || announcestats)
946 message("%s: %ld aliases, longest %ld bytes, %ld bytes total",
947 map->map_file, naliases, longest, bytes);
948 if (LogLevel > 7 && logstats)
949 sm_syslog(LOG_INFO, NOQID,
950 "%s: %ld aliases, longest %ld bytes, %ld bytes total",
951 map->map_file, naliases, longest, bytes);
954 ** FORWARD -- Try to forward mail
956 ** This is similar but not identical to aliasing.
959 ** user -- the name of the user who's mail we would like
960 ** to forward to. It must have been verified --
961 ** i.e., the q_home field must have been filled in.
962 ** sendq -- a pointer to the head of the send queue to
963 ** put this user's aliases in.
964 ** aliaslevel -- the current alias nesting depth.
965 ** e -- the current envelope.
971 ** New names are added to send queues.
975 forward(user, sendq, aliaslevel, e)
979 register ENVELOPE *e;
986 sm_dprintf("forward(%s)\n", user->q_paddr);
988 if (!bitnset(M_HASPWENT, user->q_mailer->m_flags) ||
989 !QS_IS_OK(user->q_state))
991 if (ForwardPath != NULL && *ForwardPath == '\0')
993 if (user->q_home == NULL)
995 syserr("554 5.3.0 forward: no home");
996 user->q_home = "/no/such/directory";
999 /* good address -- look for .forward file in home */
1000 macdefine(&e->e_macro, A_PERM, 'z', user->q_home);
1001 macdefine(&e->e_macro, A_PERM, 'u', user->q_user);
1003 #if _FFR_8BITENVADDR
1008 pp = quote_internal_chars(pp, NULL, &len, NULL);
1011 macdefine(&e->e_macro, A_PERM, 'h', pp);
1012 if (ForwardPath == NULL)
1013 ForwardPath = newstr("\201z/.forward");
1015 got_transient = false;
1016 for (pp = ForwardPath; pp != NULL; pp = ep)
1019 char buf[MAXPATHLEN];
1022 ep = strchr(pp, SEPARATOR);
1025 expand(pp, buf, sizeof(buf), e);
1031 sm_dprintf("forward: trying %s\n", buf);
1033 err = include(buf, true, user, sendq, aliaslevel, e);
1036 else if (transienterror(err))
1038 /* we may have to suspend this message */
1039 got_transient = true;
1041 sm_dprintf("forward: transient error on %s\n",
1045 char *curhost = CurHostName;
1048 sm_syslog(LOG_ERR, e->e_id,
1049 "forward %s: transient error: %s",
1050 buf, sm_errstring(err));
1051 CurHostName = curhost;
1064 /* check if it even exists */
1065 if (stat(buf, &st) < 0 && errno == ENOENT)
1067 if (bitnset(DBS_DONTWARNFORWARDFILEINUNSAFEDIRPATH,
1073 #if _FFR_FORWARD_SYSERR
1080 syserr("forward: %s: %s", buf, sm_errstring(err));
1082 #endif /* _FFR_FORWARD_SYSERR */
1085 if (LogLevel > (RunAsUid == 0 ? 2 : 10))
1086 sm_syslog(LOG_WARNING, e->e_id,
1087 "forward %s: %s", buf,
1090 message("forward: %s: %s",
1091 buf, sm_errstring(err));
1096 if (pp == NULL && got_transient)
1099 ** There was no successful .forward open and at least one
1100 ** transient open. We have to defer this address for
1101 ** further delivery.
1104 message("transient .forward open error: message queued");
1105 user->q_state = QS_QUEUEUP;