2 * Copyright (c) 1998-2008 Proofpoint, 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.713 2013-11-22 20:51:55 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 */
48 # if DB_VERSION_MAJOR < 2
49 static bool db_map_open __P((MAP *, int, char *, DBTYPE, const void *));
51 # if DB_VERSION_MAJOR == 2
52 static bool db_map_open __P((MAP *, int, char *, DBTYPE, DB_INFO *));
54 # if DB_VERSION_MAJOR > 2
55 static bool db_map_open __P((MAP *, int, char *, DBTYPE, void **));
58 static bool extract_canonname __P((char *, char *, char *, char[], int));
59 static void map_close __P((STAB *, int));
60 static void map_init __P((STAB *, int));
62 static STAB * ldapmap_findconn __P((SM_LDAP_STRUCT *));
65 static bool nisplus_getcanonname __P((char *, int, int *));
68 static bool nis_getcanonname __P((char *, int, int *));
71 static bool ni_getcanonname __P((char *, int, int *));
73 static bool text_getcanonname __P((char *, int, int *));
75 static STAB *socket_map_findconn __P((const char*));
77 /* XXX arbitrary limit for sanity */
78 # define SOCKETMAP_MAXL 1000000
79 #endif /* SOCKETMAP */
81 /* default error message for trying to open a map in write mode */
83 # define SM_EMAPCANTWRITE ENOSYS
86 # define SM_EMAPCANTWRITE EFTYPE
88 # define SM_EMAPCANTWRITE ENXIO
93 ** MAP.C -- implementations for various map classes.
95 ** Each map class implements a series of functions:
97 ** bool map_parse(MAP *map, char *args)
98 ** Parse the arguments from the config file. Return true
99 ** if they were ok, false otherwise. Fill in map with the
102 ** char *map_lookup(MAP *map, char *key, char **args, int *pstat)
103 ** Look up the key in the given map. If found, do any
104 ** rewriting the map wants (including "args" if desired)
105 ** and return the value. Set *pstat to the appropriate status
106 ** on error and return NULL. Args will be NULL if called
107 ** from the alias routines, although this should probably
108 ** not be relied upon. It is suggested you call map_rewrite
109 ** to return the results -- it takes care of null termination
110 ** and uses a dynamically expanded buffer as needed.
112 ** void map_store(MAP *map, char *key, char *value)
113 ** Store the key:value pair in the map.
115 ** bool map_open(MAP *map, int mode)
116 ** Open the map for the indicated mode. Mode should
117 ** be either O_RDONLY or O_RDWR. Return true if it
118 ** was opened successfully, false otherwise. If the open
119 ** failed and the MF_OPTIONAL flag is not set, it should
120 ** also print an error. If the MF_ALIAS bit is set
121 ** and this map class understands the @:@ convention, it
122 ** should call aliaswait() before returning.
124 ** void map_close(MAP *map)
127 ** This file also includes the implementation for getcanonname.
128 ** It is currently implemented in a pretty ad-hoc manner; it ought
129 ** to be more properly integrated into the map structure.
132 #if O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL
133 # define LOCK_ON_OPEN 1 /* we can open/create a locked file */
135 # define LOCK_ON_OPEN 0 /* no such luck -- bend over backwards */
139 ** MAP_PARSEARGS -- parse config line arguments for database lookup
141 ** This is a generic version of the map_parse method.
144 ** map -- the map being initialized.
145 ** ap -- a pointer to the args on the config line.
148 ** true -- if everything parsed OK.
149 ** false -- otherwise.
152 ** null terminates the filename; stores it in map
156 map_parseargs(map, ap)
160 register char *p = ap;
163 ** There is no check whether there is really an argument,
164 ** but that's not important enough to warrant extra code.
167 map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL;
168 map->map_spacesub = SpaceSub; /* default value */
171 while (SM_ISSPACE(*p))
178 map->map_mflags |= MF_APPEND;
186 map->map_mflags |= MF_DEFER;
197 map->map_timeout = convtime(p, 's');
204 map->map_mflags |= MF_NOFOLDCASE;
208 while (isascii(*++p) && isspace(*p))
210 map->map_keycolnm = p;
214 map->map_mflags |= MF_MATCHONLY;
218 map->map_mflags |= MF_INCLNULL;
219 map->map_mflags &= ~MF_TRY0NULL;
223 map->map_mflags &= ~MF_TRY1NULL;
227 map->map_mflags |= MF_OPTIONAL;
231 map->map_mflags |= MF_KEEPQUOTES;
235 map->map_spacesub = *++p;
243 map->map_mflags |= MF_NODEFER;
247 while (isascii(*++p) && isspace(*p))
249 map->map_valcolnm = p;
254 map->map_coldelim = *p;
260 map->map_coldelim = '\n';
264 map->map_coldelim = '\t';
268 map->map_coldelim = '\\';
274 syserr("Illegal option %c map %s", *p, map->map_mname);
277 while (*p != '\0' && !(SM_ISSPACE(*p)))
282 if (map->map_app != NULL)
283 map->map_app = newstr(map->map_app);
284 if (map->map_tapp != NULL)
285 map->map_tapp = newstr(map->map_tapp);
286 if (map->map_keycolnm != NULL)
287 map->map_keycolnm = newstr(map->map_keycolnm);
288 if (map->map_valcolnm != NULL)
289 map->map_valcolnm = newstr(map->map_valcolnm);
294 while (*p != '\0' && !(SM_ISSPACE(*p)))
298 map->map_file = newstr(map->map_file);
301 while (*p != '\0' && SM_ISSPACE(*p))
304 map->map_rebuild = newstr(p);
306 if (map->map_file == NULL &&
307 !bitset(MCF_OPTFILE, map->map_class->map_cflags))
309 syserr("No file name for %s map %s",
310 map->map_class->map_cname, map->map_mname);
316 ** MAP_REWRITE -- rewrite a database key, interpolating %n indications.
318 ** It also adds the map_app string. It can be used as a utility
319 ** in the map_lookup method.
322 ** map -- the map that causes this.
323 ** s -- the string to rewrite, NOT necessarily null terminated.
324 ** slen -- the length of s.
325 ** av -- arguments to interpolate into buf.
328 ** Pointer to rewritten result. This is static data that
329 ** should be copied if it is to be saved!
333 map_rewrite(map, s, slen, av)
335 register const char *s;
345 static size_t buflen = 0;
346 static char *buf = NULL;
350 sm_dprintf("map_rewrite(%.*s), av =", (int) slen, s);
352 sm_dprintf(" (nullv)");
355 for (avp = av; *avp != NULL; avp++)
356 sm_dprintf("\n\t%s", *avp);
361 /* count expected size of output (can safely overestimate) */
367 while (l-- > 0 && (c = *sp++) != '\0')
374 if (!(isascii(c) && isdigit(c)))
376 for (avp = av; --c >= '0' && *avp != NULL; avp++)
383 if (map->map_app != NULL)
384 len += strlen(map->map_app);
387 /* need to malloc additional space */
391 buf = sm_pmalloc_x(buflen);
397 memmove(bp, s, slen);
400 /* assert(len > slen); */
405 while (slen-- > 0 && (c = *s++) != '\0')
415 if (slen-- <= 0 || (c = *s++) == '\0')
419 if (!(isascii(c) && isdigit(c)))
426 for (avp = av; --c >= '0' && *avp != NULL; avp++)
431 /* transliterate argument into output string */
432 for (ap = *avp; (c = *ap++) != '\0' && len > 0; --len)
436 if (map->map_app != NULL && len > 0)
437 (void) sm_strlcpy(bp, map->map_app, len);
441 sm_dprintf("map_rewrite => %s\n", buf);
445 ** INITMAPS -- rebuild alias maps
458 checkfd012("entering initmaps");
460 stabapply(map_init, 0);
462 checkfd012("exiting initmaps");
466 ** MAP_INIT -- rebuild a map
469 ** s -- STAB entry: if map: try to rebuild
470 ** unused -- unused variable
476 ** will close already open rebuildable map.
487 /* has to be a map */
488 if (s->s_symtype != ST_MAP)
492 if (!bitset(MF_VALID, map->map_mflags))
496 sm_dprintf("map_init(%s:%s, %s)\n",
497 map->map_class->map_cname == NULL ? "NULL" :
498 map->map_class->map_cname,
499 map->map_mname == NULL ? "NULL" : map->map_mname,
500 map->map_file == NULL ? "NULL" : map->map_file);
502 if (!bitset(MF_ALIAS, map->map_mflags) ||
503 !bitset(MCF_REBUILDABLE, map->map_class->map_cflags))
506 sm_dprintf("\tnot rebuildable\n");
510 /* if already open, close it (for nested open) */
511 if (bitset(MF_OPEN, map->map_mflags))
513 map->map_mflags |= MF_CLOSING;
514 map->map_class->map_close(map);
515 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
518 (void) rebuildaliases(map, false);
522 ** OPENMAP -- open a map
525 ** map -- map to open (it must not be open).
528 ** whether open succeeded.
535 bool restore = false;
536 bool savehold = HoldErrs;
537 bool savequick = QuickAbort;
538 int saveerrors = Errors;
540 if (!bitset(MF_VALID, map->map_mflags))
543 /* better safe than sorry... */
544 if (bitset(MF_OPEN, map->map_mflags))
547 /* Don't send a map open error out via SMTP */
548 if ((OnlyOneError || QuickAbort) &&
549 (OpMode == MD_SMTP || OpMode == MD_DAEMON))
557 if (map->map_class->map_open(map, O_RDONLY))
560 sm_dprintf("openmap()\t%s:%s %s: valid\n",
561 map->map_class->map_cname == NULL ? "NULL" :
562 map->map_class->map_cname,
563 map->map_mname == NULL ? "NULL" :
565 map->map_file == NULL ? "NULL" :
567 map->map_mflags |= MF_OPEN;
568 map->map_pid = CurrentPid;
573 sm_dprintf("openmap()\t%s:%s %s: invalid%s%s\n",
574 map->map_class->map_cname == NULL ? "NULL" :
575 map->map_class->map_cname,
576 map->map_mname == NULL ? "NULL" :
578 map->map_file == NULL ? "NULL" :
580 errno == 0 ? "" : ": ",
581 errno == 0 ? "" : sm_errstring(errno));
582 if (!bitset(MF_OPTIONAL, map->map_mflags))
584 extern MAPCLASS BogusMapClass;
586 map->map_orgclass = map->map_class;
587 map->map_class = &BogusMapClass;
588 map->map_mflags |= MF_OPEN|MF_OPENBOGUS;
589 map->map_pid = CurrentPid;
593 /* don't try again */
594 map->map_mflags &= ~MF_VALID;
602 QuickAbort = savequick;
605 return bitset(MF_OPEN, map->map_mflags);
608 ** CLOSEMAPS -- close all open maps opened by the current pid.
611 ** bogus -- only close bogus maps.
621 stabapply(map_close, bogus);
624 ** MAP_CLOSE -- close a map opened by the current pid.
627 ** s -- STAB entry: if map: try to close
628 ** bogus -- only close bogus maps or MCF_NOTPERSIST maps.
637 int bogus; /* int because of stabapply(), used as bool */
640 extern MAPCLASS BogusMapClass;
642 if (s->s_symtype != ST_MAP)
648 ** close the map iff:
649 ** it is valid and open and opened by this process
650 ** and (!bogus or it's a bogus map or it is not persistent)
651 ** negate this: return iff
652 ** it is not valid or it is not open or not opened by this process
653 ** or (bogus and it's not a bogus map and it's not not-persistent)
656 if (!bitset(MF_VALID, map->map_mflags) ||
657 !bitset(MF_OPEN, map->map_mflags) ||
658 bitset(MF_CLOSING, map->map_mflags) ||
659 map->map_pid != CurrentPid ||
660 (bogus && map->map_class != &BogusMapClass &&
661 !bitset(MCF_NOTPERSIST, map->map_class->map_cflags)))
664 if (map->map_class == &BogusMapClass && map->map_orgclass != NULL &&
665 map->map_orgclass != &BogusMapClass)
666 map->map_class = map->map_orgclass;
668 sm_dprintf("closemaps: closing %s (%s)\n",
669 map->map_mname == NULL ? "NULL" : map->map_mname,
670 map->map_file == NULL ? "NULL" : map->map_file);
672 if (!bitset(MF_OPENBOGUS, map->map_mflags))
674 map->map_mflags |= MF_CLOSING;
675 map->map_class->map_close(map);
677 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_OPENBOGUS|MF_CLOSING);
680 #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
681 extern int getdomainname();
683 /* this is mainly for backward compatibility in Sun environment */
688 ** Get the domain name from the kernel.
689 ** If it does not start with a leading dot, then remove
690 ** the first component. Since leading dots are funny Unix
691 ** files, we treat a leading "+" the same as a leading dot.
692 ** Finally, force there to be at least one dot in the domain name
693 ** (i.e. top-level domains are not allowed, like "com", must be
694 ** something like "sun.com").
698 char *period, *autodomain;
700 if (getdomainname(buf, sizeof buf) < 0)
707 printf("domainname = %s\n", buf);
711 period = strchr(buf, '.');
715 autodomain = period + 1;
716 if (strchr(autodomain, '.') == NULL)
719 return newstr(autodomain);
721 #endif /* SUN_EXTENSIONS && SUN_INIT_DOMAIN */
724 ** GETCANONNAME -- look up name using service switch
727 ** host -- the host name to look up.
728 ** hbsize -- the size of the host buffer.
729 ** trymx -- if set, try MX records.
730 ** pttl -- pointer to return TTL (can be NULL).
733 ** >0 -- if the host was found.
738 getcanonname(host, hbsize, trymx, pttl)
747 bool got_tempfail = false;
748 auto int status = EX_UNAVAILABLE;
749 char *maptype[MAXMAPSTACK];
750 short mapreturn[MAXMAPACTIONS];
751 #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
752 bool should_try_nis_domain = false;
753 static char *nis_domain = NULL;
755 bool secure = true; /* consider all maps secure by default */
757 nmaps = switch_map_find("hosts", maptype, mapreturn);
759 *pttl = SM_DEFAULT_TTL;
760 for (mapno = 0; mapno < nmaps; mapno++)
765 sm_dprintf("getcanonname(%s), trying %s\n",
766 host, maptype[mapno]);
767 if (strcmp("files", maptype[mapno]) == 0)
769 found = text_getcanonname(host, hbsize, &status);
772 else if (strcmp("nis", maptype[mapno]) == 0)
774 found = nis_getcanonname(host, hbsize, &status);
775 # if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
776 if (nis_domain == NULL)
777 nis_domain = sun_init_domain();
782 else if (strcmp("nisplus", maptype[mapno]) == 0)
784 found = nisplus_getcanonname(host, hbsize, &status);
785 # if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
786 if (nis_domain == NULL)
787 nis_domain = sun_init_domain();
792 else if (strcmp("dns", maptype[mapno]) == 0)
796 r = dns_getcanonname(host, hbsize, trymx, &status,
798 secure = HOST_SECURE == r;
801 #endif /* NAMED_BIND */
803 else if (strcmp("netinfo", maptype[mapno]) == 0)
805 found = ni_getcanonname(host, hbsize, &status);
811 status = EX_UNAVAILABLE;
815 ** Heuristic: if $m is not set, we are running during system
816 ** startup. In this case, when a name is apparently found
817 ** but has no dot, treat is as not found. This avoids
818 ** problems if /etc/hosts has no FQDN but is listed first
819 ** in the service switch.
823 (macvalue('m', CurEnv) != NULL || strchr(host, '.') != NULL))
826 #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
828 should_try_nis_domain = true;
829 /* but don't break, as we need to try all methods first */
830 #endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */
832 /* see if we should continue */
833 if (status == EX_TEMPFAIL)
838 else if (status == EX_NOTFOUND)
842 if (bitset(1 << mapno, mapreturn[i]))
851 sm_dprintf("getcanonname(%s), found, ad=%d\n", host, secure);
854 ** If returned name is still single token, compensate
855 ** by tagging on $m. This is because some sites set
856 ** up their DNS or NIS databases wrong.
859 if ((d = strchr(host, '.')) == NULL || d[1] == '\0')
861 d = macvalue('m', CurEnv);
863 hbsize > (int) (strlen(host) + strlen(d) + 1))
865 if (host[strlen(host) - 1] != '.')
866 (void) sm_strlcat2(host, ".", d,
869 (void) sm_strlcat(host, d, hbsize);
873 #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
874 if (VendorCode == VENDOR_SUN &&
875 should_try_nis_domain)
879 #endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */
880 return HOST_NOTFOUND;
883 return secure ? HOST_SECURE : HOST_OK;
886 #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
887 if (VendorCode == VENDOR_SUN && should_try_nis_domain)
890 if (nis_domain != NULL &&
891 strlen(nis_domain) + strlen(host) + 1 < hbsize)
893 (void) sm_strlcat2(host, ".", nis_domain, hbsize);
897 #endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */
900 sm_dprintf("getcanonname(%s), failed, status=%d\n", host,
904 SM_SET_H_ERRNO(TRY_AGAIN);
906 SM_SET_H_ERRNO(HOST_NOT_FOUND);
908 return HOST_NOTFOUND;
911 ** EXTRACT_CANONNAME -- extract canonical name from /etc/hosts entry
914 ** name -- the name against which to match.
915 ** dot -- where to reinsert '.' to get FQDN
916 ** line -- the /etc/hosts line.
917 ** cbuf -- the location to store the result.
918 ** cbuflen -- the size of cbuf.
921 ** true -- if the line matched the desired name.
922 ** false -- otherwise.
926 extract_canonname(name, dot, line, cbuf, cbuflen)
943 char nbuf[MAXNAME + 1];
945 p = get_column(line, i, '\0', nbuf, sizeof(nbuf));
950 if (cbuf[0] == '\0' ||
951 (strchr(cbuf, '.') == NULL && strchr(p, '.') != NULL))
953 (void) sm_strlcpy(cbuf, p, cbuflen);
955 if (sm_strcasecmp(name, p) == 0)
957 else if (dot != NULL)
959 /* try looking for the FQDN as well */
961 if (sm_strcasecmp(name, p) == 0)
966 if (found && strchr(cbuf, '.') == NULL)
968 /* try to add a domain on the end of the name */
969 char *domain = macvalue('m', CurEnv);
971 if (domain != NULL &&
972 strlen(domain) + (i = strlen(cbuf)) + 1 < (size_t) cbuflen)
976 (void) sm_strlcpy(p, domain, cbuflen - i - 1);
989 # include "sm_resolve.h"
990 # if NETINET || NETINET6
991 # include <arpa/inet.h>
995 ** DNS_MAP_OPEN -- stub to check proper value for dns map type
999 dns_map_open(map, mode)
1004 sm_dprintf("dns_map_open(%s, %d)\n", map->map_mname, mode);
1007 if (mode != O_RDONLY)
1009 /* issue a pseudo-error message */
1010 errno = SM_EMAPCANTWRITE;
1017 ** DNS_MAP_PARSEARGS -- parse dns map definition args.
1020 ** map -- pointer to MAP
1021 ** args -- pointer to the args on the config line.
1024 ** true -- if everything parsed OK.
1025 ** false -- otherwise.
1028 #define map_sizelimit map_lockfd /* overload field */
1033 unsigned int dns_m_options;
1037 dns_map_parseargs(map,args)
1041 register char *p = args;
1042 struct dns_map *map_p;
1044 map_p = (struct dns_map *) xalloc(sizeof(*map_p));
1045 memset(map_p, '\0', sizeof(*map_p));
1046 map_p->dns_m_type = -1;
1047 map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL;
1051 while (SM_ISSPACE(*p))
1060 if (nsportip(p) < 0)
1061 syserr("dns map %s: nsportip(%s)=failed",
1064 #endif /* DNSSEC_TEST */
1067 map->map_mflags |= MF_APPEND;
1074 case 'B': /* base domain */
1078 while (isascii(*++p) && isspace(*p))
1085 ** slight abuse of map->map_file; it isn't
1086 ** used otherwise in this map type.
1089 map->map_file = newstr(p);
1103 map->map_timeout = convtime(p, 's');
1110 map->map_mflags |= MF_NOFOLDCASE;
1114 map->map_mflags |= MF_MATCHONLY;
1118 map->map_mflags |= MF_INCLNULL;
1119 map->map_mflags &= ~MF_TRY0NULL;
1123 map->map_mflags &= ~MF_TRY1NULL;
1127 map->map_mflags |= MF_OPTIONAL;
1131 map->map_mflags |= MF_KEEPQUOTES;
1135 #if defined(RES_USE_EDNS0) && defined(RES_USE_DNSSEC)
1136 map_p->dns_m_options |= SM_RES_DNSSEC;
1141 while (isascii(*++p) && isspace(*p))
1143 map->map_retry = atoi(p);
1147 map->map_mflags |= MF_NODEFER;
1151 map->map_tapp = ++p;
1156 map->map_coldelim = *p;
1162 map->map_coldelim = '\n';
1166 map->map_coldelim = '\t';
1170 map->map_coldelim = '\\';
1176 while (isascii(*++p) && isspace(*p))
1178 map->map_sizelimit = atoi(p);
1181 /* Start of dns_map specific args */
1182 case 'R': /* search field */
1186 while (isascii(*++p) && isspace(*p))
1191 map_p->dns_m_type = dns_string_to_type(p);
1194 if (map_p->dns_m_type < 0)
1195 syserr("dns map %s: wrong type %s",
1201 while (*p != '\0' && !(SM_ISSPACE(*p)))
1206 if (map_p->dns_m_type < 0)
1207 syserr("dns map %s: missing -R type", map->map_mname);
1208 if (map->map_app != NULL)
1209 map->map_app = newstr(map->map_app);
1210 if (map->map_tapp != NULL)
1211 map->map_tapp = newstr(map->map_tapp);
1214 ** Assumption: assert(sizeof(int) <= sizeof(ARBPTR_T));
1215 ** Even if this assumption is wrong, we use only one byte,
1216 ** so it doesn't really matter.
1219 map->map_db1 = (ARBPTR_T) map_p;
1224 ** DNS_MAP_LOOKUP -- perform dns map lookup.
1227 ** map -- pointer to MAP
1228 ** name -- name to lookup
1229 ** av -- arguments to interpolate into buf.
1230 ** statp -- pointer to status (EX_)
1233 ** result of lookup if succeeded.
1234 ** NULL -- otherwise.
1238 dns_map_lookup(map, name, av, statp)
1245 char *vp = NULL, *result = NULL;
1247 struct dns_map *map_p;
1248 RESOURCE_RECORD_T *rr = NULL;
1249 DNS_REPLY_T *r = NULL;
1250 unsigned int options;
1252 static char buf6[INET6_ADDRSTRLEN];
1256 sm_dprintf("dns_map_lookup(%s, %s)\n",
1257 map->map_mname, name);
1259 map_p = (struct dns_map *)(map->map_db1);
1260 options = map_p->dns_m_options;
1261 if (map->map_file != NULL && *map->map_file != '\0')
1266 len = strlen(map->map_file) + strlen(name) + 2;
1267 appdomain = (char *) sm_malloc(len);
1268 if (appdomain == NULL)
1270 *statp = EX_UNAVAILABLE;
1273 (void) sm_strlcpyn(appdomain, len, 3, name, ".", map->map_file);
1274 r = dns_lookup_map(appdomain, C_IN, map_p->dns_m_type,
1275 map->map_timeout, map->map_retry, options);
1280 r = dns_lookup_map(name, C_IN, map_p->dns_m_type,
1281 map->map_timeout, map->map_retry, options);
1287 if (h_errno == TRY_AGAIN || transienterror(errno))
1288 *statp = EX_TEMPFAIL;
1290 *statp = EX_NOTFOUND;
1294 for (rr = r->dns_r_head; rr != NULL; rr = rr->rr_next)
1299 switch (rr->rr_type)
1303 value = rr->rr_u.rr_txt;
1307 value = rr->rr_u.rr_txt;
1311 value = rr->rr_u.rr_mx->mx_r_domain;
1315 value = rr->rr_u.rr_srv->srv_r_target;
1319 value = rr->rr_u.rr_txt;
1323 value = rr->rr_u.rr_txt;
1327 value = rr->rr_u.rr_mx->mx_r_domain;
1332 value = inet_ntoa(*(rr->rr_u.rr_a));
1334 # endif /* NETINET */
1338 value = anynet_ntop(rr->rr_u.rr_aaaa, buf6,
1341 # endif /* NETINET6 */
1345 value = rr->rr_u.rr_txt;
1347 # endif /* T_TLSA */
1350 (void) strreplnonprt(value, 'X');
1351 if (map_p->dns_m_type != rr->rr_type)
1354 sm_dprintf("\tskipping type %s (%d) value %s\n",
1355 type != NULL ? type : "<UNKNOWN>",
1357 value != NULL ? value : "<NO VALUE>");
1362 if (rr->rr_type == T_AAAA && value == NULL)
1365 *statp = EX_DATAERR;
1367 sm_dprintf("\tbad T_AAAA conversion\n");
1370 # endif /* NETINET6 */
1372 sm_dprintf("\tfound type %s (%d) value %s\n",
1373 type != NULL ? type : "<UNKNOWN>",
1375 value != NULL ? value : "<NO VALUE>");
1376 if (value != NULL &&
1377 (map->map_coldelim == '\0' ||
1378 map->map_sizelimit == 1 ||
1379 bitset(MF_MATCHONLY, map->map_mflags)))
1381 /* Only care about the first match */
1385 else if (vp == NULL)
1392 /* concatenate the results */
1396 sz = strlen(vp) + strlen(value) + 2;
1398 (void) sm_snprintf(new, sz, "%s%c%s",
1399 vp, map->map_coldelim, value);
1402 if (map->map_sizelimit > 0 &&
1403 ++resnum >= map->map_sizelimit)
1410 *statp = EX_NOTFOUND;
1412 sm_dprintf("\tno match found\n");
1416 /* Cleanly truncate for rulesets */
1417 truncate_at_delim(vp, PSBUFSIZE / 2, map->map_coldelim);
1422 sm_syslog(LOG_INFO, CurEnv->e_id, "dns %.100s => %s",
1424 if (bitset(MF_MATCHONLY, map->map_mflags))
1425 result = map_rewrite(map, name, strlen(name), NULL);
1427 result = map_rewrite(map, vp, vsize, av);
1435 # endif /* DNSMAP */
1436 #endif /* NAMED_BIND */
1445 ** NDBM_MAP_OPEN -- DBM-style map open
1449 ndbm_map_open(map, mode)
1459 int smode = S_IREAD;
1460 char dirfile[MAXPATHLEN];
1461 char pagfile[MAXPATHLEN];
1463 struct stat std, stp;
1466 sm_dprintf("ndbm_map_open(%s, %s, %d)\n",
1467 map->map_mname, map->map_file, mode);
1468 map->map_lockfd = -1;
1471 /* do initial file and directory checks */
1472 if (sm_strlcpyn(dirfile, sizeof(dirfile), 2,
1473 map->map_file, ".dir") >= sizeof(dirfile) ||
1474 sm_strlcpyn(pagfile, sizeof(pagfile), 2,
1475 map->map_file, ".pag") >= sizeof(pagfile))
1478 if (!bitset(MF_OPTIONAL, map->map_mflags))
1479 syserr("dbm map \"%s\": map file %s name too long",
1480 map->map_mname, map->map_file);
1483 sff = SFF_ROOTOK|SFF_REGONLY;
1487 if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail))
1489 if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail))
1495 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
1498 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
1499 sff |= SFF_SAFEDIRPATH;
1500 ret = safefile(dirfile, RunAsUid, RunAsGid, RunAsUserName,
1503 ret = safefile(pagfile, RunAsUid, RunAsGid, RunAsUserName,
1508 char *prob = "unsafe";
1510 /* cannot open this map */
1514 sm_dprintf("\t%s map file: %d\n", prob, ret);
1515 if (!bitset(MF_OPTIONAL, map->map_mflags))
1516 syserr("dbm map \"%s\": %s map file %s",
1517 map->map_mname, prob, map->map_file);
1520 if (std.st_mode == ST_MODE_NOFILE)
1521 mode |= O_CREAT|O_EXCL;
1524 if (mode == O_RDONLY)
1527 mode |= O_TRUNC|O_EXLOCK;
1528 # else /* LOCK_ON_OPEN */
1529 if ((mode & O_ACCMODE) == O_RDWR)
1533 ** Warning: race condition. Try to lock the file as
1534 ** quickly as possible after opening it.
1535 ** This may also have security problems on some systems,
1536 ** but there isn't anything we can do about it.
1540 # else /* NOFTRUNCATE */
1542 ** This ugly code opens the map without truncating it,
1543 ** locks the file, then truncates it. Necessary to
1544 ** avoid race conditions.
1549 long sff = SFF_CREAT|SFF_OPENASROOT;
1551 if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail))
1553 if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail))
1556 dirfd = safeopen(dirfile, mode, DBMMODE, sff);
1557 pagfd = safeopen(pagfile, mode, DBMMODE, sff);
1559 if (dirfd < 0 || pagfd < 0)
1563 (void) close(dirfd);
1565 (void) close(pagfd);
1567 syserr("ndbm_map_open: cannot create database %s",
1571 if (ftruncate(dirfd, (off_t) 0) < 0 ||
1572 ftruncate(pagfd, (off_t) 0) < 0)
1575 (void) close(dirfd);
1576 (void) close(pagfd);
1578 syserr("ndbm_map_open: cannot truncate %s.{dir,pag}",
1583 /* if new file, get "before" bits for later filechanged check */
1584 if (std.st_mode == ST_MODE_NOFILE &&
1585 (fstat(dirfd, &std) < 0 || fstat(pagfd, &stp) < 0))
1588 (void) close(dirfd);
1589 (void) close(pagfd);
1591 syserr("ndbm_map_open(%s.{dir,pag}): cannot fstat pre-opened file",
1596 /* have to save the lock for the duration (bletch) */
1597 map->map_lockfd = dirfd;
1598 (void) close(pagfd);
1600 /* twiddle bits for dbm_open */
1601 mode &= ~(O_CREAT|O_EXCL);
1602 # endif /* NOFTRUNCATE */
1604 # endif /* LOCK_ON_OPEN */
1606 /* open the database */
1607 dbm = dbm_open(map->map_file, mode, DBMMODE);
1611 if (bitset(MF_ALIAS, map->map_mflags) &&
1612 aliaswait(map, ".pag", false))
1614 # if !LOCK_ON_OPEN && !NOFTRUNCATE
1615 if (map->map_lockfd >= 0)
1616 (void) close(map->map_lockfd);
1619 if (!bitset(MF_OPTIONAL, map->map_mflags))
1620 syserr("Cannot open DBM database %s", map->map_file);
1623 dfd = dbm_dirfno(dbm);
1624 pfd = dbm_pagfno(dbm);
1627 /* heuristic: if files are linked, this is actually gdbm */
1629 # if !LOCK_ON_OPEN && !NOFTRUNCATE
1630 if (map->map_lockfd >= 0)
1631 (void) close(map->map_lockfd);
1634 syserr("dbm map \"%s\": cannot support GDBM",
1639 if (filechanged(dirfile, dfd, &std) ||
1640 filechanged(pagfile, pfd, &stp))
1644 # if !LOCK_ON_OPEN && !NOFTRUNCATE
1645 if (map->map_lockfd >= 0)
1646 (void) close(map->map_lockfd);
1649 syserr("ndbm_map_open(%s): file changed after open",
1654 map->map_db1 = (ARBPTR_T) dbm;
1657 ** Need to set map_mtime before the call to aliaswait()
1658 ** as aliaswait() will call map_lookup() which requires
1659 ** map_mtime to be set
1662 if (fstat(pfd, &st) >= 0)
1663 map->map_mtime = st.st_mtime;
1665 if (mode == O_RDONLY)
1669 (void) lockfile(dfd, map->map_file, ".dir", LOCK_UN);
1671 (void) lockfile(pfd, map->map_file, ".pag", LOCK_UN);
1672 # endif /* LOCK_ON_OPEN */
1673 if (bitset(MF_ALIAS, map->map_mflags) &&
1674 !aliaswait(map, ".pag", true))
1679 map->map_mflags |= MF_LOCKED;
1680 if (geteuid() == 0 && TrustedUid != 0)
1683 if (fchown(dfd, TrustedUid, -1) < 0 ||
1684 fchown(pfd, TrustedUid, -1) < 0)
1688 sm_syslog(LOG_ALERT, NOQID,
1689 "ownership change on %s failed: %s",
1690 map->map_file, sm_errstring(err));
1691 message("050 ownership change on %s failed: %s",
1692 map->map_file, sm_errstring(err));
1694 # else /* HASFCHOWN */
1695 sm_syslog(LOG_ALERT, NOQID,
1696 "no fchown(): cannot change ownership on %s",
1698 message("050 no fchown(): cannot change ownership on %s",
1700 # endif /* HASFCHOWN */
1708 ** NDBM_MAP_LOOKUP -- look up a datum in a DBM-type map
1712 ndbm_map_lookup(map, name, av, statp)
1720 char keybuf[MAXNAME + 1];
1724 sm_dprintf("ndbm_map_lookup(%s, %s)\n",
1725 map->map_mname, name);
1728 key.dsize = strlen(name);
1729 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
1731 if (key.dsize > sizeof(keybuf) - 1)
1732 key.dsize = sizeof(keybuf) - 1;
1733 memmove(keybuf, key.dptr, key.dsize);
1734 keybuf[key.dsize] = '\0';
1739 dfd = dbm_dirfno((DBM *) map->map_db1);
1740 if (dfd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
1741 (void) lockfile(dfd, map->map_file, ".dir", LOCK_SH);
1742 pfd = dbm_pagfno((DBM *) map->map_db1);
1743 if (pfd < 0 || fstat(pfd, &stbuf) < 0 ||
1744 stbuf.st_mtime > map->map_mtime)
1746 /* Reopen the database to sync the cache */
1747 int omode = bitset(map->map_mflags, MF_WRITABLE) ? O_RDWR
1750 if (dfd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
1751 (void) lockfile(dfd, map->map_file, ".dir", LOCK_UN);
1752 map->map_mflags |= MF_CLOSING;
1753 map->map_class->map_close(map);
1754 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
1755 if (map->map_class->map_open(map, omode))
1757 map->map_mflags |= MF_OPEN;
1758 map->map_pid = CurrentPid;
1759 if ((omode & O_ACCMODE) == O_RDWR)
1760 map->map_mflags |= MF_WRITABLE;
1765 if (!bitset(MF_OPTIONAL, map->map_mflags))
1767 extern MAPCLASS BogusMapClass;
1769 *statp = EX_TEMPFAIL;
1770 map->map_orgclass = map->map_class;
1771 map->map_class = &BogusMapClass;
1772 map->map_mflags |= MF_OPEN;
1773 map->map_pid = CurrentPid;
1774 syserr("Cannot reopen NDBM database %s",
1781 if (bitset(MF_TRY0NULL, map->map_mflags))
1783 val = dbm_fetch((DBM *) map->map_db1, key);
1784 if (val.dptr != NULL)
1785 map->map_mflags &= ~MF_TRY1NULL;
1787 if (val.dptr == NULL && bitset(MF_TRY1NULL, map->map_mflags))
1790 val = dbm_fetch((DBM *) map->map_db1, key);
1791 if (val.dptr != NULL)
1792 map->map_mflags &= ~MF_TRY0NULL;
1794 if (dfd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
1795 (void) lockfile(dfd, map->map_file, ".dir", LOCK_UN);
1796 if (val.dptr == NULL)
1798 if (bitset(MF_MATCHONLY, map->map_mflags))
1799 return map_rewrite(map, name, strlen(name), NULL);
1801 return map_rewrite(map, val.dptr, val.dsize, av);
1806 ** NDBM_MAP_STORE -- store a datum in the database
1810 ndbm_map_store(map, lhs, rhs)
1818 char keybuf[MAXNAME + 1];
1821 sm_dprintf("ndbm_map_store(%s, %s, %s)\n",
1822 map->map_mname, lhs, rhs);
1824 key.dsize = strlen(lhs);
1826 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
1828 if (key.dsize > sizeof(keybuf) - 1)
1829 key.dsize = sizeof(keybuf) - 1;
1830 memmove(keybuf, key.dptr, key.dsize);
1831 keybuf[key.dsize] = '\0';
1836 data.dsize = strlen(rhs);
1839 if (bitset(MF_INCLNULL, map->map_mflags))
1845 status = dbm_store((DBM *) map->map_db1, key, data, DBM_INSERT);
1848 if (!bitset(MF_APPEND, map->map_mflags))
1849 message("050 Warning: duplicate alias name %s", lhs);
1852 static char *buf = NULL;
1853 static int bufsiz = 0;
1857 old.dptr = ndbm_map_lookup(map, key.dptr,
1858 (char **) NULL, &xstat);
1859 if (old.dptr != NULL && *(char *) old.dptr != '\0')
1861 old.dsize = strlen(old.dptr);
1862 if (data.dsize + old.dsize + 2 > bufsiz)
1865 (void) sm_free(buf);
1866 bufsiz = data.dsize + old.dsize + 2;
1867 buf = sm_pmalloc_x(bufsiz);
1869 (void) sm_strlcpyn(buf, bufsiz, 3,
1870 data.dptr, ",", old.dptr);
1871 data.dsize = data.dsize + old.dsize + 1;
1874 sm_dprintf("ndbm_map_store append=%s\n",
1878 status = dbm_store((DBM *) map->map_db1,
1879 key, data, DBM_REPLACE);
1882 syserr("readaliases: dbm put (%s): %d", lhs, status);
1887 ** NDBM_MAP_CLOSE -- close the database
1895 sm_dprintf("ndbm_map_close(%s, %s, %lx)\n",
1896 map->map_mname, map->map_file, map->map_mflags);
1898 if (bitset(MF_WRITABLE, map->map_mflags))
1900 # ifdef NDBM_YP_COMPAT
1902 char buf[MAXHOSTNAMELEN];
1904 inclnull = bitset(MF_INCLNULL, map->map_mflags);
1905 map->map_mflags &= ~MF_INCLNULL;
1907 if (strstr(map->map_file, "/yp/") != NULL)
1909 long save_mflags = map->map_mflags;
1911 map->map_mflags |= MF_NOFOLDCASE;
1913 (void) sm_snprintf(buf, sizeof(buf), "%010ld", curtime());
1914 ndbm_map_store(map, "YP_LAST_MODIFIED", buf);
1916 (void) gethostname(buf, sizeof(buf));
1917 ndbm_map_store(map, "YP_MASTER_NAME", buf);
1919 map->map_mflags = save_mflags;
1923 map->map_mflags |= MF_INCLNULL;
1924 # endif /* NDBM_YP_COMPAT */
1926 /* write out the distinguished alias */
1927 ndbm_map_store(map, "@", "@");
1929 dbm_close((DBM *) map->map_db1);
1931 /* release lock (if needed) */
1933 if (map->map_lockfd >= 0)
1934 (void) close(map->map_lockfd);
1940 ** NEWDB (Hash and BTree) Modules
1946 ** BT_MAP_OPEN, HASH_MAP_OPEN -- database open primitives.
1948 ** These do rather bizarre locking. If you can lock on open,
1949 ** do that to avoid the condition of opening a database that
1950 ** is being rebuilt. If you don't, we'll try to fake it, but
1951 ** there will be a race condition. If opening for read-only,
1952 ** we immediately release the lock to avoid freezing things up.
1953 ** We really ought to hold the lock, but guarantee that we won't
1954 ** be pokey about it. That's hard to do.
1957 /* these should be K line arguments */
1958 # if DB_VERSION_MAJOR < 2
1959 # define db_cachesize cachesize
1960 # define h_nelem nelem
1961 # ifndef DB_CACHE_SIZE
1962 # define DB_CACHE_SIZE (1024 * 1024) /* database memory cache size */
1964 # ifndef DB_HASH_NELEM
1965 # define DB_HASH_NELEM 4096 /* (starting) size of hash table */
1967 # endif /* DB_VERSION_MAJOR < 2 */
1970 bt_map_open(map, mode)
1974 # if DB_VERSION_MAJOR < 2
1977 # if DB_VERSION_MAJOR == 2
1980 # if DB_VERSION_MAJOR > 2
1981 void *btinfo = NULL;
1985 sm_dprintf("bt_map_open(%s, %s, %d)\n",
1986 map->map_mname, map->map_file, mode);
1988 # if DB_VERSION_MAJOR < 3
1989 memset(&btinfo, '\0', sizeof(btinfo));
1990 # ifdef DB_CACHE_SIZE
1991 btinfo.db_cachesize = DB_CACHE_SIZE;
1993 # endif /* DB_VERSION_MAJOR < 3 */
1995 return db_map_open(map, mode, "btree", DB_BTREE, &btinfo);
1999 hash_map_open(map, mode)
2003 # if DB_VERSION_MAJOR < 2
2006 # if DB_VERSION_MAJOR == 2
2009 # if DB_VERSION_MAJOR > 2
2014 sm_dprintf("hash_map_open(%s, %s, %d)\n",
2015 map->map_mname, map->map_file, mode);
2017 # if DB_VERSION_MAJOR < 3
2018 memset(&hinfo, '\0', sizeof(hinfo));
2019 # ifdef DB_HASH_NELEM
2020 hinfo.h_nelem = DB_HASH_NELEM;
2022 # ifdef DB_CACHE_SIZE
2023 hinfo.db_cachesize = DB_CACHE_SIZE;
2025 # endif /* DB_VERSION_MAJOR < 3 */
2027 return db_map_open(map, mode, "hash", DB_HASH, &hinfo);
2031 db_map_open(map, mode, mapclassname, dbtype, openinfo)
2036 # if DB_VERSION_MAJOR < 2
2037 const void *openinfo;
2039 # if DB_VERSION_MAJOR == 2
2042 # if DB_VERSION_MAJOR > 2
2049 int smode = S_IREAD;
2054 char buf[MAXPATHLEN];
2056 /* do initial file and directory checks */
2057 if (sm_strlcpy(buf, map->map_file, sizeof(buf)) >= sizeof(buf))
2060 if (!bitset(MF_OPTIONAL, map->map_mflags))
2061 syserr("map \"%s\": map file %s name too long",
2062 map->map_mname, map->map_file);
2066 if (i < 3 || strcmp(&buf[i - 3], ".db") != 0)
2068 if (sm_strlcat(buf, ".db", sizeof(buf)) >= sizeof(buf))
2071 if (!bitset(MF_OPTIONAL, map->map_mflags))
2072 syserr("map \"%s\": map file %s name too long",
2073 map->map_mname, map->map_file);
2081 sff = SFF_ROOTOK|SFF_REGONLY;
2085 if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail))
2087 if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail))
2093 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
2096 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
2097 sff |= SFF_SAFEDIRPATH;
2098 i = safefile(buf, RunAsUid, RunAsGid, RunAsUserName, sff, smode, &st);
2102 char *prob = "unsafe";
2104 /* cannot open this map */
2108 sm_dprintf("\t%s map file: %s\n", prob, sm_errstring(i));
2110 if (!bitset(MF_OPTIONAL, map->map_mflags))
2111 syserr("%s map \"%s\": %s map file %s",
2112 mapclassname, map->map_mname, prob, buf);
2115 if (st.st_mode == ST_MODE_NOFILE)
2116 omode |= O_CREAT|O_EXCL;
2118 map->map_lockfd = -1;
2122 omode |= O_TRUNC|O_EXLOCK;
2125 # else /* LOCK_ON_OPEN */
2127 ** Pre-lock the file to avoid race conditions. In particular,
2128 ** since dbopen returns NULL if the file is zero length, we
2129 ** must have a locked instance around the dbopen.
2132 fd = open(buf, omode, DBMMODE);
2135 if (!bitset(MF_OPTIONAL, map->map_mflags))
2136 syserr("db_map_open: cannot pre-open database %s", buf);
2140 /* make sure no baddies slipped in just before the open... */
2141 if (filechanged(buf, fd, &st))
2146 syserr("db_map_open(%s): file changed after pre-open", buf);
2150 /* if new file, get the "before" bits for later filechanged check */
2151 if (st.st_mode == ST_MODE_NOFILE && fstat(fd, &st) < 0)
2156 syserr("db_map_open(%s): cannot fstat pre-opened file",
2161 /* actually lock the pre-opened file */
2162 if (!lockfile(fd, buf, NULL, mode == O_RDONLY ? LOCK_SH : LOCK_EX))
2163 syserr("db_map_open: cannot lock %s", buf);
2165 /* set up mode bits for dbopen */
2168 omode &= ~(O_EXCL|O_CREAT);
2169 # endif /* LOCK_ON_OPEN */
2171 # if DB_VERSION_MAJOR < 2
2172 db = dbopen(buf, omode, DBMMODE, dbtype, openinfo);
2173 # else /* DB_VERSION_MAJOR < 2 */
2176 # if DB_VERSION_MAJOR > 2
2180 if (mode == O_RDONLY)
2182 if (bitset(O_CREAT, omode))
2184 if (bitset(O_TRUNC, omode))
2185 flags |= DB_TRUNCATE;
2186 SM_DB_FLAG_ADD(flags);
2188 # if DB_VERSION_MAJOR > 2
2189 ret = db_create(&db, NULL, 0);
2190 # ifdef DB_CACHE_SIZE
2191 if (ret == 0 && db != NULL)
2193 ret = db->set_cachesize(db, 0, DB_CACHE_SIZE, 0);
2196 (void) db->close(db, 0);
2200 # endif /* DB_CACHE_SIZE */
2201 # ifdef DB_HASH_NELEM
2202 if (dbtype == DB_HASH && ret == 0 && db != NULL)
2204 ret = db->set_h_nelem(db, DB_HASH_NELEM);
2207 (void) db->close(db, 0);
2211 # endif /* DB_HASH_NELEM */
2212 if (ret == 0 && db != NULL)
2215 DBTXN /* transaction for DB 4.1 */
2216 buf, NULL, dbtype, flags, DBMMODE);
2219 #ifdef DB_OLD_VERSION
2220 if (ret == DB_OLD_VERSION)
2222 #endif /* DB_OLD_VERSION */
2223 (void) db->close(db, 0);
2228 # else /* DB_VERSION_MAJOR > 2 */
2229 errno = db_open(buf, dbtype, flags, DBMMODE,
2230 NULL, openinfo, &db);
2231 # endif /* DB_VERSION_MAJOR > 2 */
2233 # endif /* DB_VERSION_MAJOR < 2 */
2238 map->map_lockfd = fd;
2241 # endif /* !LOCK_ON_OPEN */
2245 if (mode == O_RDONLY && bitset(MF_ALIAS, map->map_mflags) &&
2246 aliaswait(map, ".db", false))
2249 if (map->map_lockfd >= 0)
2250 (void) close(map->map_lockfd);
2253 if (!bitset(MF_OPTIONAL, map->map_mflags))
2254 syserr("Cannot open %s database %s",
2259 # if DB_VERSION_MAJOR < 2
2263 errno = db->fd(db, &fd);
2264 # endif /* DB_VERSION_MAJOR < 2 */
2265 if (filechanged(buf, fd, &st))
2268 # if DB_VERSION_MAJOR < 2
2269 (void) db->close(db);
2271 errno = db->close(db, 0);
2272 # endif /* DB_VERSION_MAJOR < 2 */
2274 if (map->map_lockfd >= 0)
2275 (void) close(map->map_lockfd);
2278 syserr("db_map_open(%s): file changed after open", buf);
2283 map->map_mflags |= MF_LOCKED;
2285 if (fd >= 0 && mode == O_RDONLY)
2287 (void) lockfile(fd, buf, NULL, LOCK_UN);
2289 # endif /* LOCK_ON_OPEN */
2291 /* try to make sure that at least the database header is on disk */
2294 (void) db->sync(db, 0);
2295 if (geteuid() == 0 && TrustedUid != 0)
2298 if (fchown(fd, TrustedUid, -1) < 0)
2302 sm_syslog(LOG_ALERT, NOQID,
2303 "ownership change on %s failed: %s",
2304 buf, sm_errstring(err));
2305 message("050 ownership change on %s failed: %s",
2306 buf, sm_errstring(err));
2308 # else /* HASFCHOWN */
2309 sm_syslog(LOG_ALERT, NOQID,
2310 "no fchown(): cannot change ownership on %s",
2312 message("050 no fchown(): cannot change ownership on %s",
2314 # endif /* HASFCHOWN */
2318 map->map_db2 = (ARBPTR_T) db;
2321 ** Need to set map_mtime before the call to aliaswait()
2322 ** as aliaswait() will call map_lookup() which requires
2323 ** map_mtime to be set
2326 if (fd >= 0 && fstat(fd, &st) >= 0)
2327 map->map_mtime = st.st_mtime;
2329 if (mode == O_RDONLY && bitset(MF_ALIAS, map->map_mflags) &&
2330 !aliaswait(map, ".db", true))
2337 ** DB_MAP_LOOKUP -- look up a datum in a BTREE- or HASH-type map
2341 db_map_lookup(map, name, av, statp)
2348 register DB *db = (DB *) map->map_db2;
2354 char keybuf[MAXNAME + 1];
2355 char buf[MAXPATHLEN];
2357 memset(&key, '\0', sizeof(key));
2358 memset(&val, '\0', sizeof(val));
2361 sm_dprintf("db_map_lookup(%s, %s)\n",
2362 map->map_mname, name);
2364 if (sm_strlcpy(buf, map->map_file, sizeof(buf)) >= sizeof(buf))
2367 if (!bitset(MF_OPTIONAL, map->map_mflags))
2368 syserr("map \"%s\": map file %s name too long",
2369 map->map_mname, map->map_file);
2373 if (i > 3 && strcmp(&buf[i - 3], ".db") == 0)
2376 key.size = strlen(name);
2377 if (key.size > sizeof(keybuf) - 1)
2378 key.size = sizeof(keybuf) - 1;
2380 memmove(keybuf, name, key.size);
2381 keybuf[key.size] = '\0';
2382 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
2385 # if DB_VERSION_MAJOR < 2
2389 errno = db->fd(db, &fd);
2390 # endif /* DB_VERSION_MAJOR < 2 */
2391 if (fd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
2392 (void) lockfile(fd, buf, ".db", LOCK_SH);
2393 if (fd < 0 || fstat(fd, &stbuf) < 0 || stbuf.st_mtime > map->map_mtime)
2395 /* Reopen the database to sync the cache */
2396 int omode = bitset(map->map_mflags, MF_WRITABLE) ? O_RDWR
2399 if (fd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
2400 (void) lockfile(fd, buf, ".db", LOCK_UN);
2401 map->map_mflags |= MF_CLOSING;
2402 map->map_class->map_close(map);
2403 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
2404 if (map->map_class->map_open(map, omode))
2406 map->map_mflags |= MF_OPEN;
2407 map->map_pid = CurrentPid;
2408 if ((omode & O_ACCMODE) == O_RDWR)
2409 map->map_mflags |= MF_WRITABLE;
2410 db = (DB *) map->map_db2;
2415 if (!bitset(MF_OPTIONAL, map->map_mflags))
2417 extern MAPCLASS BogusMapClass;
2419 *statp = EX_TEMPFAIL;
2420 map->map_orgclass = map->map_class;
2421 map->map_class = &BogusMapClass;
2422 map->map_mflags |= MF_OPEN;
2423 map->map_pid = CurrentPid;
2424 syserr("Cannot reopen DB database %s",
2432 if (bitset(MF_TRY0NULL, map->map_mflags))
2434 # if DB_VERSION_MAJOR < 2
2435 st = db->get(db, &key, &val, 0);
2436 # else /* DB_VERSION_MAJOR < 2 */
2437 errno = db->get(db, NULL, &key, &val, 0);
2453 # endif /* DB_VERSION_MAJOR < 2 */
2455 map->map_mflags &= ~MF_TRY1NULL;
2457 if (st != 0 && bitset(MF_TRY1NULL, map->map_mflags))
2460 # if DB_VERSION_MAJOR < 2
2461 st = db->get(db, &key, &val, 0);
2462 # else /* DB_VERSION_MAJOR < 2 */
2463 errno = db->get(db, NULL, &key, &val, 0);
2479 # endif /* DB_VERSION_MAJOR < 2 */
2481 map->map_mflags &= ~MF_TRY0NULL;
2484 if (fd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
2485 (void) lockfile(fd, buf, ".db", LOCK_UN);
2490 syserr("db_map_lookup: get (%s)", name);
2493 if (bitset(MF_MATCHONLY, map->map_mflags))
2494 return map_rewrite(map, name, strlen(name), NULL);
2496 return map_rewrite(map, val.data, val.size, av);
2501 ** DB_MAP_STORE -- store a datum in the NEWDB database
2505 db_map_store(map, lhs, rhs)
2513 register DB *db = map->map_db2;
2514 char keybuf[MAXNAME + 1];
2516 memset(&key, '\0', sizeof(key));
2517 memset(&data, '\0', sizeof(data));
2520 sm_dprintf("db_map_store(%s, %s, %s)\n",
2521 map->map_mname, lhs, rhs);
2523 key.size = strlen(lhs);
2525 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
2527 if (key.size > sizeof(keybuf) - 1)
2528 key.size = sizeof(keybuf) - 1;
2529 memmove(keybuf, key.data, key.size);
2530 keybuf[key.size] = '\0';
2535 data.size = strlen(rhs);
2538 if (bitset(MF_INCLNULL, map->map_mflags))
2544 # if DB_VERSION_MAJOR < 2
2545 status = db->put(db, &key, &data, R_NOOVERWRITE);
2546 # else /* DB_VERSION_MAJOR < 2 */
2547 errno = db->put(db, NULL, &key, &data, DB_NOOVERWRITE);
2562 # endif /* DB_VERSION_MAJOR < 2 */
2565 if (!bitset(MF_APPEND, map->map_mflags))
2566 message("050 Warning: duplicate alias name %s", lhs);
2569 static char *buf = NULL;
2570 static int bufsiz = 0;
2573 memset(&old, '\0', sizeof(old));
2575 old.data = db_map_lookup(map, key.data,
2576 (char **) NULL, &status);
2577 if (old.data != NULL)
2579 old.size = strlen(old.data);
2580 if (data.size + old.size + 2 > (size_t) bufsiz)
2584 bufsiz = data.size + old.size + 2;
2585 buf = sm_pmalloc_x(bufsiz);
2587 (void) sm_strlcpyn(buf, bufsiz, 3,
2588 (char *) data.data, ",",
2590 data.size = data.size + old.size + 1;
2593 sm_dprintf("db_map_store append=%s\n",
2594 (char *) data.data);
2597 # if DB_VERSION_MAJOR < 2
2598 status = db->put(db, &key, &data, 0);
2600 status = errno = db->put(db, NULL, &key, &data, 0);
2601 # endif /* DB_VERSION_MAJOR < 2 */
2604 syserr("readaliases: db put (%s)", lhs);
2609 ** DB_MAP_CLOSE -- add distinguished entries and close the database
2616 register DB *db = map->map_db2;
2619 sm_dprintf("db_map_close(%s, %s, %lx)\n",
2620 map->map_mname, map->map_file, map->map_mflags);
2622 if (bitset(MF_WRITABLE, map->map_mflags))
2624 /* write out the distinguished alias */
2625 db_map_store(map, "@", "@");
2628 (void) db->sync(db, 0);
2631 if (map->map_lockfd >= 0)
2632 (void) close(map->map_lockfd);
2633 # endif /* !LOCK_ON_OPEN */
2635 # if DB_VERSION_MAJOR < 2
2636 if (db->close(db) != 0)
2637 # else /* DB_VERSION_MAJOR < 2 */
2639 ** Berkeley DB can use internal shared memory
2640 ** locking for its memory pool. Closing a map
2641 ** opened by another process will interfere
2642 ** with the shared memory and locks of the parent
2643 ** process leaving things in a bad state.
2647 ** If this map was not opened by the current
2648 ** process, do not close the map but recover
2649 ** the file descriptor.
2652 if (map->map_pid != CurrentPid)
2656 errno = db->fd(db, &fd);
2662 if ((errno = db->close(db, 0)) != 0)
2663 # endif /* DB_VERSION_MAJOR < 2 */
2664 syserr("db_map_close(%s, %s, %lx): db close failure",
2665 map->map_mname, map->map_file, map->map_mflags);
2674 static bool smdb_add_extension __P((char *, int, char *, char *));
2677 ** SMDB_ADD_EXTENSION -- Adds an extension to a file name.
2679 ** Just adds a . followed by a string to a db_name if there
2680 ** is room and the db_name does not already have that extension.
2683 ** full_name -- The final file name.
2684 ** max_full_name_len -- The max length for full_name.
2685 ** db_name -- The name of the db.
2686 ** extension -- The extension to add.
2689 ** SMDBE_OK -- Success.
2690 ** Anything else is an error. Look up more info about the
2691 ** error in the comments for the specific open() used.
2695 smdb_add_extension(full_name, max_full_name_len, db_name, extension)
2697 int max_full_name_len;
2704 if (full_name == NULL || db_name == NULL || extension == NULL)
2705 return false; /* SMDBE_INVALID_PARAMETER; */
2707 extension_len = strlen(extension);
2708 db_name_len = strlen(db_name);
2710 if (extension_len + db_name_len + 2 > max_full_name_len)
2711 return false; /* SMDBE_DB_NAME_TOO_LONG; */
2713 if (db_name_len < extension_len + 1 ||
2714 db_name[db_name_len - extension_len - 1] != '.' ||
2715 strcmp(&db_name[db_name_len - extension_len], extension) != 0)
2716 (void) sm_snprintf(full_name, max_full_name_len, "%s.%s",
2717 db_name, extension);
2719 (void) sm_strlcpy(full_name, db_name, max_full_name_len);
2725 cdb_map_open(map, mode)
2729 int fd, status, omode, smode;
2732 char buf[MAXPATHLEN];
2735 sm_dprintf("cdb_map_open(%s, %s, %d)\n",
2736 map->map_mname, map->map_file, mode);
2737 map->map_db1 = (ARBPTR_T)NULL;
2738 map->map_db2 = (ARBPTR_T)NULL;
2745 ** If a temporary file is used, then there must be some check
2746 ** that the rename() is "safe" (i.e., does not overwrite some
2747 ** "other" file created by an attacker).
2749 ** The code to add the extension and to set up safefile()
2750 ** and open() should be in a common function
2751 ** (it would be nice to re-use libsmdb?)
2754 if (!smdb_add_extension(buf, sizeof(buf), map->map_file, CDBext))
2757 if (!bitset(MF_OPTIONAL, map->map_mflags))
2758 syserr("cdb map \"%s\": map file %s name too long",
2759 map->map_mname, map->map_file);
2763 sff = SFF_ROOTOK|SFF_REGONLY;
2766 if (sm_strlcat(buf, ".tmp", sizeof buf) >= sizeof buf)
2769 if (!bitset(MF_OPTIONAL, map->map_mflags))
2770 syserr("cdb map \"%s\": map file %s name too long",
2771 map->map_mname, map->map_file);
2775 if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail))
2777 if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail))
2784 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
2787 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
2788 sff |= SFF_SAFEDIRPATH;
2789 status = safefile(buf, RunAsUid, RunAsGid, RunAsUserName, sff, smode, &st);
2792 char *prob = "unsafe";
2794 /* cannot open this map */
2795 if (status == ENOENT)
2799 sm_dprintf("\t%s map file: %s\n", prob, sm_errstring(status));
2800 if (!bitset(MF_OPTIONAL, map->map_mflags))
2801 syserr("%s map \"%s\": %s map file %s",
2802 map->map_mname, prob, buf, sm_errstring(status));
2806 if (st.st_mode == ST_MODE_NOFILE)
2807 omode |= O_CREAT|O_EXCL;
2810 omode |= O_TRUNC|O_EXLOCK;
2816 # endif /* LOCK_ON_OPEN */
2818 fd = open(buf, omode, DBMMODE);
2821 if (!bitset(MF_OPTIONAL, map->map_mflags))
2822 syserr("cdb_map_open: cannot open database %s", buf);
2827 /* make sure no baddies slipped in just before the open... */
2828 if (filechanged(buf, fd, &st))
2835 syserr("cdb_map_open(%s): file changed after open", buf);
2839 /* actually lock the opened file */
2840 if (!lockfile(fd, buf, NULL, mode == O_RDONLY ? LOCK_SH : LOCK_EX))
2841 syserr("cdb_map_open: cannot lock %s", buf);
2842 # endif /* !LOCK_ON_OPEN */
2844 /* only for aliases! */
2847 struct cdb_make *cdbmp;
2849 cdbmp = (struct cdb_make *) xalloc(sizeof(*cdbmp));
2850 status = cdb_make_start(cdbmp, fd);
2854 if (!bitset(MF_OPTIONAL, map->map_mflags))
2855 syserr("initialization of cdb map (make) failed");
2859 map->map_db2 = (ARBPTR_T)cdbmp;
2866 cdbp = (struct cdb *) xalloc(sizeof(*cdbp));
2867 status = cdb_init(cdbp, fd);
2871 if (!bitset(MF_OPTIONAL, map->map_mflags))
2872 syserr("initialization of cdb map failed");
2875 map->map_db1 = (ARBPTR_T)cdbp;
2884 cdb_map_lookup (map, name, av, statp)
2892 unsigned int klen, dlen;
2894 char key[MAXNAME+1];
2897 cdbmap = map->map_db1;
2899 sm_dprintf("cdb_map_lookup(%s, %s)\n", map->map_mname, name);
2901 klen = strlen(name);
2902 if (klen > sizeof(key) - 1)
2903 klen = sizeof(key) - 1;
2904 memmove(key, name, klen);
2907 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
2911 if (bitset(MF_TRY0NULL, map->map_mflags))
2913 st = cdb_find(cdbmap, key, klen);
2915 map->map_mflags &= ~MF_TRY1NULL;
2917 if (st != 1 && bitset(MF_TRY1NULL, map->map_mflags))
2919 st = cdb_find(cdbmap, key, klen + 1);
2921 map->map_mflags &= ~MF_TRY0NULL;
2926 syserr("cdb_map_lookup: get (%s)", name);
2931 dlen = cdb_datalen(cdbmap);
2932 data = malloc(dlen + 1);
2933 cdb_read(cdbmap, data, dlen, cdb_datapos(cdbmap));
2936 if (bitset(MF_MATCHONLY, map->map_mflags))
2937 return map_rewrite(map, name, strlen(name), NULL);
2939 return map_rewrite(map, data, dlen, av);
2943 ** CDB_MAP_STORE -- store a datum in the CDB database
2947 cdb_map_store(map, lhs, rhs)
2952 struct cdb_make *cdbmp;
2956 char keybuf[MAXNAME + 1];
2958 cdbmp = map->map_db2;
2964 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
2966 if (klen > sizeof(keybuf) - 1)
2967 klen = sizeof(keybuf) - 1;
2968 memmove(keybuf, lhs, klen);
2969 keybuf[klen] = '\0';
2974 if (bitset(MF_INCLNULL, map->map_mflags))
2981 status = cdb_make_put(cdbmp, lhs, klen, rhs, vlen, 0);
2990 struct cdb_make *cdbmp;
2994 cdbp = map->map_db1;
2998 sm_dprintf("cdb_map_close(%p)\n", (void *)cdbp);
2999 fd = cdb_fileno(cdbp);
3004 cdbmp = map->map_db2;
3007 char tmpfn[MAXPATHLEN], cdbfn[MAXPATHLEN];
3010 sm_dprintf("cdb_map_close(%p)\n", (void *)cdbmp);
3011 fd = cdb_fileno(cdbmp);
3013 /* write out the distinguished alias */
3014 /* XXX Why isn't this in a common place? */
3015 cdb_map_store(map, "@", "@");
3017 if (cdb_make_finish(cdbmp) != 0)
3018 syserr("cdb: failed to write %s", map->map_file);
3021 if (fsync(fd) == -1)
3022 syserr("cdb: fsync(%s) failed", map->map_file);
3023 if (close(fd) == -1)
3024 syserr("cdb: close(%s) failed", map->map_file);
3027 if (!smdb_add_extension(cdbfn, sizeof(cdbfn), map->map_file,
3030 syserr("cdb: add extension to %s failed",
3033 if (sm_strlcpy(tmpfn, cdbfn, sizeof tmpfn) >= sizeof tmpfn ||
3034 sm_strlcat(tmpfn, ".tmp", sizeof tmpfn) >= sizeof tmpfn)
3036 syserr("cdb: set temp filename for %s failed",
3040 sm_dprintf("rename(%s, %s)\n", tmpfn, cdbfn);
3041 if (rename(tmpfn, cdbfn) == -1)
3042 syserr("cdb: rename(%s, %s) failed", tmpfn, cdbfn);
3058 # define YPERR_BUSY 16
3062 ** NIS_MAP_OPEN -- open DBM map
3066 nis_map_open(map, mode)
3076 sm_dprintf("nis_map_open(%s, %s, %d)\n",
3077 map->map_mname, map->map_file, mode);
3080 if (mode != O_RDONLY)
3082 /* issue a pseudo-error message */
3083 errno = SM_EMAPCANTWRITE;
3087 p = strchr(map->map_file, '@');
3092 map->map_domain = p;
3095 if (*map->map_file == '\0')
3096 map->map_file = "mail.aliases";
3098 if (map->map_domain == NULL)
3100 yperr = yp_get_default_domain(&map->map_domain);
3103 if (!bitset(MF_OPTIONAL, map->map_mflags))
3104 syserr("451 4.3.5 NIS map %s specified, but NIS not running",
3110 /* check to see if this map actually exists */
3112 yperr = yp_match(map->map_domain, map->map_file, "@", 1,
3115 sm_dprintf("nis_map_open: yp_match(@, %s, %s) => %s\n",
3116 map->map_domain, map->map_file, yperr_string(yperr));
3120 if (yperr == 0 || yperr == YPERR_KEY || yperr == YPERR_BUSY)
3123 ** We ought to be calling aliaswait() here if this is an
3124 ** alias file, but powerful HP-UX NIS servers apparently
3125 ** don't insert the @:@ token into the alias map when it
3126 ** is rebuilt, so aliaswait() just hangs. I hate HP-UX.
3130 if (!bitset(MF_ALIAS, map->map_mflags) ||
3131 aliaswait(map, NULL, true))
3136 if (!bitset(MF_OPTIONAL, map->map_mflags))
3138 syserr("451 4.3.5 Cannot bind to map %s in domain %s: %s",
3139 map->map_file, map->map_domain, yperr_string(yperr));
3147 ** NIS_MAP_LOOKUP -- look up a datum in a NIS map
3152 nis_map_lookup(map, name, av, statp)
3162 char keybuf[MAXNAME + 1];
3163 char *SM_NONVOLATILE result = NULL;
3166 sm_dprintf("nis_map_lookup(%s, %s)\n",
3167 map->map_mname, name);
3169 buflen = strlen(name);
3170 if (buflen > sizeof(keybuf) - 1)
3171 buflen = sizeof(keybuf) - 1;
3172 memmove(keybuf, name, buflen);
3173 keybuf[buflen] = '\0';
3174 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
3178 if (bitset(MF_TRY0NULL, map->map_mflags))
3180 yperr = yp_match(map->map_domain, map->map_file, keybuf, buflen,
3183 map->map_mflags &= ~MF_TRY1NULL;
3185 if (yperr == YPERR_KEY && bitset(MF_TRY1NULL, map->map_mflags))
3189 yperr = yp_match(map->map_domain, map->map_file, keybuf, buflen,
3192 map->map_mflags &= ~MF_TRY0NULL;
3196 if (yperr != YPERR_KEY && yperr != YPERR_BUSY)
3197 map->map_mflags &= ~(MF_VALID|MF_OPEN);
3203 if (bitset(MF_MATCHONLY, map->map_mflags))
3204 result = map_rewrite(map, name, strlen(name), NULL);
3206 result = map_rewrite(map, vp, vsize, av);
3216 ** NIS_GETCANONNAME -- look up canonical name in NIS
3220 nis_getcanonname(name, hbsize, statp)
3229 static bool try0null = true;
3230 static bool try1null = true;
3231 static char *yp_domain = NULL;
3232 char host_record[MAXLINE];
3234 char nbuf[MAXNAME + 1];
3237 sm_dprintf("nis_getcanonname(%s)\n", name);
3239 if (sm_strlcpy(nbuf, name, sizeof(nbuf)) >= sizeof(nbuf))
3241 *statp = EX_UNAVAILABLE;
3244 (void) shorten_hostname(nbuf);
3245 keylen = strlen(nbuf);
3247 if (yp_domain == NULL)
3248 (void) yp_get_default_domain(&yp_domain);
3254 yperr = yp_match(yp_domain, "hosts.byname", nbuf, keylen,
3259 if (yperr == YPERR_KEY && try1null)
3263 yperr = yp_match(yp_domain, "hosts.byname", nbuf, keylen,
3270 if (yperr == YPERR_KEY)
3272 else if (yperr == YPERR_BUSY)
3273 *statp = EX_TEMPFAIL;
3275 *statp = EX_UNAVAILABLE;
3280 (void) sm_strlcpy(host_record, vp, sizeof(host_record));
3283 sm_dprintf("got record `%s'\n", host_record);
3284 vp = strpbrk(host_record, "#\n");
3287 if (!extract_canonname(nbuf, NULL, host_record, cbuf, sizeof(cbuf)))
3289 /* this should not happen, but.... */
3293 if (sm_strlcpy(name, cbuf, hbsize) >= hbsize)
3295 *statp = EX_UNAVAILABLE;
3306 ** This code donated by Sun Microsystems.
3311 # undef NIS /* symbol conflict in nis.h */
3312 # undef T_UNSPEC /* symbol conflict in nis.h -> ... -> sys/tiuser.h */
3313 # include <rpcsvc/nis.h>
3314 # include <rpcsvc/nislib.h>
3315 # ifndef NIS_TABLE_OBJ
3316 # define NIS_TABLE_OBJ TABLE_OBJ
3319 # define EN_col(col) zo_data.objdata_u.en_data.en_cols.en_cols_val[(col)].ec_value.ec_value_val
3320 # define COL_NAME(res,i) ((res->objects.objects_val)->TA_data.ta_cols.ta_cols_val)[i].tc_name
3321 # define COL_MAX(res) ((res->objects.objects_val)->TA_data.ta_cols.ta_cols_len)
3322 # define PARTIAL_NAME(x) ((x)[strlen(x) - 1] != '.')
3325 ** NISPLUS_MAP_OPEN -- open nisplus table
3329 nisplus_map_open(map, mode)
3333 nis_result *res = NULL;
3334 int retry_cnt, max_col, i;
3335 char qbuf[MAXLINE + NIS_MAXNAMELEN];
3338 sm_dprintf("nisplus_map_open(%s, %s, %d)\n",
3339 map->map_mname, map->map_file, mode);
3342 if (mode != O_RDONLY)
3348 if (*map->map_file == '\0')
3349 map->map_file = "mail_aliases.org_dir";
3351 if (PARTIAL_NAME(map->map_file) && map->map_domain == NULL)
3353 /* set default NISPLUS Domain to $m */
3354 map->map_domain = newstr(nisplus_default_domain());
3356 sm_dprintf("nisplus_map_open(%s): using domain %s\n",
3357 map->map_file, map->map_domain);
3359 if (!PARTIAL_NAME(map->map_file))
3361 map->map_domain = newstr("");
3362 (void) sm_strlcpy(qbuf, map->map_file, sizeof(qbuf));
3366 /* check to see if this map actually exists */
3367 (void) sm_strlcpyn(qbuf, sizeof(qbuf), 3,
3368 map->map_file, ".", map->map_domain);
3372 while (res == NULL || res->status != NIS_SUCCESS)
3374 res = nis_lookup(qbuf, FOLLOW_LINKS);
3375 switch (res->status)
3382 case NIS_NAMEUNREACHABLE:
3383 if (retry_cnt++ > 4)
3388 /* try not to overwhelm hosed server */
3392 default: /* all other nisplus errors */
3394 if (!bitset(MF_OPTIONAL, map->map_mflags))
3395 syserr("451 4.3.5 Cannot find table %s.%s: %s",
3396 map->map_file, map->map_domain,
3397 nis_sperrno(res->status));
3404 if (NIS_RES_NUMOBJ(res) != 1 ||
3405 (NIS_RES_OBJECT(res)->zo_data.zo_type != NIS_TABLE_OBJ))
3408 sm_dprintf("nisplus_map_open: %s is not a table\n", qbuf);
3410 if (!bitset(MF_OPTIONAL, map->map_mflags))
3411 syserr("451 4.3.5 %s.%s: %s is not a table",
3412 map->map_file, map->map_domain,
3413 nis_sperrno(res->status));
3418 /* default key column is column 0 */
3419 if (map->map_keycolnm == NULL)
3420 map->map_keycolnm = newstr(COL_NAME(res,0));
3422 max_col = COL_MAX(res);
3424 /* verify the key column exist */
3425 for (i = 0; i < max_col; i++)
3427 if (strcmp(map->map_keycolnm, COL_NAME(res,i)) == 0)
3433 sm_dprintf("nisplus_map_open(%s): can not find key column %s\n",
3434 map->map_file, map->map_keycolnm);
3439 /* default value column is the last column */
3440 if (map->map_valcolnm == NULL)
3442 map->map_valcolno = max_col - 1;
3446 for (i = 0; i< max_col; i++)
3448 if (strcmp(map->map_valcolnm, COL_NAME(res,i)) == 0)
3450 map->map_valcolno = i;
3456 sm_dprintf("nisplus_map_open(%s): can not find column %s\n",
3457 map->map_file, map->map_keycolnm);
3464 ** NISPLUS_MAP_LOOKUP -- look up a datum in a NISPLUS table
3468 nisplus_map_lookup(map, name, av, statp)
3478 char search_key[MAXNAME + 4];
3479 char qbuf[MAXLINE + NIS_MAXNAMELEN];
3483 sm_dprintf("nisplus_map_lookup(%s, %s)\n",
3484 map->map_mname, name);
3486 if (!bitset(MF_OPEN, map->map_mflags))
3488 if (nisplus_map_open(map, O_RDONLY))
3490 map->map_mflags |= MF_OPEN;
3491 map->map_pid = CurrentPid;
3495 *statp = EX_UNAVAILABLE;
3501 ** Copy the name to the key buffer, escaping double quote characters
3502 ** by doubling them and quoting "]" and "," to avoid having the
3503 ** NIS+ parser choke on them.
3506 skleft = sizeof(search_key) - 4;
3508 for (p = name; *p != '\0' && skleft > 0; p++)
3514 /* quote the character */
3522 /* double the quote */
3534 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
3535 makelower(search_key);
3537 /* construct the query */
3538 if (PARTIAL_NAME(map->map_file))
3539 (void) sm_snprintf(qbuf, sizeof(qbuf), "[%s=%s],%s.%s",
3540 map->map_keycolnm, search_key, map->map_file,
3543 (void) sm_snprintf(qbuf, sizeof(qbuf), "[%s=%s],%s",
3544 map->map_keycolnm, search_key, map->map_file);
3547 sm_dprintf("qbuf=%s\n", qbuf);
3548 result = nis_list(qbuf, FOLLOW_LINKS | FOLLOW_PATH, NULL, NULL);
3549 if (result->status == NIS_SUCCESS)
3554 if ((count = NIS_RES_NUMOBJ(result)) != 1)
3557 sm_syslog(LOG_WARNING, CurEnv->e_id,
3558 "%s: lookup error, expected 1 entry, got %d",
3559 map->map_file, count);
3561 /* ignore second entry */
3563 sm_dprintf("nisplus_map_lookup(%s), got %d entries, additional entries ignored\n",
3567 p = ((NIS_RES_OBJECT(result))->EN_col(map->map_valcolno));
3568 /* set the length of the result */
3573 sm_dprintf("nisplus_map_lookup(%s), found %s\n",
3575 if (bitset(MF_MATCHONLY, map->map_mflags))
3576 str = map_rewrite(map, name, strlen(name), NULL);
3578 str = map_rewrite(map, p, vsize, av);
3579 nis_freeresult(result);
3585 if (result->status == NIS_NOTFOUND)
3586 *statp = EX_NOTFOUND;
3587 else if (result->status == NIS_TRYAGAIN)
3588 *statp = EX_TEMPFAIL;
3591 *statp = EX_UNAVAILABLE;
3592 map->map_mflags &= ~(MF_VALID|MF_OPEN);
3596 sm_dprintf("nisplus_map_lookup(%s), failed\n", name);
3597 nis_freeresult(result);
3604 ** NISPLUS_GETCANONNAME -- look up canonical name in NIS+
3608 nisplus_getcanonname(name, hbsize, statp)
3617 char nbuf[MAXNAME + 1];
3618 char qbuf[MAXLINE + NIS_MAXNAMELEN];
3620 if (sm_strlcpy(nbuf, name, sizeof(nbuf)) >= sizeof(nbuf))
3622 *statp = EX_UNAVAILABLE;
3625 (void) shorten_hostname(nbuf);
3627 p = strchr(nbuf, '.');
3631 (void) sm_snprintf(qbuf, sizeof(qbuf),
3632 "[name=%s],hosts.org_dir", nbuf);
3634 else if (p[1] != '\0')
3636 /* multi token -- take only first token in nbuf */
3638 (void) sm_snprintf(qbuf, sizeof(qbuf),
3639 "[name=%s],hosts.org_dir.%s", nbuf, &p[1]);
3648 sm_dprintf("\nnisplus_getcanonname(%s), qbuf=%s\n",
3651 result = nis_list(qbuf, EXPAND_NAME|FOLLOW_LINKS|FOLLOW_PATH,
3654 if (result->status == NIS_SUCCESS)
3659 if ((count = NIS_RES_NUMOBJ(result)) != 1)
3662 sm_syslog(LOG_WARNING, CurEnv->e_id,
3663 "nisplus_getcanonname: lookup error, expected 1 entry, got %d",
3666 /* ignore second entry */
3668 sm_dprintf("nisplus_getcanonname(%s), got %d entries, all but first ignored\n",
3673 sm_dprintf("nisplus_getcanonname(%s), found in directory \"%s\"\n",
3674 name, (NIS_RES_OBJECT(result))->zo_domain);
3677 vp = ((NIS_RES_OBJECT(result))->EN_col(0));
3680 sm_dprintf("nisplus_getcanonname(%s), found %s\n",
3682 if (strchr(vp, '.') != NULL)
3688 domain = macvalue('m', CurEnv);
3692 if (hbsize > vsize + (int) strlen(domain) + 1)
3694 if (domain[0] == '\0')
3695 (void) sm_strlcpy(name, vp, hbsize);
3697 (void) sm_snprintf(name, hbsize,
3698 "%s.%s", vp, domain);
3703 nis_freeresult(result);
3708 if (result->status == NIS_NOTFOUND)
3710 else if (result->status == NIS_TRYAGAIN)
3711 *statp = EX_TEMPFAIL;
3713 *statp = EX_UNAVAILABLE;
3716 sm_dprintf("nisplus_getcanonname(%s), failed, status=%d, nsw_stat=%d\n",
3717 name, result->status, *statp);
3718 nis_freeresult(result);
3723 nisplus_default_domain()
3725 static char default_domain[MAXNAME + 1] = "";
3728 if (default_domain[0] != '\0')
3729 return default_domain;
3731 p = nis_local_directory();
3732 (void) sm_strlcpy(default_domain, p, sizeof(default_domain));
3733 return default_domain;
3736 #endif /* NISPLUS */
3742 ** LDAPMAP_DEQUOTE - helper routine for ldapmap_parseargs
3745 #if defined(LDAPMAP) || defined(PH_MAP)
3748 # define ph_map_dequote ldapmap_dequote
3751 static char *ldapmap_dequote __P((char *));
3754 ldapmap_dequote(str)
3766 /* Should probably swallow initial whitespace here */
3771 while (*p != '"' && *p != '\0')
3777 #endif /* defined(LDAPMAP) || defined(PH_MAP) */
3781 static SM_LDAP_STRUCT *LDAPDefaults = NULL;
3784 ** LDAPMAP_OPEN -- open LDAP map
3786 ** Connect to the LDAP server. Re-use existing connections since a
3787 ** single server connection to a host (with the same host, port,
3788 ** bind DN, and secret) can answer queries for multiple maps.
3792 ldapmap_open(map, mode)
3796 SM_LDAP_STRUCT *lmap;
3801 sm_dprintf("ldapmap_open(%s, %d): ", map->map_mname, mode);
3803 #if defined(SUN_EXTENSIONS) && defined(SUN_SIMPLIFIED_LDAP) && \
3804 HASLDAPGETALIASBYNAME
3805 if (VendorCode == VENDOR_SUN &&
3806 strcmp(map->map_mname, "aliases.ldap") == 0)
3810 #endif /* defined(SUN_EXTENSIONS) && defined(SUN_SIMPLIFIED_LDAP) && ... */
3814 /* sendmail doesn't have the ability to write to LDAP (yet) */
3815 if (mode != O_RDONLY)
3817 /* issue a pseudo-error message */
3818 errno = SM_EMAPCANTWRITE;
3822 lmap = (SM_LDAP_STRUCT *) map->map_db1;
3824 s = ldapmap_findconn(lmap);
3825 if (s->s_lmap != NULL)
3827 /* Already have a connection open to this LDAP server */
3828 lmap->ldap_ld = ((SM_LDAP_STRUCT *)s->s_lmap->map_db1)->ldap_ld;
3829 lmap->ldap_pid = ((SM_LDAP_STRUCT *)s->s_lmap->map_db1)->ldap_pid;
3831 /* Add this map as head of linked list */
3832 lmap->ldap_next = s->s_lmap;
3836 sm_dprintf("using cached connection\n");
3841 sm_dprintf("opening new connection\n");
3843 if (lmap->ldap_host != NULL)
3844 id = lmap->ldap_host;
3845 else if (lmap->ldap_uri != NULL)
3846 id = lmap->ldap_uri;
3852 extern MAPCLASS NullMapClass;
3854 /* debug mode: don't actually open an LDAP connection */
3855 map->map_orgclass = map->map_class;
3856 map->map_class = &NullMapClass;
3857 map->map_mflags |= MF_OPEN;
3858 map->map_pid = CurrentPid;
3862 /* No connection yet, connect */
3863 if (!sm_ldap_start(map->map_mname, lmap))
3865 if (errno == ETIMEDOUT)
3868 sm_syslog(LOG_NOTICE, CurEnv->e_id,
3869 "timeout connecting to LDAP server %.100s",
3873 if (!bitset(MF_OPTIONAL, map->map_mflags))
3875 if (bitset(MF_NODEFER, map->map_mflags))
3877 syserr("%s failed to %s in map %s",
3879 "ldap_init/ldap_bind",
3883 id, map->map_mname);
3887 syserr("451 4.3.5 %s failed to %s in map %s",
3889 "ldap_init/ldap_bind",
3893 id, map->map_mname);
3899 /* Save connection for reuse */
3905 ** LDAPMAP_CLOSE -- close ldap map
3912 SM_LDAP_STRUCT *lmap;
3916 sm_dprintf("ldapmap_close(%s)\n", map->map_mname);
3918 lmap = (SM_LDAP_STRUCT *) map->map_db1;
3920 /* Check if already closed */
3921 if (lmap->ldap_ld == NULL)
3924 /* Close the LDAP connection */
3925 sm_ldap_close(lmap);
3927 /* Mark all the maps that share the connection as closed */
3928 s = ldapmap_findconn(lmap);
3930 while (s->s_lmap != NULL)
3932 MAP *smap = s->s_lmap;
3934 if (tTd(38, 2) && smap != map)
3935 sm_dprintf("ldapmap_close(%s): closed %s (shared LDAP connection)\n",
3936 map->map_mname, smap->map_mname);
3937 smap->map_mflags &= ~(MF_OPEN|MF_WRITABLE);
3938 lmap = (SM_LDAP_STRUCT *) smap->map_db1;
3939 lmap->ldap_ld = NULL;
3940 s->s_lmap = lmap->ldap_next;
3941 lmap->ldap_next = NULL;
3947 ** SUNET_ID_HASH -- Convert a string to its Sunet_id canonical form
3948 ** This only makes sense at Stanford University.
3961 if (isascii(*p) && (islower(*p) || isdigit(*p)))
3966 else if (isascii(*p) && isupper(*p))
3968 *p_last = tolower(*p);
3973 if (*p_last != '\0')
3977 # define SM_CONVERT_ID(str) sunet_id_hash(str)
3978 # else /* SUNET_ID */
3979 # define SM_CONVERT_ID(str) makelower(str)
3980 # endif /* SUNET_ID */
3983 ** LDAPMAP_LOOKUP -- look up a datum in a LDAP map
3987 ldapmap_lookup(map, name, av, statp)
4000 char *result = NULL;
4002 SM_LDAP_STRUCT *lmap = NULL;
4003 char *argv[SM_LDAP_ARGS];
4004 char keybuf[MAXKEY];
4005 #if SM_LDAP_ARGS != MAX_MAP_ARGS
4006 # ERROR _SM_LDAP_ARGS must be the same as _MAX_MAP_ARGS
4009 #if defined(SUN_EXTENSIONS) && defined(SUN_SIMPLIFIED_LDAP) && \
4010 HASLDAPGETALIASBYNAME
4011 if (VendorCode == VENDOR_SUN &&
4012 strcmp(map->map_mname, "aliases.ldap") == 0)
4015 #if defined(GETLDAPALIASBYNAME_VERSION) && (GETLDAPALIASBYNAME_VERSION >= 2)
4016 extern char *__getldapaliasbyname();
4019 answer = __getldapaliasbyname(name, &rc);
4021 char answer[MAXNAME + 1];
4023 rc = __getldapaliasbyname(name, answer, sizeof(answer));
4028 sm_dprintf("getldapaliasbyname(%.100s) failed, errno=%d\n",
4030 *statp = EX_NOTFOUND;
4035 sm_dprintf("getldapaliasbyname(%.100s) => %s\n", name,
4037 if (bitset(MF_MATCHONLY, map->map_mflags))
4038 result = map_rewrite(map, name, strlen(name), NULL);
4040 result = map_rewrite(map, answer, strlen(answer), av);
4041 #if defined(GETLDAPALIASBYNAME_VERSION) && (GETLDAPALIASBYNAME_VERSION >= 2)
4046 #endif /* defined(SUN_EXTENSIONS) && defined(SUN_SIMPLIFIED_LDAP) && ... */
4048 /* Get ldap struct pointer from map */
4049 lmap = (SM_LDAP_STRUCT *) map->map_db1;
4050 sm_ldap_setopts(lmap->ldap_ld, lmap);
4052 if (lmap->ldap_multi_args)
4054 SM_REQUIRE(av != NULL);
4055 memset(argv, '\0', sizeof(argv));
4056 for (i = 0; i < SM_LDAP_ARGS && av[i] != NULL; i++)
4058 argv[i] = sm_strdup(av[i]);
4059 if (argv[i] == NULL)
4064 for (j = 0; j < i && argv[j] != NULL; j++)
4066 *statp = EX_TEMPFAIL;
4071 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
4072 SM_CONVERT_ID(av[i]);
4077 (void) sm_strlcpy(keybuf, name, sizeof(keybuf));
4079 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
4080 SM_CONVERT_ID(keybuf);
4085 if (lmap->ldap_multi_args)
4087 sm_dprintf("ldapmap_lookup(%s, argv)\n",
4089 for (i = 0; i < SM_LDAP_ARGS; i++)
4091 sm_dprintf(" argv[%d] = %s\n", i,
4092 argv[i] == NULL ? "NULL" : argv[i]);
4097 sm_dprintf("ldapmap_lookup(%s, %s)\n",
4098 map->map_mname, name);
4102 if (lmap->ldap_multi_args)
4104 msgid = sm_ldap_search_m(lmap, argv);
4106 /* free the argv array and its content, no longer needed */
4107 for (i = 0; i < SM_LDAP_ARGS && argv[i] != NULL; i++)
4111 msgid = sm_ldap_search(lmap, keybuf);
4112 if (msgid == SM_LDAP_ERR)
4114 errno = sm_ldap_geterrno(lmap->ldap_ld) + E_LDAPBASE;
4116 if (!bitset(MF_OPTIONAL, map->map_mflags))
4119 ** Do not include keybuf as this error may be shown
4123 if (bitset(MF_NODEFER, map->map_mflags))
4124 syserr("Error in ldap_search in map %s",
4127 syserr("451 4.3.5 Error in ldap_search in map %s",
4130 *statp = EX_TEMPFAIL;
4131 switch (save_errno - E_LDAPBASE)
4133 # ifdef LDAP_SERVER_DOWN
4134 case LDAP_SERVER_DOWN:
4137 case LDAP_UNAVAILABLE:
4138 /* server disappeared, try reopen on next search */
4145 #if SM_LDAP_ERROR_ON_MISSING_ARGS
4146 else if (msgid == SM_LDAP_ERR_ARG_MISS)
4148 if (bitset(MF_NODEFER, map->map_mflags))
4149 syserr("Error in ldap_search in map %s, too few arguments",
4152 syserr("554 5.3.5 Error in ldap_search in map %s, too few arguments",
4157 #endif /* SM_LDAP_ERROR_ON_MISSING_ARGS */
4159 *statp = EX_NOTFOUND;
4163 if (bitset(MF_SINGLEMATCH, map->map_mflags))
4164 flags |= SM_LDAP_SINGLEMATCH;
4165 if (bitset(MF_MATCHONLY, map->map_mflags))
4166 flags |= SM_LDAP_MATCHONLY;
4167 # if _FFR_LDAP_SINGLEDN
4168 if (bitset(MF_SINGLEDN, map->map_mflags))
4169 flags |= SM_LDAP_SINGLEDN;
4172 /* Create an rpool for search related memory usage */
4173 rpool = sm_rpool_new_x(NULL);
4176 *statp = sm_ldap_results(lmap, msgid, flags, map->map_coldelim,
4177 rpool, &p, &plen, &psize, NULL);
4180 /* Copy result so rpool can be freed */
4181 if (*statp == EX_OK && p != NULL)
4183 sm_rpool_free(rpool);
4185 /* need to restart LDAP connection? */
4186 if (*statp == EX_RESTART)
4188 *statp = EX_TEMPFAIL;
4193 if (*statp != EX_OK && *statp != EX_NOTFOUND)
4195 if (!bitset(MF_OPTIONAL, map->map_mflags))
4197 if (bitset(MF_NODEFER, map->map_mflags))
4198 syserr("Error getting LDAP results, map=%s, name=%s",
4199 map->map_mname, name);
4201 syserr("451 4.3.5 Error getting LDAP results, map=%s, name=%s",
4202 map->map_mname, name);
4208 /* Did we match anything? */
4209 if (vp == NULL && !bitset(MF_MATCHONLY, map->map_mflags))
4212 if (*statp == EX_OK)
4215 sm_syslog(LOG_INFO, CurEnv->e_id,
4216 "ldap=%s, %.100s=>%s", map->map_mname, name,
4217 vp == NULL ? "<NULL>" : vp);
4218 if (bitset(MF_MATCHONLY, map->map_mflags))
4219 result = map_rewrite(map, name, strlen(name), NULL);
4222 /* vp != NULL according to test above */
4223 result = map_rewrite(map, vp, strlen(vp), av);
4226 sm_free(vp); /* XXX */
4232 ** LDAPMAP_FINDCONN -- find an LDAP connection to the server
4234 ** Cache LDAP connections based on the host, port, bind DN,
4235 ** secret, and PID so we don't have multiple connections open to
4236 ** the same server for different maps. Need a separate connection
4237 ** per PID since a parent process may close the map before the
4238 ** child is done with it.
4241 ** lmap -- LDAP map information
4244 ** Symbol table entry for the LDAP connection.
4248 ldapmap_findconn(lmap)
4249 SM_LDAP_STRUCT *lmap;
4254 STAB *SM_NONVOLATILE s = NULL;
4256 if (lmap->ldap_host != NULL)
4257 id = lmap->ldap_host;
4258 else if (lmap->ldap_uri != NULL)
4259 id = lmap->ldap_uri;
4263 format = "%s%c%d%c%d%c%s%c%s%d";
4264 nbuf = sm_stringf_x(format,
4271 (lmap->ldap_binddn == NULL ? ""
4272 : lmap->ldap_binddn),
4274 (lmap->ldap_secret == NULL ? ""
4275 : lmap->ldap_secret),
4278 s = stab(nbuf, ST_LMAP, ST_ENTER);
4285 ** LDAPMAP_PARSEARGS -- parse ldap map definition args.
4288 static struct lamvalues LDAPAuthMethods[] =
4290 { "none", LDAP_AUTH_NONE },
4291 { "simple", LDAP_AUTH_SIMPLE },
4292 # ifdef LDAP_AUTH_KRBV4
4293 { "krbv4", LDAP_AUTH_KRBV4 },
4298 static struct ladvalues LDAPAliasDereference[] =
4300 { "never", LDAP_DEREF_NEVER },
4301 { "always", LDAP_DEREF_ALWAYS },
4302 { "search", LDAP_DEREF_SEARCHING },
4303 { "find", LDAP_DEREF_FINDING },
4307 static struct lssvalues LDAPSearchScope[] =
4309 { "base", LDAP_SCOPE_BASE },
4310 { "one", LDAP_SCOPE_ONELEVEL },
4311 { "sub", LDAP_SCOPE_SUBTREE },
4316 ldapmap_parseargs(map, args)
4320 bool secretread = true;
4321 bool attrssetup = false;
4323 register char *p = args;
4324 SM_LDAP_STRUCT *lmap;
4325 struct lamvalues *lam;
4326 struct ladvalues *lad;
4327 struct lssvalues *lss;
4328 char ldapfilt[MAXLINE];
4329 char m_tmp[MAXPATHLEN + LDAPMAP_MAX_PASSWD];
4331 /* Get ldap struct pointer from map */
4332 lmap = (SM_LDAP_STRUCT *) map->map_db1;
4334 /* Check if setting the initial LDAP defaults */
4335 if (lmap == NULL || lmap != LDAPDefaults)
4337 /* We need to alloc an SM_LDAP_STRUCT struct */
4338 lmap = (SM_LDAP_STRUCT *) xalloc(sizeof(*lmap));
4339 if (LDAPDefaults == NULL)
4340 sm_ldap_clear(lmap);
4342 STRUCTCOPY(*LDAPDefaults, *lmap);
4345 /* there is no check whether there is really an argument */
4346 map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL;
4347 map->map_spacesub = SpaceSub; /* default value */
4349 /* Check if setting up an alias or file class LDAP map */
4350 if (bitset(MF_ALIAS, map->map_mflags))
4352 /* Comma separate if used as an alias file */
4353 map->map_coldelim = ',';
4358 char jbuf[MAXHOSTNAMELEN];
4359 char lcbuf[MAXLINE];
4362 expand("\201j", jbuf, sizeof(jbuf), &BlankEnvelope);
4363 if (jbuf[0] == '\0')
4365 (void) sm_strlcpy(jbuf, "localhost",
4369 lc = macvalue(macid("{sendmailMTACluster}"), CurEnv);
4374 expand(lc, lcbuf, sizeof(lcbuf), CurEnv);
4378 n = sm_snprintf(ldapfilt, sizeof(ldapfilt),
4379 "(&(objectClass=sendmailMTAAliasObject)(sendmailMTAAliasGrouping=aliases)(|(sendmailMTACluster=%s)(sendmailMTAHost=%s))(sendmailMTAKey=%%0))",
4381 if (n >= sizeof(ldapfilt))
4383 syserr("%s: Default LDAP string too long",
4388 /* default args for an alias LDAP entry */
4389 lmap->ldap_filter = ldapfilt;
4390 lmap->ldap_attr[0] = "objectClass";
4391 lmap->ldap_attr_type[0] = SM_LDAP_ATTR_OBJCLASS;
4392 lmap->ldap_attr_needobjclass[0] = NULL;
4393 lmap->ldap_attr[1] = "sendmailMTAAliasValue";
4394 lmap->ldap_attr_type[1] = SM_LDAP_ATTR_NORMAL;
4395 lmap->ldap_attr_needobjclass[1] = NULL;
4396 lmap->ldap_attr[2] = "sendmailMTAAliasSearch";
4397 lmap->ldap_attr_type[2] = SM_LDAP_ATTR_FILTER;
4398 lmap->ldap_attr_needobjclass[2] = "sendmailMTAMapObject";
4399 lmap->ldap_attr[3] = "sendmailMTAAliasURL";
4400 lmap->ldap_attr_type[3] = SM_LDAP_ATTR_URL;
4401 lmap->ldap_attr_needobjclass[3] = "sendmailMTAMapObject";
4402 lmap->ldap_attr[4] = NULL;
4403 lmap->ldap_attr_type[4] = SM_LDAP_ATTR_NONE;
4404 lmap->ldap_attr_needobjclass[4] = NULL;
4408 else if (bitset(MF_FILECLASS, map->map_mflags))
4410 /* Space separate if used as a file class file */
4411 map->map_coldelim = ' ';
4414 # if LDAP_NETWORK_TIMEOUT
4415 if (0 == lmap->ldap_networktmo)
4416 lmap->ldap_networktmo = (LDAP_NETWORK_TIMEOUT > 1)
4417 ? LDAP_NETWORK_TIMEOUT : 60;
4422 while (SM_ISSPACE(*p))
4429 map->map_mflags |= MF_APPEND;
4437 map->map_mflags |= MF_DEFER;
4441 map->map_mflags |= MF_NOFOLDCASE;
4445 map->map_mflags |= MF_MATCHONLY;
4449 map->map_mflags |= MF_INCLNULL;
4450 map->map_mflags &= ~MF_TRY0NULL;
4454 map->map_mflags &= ~MF_TRY1NULL;
4458 map->map_mflags |= MF_OPTIONAL;
4462 map->map_mflags |= MF_KEEPQUOTES;
4466 map->map_spacesub = *++p;
4470 map->map_tapp = ++p;
4474 map->map_mflags |= MF_NODEFER;
4479 map->map_coldelim = *p;
4485 map->map_coldelim = '\n';
4489 map->map_coldelim = '\t';
4493 map->map_coldelim = '\\';
4498 /* Start of ldapmap specific args */
4500 map->map_mflags |= MF_SINGLEMATCH;
4503 # if _FFR_LDAP_SINGLEDN
4505 map->map_mflags |= MF_SINGLEDN;
4507 # endif /* _FFR_LDAP_SINGLEDN */
4509 case 'b': /* search base */
4510 while (isascii(*++p) && isspace(*p))
4512 lmap->ldap_base = p;
4515 # if LDAP_NETWORK_TIMEOUT
4516 case 'c': /* network (connect) timeout */
4517 while (isascii(*++p) && isspace(*p))
4519 lmap->ldap_networktmo = atoi(p);
4521 # endif /* LDAP_NETWORK_TIMEOUT */
4523 case 'd': /* Dn to bind to server as */
4524 while (isascii(*++p) && isspace(*p))
4526 lmap->ldap_binddn = p;
4529 case 'H': /* Use LDAP URI */
4531 syserr("Must compile with -DUSE_LDAP_INIT to use LDAP URIs (-H) in map %s",
4534 # else /* !USE_LDAP_INIT */
4535 if (lmap->ldap_host != NULL)
4537 syserr("Can not specify both an LDAP host and an LDAP URI in map %s",
4541 while (isascii(*++p) && isspace(*p))
4545 # endif /* !USE_LDAP_INIT */
4547 case 'h': /* ldap host */
4548 while (isascii(*++p) && isspace(*p))
4550 if (lmap->ldap_uri != NULL)
4552 syserr("Can not specify both an LDAP host and an LDAP URI in map %s",
4556 lmap->ldap_host = p;
4560 lmap->ldap_multi_args = true;
4563 case 'k': /* search field */
4564 while (isascii(*++p) && isspace(*p))
4566 lmap->ldap_filter = p;
4569 case 'l': /* time limit */
4570 while (isascii(*++p) && isspace(*p))
4572 lmap->ldap_timelimit = atoi(p);
4573 lmap->ldap_timeout.tv_sec = lmap->ldap_timelimit;
4576 case 'M': /* Method for binding */
4577 while (isascii(*++p) && isspace(*p))
4580 if (sm_strncasecmp(p, "LDAP_AUTH_", 10) == 0)
4583 for (lam = LDAPAuthMethods;
4584 lam != NULL && lam->lam_name != NULL; lam++)
4586 if (sm_strncasecmp(p, lam->lam_name,
4587 strlen(lam->lam_name)) == 0)
4590 if (lam->lam_name != NULL)
4591 lmap->ldap_method = lam->lam_code;
4594 /* bad config line */
4595 if (!bitset(MCF_OPTFILE,
4596 map->map_class->map_cflags))
4600 if ((ptr = strchr(p, ' ')) != NULL)
4602 syserr("Method for binding must be [none|simple|krbv4] (not %s) in map %s",
4611 case 'n': /* retrieve attribute names only */
4612 lmap->ldap_attrsonly = LDAPMAP_TRUE;
4616 ** This is a string that is dependent on the
4617 ** method used defined by 'M'.
4620 case 'P': /* Secret password for binding */
4621 while (isascii(*++p) && isspace(*p))
4623 lmap->ldap_secret = p;
4627 case 'p': /* ldap port */
4628 while (isascii(*++p) && isspace(*p))
4630 lmap->ldap_port = atoi(p);
4633 /* args stolen from ldapsearch.c */
4634 case 'R': /* don't auto chase referrals */
4635 # ifdef LDAP_REFERRALS
4636 lmap->ldap_options &= ~LDAP_OPT_REFERRALS;
4638 syserr("compile with -DLDAP_REFERRALS for referral support");
4639 # endif /* LDAP_REFERRALS */
4642 case 'r': /* alias dereferencing */
4643 while (isascii(*++p) && isspace(*p))
4646 if (sm_strncasecmp(p, "LDAP_DEREF_", 11) == 0)
4649 for (lad = LDAPAliasDereference;
4650 lad != NULL && lad->lad_name != NULL; lad++)
4652 if (sm_strncasecmp(p, lad->lad_name,
4653 strlen(lad->lad_name)) == 0)
4656 if (lad->lad_name != NULL)
4657 lmap->ldap_deref = lad->lad_code;
4660 /* bad config line */
4661 if (!bitset(MCF_OPTFILE,
4662 map->map_class->map_cflags))
4666 if ((ptr = strchr(p, ' ')) != NULL)
4668 syserr("Deref must be [never|always|search|find] (not %s) in map %s",
4677 case 's': /* search scope */
4678 while (isascii(*++p) && isspace(*p))
4681 if (sm_strncasecmp(p, "LDAP_SCOPE_", 11) == 0)
4684 for (lss = LDAPSearchScope;
4685 lss != NULL && lss->lss_name != NULL; lss++)
4687 if (sm_strncasecmp(p, lss->lss_name,
4688 strlen(lss->lss_name)) == 0)
4691 if (lss->lss_name != NULL)
4692 lmap->ldap_scope = lss->lss_code;
4695 /* bad config line */
4696 if (!bitset(MCF_OPTFILE,
4697 map->map_class->map_cflags))
4701 if ((ptr = strchr(p, ' ')) != NULL)
4703 syserr("Scope must be [base|one|sub] (not %s) in map %s",
4714 lmap->ldap_attrsep = *p;
4720 lmap->ldap_attrsep = '\n';
4724 lmap->ldap_attrsep = '\t';
4728 lmap->ldap_attrsep = '\\';
4733 case 'v': /* attr to return */
4734 while (isascii(*++p) && isspace(*p))
4736 lmap->ldap_attr[0] = p;
4737 lmap->ldap_attr[1] = NULL;
4741 /* -w should be for passwd, -P should be for version */
4742 while (isascii(*++p) && isspace(*p))
4744 lmap->ldap_version = atoi(p);
4745 # ifdef LDAP_VERSION_MAX
4746 if (lmap->ldap_version > LDAP_VERSION_MAX)
4748 syserr("LDAP version %d exceeds max of %d in map %s",
4749 lmap->ldap_version, LDAP_VERSION_MAX,
4753 # endif /* LDAP_VERSION_MAX */
4754 # ifdef LDAP_VERSION_MIN
4755 if (lmap->ldap_version < LDAP_VERSION_MIN)
4757 syserr("LDAP version %d is lower than min of %d in map %s",
4758 lmap->ldap_version, LDAP_VERSION_MIN,
4762 # endif /* LDAP_VERSION_MIN */
4766 # if _FFR_SM_LDAP_DBG
4767 while (isascii(*++p) && isspace(*p))
4769 lmap->ldap_debug = atoi(p);
4774 while (isascii(*++p) && isspace(*p))
4776 lmap->ldap_sizelimit = atoi(p);
4780 syserr("Illegal option %c map %s", *p, map->map_mname);
4784 /* need to account for quoted strings here */
4785 while (*p != '\0' && !(SM_ISSPACE(*p)))
4789 while (*++p != '"' && *p != '\0')
4802 if (map->map_app != NULL)
4803 map->map_app = newstr(ldapmap_dequote(map->map_app));
4804 if (map->map_tapp != NULL)
4805 map->map_tapp = newstr(ldapmap_dequote(map->map_tapp));
4808 ** We need to swallow up all the stuff into a struct
4809 ** and dump it into map->map_dbptr1
4812 if (lmap->ldap_host != NULL &&
4813 (LDAPDefaults == NULL ||
4814 LDAPDefaults == lmap ||
4815 LDAPDefaults->ldap_host != lmap->ldap_host))
4816 lmap->ldap_host = newstr(ldapmap_dequote(lmap->ldap_host));
4817 map->map_domain = lmap->ldap_host;
4819 if (lmap->ldap_uri != NULL &&
4820 (LDAPDefaults == NULL ||
4821 LDAPDefaults == lmap ||
4822 LDAPDefaults->ldap_uri != lmap->ldap_uri))
4823 lmap->ldap_uri = newstr(ldapmap_dequote(lmap->ldap_uri));
4824 map->map_domain = lmap->ldap_uri;
4826 if (lmap->ldap_binddn != NULL &&
4827 (LDAPDefaults == NULL ||
4828 LDAPDefaults == lmap ||
4829 LDAPDefaults->ldap_binddn != lmap->ldap_binddn))
4830 lmap->ldap_binddn = newstr(ldapmap_dequote(lmap->ldap_binddn));
4832 if (lmap->ldap_secret != NULL &&
4833 (LDAPDefaults == NULL ||
4834 LDAPDefaults == lmap ||
4835 LDAPDefaults->ldap_secret != lmap->ldap_secret))
4838 long sff = SFF_OPENASROOT|SFF_ROOTOK|SFF_NOWLINK|SFF_NOWWFILES|SFF_NOGWFILES;
4840 if (DontLockReadFiles)
4843 /* need to use method to map secret to passwd string */
4844 switch (lmap->ldap_method)
4846 case LDAP_AUTH_NONE:
4850 case LDAP_AUTH_SIMPLE:
4853 ** Secret is the name of a file with
4854 ** the first line as the password.
4857 /* Already read in the secret? */
4861 sfd = safefopen(ldapmap_dequote(lmap->ldap_secret),
4865 syserr("LDAP map: cannot open secret %s",
4866 ldapmap_dequote(lmap->ldap_secret));
4869 lmap->ldap_secret = sfgets(m_tmp, sizeof(m_tmp),
4870 sfd, TimeOuts.to_fileopen,
4871 "ldapmap_parseargs");
4872 (void) sm_io_close(sfd, SM_TIME_DEFAULT);
4873 if (strlen(m_tmp) > LDAPMAP_MAX_PASSWD)
4875 syserr("LDAP map: secret in %s too long",
4876 ldapmap_dequote(lmap->ldap_secret));
4879 if (lmap->ldap_secret != NULL &&
4883 if (m_tmp[strlen(m_tmp) - 1] == '\n')
4884 m_tmp[strlen(m_tmp) - 1] = '\0';
4886 lmap->ldap_secret = m_tmp;
4890 # ifdef LDAP_AUTH_KRBV4
4891 case LDAP_AUTH_KRBV4:
4894 ** Secret is where the ticket file is
4898 (void) sm_snprintf(m_tmp, sizeof(m_tmp),
4900 ldapmap_dequote(lmap->ldap_secret));
4901 lmap->ldap_secret = m_tmp;
4903 # endif /* LDAP_AUTH_KRBV4 */
4905 default: /* Should NEVER get here */
4906 syserr("LDAP map: Illegal value in lmap method");
4913 if (lmap->ldap_secret != NULL &&
4914 (LDAPDefaults == NULL ||
4915 LDAPDefaults == lmap ||
4916 LDAPDefaults->ldap_secret != lmap->ldap_secret))
4917 lmap->ldap_secret = newstr(ldapmap_dequote(lmap->ldap_secret));
4919 if (lmap->ldap_base != NULL &&
4920 (LDAPDefaults == NULL ||
4921 LDAPDefaults == lmap ||
4922 LDAPDefaults->ldap_base != lmap->ldap_base))
4923 lmap->ldap_base = newstr(ldapmap_dequote(lmap->ldap_base));
4926 ** Save the server from extra work. If request is for a single
4927 ** match, tell the server to only return enough records to
4928 ** determine if there is a single match or not. This can not
4929 ** be one since the server would only return one and we wouldn't
4930 ** know if there were others available.
4933 if (bitset(MF_SINGLEMATCH, map->map_mflags))
4934 lmap->ldap_sizelimit = 2;
4936 /* If setting defaults, don't process ldap_filter and ldap_attr */
4937 if (lmap == LDAPDefaults)
4940 if (lmap->ldap_filter != NULL)
4941 lmap->ldap_filter = newstr(ldapmap_dequote(lmap->ldap_filter));
4944 if (!bitset(MCF_OPTFILE, map->map_class->map_cflags))
4946 syserr("No filter given in map %s", map->map_mname);
4951 if (!attrssetup && lmap->ldap_attr[0] != NULL)
4953 bool recurse = false;
4954 bool normalseen = false;
4957 p = ldapmap_dequote(lmap->ldap_attr[0]);
4958 lmap->ldap_attr[0] = NULL;
4960 /* Prime the attr list with the objectClass attribute */
4961 lmap->ldap_attr[i] = "objectClass";
4962 lmap->ldap_attr_type[i] = SM_LDAP_ATTR_OBJCLASS;
4963 lmap->ldap_attr_needobjclass[i] = NULL;
4970 while (SM_ISSPACE(*p))
4979 if (i >= LDAPMAP_MAX_ATTR)
4981 syserr("Too many return attributes in %s (max %d)",
4982 map->map_mname, LDAPMAP_MAX_ATTR);
4992 type = strchr(v, ':');
4996 needobjclass = strchr(type, ':');
4997 if (needobjclass != NULL)
4998 *needobjclass++ = '\0';
5002 needobjclass = NULL;
5007 /* allow override on "objectClass" type */
5008 if (sm_strcasecmp(v, "objectClass") == 0 &&
5009 lmap->ldap_attr_type[0] == SM_LDAP_ATTR_OBJCLASS)
5016 ** Don't add something to attribute
5020 for (j = 1; j < i; j++)
5022 if (sm_strcasecmp(v, lmap->ldap_attr[j]) == 0)
5024 syserr("Duplicate attribute (%s) in %s",
5030 lmap->ldap_attr[use] = newstr(v);
5031 if (needobjclass != NULL &&
5032 *needobjclass != '\0' &&
5033 *needobjclass != '*')
5035 lmap->ldap_attr_needobjclass[use] = newstr(needobjclass);
5039 lmap->ldap_attr_needobjclass[use] = NULL;
5044 if (type != NULL && *type != '\0')
5046 if (sm_strcasecmp(type, "dn") == 0)
5049 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_DN;
5051 else if (sm_strcasecmp(type, "filter") == 0)
5054 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_FILTER;
5056 else if (sm_strcasecmp(type, "url") == 0)
5059 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_URL;
5061 else if (sm_strcasecmp(type, "normal") == 0)
5063 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_NORMAL;
5068 syserr("Unknown attribute type (%s) in %s",
5069 type, map->map_mname);
5075 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_NORMAL;
5081 lmap->ldap_attr[i] = NULL;
5083 /* Set in case needed in future code */
5086 if (recurse && !normalseen)
5088 syserr("LDAP recursion requested in %s but no returnable attribute given",
5092 if (recurse && lmap->ldap_attrsonly == LDAPMAP_TRUE)
5094 syserr("LDAP recursion requested in %s can not be used with -n",
5099 map->map_db1 = (ARBPTR_T) lmap;
5104 ** LDAPMAP_SET_DEFAULTS -- Read default map spec from LDAPDefaults in .cf
5107 ** spec -- map argument string from LDAPDefaults option
5114 ldapmap_set_defaults(spec)
5120 /* Allocate and set the default values */
5121 if (LDAPDefaults == NULL)
5122 LDAPDefaults = (SM_LDAP_STRUCT *) xalloc(sizeof(*LDAPDefaults));
5123 sm_ldap_clear(LDAPDefaults);
5125 memset(&map, '\0', sizeof(map));
5127 /* look up the class */
5128 class = stab("ldap", ST_MAPCLASS, ST_FIND);
5131 syserr("readcf: LDAPDefaultSpec: class ldap not available");
5134 map.map_class = &class->s_mapclass;
5135 map.map_db1 = (ARBPTR_T) LDAPDefaults;
5136 map.map_mname = "O LDAPDefaultSpec";
5138 (void) ldapmap_parseargs(&map, spec);
5140 /* These should never be set in LDAPDefaults */
5141 if (map.map_mflags != (MF_TRY0NULL|MF_TRY1NULL) ||
5142 map.map_spacesub != SpaceSub ||
5143 map.map_app != NULL ||
5144 map.map_tapp != NULL)
5146 syserr("readcf: option LDAPDefaultSpec: Do not set non-LDAP specific flags");
5147 SM_FREE(map.map_app);
5148 SM_FREE(map.map_tapp);
5151 if (LDAPDefaults->ldap_filter != NULL)
5153 syserr("readcf: option LDAPDefaultSpec: Do not set the LDAP search filter");
5155 /* don't free, it isn't malloc'ed in parseargs */
5156 LDAPDefaults->ldap_filter = NULL;
5159 if (LDAPDefaults->ldap_attr[0] != NULL)
5161 syserr("readcf: option LDAPDefaultSpec: Do not set the requested LDAP attributes");
5162 /* don't free, they aren't malloc'ed in parseargs */
5163 LDAPDefaults->ldap_attr[0] = NULL;
5166 #endif /* LDAPMAP */
5174 ** Support for the CCSO Nameserver (ph/qi).
5175 ** This code is intended to replace the so-called "ph mailer".
5176 ** Contributed by Mark D. Roth. Contact him for support.
5179 /* what version of the ph map code we're running */
5180 static char phmap_id[128];
5182 /* sendmail version for phmap id string */
5183 extern const char Version[];
5185 /* assume we're using nph-1.2.x if not specified */
5186 # ifndef NPH_VERSION
5187 # define NPH_VERSION 10200
5190 /* compatibility for versions older than nph-1.2.0 */
5191 # if NPH_VERSION < 10200
5192 # define PH_OPEN_ROUNDROBIN PH_ROUNDROBIN
5193 # define PH_OPEN_DONTID PH_DONTID
5194 # define PH_CLOSE_FAST PH_FASTCLOSE
5195 # define PH_ERR_DATAERR PH_DATAERR
5196 # define PH_ERR_NOMATCH PH_NOMATCH
5197 # endif /* NPH_VERSION < 10200 */
5200 ** PH_MAP_PARSEARGS -- parse ph map definition args.
5204 ph_map_parseargs(map, args)
5209 register char *p = args;
5210 PH_MAP_STRUCT *pmap = NULL;
5212 /* initialize version string */
5213 (void) sm_snprintf(phmap_id, sizeof(phmap_id),
5214 "sendmail-%s phmap-20010529 libphclient-%s",
5215 Version, libphclient_version);
5217 pmap = (PH_MAP_STRUCT *) xalloc(sizeof(*pmap));
5220 pmap->ph_servers = NULL;
5221 pmap->ph_field_list = NULL;
5223 pmap->ph_timeout = 0;
5224 pmap->ph_fastclose = 0;
5226 map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL;
5229 while (SM_ISSPACE(*p))
5236 map->map_mflags |= MF_INCLNULL;
5237 map->map_mflags &= ~MF_TRY0NULL;
5241 map->map_mflags &= ~MF_TRY1NULL;
5245 map->map_mflags |= MF_OPTIONAL;
5249 map->map_mflags |= MF_NOFOLDCASE;
5253 map->map_mflags |= MF_MATCHONLY;
5257 map->map_mflags |= MF_APPEND;
5261 map->map_mflags |= MF_KEEPQUOTES;
5265 map->map_mflags |= MF_NODEFER;
5273 map->map_tapp = ++p;
5277 while (isascii(*++p) && isspace(*p))
5279 pmap->ph_timeout = atoi(p);
5283 map->map_spacesub = *++p;
5287 map->map_mflags |= MF_DEFER;
5290 case 'h': /* PH server list */
5291 while (isascii(*++p) && isspace(*p))
5293 pmap->ph_servers = p;
5296 case 'k': /* fields to search for */
5297 while (isascii(*++p) && isspace(*p))
5299 pmap->ph_field_list = p;
5303 syserr("ph_map_parseargs: unknown option -%c", *p);
5306 /* try to account for quoted strings */
5307 done = SM_ISSPACE(*p);
5308 while (*p != '\0' && !done)
5312 while (*++p != '"' && *p != '\0')
5319 done = SM_ISSPACE(*p);
5326 if (map->map_app != NULL)
5327 map->map_app = newstr(ph_map_dequote(map->map_app));
5328 if (map->map_tapp != NULL)
5329 map->map_tapp = newstr(ph_map_dequote(map->map_tapp));
5331 if (pmap->ph_field_list != NULL)
5332 pmap->ph_field_list = newstr(ph_map_dequote(pmap->ph_field_list));
5334 if (pmap->ph_servers != NULL)
5335 pmap->ph_servers = newstr(ph_map_dequote(pmap->ph_servers));
5338 syserr("ph_map_parseargs: -h flag is required");
5342 map->map_db1 = (ARBPTR_T) pmap;
5347 ** PH_MAP_CLOSE -- close the connection to the ph server
5354 PH_MAP_STRUCT *pmap;
5356 pmap = (PH_MAP_STRUCT *)map->map_db1;
5358 sm_dprintf("ph_map_close(%s): pmap->ph_fastclose=%d\n",
5359 map->map_mname, pmap->ph_fastclose);
5362 if (pmap->ph != NULL)
5364 ph_set_sendhook(pmap->ph, NULL);
5365 ph_set_recvhook(pmap->ph, NULL);
5366 ph_close(pmap->ph, pmap->ph_fastclose);
5369 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE);
5372 static jmp_buf PHTimeout;
5380 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
5381 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
5386 longjmp(PHTimeout, 1);
5390 #if NPH_VERSION >= 10200
5391 ph_map_send_debug(appdata, text)
5394 ph_map_send_debug(text)
5399 sm_syslog(LOG_NOTICE, CurEnv->e_id,
5400 "ph_map_send_debug: ==> %s", text);
5402 sm_dprintf("ph_map_send_debug: ==> %s\n", text);
5406 #if NPH_VERSION >= 10200
5407 ph_map_recv_debug(appdata, text)
5410 ph_map_recv_debug(text)
5415 sm_syslog(LOG_NOTICE, CurEnv->e_id,
5416 "ph_map_recv_debug: <== %s", text);
5418 sm_dprintf("ph_map_recv_debug: <== %s\n", text);
5422 ** PH_MAP_OPEN -- sub for opening PH map
5425 ph_map_open(map, mode)
5429 PH_MAP_STRUCT *pmap;
5430 register SM_EVENT *ev = NULL;
5432 char *hostlist, *host;
5435 sm_dprintf("ph_map_open(%s)\n", map->map_mname);
5438 if (mode != O_RDONLY)
5440 /* issue a pseudo-error message */
5441 errno = SM_EMAPCANTWRITE;
5445 if (CurEnv != NULL && CurEnv->e_sendmode == SM_DEFER &&
5446 bitset(MF_DEFER, map->map_mflags))
5449 sm_dprintf("ph_map_open(%s) => DEFERRED\n",
5453 ** Unset MF_DEFER here so that map_lookup() returns
5454 ** a temporary failure using the bogus map and
5455 ** map->map_tapp instead of the default permanent error.
5458 map->map_mflags &= ~MF_DEFER;
5462 pmap = (PH_MAP_STRUCT *)map->map_db1;
5463 pmap->ph_fastclose = 0; /* refresh field for reopen */
5465 /* try each host in the list */
5466 hostlist = newstr(pmap->ph_servers);
5467 for (host = strtok(hostlist, " ");
5469 host = strtok(NULL, " "))
5472 if (pmap->ph_timeout != 0)
5474 if (setjmp(PHTimeout) != 0)
5478 sm_syslog(LOG_NOTICE, CurEnv->e_id,
5479 "timeout connecting to PH server %.100s",
5482 goto ph_map_open_abort;
5484 ev = sm_setevent(pmap->ph_timeout, ph_timeout, 0);
5487 /* open connection to server */
5488 if (ph_open(&(pmap->ph), host,
5489 PH_OPEN_ROUNDROBIN|PH_OPEN_DONTID,
5490 ph_map_send_debug, ph_map_recv_debug
5491 #if NPH_VERSION >= 10200
5495 && ph_id(pmap->ph, phmap_id) == 0)
5499 sm_free(hostlist); /* XXX */
5507 pmap->ph_fastclose = PH_CLOSE_FAST;
5512 if (bitset(MF_NODEFER, map->map_mflags))
5516 syserr("ph_map_open: %s: cannot connect to PH server",
5519 else if (!bitset(MF_OPTIONAL, map->map_mflags) && LogLevel > 1)
5520 sm_syslog(LOG_NOTICE, CurEnv->e_id,
5521 "ph_map_open: %s: cannot connect to PH server",
5523 sm_free(hostlist); /* XXX */
5528 ** PH_MAP_LOOKUP -- look up key from ph server
5532 ph_map_lookup(map, key, args, pstat)
5538 int i, save_errno = 0;
5539 register SM_EVENT *ev = NULL;
5540 PH_MAP_STRUCT *pmap;
5543 pmap = (PH_MAP_STRUCT *)map->map_db1;
5548 if (pmap->ph_timeout != 0)
5550 if (setjmp(PHTimeout) != 0)
5554 sm_syslog(LOG_NOTICE, CurEnv->e_id,
5555 "timeout during PH lookup of %.100s",
5558 *pstat = EX_TEMPFAIL;
5559 goto ph_map_lookup_abort;
5561 ev = sm_setevent(pmap->ph_timeout, ph_timeout, 0);
5564 /* perform lookup */
5565 i = ph_email_resolve(pmap->ph, key, pmap->ph_field_list, &value);
5567 *pstat = EX_TEMPFAIL;
5568 else if (i == PH_ERR_NOMATCH || i == PH_ERR_DATAERR)
5569 *pstat = EX_UNAVAILABLE;
5571 ph_map_lookup_abort:
5576 ** Close the connection if the timer popped
5577 ** or we got a temporary PH error
5580 if (*pstat == EX_TEMPFAIL)
5583 pmap->ph_fastclose = PH_CLOSE_FAST;
5588 if (*pstat == EX_OK)
5591 sm_dprintf("ph_map_lookup: %s => %s\n", key, value);
5593 if (bitset(MF_MATCHONLY, map->map_mflags))
5594 return map_rewrite(map, key, strlen(key), NULL);
5596 return map_rewrite(map, value, strlen(value), args);
5607 #define map_prio map_lockfd /* overload field */
5610 ** SYSLOG_MAP_PARSEARGS -- check for priority level to syslog messages.
5614 syslog_map_parseargs(map, args)
5619 char *priority = NULL;
5621 /* there is no check whether there is really an argument */
5624 while (SM_ISSPACE(*p))
5631 map->map_mflags |= MF_DEFER;
5636 map->map_spacesub = *++p;
5642 while (*++p != '\0' && SM_ISSPACE(*p))
5647 while (*p != '\0' && !(SM_ISSPACE(*p)))
5654 syserr("Illegal option %c map syslog", *p);
5659 if (priority == NULL)
5660 map->map_prio = LOG_INFO;
5663 if (sm_strncasecmp("LOG_", priority, 4) == 0)
5667 if (sm_strcasecmp("EMERG", priority) == 0)
5668 map->map_prio = LOG_EMERG;
5670 #endif /* LOG_EMERG */
5672 if (sm_strcasecmp("ALERT", priority) == 0)
5673 map->map_prio = LOG_ALERT;
5675 #endif /* LOG_ALERT */
5677 if (sm_strcasecmp("CRIT", priority) == 0)
5678 map->map_prio = LOG_CRIT;
5680 #endif /* LOG_CRIT */
5682 if (sm_strcasecmp("ERR", priority) == 0)
5683 map->map_prio = LOG_ERR;
5685 #endif /* LOG_ERR */
5687 if (sm_strcasecmp("WARNING", priority) == 0)
5688 map->map_prio = LOG_WARNING;
5690 #endif /* LOG_WARNING */
5692 if (sm_strcasecmp("NOTICE", priority) == 0)
5693 map->map_prio = LOG_NOTICE;
5695 #endif /* LOG_NOTICE */
5697 if (sm_strcasecmp("INFO", priority) == 0)
5698 map->map_prio = LOG_INFO;
5700 #endif /* LOG_INFO */
5702 if (sm_strcasecmp("DEBUG", priority) == 0)
5703 map->map_prio = LOG_DEBUG;
5705 #endif /* LOG_DEBUG */
5707 syserr("syslog_map_parseargs: Unknown priority %s",
5716 ** SYSLOG_MAP_LOOKUP -- rewrite and syslog message. Always return empty string
5720 syslog_map_lookup(map, string, args, statp)
5726 char *ptr = map_rewrite(map, string, strlen(string), args);
5731 sm_dprintf("syslog_map_lookup(%s (priority %d): %s\n",
5732 map->map_mname, map->map_prio, ptr);
5734 sm_syslog(map->map_prio, CurEnv->e_id, "%s", ptr);
5741 #if _FFR_DPRINTF_MAP
5746 #define map_dbg_level map_lockfd /* overload field */
5749 ** DPRINTF_MAP_PARSEARGS -- check for priority level to dprintf messages.
5753 dprintf_map_parseargs(map, args)
5758 char *dbg_level = NULL;
5760 /* there is no check whether there is really an argument */
5763 while (SM_ISSPACE(*p))
5770 map->map_mflags |= MF_DEFER;
5775 map->map_spacesub = *++p;
5781 while (*++p != '\0' && SM_ISSPACE(*p))
5786 while (*p != '\0' && !(SM_ISSPACE(*p)))
5793 syserr("Illegal option %c map dprintf", *p);
5798 if (dbg_level == NULL)
5799 map->map_dbg_level = 0;
5802 if (!(isascii(*dbg_level) && isdigit(*dbg_level)))
5804 syserr("dprintf map \"%s\", file %s: -d should specify a number, not %s",
5805 map->map_mname, map->map_file,
5809 map->map_dbg_level = atoi(dbg_level);
5815 ** DPRINTF_MAP_LOOKUP -- rewrite and print message. Always return empty string
5819 dprintf_map_lookup(map, string, args, statp)
5825 char *ptr = map_rewrite(map, string, strlen(string), args);
5827 if (ptr != NULL && tTd(85, map->map_dbg_level))
5828 sm_dprintf("%s\n", ptr);
5832 #endif /* _FFR_DPRINTF_MAP */
5841 hes_map_open(map, mode)
5846 sm_dprintf("hes_map_open(%s, %s, %d)\n",
5847 map->map_mname, map->map_file, mode);
5849 if (mode != O_RDONLY)
5851 /* issue a pseudo-error message */
5852 errno = SM_EMAPCANTWRITE;
5857 if (HesiodContext != NULL || hesiod_init(&HesiodContext) == 0)
5860 if (!bitset(MF_OPTIONAL, map->map_mflags))
5861 syserr("451 4.3.5 cannot initialize Hesiod map (%s)",
5862 sm_errstring(errno));
5864 # else /* HESIOD_INIT */
5865 if (hes_error() == HES_ER_UNINIT)
5867 switch (hes_error())
5870 case HES_ER_NOTFOUND:
5874 if (!bitset(MF_OPTIONAL, map->map_mflags))
5875 syserr("451 4.3.5 cannot initialize Hesiod map (%d)", hes_error());
5878 # endif /* HESIOD_INIT */
5882 hes_map_lookup(map, name, av, statp)
5891 sm_dprintf("hes_map_lookup(%s, %s)\n", map->map_file, name);
5893 if (name[0] == '\\')
5901 if (nl < sizeof(nbuf) - 1)
5904 np = xalloc(strlen(name) + 2);
5906 (void) sm_strlcpy(&np[1], name, (sizeof(nbuf)) - 1);
5908 hp = hesiod_resolve(HesiodContext, np, map->map_file);
5910 hp = hes_resolve(np, map->map_file);
5911 # endif /* HESIOD_INIT */
5914 sm_free(np); /* XXX */
5920 hp = hesiod_resolve(HesiodContext, name, map->map_file);
5922 hp = hes_resolve(name, map->map_file);
5923 # endif /* HESIOD_INIT */
5926 if (hp == NULL || *hp == NULL)
5931 *statp = EX_NOTFOUND;
5934 *statp = EX_TEMPFAIL;
5939 *statp = EX_UNAVAILABLE;
5943 hesiod_free_list(HesiodContext, hp);
5946 # else /* HESIOD_INIT */
5947 if (hp == NULL || hp[0] == NULL)
5949 switch (hes_error())
5955 case HES_ER_NOTFOUND:
5956 *statp = EX_NOTFOUND;
5960 *statp = EX_UNAVAILABLE;
5964 *statp = EX_TEMPFAIL;
5969 # endif /* HESIOD_INIT */
5971 if (bitset(MF_MATCHONLY, map->map_mflags))
5972 return map_rewrite(map, name, strlen(name), NULL);
5974 return map_rewrite(map, hp[0], strlen(hp[0]), av);
5978 ** HES_MAP_CLOSE -- free the Hesiod context
5986 sm_dprintf("hes_map_close(%s)\n", map->map_file);
5989 /* Free the hesiod context */
5990 if (HesiodContext != NULL)
5992 hesiod_end(HesiodContext);
5993 HesiodContext = NULL;
5995 # endif /* HESIOD_INIT */
6000 ** NeXT NETINFO Modules
6005 # define NETINFO_DEFAULT_DIR "/aliases"
6006 # define NETINFO_DEFAULT_PROPERTY "members"
6009 ** NI_MAP_OPEN -- open NetInfo Aliases
6013 ni_map_open(map, mode)
6018 sm_dprintf("ni_map_open(%s, %s, %d)\n",
6019 map->map_mname, map->map_file, mode);
6022 if (*map->map_file == '\0')
6023 map->map_file = NETINFO_DEFAULT_DIR;
6025 if (map->map_valcolnm == NULL)
6026 map->map_valcolnm = NETINFO_DEFAULT_PROPERTY;
6028 if (map->map_coldelim == '\0')
6030 if (bitset(MF_ALIAS, map->map_mflags))
6031 map->map_coldelim = ',';
6032 else if (bitset(MF_FILECLASS, map->map_mflags))
6033 map->map_coldelim = ' ';
6040 ** NI_MAP_LOOKUP -- look up a datum in NetInfo
6044 ni_map_lookup(map, name, av, statp)
6054 sm_dprintf("ni_map_lookup(%s, %s)\n", map->map_mname, name);
6056 propval = ni_propval(map->map_file, map->map_keycolnm, name,
6057 map->map_valcolnm, map->map_coldelim);
6059 if (propval == NULL)
6063 if (bitset(MF_MATCHONLY, map->map_mflags))
6064 res = map_rewrite(map, name, strlen(name), NULL);
6066 res = map_rewrite(map, propval, strlen(propval), av);
6075 ni_getcanonname(name, hbsize, statp)
6082 char nbuf[MAXNAME + 1];
6085 sm_dprintf("ni_getcanonname(%s)\n", name);
6087 if (sm_strlcpy(nbuf, name, sizeof(nbuf)) >= sizeof(nbuf))
6089 *statp = EX_UNAVAILABLE;
6092 (void) shorten_hostname(nbuf);
6094 /* we only accept single token search key */
6095 if (strchr(nbuf, '.'))
6102 vptr = ni_propval("/machines", NULL, nbuf, "name", '\n');
6110 /* Only want the first machine name */
6111 if ((ptr = strchr(vptr, '\n')) != NULL)
6114 if (sm_strlcpy(name, vptr, hbsize) >= hbsize)
6117 *statp = EX_UNAVAILABLE;
6124 #endif /* NETINFO */
6126 ** TEXT (unindexed text file) Modules
6128 ** This code donated by Sun Microsystems.
6131 #define map_sff map_lockfd /* overload field */
6135 ** TEXT_MAP_OPEN -- open text table
6139 text_map_open(map, mode)
6147 sm_dprintf("text_map_open(%s, %s, %d)\n",
6148 map->map_mname, map->map_file, mode);
6151 if (mode != O_RDONLY)
6157 if (*map->map_file == '\0')
6159 syserr("text map \"%s\": file name required",
6164 if (map->map_file[0] != '/')
6166 syserr("text map \"%s\": file name must be fully qualified",
6171 sff = SFF_ROOTOK|SFF_REGONLY;
6172 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
6174 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
6175 sff |= SFF_SAFEDIRPATH;
6176 if ((i = safefile(map->map_file, RunAsUid, RunAsGid, RunAsUserName,
6177 sff, S_IRUSR, NULL)) != 0)
6179 int save_errno = errno;
6181 /* cannot open this map */
6183 sm_dprintf("\tunsafe map file: %d\n", i);
6185 if (!bitset(MF_OPTIONAL, map->map_mflags))
6186 syserr("text map \"%s\": unsafe map file %s",
6187 map->map_mname, map->map_file);
6191 if (map->map_keycolnm == NULL)
6192 map->map_keycolno = 0;
6195 if (!(isascii(*map->map_keycolnm) && isdigit(*map->map_keycolnm)))
6197 syserr("text map \"%s\", file %s: -k should specify a number, not %s",
6198 map->map_mname, map->map_file,
6202 map->map_keycolno = atoi(map->map_keycolnm);
6205 if (map->map_valcolnm == NULL)
6206 map->map_valcolno = 0;
6209 if (!(isascii(*map->map_valcolnm) && isdigit(*map->map_valcolnm)))
6211 syserr("text map \"%s\", file %s: -v should specify a number, not %s",
6212 map->map_mname, map->map_file,
6216 map->map_valcolno = atoi(map->map_valcolnm);
6221 sm_dprintf("text_map_open(%s, %s): delimiter = ",
6222 map->map_mname, map->map_file);
6223 if (map->map_coldelim == '\0')
6224 sm_dprintf("(white space)\n");
6226 sm_dprintf("%c\n", map->map_coldelim);
6235 ** TEXT_MAP_LOOKUP -- look up a datum in a TEXT table
6239 text_map_lookup(map, name, av, statp)
6252 long sff = map->map_sff;
6253 char search_key[MAXNAME + 1];
6254 char linebuf[MAXLINE];
6255 char buf[MAXNAME + 1];
6259 sm_dprintf("text_map_lookup(%s, %s)\n", map->map_mname, name);
6261 buflen = strlen(name);
6262 if (buflen > sizeof(search_key) - 1)
6263 buflen = sizeof(search_key) - 1; /* XXX just cut if off? */
6264 memmove(search_key, name, buflen);
6265 search_key[buflen] = '\0';
6266 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
6267 makelower(search_key);
6269 f = safefopen(map->map_file, O_RDONLY, FileMode, sff);
6272 map->map_mflags &= ~(MF_VALID|MF_OPEN);
6273 *statp = EX_UNAVAILABLE;
6276 key_idx = map->map_keycolno;
6277 delim = map->map_coldelim;
6278 while (sm_io_fgets(f, SM_TIME_DEFAULT,
6279 linebuf, sizeof(linebuf)) >= 0)
6283 /* skip comment line */
6284 if (linebuf[0] == '#')
6286 p = strchr(linebuf, '\n');
6289 p = get_column(linebuf, key_idx, delim, buf, sizeof(buf));
6290 if (p != NULL && sm_strcasecmp(search_key, p) == 0)
6296 (void) sm_io_close(f, SM_TIME_DEFAULT);
6299 *statp = EX_NOTFOUND;
6302 vp = get_column(linebuf, map->map_valcolno, delim, buf, sizeof(buf));
6305 *statp = EX_NOTFOUND;
6310 if (bitset(MF_MATCHONLY, map->map_mflags))
6311 return map_rewrite(map, name, strlen(name), NULL);
6313 return map_rewrite(map, vp, vsize, av);
6317 ** TEXT_GETCANONNAME -- look up canonical name in hosts file
6321 text_getcanonname(name, hbsize, statp)
6329 char linebuf[MAXLINE];
6330 char cbuf[MAXNAME + 1];
6331 char nbuf[MAXNAME + 1];
6334 sm_dprintf("text_getcanonname(%s)\n", name);
6336 if (sm_strlcpy(nbuf, name, sizeof(nbuf)) >= sizeof(nbuf))
6338 *statp = EX_UNAVAILABLE;
6341 dot = shorten_hostname(nbuf);
6343 f = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, HostsFile, SM_IO_RDONLY,
6347 *statp = EX_UNAVAILABLE;
6352 sm_io_fgets(f, SM_TIME_DEFAULT,
6353 linebuf, sizeof(linebuf)) >= 0)
6355 char *p = strpbrk(linebuf, "#\n");
6359 if (linebuf[0] != '\0')
6360 found = extract_canonname(nbuf, dot, linebuf,
6361 cbuf, sizeof(cbuf));
6363 (void) sm_io_close(f, SM_TIME_DEFAULT);
6370 if (sm_strlcpy(name, cbuf, hbsize) >= hbsize)
6372 *statp = EX_UNAVAILABLE;
6379 ** STAB (Symbol Table) Modules
6384 ** STAB_MAP_LOOKUP -- look up alias in symbol table
6389 stab_map_lookup(map, name, av, pstat)
6398 sm_dprintf("stab_lookup(%s, %s)\n",
6399 map->map_mname, name);
6401 s = stab(name, ST_ALIAS, ST_FIND);
6404 if (bitset(MF_MATCHONLY, map->map_mflags))
6405 return map_rewrite(map, name, strlen(name), NULL);
6407 return map_rewrite(map, s->s_alias, strlen(s->s_alias), av);
6411 ** STAB_MAP_STORE -- store in symtab (actually using during init, not rebuild)
6415 stab_map_store(map, lhs, rhs)
6422 s = stab(lhs, ST_ALIAS, ST_ENTER);
6423 s->s_alias = newstr(rhs);
6428 ** STAB_MAP_OPEN -- initialize (reads data file)
6430 ** This is a weird case -- it is only intended as a fallback for
6431 ** aliases. For this reason, opens for write (only during a
6432 ** "newaliases") always fails, and opens for read open the
6433 ** actual underlying text file instead of the database.
6437 stab_map_open(map, mode)
6446 sm_dprintf("stab_map_open(%s, %s, %d)\n",
6447 map->map_mname, map->map_file, mode);
6450 if (mode != O_RDONLY)
6456 sff = SFF_ROOTOK|SFF_REGONLY;
6457 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
6459 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
6460 sff |= SFF_SAFEDIRPATH;
6461 af = safefopen(map->map_file, O_RDONLY, 0444, sff);
6464 readaliases(map, af, false, false);
6466 if (fstat(sm_io_getinfo(af, SM_IO_WHAT_FD, NULL), &st) >= 0)
6467 map->map_mtime = st.st_mtime;
6468 (void) sm_io_close(af, SM_TIME_DEFAULT);
6475 ** Tries several types. For back compatibility of aliases.
6480 ** IMPL_MAP_LOOKUP -- lookup in best open database
6484 impl_map_lookup(map, name, av, pstat)
6491 sm_dprintf("impl_map_lookup(%s, %s)\n",
6492 map->map_mname, name);
6495 if (bitset(MF_IMPL_HASH, map->map_mflags))
6496 return db_map_lookup(map, name, av, pstat);
6499 if (bitset(MF_IMPL_NDBM, map->map_mflags))
6500 return ndbm_map_lookup(map, name, av, pstat);
6503 if (bitset(MF_IMPL_CDB, map->map_mflags))
6504 return cdb_map_lookup(map, name, av, pstat);
6506 return stab_map_lookup(map, name, av, pstat);
6510 ** IMPL_MAP_STORE -- store in open databases
6514 impl_map_store(map, lhs, rhs)
6520 sm_dprintf("impl_map_store(%s, %s, %s)\n",
6521 map->map_mname, lhs, rhs);
6523 if (bitset(MF_IMPL_HASH, map->map_mflags))
6524 db_map_store(map, lhs, rhs);
6527 if (bitset(MF_IMPL_NDBM, map->map_mflags))
6528 ndbm_map_store(map, lhs, rhs);
6531 if (bitset(MF_IMPL_CDB, map->map_mflags))
6532 cdb_map_store(map, lhs, rhs);
6534 stab_map_store(map, lhs, rhs);
6538 ** IMPL_MAP_OPEN -- implicit database open
6542 impl_map_open(map, mode)
6549 sm_dprintf("impl_map_open(%s, %s, %d)\n",
6550 map->map_mname, map->map_file, mode);
6553 wasopt = bitset(MF_OPTIONAL, map->map_mflags);
6555 /* suppress error msgs */
6556 map->map_mflags |= MF_OPTIONAL;
6558 map->map_mflags |= MF_IMPL_HASH;
6559 if (hash_map_open(map, mode))
6561 # ifdef NDBM_YP_COMPAT
6562 if (mode == O_RDONLY || strstr(map->map_file, "/yp/") == NULL)
6567 map->map_mflags &= ~MF_IMPL_HASH;
6570 map->map_mflags |= MF_IMPL_NDBM;
6571 if (ndbm_map_open(map, mode))
6574 map->map_mflags &= ~MF_IMPL_NDBM;
6578 map->map_mflags |= MF_IMPL_CDB;
6579 if (cdb_map_open(map, mode))
6582 map->map_mflags &= ~MF_IMPL_CDB;
6585 if (!bitset(MF_ALIAS, map->map_mflags))
6587 #if NEWDB || NDBM || CDB
6589 message("WARNING: cannot open alias database %s%s",
6591 mode == O_RDONLY ? "; reading text version" : "");
6593 if (mode != O_RDONLY)
6594 usrerr("Cannot rebuild aliases: no database format defined");
6597 if (mode == O_RDONLY && stab_map_open(map, mode))
6602 map->map_mflags &= ~MF_OPTIONAL;
6607 map->map_mflags &= ~MF_OPTIONAL;
6613 ** IMPL_MAP_CLOSE -- close any open database(s)
6621 sm_dprintf("impl_map_close(%s, %s, %lx)\n",
6622 map->map_mname, map->map_file, map->map_mflags);
6624 if (bitset(MF_IMPL_HASH, map->map_mflags))
6627 map->map_mflags &= ~MF_IMPL_HASH;
6632 if (bitset(MF_IMPL_NDBM, map->map_mflags))
6634 ndbm_map_close(map);
6635 map->map_mflags &= ~MF_IMPL_NDBM;
6639 if (bitset(MF_IMPL_CDB, map->map_mflags))
6642 map->map_mflags &= ~MF_IMPL_CDB;
6650 ** Provides access to the system password file.
6654 ** USER_MAP_OPEN -- open user map
6656 ** Really just binds field names to field numbers.
6660 user_map_open(map, mode)
6665 sm_dprintf("user_map_open(%s, %d)\n",
6666 map->map_mname, mode);
6669 if (mode != O_RDONLY)
6671 /* issue a pseudo-error message */
6672 errno = SM_EMAPCANTWRITE;
6675 if (map->map_valcolnm == NULL)
6678 else if (sm_strcasecmp(map->map_valcolnm, "name") == 0)
6679 map->map_valcolno = 1;
6680 else if (sm_strcasecmp(map->map_valcolnm, "passwd") == 0)
6681 map->map_valcolno = 2;
6682 else if (sm_strcasecmp(map->map_valcolnm, "uid") == 0)
6683 map->map_valcolno = 3;
6684 else if (sm_strcasecmp(map->map_valcolnm, "gid") == 0)
6685 map->map_valcolno = 4;
6686 else if (sm_strcasecmp(map->map_valcolnm, "gecos") == 0)
6687 map->map_valcolno = 5;
6688 else if (sm_strcasecmp(map->map_valcolnm, "dir") == 0)
6689 map->map_valcolno = 6;
6690 else if (sm_strcasecmp(map->map_valcolnm, "shell") == 0)
6691 map->map_valcolno = 7;
6694 syserr("User map %s: unknown column name %s",
6695 map->map_mname, map->map_valcolnm);
6703 ** USER_MAP_LOOKUP -- look up a user in the passwd file.
6708 user_map_lookup(map, key, av, statp)
6718 sm_dprintf("user_map_lookup(%s, %s)\n",
6719 map->map_mname, key);
6721 *statp = finduser(key, &fuzzy, &user);
6722 if (*statp != EX_OK)
6724 if (bitset(MF_MATCHONLY, map->map_mflags))
6725 return map_rewrite(map, key, strlen(key), NULL);
6731 switch (map->map_valcolno)
6735 rwval = user.mbdb_name;
6739 rwval = "x"; /* passwd no longer supported */
6743 (void) sm_snprintf(buf, sizeof(buf), "%d",
6744 (int) user.mbdb_uid);
6749 (void) sm_snprintf(buf, sizeof(buf), "%d",
6750 (int) user.mbdb_gid);
6755 rwval = user.mbdb_fullname;
6759 rwval = user.mbdb_homedir;
6763 rwval = user.mbdb_shell;
6766 syserr("user_map %s: bogus field %d",
6767 map->map_mname, map->map_valcolno);
6770 return map_rewrite(map, rwval, strlen(rwval), av);
6774 ** Program map type.
6776 ** This provides access to arbitrary programs. It should be used
6777 ** only very sparingly, since there is no way to bound the cost
6778 ** of invoking an arbitrary program.
6782 prog_map_lookup(map, name, av, statp)
6795 char *argv[MAXPV + 1];
6799 sm_dprintf("prog_map_lookup(%s, %s) %s\n",
6800 map->map_mname, name, map->map_file);
6803 argv[i++] = map->map_file;
6804 if (map->map_rebuild != NULL)
6806 (void) sm_strlcpy(buf, map->map_rebuild, sizeof(buf));
6807 for (p = strtok(buf, " \t"); p != NULL; p = strtok(NULL, " \t"))
6818 sm_dprintf("prog_open:");
6819 for (i = 0; argv[i] != NULL; i++)
6820 sm_dprintf(" %s", argv[i]);
6823 (void) sm_blocksignal(SIGCHLD);
6824 pid = prog_open(argv, &fd, CurEnv);
6827 if (!bitset(MF_OPTIONAL, map->map_mflags))
6828 syserr("prog_map_lookup(%s) failed (%s) -- closing",
6829 map->map_mname, sm_errstring(errno));
6830 else if (tTd(38, 9))
6831 sm_dprintf("prog_map_lookup(%s) failed (%s) -- closing",
6832 map->map_mname, sm_errstring(errno));
6833 map->map_mflags &= ~(MF_VALID|MF_OPEN);
6837 i = read(fd, buf, sizeof(buf) - 1);
6840 syserr("prog_map_lookup(%s): read error %s",
6841 map->map_mname, sm_errstring(errno));
6847 sm_dprintf("prog_map_lookup(%s): empty answer\n",
6854 p = strchr(buf, '\n');
6858 /* collect the return value */
6859 if (bitset(MF_MATCHONLY, map->map_mflags))
6860 rval = map_rewrite(map, name, strlen(name), NULL);
6862 rval = map_rewrite(map, buf, strlen(buf), av);
6864 /* now flush any additional output */
6865 while ((i = read(fd, buf, sizeof(buf))) > 0)
6869 /* wait for the process to terminate */
6871 status = waitfor(pid);
6873 (void) sm_releasesignal(SIGCHLD);
6878 syserr("prog_map_lookup(%s): wait error %s",
6879 map->map_mname, sm_errstring(errno));
6880 *statp = EX_SOFTWARE;
6883 else if (WIFEXITED(status))
6885 if ((*statp = WEXITSTATUS(status)) != EX_OK)
6890 syserr("prog_map_lookup(%s): child died on signal %d",
6891 map->map_mname, status);
6892 *statp = EX_UNAVAILABLE;
6898 ** Sequenced map type.
6900 ** Tries each map in order until something matches, much like
6901 ** implicit. Stores go to the first map in the list that can
6904 ** This is slightly unusual in that there are two interfaces.
6905 ** The "sequence" interface lets you stack maps arbitrarily.
6906 ** The "switch" interface builds a sequence map by looking
6907 ** at a system-dependent configuration file such as
6908 ** /etc/nsswitch.conf on Solaris or /etc/svc.conf on Ultrix.
6910 ** We don't need an explicit open, since all maps are
6911 ** opened on demand.
6915 ** SEQ_MAP_PARSE -- Sequenced map parsing
6919 seq_map_parse(map, ap)
6926 sm_dprintf("seq_map_parse(%s, %s)\n", map->map_mname, ap);
6933 /* find beginning of map name */
6934 while (SM_ISSPACE(*ap))
6937 (isascii(*p) && isalnum(*p)) || *p == '_' || *p == '.';
6942 while (*p != '\0' && (!isascii(*p) || !isalnum(*p)))
6949 s = stab(ap, ST_MAP, ST_FIND);
6952 syserr("Sequence map %s: unknown member map %s",
6953 map->map_mname, ap);
6955 else if (maxmap >= MAXMAPSTACK)
6957 syserr("Sequence map %s: too many member maps (%d max)",
6958 map->map_mname, MAXMAPSTACK);
6961 else if (maxmap < MAXMAPSTACK)
6963 map->map_stack[maxmap++] = &s->s_map;
6971 ** SWITCH_MAP_OPEN -- open a switched map
6973 ** This looks at the system-dependent configuration and builds
6974 ** a sequence map that does the same thing.
6976 ** Every system must define a switch_map_find routine in conf.c
6977 ** that will return the list of service types associated with a
6978 ** given service class.
6982 switch_map_open(map, mode)
6988 char *maptype[MAXMAPSTACK];
6991 sm_dprintf("switch_map_open(%s, %s, %d)\n",
6992 map->map_mname, map->map_file, mode);
6995 nmaps = switch_map_find(map->map_file, maptype, map->map_return);
6998 sm_dprintf("\tswitch_map_find => %d\n", nmaps);
6999 for (mapno = 0; mapno < nmaps; mapno++)
7000 sm_dprintf("\t\t%s\n", maptype[mapno]);
7002 if (nmaps <= 0 || nmaps > MAXMAPSTACK)
7005 for (mapno = 0; mapno < nmaps; mapno++)
7008 char nbuf[MAXNAME + 1];
7010 if (maptype[mapno] == NULL)
7012 (void) sm_strlcpyn(nbuf, sizeof(nbuf), 3,
7013 map->map_mname, ".", maptype[mapno]);
7014 s = stab(nbuf, ST_MAP, ST_FIND);
7017 syserr("Switch map %s: unknown member map %s",
7018 map->map_mname, nbuf);
7022 map->map_stack[mapno] = &s->s_map;
7024 sm_dprintf("\tmap_stack[%d] = %s:%s\n",
7026 s->s_map.map_class->map_cname,
7035 ** SEQ_MAP_CLOSE -- close all underlying maps
7045 sm_dprintf("seq_map_close(%s)\n", map->map_mname);
7047 for (mapno = 0; mapno < MAXMAPSTACK; mapno++)
7049 MAP *mm = map->map_stack[mapno];
7051 if (mm == NULL || !bitset(MF_OPEN, mm->map_mflags))
7053 mm->map_mflags |= MF_CLOSING;
7054 mm->map_class->map_close(mm);
7055 mm->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
7061 ** SEQ_MAP_LOOKUP -- sequenced map lookup
7065 seq_map_lookup(map, key, args, pstat)
7073 bool tempfail = false;
7076 sm_dprintf("seq_map_lookup(%s, %s)\n", map->map_mname, key);
7078 for (mapno = 0; mapno < MAXMAPSTACK; mapbit <<= 1, mapno++)
7080 MAP *mm = map->map_stack[mapno];
7085 if (!bitset(MF_OPEN, mm->map_mflags) &&
7088 if (bitset(mapbit, map->map_return[MA_UNAVAIL]))
7090 *pstat = EX_UNAVAILABLE;
7096 rv = mm->map_class->map_lookup(mm, key, args, pstat);
7099 if (*pstat == EX_TEMPFAIL)
7101 if (bitset(mapbit, map->map_return[MA_TRYAGAIN]))
7105 else if (bitset(mapbit, map->map_return[MA_NOTFOUND]))
7109 *pstat = EX_TEMPFAIL;
7110 else if (*pstat == EX_OK)
7111 *pstat = EX_NOTFOUND;
7116 ** SEQ_MAP_STORE -- sequenced map store
7120 seq_map_store(map, key, val)
7128 sm_dprintf("seq_map_store(%s, %s, %s)\n",
7129 map->map_mname, key, val);
7131 for (mapno = 0; mapno < MAXMAPSTACK; mapno++)
7133 MAP *mm = map->map_stack[mapno];
7135 if (mm == NULL || !bitset(MF_WRITABLE, mm->map_mflags))
7138 mm->map_class->map_store(mm, key, val);
7141 syserr("seq_map_store(%s, %s, %s): no writable map",
7142 map->map_mname, key, val);
7150 null_map_open(map, mode)
7166 null_map_lookup(map, key, args, pstat)
7172 *pstat = EX_NOTFOUND;
7178 null_map_store(map, key, val)
7186 MAPCLASS NullMapClass =
7188 "null-map", NULL, 0,
7189 NULL, null_map_lookup, null_map_store,
7190 null_map_open, null_map_close,
7198 bogus_map_lookup(map, key, args, pstat)
7204 *pstat = EX_TEMPFAIL;
7208 MAPCLASS BogusMapClass =
7210 "bogus-map", NULL, 0,
7211 NULL, bogus_map_lookup, null_map_store,
7212 null_map_open, null_map_close,
7219 macro_map_lookup(map, name, av, statp)
7228 sm_dprintf("macro_map_lookup(%s, %s)\n", map->map_mname,
7229 name == NULL ? "NULL" : name);
7233 (mid = macid(name)) == 0)
7240 macdefine(&CurEnv->e_macro, A_PERM, mid, NULL);
7242 macdefine(&CurEnv->e_macro, A_TEMP, mid, av[1]);
7255 # define DEFAULT_DELIM CONDELSE
7256 # define END_OF_FIELDS -1
7257 # define ERRBUF_SIZE 80
7258 # define MAX_MATCH 32
7260 # define xnalloc(s) memset(xalloc(s), '\0', s);
7264 regex_t *regex_pattern_buf; /* xalloc it */
7265 int *regex_subfields; /* move to type MAP */
7266 char *regex_delim; /* move to type MAP */
7269 static int parse_fields __P((char *, int *, int, int));
7270 static char *regex_map_rewrite __P((MAP *, const char*, size_t, char **));
7273 parse_fields(s, ibuf, blen, nr_substrings)
7275 int *ibuf; /* array */
7276 int blen; /* number of elements in ibuf */
7277 int nr_substrings; /* number of substrings in the pattern */
7281 bool lastone = false;
7283 blen--; /* for terminating END_OF_FIELDS */
7304 if (val < 0 || val >= nr_substrings)
7306 syserr("field (%d) out of range, only %d substrings in pattern",
7307 val, nr_substrings);
7314 syserr("too many fields, %d max", blen);
7319 ibuf[i] = END_OF_FIELDS;
7324 regex_map_init(map, ap)
7329 struct regex_map *map_p;
7331 char *sub_param = NULL;
7333 static char defdstr[] = { (char) DEFAULT_DELIM, '\0' };
7336 sm_dprintf("regex_map_init: mapname '%s', args '%s'\n",
7337 map->map_mname, ap);
7339 pflags = REG_ICASE | REG_EXTENDED | REG_NOSUB;
7341 map_p = (struct regex_map *) xnalloc(sizeof(*map_p));
7342 map_p->regex_pattern_buf = (regex_t *)xnalloc(sizeof(regex_t));
7346 while (SM_ISSPACE(*p))
7353 map->map_mflags |= MF_REGEX_NOT;
7356 case 'f': /* case sensitive */
7357 map->map_mflags |= MF_NOFOLDCASE;
7358 pflags &= ~REG_ICASE;
7361 case 'b': /* basic regular expressions */
7362 pflags &= ~REG_EXTENDED;
7365 case 's': /* substring match () syntax */
7367 pflags &= ~REG_NOSUB;
7370 case 'd': /* delimiter */
7371 map_p->regex_delim = ++p;
7374 case 'a': /* map append */
7378 case 'm': /* matchonly */
7379 map->map_mflags |= MF_MATCHONLY;
7383 map->map_mflags |= MF_KEEPQUOTES;
7387 map->map_spacesub = *++p;
7391 map->map_mflags |= MF_DEFER;
7395 while (*p != '\0' && !(SM_ISSPACE(*p)))
7401 sm_dprintf("regex_map_init: compile '%s' 0x%x\n", p, pflags);
7403 if ((regerr = regcomp(map_p->regex_pattern_buf, p, pflags)) != 0)
7406 char errbuf[ERRBUF_SIZE];
7408 (void) regerror(regerr, map_p->regex_pattern_buf,
7409 errbuf, sizeof(errbuf));
7410 syserr("pattern-compile-error: %s", errbuf);
7411 sm_free(map_p->regex_pattern_buf); /* XXX */
7412 sm_free(map_p); /* XXX */
7416 if (map->map_app != NULL)
7417 map->map_app = newstr(map->map_app);
7418 if (map_p->regex_delim != NULL)
7419 map_p->regex_delim = newstr(map_p->regex_delim);
7421 map_p->regex_delim = defdstr;
7423 if (!bitset(REG_NOSUB, pflags))
7425 /* substring matching */
7427 int *fields = (int *) xalloc(sizeof(int) * (MAX_MATCH + 1));
7429 substrings = map_p->regex_pattern_buf->re_nsub + 1;
7432 sm_dprintf("regex_map_init: nr of substrings %d\n",
7435 if (substrings >= MAX_MATCH)
7437 syserr("too many substrings, %d max", MAX_MATCH);
7438 sm_free(map_p->regex_pattern_buf); /* XXX */
7439 sm_free(map_p); /* XXX */
7442 if (sub_param != NULL && sub_param[0] != '\0')
7444 /* optional parameter -sfields */
7445 if (parse_fields(sub_param, fields,
7446 MAX_MATCH + 1, substrings) == -1)
7453 /* set default fields */
7454 for (i = 0; i < substrings; i++)
7456 fields[i] = END_OF_FIELDS;
7458 map_p->regex_subfields = fields;
7463 sm_dprintf("regex_map_init: subfields");
7464 for (ip = fields; *ip != END_OF_FIELDS; ip++)
7465 sm_dprintf(" %d", *ip);
7469 map->map_db1 = (ARBPTR_T) map_p; /* dirty hack */
7474 regex_map_rewrite(map, s, slen, av)
7480 if (bitset(MF_MATCHONLY, map->map_mflags))
7481 return map_rewrite(map, av[0], strlen(av[0]), NULL);
7483 return map_rewrite(map, s, slen, av);
7487 regex_map_lookup(map, name, av, statp)
7494 struct regex_map *map_p;
7495 regmatch_t pmatch[MAX_MATCH];
7501 sm_dprintf("regex_map_lookup: key '%s'\n", name);
7502 for (cpp = av; cpp != NULL && *cpp != NULL; cpp++)
7503 sm_dprintf("regex_map_lookup: arg '%s'\n", *cpp);
7506 map_p = (struct regex_map *)(map->map_db1);
7507 reg_res = regexec(map_p->regex_pattern_buf,
7508 name, MAX_MATCH, pmatch, 0);
7510 if (bitset(MF_REGEX_NOT, map->map_mflags))
7513 if (reg_res == REG_NOMATCH)
7514 return regex_map_rewrite(map, "", (size_t) 0, av);
7518 if (reg_res == REG_NOMATCH)
7521 if (map_p->regex_subfields != NULL)
7524 static char retbuf[MAXNAME];
7525 int fields[MAX_MATCH + 1];
7527 int anglecnt = 0, cmntcnt = 0, spacecnt = 0;
7528 bool quotemode = false, bslashmode = false;
7529 register char *dp, *sp;
7534 ldp = retbuf + sizeof(retbuf) - 1;
7538 if (parse_fields(av[1], fields, MAX_MATCH + 1,
7539 (int) map_p->regex_pattern_buf->re_nsub + 1) == -1)
7547 ip = map_p->regex_subfields;
7549 for ( ; *ip != END_OF_FIELDS; ip++)
7553 for (sp = map_p->regex_delim; *sp; sp++)
7562 if (*ip >= MAX_MATCH ||
7563 pmatch[*ip].rm_so < 0 || pmatch[*ip].rm_eo < 0)
7566 sp = name + pmatch[*ip].rm_so;
7567 endp = name + pmatch[*ip].rm_eo;
7568 for (; endp > sp; sp++)
7577 else if (quotemode && *sp != '"' &&
7582 else switch (*dp++ = *sp)
7609 quotemode = !quotemode;
7615 if (anglecnt != 0 || cmntcnt != 0 || quotemode ||
7616 bslashmode || spacecnt != 0)
7618 sm_syslog(LOG_WARNING, NOQID,
7619 "Warning: regex may cause prescan() failure map=%s lookup=%s",
7620 map->map_mname, name);
7626 return regex_map_rewrite(map, retbuf, strlen(retbuf), av);
7628 return regex_map_rewrite(map, "", (size_t)0, av);
7630 #endif /* MAP_REGEX */
7637 # define _DATUM_DEFINED
7638 # include <ns_api.h>
7640 typedef struct ns_map_list
7642 ns_map_t *map; /* XXX ns_ ? */
7644 struct ns_map_list *next;
7648 ns_map_t_find(mapname)
7651 static ns_map_list_t *ns_maps = NULL;
7652 ns_map_list_t *ns_map;
7654 /* walk the list of maps looking for the correctly named map */
7655 for (ns_map = ns_maps; ns_map != NULL; ns_map = ns_map->next)
7657 if (strcmp(ns_map->mapname, mapname) == 0)
7661 /* if we are looking at a NULL ns_map_list_t, then create a new one */
7664 ns_map = (ns_map_list_t *) xalloc(sizeof(*ns_map));
7665 ns_map->mapname = newstr(mapname);
7666 ns_map->map = (ns_map_t *) xalloc(sizeof(*ns_map->map));
7667 memset(ns_map->map, '\0', sizeof(*ns_map->map));
7668 ns_map->next = ns_maps;
7675 nsd_map_lookup(map, name, av, statp)
7684 char keybuf[MAXNAME + 1];
7688 sm_dprintf("nsd_map_lookup(%s, %s)\n", map->map_mname, name);
7690 buflen = strlen(name);
7691 if (buflen > sizeof(keybuf) - 1)
7692 buflen = sizeof(keybuf) - 1; /* XXX simply cut off? */
7693 memmove(keybuf, name, buflen);
7694 keybuf[buflen] = '\0';
7695 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
7698 ns_map = ns_map_t_find(map->map_file);
7702 sm_dprintf("nsd_map_t_find failed\n");
7703 *statp = EX_UNAVAILABLE;
7706 r = ns_lookup(ns_map, NULL, map->map_file, keybuf, NULL,
7708 if (r == NS_UNAVAIL || r == NS_TRYAGAIN)
7710 *statp = EX_TEMPFAIL;
7722 if (r != NS_SUCCESS)
7724 *statp = EX_NOTFOUND;
7730 /* Null out trailing \n */
7731 if ((p = strchr(buf, '\n')) != NULL)
7734 return map_rewrite(map, buf, strlen(buf), av);
7736 #endif /* MAP_NSD */
7739 arith_map_lookup(map, name, av, statp)
7749 static char result[16];
7754 sm_dprintf("arith_map_lookup: key '%s'\n", name);
7755 for (cpp = av; cpp != NULL && *cpp != NULL; cpp++)
7756 sm_dprintf("arith_map_lookup: arg '%s'\n", *cpp);
7764 ** read arguments for arith map
7765 ** - no check is made whether they are really numbers
7766 ** - just ignores args after the second
7769 for (++cpp; cpp != NULL && *cpp != NULL && r < 2; cpp++)
7770 v[r++] = strtol(*cpp, NULL, 0);
7772 /* operator and (at least) two operands given? */
7773 if (name != NULL && r == 2)
7819 r = v[1] - v[0] + 1;
7822 r = get_random() % r + v[0];
7829 sm_syslog(LOG_WARNING, NOQID,
7830 "arith_map: unknown operator %c",
7831 (isascii(*name) && isprint(*name)) ?
7836 (void) sm_snprintf(result, sizeof(result),
7837 res ? "TRUE" : "FALSE");
7839 (void) sm_snprintf(result, sizeof(result), "%ld", r);
7847 arpa_map_lookup(map, name, av, statp)
7855 char result[128]; /* IPv6: 64 + 10 + 1 would be enough */
7858 sm_dprintf("arpa_map_lookup: key '%s'\n", name);
7859 *statp = EX_DATAERR;
7861 memset(result, '\0', sizeof(result));
7865 if (sm_strncasecmp(name, "IPv6:", 5) == 0)
7867 struct in6_addr in6_addr;
7869 r = anynet_pton(AF_INET6, name, &in6_addr);
7872 static char hex_digits[] =
7873 { '0', '1', '2', '3', '4', '5', '6', '7', '8',
7874 '9', 'a', 'b', 'c', 'd', 'e', 'f' };
7880 src = (unsigned char *) &in6_addr;
7882 for (i = 15; i >= 0; i--) {
7883 *dst++ = hex_digits[src[i] & 0x0f];
7885 *dst++ = hex_digits[(src[i] >> 4) & 0x0f];
7893 # endif /* NETINET6 */
7896 struct in_addr in_addr;
7898 r = inet_pton(AF_INET, name, &in_addr);
7903 src = (unsigned char *) &in_addr;
7904 (void) snprintf(result, sizeof(result),
7906 src[3], src[2], src[1], src[0]);
7910 # endif /* NETINET */
7912 *statp = EX_UNAVAILABLE;
7914 sm_dprintf("arpa_map_lookup: r=%d, result='%s'\n", r, result);
7915 if (*statp == EX_OK)
7917 if (bitset(MF_MATCHONLY, map->map_mflags))
7918 rval = map_rewrite(map, name, strlen(name), NULL);
7920 rval = map_rewrite(map, result, strlen(result), av);
7925 #if _FFR_SETDEBUG_MAP
7927 setdebug_map_lookup(map, name, av, statp)
7938 sm_dprintf("setdebug_map_lookup: key '%s'\n", name);
7939 for (cpp = av; cpp != NULL && *cpp != NULL; cpp++)
7940 sm_dprintf("setdebug_map_lookup: arg '%s'\n", *cpp);
7950 setopt_map_lookup(map, name, av, statp)
7956 # if !_FFR_SETANYOPT
7963 sm_dprintf("setopt_map_lookup: key '%s'\n", name);
7964 for (cpp = av; cpp != NULL && *cpp != NULL; cpp++)
7965 sm_dprintf("setopt_map_lookup: arg '%s'\n", *cpp);
7969 ** API screwed up...
7970 ** first arg is the "short" name and second is the entire string...
7973 sm_dprintf("setoption: name=%s\n", name);
7974 setoption(' ', name, true, false, CurEnv);
7977 # else /* _FFR_SETANYOPT */
7981 if (cpp == NULL || ++cpp == NULL || *cpp == NULL)
7985 val = strtol(*cpp, NULL, 0);
7986 /* check for valid number? */
7989 if (sm_strcasecmp(name, "LogLevel") == 0)
7992 sm_dprintf("LogLevel=%d\n", val);
7995 # endif /* _FFR_SETANYOPT */
8004 # if NETINET || NETINET6
8005 # include <arpa/inet.h>
8008 # define socket_map_next map_stack[0]
8011 ** SOCKET_MAP_OPEN -- open socket table
8015 socket_map_open(map, mode)
8022 SOCKADDR_LEN_T addrlen = 0;
8028 struct hostent *hp = NULL;
8032 sm_dprintf("socket_map_open(%s, %s, %d)\n",
8033 map->map_mname, map->map_file, mode);
8037 /* sendmail doesn't have the ability to write to SOCKET (yet) */
8038 if (mode != O_RDONLY)
8040 /* issue a pseudo-error message */
8041 errno = SM_EMAPCANTWRITE;
8045 if (*map->map_file == '\0')
8047 syserr("socket map \"%s\": empty or missing socket information",
8052 s = socket_map_findconn(map->map_file);
8053 if (s->s_socketmap != NULL)
8055 /* Copy open connection */
8056 map->map_db1 = s->s_socketmap->map_db1;
8058 /* Add this map as head of linked list */
8059 map->socket_map_next = s->s_socketmap;
8060 s->s_socketmap = map;
8063 sm_dprintf("using cached connection\n");
8068 sm_dprintf("opening new connection\n");
8070 /* following code is ripped from milter.c */
8071 /* XXX It should be put in a library... */
8073 /* protocol:filename or protocol:port@host */
8074 memset(&addr, '\0', sizeof(addr));
8076 colon = strchr(p, ':');
8084 /* default to AF_UNIX */
8085 addr.sa.sa_family = AF_UNIX;
8086 # else /* NETUNIX */
8088 /* default to AF_INET */
8089 addr.sa.sa_family = AF_INET;
8090 # else /* NETINET */
8092 /* default to AF_INET6 */
8093 addr.sa.sa_family = AF_INET6;
8094 # else /* NETINET6 */
8095 /* no protocols available */
8096 syserr("socket map \"%s\": no valid socket protocols available",
8099 # endif /* NETINET6 */
8100 # endif /* NETINET */
8101 # endif /* NETUNIX */
8104 else if (sm_strcasecmp(p, "unix") == 0 ||
8105 sm_strcasecmp(p, "local") == 0)
8106 addr.sa.sa_family = AF_UNIX;
8107 # endif /* NETUNIX */
8109 else if (sm_strcasecmp(p, "inet") == 0)
8110 addr.sa.sa_family = AF_INET;
8111 # endif /* NETINET */
8113 else if (sm_strcasecmp(p, "inet6") == 0)
8114 addr.sa.sa_family = AF_INET6;
8115 # endif /* NETINET6 */
8118 # ifdef EPROTONOSUPPORT
8119 errno = EPROTONOSUPPORT;
8122 # endif /* EPROTONOSUPPORT */
8123 syserr("socket map \"%s\": unknown socket type %s",
8133 /* default to AF_UNIX */
8134 addr.sa.sa_family = AF_UNIX;
8137 /* default to AF_INET */
8138 addr.sa.sa_family = AF_INET;
8139 # else /* NETINET */
8141 /* default to AF_INET6 */
8142 addr.sa.sa_family = AF_INET6;
8143 # else /* NETINET6 */
8144 syserr("socket map \"%s\": unknown socket type %s",
8147 # endif /* NETINET6 */
8148 # endif /* NETINET */
8149 #endif /* NETUNIX */
8153 if (addr.sa.sa_family == AF_UNIX)
8155 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_EXECOK;
8158 if (strlen(colon) >= sizeof(addr.sunix.sun_path))
8160 syserr("socket map \"%s\": local socket name %s too long",
8161 map->map_mname, colon);
8164 errno = safefile(colon, RunAsUid, RunAsGid, RunAsUserName, sff,
8165 S_IRUSR|S_IWUSR, NULL);
8169 /* if not safe, don't create */
8170 syserr("socket map \"%s\": local socket name %s unsafe",
8171 map->map_mname, colon);
8175 (void) sm_strlcpy(addr.sunix.sun_path, colon,
8176 sizeof(addr.sunix.sun_path));
8177 addrlen = sizeof(struct sockaddr_un);
8180 # endif /* NETUNIX */
8181 # if NETINET || NETINET6
8184 || addr.sa.sa_family == AF_INET
8187 || addr.sa.sa_family == AF_INET6
8191 unsigned short port;
8193 /* Parse port@host */
8194 at = strchr(colon, '@');
8197 syserr("socket map \"%s\": bad address %s (expected port@host)",
8198 map->map_mname, colon);
8202 if (isascii(*colon) && isdigit(*colon))
8203 port = htons((unsigned short) atoi(colon));
8206 # ifdef NO_GETSERVBYNAME
8207 syserr("socket map \"%s\": invalid port number %s",
8208 map->map_mname, colon);
8210 # else /* NO_GETSERVBYNAME */
8211 register struct servent *sp;
8213 sp = getservbyname(colon, "tcp");
8216 syserr("socket map \"%s\": unknown port name %s",
8217 map->map_mname, colon);
8221 # endif /* NO_GETSERVBYNAME */
8228 end = strchr(at, ']');
8233 unsigned long hid = INADDR_NONE;
8236 struct sockaddr_in6 hid6;
8241 if (addr.sa.sa_family == AF_INET &&
8242 (hid = inet_addr(&at[1])) != INADDR_NONE)
8244 addr.sin.sin_addr.s_addr = hid;
8245 addr.sin.sin_port = port;
8248 # endif /* NETINET */
8250 (void) memset(&hid6, '\0', sizeof(hid6));
8251 if (addr.sa.sa_family == AF_INET6 &&
8252 anynet_pton(AF_INET6, &at[1],
8253 &hid6.sin6_addr) == 1)
8255 addr.sin6.sin6_addr = hid6.sin6_addr;
8256 addr.sin6.sin6_port = port;
8259 # endif /* NETINET6 */
8263 syserr("socket map \"%s\": Invalid numeric domain spec \"%s\"",
8264 map->map_mname, at);
8270 syserr("socket map \"%s\": Invalid numeric domain spec \"%s\"",
8271 map->map_mname, at);
8277 hp = sm_gethostbyname(at, addr.sa.sa_family);
8280 syserr("socket map \"%s\": Unknown host name %s",
8281 map->map_mname, at);
8284 addr.sa.sa_family = hp->h_addrtype;
8285 switch (hp->h_addrtype)
8289 memmove(&addr.sin.sin_addr,
8290 hp->h_addr, INADDRSZ);
8291 addr.sin.sin_port = port;
8292 addrlen = sizeof(struct sockaddr_in);
8295 # endif /* NETINET */
8299 memmove(&addr.sin6.sin6_addr,
8300 hp->h_addr, IN6ADDRSZ);
8301 addr.sin6.sin6_port = port;
8302 addrlen = sizeof(struct sockaddr_in6);
8305 # endif /* NETINET6 */
8308 syserr("socket map \"%s\": Unknown protocol for %s (%d)",
8309 map->map_mname, at, hp->h_addrtype);
8318 # endif /* NETINET || NETINET6 */
8320 syserr("socket map \"%s\": unknown socket protocol",
8325 /* nope, actually connecting */
8328 sock = socket(addr.sa.sa_family, SOCK_STREAM, 0);
8333 sm_dprintf("socket map \"%s\": error creating socket: %s\n",
8335 sm_errstring(save_errno));
8339 # endif /* NETINET6 */
8343 if (connect(sock, (struct sockaddr *) &addr, addrlen) >= 0)
8346 /* couldn't connect.... try next address */
8351 sm_dprintf("socket_open (%s): open %s failed: %s\n",
8352 map->map_mname, at, sm_errstring(save_errno));
8356 /* try next address */
8357 if (hp != NULL && hp->h_addr_list[addrno] != NULL)
8359 switch (addr.sa.sa_family)
8363 memmove(&addr.sin.sin_addr,
8364 hp->h_addr_list[addrno++],
8367 # endif /* NETINET */
8371 memmove(&addr.sin6.sin6_addr,
8372 hp->h_addr_list[addrno++],
8375 # endif /* NETINET6 */
8379 sm_dprintf("socket map \"%s\": Unknown protocol for %s (%d)\n",
8392 sm_dprintf("socket map \"%s\": error connecting to socket map: %s\n",
8393 map->map_mname, sm_errstring(save_errno));
8407 # endif /* NETINET6 */
8408 if ((map->map_db1 = (ARBPTR_T) sm_io_open(SmFtStdiofd,
8416 sm_dprintf("socket_open (%s): failed to create stream: %s\n",
8417 map->map_mname, sm_errstring(errno));
8421 tmo = map->map_timeout;
8423 tmo = 30000; /* default: 30s */
8425 tmo *= 1000; /* s -> ms */
8426 sm_io_setinfo(map->map_db1, SM_IO_WHAT_TIMEOUT, &tmo);
8428 /* Save connection for reuse */
8429 s->s_socketmap = map;
8434 ** SOCKET_MAP_FINDCONN -- find a SOCKET connection to the server
8436 ** Cache SOCKET connections based on the connection specifier
8437 ** and PID so we don't have multiple connections open to
8438 ** the same server for different maps. Need a separate connection
8439 ** per PID since a parent process may close the map before the
8440 ** child is done with it.
8443 ** conn -- SOCKET map connection specifier
8446 ** Symbol table entry for the SOCKET connection.
8450 socket_map_findconn(conn)
8454 STAB *SM_NONVOLATILE s = NULL;
8456 nbuf = sm_stringf_x("%s%c%d", conn, CONDELSE, (int) CurrentPid);
8458 s = stab(nbuf, ST_SOCKETMAP, ST_ENTER);
8466 ** SOCKET_MAP_CLOSE -- close the socket
8470 socket_map_close(map)
8477 sm_dprintf("socket_map_close(%s), pid=%ld\n", map->map_file,
8480 /* Check if already closed */
8481 if (map->map_db1 == NULL)
8484 sm_dprintf("socket_map_close(%s) already closed\n",
8488 sm_io_close((SM_FILE_T *)map->map_db1, SM_TIME_DEFAULT);
8490 /* Mark all the maps that share the connection as closed */
8491 s = socket_map_findconn(map->map_file);
8492 smap = s->s_socketmap;
8493 while (smap != NULL)
8497 if (tTd(38, 2) && smap != map)
8498 sm_dprintf("socket_map_close(%s): closed %s (shared SOCKET connection)\n",
8499 map->map_mname, smap->map_mname);
8501 smap->map_mflags &= ~(MF_OPEN|MF_WRITABLE);
8502 smap->map_db1 = NULL;
8503 next = smap->socket_map_next;
8504 smap->socket_map_next = NULL;
8507 s->s_socketmap = NULL;
8511 ** SOCKET_MAP_LOOKUP -- look up a datum in a SOCKET table
8515 socket_map_lookup(map, name, av, statp)
8521 unsigned int nettolen, replylen, recvlen;
8523 char *replybuf, *rval, *value, *status, *key;
8525 char keybuf[MAXNAME + 1];
8529 f = (SM_FILE_T *)map->map_db1;
8531 sm_dprintf("socket_map_lookup(%s, %s) %s\n",
8532 map->map_mname, name, map->map_file);
8534 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
8536 nettolen = strlen(name);
8537 if (nettolen > sizeof(keybuf) - 1)
8538 nettolen = sizeof(keybuf) - 1;
8539 memmove(keybuf, name, nettolen);
8540 keybuf[nettolen] = '\0';
8547 nettolen = strlen(map->map_mname) + 1 + strlen(key);
8548 SM_ASSERT(nettolen > strlen(map->map_mname));
8549 SM_ASSERT(nettolen > strlen(key));
8550 if ((sm_io_fprintf(f, SM_TIME_DEFAULT, "%u:%s %s,",
8551 nettolen, map->map_mname, key) == SM_IO_EOF) ||
8552 (sm_io_flush(f, SM_TIME_DEFAULT) != 0) ||
8555 syserr("451 4.3.0 socket_map_lookup(%s): failed to send lookup request",
8557 *statp = EX_TEMPFAIL;
8561 if ((ret = sm_io_fscanf(f, SM_TIME_DEFAULT, "%9u", &replylen)) != 1)
8563 if (errno == EAGAIN)
8565 syserr("451 4.3.0 socket_map_lookup(%s): read timeout",
8568 else if (SM_IO_EOF == ret)
8571 sm_syslog(LOG_INFO, CurEnv->e_id,
8572 "socket_map_lookup(%s): EOF",
8577 syserr("451 4.3.0 socket_map_lookup(%s): failed to read length parameter of reply %d",
8578 map->map_mname, errno);
8580 *statp = EX_TEMPFAIL;
8583 if (replylen > SOCKETMAP_MAXL)
8585 syserr("451 4.3.0 socket_map_lookup(%s): reply too long: %u",
8586 map->map_mname, replylen);
8587 *statp = EX_TEMPFAIL;
8590 if (sm_io_getc(f, SM_TIME_DEFAULT) != ':')
8592 syserr("451 4.3.0 socket_map_lookup(%s): missing ':' in reply",
8594 *statp = EX_TEMPFAIL;
8598 replybuf = (char *) sm_malloc(replylen + 1);
8599 if (replybuf == NULL)
8601 syserr("451 4.3.0 socket_map_lookup(%s): can't allocate %u bytes",
8602 map->map_mname, replylen + 1);
8607 recvlen = sm_io_read(f, SM_TIME_DEFAULT, replybuf, replylen);
8608 if (recvlen < replylen)
8610 syserr("451 4.3.0 socket_map_lookup(%s): received only %u of %u reply characters",
8611 map->map_mname, recvlen, replylen);
8612 *statp = EX_TEMPFAIL;
8615 if (sm_io_getc(f, SM_TIME_DEFAULT) != ',')
8617 syserr("451 4.3.0 socket_map_lookup(%s): missing ',' in reply",
8619 *statp = EX_TEMPFAIL;
8623 replybuf[recvlen] = '\0';
8624 value = strchr(replybuf, ' ');
8630 if (strcmp(status, "OK") == 0)
8634 /* collect the return value */
8635 if (bitset(MF_MATCHONLY, map->map_mflags))
8636 rval = map_rewrite(map, key, strlen(key), NULL);
8638 rval = map_rewrite(map, value, strlen(value), av);
8640 else if (strcmp(status, "NOTFOUND") == 0)
8642 *statp = EX_NOTFOUND;
8644 sm_dprintf("socket_map_lookup(%s): %s not found\n",
8645 map->map_mname, key);
8650 sm_dprintf("socket_map_lookup(%s, %s): server returned error: type=%s, reason=%s\n",
8651 map->map_mname, key, status,
8652 value ? value : "");
8653 if ((strcmp(status, "TEMP") == 0) ||
8654 (strcmp(status, "TIMEOUT") == 0))
8655 *statp = EX_TEMPFAIL;
8656 else if(strcmp(status, "PERM") == 0)
8657 *statp = EX_UNAVAILABLE;
8659 *statp = EX_PROTOCOL;
8662 if (replybuf != NULL)
8667 socket_map_close(map);
8669 if (replybuf != NULL)
8673 #endif /* SOCKETMAP */