2 * Copyright (c) 1998-2005 Sendmail, Inc. and its suppliers.
4 * Copyright (c) 1992, 1995-1997 Eric P. Allman. All rights reserved.
5 * Copyright (c) 1992, 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: map.c,v 8.669 2005/02/09 01:46:35 ca Exp $")
25 ERROR README: You are running the Berkeley DB version of ndbm.h. See
26 ERROR README: the README file about tweaking Berkeley DB so it can
27 ERROR README: coexist with NDBM, or delete -DNDBM from the Makefile
28 ERROR README: and use -DNEWDB instead.
35 struct dom_binding; /* forward reference needed on IRIX */
36 # include <rpcsvc/ypclnt.h>
38 # define NDBM_YP_COMPAT /* create YP-compatible NDBM files */
43 # if DB_VERSION_MAJOR < 2
44 static bool db_map_open __P((MAP *, int, char *, DBTYPE, const void *));
45 # endif /* DB_VERSION_MAJOR < 2 */
46 # if DB_VERSION_MAJOR == 2
47 static bool db_map_open __P((MAP *, int, char *, DBTYPE, DB_INFO *));
48 # endif /* DB_VERSION_MAJOR == 2 */
49 # if DB_VERSION_MAJOR > 2
50 static bool db_map_open __P((MAP *, int, char *, DBTYPE, void **));
51 # endif /* DB_VERSION_MAJOR > 2 */
53 static bool extract_canonname __P((char *, char *, char *, char[], int));
54 static void map_close __P((STAB *, int));
55 static void map_init __P((STAB *, int));
57 static STAB * ldapmap_findconn __P((SM_LDAP_STRUCT *));
60 static bool nisplus_getcanonname __P((char *, int, int *));
63 static bool nis_getcanonname __P((char *, int, int *));
66 static bool ni_getcanonname __P((char *, int, int *));
68 static bool text_getcanonname __P((char *, int, int *));
70 static STAB *socket_map_findconn __P((const char*));
72 /* XXX arbitrary limit for sanity */
73 # define SOCKETMAP_MAXL 1000000
74 #endif /* SOCKETMAP */
76 /* default error message for trying to open a map in write mode */
78 # define SM_EMAPCANTWRITE ENOSYS
81 # define SM_EMAPCANTWRITE EFTYPE
83 # define SM_EMAPCANTWRITE ENXIO
88 ** MAP.C -- implementations for various map classes.
90 ** Each map class implements a series of functions:
92 ** bool map_parse(MAP *map, char *args)
93 ** Parse the arguments from the config file. Return true
94 ** if they were ok, false otherwise. Fill in map with the
97 ** char *map_lookup(MAP *map, char *key, char **args, int *pstat)
98 ** Look up the key in the given map. If found, do any
99 ** rewriting the map wants (including "args" if desired)
100 ** and return the value. Set *pstat to the appropriate status
101 ** on error and return NULL. Args will be NULL if called
102 ** from the alias routines, although this should probably
103 ** not be relied upon. It is suggested you call map_rewrite
104 ** to return the results -- it takes care of null termination
105 ** and uses a dynamically expanded buffer as needed.
107 ** void map_store(MAP *map, char *key, char *value)
108 ** Store the key:value pair in the map.
110 ** bool map_open(MAP *map, int mode)
111 ** Open the map for the indicated mode. Mode should
112 ** be either O_RDONLY or O_RDWR. Return true if it
113 ** was opened successfully, false otherwise. If the open
114 ** failed and the MF_OPTIONAL flag is not set, it should
115 ** also print an error. If the MF_ALIAS bit is set
116 ** and this map class understands the @:@ convention, it
117 ** should call aliaswait() before returning.
119 ** void map_close(MAP *map)
122 ** This file also includes the implementation for getcanonname.
123 ** It is currently implemented in a pretty ad-hoc manner; it ought
124 ** to be more properly integrated into the map structure.
127 #if O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL
128 # define LOCK_ON_OPEN 1 /* we can open/create a locked file */
129 #else /* O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL */
130 # define LOCK_ON_OPEN 0 /* no such luck -- bend over backwards */
131 #endif /* O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL */
134 ** MAP_PARSEARGS -- parse config line arguments for database lookup
136 ** This is a generic version of the map_parse method.
139 ** map -- the map being initialized.
140 ** ap -- a pointer to the args on the config line.
143 ** true -- if everything parsed OK.
144 ** false -- otherwise.
147 ** null terminates the filename; stores it in map
151 map_parseargs(map, ap)
155 register char *p = ap;
158 ** There is no check whether there is really an argument,
159 ** but that's not important enough to warrant extra code.
162 map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL;
163 map->map_spacesub = SpaceSub; /* default value */
166 while (isascii(*p) && isspace(*p))
173 map->map_mflags |= MF_INCLNULL;
174 map->map_mflags &= ~MF_TRY0NULL;
178 map->map_mflags &= ~MF_TRY1NULL;
182 map->map_mflags |= MF_OPTIONAL;
186 map->map_mflags |= MF_NOFOLDCASE;
190 map->map_mflags |= MF_MATCHONLY;
194 map->map_mflags |= MF_APPEND;
198 map->map_mflags |= MF_KEEPQUOTES;
210 while (isascii(*++p) && isspace(*p))
212 map->map_keycolnm = p;
216 while (isascii(*++p) && isspace(*p))
218 map->map_valcolnm = p;
223 map->map_coldelim = *p;
229 map->map_coldelim = '\n';
233 map->map_coldelim = '\t';
237 map->map_coldelim = '\\';
243 map->map_mflags |= MF_NODEFER;
248 map->map_spacesub = *++p;
252 map->map_mflags |= MF_DEFER;
256 syserr("Illegal option %c map %s", *p, map->map_mname);
259 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
264 if (map->map_app != NULL)
265 map->map_app = newstr(map->map_app);
266 if (map->map_tapp != NULL)
267 map->map_tapp = newstr(map->map_tapp);
268 if (map->map_keycolnm != NULL)
269 map->map_keycolnm = newstr(map->map_keycolnm);
270 if (map->map_valcolnm != NULL)
271 map->map_valcolnm = newstr(map->map_valcolnm);
276 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
280 map->map_file = newstr(map->map_file);
283 while (*p != '\0' && isascii(*p) && isspace(*p))
286 map->map_rebuild = newstr(p);
288 if (map->map_file == NULL &&
289 !bitset(MCF_OPTFILE, map->map_class->map_cflags))
291 syserr("No file name for %s map %s",
292 map->map_class->map_cname, map->map_mname);
298 ** MAP_REWRITE -- rewrite a database key, interpolating %n indications.
300 ** It also adds the map_app string. It can be used as a utility
301 ** in the map_lookup method.
304 ** map -- the map that causes this.
305 ** s -- the string to rewrite, NOT necessarily null terminated.
306 ** slen -- the length of s.
307 ** av -- arguments to interpolate into buf.
310 ** Pointer to rewritten result. This is static data that
311 ** should be copied if it is to be saved!
315 map_rewrite(map, s, slen, av)
317 register const char *s;
327 static size_t buflen = 0;
328 static char *buf = NULL;
332 sm_dprintf("map_rewrite(%.*s), av =", (int) slen, s);
334 sm_dprintf(" (nullv)");
337 for (avp = av; *avp != NULL; avp++)
338 sm_dprintf("\n\t%s", *avp);
343 /* count expected size of output (can safely overestimate) */
349 while (l-- > 0 && (c = *sp++) != '\0')
356 if (!(isascii(c) && isdigit(c)))
358 for (avp = av; --c >= '0' && *avp != NULL; avp++)
365 if (map->map_app != NULL)
366 len += strlen(map->map_app);
369 /* need to malloc additional space */
373 buf = sm_pmalloc_x(buflen);
379 memmove(bp, s, slen);
382 /* assert(len > slen); */
387 while (slen-- > 0 && (c = *s++) != '\0')
397 if (slen-- <= 0 || (c = *s++) == '\0')
401 if (!(isascii(c) && isdigit(c)))
408 for (avp = av; --c >= '0' && *avp != NULL; avp++)
413 /* transliterate argument into output string */
414 for (ap = *avp; (c = *ap++) != '\0' && len > 0; --len)
418 if (map->map_app != NULL && len > 0)
419 (void) sm_strlcpy(bp, map->map_app, len);
423 sm_dprintf("map_rewrite => %s\n", buf);
427 ** INITMAPS -- rebuild alias maps
440 checkfd012("entering initmaps");
442 stabapply(map_init, 0);
444 checkfd012("exiting initmaps");
448 ** MAP_INIT -- rebuild a map
451 ** s -- STAB entry: if map: try to rebuild
452 ** unused -- unused variable
458 ** will close already open rebuildable map.
469 /* has to be a map */
470 if (s->s_symtype != ST_MAP)
474 if (!bitset(MF_VALID, map->map_mflags))
478 sm_dprintf("map_init(%s:%s, %s)\n",
479 map->map_class->map_cname == NULL ? "NULL" :
480 map->map_class->map_cname,
481 map->map_mname == NULL ? "NULL" : map->map_mname,
482 map->map_file == NULL ? "NULL" : map->map_file);
484 if (!bitset(MF_ALIAS, map->map_mflags) ||
485 !bitset(MCF_REBUILDABLE, map->map_class->map_cflags))
488 sm_dprintf("\tnot rebuildable\n");
492 /* if already open, close it (for nested open) */
493 if (bitset(MF_OPEN, map->map_mflags))
495 map->map_mflags |= MF_CLOSING;
496 map->map_class->map_close(map);
497 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
500 (void) rebuildaliases(map, false);
504 ** OPENMAP -- open a map
507 ** map -- map to open (it must not be open).
510 ** whether open succeeded.
517 bool restore = false;
518 bool savehold = HoldErrs;
519 bool savequick = QuickAbort;
520 int saveerrors = Errors;
522 if (!bitset(MF_VALID, map->map_mflags))
525 /* better safe than sorry... */
526 if (bitset(MF_OPEN, map->map_mflags))
529 /* Don't send a map open error out via SMTP */
530 if ((OnlyOneError || QuickAbort) &&
531 (OpMode == MD_SMTP || OpMode == MD_DAEMON))
539 if (map->map_class->map_open(map, O_RDONLY))
542 sm_dprintf("openmap()\t%s:%s %s: valid\n",
543 map->map_class->map_cname == NULL ? "NULL" :
544 map->map_class->map_cname,
545 map->map_mname == NULL ? "NULL" :
547 map->map_file == NULL ? "NULL" :
549 map->map_mflags |= MF_OPEN;
550 map->map_pid = CurrentPid;
555 sm_dprintf("openmap()\t%s:%s %s: invalid%s%s\n",
556 map->map_class->map_cname == NULL ? "NULL" :
557 map->map_class->map_cname,
558 map->map_mname == NULL ? "NULL" :
560 map->map_file == NULL ? "NULL" :
562 errno == 0 ? "" : ": ",
563 errno == 0 ? "" : sm_errstring(errno));
564 if (!bitset(MF_OPTIONAL, map->map_mflags))
566 extern MAPCLASS BogusMapClass;
568 map->map_orgclass = map->map_class;
569 map->map_class = &BogusMapClass;
570 map->map_mflags |= MF_OPEN|MF_OPENBOGUS;
571 map->map_pid = CurrentPid;
575 /* don't try again */
576 map->map_mflags &= ~MF_VALID;
584 QuickAbort = savequick;
587 return bitset(MF_OPEN, map->map_mflags);
590 ** CLOSEMAPS -- close all open maps opened by the current pid.
593 ** bogus -- only close bogus maps.
603 stabapply(map_close, bogus);
606 ** MAP_CLOSE -- close a map opened by the current pid.
609 ** s -- STAB entry: if map: try to close
610 ** bogus -- only close bogus maps or MCF_NOTPERSIST maps.
620 int bogus; /* int because of stabapply(), used as bool */
623 extern MAPCLASS BogusMapClass;
625 if (s->s_symtype != ST_MAP)
631 ** close the map iff:
632 ** it is valid and open and opened by this process
633 ** and (!bogus or it's a bogus map or it is not persistent)
634 ** negate this: return iff
635 ** it is not valid or it is not open or not opened by this process
636 ** or (bogus and it's not a bogus map and it's not not-persistent)
639 if (!bitset(MF_VALID, map->map_mflags) ||
640 !bitset(MF_OPEN, map->map_mflags) ||
641 bitset(MF_CLOSING, map->map_mflags) ||
642 map->map_pid != CurrentPid ||
643 (bogus && map->map_class != &BogusMapClass &&
644 !bitset(MCF_NOTPERSIST, map->map_class->map_cflags)))
647 if (map->map_class == &BogusMapClass && map->map_orgclass != NULL &&
648 map->map_orgclass != &BogusMapClass)
649 map->map_class = map->map_orgclass;
651 sm_dprintf("closemaps: closing %s (%s)\n",
652 map->map_mname == NULL ? "NULL" : map->map_mname,
653 map->map_file == NULL ? "NULL" : map->map_file);
655 if (!bitset(MF_OPENBOGUS, map->map_mflags))
657 map->map_mflags |= MF_CLOSING;
658 map->map_class->map_close(map);
660 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_OPENBOGUS|MF_CLOSING);
663 ** GETCANONNAME -- look up name using service switch
666 ** host -- the host name to look up.
667 ** hbsize -- the size of the host buffer.
668 ** trymx -- if set, try MX records.
669 ** pttl -- pointer to return TTL (can be NULL).
672 ** true -- if the host was found.
673 ** false -- otherwise.
677 getcanonname(host, hbsize, trymx, pttl)
686 bool got_tempfail = false;
688 char *maptype[MAXMAPSTACK];
689 short mapreturn[MAXMAPACTIONS];
691 nmaps = switch_map_find("hosts", maptype, mapreturn);
693 *pttl = SM_DEFAULT_TTL;
694 for (mapno = 0; mapno < nmaps; mapno++)
699 sm_dprintf("getcanonname(%s), trying %s\n",
700 host, maptype[mapno]);
701 if (strcmp("files", maptype[mapno]) == 0)
703 found = text_getcanonname(host, hbsize, &status);
706 else if (strcmp("nis", maptype[mapno]) == 0)
708 found = nis_getcanonname(host, hbsize, &status);
712 else if (strcmp("nisplus", maptype[mapno]) == 0)
714 found = nisplus_getcanonname(host, hbsize, &status);
718 else if (strcmp("dns", maptype[mapno]) == 0)
720 found = dns_getcanonname(host, hbsize, trymx, &status, pttl);
722 #endif /* NAMED_BIND */
724 else if (strcmp("netinfo", maptype[mapno]) == 0)
726 found = ni_getcanonname(host, hbsize, &status);
732 status = EX_UNAVAILABLE;
736 ** Heuristic: if $m is not set, we are running during system
737 ** startup. In this case, when a name is apparently found
738 ** but has no dot, treat is as not found. This avoids
739 ** problems if /etc/hosts has no FQDN but is listed first
740 ** in the service switch.
744 (macvalue('m', CurEnv) != NULL || strchr(host, '.') != NULL))
747 /* see if we should continue */
748 if (status == EX_TEMPFAIL)
753 else if (status == EX_NOTFOUND)
757 if (bitset(1 << mapno, mapreturn[i]))
766 sm_dprintf("getcanonname(%s), found\n", host);
769 ** If returned name is still single token, compensate
770 ** by tagging on $m. This is because some sites set
771 ** up their DNS or NIS databases wrong.
774 if ((d = strchr(host, '.')) == NULL || d[1] == '\0')
776 d = macvalue('m', CurEnv);
778 hbsize > (int) (strlen(host) + strlen(d) + 1))
780 if (host[strlen(host) - 1] != '.')
781 (void) sm_strlcat2(host, ".", d,
784 (void) sm_strlcat(host, d, hbsize);
793 sm_dprintf("getcanonname(%s), failed, status=%d\n", host,
797 SM_SET_H_ERRNO(TRY_AGAIN);
799 SM_SET_H_ERRNO(HOST_NOT_FOUND);
804 ** EXTRACT_CANONNAME -- extract canonical name from /etc/hosts entry
807 ** name -- the name against which to match.
808 ** dot -- where to reinsert '.' to get FQDN
809 ** line -- the /etc/hosts line.
810 ** cbuf -- the location to store the result.
811 ** cbuflen -- the size of cbuf.
814 ** true -- if the line matched the desired name.
815 ** false -- otherwise.
819 extract_canonname(name, dot, line, cbuf, cbuflen)
836 char nbuf[MAXNAME + 1];
838 p = get_column(line, i, '\0', nbuf, sizeof nbuf);
843 if (cbuf[0] == '\0' ||
844 (strchr(cbuf, '.') == NULL && strchr(p, '.') != NULL))
846 (void) sm_strlcpy(cbuf, p, cbuflen);
848 if (sm_strcasecmp(name, p) == 0)
850 else if (dot != NULL)
852 /* try looking for the FQDN as well */
854 if (sm_strcasecmp(name, p) == 0)
859 if (found && strchr(cbuf, '.') == NULL)
861 /* try to add a domain on the end of the name */
862 char *domain = macvalue('m', CurEnv);
864 if (domain != NULL &&
865 strlen(domain) + (i = strlen(cbuf)) + 1 < (size_t) cbuflen)
869 (void) sm_strlcpy(p, domain, cbuflen - i - 1);
882 # include "sm_resolve.h"
883 # if NETINET || NETINET6
884 # include <arpa/inet.h>
885 # endif /* NETINET || NETINET6 */
888 ** DNS_MAP_OPEN -- stub to check proper value for dns map type
892 dns_map_open(map, mode)
897 sm_dprintf("dns_map_open(%s, %d)\n", map->map_mname, mode);
900 if (mode != O_RDONLY)
902 /* issue a pseudo-error message */
903 errno = SM_EMAPCANTWRITE;
910 ** DNS_MAP_PARSEARGS -- parse dns map definition args.
913 ** map -- pointer to MAP
914 ** args -- pointer to the args on the config line.
917 ** true -- if everything parsed OK.
918 ** false -- otherwise.
921 # if _FFR_DNSMAP_MULTILIMIT
922 # if !_FFR_DNSMAP_MULTI
923 ERROR README: You must define _FFR_DNSMAP_MULTI to use _FFR_DNSMAP_MULTILIMIT
924 # endif /* ! _FFR_DNSMAP_MULTI */
925 # endif /* _FFR_DNSMAP_MULTILIMIT */
927 # if _FFR_DNSMAP_MULTI
928 # if _FFR_DNSMAP_MULTILIMIT
929 # define map_sizelimit map_lockfd /* overload field */
930 # endif /* _FFR_DNSMAP_MULTILIMIT */
931 # endif /* _FFR_DNSMAP_MULTI */
939 dns_map_parseargs(map,args)
943 register char *p = args;
944 struct dns_map *map_p;
946 map_p = (struct dns_map *) xalloc(sizeof *map_p);
947 map_p->dns_m_type = -1;
948 map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL;
952 while (isascii(*p) && isspace(*p))
959 map->map_mflags |= MF_INCLNULL;
960 map->map_mflags &= ~MF_TRY0NULL;
964 map->map_mflags &= ~MF_TRY1NULL;
968 map->map_mflags |= MF_OPTIONAL;
972 map->map_mflags |= MF_NOFOLDCASE;
976 map->map_mflags |= MF_MATCHONLY;
980 map->map_mflags |= MF_APPEND;
984 map->map_mflags |= MF_KEEPQUOTES;
988 map->map_mflags |= MF_NODEFER;
1007 map->map_timeout = convtime(p, 's');
1014 while (isascii(*++p) && isspace(*p))
1016 map->map_retry = atoi(p);
1019 # if _FFR_DNSMAP_MULTI
1022 map->map_coldelim = *p;
1028 map->map_coldelim = '\n';
1032 map->map_coldelim = '\t';
1036 map->map_coldelim = '\\';
1041 # if _FFR_DNSMAP_MULTILIMIT
1043 while (isascii(*++p) && isspace(*p))
1045 map->map_sizelimit = atoi(p);
1047 # endif /* _FFR_DNSMAP_MULTILIMIT */
1048 # endif /* _FFR_DNSMAP_MULTI */
1050 /* Start of dns_map specific args */
1051 case 'R': /* search field */
1055 while (isascii(*++p) && isspace(*p))
1060 map_p->dns_m_type = dns_string_to_type(p);
1063 if (map_p->dns_m_type < 0)
1064 syserr("dns map %s: wrong type %s",
1069 # if _FFR_DNSMAP_BASE
1070 case 'B': /* base domain */
1074 while (isascii(*++p) && isspace(*p))
1081 ** slight abuse of map->map_file; it isn't
1082 ** used otherwise in this map type.
1085 map->map_file = newstr(p);
1090 # endif /* _FFR_DNSMAP_BASE */
1093 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
1098 if (map_p->dns_m_type < 0)
1099 syserr("dns map %s: missing -R type", map->map_mname);
1100 if (map->map_app != NULL)
1101 map->map_app = newstr(map->map_app);
1102 if (map->map_tapp != NULL)
1103 map->map_tapp = newstr(map->map_tapp);
1106 ** Assumption: assert(sizeof int <= sizeof(ARBPTR_T));
1107 ** Even if this assumption is wrong, we use only one byte,
1108 ** so it doesn't really matter.
1111 map->map_db1 = (ARBPTR_T) map_p;
1116 ** DNS_MAP_LOOKUP -- perform dns map lookup.
1119 ** map -- pointer to MAP
1120 ** name -- name to lookup
1121 ** av -- arguments to interpolate into buf.
1122 ** statp -- pointer to status (EX_)
1125 ** result of lookup if succeeded.
1126 ** NULL -- otherwise.
1130 dns_map_lookup(map, name, av, statp)
1136 # if _FFR_DNSMAP_MULTI
1137 # if _FFR_DNSMAP_MULTILIMIT
1139 # endif /* _FFR_DNSMAP_MULTILIMIT */
1140 # endif /* _FFR_DNSMAP_MULTI */
1141 char *vp = NULL, *result = NULL;
1143 struct dns_map *map_p;
1144 RESOURCE_RECORD_T *rr = NULL;
1145 DNS_REPLY_T *r = NULL;
1147 static char buf6[INET6_ADDRSTRLEN];
1148 # endif /* NETINET6 */
1151 sm_dprintf("dns_map_lookup(%s, %s)\n",
1152 map->map_mname, name);
1154 map_p = (struct dns_map *)(map->map_db1);
1155 # if _FFR_DNSMAP_BASE
1156 if (map->map_file != NULL && *map->map_file != '\0')
1161 len = strlen(map->map_file) + strlen(name) + 2;
1162 appdomain = (char *) sm_malloc(len);
1163 if (appdomain == NULL)
1165 *statp = EX_UNAVAILABLE;
1168 (void) sm_strlcpyn(appdomain, len, 3, name, ".", map->map_file);
1169 r = dns_lookup_int(appdomain, C_IN, map_p->dns_m_type,
1170 map->map_timeout, map->map_retry);
1174 # endif /* _FFR_DNSMAP_BASE */
1176 r = dns_lookup_int(name, C_IN, map_p->dns_m_type,
1177 map->map_timeout, map->map_retry);
1183 if (h_errno == TRY_AGAIN || transienterror(errno))
1184 *statp = EX_TEMPFAIL;
1186 *statp = EX_NOTFOUND;
1190 for (rr = r->dns_r_head; rr != NULL; rr = rr->rr_next)
1195 switch (rr->rr_type)
1199 value = rr->rr_u.rr_txt;
1203 value = rr->rr_u.rr_txt;
1207 value = rr->rr_u.rr_mx->mx_r_domain;
1211 value = rr->rr_u.rr_srv->srv_r_target;
1215 value = rr->rr_u.rr_txt;
1219 value = rr->rr_u.rr_txt;
1223 value = rr->rr_u.rr_mx->mx_r_domain;
1228 value = inet_ntoa(*(rr->rr_u.rr_a));
1230 # endif /* NETINET */
1234 value = anynet_ntop(rr->rr_u.rr_aaaa, buf6,
1237 # endif /* NETINET6 */
1240 (void) strreplnonprt(value, 'X');
1241 if (map_p->dns_m_type != rr->rr_type)
1244 sm_dprintf("\tskipping type %s (%d) value %s\n",
1245 type != NULL ? type : "<UNKNOWN>",
1247 value != NULL ? value : "<NO VALUE>");
1252 if (rr->rr_type == T_AAAA && value == NULL)
1255 *statp = EX_DATAERR;
1257 sm_dprintf("\tbad T_AAAA conversion\n");
1260 # endif /* NETINET6 */
1262 sm_dprintf("\tfound type %s (%d) value %s\n",
1263 type != NULL ? type : "<UNKNOWN>",
1265 value != NULL ? value : "<NO VALUE>");
1266 # if _FFR_DNSMAP_MULTI
1267 if (value != NULL &&
1268 (map->map_coldelim == '\0' ||
1269 # if _FFR_DNSMAP_MULTILIMIT
1270 map->map_sizelimit == 1 ||
1271 # endif /* _FFR_DNSMAP_MULTILIMIT */
1272 bitset(MF_MATCHONLY, map->map_mflags)))
1274 /* Only care about the first match */
1278 else if (vp == NULL)
1285 /* concatenate the results */
1289 sz = strlen(vp) + strlen(value) + 2;
1291 (void) sm_snprintf(new, sz, "%s%c%s",
1292 vp, map->map_coldelim, value);
1295 # if _FFR_DNSMAP_MULTILIMIT
1296 if (map->map_sizelimit > 0 &&
1297 ++resnum >= map->map_sizelimit)
1299 # endif /* _FFR_DNSMAP_MULTILIMIT */
1301 # else /* _FFR_DNSMAP_MULTI */
1304 # endif /* _FFR_DNSMAP_MULTI */
1309 *statp = EX_NOTFOUND;
1311 sm_dprintf("\tno match found\n");
1315 # if _FFR_DNSMAP_MULTI
1316 /* Cleanly truncate for rulesets */
1317 truncate_at_delim(vp, PSBUFSIZE / 2, map->map_coldelim);
1318 # endif /* _FFR_DNSMAP_MULTI */
1323 sm_syslog(LOG_INFO, CurEnv->e_id, "dns %.100s => %s",
1325 if (bitset(MF_MATCHONLY, map->map_mflags))
1326 result = map_rewrite(map, name, strlen(name), NULL);
1328 result = map_rewrite(map, vp, vsize, av);
1331 # if _FFR_DNSMAP_MULTI
1334 # endif /* _FFR_DNSMAP_MULTI */
1339 # endif /* DNSMAP */
1340 #endif /* NAMED_BIND */
1349 ** NDBM_MAP_OPEN -- DBM-style map open
1353 ndbm_map_open(map, mode)
1363 int smode = S_IREAD;
1364 char dirfile[MAXPATHLEN];
1365 char pagfile[MAXPATHLEN];
1367 struct stat std, stp;
1370 sm_dprintf("ndbm_map_open(%s, %s, %d)\n",
1371 map->map_mname, map->map_file, mode);
1372 map->map_lockfd = -1;
1375 /* do initial file and directory checks */
1376 if (sm_strlcpyn(dirfile, sizeof dirfile, 2,
1377 map->map_file, ".dir") >= sizeof dirfile ||
1378 sm_strlcpyn(pagfile, sizeof pagfile, 2,
1379 map->map_file, ".pag") >= sizeof pagfile)
1382 if (!bitset(MF_OPTIONAL, map->map_mflags))
1383 syserr("dbm map \"%s\": map file %s name too long",
1384 map->map_mname, map->map_file);
1387 sff = SFF_ROOTOK|SFF_REGONLY;
1391 if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail))
1393 if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail))
1399 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
1402 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
1403 sff |= SFF_SAFEDIRPATH;
1404 ret = safefile(dirfile, RunAsUid, RunAsGid, RunAsUserName,
1407 ret = safefile(pagfile, RunAsUid, RunAsGid, RunAsUserName,
1412 char *prob = "unsafe";
1414 /* cannot open this map */
1418 sm_dprintf("\t%s map file: %d\n", prob, ret);
1419 if (!bitset(MF_OPTIONAL, map->map_mflags))
1420 syserr("dbm map \"%s\": %s map file %s",
1421 map->map_mname, prob, map->map_file);
1424 if (std.st_mode == ST_MODE_NOFILE)
1425 mode |= O_CREAT|O_EXCL;
1428 if (mode == O_RDONLY)
1431 mode |= O_TRUNC|O_EXLOCK;
1432 # else /* LOCK_ON_OPEN */
1433 if ((mode & O_ACCMODE) == O_RDWR)
1437 ** Warning: race condition. Try to lock the file as
1438 ** quickly as possible after opening it.
1439 ** This may also have security problems on some systems,
1440 ** but there isn't anything we can do about it.
1444 # else /* NOFTRUNCATE */
1446 ** This ugly code opens the map without truncating it,
1447 ** locks the file, then truncates it. Necessary to
1448 ** avoid race conditions.
1453 long sff = SFF_CREAT|SFF_OPENASROOT;
1455 if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail))
1457 if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail))
1460 dirfd = safeopen(dirfile, mode, DBMMODE, sff);
1461 pagfd = safeopen(pagfile, mode, DBMMODE, sff);
1463 if (dirfd < 0 || pagfd < 0)
1467 (void) close(dirfd);
1469 (void) close(pagfd);
1471 syserr("ndbm_map_open: cannot create database %s",
1475 if (ftruncate(dirfd, (off_t) 0) < 0 ||
1476 ftruncate(pagfd, (off_t) 0) < 0)
1479 (void) close(dirfd);
1480 (void) close(pagfd);
1482 syserr("ndbm_map_open: cannot truncate %s.{dir,pag}",
1487 /* if new file, get "before" bits for later filechanged check */
1488 if (std.st_mode == ST_MODE_NOFILE &&
1489 (fstat(dirfd, &std) < 0 || fstat(pagfd, &stp) < 0))
1492 (void) close(dirfd);
1493 (void) close(pagfd);
1495 syserr("ndbm_map_open(%s.{dir,pag}): cannot fstat pre-opened file",
1500 /* have to save the lock for the duration (bletch) */
1501 map->map_lockfd = dirfd;
1502 (void) close(pagfd);
1504 /* twiddle bits for dbm_open */
1505 mode &= ~(O_CREAT|O_EXCL);
1506 # endif /* NOFTRUNCATE */
1508 # endif /* LOCK_ON_OPEN */
1510 /* open the database */
1511 dbm = dbm_open(map->map_file, mode, DBMMODE);
1515 if (bitset(MF_ALIAS, map->map_mflags) &&
1516 aliaswait(map, ".pag", false))
1518 # if !LOCK_ON_OPEN && !NOFTRUNCATE
1519 if (map->map_lockfd >= 0)
1520 (void) close(map->map_lockfd);
1521 # endif /* !LOCK_ON_OPEN && !NOFTRUNCATE */
1523 if (!bitset(MF_OPTIONAL, map->map_mflags))
1524 syserr("Cannot open DBM database %s", map->map_file);
1527 dfd = dbm_dirfno(dbm);
1528 pfd = dbm_pagfno(dbm);
1531 /* heuristic: if files are linked, this is actually gdbm */
1533 # if !LOCK_ON_OPEN && !NOFTRUNCATE
1534 if (map->map_lockfd >= 0)
1535 (void) close(map->map_lockfd);
1536 # endif /* !LOCK_ON_OPEN && !NOFTRUNCATE */
1538 syserr("dbm map \"%s\": cannot support GDBM",
1543 if (filechanged(dirfile, dfd, &std) ||
1544 filechanged(pagfile, pfd, &stp))
1548 # if !LOCK_ON_OPEN && !NOFTRUNCATE
1549 if (map->map_lockfd >= 0)
1550 (void) close(map->map_lockfd);
1551 # endif /* !LOCK_ON_OPEN && !NOFTRUNCATE */
1553 syserr("ndbm_map_open(%s): file changed after open",
1558 map->map_db1 = (ARBPTR_T) dbm;
1561 ** Need to set map_mtime before the call to aliaswait()
1562 ** as aliaswait() will call map_lookup() which requires
1563 ** map_mtime to be set
1566 if (fstat(pfd, &st) >= 0)
1567 map->map_mtime = st.st_mtime;
1569 if (mode == O_RDONLY)
1573 (void) lockfile(dfd, map->map_file, ".dir", LOCK_UN);
1575 (void) lockfile(pfd, map->map_file, ".pag", LOCK_UN);
1576 # endif /* LOCK_ON_OPEN */
1577 if (bitset(MF_ALIAS, map->map_mflags) &&
1578 !aliaswait(map, ".pag", true))
1583 map->map_mflags |= MF_LOCKED;
1584 if (geteuid() == 0 && TrustedUid != 0)
1587 if (fchown(dfd, TrustedUid, -1) < 0 ||
1588 fchown(pfd, TrustedUid, -1) < 0)
1592 sm_syslog(LOG_ALERT, NOQID,
1593 "ownership change on %s failed: %s",
1594 map->map_file, sm_errstring(err));
1595 message("050 ownership change on %s failed: %s",
1596 map->map_file, sm_errstring(err));
1598 # else /* HASFCHOWN */
1599 sm_syslog(LOG_ALERT, NOQID,
1600 "no fchown(): cannot change ownership on %s",
1602 message("050 no fchown(): cannot change ownership on %s",
1604 # endif /* HASFCHOWN */
1612 ** NDBM_MAP_LOOKUP -- look up a datum in a DBM-type map
1616 ndbm_map_lookup(map, name, av, statp)
1624 char keybuf[MAXNAME + 1];
1628 sm_dprintf("ndbm_map_lookup(%s, %s)\n",
1629 map->map_mname, name);
1632 key.dsize = strlen(name);
1633 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
1635 if (key.dsize > sizeof keybuf - 1)
1636 key.dsize = sizeof keybuf - 1;
1637 memmove(keybuf, key.dptr, key.dsize);
1638 keybuf[key.dsize] = '\0';
1643 dfd = dbm_dirfno((DBM *) map->map_db1);
1644 if (dfd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
1645 (void) lockfile(dfd, map->map_file, ".dir", LOCK_SH);
1646 pfd = dbm_pagfno((DBM *) map->map_db1);
1647 if (pfd < 0 || fstat(pfd, &stbuf) < 0 ||
1648 stbuf.st_mtime > map->map_mtime)
1650 /* Reopen the database to sync the cache */
1651 int omode = bitset(map->map_mflags, MF_WRITABLE) ? O_RDWR
1654 if (dfd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
1655 (void) lockfile(dfd, map->map_file, ".dir", LOCK_UN);
1656 map->map_mflags |= MF_CLOSING;
1657 map->map_class->map_close(map);
1658 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
1659 if (map->map_class->map_open(map, omode))
1661 map->map_mflags |= MF_OPEN;
1662 map->map_pid = CurrentPid;
1663 if ((omode && O_ACCMODE) == O_RDWR)
1664 map->map_mflags |= MF_WRITABLE;
1669 if (!bitset(MF_OPTIONAL, map->map_mflags))
1671 extern MAPCLASS BogusMapClass;
1673 *statp = EX_TEMPFAIL;
1674 map->map_orgclass = map->map_class;
1675 map->map_class = &BogusMapClass;
1676 map->map_mflags |= MF_OPEN;
1677 map->map_pid = CurrentPid;
1678 syserr("Cannot reopen NDBM database %s",
1685 if (bitset(MF_TRY0NULL, map->map_mflags))
1687 val = dbm_fetch((DBM *) map->map_db1, key);
1688 if (val.dptr != NULL)
1689 map->map_mflags &= ~MF_TRY1NULL;
1691 if (val.dptr == NULL && bitset(MF_TRY1NULL, map->map_mflags))
1694 val = dbm_fetch((DBM *) map->map_db1, key);
1695 if (val.dptr != NULL)
1696 map->map_mflags &= ~MF_TRY0NULL;
1698 if (dfd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
1699 (void) lockfile(dfd, map->map_file, ".dir", LOCK_UN);
1700 if (val.dptr == NULL)
1702 if (bitset(MF_MATCHONLY, map->map_mflags))
1703 return map_rewrite(map, name, strlen(name), NULL);
1705 return map_rewrite(map, val.dptr, val.dsize, av);
1710 ** NDBM_MAP_STORE -- store a datum in the database
1714 ndbm_map_store(map, lhs, rhs)
1722 char keybuf[MAXNAME + 1];
1725 sm_dprintf("ndbm_map_store(%s, %s, %s)\n",
1726 map->map_mname, lhs, rhs);
1728 key.dsize = strlen(lhs);
1730 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
1732 if (key.dsize > sizeof keybuf - 1)
1733 key.dsize = sizeof keybuf - 1;
1734 memmove(keybuf, key.dptr, key.dsize);
1735 keybuf[key.dsize] = '\0';
1740 data.dsize = strlen(rhs);
1743 if (bitset(MF_INCLNULL, map->map_mflags))
1749 status = dbm_store((DBM *) map->map_db1, key, data, DBM_INSERT);
1752 if (!bitset(MF_APPEND, map->map_mflags))
1753 message("050 Warning: duplicate alias name %s", lhs);
1756 static char *buf = NULL;
1757 static int bufsiz = 0;
1761 old.dptr = ndbm_map_lookup(map, key.dptr,
1762 (char **) NULL, &xstat);
1763 if (old.dptr != NULL && *(char *) old.dptr != '\0')
1765 old.dsize = strlen(old.dptr);
1766 if (data.dsize + old.dsize + 2 > bufsiz)
1769 (void) sm_free(buf);
1770 bufsiz = data.dsize + old.dsize + 2;
1771 buf = sm_pmalloc_x(bufsiz);
1773 (void) sm_strlcpyn(buf, bufsiz, 3,
1774 data.dptr, ",", old.dptr);
1775 data.dsize = data.dsize + old.dsize + 1;
1778 sm_dprintf("ndbm_map_store append=%s\n",
1782 status = dbm_store((DBM *) map->map_db1,
1783 key, data, DBM_REPLACE);
1786 syserr("readaliases: dbm put (%s): %d", lhs, status);
1791 ** NDBM_MAP_CLOSE -- close the database
1799 sm_dprintf("ndbm_map_close(%s, %s, %lx)\n",
1800 map->map_mname, map->map_file, map->map_mflags);
1802 if (bitset(MF_WRITABLE, map->map_mflags))
1804 # ifdef NDBM_YP_COMPAT
1806 char buf[MAXHOSTNAMELEN];
1808 inclnull = bitset(MF_INCLNULL, map->map_mflags);
1809 map->map_mflags &= ~MF_INCLNULL;
1811 if (strstr(map->map_file, "/yp/") != NULL)
1813 long save_mflags = map->map_mflags;
1815 map->map_mflags |= MF_NOFOLDCASE;
1817 (void) sm_snprintf(buf, sizeof buf, "%010ld", curtime());
1818 ndbm_map_store(map, "YP_LAST_MODIFIED", buf);
1820 (void) gethostname(buf, sizeof buf);
1821 ndbm_map_store(map, "YP_MASTER_NAME", buf);
1823 map->map_mflags = save_mflags;
1827 map->map_mflags |= MF_INCLNULL;
1828 # endif /* NDBM_YP_COMPAT */
1830 /* write out the distinguished alias */
1831 ndbm_map_store(map, "@", "@");
1833 dbm_close((DBM *) map->map_db1);
1835 /* release lock (if needed) */
1837 if (map->map_lockfd >= 0)
1838 (void) close(map->map_lockfd);
1839 # endif /* !LOCK_ON_OPEN */
1844 ** NEWDB (Hash and BTree) Modules
1850 ** BT_MAP_OPEN, HASH_MAP_OPEN -- database open primitives.
1852 ** These do rather bizarre locking. If you can lock on open,
1853 ** do that to avoid the condition of opening a database that
1854 ** is being rebuilt. If you don't, we'll try to fake it, but
1855 ** there will be a race condition. If opening for read-only,
1856 ** we immediately release the lock to avoid freezing things up.
1857 ** We really ought to hold the lock, but guarantee that we won't
1858 ** be pokey about it. That's hard to do.
1861 /* these should be K line arguments */
1862 # if DB_VERSION_MAJOR < 2
1863 # define db_cachesize cachesize
1864 # define h_nelem nelem
1865 # ifndef DB_CACHE_SIZE
1866 # define DB_CACHE_SIZE (1024 * 1024) /* database memory cache size */
1867 # endif /* ! DB_CACHE_SIZE */
1868 # ifndef DB_HASH_NELEM
1869 # define DB_HASH_NELEM 4096 /* (starting) size of hash table */
1870 # endif /* ! DB_HASH_NELEM */
1871 # endif /* DB_VERSION_MAJOR < 2 */
1874 bt_map_open(map, mode)
1878 # if DB_VERSION_MAJOR < 2
1880 # endif /* DB_VERSION_MAJOR < 2 */
1881 # if DB_VERSION_MAJOR == 2
1883 # endif /* DB_VERSION_MAJOR == 2 */
1884 # if DB_VERSION_MAJOR > 2
1885 void *btinfo = NULL;
1886 # endif /* DB_VERSION_MAJOR > 2 */
1889 sm_dprintf("bt_map_open(%s, %s, %d)\n",
1890 map->map_mname, map->map_file, mode);
1892 # if DB_VERSION_MAJOR < 3
1893 memset(&btinfo, '\0', sizeof btinfo);
1894 # ifdef DB_CACHE_SIZE
1895 btinfo.db_cachesize = DB_CACHE_SIZE;
1896 # endif /* DB_CACHE_SIZE */
1897 # endif /* DB_VERSION_MAJOR < 3 */
1899 return db_map_open(map, mode, "btree", DB_BTREE, &btinfo);
1903 hash_map_open(map, mode)
1907 # if DB_VERSION_MAJOR < 2
1909 # endif /* DB_VERSION_MAJOR < 2 */
1910 # if DB_VERSION_MAJOR == 2
1912 # endif /* DB_VERSION_MAJOR == 2 */
1913 # if DB_VERSION_MAJOR > 2
1915 # endif /* DB_VERSION_MAJOR > 2 */
1918 sm_dprintf("hash_map_open(%s, %s, %d)\n",
1919 map->map_mname, map->map_file, mode);
1921 # if DB_VERSION_MAJOR < 3
1922 memset(&hinfo, '\0', sizeof hinfo);
1923 # ifdef DB_HASH_NELEM
1924 hinfo.h_nelem = DB_HASH_NELEM;
1925 # endif /* DB_HASH_NELEM */
1926 # ifdef DB_CACHE_SIZE
1927 hinfo.db_cachesize = DB_CACHE_SIZE;
1928 # endif /* DB_CACHE_SIZE */
1929 # endif /* DB_VERSION_MAJOR < 3 */
1931 return db_map_open(map, mode, "hash", DB_HASH, &hinfo);
1935 db_map_open(map, mode, mapclassname, dbtype, openinfo)
1940 # if DB_VERSION_MAJOR < 2
1941 const void *openinfo;
1942 # endif /* DB_VERSION_MAJOR < 2 */
1943 # if DB_VERSION_MAJOR == 2
1945 # endif /* DB_VERSION_MAJOR == 2 */
1946 # if DB_VERSION_MAJOR > 2
1948 # endif /* DB_VERSION_MAJOR > 2 */
1953 int smode = S_IREAD;
1958 char buf[MAXPATHLEN];
1960 /* do initial file and directory checks */
1961 if (sm_strlcpy(buf, map->map_file, sizeof buf) >= sizeof buf)
1964 if (!bitset(MF_OPTIONAL, map->map_mflags))
1965 syserr("map \"%s\": map file %s name too long",
1966 map->map_mname, map->map_file);
1970 if (i < 3 || strcmp(&buf[i - 3], ".db") != 0)
1972 if (sm_strlcat(buf, ".db", sizeof buf) >= sizeof buf)
1975 if (!bitset(MF_OPTIONAL, map->map_mflags))
1976 syserr("map \"%s\": map file %s name too long",
1977 map->map_mname, map->map_file);
1985 sff = SFF_ROOTOK|SFF_REGONLY;
1989 if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail))
1991 if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail))
1997 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
2000 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
2001 sff |= SFF_SAFEDIRPATH;
2002 i = safefile(buf, RunAsUid, RunAsGid, RunAsUserName, sff, smode, &st);
2006 char *prob = "unsafe";
2008 /* cannot open this map */
2012 sm_dprintf("\t%s map file: %s\n", prob, sm_errstring(i));
2014 if (!bitset(MF_OPTIONAL, map->map_mflags))
2015 syserr("%s map \"%s\": %s map file %s",
2016 mapclassname, map->map_mname, prob, buf);
2019 if (st.st_mode == ST_MODE_NOFILE)
2020 omode |= O_CREAT|O_EXCL;
2022 map->map_lockfd = -1;
2026 omode |= O_TRUNC|O_EXLOCK;
2029 # else /* LOCK_ON_OPEN */
2031 ** Pre-lock the file to avoid race conditions. In particular,
2032 ** since dbopen returns NULL if the file is zero length, we
2033 ** must have a locked instance around the dbopen.
2036 fd = open(buf, omode, DBMMODE);
2039 if (!bitset(MF_OPTIONAL, map->map_mflags))
2040 syserr("db_map_open: cannot pre-open database %s", buf);
2044 /* make sure no baddies slipped in just before the open... */
2045 if (filechanged(buf, fd, &st))
2050 syserr("db_map_open(%s): file changed after pre-open", buf);
2054 /* if new file, get the "before" bits for later filechanged check */
2055 if (st.st_mode == ST_MODE_NOFILE && fstat(fd, &st) < 0)
2060 syserr("db_map_open(%s): cannot fstat pre-opened file",
2065 /* actually lock the pre-opened file */
2066 if (!lockfile(fd, buf, NULL, mode == O_RDONLY ? LOCK_SH : LOCK_EX))
2067 syserr("db_map_open: cannot lock %s", buf);
2069 /* set up mode bits for dbopen */
2072 omode &= ~(O_EXCL|O_CREAT);
2073 # endif /* LOCK_ON_OPEN */
2075 # if DB_VERSION_MAJOR < 2
2076 db = dbopen(buf, omode, DBMMODE, dbtype, openinfo);
2077 # else /* DB_VERSION_MAJOR < 2 */
2080 # if DB_VERSION_MAJOR > 2
2082 # endif /* DB_VERSION_MAJOR > 2 */
2084 if (mode == O_RDONLY)
2086 if (bitset(O_CREAT, omode))
2088 if (bitset(O_TRUNC, omode))
2089 flags |= DB_TRUNCATE;
2090 SM_DB_FLAG_ADD(flags);
2092 # if DB_VERSION_MAJOR > 2
2093 ret = db_create(&db, NULL, 0);
2094 # ifdef DB_CACHE_SIZE
2095 if (ret == 0 && db != NULL)
2097 ret = db->set_cachesize(db, 0, DB_CACHE_SIZE, 0);
2100 (void) db->close(db, 0);
2104 # endif /* DB_CACHE_SIZE */
2105 # ifdef DB_HASH_NELEM
2106 if (dbtype == DB_HASH && ret == 0 && db != NULL)
2108 ret = db->set_h_nelem(db, DB_HASH_NELEM);
2111 (void) db->close(db, 0);
2115 # endif /* DB_HASH_NELEM */
2116 if (ret == 0 && db != NULL)
2119 DBTXN /* transaction for DB 4.1 */
2120 buf, NULL, dbtype, flags, DBMMODE);
2123 #ifdef DB_OLD_VERSION
2124 if (ret == DB_OLD_VERSION)
2126 #endif /* DB_OLD_VERSION */
2127 (void) db->close(db, 0);
2132 # else /* DB_VERSION_MAJOR > 2 */
2133 errno = db_open(buf, dbtype, flags, DBMMODE,
2134 NULL, openinfo, &db);
2135 # endif /* DB_VERSION_MAJOR > 2 */
2137 # endif /* DB_VERSION_MAJOR < 2 */
2142 map->map_lockfd = fd;
2145 # endif /* !LOCK_ON_OPEN */
2149 if (mode == O_RDONLY && bitset(MF_ALIAS, map->map_mflags) &&
2150 aliaswait(map, ".db", false))
2153 if (map->map_lockfd >= 0)
2154 (void) close(map->map_lockfd);
2155 # endif /* !LOCK_ON_OPEN */
2157 if (!bitset(MF_OPTIONAL, map->map_mflags))
2158 syserr("Cannot open %s database %s",
2163 # if DB_VERSION_MAJOR < 2
2165 # else /* DB_VERSION_MAJOR < 2 */
2167 errno = db->fd(db, &fd);
2168 # endif /* DB_VERSION_MAJOR < 2 */
2169 if (filechanged(buf, fd, &st))
2172 # if DB_VERSION_MAJOR < 2
2173 (void) db->close(db);
2174 # else /* DB_VERSION_MAJOR < 2 */
2175 errno = db->close(db, 0);
2176 # endif /* DB_VERSION_MAJOR < 2 */
2178 if (map->map_lockfd >= 0)
2179 (void) close(map->map_lockfd);
2180 # endif /* !LOCK_ON_OPEN */
2182 syserr("db_map_open(%s): file changed after open", buf);
2187 map->map_mflags |= MF_LOCKED;
2189 if (fd >= 0 && mode == O_RDONLY)
2191 (void) lockfile(fd, buf, NULL, LOCK_UN);
2193 # endif /* LOCK_ON_OPEN */
2195 /* try to make sure that at least the database header is on disk */
2198 (void) db->sync(db, 0);
2199 if (geteuid() == 0 && TrustedUid != 0)
2202 if (fchown(fd, TrustedUid, -1) < 0)
2206 sm_syslog(LOG_ALERT, NOQID,
2207 "ownership change on %s failed: %s",
2208 buf, sm_errstring(err));
2209 message("050 ownership change on %s failed: %s",
2210 buf, sm_errstring(err));
2212 # else /* HASFCHOWN */
2213 sm_syslog(LOG_ALERT, NOQID,
2214 "no fchown(): cannot change ownership on %s",
2216 message("050 no fchown(): cannot change ownership on %s",
2218 # endif /* HASFCHOWN */
2222 map->map_db2 = (ARBPTR_T) db;
2225 ** Need to set map_mtime before the call to aliaswait()
2226 ** as aliaswait() will call map_lookup() which requires
2227 ** map_mtime to be set
2230 if (fd >= 0 && fstat(fd, &st) >= 0)
2231 map->map_mtime = st.st_mtime;
2233 if (mode == O_RDONLY && bitset(MF_ALIAS, map->map_mflags) &&
2234 !aliaswait(map, ".db", true))
2241 ** DB_MAP_LOOKUP -- look up a datum in a BTREE- or HASH-type map
2245 db_map_lookup(map, name, av, statp)
2252 register DB *db = (DB *) map->map_db2;
2258 char keybuf[MAXNAME + 1];
2259 char buf[MAXPATHLEN];
2261 memset(&key, '\0', sizeof key);
2262 memset(&val, '\0', sizeof val);
2265 sm_dprintf("db_map_lookup(%s, %s)\n",
2266 map->map_mname, name);
2268 if (sm_strlcpy(buf, map->map_file, sizeof buf) >= sizeof buf)
2271 if (!bitset(MF_OPTIONAL, map->map_mflags))
2272 syserr("map \"%s\": map file %s name too long",
2273 map->map_mname, map->map_file);
2277 if (i > 3 && strcmp(&buf[i - 3], ".db") == 0)
2280 key.size = strlen(name);
2281 if (key.size > sizeof keybuf - 1)
2282 key.size = sizeof keybuf - 1;
2284 memmove(keybuf, name, key.size);
2285 keybuf[key.size] = '\0';
2286 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
2289 # if DB_VERSION_MAJOR < 2
2291 # else /* DB_VERSION_MAJOR < 2 */
2293 errno = db->fd(db, &fd);
2294 # endif /* DB_VERSION_MAJOR < 2 */
2295 if (fd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
2296 (void) lockfile(fd, buf, ".db", LOCK_SH);
2297 if (fd < 0 || fstat(fd, &stbuf) < 0 || stbuf.st_mtime > map->map_mtime)
2299 /* Reopen the database to sync the cache */
2300 int omode = bitset(map->map_mflags, MF_WRITABLE) ? O_RDWR
2303 if (fd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
2304 (void) lockfile(fd, buf, ".db", LOCK_UN);
2305 map->map_mflags |= MF_CLOSING;
2306 map->map_class->map_close(map);
2307 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
2308 if (map->map_class->map_open(map, omode))
2310 map->map_mflags |= MF_OPEN;
2311 map->map_pid = CurrentPid;
2312 if ((omode && O_ACCMODE) == O_RDWR)
2313 map->map_mflags |= MF_WRITABLE;
2314 db = (DB *) map->map_db2;
2319 if (!bitset(MF_OPTIONAL, map->map_mflags))
2321 extern MAPCLASS BogusMapClass;
2323 *statp = EX_TEMPFAIL;
2324 map->map_orgclass = map->map_class;
2325 map->map_class = &BogusMapClass;
2326 map->map_mflags |= MF_OPEN;
2327 map->map_pid = CurrentPid;
2328 syserr("Cannot reopen DB database %s",
2336 if (bitset(MF_TRY0NULL, map->map_mflags))
2338 # if DB_VERSION_MAJOR < 2
2339 st = db->get(db, &key, &val, 0);
2340 # else /* DB_VERSION_MAJOR < 2 */
2341 errno = db->get(db, NULL, &key, &val, 0);
2357 # endif /* DB_VERSION_MAJOR < 2 */
2359 map->map_mflags &= ~MF_TRY1NULL;
2361 if (st != 0 && bitset(MF_TRY1NULL, map->map_mflags))
2364 # if DB_VERSION_MAJOR < 2
2365 st = db->get(db, &key, &val, 0);
2366 # else /* DB_VERSION_MAJOR < 2 */
2367 errno = db->get(db, NULL, &key, &val, 0);
2383 # endif /* DB_VERSION_MAJOR < 2 */
2385 map->map_mflags &= ~MF_TRY0NULL;
2388 if (fd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
2389 (void) lockfile(fd, buf, ".db", LOCK_UN);
2394 syserr("db_map_lookup: get (%s)", name);
2397 if (bitset(MF_MATCHONLY, map->map_mflags))
2398 return map_rewrite(map, name, strlen(name), NULL);
2400 return map_rewrite(map, val.data, val.size, av);
2405 ** DB_MAP_STORE -- store a datum in the NEWDB database
2409 db_map_store(map, lhs, rhs)
2417 register DB *db = map->map_db2;
2418 char keybuf[MAXNAME + 1];
2420 memset(&key, '\0', sizeof key);
2421 memset(&data, '\0', sizeof data);
2424 sm_dprintf("db_map_store(%s, %s, %s)\n",
2425 map->map_mname, lhs, rhs);
2427 key.size = strlen(lhs);
2429 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
2431 if (key.size > sizeof keybuf - 1)
2432 key.size = sizeof keybuf - 1;
2433 memmove(keybuf, key.data, key.size);
2434 keybuf[key.size] = '\0';
2439 data.size = strlen(rhs);
2442 if (bitset(MF_INCLNULL, map->map_mflags))
2448 # if DB_VERSION_MAJOR < 2
2449 status = db->put(db, &key, &data, R_NOOVERWRITE);
2450 # else /* DB_VERSION_MAJOR < 2 */
2451 errno = db->put(db, NULL, &key, &data, DB_NOOVERWRITE);
2466 # endif /* DB_VERSION_MAJOR < 2 */
2469 if (!bitset(MF_APPEND, map->map_mflags))
2470 message("050 Warning: duplicate alias name %s", lhs);
2473 static char *buf = NULL;
2474 static int bufsiz = 0;
2477 memset(&old, '\0', sizeof old);
2479 old.data = db_map_lookup(map, key.data,
2480 (char **) NULL, &status);
2481 if (old.data != NULL)
2483 old.size = strlen(old.data);
2484 if (data.size + old.size + 2 > (size_t) bufsiz)
2488 bufsiz = data.size + old.size + 2;
2489 buf = sm_pmalloc_x(bufsiz);
2491 (void) sm_strlcpyn(buf, bufsiz, 3,
2492 (char *) data.data, ",",
2494 data.size = data.size + old.size + 1;
2497 sm_dprintf("db_map_store append=%s\n",
2498 (char *) data.data);
2501 # if DB_VERSION_MAJOR < 2
2502 status = db->put(db, &key, &data, 0);
2503 # else /* DB_VERSION_MAJOR < 2 */
2504 status = errno = db->put(db, NULL, &key, &data, 0);
2505 # endif /* DB_VERSION_MAJOR < 2 */
2508 syserr("readaliases: db put (%s)", lhs);
2513 ** DB_MAP_CLOSE -- add distinguished entries and close the database
2520 register DB *db = map->map_db2;
2523 sm_dprintf("db_map_close(%s, %s, %lx)\n",
2524 map->map_mname, map->map_file, map->map_mflags);
2526 if (bitset(MF_WRITABLE, map->map_mflags))
2528 /* write out the distinguished alias */
2529 db_map_store(map, "@", "@");
2532 (void) db->sync(db, 0);
2535 if (map->map_lockfd >= 0)
2536 (void) close(map->map_lockfd);
2537 # endif /* !LOCK_ON_OPEN */
2539 # if DB_VERSION_MAJOR < 2
2540 if (db->close(db) != 0)
2541 # else /* DB_VERSION_MAJOR < 2 */
2543 ** Berkeley DB can use internal shared memory
2544 ** locking for its memory pool. Closing a map
2545 ** opened by another process will interfere
2546 ** with the shared memory and locks of the parent
2547 ** process leaving things in a bad state.
2551 ** If this map was not opened by the current
2552 ** process, do not close the map but recover
2553 ** the file descriptor.
2556 if (map->map_pid != CurrentPid)
2560 errno = db->fd(db, &fd);
2566 if ((errno = db->close(db, 0)) != 0)
2567 # endif /* DB_VERSION_MAJOR < 2 */
2568 syserr("db_map_close(%s, %s, %lx): db close failure",
2569 map->map_mname, map->map_file, map->map_mflags);
2579 # define YPERR_BUSY 16
2580 # endif /* ! YPERR_BUSY */
2583 ** NIS_MAP_OPEN -- open DBM map
2587 nis_map_open(map, mode)
2597 sm_dprintf("nis_map_open(%s, %s, %d)\n",
2598 map->map_mname, map->map_file, mode);
2601 if (mode != O_RDONLY)
2603 /* issue a pseudo-error message */
2604 errno = SM_EMAPCANTWRITE;
2608 p = strchr(map->map_file, '@');
2613 map->map_domain = p;
2616 if (*map->map_file == '\0')
2617 map->map_file = "mail.aliases";
2619 if (map->map_domain == NULL)
2621 yperr = yp_get_default_domain(&map->map_domain);
2624 if (!bitset(MF_OPTIONAL, map->map_mflags))
2625 syserr("451 4.3.5 NIS map %s specified, but NIS not running",
2631 /* check to see if this map actually exists */
2633 yperr = yp_match(map->map_domain, map->map_file, "@", 1,
2636 sm_dprintf("nis_map_open: yp_match(@, %s, %s) => %s\n",
2637 map->map_domain, map->map_file, yperr_string(yperr));
2641 if (yperr == 0 || yperr == YPERR_KEY || yperr == YPERR_BUSY)
2644 ** We ought to be calling aliaswait() here if this is an
2645 ** alias file, but powerful HP-UX NIS servers apparently
2646 ** don't insert the @:@ token into the alias map when it
2647 ** is rebuilt, so aliaswait() just hangs. I hate HP-UX.
2651 if (!bitset(MF_ALIAS, map->map_mflags) ||
2652 aliaswait(map, NULL, true))
2657 if (!bitset(MF_OPTIONAL, map->map_mflags))
2659 syserr("451 4.3.5 Cannot bind to map %s in domain %s: %s",
2660 map->map_file, map->map_domain, yperr_string(yperr));
2668 ** NIS_MAP_LOOKUP -- look up a datum in a NIS map
2673 nis_map_lookup(map, name, av, statp)
2683 char keybuf[MAXNAME + 1];
2684 char *SM_NONVOLATILE result = NULL;
2687 sm_dprintf("nis_map_lookup(%s, %s)\n",
2688 map->map_mname, name);
2690 buflen = strlen(name);
2691 if (buflen > sizeof keybuf - 1)
2692 buflen = sizeof keybuf - 1;
2693 memmove(keybuf, name, buflen);
2694 keybuf[buflen] = '\0';
2695 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
2699 if (bitset(MF_TRY0NULL, map->map_mflags))
2701 yperr = yp_match(map->map_domain, map->map_file, keybuf, buflen,
2704 map->map_mflags &= ~MF_TRY1NULL;
2706 if (yperr == YPERR_KEY && bitset(MF_TRY1NULL, map->map_mflags))
2710 yperr = yp_match(map->map_domain, map->map_file, keybuf, buflen,
2713 map->map_mflags &= ~MF_TRY0NULL;
2717 if (yperr != YPERR_KEY && yperr != YPERR_BUSY)
2718 map->map_mflags &= ~(MF_VALID|MF_OPEN);
2724 if (bitset(MF_MATCHONLY, map->map_mflags))
2725 result = map_rewrite(map, name, strlen(name), NULL);
2727 result = map_rewrite(map, vp, vsize, av);
2737 ** NIS_GETCANONNAME -- look up canonical name in NIS
2741 nis_getcanonname(name, hbsize, statp)
2750 static bool try0null = true;
2751 static bool try1null = true;
2752 static char *yp_domain = NULL;
2753 char host_record[MAXLINE];
2755 char nbuf[MAXNAME + 1];
2758 sm_dprintf("nis_getcanonname(%s)\n", name);
2760 if (sm_strlcpy(nbuf, name, sizeof nbuf) >= sizeof nbuf)
2762 *statp = EX_UNAVAILABLE;
2765 (void) shorten_hostname(nbuf);
2766 keylen = strlen(nbuf);
2768 if (yp_domain == NULL)
2769 (void) yp_get_default_domain(&yp_domain);
2775 yperr = yp_match(yp_domain, "hosts.byname", nbuf, keylen,
2780 if (yperr == YPERR_KEY && try1null)
2784 yperr = yp_match(yp_domain, "hosts.byname", nbuf, keylen,
2791 if (yperr == YPERR_KEY)
2793 else if (yperr == YPERR_BUSY)
2794 *statp = EX_TEMPFAIL;
2796 *statp = EX_UNAVAILABLE;
2801 (void) sm_strlcpy(host_record, vp, sizeof host_record);
2804 sm_dprintf("got record `%s'\n", host_record);
2805 vp = strpbrk(host_record, "#\n");
2808 if (!extract_canonname(nbuf, NULL, host_record, cbuf, sizeof cbuf))
2810 /* this should not happen, but.... */
2814 if (sm_strlcpy(name, cbuf, hbsize) >= hbsize)
2816 *statp = EX_UNAVAILABLE;
2827 ** This code donated by Sun Microsystems.
2832 # undef NIS /* symbol conflict in nis.h */
2833 # undef T_UNSPEC /* symbol conflict in nis.h -> ... -> sys/tiuser.h */
2834 # include <rpcsvc/nis.h>
2835 # include <rpcsvc/nislib.h>
2837 # define EN_col(col) zo_data.objdata_u.en_data.en_cols.en_cols_val[(col)].ec_value.ec_value_val
2838 # define COL_NAME(res,i) ((res->objects.objects_val)->TA_data.ta_cols.ta_cols_val)[i].tc_name
2839 # define COL_MAX(res) ((res->objects.objects_val)->TA_data.ta_cols.ta_cols_len)
2840 # define PARTIAL_NAME(x) ((x)[strlen(x) - 1] != '.')
2843 ** NISPLUS_MAP_OPEN -- open nisplus table
2847 nisplus_map_open(map, mode)
2851 nis_result *res = NULL;
2852 int retry_cnt, max_col, i;
2853 char qbuf[MAXLINE + NIS_MAXNAMELEN];
2856 sm_dprintf("nisplus_map_open(%s, %s, %d)\n",
2857 map->map_mname, map->map_file, mode);
2860 if (mode != O_RDONLY)
2866 if (*map->map_file == '\0')
2867 map->map_file = "mail_aliases.org_dir";
2869 if (PARTIAL_NAME(map->map_file) && map->map_domain == NULL)
2871 /* set default NISPLUS Domain to $m */
2872 map->map_domain = newstr(nisplus_default_domain());
2874 sm_dprintf("nisplus_map_open(%s): using domain %s\n",
2875 map->map_file, map->map_domain);
2877 if (!PARTIAL_NAME(map->map_file))
2879 map->map_domain = newstr("");
2880 (void) sm_strlcpy(qbuf, map->map_file, sizeof qbuf);
2884 /* check to see if this map actually exists */
2885 (void) sm_strlcpyn(qbuf, sizeof qbuf, 3,
2886 map->map_file, ".", map->map_domain);
2890 while (res == NULL || res->status != NIS_SUCCESS)
2892 res = nis_lookup(qbuf, FOLLOW_LINKS);
2893 switch (res->status)
2900 case NIS_NAMEUNREACHABLE:
2901 if (retry_cnt++ > 4)
2906 /* try not to overwhelm hosed server */
2910 default: /* all other nisplus errors */
2912 if (!bitset(MF_OPTIONAL, map->map_mflags))
2913 syserr("451 4.3.5 Cannot find table %s.%s: %s",
2914 map->map_file, map->map_domain,
2915 nis_sperrno(res->status));
2922 if (NIS_RES_NUMOBJ(res) != 1 ||
2923 (NIS_RES_OBJECT(res)->zo_data.zo_type != TABLE_OBJ))
2926 sm_dprintf("nisplus_map_open: %s is not a table\n", qbuf);
2928 if (!bitset(MF_OPTIONAL, map->map_mflags))
2929 syserr("451 4.3.5 %s.%s: %s is not a table",
2930 map->map_file, map->map_domain,
2931 nis_sperrno(res->status));
2936 /* default key column is column 0 */
2937 if (map->map_keycolnm == NULL)
2938 map->map_keycolnm = newstr(COL_NAME(res,0));
2940 max_col = COL_MAX(res);
2942 /* verify the key column exist */
2943 for (i = 0; i < max_col; i++)
2945 if (strcmp(map->map_keycolnm, COL_NAME(res,i)) == 0)
2951 sm_dprintf("nisplus_map_open(%s): can not find key column %s\n",
2952 map->map_file, map->map_keycolnm);
2957 /* default value column is the last column */
2958 if (map->map_valcolnm == NULL)
2960 map->map_valcolno = max_col - 1;
2964 for (i = 0; i< max_col; i++)
2966 if (strcmp(map->map_valcolnm, COL_NAME(res,i)) == 0)
2968 map->map_valcolno = i;
2974 sm_dprintf("nisplus_map_open(%s): can not find column %s\n",
2975 map->map_file, map->map_keycolnm);
2982 ** NISPLUS_MAP_LOOKUP -- look up a datum in a NISPLUS table
2986 nisplus_map_lookup(map, name, av, statp)
2996 char search_key[MAXNAME + 4];
2997 char qbuf[MAXLINE + NIS_MAXNAMELEN];
3001 sm_dprintf("nisplus_map_lookup(%s, %s)\n",
3002 map->map_mname, name);
3004 if (!bitset(MF_OPEN, map->map_mflags))
3006 if (nisplus_map_open(map, O_RDONLY))
3008 map->map_mflags |= MF_OPEN;
3009 map->map_pid = CurrentPid;
3013 *statp = EX_UNAVAILABLE;
3019 ** Copy the name to the key buffer, escaping double quote characters
3020 ** by doubling them and quoting "]" and "," to avoid having the
3021 ** NIS+ parser choke on them.
3024 skleft = sizeof search_key - 4;
3026 for (p = name; *p != '\0' && skleft > 0; p++)
3032 /* quote the character */
3040 /* double the quote */
3052 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
3053 makelower(search_key);
3055 /* construct the query */
3056 if (PARTIAL_NAME(map->map_file))
3057 (void) sm_snprintf(qbuf, sizeof qbuf, "[%s=%s],%s.%s",
3058 map->map_keycolnm, search_key, map->map_file,
3061 (void) sm_snprintf(qbuf, sizeof qbuf, "[%s=%s],%s",
3062 map->map_keycolnm, search_key, map->map_file);
3065 sm_dprintf("qbuf=%s\n", qbuf);
3066 result = nis_list(qbuf, FOLLOW_LINKS | FOLLOW_PATH, NULL, NULL);
3067 if (result->status == NIS_SUCCESS)
3072 if ((count = NIS_RES_NUMOBJ(result)) != 1)
3075 sm_syslog(LOG_WARNING, CurEnv->e_id,
3076 "%s: lookup error, expected 1 entry, got %d",
3077 map->map_file, count);
3079 /* ignore second entry */
3081 sm_dprintf("nisplus_map_lookup(%s), got %d entries, additional entries ignored\n",
3085 p = ((NIS_RES_OBJECT(result))->EN_col(map->map_valcolno));
3086 /* set the length of the result */
3091 sm_dprintf("nisplus_map_lookup(%s), found %s\n",
3093 if (bitset(MF_MATCHONLY, map->map_mflags))
3094 str = map_rewrite(map, name, strlen(name), NULL);
3096 str = map_rewrite(map, p, vsize, av);
3097 nis_freeresult(result);
3103 if (result->status == NIS_NOTFOUND)
3104 *statp = EX_NOTFOUND;
3105 else if (result->status == NIS_TRYAGAIN)
3106 *statp = EX_TEMPFAIL;
3109 *statp = EX_UNAVAILABLE;
3110 map->map_mflags &= ~(MF_VALID|MF_OPEN);
3114 sm_dprintf("nisplus_map_lookup(%s), failed\n", name);
3115 nis_freeresult(result);
3122 ** NISPLUS_GETCANONNAME -- look up canonical name in NIS+
3126 nisplus_getcanonname(name, hbsize, statp)
3135 char nbuf[MAXNAME + 1];
3136 char qbuf[MAXLINE + NIS_MAXNAMELEN];
3138 if (sm_strlcpy(nbuf, name, sizeof nbuf) >= sizeof nbuf)
3140 *statp = EX_UNAVAILABLE;
3143 (void) shorten_hostname(nbuf);
3145 p = strchr(nbuf, '.');
3149 (void) sm_snprintf(qbuf, sizeof qbuf,
3150 "[name=%s],hosts.org_dir", nbuf);
3152 else if (p[1] != '\0')
3154 /* multi token -- take only first token in nbuf */
3156 (void) sm_snprintf(qbuf, sizeof qbuf,
3157 "[name=%s],hosts.org_dir.%s", nbuf, &p[1]);
3166 sm_dprintf("\nnisplus_getcanonname(%s), qbuf=%s\n",
3169 result = nis_list(qbuf, EXPAND_NAME|FOLLOW_LINKS|FOLLOW_PATH,
3172 if (result->status == NIS_SUCCESS)
3177 if ((count = NIS_RES_NUMOBJ(result)) != 1)
3180 sm_syslog(LOG_WARNING, CurEnv->e_id,
3181 "nisplus_getcanonname: lookup error, expected 1 entry, got %d",
3184 /* ignore second entry */
3186 sm_dprintf("nisplus_getcanonname(%s), got %d entries, all but first ignored\n",
3191 sm_dprintf("nisplus_getcanonname(%s), found in directory \"%s\"\n",
3192 name, (NIS_RES_OBJECT(result))->zo_domain);
3195 vp = ((NIS_RES_OBJECT(result))->EN_col(0));
3198 sm_dprintf("nisplus_getcanonname(%s), found %s\n",
3200 if (strchr(vp, '.') != NULL)
3206 domain = macvalue('m', CurEnv);
3210 if (hbsize > vsize + (int) strlen(domain) + 1)
3212 if (domain[0] == '\0')
3213 (void) sm_strlcpy(name, vp, hbsize);
3215 (void) sm_snprintf(name, hbsize,
3216 "%s.%s", vp, domain);
3221 nis_freeresult(result);
3226 if (result->status == NIS_NOTFOUND)
3228 else if (result->status == NIS_TRYAGAIN)
3229 *statp = EX_TEMPFAIL;
3231 *statp = EX_UNAVAILABLE;
3234 sm_dprintf("nisplus_getcanonname(%s), failed, status=%d, nsw_stat=%d\n",
3235 name, result->status, *statp);
3236 nis_freeresult(result);
3241 nisplus_default_domain()
3243 static char default_domain[MAXNAME + 1] = "";
3246 if (default_domain[0] != '\0')
3247 return default_domain;
3249 p = nis_local_directory();
3250 (void) sm_strlcpy(default_domain, p, sizeof default_domain);
3251 return default_domain;
3254 #endif /* NISPLUS */
3260 ** LDAPMAP_DEQUOTE - helper routine for ldapmap_parseargs
3263 #if defined(LDAPMAP) || defined(PH_MAP)
3266 # define ph_map_dequote ldapmap_dequote
3267 # endif /* PH_MAP */
3269 static char *ldapmap_dequote __P((char *));
3272 ldapmap_dequote(str)
3284 /* Should probably swallow initial whitespace here */
3289 while (*p != '"' && *p != '\0')
3295 #endif /* defined(LDAPMAP) || defined(PH_MAP) */
3299 static SM_LDAP_STRUCT *LDAPDefaults = NULL;
3302 ** LDAPMAP_OPEN -- open LDAP map
3304 ** Connect to the LDAP server. Re-use existing connections since a
3305 ** single server connection to a host (with the same host, port,
3306 ** bind DN, and secret) can answer queries for multiple maps.
3310 ldapmap_open(map, mode)
3314 SM_LDAP_STRUCT *lmap;
3319 sm_dprintf("ldapmap_open(%s, %d): ", map->map_mname, mode);
3323 /* sendmail doesn't have the ability to write to LDAP (yet) */
3324 if (mode != O_RDONLY)
3326 /* issue a pseudo-error message */
3327 errno = SM_EMAPCANTWRITE;
3331 lmap = (SM_LDAP_STRUCT *) map->map_db1;
3333 s = ldapmap_findconn(lmap);
3334 if (s->s_lmap != NULL)
3336 /* Already have a connection open to this LDAP server */
3337 lmap->ldap_ld = ((SM_LDAP_STRUCT *)s->s_lmap->map_db1)->ldap_ld;
3338 lmap->ldap_pid = ((SM_LDAP_STRUCT *)s->s_lmap->map_db1)->ldap_pid;
3340 /* Add this map as head of linked list */
3341 lmap->ldap_next = s->s_lmap;
3345 sm_dprintf("using cached connection\n");
3350 sm_dprintf("opening new connection\n");
3352 if (lmap->ldap_host != NULL)
3353 id = lmap->ldap_host;
3354 else if (lmap->ldap_uri != NULL)
3355 id = lmap->ldap_uri;
3359 /* No connection yet, connect */
3360 if (!sm_ldap_start(map->map_mname, lmap))
3362 if (errno == ETIMEDOUT)
3365 sm_syslog(LOG_NOTICE, CurEnv->e_id,
3366 "timeout conning to LDAP server %.100s",
3370 if (!bitset(MF_OPTIONAL, map->map_mflags))
3372 if (bitset(MF_NODEFER, map->map_mflags))
3374 syserr("%s failed to %s in map %s",
3376 "ldap_init/ldap_bind",
3377 # else /* USE_LDAP_INIT */
3379 # endif /* USE_LDAP_INIT */
3380 id, map->map_mname);
3384 syserr("451 4.3.5 %s failed to %s in map %s",
3386 "ldap_init/ldap_bind",
3387 # else /* USE_LDAP_INIT */
3389 # endif /* USE_LDAP_INIT */
3390 id, map->map_mname);
3396 /* Save connection for reuse */
3402 ** LDAPMAP_CLOSE -- close ldap map
3409 SM_LDAP_STRUCT *lmap;
3413 sm_dprintf("ldapmap_close(%s)\n", map->map_mname);
3415 lmap = (SM_LDAP_STRUCT *) map->map_db1;
3417 /* Check if already closed */
3418 if (lmap->ldap_ld == NULL)
3421 /* Close the LDAP connection */
3422 sm_ldap_close(lmap);
3424 /* Mark all the maps that share the connection as closed */
3425 s = ldapmap_findconn(lmap);
3427 while (s->s_lmap != NULL)
3429 MAP *smap = s->s_lmap;
3431 if (tTd(38, 2) && smap != map)
3432 sm_dprintf("ldapmap_close(%s): closed %s (shared LDAP connection)\n",
3433 map->map_mname, smap->map_mname);
3434 smap->map_mflags &= ~(MF_OPEN|MF_WRITABLE);
3435 lmap = (SM_LDAP_STRUCT *) smap->map_db1;
3436 lmap->ldap_ld = NULL;
3437 s->s_lmap = lmap->ldap_next;
3438 lmap->ldap_next = NULL;
3444 ** SUNET_ID_HASH -- Convert a string to its Sunet_id canonical form
3445 ** This only makes sense at Stanford University.
3458 if (islower(*p) || isdigit(*p))
3463 else if (isupper(*p))
3465 *p_last = tolower(*p);
3470 if (*p_last != '\0')
3474 # endif /* SUNET_ID */
3477 ** LDAPMAP_LOOKUP -- look up a datum in a LDAP map
3481 ldapmap_lookup(map, name, av, statp)
3493 char *result = NULL;
3495 SM_LDAP_STRUCT *lmap = NULL;
3496 char keybuf[MAXNAME + 1];
3499 sm_dprintf("ldapmap_lookup(%s, %s)\n", map->map_mname, name);
3501 /* Get ldap struct pointer from map */
3502 lmap = (SM_LDAP_STRUCT *) map->map_db1;
3503 sm_ldap_setopts(lmap->ldap_ld, lmap);
3505 (void) sm_strlcpy(keybuf, name, sizeof keybuf);
3507 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
3510 sunet_id_hash(keybuf);
3511 # else /* SUNET_ID */
3513 # endif /* SUNET_ID */
3516 msgid = sm_ldap_search(lmap, keybuf);
3519 errno = sm_ldap_geterrno(lmap->ldap_ld) + E_LDAPBASE;
3521 if (!bitset(MF_OPTIONAL, map->map_mflags))
3523 if (bitset(MF_NODEFER, map->map_mflags))
3524 syserr("Error in ldap_search using %s in map %s",
3525 keybuf, map->map_mname);
3527 syserr("451 4.3.5 Error in ldap_search using %s in map %s",
3528 keybuf, map->map_mname);
3530 *statp = EX_TEMPFAIL;
3531 switch (save_errno - E_LDAPBASE)
3533 # ifdef LDAP_SERVER_DOWN
3534 case LDAP_SERVER_DOWN:
3535 # endif /* LDAP_SERVER_DOWN */
3537 case LDAP_UNAVAILABLE:
3538 /* server disappeared, try reopen on next search */
3546 *statp = EX_NOTFOUND;
3550 if (bitset(MF_SINGLEMATCH, map->map_mflags))
3551 flags |= SM_LDAP_SINGLEMATCH;
3552 if (bitset(MF_MATCHONLY, map->map_mflags))
3553 flags |= SM_LDAP_MATCHONLY;
3555 /* Create an rpool for search related memory usage */
3556 rpool = sm_rpool_new_x(NULL);
3559 *statp = sm_ldap_results(lmap, msgid, flags, map->map_coldelim,
3560 rpool, &p, &plen, &psize, NULL);
3563 /* Copy result so rpool can be freed */
3564 if (*statp == EX_OK && p != NULL)
3566 sm_rpool_free(rpool);
3568 /* need to restart LDAP connection? */
3569 if (*statp == EX_RESTART)
3571 *statp = EX_TEMPFAIL;
3576 if (*statp != EX_OK && *statp != EX_NOTFOUND)
3578 if (!bitset(MF_OPTIONAL, map->map_mflags))
3580 if (bitset(MF_NODEFER, map->map_mflags))
3581 syserr("Error getting LDAP results in map %s",
3584 syserr("451 4.3.5 Error getting LDAP results in map %s",
3591 /* Did we match anything? */
3592 if (vp == NULL && !bitset(MF_MATCHONLY, map->map_mflags))
3595 if (*statp == EX_OK)
3598 sm_syslog(LOG_INFO, CurEnv->e_id,
3599 "ldap %.100s => %s", name,
3600 vp == NULL ? "<NULL>" : vp);
3601 if (bitset(MF_MATCHONLY, map->map_mflags))
3602 result = map_rewrite(map, name, strlen(name), NULL);
3605 /* vp != NULL according to test above */
3606 result = map_rewrite(map, vp, strlen(vp), av);
3609 sm_free(vp); /* XXX */
3615 ** LDAPMAP_FINDCONN -- find an LDAP connection to the server
3617 ** Cache LDAP connections based on the host, port, bind DN,
3618 ** secret, and PID so we don't have multiple connections open to
3619 ** the same server for different maps. Need a separate connection
3620 ** per PID since a parent process may close the map before the
3621 ** child is done with it.
3624 ** lmap -- LDAP map information
3627 ** Symbol table entry for the LDAP connection.
3631 ldapmap_findconn(lmap)
3632 SM_LDAP_STRUCT *lmap;
3637 STAB *SM_NONVOLATILE s = NULL;
3639 if (lmap->ldap_host != NULL)
3640 id = lmap->ldap_host;
3641 else if (lmap->ldap_uri != NULL)
3642 id = lmap->ldap_uri;
3646 format = "%s%c%d%c%d%c%s%c%s%d";
3647 nbuf = sm_stringf_x(format,
3654 (lmap->ldap_binddn == NULL ? ""
3655 : lmap->ldap_binddn),
3657 (lmap->ldap_secret == NULL ? ""
3658 : lmap->ldap_secret),
3661 s = stab(nbuf, ST_LMAP, ST_ENTER);
3668 ** LDAPMAP_PARSEARGS -- parse ldap map definition args.
3671 static struct lamvalues LDAPAuthMethods[] =
3673 { "none", LDAP_AUTH_NONE },
3674 { "simple", LDAP_AUTH_SIMPLE },
3675 # ifdef LDAP_AUTH_KRBV4
3676 { "krbv4", LDAP_AUTH_KRBV4 },
3677 # endif /* LDAP_AUTH_KRBV4 */
3681 static struct ladvalues LDAPAliasDereference[] =
3683 { "never", LDAP_DEREF_NEVER },
3684 { "always", LDAP_DEREF_ALWAYS },
3685 { "search", LDAP_DEREF_SEARCHING },
3686 { "find", LDAP_DEREF_FINDING },
3690 static struct lssvalues LDAPSearchScope[] =
3692 { "base", LDAP_SCOPE_BASE },
3693 { "one", LDAP_SCOPE_ONELEVEL },
3694 { "sub", LDAP_SCOPE_SUBTREE },
3699 ldapmap_parseargs(map, args)
3703 bool secretread = true;
3704 bool attrssetup = false;
3706 register char *p = args;
3707 SM_LDAP_STRUCT *lmap;
3708 struct lamvalues *lam;
3709 struct ladvalues *lad;
3710 struct lssvalues *lss;
3711 char ldapfilt[MAXLINE];
3712 char m_tmp[MAXPATHLEN + LDAPMAP_MAX_PASSWD];
3714 /* Get ldap struct pointer from map */
3715 lmap = (SM_LDAP_STRUCT *) map->map_db1;
3717 /* Check if setting the initial LDAP defaults */
3718 if (lmap == NULL || lmap != LDAPDefaults)
3720 /* We need to alloc an SM_LDAP_STRUCT struct */
3721 lmap = (SM_LDAP_STRUCT *) xalloc(sizeof *lmap);
3722 if (LDAPDefaults == NULL)
3723 sm_ldap_clear(lmap);
3725 STRUCTCOPY(*LDAPDefaults, *lmap);
3728 /* there is no check whether there is really an argument */
3729 map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL;
3730 map->map_spacesub = SpaceSub; /* default value */
3732 /* Check if setting up an alias or file class LDAP map */
3733 if (bitset(MF_ALIAS, map->map_mflags))
3735 /* Comma separate if used as an alias file */
3736 map->map_coldelim = ',';
3741 char jbuf[MAXHOSTNAMELEN];
3742 char lcbuf[MAXLINE];
3745 expand("\201j", jbuf, sizeof jbuf, &BlankEnvelope);
3746 if (jbuf[0] == '\0')
3748 (void) sm_strlcpy(jbuf, "localhost",
3752 lc = macvalue(macid("{sendmailMTACluster}"), CurEnv);
3757 expand(lc, lcbuf, sizeof lcbuf, CurEnv);
3761 n = sm_snprintf(ldapfilt, sizeof ldapfilt,
3762 "(&(objectClass=sendmailMTAAliasObject)(sendmailMTAAliasGrouping=aliases)(|(sendmailMTACluster=%s)(sendmailMTAHost=%s))(sendmailMTAKey=%%0))",
3764 if (n >= sizeof ldapfilt)
3766 syserr("%s: Default LDAP string too long",
3771 /* default args for an alias LDAP entry */
3772 lmap->ldap_filter = ldapfilt;
3773 lmap->ldap_attr[0] = "objectClass";
3774 lmap->ldap_attr_type[0] = SM_LDAP_ATTR_OBJCLASS;
3775 lmap->ldap_attr_needobjclass[0] = NULL;
3776 lmap->ldap_attr[1] = "sendmailMTAAliasValue";
3777 lmap->ldap_attr_type[1] = SM_LDAP_ATTR_NORMAL;
3778 lmap->ldap_attr_needobjclass[1] = NULL;
3779 lmap->ldap_attr[2] = "sendmailMTAAliasSearch";
3780 lmap->ldap_attr_type[2] = SM_LDAP_ATTR_FILTER;
3781 lmap->ldap_attr_needobjclass[2] = "sendmailMTAMapObject";
3782 lmap->ldap_attr[3] = "sendmailMTAAliasURL";
3783 lmap->ldap_attr_type[3] = SM_LDAP_ATTR_URL;
3784 lmap->ldap_attr_needobjclass[3] = "sendmailMTAMapObject";
3785 lmap->ldap_attr[4] = NULL;
3786 lmap->ldap_attr_type[4] = SM_LDAP_ATTR_NONE;
3787 lmap->ldap_attr_needobjclass[4] = NULL;
3791 else if (bitset(MF_FILECLASS, map->map_mflags))
3793 /* Space separate if used as a file class file */
3794 map->map_coldelim = ' ';
3799 while (isascii(*p) && isspace(*p))
3806 map->map_mflags |= MF_INCLNULL;
3807 map->map_mflags &= ~MF_TRY0NULL;
3811 map->map_mflags &= ~MF_TRY1NULL;
3815 map->map_mflags |= MF_OPTIONAL;
3819 map->map_mflags |= MF_NOFOLDCASE;
3823 map->map_mflags |= MF_MATCHONLY;
3827 map->map_mflags |= MF_APPEND;
3831 map->map_mflags |= MF_KEEPQUOTES;
3839 map->map_tapp = ++p;
3843 map->map_mflags |= MF_NODEFER;
3847 map->map_spacesub = *++p;
3851 map->map_mflags |= MF_DEFER;
3856 map->map_coldelim = *p;
3862 map->map_coldelim = '\n';
3866 map->map_coldelim = '\t';
3870 map->map_coldelim = '\\';
3875 /* Start of ldapmap specific args */
3878 lmap->ldap_attrsep = *p;
3884 lmap->ldap_attrsep = '\n';
3888 lmap->ldap_attrsep = '\t';
3892 lmap->ldap_attrsep = '\\';
3897 case 'k': /* search field */
3898 while (isascii(*++p) && isspace(*p))
3900 lmap->ldap_filter = p;
3903 case 'v': /* attr to return */
3904 while (isascii(*++p) && isspace(*p))
3906 lmap->ldap_attr[0] = p;
3907 lmap->ldap_attr[1] = NULL;
3911 map->map_mflags |= MF_SINGLEMATCH;
3914 /* args stolen from ldapsearch.c */
3915 case 'R': /* don't auto chase referrals */
3916 # ifdef LDAP_REFERRALS
3917 lmap->ldap_options &= ~LDAP_OPT_REFERRALS;
3918 # else /* LDAP_REFERRALS */
3919 syserr("compile with -DLDAP_REFERRALS for referral support");
3920 # endif /* LDAP_REFERRALS */
3923 case 'n': /* retrieve attribute names only */
3924 lmap->ldap_attrsonly = LDAPMAP_TRUE;
3927 case 'r': /* alias dereferencing */
3928 while (isascii(*++p) && isspace(*p))
3931 if (sm_strncasecmp(p, "LDAP_DEREF_", 11) == 0)
3934 for (lad = LDAPAliasDereference;
3935 lad != NULL && lad->lad_name != NULL; lad++)
3937 if (sm_strncasecmp(p, lad->lad_name,
3938 strlen(lad->lad_name)) == 0)
3941 if (lad->lad_name != NULL)
3942 lmap->ldap_deref = lad->lad_code;
3945 /* bad config line */
3946 if (!bitset(MCF_OPTFILE,
3947 map->map_class->map_cflags))
3951 if ((ptr = strchr(p, ' ')) != NULL)
3953 syserr("Deref must be [never|always|search|find] (not %s) in map %s",
3962 case 's': /* search scope */
3963 while (isascii(*++p) && isspace(*p))
3966 if (sm_strncasecmp(p, "LDAP_SCOPE_", 11) == 0)
3969 for (lss = LDAPSearchScope;
3970 lss != NULL && lss->lss_name != NULL; lss++)
3972 if (sm_strncasecmp(p, lss->lss_name,
3973 strlen(lss->lss_name)) == 0)
3976 if (lss->lss_name != NULL)
3977 lmap->ldap_scope = lss->lss_code;
3980 /* bad config line */
3981 if (!bitset(MCF_OPTFILE,
3982 map->map_class->map_cflags))
3986 if ((ptr = strchr(p, ' ')) != NULL)
3988 syserr("Scope must be [base|one|sub] (not %s) in map %s",
3997 case 'h': /* ldap host */
3998 while (isascii(*++p) && isspace(*p))
4000 if (lmap->ldap_uri != NULL)
4002 syserr("Can not specify both an LDAP host and an LDAP URI in map %s",
4006 lmap->ldap_host = p;
4009 case 'b': /* search base */
4010 while (isascii(*++p) && isspace(*p))
4012 lmap->ldap_base = p;
4015 case 'p': /* ldap port */
4016 while (isascii(*++p) && isspace(*p))
4018 lmap->ldap_port = atoi(p);
4021 case 'l': /* time limit */
4022 while (isascii(*++p) && isspace(*p))
4024 lmap->ldap_timelimit = atoi(p);
4025 lmap->ldap_timeout.tv_sec = lmap->ldap_timelimit;
4029 while (isascii(*++p) && isspace(*p))
4031 lmap->ldap_sizelimit = atoi(p);
4034 case 'd': /* Dn to bind to server as */
4035 while (isascii(*++p) && isspace(*p))
4037 lmap->ldap_binddn = p;
4040 case 'M': /* Method for binding */
4041 while (isascii(*++p) && isspace(*p))
4044 if (sm_strncasecmp(p, "LDAP_AUTH_", 10) == 0)
4047 for (lam = LDAPAuthMethods;
4048 lam != NULL && lam->lam_name != NULL; lam++)
4050 if (sm_strncasecmp(p, lam->lam_name,
4051 strlen(lam->lam_name)) == 0)
4054 if (lam->lam_name != NULL)
4055 lmap->ldap_method = lam->lam_code;
4058 /* bad config line */
4059 if (!bitset(MCF_OPTFILE,
4060 map->map_class->map_cflags))
4064 if ((ptr = strchr(p, ' ')) != NULL)
4066 syserr("Method for binding must be [none|simple|krbv4] (not %s) in map %s",
4077 ** This is a string that is dependent on the
4078 ** method used defined above.
4081 case 'P': /* Secret password for binding */
4082 while (isascii(*++p) && isspace(*p))
4084 lmap->ldap_secret = p;
4088 case 'H': /* Use LDAP URI */
4090 syserr("Must compile with -DUSE_LDAP_INIT to use LDAP URIs (-H) in map %s",
4093 # else /* !USE_LDAP_INIT */
4094 if (lmap->ldap_host != NULL)
4096 syserr("Can not specify both an LDAP host and an LDAP URI in map %s",
4100 while (isascii(*++p) && isspace(*p))
4104 # endif /* !USE_LDAP_INIT */
4107 /* -w should be for passwd, -P should be for version */
4108 while (isascii(*++p) && isspace(*p))
4110 lmap->ldap_version = atoi(p);
4111 # ifdef LDAP_VERSION_MAX
4112 if (lmap->ldap_version > LDAP_VERSION_MAX)
4114 syserr("LDAP version %d exceeds max of %d in map %s",
4115 lmap->ldap_version, LDAP_VERSION_MAX,
4119 # endif /* LDAP_VERSION_MAX */
4120 # ifdef LDAP_VERSION_MIN
4121 if (lmap->ldap_version < LDAP_VERSION_MIN)
4123 syserr("LDAP version %d is lower than min of %d in map %s",
4124 lmap->ldap_version, LDAP_VERSION_MIN,
4128 # endif /* LDAP_VERSION_MIN */
4132 syserr("Illegal option %c map %s", *p, map->map_mname);
4136 /* need to account for quoted strings here */
4137 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4141 while (*++p != '"' && *p != '\0')
4154 if (map->map_app != NULL)
4155 map->map_app = newstr(ldapmap_dequote(map->map_app));
4156 if (map->map_tapp != NULL)
4157 map->map_tapp = newstr(ldapmap_dequote(map->map_tapp));
4160 ** We need to swallow up all the stuff into a struct
4161 ** and dump it into map->map_dbptr1
4164 if (lmap->ldap_host != NULL &&
4165 (LDAPDefaults == NULL ||
4166 LDAPDefaults == lmap ||
4167 LDAPDefaults->ldap_host != lmap->ldap_host))
4168 lmap->ldap_host = newstr(ldapmap_dequote(lmap->ldap_host));
4169 map->map_domain = lmap->ldap_host;
4171 if (lmap->ldap_uri != NULL &&
4172 (LDAPDefaults == NULL ||
4173 LDAPDefaults == lmap ||
4174 LDAPDefaults->ldap_uri != lmap->ldap_uri))
4175 lmap->ldap_uri = newstr(ldapmap_dequote(lmap->ldap_uri));
4176 map->map_domain = lmap->ldap_uri;
4178 if (lmap->ldap_binddn != NULL &&
4179 (LDAPDefaults == NULL ||
4180 LDAPDefaults == lmap ||
4181 LDAPDefaults->ldap_binddn != lmap->ldap_binddn))
4182 lmap->ldap_binddn = newstr(ldapmap_dequote(lmap->ldap_binddn));
4184 if (lmap->ldap_secret != NULL &&
4185 (LDAPDefaults == NULL ||
4186 LDAPDefaults == lmap ||
4187 LDAPDefaults->ldap_secret != lmap->ldap_secret))
4190 long sff = SFF_OPENASROOT|SFF_ROOTOK|SFF_NOWLINK|SFF_NOWWFILES|SFF_NOGWFILES;
4192 if (DontLockReadFiles)
4195 /* need to use method to map secret to passwd string */
4196 switch (lmap->ldap_method)
4198 case LDAP_AUTH_NONE:
4202 case LDAP_AUTH_SIMPLE:
4205 ** Secret is the name of a file with
4206 ** the first line as the password.
4209 /* Already read in the secret? */
4213 sfd = safefopen(ldapmap_dequote(lmap->ldap_secret),
4217 syserr("LDAP map: cannot open secret %s",
4218 ldapmap_dequote(lmap->ldap_secret));
4221 lmap->ldap_secret = sfgets(m_tmp, sizeof m_tmp,
4222 sfd, TimeOuts.to_fileopen,
4223 "ldapmap_parseargs");
4224 (void) sm_io_close(sfd, SM_TIME_DEFAULT);
4225 if (strlen(m_tmp) > LDAPMAP_MAX_PASSWD)
4227 syserr("LDAP map: secret in %s too long",
4228 ldapmap_dequote(lmap->ldap_secret));
4231 if (lmap->ldap_secret != NULL &&
4235 if (m_tmp[strlen(m_tmp) - 1] == '\n')
4236 m_tmp[strlen(m_tmp) - 1] = '\0';
4238 lmap->ldap_secret = m_tmp;
4242 # ifdef LDAP_AUTH_KRBV4
4243 case LDAP_AUTH_KRBV4:
4246 ** Secret is where the ticket file is
4250 (void) sm_snprintf(m_tmp, sizeof m_tmp,
4252 ldapmap_dequote(lmap->ldap_secret));
4253 lmap->ldap_secret = m_tmp;
4255 # endif /* LDAP_AUTH_KRBV4 */
4257 default: /* Should NEVER get here */
4258 syserr("LDAP map: Illegal value in lmap method");
4265 if (lmap->ldap_secret != NULL &&
4266 (LDAPDefaults == NULL ||
4267 LDAPDefaults == lmap ||
4268 LDAPDefaults->ldap_secret != lmap->ldap_secret))
4269 lmap->ldap_secret = newstr(ldapmap_dequote(lmap->ldap_secret));
4271 if (lmap->ldap_base != NULL &&
4272 (LDAPDefaults == NULL ||
4273 LDAPDefaults == lmap ||
4274 LDAPDefaults->ldap_base != lmap->ldap_base))
4275 lmap->ldap_base = newstr(ldapmap_dequote(lmap->ldap_base));
4278 ** Save the server from extra work. If request is for a single
4279 ** match, tell the server to only return enough records to
4280 ** determine if there is a single match or not. This can not
4281 ** be one since the server would only return one and we wouldn't
4282 ** know if there were others available.
4285 if (bitset(MF_SINGLEMATCH, map->map_mflags))
4286 lmap->ldap_sizelimit = 2;
4288 /* If setting defaults, don't process ldap_filter and ldap_attr */
4289 if (lmap == LDAPDefaults)
4292 if (lmap->ldap_filter != NULL)
4293 lmap->ldap_filter = newstr(ldapmap_dequote(lmap->ldap_filter));
4296 if (!bitset(MCF_OPTFILE, map->map_class->map_cflags))
4298 syserr("No filter given in map %s", map->map_mname);
4303 if (!attrssetup && lmap->ldap_attr[0] != NULL)
4305 bool recurse = false;
4306 bool normalseen = false;
4309 p = ldapmap_dequote(lmap->ldap_attr[0]);
4310 lmap->ldap_attr[0] = NULL;
4312 /* Prime the attr list with the objectClass attribute */
4313 lmap->ldap_attr[i] = "objectClass";
4314 lmap->ldap_attr_type[i] = SM_LDAP_ATTR_OBJCLASS;
4315 lmap->ldap_attr_needobjclass[i] = NULL;
4322 while (isascii(*p) && isspace(*p))
4331 if (i >= LDAPMAP_MAX_ATTR)
4333 syserr("Too many return attributes in %s (max %d)",
4334 map->map_mname, LDAPMAP_MAX_ATTR);
4344 type = strchr(v, ':');
4348 needobjclass = strchr(type, ':');
4349 if (needobjclass != NULL)
4350 *needobjclass++ = '\0';
4354 needobjclass = NULL;
4359 /* allow override on "objectClass" type */
4360 if (sm_strcasecmp(v, "objectClass") == 0 &&
4361 lmap->ldap_attr_type[0] == SM_LDAP_ATTR_OBJCLASS)
4368 ** Don't add something to attribute
4372 for (j = 1; j < i; j++)
4374 if (sm_strcasecmp(v, lmap->ldap_attr[j]) == 0)
4376 syserr("Duplicate attribute (%s) in %s",
4382 lmap->ldap_attr[use] = newstr(v);
4383 if (needobjclass != NULL &&
4384 *needobjclass != '\0' &&
4385 *needobjclass != '*')
4387 lmap->ldap_attr_needobjclass[use] = newstr(needobjclass);
4391 lmap->ldap_attr_needobjclass[use] = NULL;
4396 if (type != NULL && *type != '\0')
4398 if (sm_strcasecmp(type, "dn") == 0)
4401 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_DN;
4403 else if (sm_strcasecmp(type, "filter") == 0)
4406 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_FILTER;
4408 else if (sm_strcasecmp(type, "url") == 0)
4411 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_URL;
4413 else if (sm_strcasecmp(type, "normal") == 0)
4415 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_NORMAL;
4420 syserr("Unknown attribute type (%s) in %s",
4421 type, map->map_mname);
4427 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_NORMAL;
4433 lmap->ldap_attr[i] = NULL;
4435 /* Set in case needed in future code */
4438 if (recurse && !normalseen)
4440 syserr("LDAP recursion requested in %s but no returnable attribute given",
4444 if (recurse && lmap->ldap_attrsonly == LDAPMAP_TRUE)
4446 syserr("LDAP recursion requested in %s can not be used with -n",
4451 map->map_db1 = (ARBPTR_T) lmap;
4456 ** LDAPMAP_SET_DEFAULTS -- Read default map spec from LDAPDefaults in .cf
4459 ** spec -- map argument string from LDAPDefaults option
4466 ldapmap_set_defaults(spec)
4472 /* Allocate and set the default values */
4473 if (LDAPDefaults == NULL)
4474 LDAPDefaults = (SM_LDAP_STRUCT *) xalloc(sizeof *LDAPDefaults);
4475 sm_ldap_clear(LDAPDefaults);
4477 memset(&map, '\0', sizeof map);
4479 /* look up the class */
4480 class = stab("ldap", ST_MAPCLASS, ST_FIND);
4483 syserr("readcf: LDAPDefaultSpec: class ldap not available");
4486 map.map_class = &class->s_mapclass;
4487 map.map_db1 = (ARBPTR_T) LDAPDefaults;
4488 map.map_mname = "O LDAPDefaultSpec";
4490 (void) ldapmap_parseargs(&map, spec);
4492 /* These should never be set in LDAPDefaults */
4493 if (map.map_mflags != (MF_TRY0NULL|MF_TRY1NULL) ||
4494 map.map_spacesub != SpaceSub ||
4495 map.map_app != NULL ||
4496 map.map_tapp != NULL)
4498 syserr("readcf: option LDAPDefaultSpec: Do not set non-LDAP specific flags");
4499 SM_FREE_CLR(map.map_app);
4500 SM_FREE_CLR(map.map_tapp);
4503 if (LDAPDefaults->ldap_filter != NULL)
4505 syserr("readcf: option LDAPDefaultSpec: Do not set the LDAP search filter");
4507 /* don't free, it isn't malloc'ed in parseargs */
4508 LDAPDefaults->ldap_filter = NULL;
4511 if (LDAPDefaults->ldap_attr[0] != NULL)
4513 syserr("readcf: option LDAPDefaultSpec: Do not set the requested LDAP attributes");
4514 /* don't free, they aren't malloc'ed in parseargs */
4515 LDAPDefaults->ldap_attr[0] = NULL;
4518 #endif /* LDAPMAP */
4526 ** Support for the CCSO Nameserver (ph/qi).
4527 ** This code is intended to replace the so-called "ph mailer".
4528 ** Contributed by Mark D. Roth <roth@uiuc.edu>. Contact him for support.
4531 /* what version of the ph map code we're running */
4532 static char phmap_id[128];
4534 /* sendmail version for phmap id string */
4535 extern const char Version[];
4537 /* assume we're using nph-1.2.x if not specified */
4538 # ifndef NPH_VERSION
4539 # define NPH_VERSION 10200
4542 /* compatibility for versions older than nph-1.2.0 */
4543 # if NPH_VERSION < 10200
4544 # define PH_OPEN_ROUNDROBIN PH_ROUNDROBIN
4545 # define PH_OPEN_DONTID PH_DONTID
4546 # define PH_CLOSE_FAST PH_FASTCLOSE
4547 # define PH_ERR_DATAERR PH_DATAERR
4548 # define PH_ERR_NOMATCH PH_NOMATCH
4549 # endif /* NPH_VERSION < 10200 */
4552 ** PH_MAP_PARSEARGS -- parse ph map definition args.
4556 ph_map_parseargs(map, args)
4561 register char *p = args;
4562 PH_MAP_STRUCT *pmap = NULL;
4564 /* initialize version string */
4565 (void) sm_snprintf(phmap_id, sizeof phmap_id,
4566 "sendmail-%s phmap-20010529 libphclient-%s",
4567 Version, libphclient_version);
4569 pmap = (PH_MAP_STRUCT *) xalloc(sizeof *pmap);
4572 pmap->ph_servers = NULL;
4573 pmap->ph_field_list = NULL;
4575 pmap->ph_timeout = 0;
4576 pmap->ph_fastclose = 0;
4578 map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL;
4581 while (isascii(*p) && isspace(*p))
4588 map->map_mflags |= MF_INCLNULL;
4589 map->map_mflags &= ~MF_TRY0NULL;
4593 map->map_mflags &= ~MF_TRY1NULL;
4597 map->map_mflags |= MF_OPTIONAL;
4601 map->map_mflags |= MF_NOFOLDCASE;
4605 map->map_mflags |= MF_MATCHONLY;
4609 map->map_mflags |= MF_APPEND;
4613 map->map_mflags |= MF_KEEPQUOTES;
4617 map->map_mflags |= MF_NODEFER;
4625 map->map_tapp = ++p;
4629 while (isascii(*++p) && isspace(*p))
4631 pmap->ph_timeout = atoi(p);
4635 map->map_spacesub = *++p;
4639 map->map_mflags |= MF_DEFER;
4642 case 'h': /* PH server list */
4643 while (isascii(*++p) && isspace(*p))
4645 pmap->ph_servers = p;
4648 case 'k': /* fields to search for */
4649 while (isascii(*++p) && isspace(*p))
4651 pmap->ph_field_list = p;
4655 syserr("ph_map_parseargs: unknown option -%c", *p);
4658 /* try to account for quoted strings */
4659 done = isascii(*p) && isspace(*p);
4660 while (*p != '\0' && !done)
4664 while (*++p != '"' && *p != '\0')
4671 done = isascii(*p) && isspace(*p);
4678 if (map->map_app != NULL)
4679 map->map_app = newstr(ph_map_dequote(map->map_app));
4680 if (map->map_tapp != NULL)
4681 map->map_tapp = newstr(ph_map_dequote(map->map_tapp));
4683 if (pmap->ph_field_list != NULL)
4684 pmap->ph_field_list = newstr(ph_map_dequote(pmap->ph_field_list));
4686 if (pmap->ph_servers != NULL)
4687 pmap->ph_servers = newstr(ph_map_dequote(pmap->ph_servers));
4690 syserr("ph_map_parseargs: -h flag is required");
4694 map->map_db1 = (ARBPTR_T) pmap;
4699 ** PH_MAP_CLOSE -- close the connection to the ph server
4706 PH_MAP_STRUCT *pmap;
4708 pmap = (PH_MAP_STRUCT *)map->map_db1;
4710 sm_dprintf("ph_map_close(%s): pmap->ph_fastclose=%d\n",
4711 map->map_mname, pmap->ph_fastclose);
4714 if (pmap->ph != NULL)
4716 ph_set_sendhook(pmap->ph, NULL);
4717 ph_set_recvhook(pmap->ph, NULL);
4718 ph_close(pmap->ph, pmap->ph_fastclose);
4721 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE);
4724 static jmp_buf PHTimeout;
4732 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
4733 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
4738 longjmp(PHTimeout, 1);
4742 #if NPH_VERSION >= 10200
4743 ph_map_send_debug(appdata, text)
4746 ph_map_send_debug(text)
4751 sm_syslog(LOG_NOTICE, CurEnv->e_id,
4752 "ph_map_send_debug: ==> %s", text);
4754 sm_dprintf("ph_map_send_debug: ==> %s\n", text);
4758 #if NPH_VERSION >= 10200
4759 ph_map_recv_debug(appdata, text)
4762 ph_map_recv_debug(text)
4767 sm_syslog(LOG_NOTICE, CurEnv->e_id,
4768 "ph_map_recv_debug: <== %s", text);
4770 sm_dprintf("ph_map_recv_debug: <== %s\n", text);
4774 ** PH_MAP_OPEN -- sub for opening PH map
4777 ph_map_open(map, mode)
4781 PH_MAP_STRUCT *pmap;
4782 register SM_EVENT *ev = NULL;
4784 char *hostlist, *host;
4787 sm_dprintf("ph_map_open(%s)\n", map->map_mname);
4790 if (mode != O_RDONLY)
4792 /* issue a pseudo-error message */
4793 errno = SM_EMAPCANTWRITE;
4797 if (CurEnv != NULL && CurEnv->e_sendmode == SM_DEFER &&
4798 bitset(MF_DEFER, map->map_mflags))
4801 sm_dprintf("ph_map_open(%s) => DEFERRED\n",
4805 ** Unset MF_DEFER here so that map_lookup() returns
4806 ** a temporary failure using the bogus map and
4807 ** map->map_tapp instead of the default permanent error.
4810 map->map_mflags &= ~MF_DEFER;
4814 pmap = (PH_MAP_STRUCT *)map->map_db1;
4815 pmap->ph_fastclose = 0; /* refresh field for reopen */
4817 /* try each host in the list */
4818 hostlist = newstr(pmap->ph_servers);
4819 for (host = strtok(hostlist, " ");
4821 host = strtok(NULL, " "))
4824 if (pmap->ph_timeout != 0)
4826 if (setjmp(PHTimeout) != 0)
4830 sm_syslog(LOG_NOTICE, CurEnv->e_id,
4831 "timeout connecting to PH server %.100s",
4834 goto ph_map_open_abort;
4836 ev = sm_setevent(pmap->ph_timeout, ph_timeout, 0);
4839 /* open connection to server */
4840 if (ph_open(&(pmap->ph), host,
4841 PH_OPEN_ROUNDROBIN|PH_OPEN_DONTID,
4842 ph_map_send_debug, ph_map_recv_debug
4843 #if NPH_VERSION >= 10200
4847 && ph_id(pmap->ph, phmap_id) == 0)
4851 sm_free(hostlist); /* XXX */
4859 pmap->ph_fastclose = PH_CLOSE_FAST;
4864 if (bitset(MF_NODEFER, map->map_mflags))
4868 syserr("ph_map_open: %s: cannot connect to PH server",
4871 else if (!bitset(MF_OPTIONAL, map->map_mflags) && LogLevel > 1)
4872 sm_syslog(LOG_NOTICE, CurEnv->e_id,
4873 "ph_map_open: %s: cannot connect to PH server",
4875 sm_free(hostlist); /* XXX */
4880 ** PH_MAP_LOOKUP -- look up key from ph server
4884 ph_map_lookup(map, key, args, pstat)
4890 int i, save_errno = 0;
4891 register SM_EVENT *ev = NULL;
4892 PH_MAP_STRUCT *pmap;
4895 pmap = (PH_MAP_STRUCT *)map->map_db1;
4900 if (pmap->ph_timeout != 0)
4902 if (setjmp(PHTimeout) != 0)
4906 sm_syslog(LOG_NOTICE, CurEnv->e_id,
4907 "timeout during PH lookup of %.100s",
4910 *pstat = EX_TEMPFAIL;
4911 goto ph_map_lookup_abort;
4913 ev = sm_setevent(pmap->ph_timeout, ph_timeout, 0);
4916 /* perform lookup */
4917 i = ph_email_resolve(pmap->ph, key, pmap->ph_field_list, &value);
4919 *pstat = EX_TEMPFAIL;
4920 else if (i == PH_ERR_NOMATCH || i == PH_ERR_DATAERR)
4921 *pstat = EX_UNAVAILABLE;
4923 ph_map_lookup_abort:
4928 ** Close the connection if the timer popped
4929 ** or we got a temporary PH error
4932 if (*pstat == EX_TEMPFAIL)
4935 pmap->ph_fastclose = PH_CLOSE_FAST;
4940 if (*pstat == EX_OK)
4943 sm_dprintf("ph_map_lookup: %s => %s\n", key, value);
4945 if (bitset(MF_MATCHONLY, map->map_mflags))
4946 return map_rewrite(map, key, strlen(key), NULL);
4948 return map_rewrite(map, value, strlen(value), args);
4958 #define map_prio map_lockfd /* overload field */
4961 ** SYSLOG_MAP_PARSEARGS -- check for priority level to syslog messages.
4965 syslog_map_parseargs(map, args)
4970 char *priority = NULL;
4972 /* there is no check whether there is really an argument */
4975 while (isascii(*p) && isspace(*p))
4982 map->map_mflags |= MF_DEFER;
4987 map->map_spacesub = *++p;
4993 while (*++p != '\0' && isascii(*p) && isspace(*p))
4998 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
5005 syserr("Illegal option %c map syslog", *p);
5010 if (priority == NULL)
5011 map->map_prio = LOG_INFO;
5014 if (sm_strncasecmp("LOG_", priority, 4) == 0)
5018 if (sm_strcasecmp("EMERG", priority) == 0)
5019 map->map_prio = LOG_EMERG;
5021 #endif /* LOG_EMERG */
5023 if (sm_strcasecmp("ALERT", priority) == 0)
5024 map->map_prio = LOG_ALERT;
5026 #endif /* LOG_ALERT */
5028 if (sm_strcasecmp("CRIT", priority) == 0)
5029 map->map_prio = LOG_CRIT;
5031 #endif /* LOG_CRIT */
5033 if (sm_strcasecmp("ERR", priority) == 0)
5034 map->map_prio = LOG_ERR;
5036 #endif /* LOG_ERR */
5038 if (sm_strcasecmp("WARNING", priority) == 0)
5039 map->map_prio = LOG_WARNING;
5041 #endif /* LOG_WARNING */
5043 if (sm_strcasecmp("NOTICE", priority) == 0)
5044 map->map_prio = LOG_NOTICE;
5046 #endif /* LOG_NOTICE */
5048 if (sm_strcasecmp("INFO", priority) == 0)
5049 map->map_prio = LOG_INFO;
5051 #endif /* LOG_INFO */
5053 if (sm_strcasecmp("DEBUG", priority) == 0)
5054 map->map_prio = LOG_DEBUG;
5056 #endif /* LOG_DEBUG */
5058 syserr("syslog_map_parseargs: Unknown priority %s",
5067 ** SYSLOG_MAP_LOOKUP -- rewrite and syslog message. Always return empty string
5071 syslog_map_lookup(map, string, args, statp)
5077 char *ptr = map_rewrite(map, string, strlen(string), args);
5082 sm_dprintf("syslog_map_lookup(%s (priority %d): %s\n",
5083 map->map_mname, map->map_prio, ptr);
5085 sm_syslog(map->map_prio, CurEnv->e_id, "%s", ptr);
5099 hes_map_open(map, mode)
5104 sm_dprintf("hes_map_open(%s, %s, %d)\n",
5105 map->map_mname, map->map_file, mode);
5107 if (mode != O_RDONLY)
5109 /* issue a pseudo-error message */
5110 errno = SM_EMAPCANTWRITE;
5115 if (HesiodContext != NULL || hesiod_init(&HesiodContext) == 0)
5118 if (!bitset(MF_OPTIONAL, map->map_mflags))
5119 syserr("451 4.3.5 cannot initialize Hesiod map (%s)",
5120 sm_errstring(errno));
5122 # else /* HESIOD_INIT */
5123 if (hes_error() == HES_ER_UNINIT)
5125 switch (hes_error())
5128 case HES_ER_NOTFOUND:
5132 if (!bitset(MF_OPTIONAL, map->map_mflags))
5133 syserr("451 4.3.5 cannot initialize Hesiod map (%d)", hes_error());
5136 # endif /* HESIOD_INIT */
5140 hes_map_lookup(map, name, av, statp)
5149 sm_dprintf("hes_map_lookup(%s, %s)\n", map->map_file, name);
5151 if (name[0] == '\\')
5159 if (nl < sizeof nbuf - 1)
5162 np = xalloc(strlen(name) + 2);
5164 (void) sm_strlcpy(&np[1], name, (sizeof nbuf) - 1);
5166 hp = hesiod_resolve(HesiodContext, np, map->map_file);
5167 # else /* HESIOD_INIT */
5168 hp = hes_resolve(np, map->map_file);
5169 # endif /* HESIOD_INIT */
5172 sm_free(np); /* XXX */
5178 hp = hesiod_resolve(HesiodContext, name, map->map_file);
5179 # else /* HESIOD_INIT */
5180 hp = hes_resolve(name, map->map_file);
5181 # endif /* HESIOD_INIT */
5184 if (hp == NULL || *hp == NULL)
5189 *statp = EX_NOTFOUND;
5192 *statp = EX_TEMPFAIL;
5197 *statp = EX_UNAVAILABLE;
5201 hesiod_free_list(HesiodContext, hp);
5204 # else /* HESIOD_INIT */
5205 if (hp == NULL || hp[0] == NULL)
5207 switch (hes_error())
5213 case HES_ER_NOTFOUND:
5214 *statp = EX_NOTFOUND;
5218 *statp = EX_UNAVAILABLE;
5222 *statp = EX_TEMPFAIL;
5227 # endif /* HESIOD_INIT */
5229 if (bitset(MF_MATCHONLY, map->map_mflags))
5230 return map_rewrite(map, name, strlen(name), NULL);
5232 return map_rewrite(map, hp[0], strlen(hp[0]), av);
5236 ** HES_MAP_CLOSE -- free the Hesiod context
5244 sm_dprintf("hes_map_close(%s)\n", map->map_file);
5247 /* Free the hesiod context */
5248 if (HesiodContext != NULL)
5250 hesiod_end(HesiodContext);
5251 HesiodContext = NULL;
5253 # endif /* HESIOD_INIT */
5258 ** NeXT NETINFO Modules
5263 # define NETINFO_DEFAULT_DIR "/aliases"
5264 # define NETINFO_DEFAULT_PROPERTY "members"
5267 ** NI_MAP_OPEN -- open NetInfo Aliases
5271 ni_map_open(map, mode)
5276 sm_dprintf("ni_map_open(%s, %s, %d)\n",
5277 map->map_mname, map->map_file, mode);
5280 if (*map->map_file == '\0')
5281 map->map_file = NETINFO_DEFAULT_DIR;
5283 if (map->map_valcolnm == NULL)
5284 map->map_valcolnm = NETINFO_DEFAULT_PROPERTY;
5286 if (map->map_coldelim == '\0')
5288 if (bitset(MF_ALIAS, map->map_mflags))
5289 map->map_coldelim = ',';
5290 else if (bitset(MF_FILECLASS, map->map_mflags))
5291 map->map_coldelim = ' ';
5298 ** NI_MAP_LOOKUP -- look up a datum in NetInfo
5302 ni_map_lookup(map, name, av, statp)
5312 sm_dprintf("ni_map_lookup(%s, %s)\n", map->map_mname, name);
5314 propval = ni_propval(map->map_file, map->map_keycolnm, name,
5315 map->map_valcolnm, map->map_coldelim);
5317 if (propval == NULL)
5321 if (bitset(MF_MATCHONLY, map->map_mflags))
5322 res = map_rewrite(map, name, strlen(name), NULL);
5324 res = map_rewrite(map, propval, strlen(propval), av);
5333 ni_getcanonname(name, hbsize, statp)
5340 char nbuf[MAXNAME + 1];
5343 sm_dprintf("ni_getcanonname(%s)\n", name);
5345 if (sm_strlcpy(nbuf, name, sizeof nbuf) >= sizeof nbuf)
5347 *statp = EX_UNAVAILABLE;
5350 (void) shorten_hostname(nbuf);
5352 /* we only accept single token search key */
5353 if (strchr(nbuf, '.'))
5360 vptr = ni_propval("/machines", NULL, nbuf, "name", '\n');
5368 /* Only want the first machine name */
5369 if ((ptr = strchr(vptr, '\n')) != NULL)
5372 if (sm_strlcpy(name, vptr, hbsize) >= hbsize)
5375 *statp = EX_UNAVAILABLE;
5382 #endif /* NETINFO */
5384 ** TEXT (unindexed text file) Modules
5386 ** This code donated by Sun Microsystems.
5389 #define map_sff map_lockfd /* overload field */
5393 ** TEXT_MAP_OPEN -- open text table
5397 text_map_open(map, mode)
5405 sm_dprintf("text_map_open(%s, %s, %d)\n",
5406 map->map_mname, map->map_file, mode);
5409 if (mode != O_RDONLY)
5415 if (*map->map_file == '\0')
5417 syserr("text map \"%s\": file name required",
5422 if (map->map_file[0] != '/')
5424 syserr("text map \"%s\": file name must be fully qualified",
5429 sff = SFF_ROOTOK|SFF_REGONLY;
5430 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
5432 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
5433 sff |= SFF_SAFEDIRPATH;
5434 if ((i = safefile(map->map_file, RunAsUid, RunAsGid, RunAsUserName,
5435 sff, S_IRUSR, NULL)) != 0)
5437 int save_errno = errno;
5439 /* cannot open this map */
5441 sm_dprintf("\tunsafe map file: %d\n", i);
5443 if (!bitset(MF_OPTIONAL, map->map_mflags))
5444 syserr("text map \"%s\": unsafe map file %s",
5445 map->map_mname, map->map_file);
5449 if (map->map_keycolnm == NULL)
5450 map->map_keycolno = 0;
5453 if (!(isascii(*map->map_keycolnm) && isdigit(*map->map_keycolnm)))
5455 syserr("text map \"%s\", file %s: -k should specify a number, not %s",
5456 map->map_mname, map->map_file,
5460 map->map_keycolno = atoi(map->map_keycolnm);
5463 if (map->map_valcolnm == NULL)
5464 map->map_valcolno = 0;
5467 if (!(isascii(*map->map_valcolnm) && isdigit(*map->map_valcolnm)))
5469 syserr("text map \"%s\", file %s: -v should specify a number, not %s",
5470 map->map_mname, map->map_file,
5474 map->map_valcolno = atoi(map->map_valcolnm);
5479 sm_dprintf("text_map_open(%s, %s): delimiter = ",
5480 map->map_mname, map->map_file);
5481 if (map->map_coldelim == '\0')
5482 sm_dprintf("(white space)\n");
5484 sm_dprintf("%c\n", map->map_coldelim);
5493 ** TEXT_MAP_LOOKUP -- look up a datum in a TEXT table
5497 text_map_lookup(map, name, av, statp)
5510 long sff = map->map_sff;
5511 char search_key[MAXNAME + 1];
5512 char linebuf[MAXLINE];
5513 char buf[MAXNAME + 1];
5517 sm_dprintf("text_map_lookup(%s, %s)\n", map->map_mname, name);
5519 buflen = strlen(name);
5520 if (buflen > sizeof search_key - 1)
5521 buflen = sizeof search_key - 1; /* XXX just cut if off? */
5522 memmove(search_key, name, buflen);
5523 search_key[buflen] = '\0';
5524 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
5525 makelower(search_key);
5527 f = safefopen(map->map_file, O_RDONLY, FileMode, sff);
5530 map->map_mflags &= ~(MF_VALID|MF_OPEN);
5531 *statp = EX_UNAVAILABLE;
5534 key_idx = map->map_keycolno;
5535 delim = map->map_coldelim;
5536 while (sm_io_fgets(f, SM_TIME_DEFAULT,
5537 linebuf, sizeof linebuf) != NULL)
5541 /* skip comment line */
5542 if (linebuf[0] == '#')
5544 p = strchr(linebuf, '\n');
5547 p = get_column(linebuf, key_idx, delim, buf, sizeof buf);
5548 if (p != NULL && sm_strcasecmp(search_key, p) == 0)
5554 (void) sm_io_close(f, SM_TIME_DEFAULT);
5557 *statp = EX_NOTFOUND;
5560 vp = get_column(linebuf, map->map_valcolno, delim, buf, sizeof buf);
5563 *statp = EX_NOTFOUND;
5568 if (bitset(MF_MATCHONLY, map->map_mflags))
5569 return map_rewrite(map, name, strlen(name), NULL);
5571 return map_rewrite(map, vp, vsize, av);
5575 ** TEXT_GETCANONNAME -- look up canonical name in hosts file
5579 text_getcanonname(name, hbsize, statp)
5587 char linebuf[MAXLINE];
5588 char cbuf[MAXNAME + 1];
5589 char nbuf[MAXNAME + 1];
5592 sm_dprintf("text_getcanonname(%s)\n", name);
5594 if (sm_strlcpy(nbuf, name, sizeof nbuf) >= sizeof nbuf)
5596 *statp = EX_UNAVAILABLE;
5599 dot = shorten_hostname(nbuf);
5601 f = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, HostsFile, SM_IO_RDONLY,
5605 *statp = EX_UNAVAILABLE;
5610 sm_io_fgets(f, SM_TIME_DEFAULT,
5611 linebuf, sizeof linebuf) != NULL)
5613 char *p = strpbrk(linebuf, "#\n");
5617 if (linebuf[0] != '\0')
5618 found = extract_canonname(nbuf, dot, linebuf,
5621 (void) sm_io_close(f, SM_TIME_DEFAULT);
5628 if (sm_strlcpy(name, cbuf, hbsize) >= hbsize)
5630 *statp = EX_UNAVAILABLE;
5637 ** STAB (Symbol Table) Modules
5642 ** STAB_MAP_LOOKUP -- look up alias in symbol table
5647 stab_map_lookup(map, name, av, pstat)
5656 sm_dprintf("stab_lookup(%s, %s)\n",
5657 map->map_mname, name);
5659 s = stab(name, ST_ALIAS, ST_FIND);
5662 if (bitset(MF_MATCHONLY, map->map_mflags))
5663 return map_rewrite(map, name, strlen(name), NULL);
5665 return map_rewrite(map, s->s_alias, strlen(s->s_alias), av);
5669 ** STAB_MAP_STORE -- store in symtab (actually using during init, not rebuild)
5673 stab_map_store(map, lhs, rhs)
5680 s = stab(lhs, ST_ALIAS, ST_ENTER);
5681 s->s_alias = newstr(rhs);
5686 ** STAB_MAP_OPEN -- initialize (reads data file)
5688 ** This is a wierd case -- it is only intended as a fallback for
5689 ** aliases. For this reason, opens for write (only during a
5690 ** "newaliases") always fails, and opens for read open the
5691 ** actual underlying text file instead of the database.
5695 stab_map_open(map, mode)
5704 sm_dprintf("stab_map_open(%s, %s, %d)\n",
5705 map->map_mname, map->map_file, mode);
5708 if (mode != O_RDONLY)
5714 sff = SFF_ROOTOK|SFF_REGONLY;
5715 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
5717 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
5718 sff |= SFF_SAFEDIRPATH;
5719 af = safefopen(map->map_file, O_RDONLY, 0444, sff);
5722 readaliases(map, af, false, false);
5724 if (fstat(sm_io_getinfo(af, SM_IO_WHAT_FD, NULL), &st) >= 0)
5725 map->map_mtime = st.st_mtime;
5726 (void) sm_io_close(af, SM_TIME_DEFAULT);
5733 ** Tries several types. For back compatibility of aliases.
5738 ** IMPL_MAP_LOOKUP -- lookup in best open database
5742 impl_map_lookup(map, name, av, pstat)
5749 sm_dprintf("impl_map_lookup(%s, %s)\n",
5750 map->map_mname, name);
5753 if (bitset(MF_IMPL_HASH, map->map_mflags))
5754 return db_map_lookup(map, name, av, pstat);
5757 if (bitset(MF_IMPL_NDBM, map->map_mflags))
5758 return ndbm_map_lookup(map, name, av, pstat);
5760 return stab_map_lookup(map, name, av, pstat);
5764 ** IMPL_MAP_STORE -- store in open databases
5768 impl_map_store(map, lhs, rhs)
5774 sm_dprintf("impl_map_store(%s, %s, %s)\n",
5775 map->map_mname, lhs, rhs);
5777 if (bitset(MF_IMPL_HASH, map->map_mflags))
5778 db_map_store(map, lhs, rhs);
5781 if (bitset(MF_IMPL_NDBM, map->map_mflags))
5782 ndbm_map_store(map, lhs, rhs);
5784 stab_map_store(map, lhs, rhs);
5788 ** IMPL_MAP_OPEN -- implicit database open
5792 impl_map_open(map, mode)
5797 sm_dprintf("impl_map_open(%s, %s, %d)\n",
5798 map->map_mname, map->map_file, mode);
5802 map->map_mflags |= MF_IMPL_HASH;
5803 if (hash_map_open(map, mode))
5805 # ifdef NDBM_YP_COMPAT
5806 if (mode == O_RDONLY || strstr(map->map_file, "/yp/") == NULL)
5807 # endif /* NDBM_YP_COMPAT */
5811 map->map_mflags &= ~MF_IMPL_HASH;
5814 map->map_mflags |= MF_IMPL_NDBM;
5815 if (ndbm_map_open(map, mode))
5820 map->map_mflags &= ~MF_IMPL_NDBM;
5823 #if defined(NEWDB) || defined(NDBM)
5825 message("WARNING: cannot open alias database %s%s",
5827 mode == O_RDONLY ? "; reading text version" : "");
5828 #else /* defined(NEWDB) || defined(NDBM) */
5829 if (mode != O_RDONLY)
5830 usrerr("Cannot rebuild aliases: no database format defined");
5831 #endif /* defined(NEWDB) || defined(NDBM) */
5833 if (mode == O_RDONLY)
5834 return stab_map_open(map, mode);
5841 ** IMPL_MAP_CLOSE -- close any open database(s)
5849 sm_dprintf("impl_map_close(%s, %s, %lx)\n",
5850 map->map_mname, map->map_file, map->map_mflags);
5852 if (bitset(MF_IMPL_HASH, map->map_mflags))
5855 map->map_mflags &= ~MF_IMPL_HASH;
5860 if (bitset(MF_IMPL_NDBM, map->map_mflags))
5862 ndbm_map_close(map);
5863 map->map_mflags &= ~MF_IMPL_NDBM;
5870 ** Provides access to the system password file.
5874 ** USER_MAP_OPEN -- open user map
5876 ** Really just binds field names to field numbers.
5880 user_map_open(map, mode)
5885 sm_dprintf("user_map_open(%s, %d)\n",
5886 map->map_mname, mode);
5889 if (mode != O_RDONLY)
5891 /* issue a pseudo-error message */
5892 errno = SM_EMAPCANTWRITE;
5895 if (map->map_valcolnm == NULL)
5898 else if (sm_strcasecmp(map->map_valcolnm, "name") == 0)
5899 map->map_valcolno = 1;
5900 else if (sm_strcasecmp(map->map_valcolnm, "passwd") == 0)
5901 map->map_valcolno = 2;
5902 else if (sm_strcasecmp(map->map_valcolnm, "uid") == 0)
5903 map->map_valcolno = 3;
5904 else if (sm_strcasecmp(map->map_valcolnm, "gid") == 0)
5905 map->map_valcolno = 4;
5906 else if (sm_strcasecmp(map->map_valcolnm, "gecos") == 0)
5907 map->map_valcolno = 5;
5908 else if (sm_strcasecmp(map->map_valcolnm, "dir") == 0)
5909 map->map_valcolno = 6;
5910 else if (sm_strcasecmp(map->map_valcolnm, "shell") == 0)
5911 map->map_valcolno = 7;
5914 syserr("User map %s: unknown column name %s",
5915 map->map_mname, map->map_valcolnm);
5923 ** USER_MAP_LOOKUP -- look up a user in the passwd file.
5928 user_map_lookup(map, key, av, statp)
5938 sm_dprintf("user_map_lookup(%s, %s)\n",
5939 map->map_mname, key);
5941 *statp = finduser(key, &fuzzy, &user);
5942 if (*statp != EX_OK)
5944 if (bitset(MF_MATCHONLY, map->map_mflags))
5945 return map_rewrite(map, key, strlen(key), NULL);
5951 switch (map->map_valcolno)
5955 rwval = user.mbdb_name;
5959 rwval = "x"; /* passwd no longer supported */
5963 (void) sm_snprintf(buf, sizeof buf, "%d",
5964 (int) user.mbdb_uid);
5969 (void) sm_snprintf(buf, sizeof buf, "%d",
5970 (int) user.mbdb_gid);
5975 rwval = user.mbdb_fullname;
5979 rwval = user.mbdb_homedir;
5983 rwval = user.mbdb_shell;
5986 return map_rewrite(map, rwval, strlen(rwval), av);
5990 ** Program map type.
5992 ** This provides access to arbitrary programs. It should be used
5993 ** only very sparingly, since there is no way to bound the cost
5994 ** of invoking an arbitrary program.
5998 prog_map_lookup(map, name, av, statp)
6011 char *argv[MAXPV + 1];
6015 sm_dprintf("prog_map_lookup(%s, %s) %s\n",
6016 map->map_mname, name, map->map_file);
6019 argv[i++] = map->map_file;
6020 if (map->map_rebuild != NULL)
6022 (void) sm_strlcpy(buf, map->map_rebuild, sizeof buf);
6023 for (p = strtok(buf, " \t"); p != NULL; p = strtok(NULL, " \t"))
6034 sm_dprintf("prog_open:");
6035 for (i = 0; argv[i] != NULL; i++)
6036 sm_dprintf(" %s", argv[i]);
6039 (void) sm_blocksignal(SIGCHLD);
6040 pid = prog_open(argv, &fd, CurEnv);
6043 if (!bitset(MF_OPTIONAL, map->map_mflags))
6044 syserr("prog_map_lookup(%s) failed (%s) -- closing",
6045 map->map_mname, sm_errstring(errno));
6046 else if (tTd(38, 9))
6047 sm_dprintf("prog_map_lookup(%s) failed (%s) -- closing",
6048 map->map_mname, sm_errstring(errno));
6049 map->map_mflags &= ~(MF_VALID|MF_OPEN);
6053 i = read(fd, buf, sizeof buf - 1);
6056 syserr("prog_map_lookup(%s): read error %s",
6057 map->map_mname, sm_errstring(errno));
6063 sm_dprintf("prog_map_lookup(%s): empty answer\n",
6070 p = strchr(buf, '\n');
6074 /* collect the return value */
6075 if (bitset(MF_MATCHONLY, map->map_mflags))
6076 rval = map_rewrite(map, name, strlen(name), NULL);
6078 rval = map_rewrite(map, buf, strlen(buf), av);
6080 /* now flush any additional output */
6081 while ((i = read(fd, buf, sizeof buf)) > 0)
6085 /* wait for the process to terminate */
6087 status = waitfor(pid);
6089 (void) sm_releasesignal(SIGCHLD);
6094 syserr("prog_map_lookup(%s): wait error %s",
6095 map->map_mname, sm_errstring(errno));
6096 *statp = EX_SOFTWARE;
6099 else if (WIFEXITED(status))
6101 if ((*statp = WEXITSTATUS(status)) != EX_OK)
6106 syserr("prog_map_lookup(%s): child died on signal %d",
6107 map->map_mname, status);
6108 *statp = EX_UNAVAILABLE;
6114 ** Sequenced map type.
6116 ** Tries each map in order until something matches, much like
6117 ** implicit. Stores go to the first map in the list that can
6120 ** This is slightly unusual in that there are two interfaces.
6121 ** The "sequence" interface lets you stack maps arbitrarily.
6122 ** The "switch" interface builds a sequence map by looking
6123 ** at a system-dependent configuration file such as
6124 ** /etc/nsswitch.conf on Solaris or /etc/svc.conf on Ultrix.
6126 ** We don't need an explicit open, since all maps are
6127 ** opened on demand.
6131 ** SEQ_MAP_PARSE -- Sequenced map parsing
6135 seq_map_parse(map, ap)
6142 sm_dprintf("seq_map_parse(%s, %s)\n", map->map_mname, ap);
6149 /* find beginning of map name */
6150 while (isascii(*ap) && isspace(*ap))
6153 (isascii(*p) && isalnum(*p)) || *p == '_' || *p == '.';
6158 while (*p != '\0' && (!isascii(*p) || !isalnum(*p)))
6165 s = stab(ap, ST_MAP, ST_FIND);
6168 syserr("Sequence map %s: unknown member map %s",
6169 map->map_mname, ap);
6171 else if (maxmap >= MAXMAPSTACK)
6173 syserr("Sequence map %s: too many member maps (%d max)",
6174 map->map_mname, MAXMAPSTACK);
6177 else if (maxmap < MAXMAPSTACK)
6179 map->map_stack[maxmap++] = &s->s_map;
6187 ** SWITCH_MAP_OPEN -- open a switched map
6189 ** This looks at the system-dependent configuration and builds
6190 ** a sequence map that does the same thing.
6192 ** Every system must define a switch_map_find routine in conf.c
6193 ** that will return the list of service types associated with a
6194 ** given service class.
6198 switch_map_open(map, mode)
6204 char *maptype[MAXMAPSTACK];
6207 sm_dprintf("switch_map_open(%s, %s, %d)\n",
6208 map->map_mname, map->map_file, mode);
6211 nmaps = switch_map_find(map->map_file, maptype, map->map_return);
6214 sm_dprintf("\tswitch_map_find => %d\n", nmaps);
6215 for (mapno = 0; mapno < nmaps; mapno++)
6216 sm_dprintf("\t\t%s\n", maptype[mapno]);
6218 if (nmaps <= 0 || nmaps > MAXMAPSTACK)
6221 for (mapno = 0; mapno < nmaps; mapno++)
6224 char nbuf[MAXNAME + 1];
6226 if (maptype[mapno] == NULL)
6228 (void) sm_strlcpyn(nbuf, sizeof nbuf, 3,
6229 map->map_mname, ".", maptype[mapno]);
6230 s = stab(nbuf, ST_MAP, ST_FIND);
6233 syserr("Switch map %s: unknown member map %s",
6234 map->map_mname, nbuf);
6238 map->map_stack[mapno] = &s->s_map;
6240 sm_dprintf("\tmap_stack[%d] = %s:%s\n",
6242 s->s_map.map_class->map_cname,
6251 ** SEQ_MAP_CLOSE -- close all underlying maps
6261 sm_dprintf("seq_map_close(%s)\n", map->map_mname);
6263 for (mapno = 0; mapno < MAXMAPSTACK; mapno++)
6265 MAP *mm = map->map_stack[mapno];
6267 if (mm == NULL || !bitset(MF_OPEN, mm->map_mflags))
6269 mm->map_mflags |= MF_CLOSING;
6270 mm->map_class->map_close(mm);
6271 mm->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
6277 ** SEQ_MAP_LOOKUP -- sequenced map lookup
6281 seq_map_lookup(map, key, args, pstat)
6289 bool tempfail = false;
6292 sm_dprintf("seq_map_lookup(%s, %s)\n", map->map_mname, key);
6294 for (mapno = 0; mapno < MAXMAPSTACK; mapbit <<= 1, mapno++)
6296 MAP *mm = map->map_stack[mapno];
6301 if (!bitset(MF_OPEN, mm->map_mflags) &&
6304 if (bitset(mapbit, map->map_return[MA_UNAVAIL]))
6306 *pstat = EX_UNAVAILABLE;
6312 rv = mm->map_class->map_lookup(mm, key, args, pstat);
6315 if (*pstat == EX_TEMPFAIL)
6317 if (bitset(mapbit, map->map_return[MA_TRYAGAIN]))
6321 else if (bitset(mapbit, map->map_return[MA_NOTFOUND]))
6325 *pstat = EX_TEMPFAIL;
6326 else if (*pstat == EX_OK)
6327 *pstat = EX_NOTFOUND;
6332 ** SEQ_MAP_STORE -- sequenced map store
6336 seq_map_store(map, key, val)
6344 sm_dprintf("seq_map_store(%s, %s, %s)\n",
6345 map->map_mname, key, val);
6347 for (mapno = 0; mapno < MAXMAPSTACK; mapno++)
6349 MAP *mm = map->map_stack[mapno];
6351 if (mm == NULL || !bitset(MF_WRITABLE, mm->map_mflags))
6354 mm->map_class->map_store(mm, key, val);
6357 syserr("seq_map_store(%s, %s, %s): no writable map",
6358 map->map_mname, key, val);
6366 null_map_open(map, mode)
6382 null_map_lookup(map, key, args, pstat)
6388 *pstat = EX_NOTFOUND;
6394 null_map_store(map, key, val)
6407 bogus_map_lookup(map, key, args, pstat)
6413 *pstat = EX_TEMPFAIL;
6417 MAPCLASS BogusMapClass =
6419 "bogus-map", NULL, 0,
6420 NULL, bogus_map_lookup, null_map_store,
6421 null_map_open, null_map_close,
6428 macro_map_lookup(map, name, av, statp)
6437 sm_dprintf("macro_map_lookup(%s, %s)\n", map->map_mname,
6438 name == NULL ? "NULL" : name);
6442 (mid = macid(name)) == 0)
6449 macdefine(&CurEnv->e_macro, A_PERM, mid, NULL);
6451 macdefine(&CurEnv->e_macro, A_TEMP, mid, av[1]);
6464 # define DEFAULT_DELIM CONDELSE
6465 # define END_OF_FIELDS -1
6466 # define ERRBUF_SIZE 80
6467 # define MAX_MATCH 32
6469 # define xnalloc(s) memset(xalloc(s), '\0', s);
6473 regex_t *regex_pattern_buf; /* xalloc it */
6474 int *regex_subfields; /* move to type MAP */
6475 char *regex_delim; /* move to type MAP */
6478 static int parse_fields __P((char *, int *, int, int));
6479 static char *regex_map_rewrite __P((MAP *, const char*, size_t, char **));
6482 parse_fields(s, ibuf, blen, nr_substrings)
6484 int *ibuf; /* array */
6485 int blen; /* number of elements in ibuf */
6486 int nr_substrings; /* number of substrings in the pattern */
6490 bool lastone = false;
6492 blen--; /* for terminating END_OF_FIELDS */
6513 if (val < 0 || val >= nr_substrings)
6515 syserr("field (%d) out of range, only %d substrings in pattern",
6516 val, nr_substrings);
6523 syserr("too many fields, %d max", blen);
6528 ibuf[i] = END_OF_FIELDS;
6533 regex_map_init(map, ap)
6538 struct regex_map *map_p;
6540 char *sub_param = NULL;
6542 static char defdstr[] = { (char) DEFAULT_DELIM, '\0' };
6545 sm_dprintf("regex_map_init: mapname '%s', args '%s'\n",
6546 map->map_mname, ap);
6548 pflags = REG_ICASE | REG_EXTENDED | REG_NOSUB;
6550 map_p = (struct regex_map *) xnalloc(sizeof *map_p);
6551 map_p->regex_pattern_buf = (regex_t *)xnalloc(sizeof(regex_t));
6555 while (isascii(*p) && isspace(*p))
6562 map->map_mflags |= MF_REGEX_NOT;
6565 case 'f': /* case sensitive */
6566 map->map_mflags |= MF_NOFOLDCASE;
6567 pflags &= ~REG_ICASE;
6570 case 'b': /* basic regular expressions */
6571 pflags &= ~REG_EXTENDED;
6574 case 's': /* substring match () syntax */
6576 pflags &= ~REG_NOSUB;
6579 case 'd': /* delimiter */
6580 map_p->regex_delim = ++p;
6583 case 'a': /* map append */
6587 case 'm': /* matchonly */
6588 map->map_mflags |= MF_MATCHONLY;
6592 map->map_mflags |= MF_KEEPQUOTES;
6596 map->map_spacesub = *++p;
6600 map->map_mflags |= MF_DEFER;
6604 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
6610 sm_dprintf("regex_map_init: compile '%s' 0x%x\n", p, pflags);
6612 if ((regerr = regcomp(map_p->regex_pattern_buf, p, pflags)) != 0)
6615 char errbuf[ERRBUF_SIZE];
6617 (void) regerror(regerr, map_p->regex_pattern_buf,
6618 errbuf, sizeof errbuf);
6619 syserr("pattern-compile-error: %s", errbuf);
6620 sm_free(map_p->regex_pattern_buf); /* XXX */
6621 sm_free(map_p); /* XXX */
6625 if (map->map_app != NULL)
6626 map->map_app = newstr(map->map_app);
6627 if (map_p->regex_delim != NULL)
6628 map_p->regex_delim = newstr(map_p->regex_delim);
6630 map_p->regex_delim = defdstr;
6632 if (!bitset(REG_NOSUB, pflags))
6634 /* substring matching */
6636 int *fields = (int *) xalloc(sizeof(int) * (MAX_MATCH + 1));
6638 substrings = map_p->regex_pattern_buf->re_nsub + 1;
6641 sm_dprintf("regex_map_init: nr of substrings %d\n",
6644 if (substrings >= MAX_MATCH)
6646 syserr("too many substrings, %d max", MAX_MATCH);
6647 sm_free(map_p->regex_pattern_buf); /* XXX */
6648 sm_free(map_p); /* XXX */
6651 if (sub_param != NULL && sub_param[0] != '\0')
6653 /* optional parameter -sfields */
6654 if (parse_fields(sub_param, fields,
6655 MAX_MATCH + 1, substrings) == -1)
6662 /* set default fields */
6663 for (i = 0; i < substrings; i++)
6665 fields[i] = END_OF_FIELDS;
6667 map_p->regex_subfields = fields;
6672 sm_dprintf("regex_map_init: subfields");
6673 for (ip = fields; *ip != END_OF_FIELDS; ip++)
6674 sm_dprintf(" %d", *ip);
6678 map->map_db1 = (ARBPTR_T) map_p; /* dirty hack */
6683 regex_map_rewrite(map, s, slen, av)
6689 if (bitset(MF_MATCHONLY, map->map_mflags))
6690 return map_rewrite(map, av[0], strlen(av[0]), NULL);
6692 return map_rewrite(map, s, slen, av);
6696 regex_map_lookup(map, name, av, statp)
6703 struct regex_map *map_p;
6704 regmatch_t pmatch[MAX_MATCH];
6710 sm_dprintf("regex_map_lookup: key '%s'\n", name);
6711 for (cpp = av; cpp != NULL && *cpp != NULL; cpp++)
6712 sm_dprintf("regex_map_lookup: arg '%s'\n", *cpp);
6715 map_p = (struct regex_map *)(map->map_db1);
6716 reg_res = regexec(map_p->regex_pattern_buf,
6717 name, MAX_MATCH, pmatch, 0);
6719 if (bitset(MF_REGEX_NOT, map->map_mflags))
6722 if (reg_res == REG_NOMATCH)
6723 return regex_map_rewrite(map, "", (size_t) 0, av);
6727 if (reg_res == REG_NOMATCH)
6730 if (map_p->regex_subfields != NULL)
6733 static char retbuf[MAXNAME];
6734 int fields[MAX_MATCH + 1];
6736 int anglecnt = 0, cmntcnt = 0, spacecnt = 0;
6737 bool quotemode = false, bslashmode = false;
6738 register char *dp, *sp;
6743 ldp = retbuf + sizeof(retbuf) - 1;
6747 if (parse_fields(av[1], fields, MAX_MATCH + 1,
6748 (int) map_p->regex_pattern_buf->re_nsub + 1) == -1)
6756 ip = map_p->regex_subfields;
6758 for ( ; *ip != END_OF_FIELDS; ip++)
6762 for (sp = map_p->regex_delim; *sp; sp++)
6771 if (*ip >= MAX_MATCH ||
6772 pmatch[*ip].rm_so < 0 || pmatch[*ip].rm_eo < 0)
6775 sp = name + pmatch[*ip].rm_so;
6776 endp = name + pmatch[*ip].rm_eo;
6777 for (; endp > sp; sp++)
6786 else if (quotemode && *sp != '"' &&
6791 else switch (*dp++ = *sp)
6818 quotemode = !quotemode;
6824 if (anglecnt != 0 || cmntcnt != 0 || quotemode ||
6825 bslashmode || spacecnt != 0)
6827 sm_syslog(LOG_WARNING, NOQID,
6828 "Warning: regex may cause prescan() failure map=%s lookup=%s",
6829 map->map_mname, name);
6835 return regex_map_rewrite(map, retbuf, strlen(retbuf), av);
6837 return regex_map_rewrite(map, "", (size_t)0, av);
6839 #endif /* MAP_REGEX */
6846 # define _DATUM_DEFINED
6847 # include <ns_api.h>
6849 typedef struct ns_map_list
6851 ns_map_t *map; /* XXX ns_ ? */
6853 struct ns_map_list *next;
6857 ns_map_t_find(mapname)
6860 static ns_map_list_t *ns_maps = NULL;
6861 ns_map_list_t *ns_map;
6863 /* walk the list of maps looking for the correctly named map */
6864 for (ns_map = ns_maps; ns_map != NULL; ns_map = ns_map->next)
6866 if (strcmp(ns_map->mapname, mapname) == 0)
6870 /* if we are looking at a NULL ns_map_list_t, then create a new one */
6873 ns_map = (ns_map_list_t *) xalloc(sizeof *ns_map);
6874 ns_map->mapname = newstr(mapname);
6875 ns_map->map = (ns_map_t *) xalloc(sizeof *ns_map->map);
6876 memset(ns_map->map, '\0', sizeof *ns_map->map);
6877 ns_map->next = ns_maps;
6884 nsd_map_lookup(map, name, av, statp)
6893 char keybuf[MAXNAME + 1];
6897 sm_dprintf("nsd_map_lookup(%s, %s)\n", map->map_mname, name);
6899 buflen = strlen(name);
6900 if (buflen > sizeof keybuf - 1)
6901 buflen = sizeof keybuf - 1; /* XXX simply cut off? */
6902 memmove(keybuf, name, buflen);
6903 keybuf[buflen] = '\0';
6904 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
6907 ns_map = ns_map_t_find(map->map_file);
6911 sm_dprintf("nsd_map_t_find failed\n");
6912 *statp = EX_UNAVAILABLE;
6915 r = ns_lookup(ns_map, NULL, map->map_file, keybuf, NULL,
6917 if (r == NS_UNAVAIL || r == NS_TRYAGAIN)
6919 *statp = EX_TEMPFAIL;
6925 # endif /* NS_NOPERM */
6931 if (r != NS_SUCCESS)
6933 *statp = EX_NOTFOUND;
6939 /* Null out trailing \n */
6940 if ((p = strchr(buf, '\n')) != NULL)
6943 return map_rewrite(map, buf, strlen(buf), av);
6945 #endif /* MAP_NSD */
6948 arith_map_lookup(map, name, av, statp)
6958 static char result[16];
6963 sm_dprintf("arith_map_lookup: key '%s'\n", name);
6964 for (cpp = av; cpp != NULL && *cpp != NULL; cpp++)
6965 sm_dprintf("arith_map_lookup: arg '%s'\n", *cpp);
6973 ** read arguments for arith map
6974 ** - no check is made whether they are really numbers
6975 ** - just ignores args after the second
6978 for (++cpp; cpp != NULL && *cpp != NULL && r < 2; cpp++)
6979 v[r++] = strtol(*cpp, NULL, 0);
6981 /* operator and (at least) two operands given? */
6982 if (name != NULL && r == 2)
7031 sm_syslog(LOG_WARNING, NOQID,
7032 "arith_map: unknown operator %c",
7033 isprint(*name) ? *name : '?');
7037 (void) sm_snprintf(result, sizeof result,
7038 res ? "TRUE" : "FALSE");
7040 (void) sm_snprintf(result, sizeof result, "%ld", r);
7049 # if NETINET || NETINET6
7050 # include <arpa/inet.h>
7051 # endif /* NETINET || NETINET6 */
7053 # define socket_map_next map_stack[0]
7056 ** SOCKET_MAP_OPEN -- open socket table
7060 socket_map_open(map, mode)
7066 SOCKADDR_LEN_T addrlen = 0;
7072 struct hostent *hp = NULL;
7076 sm_dprintf("socket_map_open(%s, %s, %d)\n",
7077 map->map_mname, map->map_file, mode);
7081 /* sendmail doesn't have the ability to write to SOCKET (yet) */
7082 if (mode != O_RDONLY)
7084 /* issue a pseudo-error message */
7085 errno = SM_EMAPCANTWRITE;
7089 if (*map->map_file == '\0')
7091 syserr("socket map \"%s\": empty or missing socket information",
7096 s = socket_map_findconn(map->map_file);
7097 if (s->s_socketmap != NULL)
7099 /* Copy open connection */
7100 map->map_db1 = s->s_socketmap->map_db1;
7102 /* Add this map as head of linked list */
7103 map->socket_map_next = s->s_socketmap;
7104 s->s_socketmap = map;
7107 sm_dprintf("using cached connection\n");
7112 sm_dprintf("opening new connection\n");
7114 /* following code is ripped from milter.c */
7115 /* XXX It should be put in a library... */
7117 /* protocol:filename or protocol:port@host */
7118 memset(&addr, '\0', sizeof addr);
7120 colon = strchr(p, ':');
7128 /* default to AF_UNIX */
7129 addr.sa.sa_family = AF_UNIX;
7130 # else /* NETUNIX */
7132 /* default to AF_INET */
7133 addr.sa.sa_family = AF_INET;
7134 # else /* NETINET */
7136 /* default to AF_INET6 */
7137 addr.sa.sa_family = AF_INET6;
7138 # else /* NETINET6 */
7139 /* no protocols available */
7140 syserr("socket map \"%s\": no valid socket protocols available",
7143 # endif /* NETINET6 */
7144 # endif /* NETINET */
7145 # endif /* NETUNIX */
7148 else if (sm_strcasecmp(p, "unix") == 0 ||
7149 sm_strcasecmp(p, "local") == 0)
7150 addr.sa.sa_family = AF_UNIX;
7151 # endif /* NETUNIX */
7153 else if (sm_strcasecmp(p, "inet") == 0)
7154 addr.sa.sa_family = AF_INET;
7155 # endif /* NETINET */
7157 else if (sm_strcasecmp(p, "inet6") == 0)
7158 addr.sa.sa_family = AF_INET6;
7159 # endif /* NETINET6 */
7162 # ifdef EPROTONOSUPPORT
7163 errno = EPROTONOSUPPORT;
7164 # else /* EPROTONOSUPPORT */
7166 # endif /* EPROTONOSUPPORT */
7167 syserr("socket map \"%s\": unknown socket type %s",
7177 /* default to AF_UNIX */
7178 addr.sa.sa_family = AF_UNIX;
7181 /* default to AF_INET */
7182 addr.sa.sa_family = AF_INET;
7183 # else /* NETINET */
7185 /* default to AF_INET6 */
7186 addr.sa.sa_family = AF_INET6;
7187 # else /* NETINET6 */
7188 syserr("socket map \"%s\": unknown socket type %s",
7191 # endif /* NETINET6 */
7192 # endif /* NETINET */
7193 #endif /* NETUNIX */
7197 if (addr.sa.sa_family == AF_UNIX)
7199 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_EXECOK;
7202 if (strlen(colon) >= sizeof addr.sunix.sun_path)
7204 syserr("socket map \"%s\": local socket name %s too long",
7205 map->map_mname, colon);
7208 errno = safefile(colon, RunAsUid, RunAsGid, RunAsUserName, sff,
7209 S_IRUSR|S_IWUSR, NULL);
7213 /* if not safe, don't create */
7214 syserr("socket map \"%s\": local socket name %s unsafe",
7215 map->map_mname, colon);
7219 (void) sm_strlcpy(addr.sunix.sun_path, colon,
7220 sizeof addr.sunix.sun_path);
7221 addrlen = sizeof (struct sockaddr_un);
7224 # endif /* NETUNIX */
7225 # if NETINET || NETINET6
7228 || addr.sa.sa_family == AF_INET
7229 # endif /* NETINET */
7231 || addr.sa.sa_family == AF_INET6
7232 # endif /* NETINET6 */
7235 unsigned short port;
7237 /* Parse port@host */
7238 at = strchr(colon, '@');
7241 syserr("socket map \"%s\": bad address %s (expected port@host)",
7242 map->map_mname, colon);
7246 if (isascii(*colon) && isdigit(*colon))
7247 port = htons((unsigned short) atoi(colon));
7250 # ifdef NO_GETSERVBYNAME
7251 syserr("socket map \"%s\": invalid port number %s",
7252 map->map_mname, colon);
7254 # else /* NO_GETSERVBYNAME */
7255 register struct servent *sp;
7257 sp = getservbyname(colon, "tcp");
7260 syserr("socket map \"%s\": unknown port name %s",
7261 map->map_mname, colon);
7265 # endif /* NO_GETSERVBYNAME */
7272 end = strchr(at, ']');
7277 unsigned long hid = INADDR_NONE;
7278 # endif /* NETINET */
7280 struct sockaddr_in6 hid6;
7281 # endif /* NETINET6 */
7285 if (addr.sa.sa_family == AF_INET &&
7286 (hid = inet_addr(&at[1])) != INADDR_NONE)
7288 addr.sin.sin_addr.s_addr = hid;
7289 addr.sin.sin_port = port;
7292 # endif /* NETINET */
7294 (void) memset(&hid6, '\0', sizeof hid6);
7295 if (addr.sa.sa_family == AF_INET6 &&
7296 anynet_pton(AF_INET6, &at[1],
7297 &hid6.sin6_addr) == 1)
7299 addr.sin6.sin6_addr = hid6.sin6_addr;
7300 addr.sin6.sin6_port = port;
7303 # endif /* NETINET6 */
7307 syserr("socket map \"%s\": Invalid numeric domain spec \"%s\"",
7308 map->map_mname, at);
7314 syserr("socket map \"%s\": Invalid numeric domain spec \"%s\"",
7315 map->map_mname, at);
7321 hp = sm_gethostbyname(at, addr.sa.sa_family);
7324 syserr("socket map \"%s\": Unknown host name %s",
7325 map->map_mname, at);
7328 addr.sa.sa_family = hp->h_addrtype;
7329 switch (hp->h_addrtype)
7333 memmove(&addr.sin.sin_addr,
7334 hp->h_addr, INADDRSZ);
7335 addr.sin.sin_port = port;
7336 addrlen = sizeof (struct sockaddr_in);
7339 # endif /* NETINET */
7343 memmove(&addr.sin6.sin6_addr,
7344 hp->h_addr, IN6ADDRSZ);
7345 addr.sin6.sin6_port = port;
7346 addrlen = sizeof (struct sockaddr_in6);
7349 # endif /* NETINET6 */
7352 syserr("socket map \"%s\": Unknown protocol for %s (%d)",
7353 map->map_mname, at, hp->h_addrtype);
7356 # endif /* NETINET6 */
7362 # endif /* NETINET || NETINET6 */
7364 syserr("socket map \"%s\": unknown socket protocol",
7369 /* nope, actually connecting */
7372 sock = socket(addr.sa.sa_family, SOCK_STREAM, 0);
7377 sm_dprintf("socket map \"%s\": error creating socket: %s\n",
7379 sm_errstring(save_errno));
7383 # endif /* NETINET6 */
7387 if (connect(sock, (struct sockaddr *) &addr, addrlen) >= 0)
7390 /* couldn't connect.... try next address */
7395 sm_dprintf("socket_open (%s): open %s failed: %s\n",
7396 map->map_mname, at, sm_errstring(save_errno));
7400 /* try next address */
7401 if (hp != NULL && hp->h_addr_list[addrno] != NULL)
7403 switch (addr.sa.sa_family)
7407 memmove(&addr.sin.sin_addr,
7408 hp->h_addr_list[addrno++],
7411 # endif /* NETINET */
7415 memmove(&addr.sin6.sin6_addr,
7416 hp->h_addr_list[addrno++],
7419 # endif /* NETINET6 */
7423 sm_dprintf("socket map \"%s\": Unknown protocol for %s (%d)\n",
7428 # endif /* NETINET6 */
7436 sm_dprintf("socket map \"%s\": error connecting to socket map: %s\n",
7437 map->map_mname, sm_errstring(save_errno));
7442 # endif /* NETINET6 */
7451 # endif /* NETINET6 */
7452 if ((map->map_db1 = (ARBPTR_T) sm_io_open(SmFtStdiofd,
7460 sm_dprintf("socket_open (%s): failed to create stream: %s\n",
7461 map->map_mname, sm_errstring(errno));
7465 /* Save connection for reuse */
7466 s->s_socketmap = map;
7471 ** SOCKET_MAP_FINDCONN -- find a SOCKET connection to the server
7473 ** Cache SOCKET connections based on the connection specifier
7474 ** and PID so we don't have multiple connections open to
7475 ** the same server for different maps. Need a separate connection
7476 ** per PID since a parent process may close the map before the
7477 ** child is done with it.
7480 ** conn -- SOCKET map connection specifier
7483 ** Symbol table entry for the SOCKET connection.
7487 socket_map_findconn(conn)
7491 STAB *SM_NONVOLATILE s = NULL;
7493 nbuf = sm_stringf_x("%s%c%d", conn, CONDELSE, (int) CurrentPid);
7495 s = stab(nbuf, ST_SOCKETMAP, ST_ENTER);
7503 ** SOCKET_MAP_CLOSE -- close the socket
7507 socket_map_close(map)
7514 sm_dprintf("socket_map_close(%s), pid=%ld\n", map->map_file,
7517 /* Check if already closed */
7518 if (map->map_db1 == NULL)
7521 sm_dprintf("socket_map_close(%s) already closed\n",
7525 sm_io_close((SM_FILE_T *)map->map_db1, SM_TIME_DEFAULT);
7527 /* Mark all the maps that share the connection as closed */
7528 s = socket_map_findconn(map->map_file);
7529 smap = s->s_socketmap;
7530 while (smap != NULL)
7534 if (tTd(38, 2) && smap != map)
7535 sm_dprintf("socket_map_close(%s): closed %s (shared SOCKET connection)\n",
7536 map->map_mname, smap->map_mname);
7538 smap->map_mflags &= ~(MF_OPEN|MF_WRITABLE);
7539 smap->map_db1 = NULL;
7540 next = smap->socket_map_next;
7541 smap->socket_map_next = NULL;
7544 s->s_socketmap = NULL;
7548 ** SOCKET_MAP_LOOKUP -- look up a datum in a SOCKET table
7552 socket_map_lookup(map, name, av, statp)
7558 unsigned int nettolen, replylen, recvlen;
7559 char *replybuf, *rval, *value, *status, *key;
7561 char keybuf[MAXNAME + 1];
7565 f = (SM_FILE_T *)map->map_db1;
7567 sm_dprintf("socket_map_lookup(%s, %s) %s\n",
7568 map->map_mname, name, map->map_file);
7570 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
7572 nettolen = strlen(name);
7573 if (nettolen > sizeof keybuf - 1)
7574 nettolen = sizeof keybuf - 1;
7575 memmove(keybuf, name, nettolen);
7576 keybuf[nettolen] = '\0';
7583 nettolen = strlen(map->map_mname) + 1 + strlen(key);
7584 SM_ASSERT(nettolen > strlen(map->map_mname));
7585 SM_ASSERT(nettolen > strlen(key));
7586 if ((sm_io_fprintf(f, SM_TIME_DEFAULT, "%u:%s %s,",
7587 nettolen, map->map_mname, key) == SM_IO_EOF) ||
7588 (sm_io_flush(f, SM_TIME_DEFAULT) != 0) ||
7591 syserr("451 4.3.0 socket_map_lookup(%s): failed to send lookup request",
7593 *statp = EX_TEMPFAIL;
7597 if (sm_io_fscanf(f, SM_TIME_DEFAULT, "%9u", &replylen) != 1)
7599 syserr("451 4.3.0 socket_map_lookup(%s): failed to read length parameter of reply",
7601 *statp = EX_TEMPFAIL;
7604 if (replylen > SOCKETMAP_MAXL)
7606 syserr("451 4.3.0 socket_map_lookup(%s): reply too long: %u",
7607 map->map_mname, replylen);
7608 *statp = EX_TEMPFAIL;
7611 if (sm_io_getc(f, SM_TIME_DEFAULT) != ':')
7613 syserr("451 4.3.0 socket_map_lookup(%s): missing ':' in reply",
7615 *statp = EX_TEMPFAIL;
7619 replybuf = (char *) sm_malloc(replylen + 1);
7620 if (replybuf == NULL)
7622 syserr("451 4.3.0 socket_map_lookup(%s): can't allocate %u bytes",
7623 map->map_mname, replylen + 1);
7628 recvlen = sm_io_read(f, SM_TIME_DEFAULT, replybuf, replylen);
7629 if (recvlen < replylen)
7631 syserr("451 4.3.0 socket_map_lookup(%s): received only %u of %u reply characters",
7632 map->map_mname, recvlen, replylen);
7633 *statp = EX_TEMPFAIL;
7636 if (sm_io_getc(f, SM_TIME_DEFAULT) != ',')
7638 syserr("451 4.3.0 socket_map_lookup(%s): missing ',' in reply",
7640 *statp = EX_TEMPFAIL;
7644 replybuf[recvlen] = '\0';
7645 value = strchr(replybuf, ' ');
7651 if (strcmp(status, "OK") == 0)
7655 /* collect the return value */
7656 if (bitset(MF_MATCHONLY, map->map_mflags))
7657 rval = map_rewrite(map, key, strlen(key), NULL);
7659 rval = map_rewrite(map, value, strlen(value), av);
7661 else if (strcmp(status, "NOTFOUND") == 0)
7663 *statp = EX_NOTFOUND;
7665 sm_dprintf("socket_map_lookup(%s): %s not found\n",
7666 map->map_mname, key);
7671 sm_dprintf("socket_map_lookup(%s, %s): server returned error: type=%s, reason=%s\n",
7672 map->map_mname, key, status,
7673 value ? value : "");
7674 if ((strcmp(status, "TEMP") == 0) ||
7675 (strcmp(status, "TIMEOUT") == 0))
7676 *statp = EX_TEMPFAIL;
7677 else if(strcmp(status, "PERM") == 0)
7678 *statp = EX_UNAVAILABLE;
7680 *statp = EX_PROTOCOL;
7683 if (replybuf != NULL)
7688 socket_map_close(map);
7690 if (replybuf != NULL)
7694 #endif /* SOCKETMAP */