2 * Copyright (c) 1998-2008 Sendmail, Inc. and its suppliers.
4 * Copyright (c) 1992, 1995-1997 Eric P. Allman. All rights reserved.
5 * Copyright (c) 1992, 1993
6 * The Regents of the University of California. All rights reserved.
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
16 SM_RCSID("@(#)$Id: map.c,v 8.711 2013/03/12 15:24:52 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 */
45 # if DB_VERSION_MAJOR < 2
46 static bool db_map_open __P((MAP *, int, char *, DBTYPE, const void *));
47 # endif /* DB_VERSION_MAJOR < 2 */
48 # if DB_VERSION_MAJOR == 2
49 static bool db_map_open __P((MAP *, int, char *, DBTYPE, DB_INFO *));
50 # endif /* DB_VERSION_MAJOR == 2 */
51 # if DB_VERSION_MAJOR > 2
52 static bool db_map_open __P((MAP *, int, char *, DBTYPE, void **));
53 # endif /* DB_VERSION_MAJOR > 2 */
55 static bool extract_canonname __P((char *, char *, char *, char[], int));
56 static void map_close __P((STAB *, int));
57 static void map_init __P((STAB *, int));
59 static STAB * ldapmap_findconn __P((SM_LDAP_STRUCT *));
62 static bool nisplus_getcanonname __P((char *, int, int *));
65 static bool nis_getcanonname __P((char *, int, int *));
68 static bool ni_getcanonname __P((char *, int, int *));
70 static bool text_getcanonname __P((char *, int, int *));
72 static STAB *socket_map_findconn __P((const char*));
74 /* XXX arbitrary limit for sanity */
75 # define SOCKETMAP_MAXL 1000000
76 #endif /* SOCKETMAP */
78 /* default error message for trying to open a map in write mode */
80 # define SM_EMAPCANTWRITE ENOSYS
83 # define SM_EMAPCANTWRITE EFTYPE
85 # define SM_EMAPCANTWRITE ENXIO
90 ** MAP.C -- implementations for various map classes.
92 ** Each map class implements a series of functions:
94 ** bool map_parse(MAP *map, char *args)
95 ** Parse the arguments from the config file. Return true
96 ** if they were ok, false otherwise. Fill in map with the
99 ** char *map_lookup(MAP *map, char *key, char **args, int *pstat)
100 ** Look up the key in the given map. If found, do any
101 ** rewriting the map wants (including "args" if desired)
102 ** and return the value. Set *pstat to the appropriate status
103 ** on error and return NULL. Args will be NULL if called
104 ** from the alias routines, although this should probably
105 ** not be relied upon. It is suggested you call map_rewrite
106 ** to return the results -- it takes care of null termination
107 ** and uses a dynamically expanded buffer as needed.
109 ** void map_store(MAP *map, char *key, char *value)
110 ** Store the key:value pair in the map.
112 ** bool map_open(MAP *map, int mode)
113 ** Open the map for the indicated mode. Mode should
114 ** be either O_RDONLY or O_RDWR. Return true if it
115 ** was opened successfully, false otherwise. If the open
116 ** failed and the MF_OPTIONAL flag is not set, it should
117 ** also print an error. If the MF_ALIAS bit is set
118 ** and this map class understands the @:@ convention, it
119 ** should call aliaswait() before returning.
121 ** void map_close(MAP *map)
124 ** This file also includes the implementation for getcanonname.
125 ** It is currently implemented in a pretty ad-hoc manner; it ought
126 ** to be more properly integrated into the map structure.
129 #if O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL
130 # define LOCK_ON_OPEN 1 /* we can open/create a locked file */
131 #else /* O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL */
132 # define LOCK_ON_OPEN 0 /* no such luck -- bend over backwards */
133 #endif /* O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL */
136 ** MAP_PARSEARGS -- parse config line arguments for database lookup
138 ** This is a generic version of the map_parse method.
141 ** map -- the map being initialized.
142 ** ap -- a pointer to the args on the config line.
145 ** true -- if everything parsed OK.
146 ** false -- otherwise.
149 ** null terminates the filename; stores it in map
153 map_parseargs(map, ap)
157 register char *p = ap;
160 ** There is no check whether there is really an argument,
161 ** but that's not important enough to warrant extra code.
164 map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL;
165 map->map_spacesub = SpaceSub; /* default value */
168 while (isascii(*p) && isspace(*p))
175 map->map_mflags |= MF_INCLNULL;
176 map->map_mflags &= ~MF_TRY0NULL;
180 map->map_mflags &= ~MF_TRY1NULL;
184 map->map_mflags |= MF_OPTIONAL;
188 map->map_mflags |= MF_NOFOLDCASE;
192 map->map_mflags |= MF_MATCHONLY;
196 map->map_mflags |= MF_APPEND;
200 map->map_mflags |= MF_KEEPQUOTES;
212 while (isascii(*++p) && isspace(*p))
214 map->map_keycolnm = p;
218 while (isascii(*++p) && isspace(*p))
220 map->map_valcolnm = p;
225 map->map_coldelim = *p;
231 map->map_coldelim = '\n';
235 map->map_coldelim = '\t';
239 map->map_coldelim = '\\';
245 map->map_mflags |= MF_NODEFER;
250 map->map_spacesub = *++p;
254 map->map_mflags |= MF_DEFER;
258 syserr("Illegal option %c map %s", *p, map->map_mname);
261 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
266 if (map->map_app != NULL)
267 map->map_app = newstr(map->map_app);
268 if (map->map_tapp != NULL)
269 map->map_tapp = newstr(map->map_tapp);
270 if (map->map_keycolnm != NULL)
271 map->map_keycolnm = newstr(map->map_keycolnm);
272 if (map->map_valcolnm != NULL)
273 map->map_valcolnm = newstr(map->map_valcolnm);
278 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
282 map->map_file = newstr(map->map_file);
285 while (*p != '\0' && isascii(*p) && isspace(*p))
288 map->map_rebuild = newstr(p);
290 if (map->map_file == NULL &&
291 !bitset(MCF_OPTFILE, map->map_class->map_cflags))
293 syserr("No file name for %s map %s",
294 map->map_class->map_cname, map->map_mname);
300 ** MAP_REWRITE -- rewrite a database key, interpolating %n indications.
302 ** It also adds the map_app string. It can be used as a utility
303 ** in the map_lookup method.
306 ** map -- the map that causes this.
307 ** s -- the string to rewrite, NOT necessarily null terminated.
308 ** slen -- the length of s.
309 ** av -- arguments to interpolate into buf.
312 ** Pointer to rewritten result. This is static data that
313 ** should be copied if it is to be saved!
317 map_rewrite(map, s, slen, av)
319 register const char *s;
329 static size_t buflen = 0;
330 static char *buf = NULL;
334 sm_dprintf("map_rewrite(%.*s), av =", (int) slen, s);
336 sm_dprintf(" (nullv)");
339 for (avp = av; *avp != NULL; avp++)
340 sm_dprintf("\n\t%s", *avp);
345 /* count expected size of output (can safely overestimate) */
351 while (l-- > 0 && (c = *sp++) != '\0')
358 if (!(isascii(c) && isdigit(c)))
360 for (avp = av; --c >= '0' && *avp != NULL; avp++)
367 if (map->map_app != NULL)
368 len += strlen(map->map_app);
371 /* need to malloc additional space */
375 buf = sm_pmalloc_x(buflen);
381 memmove(bp, s, slen);
384 /* assert(len > slen); */
389 while (slen-- > 0 && (c = *s++) != '\0')
399 if (slen-- <= 0 || (c = *s++) == '\0')
403 if (!(isascii(c) && isdigit(c)))
410 for (avp = av; --c >= '0' && *avp != NULL; avp++)
415 /* transliterate argument into output string */
416 for (ap = *avp; (c = *ap++) != '\0' && len > 0; --len)
420 if (map->map_app != NULL && len > 0)
421 (void) sm_strlcpy(bp, map->map_app, len);
425 sm_dprintf("map_rewrite => %s\n", buf);
429 ** INITMAPS -- rebuild alias maps
442 checkfd012("entering initmaps");
444 stabapply(map_init, 0);
446 checkfd012("exiting initmaps");
450 ** MAP_INIT -- rebuild a map
453 ** s -- STAB entry: if map: try to rebuild
454 ** unused -- unused variable
460 ** will close already open rebuildable map.
471 /* has to be a map */
472 if (s->s_symtype != ST_MAP)
476 if (!bitset(MF_VALID, map->map_mflags))
480 sm_dprintf("map_init(%s:%s, %s)\n",
481 map->map_class->map_cname == NULL ? "NULL" :
482 map->map_class->map_cname,
483 map->map_mname == NULL ? "NULL" : map->map_mname,
484 map->map_file == NULL ? "NULL" : map->map_file);
486 if (!bitset(MF_ALIAS, map->map_mflags) ||
487 !bitset(MCF_REBUILDABLE, map->map_class->map_cflags))
490 sm_dprintf("\tnot rebuildable\n");
494 /* if already open, close it (for nested open) */
495 if (bitset(MF_OPEN, map->map_mflags))
497 map->map_mflags |= MF_CLOSING;
498 map->map_class->map_close(map);
499 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
502 (void) rebuildaliases(map, false);
506 ** OPENMAP -- open a map
509 ** map -- map to open (it must not be open).
512 ** whether open succeeded.
519 bool restore = false;
520 bool savehold = HoldErrs;
521 bool savequick = QuickAbort;
522 int saveerrors = Errors;
524 if (!bitset(MF_VALID, map->map_mflags))
527 /* better safe than sorry... */
528 if (bitset(MF_OPEN, map->map_mflags))
531 /* Don't send a map open error out via SMTP */
532 if ((OnlyOneError || QuickAbort) &&
533 (OpMode == MD_SMTP || OpMode == MD_DAEMON))
541 if (map->map_class->map_open(map, O_RDONLY))
544 sm_dprintf("openmap()\t%s:%s %s: valid\n",
545 map->map_class->map_cname == NULL ? "NULL" :
546 map->map_class->map_cname,
547 map->map_mname == NULL ? "NULL" :
549 map->map_file == NULL ? "NULL" :
551 map->map_mflags |= MF_OPEN;
552 map->map_pid = CurrentPid;
557 sm_dprintf("openmap()\t%s:%s %s: invalid%s%s\n",
558 map->map_class->map_cname == NULL ? "NULL" :
559 map->map_class->map_cname,
560 map->map_mname == NULL ? "NULL" :
562 map->map_file == NULL ? "NULL" :
564 errno == 0 ? "" : ": ",
565 errno == 0 ? "" : sm_errstring(errno));
566 if (!bitset(MF_OPTIONAL, map->map_mflags))
568 extern MAPCLASS BogusMapClass;
570 map->map_orgclass = map->map_class;
571 map->map_class = &BogusMapClass;
572 map->map_mflags |= MF_OPEN|MF_OPENBOGUS;
573 map->map_pid = CurrentPid;
577 /* don't try again */
578 map->map_mflags &= ~MF_VALID;
586 QuickAbort = savequick;
589 return bitset(MF_OPEN, map->map_mflags);
592 ** CLOSEMAPS -- close all open maps opened by the current pid.
595 ** bogus -- only close bogus maps.
605 stabapply(map_close, bogus);
608 ** MAP_CLOSE -- close a map opened by the current pid.
611 ** s -- STAB entry: if map: try to close
612 ** bogus -- only close bogus maps or MCF_NOTPERSIST maps.
622 int bogus; /* int because of stabapply(), used as bool */
625 extern MAPCLASS BogusMapClass;
627 if (s->s_symtype != ST_MAP)
633 ** close the map iff:
634 ** it is valid and open and opened by this process
635 ** and (!bogus or it's a bogus map or it is not persistent)
636 ** negate this: return iff
637 ** it is not valid or it is not open or not opened by this process
638 ** or (bogus and it's not a bogus map and it's not not-persistent)
641 if (!bitset(MF_VALID, map->map_mflags) ||
642 !bitset(MF_OPEN, map->map_mflags) ||
643 bitset(MF_CLOSING, map->map_mflags) ||
644 map->map_pid != CurrentPid ||
645 (bogus && map->map_class != &BogusMapClass &&
646 !bitset(MCF_NOTPERSIST, map->map_class->map_cflags)))
649 if (map->map_class == &BogusMapClass && map->map_orgclass != NULL &&
650 map->map_orgclass != &BogusMapClass)
651 map->map_class = map->map_orgclass;
653 sm_dprintf("closemaps: closing %s (%s)\n",
654 map->map_mname == NULL ? "NULL" : map->map_mname,
655 map->map_file == NULL ? "NULL" : map->map_file);
657 if (!bitset(MF_OPENBOGUS, map->map_mflags))
659 map->map_mflags |= MF_CLOSING;
660 map->map_class->map_close(map);
662 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_OPENBOGUS|MF_CLOSING);
665 #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
666 extern int getdomainname();
668 /* this is mainly for backward compatibility in Sun environment */
673 ** Get the domain name from the kernel.
674 ** If it does not start with a leading dot, then remove
675 ** the first component. Since leading dots are funny Unix
676 ** files, we treat a leading "+" the same as a leading dot.
677 ** Finally, force there to be at least one dot in the domain name
678 ** (i.e. top-level domains are not allowed, like "com", must be
679 ** something like "sun.com").
683 char *period, *autodomain;
685 if (getdomainname(buf, sizeof buf) < 0)
692 printf("domainname = %s\n", buf);
696 period = strchr(buf, '.');
700 autodomain = period + 1;
701 if (strchr(autodomain, '.') == NULL)
704 return newstr(autodomain);
706 #endif /* SUN_EXTENSIONS && SUN_INIT_DOMAIN */
709 ** GETCANONNAME -- look up name using service switch
712 ** host -- the host name to look up.
713 ** hbsize -- the size of the host buffer.
714 ** trymx -- if set, try MX records.
715 ** pttl -- pointer to return TTL (can be NULL).
718 ** true -- if the host was found.
719 ** false -- otherwise.
723 getcanonname(host, hbsize, trymx, pttl)
732 bool got_tempfail = false;
733 auto int status = EX_UNAVAILABLE;
734 char *maptype[MAXMAPSTACK];
735 short mapreturn[MAXMAPACTIONS];
736 #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
737 bool should_try_nis_domain = false;
738 static char *nis_domain = NULL;
741 nmaps = switch_map_find("hosts", maptype, mapreturn);
743 *pttl = SM_DEFAULT_TTL;
744 for (mapno = 0; mapno < nmaps; mapno++)
749 sm_dprintf("getcanonname(%s), trying %s\n",
750 host, maptype[mapno]);
751 if (strcmp("files", maptype[mapno]) == 0)
753 found = text_getcanonname(host, hbsize, &status);
756 else if (strcmp("nis", maptype[mapno]) == 0)
758 found = nis_getcanonname(host, hbsize, &status);
759 # if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
760 if (nis_domain == NULL)
761 nis_domain = sun_init_domain();
762 # endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */
766 else if (strcmp("nisplus", maptype[mapno]) == 0)
768 found = nisplus_getcanonname(host, hbsize, &status);
769 # if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
770 if (nis_domain == NULL)
771 nis_domain = sun_init_domain();
772 # endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */
776 else if (strcmp("dns", maptype[mapno]) == 0)
778 found = dns_getcanonname(host, hbsize, trymx, &status, pttl);
780 #endif /* NAMED_BIND */
782 else if (strcmp("netinfo", maptype[mapno]) == 0)
784 found = ni_getcanonname(host, hbsize, &status);
790 status = EX_UNAVAILABLE;
794 ** Heuristic: if $m is not set, we are running during system
795 ** startup. In this case, when a name is apparently found
796 ** but has no dot, treat is as not found. This avoids
797 ** problems if /etc/hosts has no FQDN but is listed first
798 ** in the service switch.
802 (macvalue('m', CurEnv) != NULL || strchr(host, '.') != NULL))
805 #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
807 should_try_nis_domain = true;
808 /* but don't break, as we need to try all methods first */
809 #endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */
811 /* see if we should continue */
812 if (status == EX_TEMPFAIL)
817 else if (status == EX_NOTFOUND)
821 if (bitset(1 << mapno, mapreturn[i]))
830 sm_dprintf("getcanonname(%s), found\n", host);
833 ** If returned name is still single token, compensate
834 ** by tagging on $m. This is because some sites set
835 ** up their DNS or NIS databases wrong.
838 if ((d = strchr(host, '.')) == NULL || d[1] == '\0')
840 d = macvalue('m', CurEnv);
842 hbsize > (int) (strlen(host) + strlen(d) + 1))
844 if (host[strlen(host) - 1] != '.')
845 (void) sm_strlcat2(host, ".", d,
848 (void) sm_strlcat(host, d, hbsize);
852 #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
853 if (VendorCode == VENDOR_SUN &&
854 should_try_nis_domain)
858 #endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */
865 #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN)
866 if (VendorCode == VENDOR_SUN && should_try_nis_domain)
869 if (nis_domain != NULL &&
870 strlen(nis_domain) + strlen(host) + 1 < hbsize)
872 (void) sm_strlcat2(host, ".", nis_domain, hbsize);
876 #endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */
879 sm_dprintf("getcanonname(%s), failed, status=%d\n", host,
883 SM_SET_H_ERRNO(TRY_AGAIN);
885 SM_SET_H_ERRNO(HOST_NOT_FOUND);
890 ** EXTRACT_CANONNAME -- extract canonical name from /etc/hosts entry
893 ** name -- the name against which to match.
894 ** dot -- where to reinsert '.' to get FQDN
895 ** line -- the /etc/hosts line.
896 ** cbuf -- the location to store the result.
897 ** cbuflen -- the size of cbuf.
900 ** true -- if the line matched the desired name.
901 ** false -- otherwise.
905 extract_canonname(name, dot, line, cbuf, cbuflen)
922 char nbuf[MAXNAME + 1];
924 p = get_column(line, i, '\0', nbuf, sizeof(nbuf));
929 if (cbuf[0] == '\0' ||
930 (strchr(cbuf, '.') == NULL && strchr(p, '.') != NULL))
932 (void) sm_strlcpy(cbuf, p, cbuflen);
934 if (sm_strcasecmp(name, p) == 0)
936 else if (dot != NULL)
938 /* try looking for the FQDN as well */
940 if (sm_strcasecmp(name, p) == 0)
945 if (found && strchr(cbuf, '.') == NULL)
947 /* try to add a domain on the end of the name */
948 char *domain = macvalue('m', CurEnv);
950 if (domain != NULL &&
951 strlen(domain) + (i = strlen(cbuf)) + 1 < (size_t) cbuflen)
955 (void) sm_strlcpy(p, domain, cbuflen - i - 1);
968 # include "sm_resolve.h"
969 # if NETINET || NETINET6
970 # include <arpa/inet.h>
971 # endif /* NETINET || NETINET6 */
974 ** DNS_MAP_OPEN -- stub to check proper value for dns map type
978 dns_map_open(map, mode)
983 sm_dprintf("dns_map_open(%s, %d)\n", map->map_mname, mode);
986 if (mode != O_RDONLY)
988 /* issue a pseudo-error message */
989 errno = SM_EMAPCANTWRITE;
996 ** DNS_MAP_PARSEARGS -- parse dns map definition args.
999 ** map -- pointer to MAP
1000 ** args -- pointer to the args on the config line.
1003 ** true -- if everything parsed OK.
1004 ** false -- otherwise.
1007 #define map_sizelimit map_lockfd /* overload field */
1015 dns_map_parseargs(map,args)
1019 register char *p = args;
1020 struct dns_map *map_p;
1022 map_p = (struct dns_map *) xalloc(sizeof(*map_p));
1023 map_p->dns_m_type = -1;
1024 map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL;
1028 while (isascii(*p) && isspace(*p))
1035 map->map_mflags |= MF_INCLNULL;
1036 map->map_mflags &= ~MF_TRY0NULL;
1040 map->map_mflags &= ~MF_TRY1NULL;
1044 map->map_mflags |= MF_OPTIONAL;
1048 map->map_mflags |= MF_NOFOLDCASE;
1052 map->map_mflags |= MF_MATCHONLY;
1056 map->map_mflags |= MF_APPEND;
1060 map->map_mflags |= MF_KEEPQUOTES;
1064 map->map_mflags |= MF_NODEFER;
1072 map->map_tapp = ++p;
1083 map->map_timeout = convtime(p, 's');
1090 while (isascii(*++p) && isspace(*p))
1092 map->map_retry = atoi(p);
1097 map->map_coldelim = *p;
1103 map->map_coldelim = '\n';
1107 map->map_coldelim = '\t';
1111 map->map_coldelim = '\\';
1117 while (isascii(*++p) && isspace(*p))
1119 map->map_sizelimit = atoi(p);
1122 /* Start of dns_map specific args */
1123 case 'R': /* search field */
1127 while (isascii(*++p) && isspace(*p))
1132 map_p->dns_m_type = dns_string_to_type(p);
1135 if (map_p->dns_m_type < 0)
1136 syserr("dns map %s: wrong type %s",
1141 case 'B': /* base domain */
1145 while (isascii(*++p) && isspace(*p))
1152 ** slight abuse of map->map_file; it isn't
1153 ** used otherwise in this map type.
1156 map->map_file = newstr(p);
1162 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
1167 if (map_p->dns_m_type < 0)
1168 syserr("dns map %s: missing -R type", map->map_mname);
1169 if (map->map_app != NULL)
1170 map->map_app = newstr(map->map_app);
1171 if (map->map_tapp != NULL)
1172 map->map_tapp = newstr(map->map_tapp);
1175 ** Assumption: assert(sizeof(int) <= sizeof(ARBPTR_T));
1176 ** Even if this assumption is wrong, we use only one byte,
1177 ** so it doesn't really matter.
1180 map->map_db1 = (ARBPTR_T) map_p;
1185 ** DNS_MAP_LOOKUP -- perform dns map lookup.
1188 ** map -- pointer to MAP
1189 ** name -- name to lookup
1190 ** av -- arguments to interpolate into buf.
1191 ** statp -- pointer to status (EX_)
1194 ** result of lookup if succeeded.
1195 ** NULL -- otherwise.
1199 dns_map_lookup(map, name, av, statp)
1206 char *vp = NULL, *result = NULL;
1208 struct dns_map *map_p;
1209 RESOURCE_RECORD_T *rr = NULL;
1210 DNS_REPLY_T *r = NULL;
1212 static char buf6[INET6_ADDRSTRLEN];
1213 # endif /* NETINET6 */
1216 sm_dprintf("dns_map_lookup(%s, %s)\n",
1217 map->map_mname, name);
1219 map_p = (struct dns_map *)(map->map_db1);
1220 if (map->map_file != NULL && *map->map_file != '\0')
1225 len = strlen(map->map_file) + strlen(name) + 2;
1226 appdomain = (char *) sm_malloc(len);
1227 if (appdomain == NULL)
1229 *statp = EX_UNAVAILABLE;
1232 (void) sm_strlcpyn(appdomain, len, 3, name, ".", map->map_file);
1233 r = dns_lookup_int(appdomain, C_IN, map_p->dns_m_type,
1234 map->map_timeout, map->map_retry);
1239 r = dns_lookup_int(name, C_IN, map_p->dns_m_type,
1240 map->map_timeout, map->map_retry);
1246 if (h_errno == TRY_AGAIN || transienterror(errno))
1247 *statp = EX_TEMPFAIL;
1249 *statp = EX_NOTFOUND;
1253 for (rr = r->dns_r_head; rr != NULL; rr = rr->rr_next)
1258 switch (rr->rr_type)
1262 value = rr->rr_u.rr_txt;
1266 value = rr->rr_u.rr_txt;
1270 value = rr->rr_u.rr_mx->mx_r_domain;
1274 value = rr->rr_u.rr_srv->srv_r_target;
1278 value = rr->rr_u.rr_txt;
1282 value = rr->rr_u.rr_txt;
1286 value = rr->rr_u.rr_mx->mx_r_domain;
1291 value = inet_ntoa(*(rr->rr_u.rr_a));
1293 # endif /* NETINET */
1297 value = anynet_ntop(rr->rr_u.rr_aaaa, buf6,
1300 # endif /* NETINET6 */
1303 (void) strreplnonprt(value, 'X');
1304 if (map_p->dns_m_type != rr->rr_type)
1307 sm_dprintf("\tskipping type %s (%d) value %s\n",
1308 type != NULL ? type : "<UNKNOWN>",
1310 value != NULL ? value : "<NO VALUE>");
1315 if (rr->rr_type == T_AAAA && value == NULL)
1318 *statp = EX_DATAERR;
1320 sm_dprintf("\tbad T_AAAA conversion\n");
1323 # endif /* NETINET6 */
1325 sm_dprintf("\tfound type %s (%d) value %s\n",
1326 type != NULL ? type : "<UNKNOWN>",
1328 value != NULL ? value : "<NO VALUE>");
1329 if (value != NULL &&
1330 (map->map_coldelim == '\0' ||
1331 map->map_sizelimit == 1 ||
1332 bitset(MF_MATCHONLY, map->map_mflags)))
1334 /* Only care about the first match */
1338 else if (vp == NULL)
1345 /* concatenate the results */
1349 sz = strlen(vp) + strlen(value) + 2;
1351 (void) sm_snprintf(new, sz, "%s%c%s",
1352 vp, map->map_coldelim, value);
1355 if (map->map_sizelimit > 0 &&
1356 ++resnum >= map->map_sizelimit)
1363 *statp = EX_NOTFOUND;
1365 sm_dprintf("\tno match found\n");
1369 /* Cleanly truncate for rulesets */
1370 truncate_at_delim(vp, PSBUFSIZE / 2, map->map_coldelim);
1375 sm_syslog(LOG_INFO, CurEnv->e_id, "dns %.100s => %s",
1377 if (bitset(MF_MATCHONLY, map->map_mflags))
1378 result = map_rewrite(map, name, strlen(name), NULL);
1380 result = map_rewrite(map, vp, vsize, av);
1389 # endif /* DNSMAP */
1390 #endif /* NAMED_BIND */
1399 ** NDBM_MAP_OPEN -- DBM-style map open
1403 ndbm_map_open(map, mode)
1413 int smode = S_IREAD;
1414 char dirfile[MAXPATHLEN];
1415 char pagfile[MAXPATHLEN];
1417 struct stat std, stp;
1420 sm_dprintf("ndbm_map_open(%s, %s, %d)\n",
1421 map->map_mname, map->map_file, mode);
1422 map->map_lockfd = -1;
1425 /* do initial file and directory checks */
1426 if (sm_strlcpyn(dirfile, sizeof(dirfile), 2,
1427 map->map_file, ".dir") >= sizeof(dirfile) ||
1428 sm_strlcpyn(pagfile, sizeof(pagfile), 2,
1429 map->map_file, ".pag") >= sizeof(pagfile))
1432 if (!bitset(MF_OPTIONAL, map->map_mflags))
1433 syserr("dbm map \"%s\": map file %s name too long",
1434 map->map_mname, map->map_file);
1437 sff = SFF_ROOTOK|SFF_REGONLY;
1441 if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail))
1443 if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail))
1449 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
1452 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
1453 sff |= SFF_SAFEDIRPATH;
1454 ret = safefile(dirfile, RunAsUid, RunAsGid, RunAsUserName,
1457 ret = safefile(pagfile, RunAsUid, RunAsGid, RunAsUserName,
1462 char *prob = "unsafe";
1464 /* cannot open this map */
1468 sm_dprintf("\t%s map file: %d\n", prob, ret);
1469 if (!bitset(MF_OPTIONAL, map->map_mflags))
1470 syserr("dbm map \"%s\": %s map file %s",
1471 map->map_mname, prob, map->map_file);
1474 if (std.st_mode == ST_MODE_NOFILE)
1475 mode |= O_CREAT|O_EXCL;
1478 if (mode == O_RDONLY)
1481 mode |= O_TRUNC|O_EXLOCK;
1482 # else /* LOCK_ON_OPEN */
1483 if ((mode & O_ACCMODE) == O_RDWR)
1487 ** Warning: race condition. Try to lock the file as
1488 ** quickly as possible after opening it.
1489 ** This may also have security problems on some systems,
1490 ** but there isn't anything we can do about it.
1494 # else /* NOFTRUNCATE */
1496 ** This ugly code opens the map without truncating it,
1497 ** locks the file, then truncates it. Necessary to
1498 ** avoid race conditions.
1503 long sff = SFF_CREAT|SFF_OPENASROOT;
1505 if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail))
1507 if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail))
1510 dirfd = safeopen(dirfile, mode, DBMMODE, sff);
1511 pagfd = safeopen(pagfile, mode, DBMMODE, sff);
1513 if (dirfd < 0 || pagfd < 0)
1517 (void) close(dirfd);
1519 (void) close(pagfd);
1521 syserr("ndbm_map_open: cannot create database %s",
1525 if (ftruncate(dirfd, (off_t) 0) < 0 ||
1526 ftruncate(pagfd, (off_t) 0) < 0)
1529 (void) close(dirfd);
1530 (void) close(pagfd);
1532 syserr("ndbm_map_open: cannot truncate %s.{dir,pag}",
1537 /* if new file, get "before" bits for later filechanged check */
1538 if (std.st_mode == ST_MODE_NOFILE &&
1539 (fstat(dirfd, &std) < 0 || fstat(pagfd, &stp) < 0))
1542 (void) close(dirfd);
1543 (void) close(pagfd);
1545 syserr("ndbm_map_open(%s.{dir,pag}): cannot fstat pre-opened file",
1550 /* have to save the lock for the duration (bletch) */
1551 map->map_lockfd = dirfd;
1552 (void) close(pagfd);
1554 /* twiddle bits for dbm_open */
1555 mode &= ~(O_CREAT|O_EXCL);
1556 # endif /* NOFTRUNCATE */
1558 # endif /* LOCK_ON_OPEN */
1560 /* open the database */
1561 dbm = dbm_open(map->map_file, mode, DBMMODE);
1565 if (bitset(MF_ALIAS, map->map_mflags) &&
1566 aliaswait(map, ".pag", false))
1568 # if !LOCK_ON_OPEN && !NOFTRUNCATE
1569 if (map->map_lockfd >= 0)
1570 (void) close(map->map_lockfd);
1571 # endif /* !LOCK_ON_OPEN && !NOFTRUNCATE */
1573 if (!bitset(MF_OPTIONAL, map->map_mflags))
1574 syserr("Cannot open DBM database %s", map->map_file);
1577 dfd = dbm_dirfno(dbm);
1578 pfd = dbm_pagfno(dbm);
1581 /* heuristic: if files are linked, this is actually gdbm */
1583 # if !LOCK_ON_OPEN && !NOFTRUNCATE
1584 if (map->map_lockfd >= 0)
1585 (void) close(map->map_lockfd);
1586 # endif /* !LOCK_ON_OPEN && !NOFTRUNCATE */
1588 syserr("dbm map \"%s\": cannot support GDBM",
1593 if (filechanged(dirfile, dfd, &std) ||
1594 filechanged(pagfile, pfd, &stp))
1598 # if !LOCK_ON_OPEN && !NOFTRUNCATE
1599 if (map->map_lockfd >= 0)
1600 (void) close(map->map_lockfd);
1601 # endif /* !LOCK_ON_OPEN && !NOFTRUNCATE */
1603 syserr("ndbm_map_open(%s): file changed after open",
1608 map->map_db1 = (ARBPTR_T) dbm;
1611 ** Need to set map_mtime before the call to aliaswait()
1612 ** as aliaswait() will call map_lookup() which requires
1613 ** map_mtime to be set
1616 if (fstat(pfd, &st) >= 0)
1617 map->map_mtime = st.st_mtime;
1619 if (mode == O_RDONLY)
1623 (void) lockfile(dfd, map->map_file, ".dir", LOCK_UN);
1625 (void) lockfile(pfd, map->map_file, ".pag", LOCK_UN);
1626 # endif /* LOCK_ON_OPEN */
1627 if (bitset(MF_ALIAS, map->map_mflags) &&
1628 !aliaswait(map, ".pag", true))
1633 map->map_mflags |= MF_LOCKED;
1634 if (geteuid() == 0 && TrustedUid != 0)
1637 if (fchown(dfd, TrustedUid, -1) < 0 ||
1638 fchown(pfd, TrustedUid, -1) < 0)
1642 sm_syslog(LOG_ALERT, NOQID,
1643 "ownership change on %s failed: %s",
1644 map->map_file, sm_errstring(err));
1645 message("050 ownership change on %s failed: %s",
1646 map->map_file, sm_errstring(err));
1648 # else /* HASFCHOWN */
1649 sm_syslog(LOG_ALERT, NOQID,
1650 "no fchown(): cannot change ownership on %s",
1652 message("050 no fchown(): cannot change ownership on %s",
1654 # endif /* HASFCHOWN */
1662 ** NDBM_MAP_LOOKUP -- look up a datum in a DBM-type map
1666 ndbm_map_lookup(map, name, av, statp)
1674 char keybuf[MAXNAME + 1];
1678 sm_dprintf("ndbm_map_lookup(%s, %s)\n",
1679 map->map_mname, name);
1682 key.dsize = strlen(name);
1683 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
1685 if (key.dsize > sizeof(keybuf) - 1)
1686 key.dsize = sizeof(keybuf) - 1;
1687 memmove(keybuf, key.dptr, key.dsize);
1688 keybuf[key.dsize] = '\0';
1693 dfd = dbm_dirfno((DBM *) map->map_db1);
1694 if (dfd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
1695 (void) lockfile(dfd, map->map_file, ".dir", LOCK_SH);
1696 pfd = dbm_pagfno((DBM *) map->map_db1);
1697 if (pfd < 0 || fstat(pfd, &stbuf) < 0 ||
1698 stbuf.st_mtime > map->map_mtime)
1700 /* Reopen the database to sync the cache */
1701 int omode = bitset(map->map_mflags, MF_WRITABLE) ? O_RDWR
1704 if (dfd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
1705 (void) lockfile(dfd, map->map_file, ".dir", LOCK_UN);
1706 map->map_mflags |= MF_CLOSING;
1707 map->map_class->map_close(map);
1708 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
1709 if (map->map_class->map_open(map, omode))
1711 map->map_mflags |= MF_OPEN;
1712 map->map_pid = CurrentPid;
1713 if ((omode & O_ACCMODE) == O_RDWR)
1714 map->map_mflags |= MF_WRITABLE;
1719 if (!bitset(MF_OPTIONAL, map->map_mflags))
1721 extern MAPCLASS BogusMapClass;
1723 *statp = EX_TEMPFAIL;
1724 map->map_orgclass = map->map_class;
1725 map->map_class = &BogusMapClass;
1726 map->map_mflags |= MF_OPEN;
1727 map->map_pid = CurrentPid;
1728 syserr("Cannot reopen NDBM database %s",
1735 if (bitset(MF_TRY0NULL, map->map_mflags))
1737 val = dbm_fetch((DBM *) map->map_db1, key);
1738 if (val.dptr != NULL)
1739 map->map_mflags &= ~MF_TRY1NULL;
1741 if (val.dptr == NULL && bitset(MF_TRY1NULL, map->map_mflags))
1744 val = dbm_fetch((DBM *) map->map_db1, key);
1745 if (val.dptr != NULL)
1746 map->map_mflags &= ~MF_TRY0NULL;
1748 if (dfd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
1749 (void) lockfile(dfd, map->map_file, ".dir", LOCK_UN);
1750 if (val.dptr == NULL)
1752 if (bitset(MF_MATCHONLY, map->map_mflags))
1753 return map_rewrite(map, name, strlen(name), NULL);
1755 return map_rewrite(map, val.dptr, val.dsize, av);
1760 ** NDBM_MAP_STORE -- store a datum in the database
1764 ndbm_map_store(map, lhs, rhs)
1772 char keybuf[MAXNAME + 1];
1775 sm_dprintf("ndbm_map_store(%s, %s, %s)\n",
1776 map->map_mname, lhs, rhs);
1778 key.dsize = strlen(lhs);
1780 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
1782 if (key.dsize > sizeof(keybuf) - 1)
1783 key.dsize = sizeof(keybuf) - 1;
1784 memmove(keybuf, key.dptr, key.dsize);
1785 keybuf[key.dsize] = '\0';
1790 data.dsize = strlen(rhs);
1793 if (bitset(MF_INCLNULL, map->map_mflags))
1799 status = dbm_store((DBM *) map->map_db1, key, data, DBM_INSERT);
1802 if (!bitset(MF_APPEND, map->map_mflags))
1803 message("050 Warning: duplicate alias name %s", lhs);
1806 static char *buf = NULL;
1807 static int bufsiz = 0;
1811 old.dptr = ndbm_map_lookup(map, key.dptr,
1812 (char **) NULL, &xstat);
1813 if (old.dptr != NULL && *(char *) old.dptr != '\0')
1815 old.dsize = strlen(old.dptr);
1816 if (data.dsize + old.dsize + 2 > bufsiz)
1819 (void) sm_free(buf);
1820 bufsiz = data.dsize + old.dsize + 2;
1821 buf = sm_pmalloc_x(bufsiz);
1823 (void) sm_strlcpyn(buf, bufsiz, 3,
1824 data.dptr, ",", old.dptr);
1825 data.dsize = data.dsize + old.dsize + 1;
1828 sm_dprintf("ndbm_map_store append=%s\n",
1832 status = dbm_store((DBM *) map->map_db1,
1833 key, data, DBM_REPLACE);
1836 syserr("readaliases: dbm put (%s): %d", lhs, status);
1841 ** NDBM_MAP_CLOSE -- close the database
1849 sm_dprintf("ndbm_map_close(%s, %s, %lx)\n",
1850 map->map_mname, map->map_file, map->map_mflags);
1852 if (bitset(MF_WRITABLE, map->map_mflags))
1854 # ifdef NDBM_YP_COMPAT
1856 char buf[MAXHOSTNAMELEN];
1858 inclnull = bitset(MF_INCLNULL, map->map_mflags);
1859 map->map_mflags &= ~MF_INCLNULL;
1861 if (strstr(map->map_file, "/yp/") != NULL)
1863 long save_mflags = map->map_mflags;
1865 map->map_mflags |= MF_NOFOLDCASE;
1867 (void) sm_snprintf(buf, sizeof(buf), "%010ld", curtime());
1868 ndbm_map_store(map, "YP_LAST_MODIFIED", buf);
1870 (void) gethostname(buf, sizeof(buf));
1871 ndbm_map_store(map, "YP_MASTER_NAME", buf);
1873 map->map_mflags = save_mflags;
1877 map->map_mflags |= MF_INCLNULL;
1878 # endif /* NDBM_YP_COMPAT */
1880 /* write out the distinguished alias */
1881 ndbm_map_store(map, "@", "@");
1883 dbm_close((DBM *) map->map_db1);
1885 /* release lock (if needed) */
1887 if (map->map_lockfd >= 0)
1888 (void) close(map->map_lockfd);
1889 # endif /* !LOCK_ON_OPEN */
1894 ** NEWDB (Hash and BTree) Modules
1900 ** BT_MAP_OPEN, HASH_MAP_OPEN -- database open primitives.
1902 ** These do rather bizarre locking. If you can lock on open,
1903 ** do that to avoid the condition of opening a database that
1904 ** is being rebuilt. If you don't, we'll try to fake it, but
1905 ** there will be a race condition. If opening for read-only,
1906 ** we immediately release the lock to avoid freezing things up.
1907 ** We really ought to hold the lock, but guarantee that we won't
1908 ** be pokey about it. That's hard to do.
1911 /* these should be K line arguments */
1912 # if DB_VERSION_MAJOR < 2
1913 # define db_cachesize cachesize
1914 # define h_nelem nelem
1915 # ifndef DB_CACHE_SIZE
1916 # define DB_CACHE_SIZE (1024 * 1024) /* database memory cache size */
1917 # endif /* ! DB_CACHE_SIZE */
1918 # ifndef DB_HASH_NELEM
1919 # define DB_HASH_NELEM 4096 /* (starting) size of hash table */
1920 # endif /* ! DB_HASH_NELEM */
1921 # endif /* DB_VERSION_MAJOR < 2 */
1924 bt_map_open(map, mode)
1928 # if DB_VERSION_MAJOR < 2
1930 # endif /* DB_VERSION_MAJOR < 2 */
1931 # if DB_VERSION_MAJOR == 2
1933 # endif /* DB_VERSION_MAJOR == 2 */
1934 # if DB_VERSION_MAJOR > 2
1935 void *btinfo = NULL;
1936 # endif /* DB_VERSION_MAJOR > 2 */
1939 sm_dprintf("bt_map_open(%s, %s, %d)\n",
1940 map->map_mname, map->map_file, mode);
1942 # if DB_VERSION_MAJOR < 3
1943 memset(&btinfo, '\0', sizeof(btinfo));
1944 # ifdef DB_CACHE_SIZE
1945 btinfo.db_cachesize = DB_CACHE_SIZE;
1946 # endif /* DB_CACHE_SIZE */
1947 # endif /* DB_VERSION_MAJOR < 3 */
1949 return db_map_open(map, mode, "btree", DB_BTREE, &btinfo);
1953 hash_map_open(map, mode)
1957 # if DB_VERSION_MAJOR < 2
1959 # endif /* DB_VERSION_MAJOR < 2 */
1960 # if DB_VERSION_MAJOR == 2
1962 # endif /* DB_VERSION_MAJOR == 2 */
1963 # if DB_VERSION_MAJOR > 2
1965 # endif /* DB_VERSION_MAJOR > 2 */
1968 sm_dprintf("hash_map_open(%s, %s, %d)\n",
1969 map->map_mname, map->map_file, mode);
1971 # if DB_VERSION_MAJOR < 3
1972 memset(&hinfo, '\0', sizeof(hinfo));
1973 # ifdef DB_HASH_NELEM
1974 hinfo.h_nelem = DB_HASH_NELEM;
1975 # endif /* DB_HASH_NELEM */
1976 # ifdef DB_CACHE_SIZE
1977 hinfo.db_cachesize = DB_CACHE_SIZE;
1978 # endif /* DB_CACHE_SIZE */
1979 # endif /* DB_VERSION_MAJOR < 3 */
1981 return db_map_open(map, mode, "hash", DB_HASH, &hinfo);
1985 db_map_open(map, mode, mapclassname, dbtype, openinfo)
1990 # if DB_VERSION_MAJOR < 2
1991 const void *openinfo;
1992 # endif /* DB_VERSION_MAJOR < 2 */
1993 # if DB_VERSION_MAJOR == 2
1995 # endif /* DB_VERSION_MAJOR == 2 */
1996 # if DB_VERSION_MAJOR > 2
1998 # endif /* DB_VERSION_MAJOR > 2 */
2003 int smode = S_IREAD;
2008 char buf[MAXPATHLEN];
2010 /* do initial file and directory checks */
2011 if (sm_strlcpy(buf, map->map_file, sizeof(buf)) >= sizeof(buf))
2014 if (!bitset(MF_OPTIONAL, map->map_mflags))
2015 syserr("map \"%s\": map file %s name too long",
2016 map->map_mname, map->map_file);
2020 if (i < 3 || strcmp(&buf[i - 3], ".db") != 0)
2022 if (sm_strlcat(buf, ".db", sizeof(buf)) >= sizeof(buf))
2025 if (!bitset(MF_OPTIONAL, map->map_mflags))
2026 syserr("map \"%s\": map file %s name too long",
2027 map->map_mname, map->map_file);
2035 sff = SFF_ROOTOK|SFF_REGONLY;
2039 if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail))
2041 if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail))
2047 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
2050 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
2051 sff |= SFF_SAFEDIRPATH;
2052 i = safefile(buf, RunAsUid, RunAsGid, RunAsUserName, sff, smode, &st);
2056 char *prob = "unsafe";
2058 /* cannot open this map */
2062 sm_dprintf("\t%s map file: %s\n", prob, sm_errstring(i));
2064 if (!bitset(MF_OPTIONAL, map->map_mflags))
2065 syserr("%s map \"%s\": %s map file %s",
2066 mapclassname, map->map_mname, prob, buf);
2069 if (st.st_mode == ST_MODE_NOFILE)
2070 omode |= O_CREAT|O_EXCL;
2072 map->map_lockfd = -1;
2076 omode |= O_TRUNC|O_EXLOCK;
2079 # else /* LOCK_ON_OPEN */
2081 ** Pre-lock the file to avoid race conditions. In particular,
2082 ** since dbopen returns NULL if the file is zero length, we
2083 ** must have a locked instance around the dbopen.
2086 fd = open(buf, omode, DBMMODE);
2089 if (!bitset(MF_OPTIONAL, map->map_mflags))
2090 syserr("db_map_open: cannot pre-open database %s", buf);
2094 /* make sure no baddies slipped in just before the open... */
2095 if (filechanged(buf, fd, &st))
2100 syserr("db_map_open(%s): file changed after pre-open", buf);
2104 /* if new file, get the "before" bits for later filechanged check */
2105 if (st.st_mode == ST_MODE_NOFILE && fstat(fd, &st) < 0)
2110 syserr("db_map_open(%s): cannot fstat pre-opened file",
2115 /* actually lock the pre-opened file */
2116 if (!lockfile(fd, buf, NULL, mode == O_RDONLY ? LOCK_SH : LOCK_EX))
2117 syserr("db_map_open: cannot lock %s", buf);
2119 /* set up mode bits for dbopen */
2122 omode &= ~(O_EXCL|O_CREAT);
2123 # endif /* LOCK_ON_OPEN */
2125 # if DB_VERSION_MAJOR < 2
2126 db = dbopen(buf, omode, DBMMODE, dbtype, openinfo);
2127 # else /* DB_VERSION_MAJOR < 2 */
2130 # if DB_VERSION_MAJOR > 2
2132 # endif /* DB_VERSION_MAJOR > 2 */
2134 if (mode == O_RDONLY)
2136 if (bitset(O_CREAT, omode))
2138 if (bitset(O_TRUNC, omode))
2139 flags |= DB_TRUNCATE;
2140 SM_DB_FLAG_ADD(flags);
2142 # if DB_VERSION_MAJOR > 2
2143 ret = db_create(&db, NULL, 0);
2144 # ifdef DB_CACHE_SIZE
2145 if (ret == 0 && db != NULL)
2147 ret = db->set_cachesize(db, 0, DB_CACHE_SIZE, 0);
2150 (void) db->close(db, 0);
2154 # endif /* DB_CACHE_SIZE */
2155 # ifdef DB_HASH_NELEM
2156 if (dbtype == DB_HASH && ret == 0 && db != NULL)
2158 ret = db->set_h_nelem(db, DB_HASH_NELEM);
2161 (void) db->close(db, 0);
2165 # endif /* DB_HASH_NELEM */
2166 if (ret == 0 && db != NULL)
2169 DBTXN /* transaction for DB 4.1 */
2170 buf, NULL, dbtype, flags, DBMMODE);
2173 #ifdef DB_OLD_VERSION
2174 if (ret == DB_OLD_VERSION)
2176 #endif /* DB_OLD_VERSION */
2177 (void) db->close(db, 0);
2182 # else /* DB_VERSION_MAJOR > 2 */
2183 errno = db_open(buf, dbtype, flags, DBMMODE,
2184 NULL, openinfo, &db);
2185 # endif /* DB_VERSION_MAJOR > 2 */
2187 # endif /* DB_VERSION_MAJOR < 2 */
2192 map->map_lockfd = fd;
2195 # endif /* !LOCK_ON_OPEN */
2199 if (mode == O_RDONLY && bitset(MF_ALIAS, map->map_mflags) &&
2200 aliaswait(map, ".db", false))
2203 if (map->map_lockfd >= 0)
2204 (void) close(map->map_lockfd);
2205 # endif /* !LOCK_ON_OPEN */
2207 if (!bitset(MF_OPTIONAL, map->map_mflags))
2208 syserr("Cannot open %s database %s",
2213 # if DB_VERSION_MAJOR < 2
2215 # else /* DB_VERSION_MAJOR < 2 */
2217 errno = db->fd(db, &fd);
2218 # endif /* DB_VERSION_MAJOR < 2 */
2219 if (filechanged(buf, fd, &st))
2222 # if DB_VERSION_MAJOR < 2
2223 (void) db->close(db);
2224 # else /* DB_VERSION_MAJOR < 2 */
2225 errno = db->close(db, 0);
2226 # endif /* DB_VERSION_MAJOR < 2 */
2228 if (map->map_lockfd >= 0)
2229 (void) close(map->map_lockfd);
2230 # endif /* !LOCK_ON_OPEN */
2232 syserr("db_map_open(%s): file changed after open", buf);
2237 map->map_mflags |= MF_LOCKED;
2239 if (fd >= 0 && mode == O_RDONLY)
2241 (void) lockfile(fd, buf, NULL, LOCK_UN);
2243 # endif /* LOCK_ON_OPEN */
2245 /* try to make sure that at least the database header is on disk */
2248 (void) db->sync(db, 0);
2249 if (geteuid() == 0 && TrustedUid != 0)
2252 if (fchown(fd, TrustedUid, -1) < 0)
2256 sm_syslog(LOG_ALERT, NOQID,
2257 "ownership change on %s failed: %s",
2258 buf, sm_errstring(err));
2259 message("050 ownership change on %s failed: %s",
2260 buf, sm_errstring(err));
2262 # else /* HASFCHOWN */
2263 sm_syslog(LOG_ALERT, NOQID,
2264 "no fchown(): cannot change ownership on %s",
2266 message("050 no fchown(): cannot change ownership on %s",
2268 # endif /* HASFCHOWN */
2272 map->map_db2 = (ARBPTR_T) db;
2275 ** Need to set map_mtime before the call to aliaswait()
2276 ** as aliaswait() will call map_lookup() which requires
2277 ** map_mtime to be set
2280 if (fd >= 0 && fstat(fd, &st) >= 0)
2281 map->map_mtime = st.st_mtime;
2283 if (mode == O_RDONLY && bitset(MF_ALIAS, map->map_mflags) &&
2284 !aliaswait(map, ".db", true))
2291 ** DB_MAP_LOOKUP -- look up a datum in a BTREE- or HASH-type map
2295 db_map_lookup(map, name, av, statp)
2302 register DB *db = (DB *) map->map_db2;
2308 char keybuf[MAXNAME + 1];
2309 char buf[MAXPATHLEN];
2311 memset(&key, '\0', sizeof(key));
2312 memset(&val, '\0', sizeof(val));
2315 sm_dprintf("db_map_lookup(%s, %s)\n",
2316 map->map_mname, name);
2318 if (sm_strlcpy(buf, map->map_file, sizeof(buf)) >= sizeof(buf))
2321 if (!bitset(MF_OPTIONAL, map->map_mflags))
2322 syserr("map \"%s\": map file %s name too long",
2323 map->map_mname, map->map_file);
2327 if (i > 3 && strcmp(&buf[i - 3], ".db") == 0)
2330 key.size = strlen(name);
2331 if (key.size > sizeof(keybuf) - 1)
2332 key.size = sizeof(keybuf) - 1;
2334 memmove(keybuf, name, key.size);
2335 keybuf[key.size] = '\0';
2336 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
2339 # if DB_VERSION_MAJOR < 2
2341 # else /* DB_VERSION_MAJOR < 2 */
2343 errno = db->fd(db, &fd);
2344 # endif /* DB_VERSION_MAJOR < 2 */
2345 if (fd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
2346 (void) lockfile(fd, buf, ".db", LOCK_SH);
2347 if (fd < 0 || fstat(fd, &stbuf) < 0 || stbuf.st_mtime > map->map_mtime)
2349 /* Reopen the database to sync the cache */
2350 int omode = bitset(map->map_mflags, MF_WRITABLE) ? O_RDWR
2353 if (fd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
2354 (void) lockfile(fd, buf, ".db", LOCK_UN);
2355 map->map_mflags |= MF_CLOSING;
2356 map->map_class->map_close(map);
2357 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
2358 if (map->map_class->map_open(map, omode))
2360 map->map_mflags |= MF_OPEN;
2361 map->map_pid = CurrentPid;
2362 if ((omode & O_ACCMODE) == O_RDWR)
2363 map->map_mflags |= MF_WRITABLE;
2364 db = (DB *) map->map_db2;
2369 if (!bitset(MF_OPTIONAL, map->map_mflags))
2371 extern MAPCLASS BogusMapClass;
2373 *statp = EX_TEMPFAIL;
2374 map->map_orgclass = map->map_class;
2375 map->map_class = &BogusMapClass;
2376 map->map_mflags |= MF_OPEN;
2377 map->map_pid = CurrentPid;
2378 syserr("Cannot reopen DB database %s",
2386 if (bitset(MF_TRY0NULL, map->map_mflags))
2388 # if DB_VERSION_MAJOR < 2
2389 st = db->get(db, &key, &val, 0);
2390 # else /* DB_VERSION_MAJOR < 2 */
2391 errno = db->get(db, NULL, &key, &val, 0);
2407 # endif /* DB_VERSION_MAJOR < 2 */
2409 map->map_mflags &= ~MF_TRY1NULL;
2411 if (st != 0 && bitset(MF_TRY1NULL, map->map_mflags))
2414 # if DB_VERSION_MAJOR < 2
2415 st = db->get(db, &key, &val, 0);
2416 # else /* DB_VERSION_MAJOR < 2 */
2417 errno = db->get(db, NULL, &key, &val, 0);
2433 # endif /* DB_VERSION_MAJOR < 2 */
2435 map->map_mflags &= ~MF_TRY0NULL;
2438 if (fd >= 0 && !bitset(MF_LOCKED, map->map_mflags))
2439 (void) lockfile(fd, buf, ".db", LOCK_UN);
2444 syserr("db_map_lookup: get (%s)", name);
2447 if (bitset(MF_MATCHONLY, map->map_mflags))
2448 return map_rewrite(map, name, strlen(name), NULL);
2450 return map_rewrite(map, val.data, val.size, av);
2455 ** DB_MAP_STORE -- store a datum in the NEWDB database
2459 db_map_store(map, lhs, rhs)
2467 register DB *db = map->map_db2;
2468 char keybuf[MAXNAME + 1];
2470 memset(&key, '\0', sizeof(key));
2471 memset(&data, '\0', sizeof(data));
2474 sm_dprintf("db_map_store(%s, %s, %s)\n",
2475 map->map_mname, lhs, rhs);
2477 key.size = strlen(lhs);
2479 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
2481 if (key.size > sizeof(keybuf) - 1)
2482 key.size = sizeof(keybuf) - 1;
2483 memmove(keybuf, key.data, key.size);
2484 keybuf[key.size] = '\0';
2489 data.size = strlen(rhs);
2492 if (bitset(MF_INCLNULL, map->map_mflags))
2498 # if DB_VERSION_MAJOR < 2
2499 status = db->put(db, &key, &data, R_NOOVERWRITE);
2500 # else /* DB_VERSION_MAJOR < 2 */
2501 errno = db->put(db, NULL, &key, &data, DB_NOOVERWRITE);
2516 # endif /* DB_VERSION_MAJOR < 2 */
2519 if (!bitset(MF_APPEND, map->map_mflags))
2520 message("050 Warning: duplicate alias name %s", lhs);
2523 static char *buf = NULL;
2524 static int bufsiz = 0;
2527 memset(&old, '\0', sizeof(old));
2529 old.data = db_map_lookup(map, key.data,
2530 (char **) NULL, &status);
2531 if (old.data != NULL)
2533 old.size = strlen(old.data);
2534 if (data.size + old.size + 2 > (size_t) bufsiz)
2538 bufsiz = data.size + old.size + 2;
2539 buf = sm_pmalloc_x(bufsiz);
2541 (void) sm_strlcpyn(buf, bufsiz, 3,
2542 (char *) data.data, ",",
2544 data.size = data.size + old.size + 1;
2547 sm_dprintf("db_map_store append=%s\n",
2548 (char *) data.data);
2551 # if DB_VERSION_MAJOR < 2
2552 status = db->put(db, &key, &data, 0);
2553 # else /* DB_VERSION_MAJOR < 2 */
2554 status = errno = db->put(db, NULL, &key, &data, 0);
2555 # endif /* DB_VERSION_MAJOR < 2 */
2558 syserr("readaliases: db put (%s)", lhs);
2563 ** DB_MAP_CLOSE -- add distinguished entries and close the database
2570 register DB *db = map->map_db2;
2573 sm_dprintf("db_map_close(%s, %s, %lx)\n",
2574 map->map_mname, map->map_file, map->map_mflags);
2576 if (bitset(MF_WRITABLE, map->map_mflags))
2578 /* write out the distinguished alias */
2579 db_map_store(map, "@", "@");
2582 (void) db->sync(db, 0);
2585 if (map->map_lockfd >= 0)
2586 (void) close(map->map_lockfd);
2587 # endif /* !LOCK_ON_OPEN */
2589 # if DB_VERSION_MAJOR < 2
2590 if (db->close(db) != 0)
2591 # else /* DB_VERSION_MAJOR < 2 */
2593 ** Berkeley DB can use internal shared memory
2594 ** locking for its memory pool. Closing a map
2595 ** opened by another process will interfere
2596 ** with the shared memory and locks of the parent
2597 ** process leaving things in a bad state.
2601 ** If this map was not opened by the current
2602 ** process, do not close the map but recover
2603 ** the file descriptor.
2606 if (map->map_pid != CurrentPid)
2610 errno = db->fd(db, &fd);
2616 if ((errno = db->close(db, 0)) != 0)
2617 # endif /* DB_VERSION_MAJOR < 2 */
2618 syserr("db_map_close(%s, %s, %lx): db close failure",
2619 map->map_mname, map->map_file, map->map_mflags);
2629 # define YPERR_BUSY 16
2630 # endif /* ! YPERR_BUSY */
2633 ** NIS_MAP_OPEN -- open DBM map
2637 nis_map_open(map, mode)
2647 sm_dprintf("nis_map_open(%s, %s, %d)\n",
2648 map->map_mname, map->map_file, mode);
2651 if (mode != O_RDONLY)
2653 /* issue a pseudo-error message */
2654 errno = SM_EMAPCANTWRITE;
2658 p = strchr(map->map_file, '@');
2663 map->map_domain = p;
2666 if (*map->map_file == '\0')
2667 map->map_file = "mail.aliases";
2669 if (map->map_domain == NULL)
2671 yperr = yp_get_default_domain(&map->map_domain);
2674 if (!bitset(MF_OPTIONAL, map->map_mflags))
2675 syserr("451 4.3.5 NIS map %s specified, but NIS not running",
2681 /* check to see if this map actually exists */
2683 yperr = yp_match(map->map_domain, map->map_file, "@", 1,
2686 sm_dprintf("nis_map_open: yp_match(@, %s, %s) => %s\n",
2687 map->map_domain, map->map_file, yperr_string(yperr));
2691 if (yperr == 0 || yperr == YPERR_KEY || yperr == YPERR_BUSY)
2694 ** We ought to be calling aliaswait() here if this is an
2695 ** alias file, but powerful HP-UX NIS servers apparently
2696 ** don't insert the @:@ token into the alias map when it
2697 ** is rebuilt, so aliaswait() just hangs. I hate HP-UX.
2701 if (!bitset(MF_ALIAS, map->map_mflags) ||
2702 aliaswait(map, NULL, true))
2707 if (!bitset(MF_OPTIONAL, map->map_mflags))
2709 syserr("451 4.3.5 Cannot bind to map %s in domain %s: %s",
2710 map->map_file, map->map_domain, yperr_string(yperr));
2718 ** NIS_MAP_LOOKUP -- look up a datum in a NIS map
2723 nis_map_lookup(map, name, av, statp)
2733 char keybuf[MAXNAME + 1];
2734 char *SM_NONVOLATILE result = NULL;
2737 sm_dprintf("nis_map_lookup(%s, %s)\n",
2738 map->map_mname, name);
2740 buflen = strlen(name);
2741 if (buflen > sizeof(keybuf) - 1)
2742 buflen = sizeof(keybuf) - 1;
2743 memmove(keybuf, name, buflen);
2744 keybuf[buflen] = '\0';
2745 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
2749 if (bitset(MF_TRY0NULL, map->map_mflags))
2751 yperr = yp_match(map->map_domain, map->map_file, keybuf, buflen,
2754 map->map_mflags &= ~MF_TRY1NULL;
2756 if (yperr == YPERR_KEY && bitset(MF_TRY1NULL, map->map_mflags))
2760 yperr = yp_match(map->map_domain, map->map_file, keybuf, buflen,
2763 map->map_mflags &= ~MF_TRY0NULL;
2767 if (yperr != YPERR_KEY && yperr != YPERR_BUSY)
2768 map->map_mflags &= ~(MF_VALID|MF_OPEN);
2774 if (bitset(MF_MATCHONLY, map->map_mflags))
2775 result = map_rewrite(map, name, strlen(name), NULL);
2777 result = map_rewrite(map, vp, vsize, av);
2787 ** NIS_GETCANONNAME -- look up canonical name in NIS
2791 nis_getcanonname(name, hbsize, statp)
2800 static bool try0null = true;
2801 static bool try1null = true;
2802 static char *yp_domain = NULL;
2803 char host_record[MAXLINE];
2805 char nbuf[MAXNAME + 1];
2808 sm_dprintf("nis_getcanonname(%s)\n", name);
2810 if (sm_strlcpy(nbuf, name, sizeof(nbuf)) >= sizeof(nbuf))
2812 *statp = EX_UNAVAILABLE;
2815 (void) shorten_hostname(nbuf);
2816 keylen = strlen(nbuf);
2818 if (yp_domain == NULL)
2819 (void) yp_get_default_domain(&yp_domain);
2825 yperr = yp_match(yp_domain, "hosts.byname", nbuf, keylen,
2830 if (yperr == YPERR_KEY && try1null)
2834 yperr = yp_match(yp_domain, "hosts.byname", nbuf, keylen,
2841 if (yperr == YPERR_KEY)
2843 else if (yperr == YPERR_BUSY)
2844 *statp = EX_TEMPFAIL;
2846 *statp = EX_UNAVAILABLE;
2851 (void) sm_strlcpy(host_record, vp, sizeof(host_record));
2854 sm_dprintf("got record `%s'\n", host_record);
2855 vp = strpbrk(host_record, "#\n");
2858 if (!extract_canonname(nbuf, NULL, host_record, cbuf, sizeof(cbuf)))
2860 /* this should not happen, but.... */
2864 if (sm_strlcpy(name, cbuf, hbsize) >= hbsize)
2866 *statp = EX_UNAVAILABLE;
2877 ** This code donated by Sun Microsystems.
2882 # undef NIS /* symbol conflict in nis.h */
2883 # undef T_UNSPEC /* symbol conflict in nis.h -> ... -> sys/tiuser.h */
2884 # include <rpcsvc/nis.h>
2885 # include <rpcsvc/nislib.h>
2886 # ifndef NIS_TABLE_OBJ
2887 # define NIS_TABLE_OBJ TABLE_OBJ
2888 # endif /* NIS_TABLE_OBJ */
2890 # define EN_col(col) zo_data.objdata_u.en_data.en_cols.en_cols_val[(col)].ec_value.ec_value_val
2891 # define COL_NAME(res,i) ((res->objects.objects_val)->TA_data.ta_cols.ta_cols_val)[i].tc_name
2892 # define COL_MAX(res) ((res->objects.objects_val)->TA_data.ta_cols.ta_cols_len)
2893 # define PARTIAL_NAME(x) ((x)[strlen(x) - 1] != '.')
2896 ** NISPLUS_MAP_OPEN -- open nisplus table
2900 nisplus_map_open(map, mode)
2904 nis_result *res = NULL;
2905 int retry_cnt, max_col, i;
2906 char qbuf[MAXLINE + NIS_MAXNAMELEN];
2909 sm_dprintf("nisplus_map_open(%s, %s, %d)\n",
2910 map->map_mname, map->map_file, mode);
2913 if (mode != O_RDONLY)
2919 if (*map->map_file == '\0')
2920 map->map_file = "mail_aliases.org_dir";
2922 if (PARTIAL_NAME(map->map_file) && map->map_domain == NULL)
2924 /* set default NISPLUS Domain to $m */
2925 map->map_domain = newstr(nisplus_default_domain());
2927 sm_dprintf("nisplus_map_open(%s): using domain %s\n",
2928 map->map_file, map->map_domain);
2930 if (!PARTIAL_NAME(map->map_file))
2932 map->map_domain = newstr("");
2933 (void) sm_strlcpy(qbuf, map->map_file, sizeof(qbuf));
2937 /* check to see if this map actually exists */
2938 (void) sm_strlcpyn(qbuf, sizeof(qbuf), 3,
2939 map->map_file, ".", map->map_domain);
2943 while (res == NULL || res->status != NIS_SUCCESS)
2945 res = nis_lookup(qbuf, FOLLOW_LINKS);
2946 switch (res->status)
2953 case NIS_NAMEUNREACHABLE:
2954 if (retry_cnt++ > 4)
2959 /* try not to overwhelm hosed server */
2963 default: /* all other nisplus errors */
2965 if (!bitset(MF_OPTIONAL, map->map_mflags))
2966 syserr("451 4.3.5 Cannot find table %s.%s: %s",
2967 map->map_file, map->map_domain,
2968 nis_sperrno(res->status));
2975 if (NIS_RES_NUMOBJ(res) != 1 ||
2976 (NIS_RES_OBJECT(res)->zo_data.zo_type != NIS_TABLE_OBJ))
2979 sm_dprintf("nisplus_map_open: %s is not a table\n", qbuf);
2981 if (!bitset(MF_OPTIONAL, map->map_mflags))
2982 syserr("451 4.3.5 %s.%s: %s is not a table",
2983 map->map_file, map->map_domain,
2984 nis_sperrno(res->status));
2989 /* default key column is column 0 */
2990 if (map->map_keycolnm == NULL)
2991 map->map_keycolnm = newstr(COL_NAME(res,0));
2993 max_col = COL_MAX(res);
2995 /* verify the key column exist */
2996 for (i = 0; i < max_col; i++)
2998 if (strcmp(map->map_keycolnm, COL_NAME(res,i)) == 0)
3004 sm_dprintf("nisplus_map_open(%s): can not find key column %s\n",
3005 map->map_file, map->map_keycolnm);
3010 /* default value column is the last column */
3011 if (map->map_valcolnm == NULL)
3013 map->map_valcolno = max_col - 1;
3017 for (i = 0; i< max_col; i++)
3019 if (strcmp(map->map_valcolnm, COL_NAME(res,i)) == 0)
3021 map->map_valcolno = i;
3027 sm_dprintf("nisplus_map_open(%s): can not find column %s\n",
3028 map->map_file, map->map_keycolnm);
3035 ** NISPLUS_MAP_LOOKUP -- look up a datum in a NISPLUS table
3039 nisplus_map_lookup(map, name, av, statp)
3049 char search_key[MAXNAME + 4];
3050 char qbuf[MAXLINE + NIS_MAXNAMELEN];
3054 sm_dprintf("nisplus_map_lookup(%s, %s)\n",
3055 map->map_mname, name);
3057 if (!bitset(MF_OPEN, map->map_mflags))
3059 if (nisplus_map_open(map, O_RDONLY))
3061 map->map_mflags |= MF_OPEN;
3062 map->map_pid = CurrentPid;
3066 *statp = EX_UNAVAILABLE;
3072 ** Copy the name to the key buffer, escaping double quote characters
3073 ** by doubling them and quoting "]" and "," to avoid having the
3074 ** NIS+ parser choke on them.
3077 skleft = sizeof(search_key) - 4;
3079 for (p = name; *p != '\0' && skleft > 0; p++)
3085 /* quote the character */
3093 /* double the quote */
3105 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
3106 makelower(search_key);
3108 /* construct the query */
3109 if (PARTIAL_NAME(map->map_file))
3110 (void) sm_snprintf(qbuf, sizeof(qbuf), "[%s=%s],%s.%s",
3111 map->map_keycolnm, search_key, map->map_file,
3114 (void) sm_snprintf(qbuf, sizeof(qbuf), "[%s=%s],%s",
3115 map->map_keycolnm, search_key, map->map_file);
3118 sm_dprintf("qbuf=%s\n", qbuf);
3119 result = nis_list(qbuf, FOLLOW_LINKS | FOLLOW_PATH, NULL, NULL);
3120 if (result->status == NIS_SUCCESS)
3125 if ((count = NIS_RES_NUMOBJ(result)) != 1)
3128 sm_syslog(LOG_WARNING, CurEnv->e_id,
3129 "%s: lookup error, expected 1 entry, got %d",
3130 map->map_file, count);
3132 /* ignore second entry */
3134 sm_dprintf("nisplus_map_lookup(%s), got %d entries, additional entries ignored\n",
3138 p = ((NIS_RES_OBJECT(result))->EN_col(map->map_valcolno));
3139 /* set the length of the result */
3144 sm_dprintf("nisplus_map_lookup(%s), found %s\n",
3146 if (bitset(MF_MATCHONLY, map->map_mflags))
3147 str = map_rewrite(map, name, strlen(name), NULL);
3149 str = map_rewrite(map, p, vsize, av);
3150 nis_freeresult(result);
3156 if (result->status == NIS_NOTFOUND)
3157 *statp = EX_NOTFOUND;
3158 else if (result->status == NIS_TRYAGAIN)
3159 *statp = EX_TEMPFAIL;
3162 *statp = EX_UNAVAILABLE;
3163 map->map_mflags &= ~(MF_VALID|MF_OPEN);
3167 sm_dprintf("nisplus_map_lookup(%s), failed\n", name);
3168 nis_freeresult(result);
3175 ** NISPLUS_GETCANONNAME -- look up canonical name in NIS+
3179 nisplus_getcanonname(name, hbsize, statp)
3188 char nbuf[MAXNAME + 1];
3189 char qbuf[MAXLINE + NIS_MAXNAMELEN];
3191 if (sm_strlcpy(nbuf, name, sizeof(nbuf)) >= sizeof(nbuf))
3193 *statp = EX_UNAVAILABLE;
3196 (void) shorten_hostname(nbuf);
3198 p = strchr(nbuf, '.');
3202 (void) sm_snprintf(qbuf, sizeof(qbuf),
3203 "[name=%s],hosts.org_dir", nbuf);
3205 else if (p[1] != '\0')
3207 /* multi token -- take only first token in nbuf */
3209 (void) sm_snprintf(qbuf, sizeof(qbuf),
3210 "[name=%s],hosts.org_dir.%s", nbuf, &p[1]);
3219 sm_dprintf("\nnisplus_getcanonname(%s), qbuf=%s\n",
3222 result = nis_list(qbuf, EXPAND_NAME|FOLLOW_LINKS|FOLLOW_PATH,
3225 if (result->status == NIS_SUCCESS)
3230 if ((count = NIS_RES_NUMOBJ(result)) != 1)
3233 sm_syslog(LOG_WARNING, CurEnv->e_id,
3234 "nisplus_getcanonname: lookup error, expected 1 entry, got %d",
3237 /* ignore second entry */
3239 sm_dprintf("nisplus_getcanonname(%s), got %d entries, all but first ignored\n",
3244 sm_dprintf("nisplus_getcanonname(%s), found in directory \"%s\"\n",
3245 name, (NIS_RES_OBJECT(result))->zo_domain);
3248 vp = ((NIS_RES_OBJECT(result))->EN_col(0));
3251 sm_dprintf("nisplus_getcanonname(%s), found %s\n",
3253 if (strchr(vp, '.') != NULL)
3259 domain = macvalue('m', CurEnv);
3263 if (hbsize > vsize + (int) strlen(domain) + 1)
3265 if (domain[0] == '\0')
3266 (void) sm_strlcpy(name, vp, hbsize);
3268 (void) sm_snprintf(name, hbsize,
3269 "%s.%s", vp, domain);
3274 nis_freeresult(result);
3279 if (result->status == NIS_NOTFOUND)
3281 else if (result->status == NIS_TRYAGAIN)
3282 *statp = EX_TEMPFAIL;
3284 *statp = EX_UNAVAILABLE;
3287 sm_dprintf("nisplus_getcanonname(%s), failed, status=%d, nsw_stat=%d\n",
3288 name, result->status, *statp);
3289 nis_freeresult(result);
3294 nisplus_default_domain()
3296 static char default_domain[MAXNAME + 1] = "";
3299 if (default_domain[0] != '\0')
3300 return default_domain;
3302 p = nis_local_directory();
3303 (void) sm_strlcpy(default_domain, p, sizeof(default_domain));
3304 return default_domain;
3307 #endif /* NISPLUS */
3313 ** LDAPMAP_DEQUOTE - helper routine for ldapmap_parseargs
3316 #if defined(LDAPMAP) || defined(PH_MAP)
3319 # define ph_map_dequote ldapmap_dequote
3320 # endif /* PH_MAP */
3322 static char *ldapmap_dequote __P((char *));
3325 ldapmap_dequote(str)
3337 /* Should probably swallow initial whitespace here */
3342 while (*p != '"' && *p != '\0')
3348 #endif /* defined(LDAPMAP) || defined(PH_MAP) */
3352 static SM_LDAP_STRUCT *LDAPDefaults = NULL;
3355 ** LDAPMAP_OPEN -- open LDAP map
3357 ** Connect to the LDAP server. Re-use existing connections since a
3358 ** single server connection to a host (with the same host, port,
3359 ** bind DN, and secret) can answer queries for multiple maps.
3363 ldapmap_open(map, mode)
3367 SM_LDAP_STRUCT *lmap;
3372 sm_dprintf("ldapmap_open(%s, %d): ", map->map_mname, mode);
3374 #if defined(SUN_EXTENSIONS) && defined(SUN_SIMPLIFIED_LDAP) && \
3375 HASLDAPGETALIASBYNAME
3376 if (VendorCode == VENDOR_SUN &&
3377 strcmp(map->map_mname, "aliases.ldap") == 0)
3381 #endif /* defined(SUN_EXTENSIONS) && defined(SUN_SIMPLIFIED_LDAP) && ... */
3385 /* sendmail doesn't have the ability to write to LDAP (yet) */
3386 if (mode != O_RDONLY)
3388 /* issue a pseudo-error message */
3389 errno = SM_EMAPCANTWRITE;
3393 lmap = (SM_LDAP_STRUCT *) map->map_db1;
3395 s = ldapmap_findconn(lmap);
3396 if (s->s_lmap != NULL)
3398 /* Already have a connection open to this LDAP server */
3399 lmap->ldap_ld = ((SM_LDAP_STRUCT *)s->s_lmap->map_db1)->ldap_ld;
3400 lmap->ldap_pid = ((SM_LDAP_STRUCT *)s->s_lmap->map_db1)->ldap_pid;
3402 /* Add this map as head of linked list */
3403 lmap->ldap_next = s->s_lmap;
3407 sm_dprintf("using cached connection\n");
3412 sm_dprintf("opening new connection\n");
3414 if (lmap->ldap_host != NULL)
3415 id = lmap->ldap_host;
3416 else if (lmap->ldap_uri != NULL)
3417 id = lmap->ldap_uri;
3423 extern MAPCLASS NullMapClass;
3425 /* debug mode: don't actually open an LDAP connection */
3426 map->map_orgclass = map->map_class;
3427 map->map_class = &NullMapClass;
3428 map->map_mflags |= MF_OPEN;
3429 map->map_pid = CurrentPid;
3433 /* No connection yet, connect */
3434 if (!sm_ldap_start(map->map_mname, lmap))
3436 if (errno == ETIMEDOUT)
3439 sm_syslog(LOG_NOTICE, CurEnv->e_id,
3440 "timeout connecting to LDAP server %.100s",
3444 if (!bitset(MF_OPTIONAL, map->map_mflags))
3446 if (bitset(MF_NODEFER, map->map_mflags))
3448 syserr("%s failed to %s in map %s",
3450 "ldap_init/ldap_bind",
3451 # else /* USE_LDAP_INIT */
3453 # endif /* USE_LDAP_INIT */
3454 id, map->map_mname);
3458 syserr("451 4.3.5 %s failed to %s in map %s",
3460 "ldap_init/ldap_bind",
3461 # else /* USE_LDAP_INIT */
3463 # endif /* USE_LDAP_INIT */
3464 id, map->map_mname);
3470 /* Save connection for reuse */
3476 ** LDAPMAP_CLOSE -- close ldap map
3483 SM_LDAP_STRUCT *lmap;
3487 sm_dprintf("ldapmap_close(%s)\n", map->map_mname);
3489 lmap = (SM_LDAP_STRUCT *) map->map_db1;
3491 /* Check if already closed */
3492 if (lmap->ldap_ld == NULL)
3495 /* Close the LDAP connection */
3496 sm_ldap_close(lmap);
3498 /* Mark all the maps that share the connection as closed */
3499 s = ldapmap_findconn(lmap);
3501 while (s->s_lmap != NULL)
3503 MAP *smap = s->s_lmap;
3505 if (tTd(38, 2) && smap != map)
3506 sm_dprintf("ldapmap_close(%s): closed %s (shared LDAP connection)\n",
3507 map->map_mname, smap->map_mname);
3508 smap->map_mflags &= ~(MF_OPEN|MF_WRITABLE);
3509 lmap = (SM_LDAP_STRUCT *) smap->map_db1;
3510 lmap->ldap_ld = NULL;
3511 s->s_lmap = lmap->ldap_next;
3512 lmap->ldap_next = NULL;
3518 ** SUNET_ID_HASH -- Convert a string to its Sunet_id canonical form
3519 ** This only makes sense at Stanford University.
3532 if (isascii(*p) && (islower(*p) || isdigit(*p)))
3537 else if (isascii(*p) && isupper(*p))
3539 *p_last = tolower(*p);
3544 if (*p_last != '\0')
3548 # define SM_CONVERT_ID(str) sunet_id_hash(str)
3549 # else /* SUNET_ID */
3550 # define SM_CONVERT_ID(str) makelower(str)
3551 # endif /* SUNET_ID */
3554 ** LDAPMAP_LOOKUP -- look up a datum in a LDAP map
3558 ldapmap_lookup(map, name, av, statp)
3571 char *result = NULL;
3573 SM_LDAP_STRUCT *lmap = NULL;
3574 char *argv[SM_LDAP_ARGS];
3575 char keybuf[MAXKEY];
3576 #if SM_LDAP_ARGS != MAX_MAP_ARGS
3577 # ERROR _SM_LDAP_ARGS must be the same as _MAX_MAP_ARGS
3578 #endif /* SM_LDAP_ARGS != MAX_MAP_ARGS */
3580 #if defined(SUN_EXTENSIONS) && defined(SUN_SIMPLIFIED_LDAP) && \
3581 HASLDAPGETALIASBYNAME
3582 if (VendorCode == VENDOR_SUN &&
3583 strcmp(map->map_mname, "aliases.ldap") == 0)
3586 #if defined(GETLDAPALIASBYNAME_VERSION) && (GETLDAPALIASBYNAME_VERSION >= 2)
3587 extern char *__getldapaliasbyname();
3590 answer = __getldapaliasbyname(name, &rc);
3592 char answer[MAXNAME + 1];
3594 rc = __getldapaliasbyname(name, answer, sizeof(answer));
3599 sm_dprintf("getldapaliasbyname(%.100s) failed, errno=%d\n",
3601 *statp = EX_NOTFOUND;
3606 sm_dprintf("getldapaliasbyname(%.100s) => %s\n", name,
3608 if (bitset(MF_MATCHONLY, map->map_mflags))
3609 result = map_rewrite(map, name, strlen(name), NULL);
3611 result = map_rewrite(map, answer, strlen(answer), av);
3612 #if defined(GETLDAPALIASBYNAME_VERSION) && (GETLDAPALIASBYNAME_VERSION >= 2)
3617 #endif /* defined(SUN_EXTENSIONS) && defined(SUN_SIMPLIFIED_LDAP) && ... */
3619 /* Get ldap struct pointer from map */
3620 lmap = (SM_LDAP_STRUCT *) map->map_db1;
3621 sm_ldap_setopts(lmap->ldap_ld, lmap);
3623 if (lmap->ldap_multi_args)
3625 SM_REQUIRE(av != NULL);
3626 memset(argv, '\0', sizeof(argv));
3627 for (i = 0; i < SM_LDAP_ARGS && av[i] != NULL; i++)
3629 argv[i] = sm_strdup(av[i]);
3630 if (argv[i] == NULL)
3635 for (j = 0; j < i && argv[j] != NULL; j++)
3637 *statp = EX_TEMPFAIL;
3642 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
3643 SM_CONVERT_ID(av[i]);
3648 (void) sm_strlcpy(keybuf, name, sizeof(keybuf));
3650 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
3651 SM_CONVERT_ID(keybuf);
3656 if (lmap->ldap_multi_args)
3658 sm_dprintf("ldapmap_lookup(%s, argv)\n",
3660 for (i = 0; i < SM_LDAP_ARGS; i++)
3662 sm_dprintf(" argv[%d] = %s\n", i,
3663 argv[i] == NULL ? "NULL" : argv[i]);
3668 sm_dprintf("ldapmap_lookup(%s, %s)\n",
3669 map->map_mname, name);
3673 if (lmap->ldap_multi_args)
3675 msgid = sm_ldap_search_m(lmap, argv);
3677 /* free the argv array and its content, no longer needed */
3678 for (i = 0; i < SM_LDAP_ARGS && argv[i] != NULL; i++)
3682 msgid = sm_ldap_search(lmap, keybuf);
3683 if (msgid == SM_LDAP_ERR)
3685 errno = sm_ldap_geterrno(lmap->ldap_ld) + E_LDAPBASE;
3687 if (!bitset(MF_OPTIONAL, map->map_mflags))
3690 ** Do not include keybuf as this error may be shown
3694 if (bitset(MF_NODEFER, map->map_mflags))
3695 syserr("Error in ldap_search in map %s",
3698 syserr("451 4.3.5 Error in ldap_search in map %s",
3701 *statp = EX_TEMPFAIL;
3702 switch (save_errno - E_LDAPBASE)
3704 # ifdef LDAP_SERVER_DOWN
3705 case LDAP_SERVER_DOWN:
3706 # endif /* LDAP_SERVER_DOWN */
3708 case LDAP_UNAVAILABLE:
3709 /* server disappeared, try reopen on next search */
3716 #if SM_LDAP_ERROR_ON_MISSING_ARGS
3717 else if (msgid == SM_LDAP_ERR_ARG_MISS)
3719 if (bitset(MF_NODEFER, map->map_mflags))
3720 syserr("Error in ldap_search in map %s, too few arguments",
3723 syserr("554 5.3.5 Error in ldap_search in map %s, too few arguments",
3728 #endif /* SM_LDAP_ERROR_ON_MISSING_ARGS */
3730 *statp = EX_NOTFOUND;
3734 if (bitset(MF_SINGLEMATCH, map->map_mflags))
3735 flags |= SM_LDAP_SINGLEMATCH;
3736 if (bitset(MF_MATCHONLY, map->map_mflags))
3737 flags |= SM_LDAP_MATCHONLY;
3738 # if _FFR_LDAP_SINGLEDN
3739 if (bitset(MF_SINGLEDN, map->map_mflags))
3740 flags |= SM_LDAP_SINGLEDN;
3741 # endif /* _FFR_LDAP_SINGLEDN */
3743 /* Create an rpool for search related memory usage */
3744 rpool = sm_rpool_new_x(NULL);
3747 *statp = sm_ldap_results(lmap, msgid, flags, map->map_coldelim,
3748 rpool, &p, &plen, &psize, NULL);
3751 /* Copy result so rpool can be freed */
3752 if (*statp == EX_OK && p != NULL)
3754 sm_rpool_free(rpool);
3756 /* need to restart LDAP connection? */
3757 if (*statp == EX_RESTART)
3759 *statp = EX_TEMPFAIL;
3764 if (*statp != EX_OK && *statp != EX_NOTFOUND)
3766 if (!bitset(MF_OPTIONAL, map->map_mflags))
3768 if (bitset(MF_NODEFER, map->map_mflags))
3769 syserr("Error getting LDAP results, map=%s, name=%s",
3770 map->map_mname, name);
3772 syserr("451 4.3.5 Error getting LDAP results, map=%s, name=%s",
3773 map->map_mname, name);
3779 /* Did we match anything? */
3780 if (vp == NULL && !bitset(MF_MATCHONLY, map->map_mflags))
3783 if (*statp == EX_OK)
3786 sm_syslog(LOG_INFO, CurEnv->e_id,
3787 "ldap=%s, %.100s=>%s", map->map_mname, name,
3788 vp == NULL ? "<NULL>" : vp);
3789 if (bitset(MF_MATCHONLY, map->map_mflags))
3790 result = map_rewrite(map, name, strlen(name), NULL);
3793 /* vp != NULL according to test above */
3794 result = map_rewrite(map, vp, strlen(vp), av);
3797 sm_free(vp); /* XXX */
3803 ** LDAPMAP_FINDCONN -- find an LDAP connection to the server
3805 ** Cache LDAP connections based on the host, port, bind DN,
3806 ** secret, and PID so we don't have multiple connections open to
3807 ** the same server for different maps. Need a separate connection
3808 ** per PID since a parent process may close the map before the
3809 ** child is done with it.
3812 ** lmap -- LDAP map information
3815 ** Symbol table entry for the LDAP connection.
3819 ldapmap_findconn(lmap)
3820 SM_LDAP_STRUCT *lmap;
3825 STAB *SM_NONVOLATILE s = NULL;
3827 if (lmap->ldap_host != NULL)
3828 id = lmap->ldap_host;
3829 else if (lmap->ldap_uri != NULL)
3830 id = lmap->ldap_uri;
3834 format = "%s%c%d%c%d%c%s%c%s%d";
3835 nbuf = sm_stringf_x(format,
3842 (lmap->ldap_binddn == NULL ? ""
3843 : lmap->ldap_binddn),
3845 (lmap->ldap_secret == NULL ? ""
3846 : lmap->ldap_secret),
3849 s = stab(nbuf, ST_LMAP, ST_ENTER);
3856 ** LDAPMAP_PARSEARGS -- parse ldap map definition args.
3859 static struct lamvalues LDAPAuthMethods[] =
3861 { "none", LDAP_AUTH_NONE },
3862 { "simple", LDAP_AUTH_SIMPLE },
3863 # ifdef LDAP_AUTH_KRBV4
3864 { "krbv4", LDAP_AUTH_KRBV4 },
3865 # endif /* LDAP_AUTH_KRBV4 */
3869 static struct ladvalues LDAPAliasDereference[] =
3871 { "never", LDAP_DEREF_NEVER },
3872 { "always", LDAP_DEREF_ALWAYS },
3873 { "search", LDAP_DEREF_SEARCHING },
3874 { "find", LDAP_DEREF_FINDING },
3878 static struct lssvalues LDAPSearchScope[] =
3880 { "base", LDAP_SCOPE_BASE },
3881 { "one", LDAP_SCOPE_ONELEVEL },
3882 { "sub", LDAP_SCOPE_SUBTREE },
3887 ldapmap_parseargs(map, args)
3891 bool secretread = true;
3892 bool attrssetup = false;
3894 register char *p = args;
3895 SM_LDAP_STRUCT *lmap;
3896 struct lamvalues *lam;
3897 struct ladvalues *lad;
3898 struct lssvalues *lss;
3899 char ldapfilt[MAXLINE];
3900 char m_tmp[MAXPATHLEN + LDAPMAP_MAX_PASSWD];
3902 /* Get ldap struct pointer from map */
3903 lmap = (SM_LDAP_STRUCT *) map->map_db1;
3905 /* Check if setting the initial LDAP defaults */
3906 if (lmap == NULL || lmap != LDAPDefaults)
3908 /* We need to alloc an SM_LDAP_STRUCT struct */
3909 lmap = (SM_LDAP_STRUCT *) xalloc(sizeof(*lmap));
3910 if (LDAPDefaults == NULL)
3911 sm_ldap_clear(lmap);
3913 STRUCTCOPY(*LDAPDefaults, *lmap);
3916 /* there is no check whether there is really an argument */
3917 map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL;
3918 map->map_spacesub = SpaceSub; /* default value */
3920 /* Check if setting up an alias or file class LDAP map */
3921 if (bitset(MF_ALIAS, map->map_mflags))
3923 /* Comma separate if used as an alias file */
3924 map->map_coldelim = ',';
3929 char jbuf[MAXHOSTNAMELEN];
3930 char lcbuf[MAXLINE];
3933 expand("\201j", jbuf, sizeof(jbuf), &BlankEnvelope);
3934 if (jbuf[0] == '\0')
3936 (void) sm_strlcpy(jbuf, "localhost",
3940 lc = macvalue(macid("{sendmailMTACluster}"), CurEnv);
3945 expand(lc, lcbuf, sizeof(lcbuf), CurEnv);
3949 n = sm_snprintf(ldapfilt, sizeof(ldapfilt),
3950 "(&(objectClass=sendmailMTAAliasObject)(sendmailMTAAliasGrouping=aliases)(|(sendmailMTACluster=%s)(sendmailMTAHost=%s))(sendmailMTAKey=%%0))",
3952 if (n >= sizeof(ldapfilt))
3954 syserr("%s: Default LDAP string too long",
3959 /* default args for an alias LDAP entry */
3960 lmap->ldap_filter = ldapfilt;
3961 lmap->ldap_attr[0] = "objectClass";
3962 lmap->ldap_attr_type[0] = SM_LDAP_ATTR_OBJCLASS;
3963 lmap->ldap_attr_needobjclass[0] = NULL;
3964 lmap->ldap_attr[1] = "sendmailMTAAliasValue";
3965 lmap->ldap_attr_type[1] = SM_LDAP_ATTR_NORMAL;
3966 lmap->ldap_attr_needobjclass[1] = NULL;
3967 lmap->ldap_attr[2] = "sendmailMTAAliasSearch";
3968 lmap->ldap_attr_type[2] = SM_LDAP_ATTR_FILTER;
3969 lmap->ldap_attr_needobjclass[2] = "sendmailMTAMapObject";
3970 lmap->ldap_attr[3] = "sendmailMTAAliasURL";
3971 lmap->ldap_attr_type[3] = SM_LDAP_ATTR_URL;
3972 lmap->ldap_attr_needobjclass[3] = "sendmailMTAMapObject";
3973 lmap->ldap_attr[4] = NULL;
3974 lmap->ldap_attr_type[4] = SM_LDAP_ATTR_NONE;
3975 lmap->ldap_attr_needobjclass[4] = NULL;
3979 else if (bitset(MF_FILECLASS, map->map_mflags))
3981 /* Space separate if used as a file class file */
3982 map->map_coldelim = ' ';
3985 # if _FFR_LDAP_NETWORK_TIMEOUT
3986 lmap->ldap_networktmo = 120;
3987 # endif /* _FFR_LDAP_NETWORK_TIMEOUT */
3991 while (isascii(*p) && isspace(*p))
3998 map->map_mflags |= MF_APPEND;
4006 map->map_mflags |= MF_DEFER;
4010 map->map_mflags |= MF_NOFOLDCASE;
4014 map->map_mflags |= MF_MATCHONLY;
4018 map->map_mflags |= MF_INCLNULL;
4019 map->map_mflags &= ~MF_TRY0NULL;
4023 map->map_mflags &= ~MF_TRY1NULL;
4027 map->map_mflags |= MF_OPTIONAL;
4031 map->map_mflags |= MF_KEEPQUOTES;
4035 map->map_spacesub = *++p;
4039 map->map_tapp = ++p;
4043 map->map_mflags |= MF_NODEFER;
4048 map->map_coldelim = *p;
4054 map->map_coldelim = '\n';
4058 map->map_coldelim = '\t';
4062 map->map_coldelim = '\\';
4067 /* Start of ldapmap specific args */
4069 map->map_mflags |= MF_SINGLEMATCH;
4072 # if _FFR_LDAP_SINGLEDN
4074 map->map_mflags |= MF_SINGLEDN;
4076 # endif /* _FFR_LDAP_SINGLEDN */
4078 case 'b': /* search base */
4079 while (isascii(*++p) && isspace(*p))
4081 lmap->ldap_base = p;
4084 # if _FFR_LDAP_NETWORK_TIMEOUT
4085 case 'c': /* network (connect) timeout */
4086 while (isascii(*++p) && isspace(*p))
4088 lmap->ldap_networktmo = atoi(p);
4090 # endif /* _FFR_LDAP_NETWORK_TIMEOUT */
4092 case 'd': /* Dn to bind to server as */
4093 while (isascii(*++p) && isspace(*p))
4095 lmap->ldap_binddn = p;
4098 case 'H': /* Use LDAP URI */
4100 syserr("Must compile with -DUSE_LDAP_INIT to use LDAP URIs (-H) in map %s",
4103 # else /* !USE_LDAP_INIT */
4104 if (lmap->ldap_host != NULL)
4106 syserr("Can not specify both an LDAP host and an LDAP URI in map %s",
4110 while (isascii(*++p) && isspace(*p))
4114 # endif /* !USE_LDAP_INIT */
4116 case 'h': /* ldap host */
4117 while (isascii(*++p) && isspace(*p))
4119 if (lmap->ldap_uri != NULL)
4121 syserr("Can not specify both an LDAP host and an LDAP URI in map %s",
4125 lmap->ldap_host = p;
4129 lmap->ldap_multi_args = true;
4132 case 'k': /* search field */
4133 while (isascii(*++p) && isspace(*p))
4135 lmap->ldap_filter = p;
4138 case 'l': /* time limit */
4139 while (isascii(*++p) && isspace(*p))
4141 lmap->ldap_timelimit = atoi(p);
4142 lmap->ldap_timeout.tv_sec = lmap->ldap_timelimit;
4145 case 'M': /* Method for binding */
4146 while (isascii(*++p) && isspace(*p))
4149 if (sm_strncasecmp(p, "LDAP_AUTH_", 10) == 0)
4152 for (lam = LDAPAuthMethods;
4153 lam != NULL && lam->lam_name != NULL; lam++)
4155 if (sm_strncasecmp(p, lam->lam_name,
4156 strlen(lam->lam_name)) == 0)
4159 if (lam->lam_name != NULL)
4160 lmap->ldap_method = lam->lam_code;
4163 /* bad config line */
4164 if (!bitset(MCF_OPTFILE,
4165 map->map_class->map_cflags))
4169 if ((ptr = strchr(p, ' ')) != NULL)
4171 syserr("Method for binding must be [none|simple|krbv4] (not %s) in map %s",
4180 case 'n': /* retrieve attribute names only */
4181 lmap->ldap_attrsonly = LDAPMAP_TRUE;
4185 ** This is a string that is dependent on the
4186 ** method used defined by 'M'.
4189 case 'P': /* Secret password for binding */
4190 while (isascii(*++p) && isspace(*p))
4192 lmap->ldap_secret = p;
4196 case 'p': /* ldap port */
4197 while (isascii(*++p) && isspace(*p))
4199 lmap->ldap_port = atoi(p);
4202 /* args stolen from ldapsearch.c */
4203 case 'R': /* don't auto chase referrals */
4204 # ifdef LDAP_REFERRALS
4205 lmap->ldap_options &= ~LDAP_OPT_REFERRALS;
4206 # else /* LDAP_REFERRALS */
4207 syserr("compile with -DLDAP_REFERRALS for referral support");
4208 # endif /* LDAP_REFERRALS */
4211 case 'r': /* alias dereferencing */
4212 while (isascii(*++p) && isspace(*p))
4215 if (sm_strncasecmp(p, "LDAP_DEREF_", 11) == 0)
4218 for (lad = LDAPAliasDereference;
4219 lad != NULL && lad->lad_name != NULL; lad++)
4221 if (sm_strncasecmp(p, lad->lad_name,
4222 strlen(lad->lad_name)) == 0)
4225 if (lad->lad_name != NULL)
4226 lmap->ldap_deref = lad->lad_code;
4229 /* bad config line */
4230 if (!bitset(MCF_OPTFILE,
4231 map->map_class->map_cflags))
4235 if ((ptr = strchr(p, ' ')) != NULL)
4237 syserr("Deref must be [never|always|search|find] (not %s) in map %s",
4246 case 's': /* search scope */
4247 while (isascii(*++p) && isspace(*p))
4250 if (sm_strncasecmp(p, "LDAP_SCOPE_", 11) == 0)
4253 for (lss = LDAPSearchScope;
4254 lss != NULL && lss->lss_name != NULL; lss++)
4256 if (sm_strncasecmp(p, lss->lss_name,
4257 strlen(lss->lss_name)) == 0)
4260 if (lss->lss_name != NULL)
4261 lmap->ldap_scope = lss->lss_code;
4264 /* bad config line */
4265 if (!bitset(MCF_OPTFILE,
4266 map->map_class->map_cflags))
4270 if ((ptr = strchr(p, ' ')) != NULL)
4272 syserr("Scope must be [base|one|sub] (not %s) in map %s",
4283 lmap->ldap_attrsep = *p;
4289 lmap->ldap_attrsep = '\n';
4293 lmap->ldap_attrsep = '\t';
4297 lmap->ldap_attrsep = '\\';
4302 case 'v': /* attr to return */
4303 while (isascii(*++p) && isspace(*p))
4305 lmap->ldap_attr[0] = p;
4306 lmap->ldap_attr[1] = NULL;
4310 /* -w should be for passwd, -P should be for version */
4311 while (isascii(*++p) && isspace(*p))
4313 lmap->ldap_version = atoi(p);
4314 # ifdef LDAP_VERSION_MAX
4315 if (lmap->ldap_version > LDAP_VERSION_MAX)
4317 syserr("LDAP version %d exceeds max of %d in map %s",
4318 lmap->ldap_version, LDAP_VERSION_MAX,
4322 # endif /* LDAP_VERSION_MAX */
4323 # ifdef LDAP_VERSION_MIN
4324 if (lmap->ldap_version < LDAP_VERSION_MIN)
4326 syserr("LDAP version %d is lower than min of %d in map %s",
4327 lmap->ldap_version, LDAP_VERSION_MIN,
4331 # endif /* LDAP_VERSION_MIN */
4335 while (isascii(*++p) && isspace(*p))
4337 lmap->ldap_sizelimit = atoi(p);
4341 syserr("Illegal option %c map %s", *p, map->map_mname);
4345 /* need to account for quoted strings here */
4346 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4350 while (*++p != '"' && *p != '\0')
4363 if (map->map_app != NULL)
4364 map->map_app = newstr(ldapmap_dequote(map->map_app));
4365 if (map->map_tapp != NULL)
4366 map->map_tapp = newstr(ldapmap_dequote(map->map_tapp));
4369 ** We need to swallow up all the stuff into a struct
4370 ** and dump it into map->map_dbptr1
4373 if (lmap->ldap_host != NULL &&
4374 (LDAPDefaults == NULL ||
4375 LDAPDefaults == lmap ||
4376 LDAPDefaults->ldap_host != lmap->ldap_host))
4377 lmap->ldap_host = newstr(ldapmap_dequote(lmap->ldap_host));
4378 map->map_domain = lmap->ldap_host;
4380 if (lmap->ldap_uri != NULL &&
4381 (LDAPDefaults == NULL ||
4382 LDAPDefaults == lmap ||
4383 LDAPDefaults->ldap_uri != lmap->ldap_uri))
4384 lmap->ldap_uri = newstr(ldapmap_dequote(lmap->ldap_uri));
4385 map->map_domain = lmap->ldap_uri;
4387 if (lmap->ldap_binddn != NULL &&
4388 (LDAPDefaults == NULL ||
4389 LDAPDefaults == lmap ||
4390 LDAPDefaults->ldap_binddn != lmap->ldap_binddn))
4391 lmap->ldap_binddn = newstr(ldapmap_dequote(lmap->ldap_binddn));
4393 if (lmap->ldap_secret != NULL &&
4394 (LDAPDefaults == NULL ||
4395 LDAPDefaults == lmap ||
4396 LDAPDefaults->ldap_secret != lmap->ldap_secret))
4399 long sff = SFF_OPENASROOT|SFF_ROOTOK|SFF_NOWLINK|SFF_NOWWFILES|SFF_NOGWFILES;
4401 if (DontLockReadFiles)
4404 /* need to use method to map secret to passwd string */
4405 switch (lmap->ldap_method)
4407 case LDAP_AUTH_NONE:
4411 case LDAP_AUTH_SIMPLE:
4414 ** Secret is the name of a file with
4415 ** the first line as the password.
4418 /* Already read in the secret? */
4422 sfd = safefopen(ldapmap_dequote(lmap->ldap_secret),
4426 syserr("LDAP map: cannot open secret %s",
4427 ldapmap_dequote(lmap->ldap_secret));
4430 lmap->ldap_secret = sfgets(m_tmp, sizeof(m_tmp),
4431 sfd, TimeOuts.to_fileopen,
4432 "ldapmap_parseargs");
4433 (void) sm_io_close(sfd, SM_TIME_DEFAULT);
4434 if (strlen(m_tmp) > LDAPMAP_MAX_PASSWD)
4436 syserr("LDAP map: secret in %s too long",
4437 ldapmap_dequote(lmap->ldap_secret));
4440 if (lmap->ldap_secret != NULL &&
4444 if (m_tmp[strlen(m_tmp) - 1] == '\n')
4445 m_tmp[strlen(m_tmp) - 1] = '\0';
4447 lmap->ldap_secret = m_tmp;
4451 # ifdef LDAP_AUTH_KRBV4
4452 case LDAP_AUTH_KRBV4:
4455 ** Secret is where the ticket file is
4459 (void) sm_snprintf(m_tmp, sizeof(m_tmp),
4461 ldapmap_dequote(lmap->ldap_secret));
4462 lmap->ldap_secret = m_tmp;
4464 # endif /* LDAP_AUTH_KRBV4 */
4466 default: /* Should NEVER get here */
4467 syserr("LDAP map: Illegal value in lmap method");
4474 if (lmap->ldap_secret != NULL &&
4475 (LDAPDefaults == NULL ||
4476 LDAPDefaults == lmap ||
4477 LDAPDefaults->ldap_secret != lmap->ldap_secret))
4478 lmap->ldap_secret = newstr(ldapmap_dequote(lmap->ldap_secret));
4480 if (lmap->ldap_base != NULL &&
4481 (LDAPDefaults == NULL ||
4482 LDAPDefaults == lmap ||
4483 LDAPDefaults->ldap_base != lmap->ldap_base))
4484 lmap->ldap_base = newstr(ldapmap_dequote(lmap->ldap_base));
4487 ** Save the server from extra work. If request is for a single
4488 ** match, tell the server to only return enough records to
4489 ** determine if there is a single match or not. This can not
4490 ** be one since the server would only return one and we wouldn't
4491 ** know if there were others available.
4494 if (bitset(MF_SINGLEMATCH, map->map_mflags))
4495 lmap->ldap_sizelimit = 2;
4497 /* If setting defaults, don't process ldap_filter and ldap_attr */
4498 if (lmap == LDAPDefaults)
4501 if (lmap->ldap_filter != NULL)
4502 lmap->ldap_filter = newstr(ldapmap_dequote(lmap->ldap_filter));
4505 if (!bitset(MCF_OPTFILE, map->map_class->map_cflags))
4507 syserr("No filter given in map %s", map->map_mname);
4512 if (!attrssetup && lmap->ldap_attr[0] != NULL)
4514 bool recurse = false;
4515 bool normalseen = false;
4518 p = ldapmap_dequote(lmap->ldap_attr[0]);
4519 lmap->ldap_attr[0] = NULL;
4521 /* Prime the attr list with the objectClass attribute */
4522 lmap->ldap_attr[i] = "objectClass";
4523 lmap->ldap_attr_type[i] = SM_LDAP_ATTR_OBJCLASS;
4524 lmap->ldap_attr_needobjclass[i] = NULL;
4531 while (isascii(*p) && isspace(*p))
4540 if (i >= LDAPMAP_MAX_ATTR)
4542 syserr("Too many return attributes in %s (max %d)",
4543 map->map_mname, LDAPMAP_MAX_ATTR);
4553 type = strchr(v, ':');
4557 needobjclass = strchr(type, ':');
4558 if (needobjclass != NULL)
4559 *needobjclass++ = '\0';
4563 needobjclass = NULL;
4568 /* allow override on "objectClass" type */
4569 if (sm_strcasecmp(v, "objectClass") == 0 &&
4570 lmap->ldap_attr_type[0] == SM_LDAP_ATTR_OBJCLASS)
4577 ** Don't add something to attribute
4581 for (j = 1; j < i; j++)
4583 if (sm_strcasecmp(v, lmap->ldap_attr[j]) == 0)
4585 syserr("Duplicate attribute (%s) in %s",
4591 lmap->ldap_attr[use] = newstr(v);
4592 if (needobjclass != NULL &&
4593 *needobjclass != '\0' &&
4594 *needobjclass != '*')
4596 lmap->ldap_attr_needobjclass[use] = newstr(needobjclass);
4600 lmap->ldap_attr_needobjclass[use] = NULL;
4605 if (type != NULL && *type != '\0')
4607 if (sm_strcasecmp(type, "dn") == 0)
4610 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_DN;
4612 else if (sm_strcasecmp(type, "filter") == 0)
4615 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_FILTER;
4617 else if (sm_strcasecmp(type, "url") == 0)
4620 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_URL;
4622 else if (sm_strcasecmp(type, "normal") == 0)
4624 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_NORMAL;
4629 syserr("Unknown attribute type (%s) in %s",
4630 type, map->map_mname);
4636 lmap->ldap_attr_type[use] = SM_LDAP_ATTR_NORMAL;
4642 lmap->ldap_attr[i] = NULL;
4644 /* Set in case needed in future code */
4647 if (recurse && !normalseen)
4649 syserr("LDAP recursion requested in %s but no returnable attribute given",
4653 if (recurse && lmap->ldap_attrsonly == LDAPMAP_TRUE)
4655 syserr("LDAP recursion requested in %s can not be used with -n",
4660 map->map_db1 = (ARBPTR_T) lmap;
4665 ** LDAPMAP_SET_DEFAULTS -- Read default map spec from LDAPDefaults in .cf
4668 ** spec -- map argument string from LDAPDefaults option
4675 ldapmap_set_defaults(spec)
4681 /* Allocate and set the default values */
4682 if (LDAPDefaults == NULL)
4683 LDAPDefaults = (SM_LDAP_STRUCT *) xalloc(sizeof(*LDAPDefaults));
4684 sm_ldap_clear(LDAPDefaults);
4686 memset(&map, '\0', sizeof(map));
4688 /* look up the class */
4689 class = stab("ldap", ST_MAPCLASS, ST_FIND);
4692 syserr("readcf: LDAPDefaultSpec: class ldap not available");
4695 map.map_class = &class->s_mapclass;
4696 map.map_db1 = (ARBPTR_T) LDAPDefaults;
4697 map.map_mname = "O LDAPDefaultSpec";
4699 (void) ldapmap_parseargs(&map, spec);
4701 /* These should never be set in LDAPDefaults */
4702 if (map.map_mflags != (MF_TRY0NULL|MF_TRY1NULL) ||
4703 map.map_spacesub != SpaceSub ||
4704 map.map_app != NULL ||
4705 map.map_tapp != NULL)
4707 syserr("readcf: option LDAPDefaultSpec: Do not set non-LDAP specific flags");
4708 SM_FREE_CLR(map.map_app);
4709 SM_FREE_CLR(map.map_tapp);
4712 if (LDAPDefaults->ldap_filter != NULL)
4714 syserr("readcf: option LDAPDefaultSpec: Do not set the LDAP search filter");
4716 /* don't free, it isn't malloc'ed in parseargs */
4717 LDAPDefaults->ldap_filter = NULL;
4720 if (LDAPDefaults->ldap_attr[0] != NULL)
4722 syserr("readcf: option LDAPDefaultSpec: Do not set the requested LDAP attributes");
4723 /* don't free, they aren't malloc'ed in parseargs */
4724 LDAPDefaults->ldap_attr[0] = NULL;
4727 #endif /* LDAPMAP */
4735 ** Support for the CCSO Nameserver (ph/qi).
4736 ** This code is intended to replace the so-called "ph mailer".
4737 ** Contributed by Mark D. Roth. Contact him for support.
4740 /* what version of the ph map code we're running */
4741 static char phmap_id[128];
4743 /* sendmail version for phmap id string */
4744 extern const char Version[];
4746 /* assume we're using nph-1.2.x if not specified */
4747 # ifndef NPH_VERSION
4748 # define NPH_VERSION 10200
4751 /* compatibility for versions older than nph-1.2.0 */
4752 # if NPH_VERSION < 10200
4753 # define PH_OPEN_ROUNDROBIN PH_ROUNDROBIN
4754 # define PH_OPEN_DONTID PH_DONTID
4755 # define PH_CLOSE_FAST PH_FASTCLOSE
4756 # define PH_ERR_DATAERR PH_DATAERR
4757 # define PH_ERR_NOMATCH PH_NOMATCH
4758 # endif /* NPH_VERSION < 10200 */
4761 ** PH_MAP_PARSEARGS -- parse ph map definition args.
4765 ph_map_parseargs(map, args)
4770 register char *p = args;
4771 PH_MAP_STRUCT *pmap = NULL;
4773 /* initialize version string */
4774 (void) sm_snprintf(phmap_id, sizeof(phmap_id),
4775 "sendmail-%s phmap-20010529 libphclient-%s",
4776 Version, libphclient_version);
4778 pmap = (PH_MAP_STRUCT *) xalloc(sizeof(*pmap));
4781 pmap->ph_servers = NULL;
4782 pmap->ph_field_list = NULL;
4784 pmap->ph_timeout = 0;
4785 pmap->ph_fastclose = 0;
4787 map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL;
4790 while (isascii(*p) && isspace(*p))
4797 map->map_mflags |= MF_INCLNULL;
4798 map->map_mflags &= ~MF_TRY0NULL;
4802 map->map_mflags &= ~MF_TRY1NULL;
4806 map->map_mflags |= MF_OPTIONAL;
4810 map->map_mflags |= MF_NOFOLDCASE;
4814 map->map_mflags |= MF_MATCHONLY;
4818 map->map_mflags |= MF_APPEND;
4822 map->map_mflags |= MF_KEEPQUOTES;
4826 map->map_mflags |= MF_NODEFER;
4834 map->map_tapp = ++p;
4838 while (isascii(*++p) && isspace(*p))
4840 pmap->ph_timeout = atoi(p);
4844 map->map_spacesub = *++p;
4848 map->map_mflags |= MF_DEFER;
4851 case 'h': /* PH server list */
4852 while (isascii(*++p) && isspace(*p))
4854 pmap->ph_servers = p;
4857 case 'k': /* fields to search for */
4858 while (isascii(*++p) && isspace(*p))
4860 pmap->ph_field_list = p;
4864 syserr("ph_map_parseargs: unknown option -%c", *p);
4867 /* try to account for quoted strings */
4868 done = isascii(*p) && isspace(*p);
4869 while (*p != '\0' && !done)
4873 while (*++p != '"' && *p != '\0')
4880 done = isascii(*p) && isspace(*p);
4887 if (map->map_app != NULL)
4888 map->map_app = newstr(ph_map_dequote(map->map_app));
4889 if (map->map_tapp != NULL)
4890 map->map_tapp = newstr(ph_map_dequote(map->map_tapp));
4892 if (pmap->ph_field_list != NULL)
4893 pmap->ph_field_list = newstr(ph_map_dequote(pmap->ph_field_list));
4895 if (pmap->ph_servers != NULL)
4896 pmap->ph_servers = newstr(ph_map_dequote(pmap->ph_servers));
4899 syserr("ph_map_parseargs: -h flag is required");
4903 map->map_db1 = (ARBPTR_T) pmap;
4908 ** PH_MAP_CLOSE -- close the connection to the ph server
4915 PH_MAP_STRUCT *pmap;
4917 pmap = (PH_MAP_STRUCT *)map->map_db1;
4919 sm_dprintf("ph_map_close(%s): pmap->ph_fastclose=%d\n",
4920 map->map_mname, pmap->ph_fastclose);
4923 if (pmap->ph != NULL)
4925 ph_set_sendhook(pmap->ph, NULL);
4926 ph_set_recvhook(pmap->ph, NULL);
4927 ph_close(pmap->ph, pmap->ph_fastclose);
4930 map->map_mflags &= ~(MF_OPEN|MF_WRITABLE);
4933 static jmp_buf PHTimeout;
4941 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
4942 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
4947 longjmp(PHTimeout, 1);
4951 #if NPH_VERSION >= 10200
4952 ph_map_send_debug(appdata, text)
4955 ph_map_send_debug(text)
4960 sm_syslog(LOG_NOTICE, CurEnv->e_id,
4961 "ph_map_send_debug: ==> %s", text);
4963 sm_dprintf("ph_map_send_debug: ==> %s\n", text);
4967 #if NPH_VERSION >= 10200
4968 ph_map_recv_debug(appdata, text)
4971 ph_map_recv_debug(text)
4976 sm_syslog(LOG_NOTICE, CurEnv->e_id,
4977 "ph_map_recv_debug: <== %s", text);
4979 sm_dprintf("ph_map_recv_debug: <== %s\n", text);
4983 ** PH_MAP_OPEN -- sub for opening PH map
4986 ph_map_open(map, mode)
4990 PH_MAP_STRUCT *pmap;
4991 register SM_EVENT *ev = NULL;
4993 char *hostlist, *host;
4996 sm_dprintf("ph_map_open(%s)\n", map->map_mname);
4999 if (mode != O_RDONLY)
5001 /* issue a pseudo-error message */
5002 errno = SM_EMAPCANTWRITE;
5006 if (CurEnv != NULL && CurEnv->e_sendmode == SM_DEFER &&
5007 bitset(MF_DEFER, map->map_mflags))
5010 sm_dprintf("ph_map_open(%s) => DEFERRED\n",
5014 ** Unset MF_DEFER here so that map_lookup() returns
5015 ** a temporary failure using the bogus map and
5016 ** map->map_tapp instead of the default permanent error.
5019 map->map_mflags &= ~MF_DEFER;
5023 pmap = (PH_MAP_STRUCT *)map->map_db1;
5024 pmap->ph_fastclose = 0; /* refresh field for reopen */
5026 /* try each host in the list */
5027 hostlist = newstr(pmap->ph_servers);
5028 for (host = strtok(hostlist, " ");
5030 host = strtok(NULL, " "))
5033 if (pmap->ph_timeout != 0)
5035 if (setjmp(PHTimeout) != 0)
5039 sm_syslog(LOG_NOTICE, CurEnv->e_id,
5040 "timeout connecting to PH server %.100s",
5043 goto ph_map_open_abort;
5045 ev = sm_setevent(pmap->ph_timeout, ph_timeout, 0);
5048 /* open connection to server */
5049 if (ph_open(&(pmap->ph), host,
5050 PH_OPEN_ROUNDROBIN|PH_OPEN_DONTID,
5051 ph_map_send_debug, ph_map_recv_debug
5052 #if NPH_VERSION >= 10200
5056 && ph_id(pmap->ph, phmap_id) == 0)
5060 sm_free(hostlist); /* XXX */
5068 pmap->ph_fastclose = PH_CLOSE_FAST;
5073 if (bitset(MF_NODEFER, map->map_mflags))
5077 syserr("ph_map_open: %s: cannot connect to PH server",
5080 else if (!bitset(MF_OPTIONAL, map->map_mflags) && LogLevel > 1)
5081 sm_syslog(LOG_NOTICE, CurEnv->e_id,
5082 "ph_map_open: %s: cannot connect to PH server",
5084 sm_free(hostlist); /* XXX */
5089 ** PH_MAP_LOOKUP -- look up key from ph server
5093 ph_map_lookup(map, key, args, pstat)
5099 int i, save_errno = 0;
5100 register SM_EVENT *ev = NULL;
5101 PH_MAP_STRUCT *pmap;
5104 pmap = (PH_MAP_STRUCT *)map->map_db1;
5109 if (pmap->ph_timeout != 0)
5111 if (setjmp(PHTimeout) != 0)
5115 sm_syslog(LOG_NOTICE, CurEnv->e_id,
5116 "timeout during PH lookup of %.100s",
5119 *pstat = EX_TEMPFAIL;
5120 goto ph_map_lookup_abort;
5122 ev = sm_setevent(pmap->ph_timeout, ph_timeout, 0);
5125 /* perform lookup */
5126 i = ph_email_resolve(pmap->ph, key, pmap->ph_field_list, &value);
5128 *pstat = EX_TEMPFAIL;
5129 else if (i == PH_ERR_NOMATCH || i == PH_ERR_DATAERR)
5130 *pstat = EX_UNAVAILABLE;
5132 ph_map_lookup_abort:
5137 ** Close the connection if the timer popped
5138 ** or we got a temporary PH error
5141 if (*pstat == EX_TEMPFAIL)
5144 pmap->ph_fastclose = PH_CLOSE_FAST;
5149 if (*pstat == EX_OK)
5152 sm_dprintf("ph_map_lookup: %s => %s\n", key, value);
5154 if (bitset(MF_MATCHONLY, map->map_mflags))
5155 return map_rewrite(map, key, strlen(key), NULL);
5157 return map_rewrite(map, value, strlen(value), args);
5168 #define map_prio map_lockfd /* overload field */
5171 ** SYSLOG_MAP_PARSEARGS -- check for priority level to syslog messages.
5175 syslog_map_parseargs(map, args)
5180 char *priority = NULL;
5182 /* there is no check whether there is really an argument */
5185 while (isascii(*p) && isspace(*p))
5192 map->map_mflags |= MF_DEFER;
5197 map->map_spacesub = *++p;
5203 while (*++p != '\0' && isascii(*p) && isspace(*p))
5208 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
5215 syserr("Illegal option %c map syslog", *p);
5220 if (priority == NULL)
5221 map->map_prio = LOG_INFO;
5224 if (sm_strncasecmp("LOG_", priority, 4) == 0)
5228 if (sm_strcasecmp("EMERG", priority) == 0)
5229 map->map_prio = LOG_EMERG;
5231 #endif /* LOG_EMERG */
5233 if (sm_strcasecmp("ALERT", priority) == 0)
5234 map->map_prio = LOG_ALERT;
5236 #endif /* LOG_ALERT */
5238 if (sm_strcasecmp("CRIT", priority) == 0)
5239 map->map_prio = LOG_CRIT;
5241 #endif /* LOG_CRIT */
5243 if (sm_strcasecmp("ERR", priority) == 0)
5244 map->map_prio = LOG_ERR;
5246 #endif /* LOG_ERR */
5248 if (sm_strcasecmp("WARNING", priority) == 0)
5249 map->map_prio = LOG_WARNING;
5251 #endif /* LOG_WARNING */
5253 if (sm_strcasecmp("NOTICE", priority) == 0)
5254 map->map_prio = LOG_NOTICE;
5256 #endif /* LOG_NOTICE */
5258 if (sm_strcasecmp("INFO", priority) == 0)
5259 map->map_prio = LOG_INFO;
5261 #endif /* LOG_INFO */
5263 if (sm_strcasecmp("DEBUG", priority) == 0)
5264 map->map_prio = LOG_DEBUG;
5266 #endif /* LOG_DEBUG */
5268 syserr("syslog_map_parseargs: Unknown priority %s",
5277 ** SYSLOG_MAP_LOOKUP -- rewrite and syslog message. Always return empty string
5281 syslog_map_lookup(map, string, args, statp)
5287 char *ptr = map_rewrite(map, string, strlen(string), args);
5292 sm_dprintf("syslog_map_lookup(%s (priority %d): %s\n",
5293 map->map_mname, map->map_prio, ptr);
5295 sm_syslog(map->map_prio, CurEnv->e_id, "%s", ptr);
5302 #if _FFR_DPRINTF_MAP
5307 #define map_dbg_level map_lockfd /* overload field */
5310 ** DPRINTF_MAP_PARSEARGS -- check for priority level to dprintf messages.
5314 dprintf_map_parseargs(map, args)
5319 char *dbg_level = NULL;
5321 /* there is no check whether there is really an argument */
5324 while (isascii(*p) && isspace(*p))
5331 map->map_mflags |= MF_DEFER;
5336 map->map_spacesub = *++p;
5342 while (*++p != '\0' && isascii(*p) && isspace(*p))
5347 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
5354 syserr("Illegal option %c map dprintf", *p);
5359 if (dbg_level == NULL)
5360 map->map_dbg_level = 0;
5363 if (!(isascii(*dbg_level) && isdigit(*dbg_level)))
5365 syserr("dprintf map \"%s\", file %s: -d should specify a number, not %s",
5366 map->map_mname, map->map_file,
5370 map->map_dbg_level = atoi(dbg_level);
5376 ** DPRINTF_MAP_LOOKUP -- rewrite and print message. Always return empty string
5380 dprintf_map_lookup(map, string, args, statp)
5386 char *ptr = map_rewrite(map, string, strlen(string), args);
5388 if (ptr != NULL && tTd(85, map->map_dbg_level))
5389 sm_dprintf("%s\n", ptr);
5393 #endif /* _FFR_DPRINTF_MAP */
5402 hes_map_open(map, mode)
5407 sm_dprintf("hes_map_open(%s, %s, %d)\n",
5408 map->map_mname, map->map_file, mode);
5410 if (mode != O_RDONLY)
5412 /* issue a pseudo-error message */
5413 errno = SM_EMAPCANTWRITE;
5418 if (HesiodContext != NULL || hesiod_init(&HesiodContext) == 0)
5421 if (!bitset(MF_OPTIONAL, map->map_mflags))
5422 syserr("451 4.3.5 cannot initialize Hesiod map (%s)",
5423 sm_errstring(errno));
5425 # else /* HESIOD_INIT */
5426 if (hes_error() == HES_ER_UNINIT)
5428 switch (hes_error())
5431 case HES_ER_NOTFOUND:
5435 if (!bitset(MF_OPTIONAL, map->map_mflags))
5436 syserr("451 4.3.5 cannot initialize Hesiod map (%d)", hes_error());
5439 # endif /* HESIOD_INIT */
5443 hes_map_lookup(map, name, av, statp)
5452 sm_dprintf("hes_map_lookup(%s, %s)\n", map->map_file, name);
5454 if (name[0] == '\\')
5462 if (nl < sizeof(nbuf) - 1)
5465 np = xalloc(strlen(name) + 2);
5467 (void) sm_strlcpy(&np[1], name, (sizeof(nbuf)) - 1);
5469 hp = hesiod_resolve(HesiodContext, np, map->map_file);
5470 # else /* HESIOD_INIT */
5471 hp = hes_resolve(np, map->map_file);
5472 # endif /* HESIOD_INIT */
5475 sm_free(np); /* XXX */
5481 hp = hesiod_resolve(HesiodContext, name, map->map_file);
5482 # else /* HESIOD_INIT */
5483 hp = hes_resolve(name, map->map_file);
5484 # endif /* HESIOD_INIT */
5487 if (hp == NULL || *hp == NULL)
5492 *statp = EX_NOTFOUND;
5495 *statp = EX_TEMPFAIL;
5500 *statp = EX_UNAVAILABLE;
5504 hesiod_free_list(HesiodContext, hp);
5507 # else /* HESIOD_INIT */
5508 if (hp == NULL || hp[0] == NULL)
5510 switch (hes_error())
5516 case HES_ER_NOTFOUND:
5517 *statp = EX_NOTFOUND;
5521 *statp = EX_UNAVAILABLE;
5525 *statp = EX_TEMPFAIL;
5530 # endif /* HESIOD_INIT */
5532 if (bitset(MF_MATCHONLY, map->map_mflags))
5533 return map_rewrite(map, name, strlen(name), NULL);
5535 return map_rewrite(map, hp[0], strlen(hp[0]), av);
5539 ** HES_MAP_CLOSE -- free the Hesiod context
5547 sm_dprintf("hes_map_close(%s)\n", map->map_file);
5550 /* Free the hesiod context */
5551 if (HesiodContext != NULL)
5553 hesiod_end(HesiodContext);
5554 HesiodContext = NULL;
5556 # endif /* HESIOD_INIT */
5561 ** NeXT NETINFO Modules
5566 # define NETINFO_DEFAULT_DIR "/aliases"
5567 # define NETINFO_DEFAULT_PROPERTY "members"
5570 ** NI_MAP_OPEN -- open NetInfo Aliases
5574 ni_map_open(map, mode)
5579 sm_dprintf("ni_map_open(%s, %s, %d)\n",
5580 map->map_mname, map->map_file, mode);
5583 if (*map->map_file == '\0')
5584 map->map_file = NETINFO_DEFAULT_DIR;
5586 if (map->map_valcolnm == NULL)
5587 map->map_valcolnm = NETINFO_DEFAULT_PROPERTY;
5589 if (map->map_coldelim == '\0')
5591 if (bitset(MF_ALIAS, map->map_mflags))
5592 map->map_coldelim = ',';
5593 else if (bitset(MF_FILECLASS, map->map_mflags))
5594 map->map_coldelim = ' ';
5601 ** NI_MAP_LOOKUP -- look up a datum in NetInfo
5605 ni_map_lookup(map, name, av, statp)
5615 sm_dprintf("ni_map_lookup(%s, %s)\n", map->map_mname, name);
5617 propval = ni_propval(map->map_file, map->map_keycolnm, name,
5618 map->map_valcolnm, map->map_coldelim);
5620 if (propval == NULL)
5624 if (bitset(MF_MATCHONLY, map->map_mflags))
5625 res = map_rewrite(map, name, strlen(name), NULL);
5627 res = map_rewrite(map, propval, strlen(propval), av);
5636 ni_getcanonname(name, hbsize, statp)
5643 char nbuf[MAXNAME + 1];
5646 sm_dprintf("ni_getcanonname(%s)\n", name);
5648 if (sm_strlcpy(nbuf, name, sizeof(nbuf)) >= sizeof(nbuf))
5650 *statp = EX_UNAVAILABLE;
5653 (void) shorten_hostname(nbuf);
5655 /* we only accept single token search key */
5656 if (strchr(nbuf, '.'))
5663 vptr = ni_propval("/machines", NULL, nbuf, "name", '\n');
5671 /* Only want the first machine name */
5672 if ((ptr = strchr(vptr, '\n')) != NULL)
5675 if (sm_strlcpy(name, vptr, hbsize) >= hbsize)
5678 *statp = EX_UNAVAILABLE;
5685 #endif /* NETINFO */
5687 ** TEXT (unindexed text file) Modules
5689 ** This code donated by Sun Microsystems.
5692 #define map_sff map_lockfd /* overload field */
5696 ** TEXT_MAP_OPEN -- open text table
5700 text_map_open(map, mode)
5708 sm_dprintf("text_map_open(%s, %s, %d)\n",
5709 map->map_mname, map->map_file, mode);
5712 if (mode != O_RDONLY)
5718 if (*map->map_file == '\0')
5720 syserr("text map \"%s\": file name required",
5725 if (map->map_file[0] != '/')
5727 syserr("text map \"%s\": file name must be fully qualified",
5732 sff = SFF_ROOTOK|SFF_REGONLY;
5733 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
5735 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
5736 sff |= SFF_SAFEDIRPATH;
5737 if ((i = safefile(map->map_file, RunAsUid, RunAsGid, RunAsUserName,
5738 sff, S_IRUSR, NULL)) != 0)
5740 int save_errno = errno;
5742 /* cannot open this map */
5744 sm_dprintf("\tunsafe map file: %d\n", i);
5746 if (!bitset(MF_OPTIONAL, map->map_mflags))
5747 syserr("text map \"%s\": unsafe map file %s",
5748 map->map_mname, map->map_file);
5752 if (map->map_keycolnm == NULL)
5753 map->map_keycolno = 0;
5756 if (!(isascii(*map->map_keycolnm) && isdigit(*map->map_keycolnm)))
5758 syserr("text map \"%s\", file %s: -k should specify a number, not %s",
5759 map->map_mname, map->map_file,
5763 map->map_keycolno = atoi(map->map_keycolnm);
5766 if (map->map_valcolnm == NULL)
5767 map->map_valcolno = 0;
5770 if (!(isascii(*map->map_valcolnm) && isdigit(*map->map_valcolnm)))
5772 syserr("text map \"%s\", file %s: -v should specify a number, not %s",
5773 map->map_mname, map->map_file,
5777 map->map_valcolno = atoi(map->map_valcolnm);
5782 sm_dprintf("text_map_open(%s, %s): delimiter = ",
5783 map->map_mname, map->map_file);
5784 if (map->map_coldelim == '\0')
5785 sm_dprintf("(white space)\n");
5787 sm_dprintf("%c\n", map->map_coldelim);
5796 ** TEXT_MAP_LOOKUP -- look up a datum in a TEXT table
5800 text_map_lookup(map, name, av, statp)
5813 long sff = map->map_sff;
5814 char search_key[MAXNAME + 1];
5815 char linebuf[MAXLINE];
5816 char buf[MAXNAME + 1];
5820 sm_dprintf("text_map_lookup(%s, %s)\n", map->map_mname, name);
5822 buflen = strlen(name);
5823 if (buflen > sizeof(search_key) - 1)
5824 buflen = sizeof(search_key) - 1; /* XXX just cut if off? */
5825 memmove(search_key, name, buflen);
5826 search_key[buflen] = '\0';
5827 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
5828 makelower(search_key);
5830 f = safefopen(map->map_file, O_RDONLY, FileMode, sff);
5833 map->map_mflags &= ~(MF_VALID|MF_OPEN);
5834 *statp = EX_UNAVAILABLE;
5837 key_idx = map->map_keycolno;
5838 delim = map->map_coldelim;
5839 while (sm_io_fgets(f, SM_TIME_DEFAULT,
5840 linebuf, sizeof(linebuf)) >= 0)
5844 /* skip comment line */
5845 if (linebuf[0] == '#')
5847 p = strchr(linebuf, '\n');
5850 p = get_column(linebuf, key_idx, delim, buf, sizeof(buf));
5851 if (p != NULL && sm_strcasecmp(search_key, p) == 0)
5857 (void) sm_io_close(f, SM_TIME_DEFAULT);
5860 *statp = EX_NOTFOUND;
5863 vp = get_column(linebuf, map->map_valcolno, delim, buf, sizeof(buf));
5866 *statp = EX_NOTFOUND;
5871 if (bitset(MF_MATCHONLY, map->map_mflags))
5872 return map_rewrite(map, name, strlen(name), NULL);
5874 return map_rewrite(map, vp, vsize, av);
5878 ** TEXT_GETCANONNAME -- look up canonical name in hosts file
5882 text_getcanonname(name, hbsize, statp)
5890 char linebuf[MAXLINE];
5891 char cbuf[MAXNAME + 1];
5892 char nbuf[MAXNAME + 1];
5895 sm_dprintf("text_getcanonname(%s)\n", name);
5897 if (sm_strlcpy(nbuf, name, sizeof(nbuf)) >= sizeof(nbuf))
5899 *statp = EX_UNAVAILABLE;
5902 dot = shorten_hostname(nbuf);
5904 f = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, HostsFile, SM_IO_RDONLY,
5908 *statp = EX_UNAVAILABLE;
5913 sm_io_fgets(f, SM_TIME_DEFAULT,
5914 linebuf, sizeof(linebuf)) >= 0)
5916 char *p = strpbrk(linebuf, "#\n");
5920 if (linebuf[0] != '\0')
5921 found = extract_canonname(nbuf, dot, linebuf,
5922 cbuf, sizeof(cbuf));
5924 (void) sm_io_close(f, SM_TIME_DEFAULT);
5931 if (sm_strlcpy(name, cbuf, hbsize) >= hbsize)
5933 *statp = EX_UNAVAILABLE;
5940 ** STAB (Symbol Table) Modules
5945 ** STAB_MAP_LOOKUP -- look up alias in symbol table
5950 stab_map_lookup(map, name, av, pstat)
5959 sm_dprintf("stab_lookup(%s, %s)\n",
5960 map->map_mname, name);
5962 s = stab(name, ST_ALIAS, ST_FIND);
5965 if (bitset(MF_MATCHONLY, map->map_mflags))
5966 return map_rewrite(map, name, strlen(name), NULL);
5968 return map_rewrite(map, s->s_alias, strlen(s->s_alias), av);
5972 ** STAB_MAP_STORE -- store in symtab (actually using during init, not rebuild)
5976 stab_map_store(map, lhs, rhs)
5983 s = stab(lhs, ST_ALIAS, ST_ENTER);
5984 s->s_alias = newstr(rhs);
5989 ** STAB_MAP_OPEN -- initialize (reads data file)
5991 ** This is a weird case -- it is only intended as a fallback for
5992 ** aliases. For this reason, opens for write (only during a
5993 ** "newaliases") always fails, and opens for read open the
5994 ** actual underlying text file instead of the database.
5998 stab_map_open(map, mode)
6007 sm_dprintf("stab_map_open(%s, %s, %d)\n",
6008 map->map_mname, map->map_file, mode);
6011 if (mode != O_RDONLY)
6017 sff = SFF_ROOTOK|SFF_REGONLY;
6018 if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail))
6020 if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail))
6021 sff |= SFF_SAFEDIRPATH;
6022 af = safefopen(map->map_file, O_RDONLY, 0444, sff);
6025 readaliases(map, af, false, false);
6027 if (fstat(sm_io_getinfo(af, SM_IO_WHAT_FD, NULL), &st) >= 0)
6028 map->map_mtime = st.st_mtime;
6029 (void) sm_io_close(af, SM_TIME_DEFAULT);
6036 ** Tries several types. For back compatibility of aliases.
6041 ** IMPL_MAP_LOOKUP -- lookup in best open database
6045 impl_map_lookup(map, name, av, pstat)
6052 sm_dprintf("impl_map_lookup(%s, %s)\n",
6053 map->map_mname, name);
6056 if (bitset(MF_IMPL_HASH, map->map_mflags))
6057 return db_map_lookup(map, name, av, pstat);
6060 if (bitset(MF_IMPL_NDBM, map->map_mflags))
6061 return ndbm_map_lookup(map, name, av, pstat);
6063 return stab_map_lookup(map, name, av, pstat);
6067 ** IMPL_MAP_STORE -- store in open databases
6071 impl_map_store(map, lhs, rhs)
6077 sm_dprintf("impl_map_store(%s, %s, %s)\n",
6078 map->map_mname, lhs, rhs);
6080 if (bitset(MF_IMPL_HASH, map->map_mflags))
6081 db_map_store(map, lhs, rhs);
6084 if (bitset(MF_IMPL_NDBM, map->map_mflags))
6085 ndbm_map_store(map, lhs, rhs);
6087 stab_map_store(map, lhs, rhs);
6091 ** IMPL_MAP_OPEN -- implicit database open
6095 impl_map_open(map, mode)
6100 sm_dprintf("impl_map_open(%s, %s, %d)\n",
6101 map->map_mname, map->map_file, mode);
6105 map->map_mflags |= MF_IMPL_HASH;
6106 if (hash_map_open(map, mode))
6108 # ifdef NDBM_YP_COMPAT
6109 if (mode == O_RDONLY || strstr(map->map_file, "/yp/") == NULL)
6110 # endif /* NDBM_YP_COMPAT */
6114 map->map_mflags &= ~MF_IMPL_HASH;
6117 map->map_mflags |= MF_IMPL_NDBM;
6118 if (ndbm_map_open(map, mode))
6123 map->map_mflags &= ~MF_IMPL_NDBM;
6126 #if defined(NEWDB) || defined(NDBM)
6128 message("WARNING: cannot open alias database %s%s",
6130 mode == O_RDONLY ? "; reading text version" : "");
6131 #else /* defined(NEWDB) || defined(NDBM) */
6132 if (mode != O_RDONLY)
6133 usrerr("Cannot rebuild aliases: no database format defined");
6134 #endif /* defined(NEWDB) || defined(NDBM) */
6136 if (mode == O_RDONLY)
6137 return stab_map_open(map, mode);
6144 ** IMPL_MAP_CLOSE -- close any open database(s)
6152 sm_dprintf("impl_map_close(%s, %s, %lx)\n",
6153 map->map_mname, map->map_file, map->map_mflags);
6155 if (bitset(MF_IMPL_HASH, map->map_mflags))
6158 map->map_mflags &= ~MF_IMPL_HASH;
6163 if (bitset(MF_IMPL_NDBM, map->map_mflags))
6165 ndbm_map_close(map);
6166 map->map_mflags &= ~MF_IMPL_NDBM;
6173 ** Provides access to the system password file.
6177 ** USER_MAP_OPEN -- open user map
6179 ** Really just binds field names to field numbers.
6183 user_map_open(map, mode)
6188 sm_dprintf("user_map_open(%s, %d)\n",
6189 map->map_mname, mode);
6192 if (mode != O_RDONLY)
6194 /* issue a pseudo-error message */
6195 errno = SM_EMAPCANTWRITE;
6198 if (map->map_valcolnm == NULL)
6201 else if (sm_strcasecmp(map->map_valcolnm, "name") == 0)
6202 map->map_valcolno = 1;
6203 else if (sm_strcasecmp(map->map_valcolnm, "passwd") == 0)
6204 map->map_valcolno = 2;
6205 else if (sm_strcasecmp(map->map_valcolnm, "uid") == 0)
6206 map->map_valcolno = 3;
6207 else if (sm_strcasecmp(map->map_valcolnm, "gid") == 0)
6208 map->map_valcolno = 4;
6209 else if (sm_strcasecmp(map->map_valcolnm, "gecos") == 0)
6210 map->map_valcolno = 5;
6211 else if (sm_strcasecmp(map->map_valcolnm, "dir") == 0)
6212 map->map_valcolno = 6;
6213 else if (sm_strcasecmp(map->map_valcolnm, "shell") == 0)
6214 map->map_valcolno = 7;
6217 syserr("User map %s: unknown column name %s",
6218 map->map_mname, map->map_valcolnm);
6226 ** USER_MAP_LOOKUP -- look up a user in the passwd file.
6231 user_map_lookup(map, key, av, statp)
6241 sm_dprintf("user_map_lookup(%s, %s)\n",
6242 map->map_mname, key);
6244 *statp = finduser(key, &fuzzy, &user);
6245 if (*statp != EX_OK)
6247 if (bitset(MF_MATCHONLY, map->map_mflags))
6248 return map_rewrite(map, key, strlen(key), NULL);
6254 switch (map->map_valcolno)
6258 rwval = user.mbdb_name;
6262 rwval = "x"; /* passwd no longer supported */
6266 (void) sm_snprintf(buf, sizeof(buf), "%d",
6267 (int) user.mbdb_uid);
6272 (void) sm_snprintf(buf, sizeof(buf), "%d",
6273 (int) user.mbdb_gid);
6278 rwval = user.mbdb_fullname;
6282 rwval = user.mbdb_homedir;
6286 rwval = user.mbdb_shell;
6289 syserr("user_map %s: bogus field %d",
6290 map->map_mname, map->map_valcolno);
6293 return map_rewrite(map, rwval, strlen(rwval), av);
6297 ** Program map type.
6299 ** This provides access to arbitrary programs. It should be used
6300 ** only very sparingly, since there is no way to bound the cost
6301 ** of invoking an arbitrary program.
6305 prog_map_lookup(map, name, av, statp)
6318 char *argv[MAXPV + 1];
6322 sm_dprintf("prog_map_lookup(%s, %s) %s\n",
6323 map->map_mname, name, map->map_file);
6326 argv[i++] = map->map_file;
6327 if (map->map_rebuild != NULL)
6329 (void) sm_strlcpy(buf, map->map_rebuild, sizeof(buf));
6330 for (p = strtok(buf, " \t"); p != NULL; p = strtok(NULL, " \t"))
6341 sm_dprintf("prog_open:");
6342 for (i = 0; argv[i] != NULL; i++)
6343 sm_dprintf(" %s", argv[i]);
6346 (void) sm_blocksignal(SIGCHLD);
6347 pid = prog_open(argv, &fd, CurEnv);
6350 if (!bitset(MF_OPTIONAL, map->map_mflags))
6351 syserr("prog_map_lookup(%s) failed (%s) -- closing",
6352 map->map_mname, sm_errstring(errno));
6353 else if (tTd(38, 9))
6354 sm_dprintf("prog_map_lookup(%s) failed (%s) -- closing",
6355 map->map_mname, sm_errstring(errno));
6356 map->map_mflags &= ~(MF_VALID|MF_OPEN);
6360 i = read(fd, buf, sizeof(buf) - 1);
6363 syserr("prog_map_lookup(%s): read error %s",
6364 map->map_mname, sm_errstring(errno));
6370 sm_dprintf("prog_map_lookup(%s): empty answer\n",
6377 p = strchr(buf, '\n');
6381 /* collect the return value */
6382 if (bitset(MF_MATCHONLY, map->map_mflags))
6383 rval = map_rewrite(map, name, strlen(name), NULL);
6385 rval = map_rewrite(map, buf, strlen(buf), av);
6387 /* now flush any additional output */
6388 while ((i = read(fd, buf, sizeof(buf))) > 0)
6392 /* wait for the process to terminate */
6394 status = waitfor(pid);
6396 (void) sm_releasesignal(SIGCHLD);
6401 syserr("prog_map_lookup(%s): wait error %s",
6402 map->map_mname, sm_errstring(errno));
6403 *statp = EX_SOFTWARE;
6406 else if (WIFEXITED(status))
6408 if ((*statp = WEXITSTATUS(status)) != EX_OK)
6413 syserr("prog_map_lookup(%s): child died on signal %d",
6414 map->map_mname, status);
6415 *statp = EX_UNAVAILABLE;
6421 ** Sequenced map type.
6423 ** Tries each map in order until something matches, much like
6424 ** implicit. Stores go to the first map in the list that can
6427 ** This is slightly unusual in that there are two interfaces.
6428 ** The "sequence" interface lets you stack maps arbitrarily.
6429 ** The "switch" interface builds a sequence map by looking
6430 ** at a system-dependent configuration file such as
6431 ** /etc/nsswitch.conf on Solaris or /etc/svc.conf on Ultrix.
6433 ** We don't need an explicit open, since all maps are
6434 ** opened on demand.
6438 ** SEQ_MAP_PARSE -- Sequenced map parsing
6442 seq_map_parse(map, ap)
6449 sm_dprintf("seq_map_parse(%s, %s)\n", map->map_mname, ap);
6456 /* find beginning of map name */
6457 while (isascii(*ap) && isspace(*ap))
6460 (isascii(*p) && isalnum(*p)) || *p == '_' || *p == '.';
6465 while (*p != '\0' && (!isascii(*p) || !isalnum(*p)))
6472 s = stab(ap, ST_MAP, ST_FIND);
6475 syserr("Sequence map %s: unknown member map %s",
6476 map->map_mname, ap);
6478 else if (maxmap >= MAXMAPSTACK)
6480 syserr("Sequence map %s: too many member maps (%d max)",
6481 map->map_mname, MAXMAPSTACK);
6484 else if (maxmap < MAXMAPSTACK)
6486 map->map_stack[maxmap++] = &s->s_map;
6494 ** SWITCH_MAP_OPEN -- open a switched map
6496 ** This looks at the system-dependent configuration and builds
6497 ** a sequence map that does the same thing.
6499 ** Every system must define a switch_map_find routine in conf.c
6500 ** that will return the list of service types associated with a
6501 ** given service class.
6505 switch_map_open(map, mode)
6511 char *maptype[MAXMAPSTACK];
6514 sm_dprintf("switch_map_open(%s, %s, %d)\n",
6515 map->map_mname, map->map_file, mode);
6518 nmaps = switch_map_find(map->map_file, maptype, map->map_return);
6521 sm_dprintf("\tswitch_map_find => %d\n", nmaps);
6522 for (mapno = 0; mapno < nmaps; mapno++)
6523 sm_dprintf("\t\t%s\n", maptype[mapno]);
6525 if (nmaps <= 0 || nmaps > MAXMAPSTACK)
6528 for (mapno = 0; mapno < nmaps; mapno++)
6531 char nbuf[MAXNAME + 1];
6533 if (maptype[mapno] == NULL)
6535 (void) sm_strlcpyn(nbuf, sizeof(nbuf), 3,
6536 map->map_mname, ".", maptype[mapno]);
6537 s = stab(nbuf, ST_MAP, ST_FIND);
6540 syserr("Switch map %s: unknown member map %s",
6541 map->map_mname, nbuf);
6545 map->map_stack[mapno] = &s->s_map;
6547 sm_dprintf("\tmap_stack[%d] = %s:%s\n",
6549 s->s_map.map_class->map_cname,
6558 ** SEQ_MAP_CLOSE -- close all underlying maps
6568 sm_dprintf("seq_map_close(%s)\n", map->map_mname);
6570 for (mapno = 0; mapno < MAXMAPSTACK; mapno++)
6572 MAP *mm = map->map_stack[mapno];
6574 if (mm == NULL || !bitset(MF_OPEN, mm->map_mflags))
6576 mm->map_mflags |= MF_CLOSING;
6577 mm->map_class->map_close(mm);
6578 mm->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING);
6584 ** SEQ_MAP_LOOKUP -- sequenced map lookup
6588 seq_map_lookup(map, key, args, pstat)
6596 bool tempfail = false;
6599 sm_dprintf("seq_map_lookup(%s, %s)\n", map->map_mname, key);
6601 for (mapno = 0; mapno < MAXMAPSTACK; mapbit <<= 1, mapno++)
6603 MAP *mm = map->map_stack[mapno];
6608 if (!bitset(MF_OPEN, mm->map_mflags) &&
6611 if (bitset(mapbit, map->map_return[MA_UNAVAIL]))
6613 *pstat = EX_UNAVAILABLE;
6619 rv = mm->map_class->map_lookup(mm, key, args, pstat);
6622 if (*pstat == EX_TEMPFAIL)
6624 if (bitset(mapbit, map->map_return[MA_TRYAGAIN]))
6628 else if (bitset(mapbit, map->map_return[MA_NOTFOUND]))
6632 *pstat = EX_TEMPFAIL;
6633 else if (*pstat == EX_OK)
6634 *pstat = EX_NOTFOUND;
6639 ** SEQ_MAP_STORE -- sequenced map store
6643 seq_map_store(map, key, val)
6651 sm_dprintf("seq_map_store(%s, %s, %s)\n",
6652 map->map_mname, key, val);
6654 for (mapno = 0; mapno < MAXMAPSTACK; mapno++)
6656 MAP *mm = map->map_stack[mapno];
6658 if (mm == NULL || !bitset(MF_WRITABLE, mm->map_mflags))
6661 mm->map_class->map_store(mm, key, val);
6664 syserr("seq_map_store(%s, %s, %s): no writable map",
6665 map->map_mname, key, val);
6673 null_map_open(map, mode)
6689 null_map_lookup(map, key, args, pstat)
6695 *pstat = EX_NOTFOUND;
6701 null_map_store(map, key, val)
6709 MAPCLASS NullMapClass =
6711 "null-map", NULL, 0,
6712 NULL, null_map_lookup, null_map_store,
6713 null_map_open, null_map_close,
6721 bogus_map_lookup(map, key, args, pstat)
6727 *pstat = EX_TEMPFAIL;
6731 MAPCLASS BogusMapClass =
6733 "bogus-map", NULL, 0,
6734 NULL, bogus_map_lookup, null_map_store,
6735 null_map_open, null_map_close,
6742 macro_map_lookup(map, name, av, statp)
6751 sm_dprintf("macro_map_lookup(%s, %s)\n", map->map_mname,
6752 name == NULL ? "NULL" : name);
6756 (mid = macid(name)) == 0)
6763 macdefine(&CurEnv->e_macro, A_PERM, mid, NULL);
6765 macdefine(&CurEnv->e_macro, A_TEMP, mid, av[1]);
6778 # define DEFAULT_DELIM CONDELSE
6779 # define END_OF_FIELDS -1
6780 # define ERRBUF_SIZE 80
6781 # define MAX_MATCH 32
6783 # define xnalloc(s) memset(xalloc(s), '\0', s);
6787 regex_t *regex_pattern_buf; /* xalloc it */
6788 int *regex_subfields; /* move to type MAP */
6789 char *regex_delim; /* move to type MAP */
6792 static int parse_fields __P((char *, int *, int, int));
6793 static char *regex_map_rewrite __P((MAP *, const char*, size_t, char **));
6796 parse_fields(s, ibuf, blen, nr_substrings)
6798 int *ibuf; /* array */
6799 int blen; /* number of elements in ibuf */
6800 int nr_substrings; /* number of substrings in the pattern */
6804 bool lastone = false;
6806 blen--; /* for terminating END_OF_FIELDS */
6827 if (val < 0 || val >= nr_substrings)
6829 syserr("field (%d) out of range, only %d substrings in pattern",
6830 val, nr_substrings);
6837 syserr("too many fields, %d max", blen);
6842 ibuf[i] = END_OF_FIELDS;
6847 regex_map_init(map, ap)
6852 struct regex_map *map_p;
6854 char *sub_param = NULL;
6856 static char defdstr[] = { (char) DEFAULT_DELIM, '\0' };
6859 sm_dprintf("regex_map_init: mapname '%s', args '%s'\n",
6860 map->map_mname, ap);
6862 pflags = REG_ICASE | REG_EXTENDED | REG_NOSUB;
6864 map_p = (struct regex_map *) xnalloc(sizeof(*map_p));
6865 map_p->regex_pattern_buf = (regex_t *)xnalloc(sizeof(regex_t));
6869 while (isascii(*p) && isspace(*p))
6876 map->map_mflags |= MF_REGEX_NOT;
6879 case 'f': /* case sensitive */
6880 map->map_mflags |= MF_NOFOLDCASE;
6881 pflags &= ~REG_ICASE;
6884 case 'b': /* basic regular expressions */
6885 pflags &= ~REG_EXTENDED;
6888 case 's': /* substring match () syntax */
6890 pflags &= ~REG_NOSUB;
6893 case 'd': /* delimiter */
6894 map_p->regex_delim = ++p;
6897 case 'a': /* map append */
6901 case 'm': /* matchonly */
6902 map->map_mflags |= MF_MATCHONLY;
6906 map->map_mflags |= MF_KEEPQUOTES;
6910 map->map_spacesub = *++p;
6914 map->map_mflags |= MF_DEFER;
6918 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
6924 sm_dprintf("regex_map_init: compile '%s' 0x%x\n", p, pflags);
6926 if ((regerr = regcomp(map_p->regex_pattern_buf, p, pflags)) != 0)
6929 char errbuf[ERRBUF_SIZE];
6931 (void) regerror(regerr, map_p->regex_pattern_buf,
6932 errbuf, sizeof(errbuf));
6933 syserr("pattern-compile-error: %s", errbuf);
6934 sm_free(map_p->regex_pattern_buf); /* XXX */
6935 sm_free(map_p); /* XXX */
6939 if (map->map_app != NULL)
6940 map->map_app = newstr(map->map_app);
6941 if (map_p->regex_delim != NULL)
6942 map_p->regex_delim = newstr(map_p->regex_delim);
6944 map_p->regex_delim = defdstr;
6946 if (!bitset(REG_NOSUB, pflags))
6948 /* substring matching */
6950 int *fields = (int *) xalloc(sizeof(int) * (MAX_MATCH + 1));
6952 substrings = map_p->regex_pattern_buf->re_nsub + 1;
6955 sm_dprintf("regex_map_init: nr of substrings %d\n",
6958 if (substrings >= MAX_MATCH)
6960 syserr("too many substrings, %d max", MAX_MATCH);
6961 sm_free(map_p->regex_pattern_buf); /* XXX */
6962 sm_free(map_p); /* XXX */
6965 if (sub_param != NULL && sub_param[0] != '\0')
6967 /* optional parameter -sfields */
6968 if (parse_fields(sub_param, fields,
6969 MAX_MATCH + 1, substrings) == -1)
6976 /* set default fields */
6977 for (i = 0; i < substrings; i++)
6979 fields[i] = END_OF_FIELDS;
6981 map_p->regex_subfields = fields;
6986 sm_dprintf("regex_map_init: subfields");
6987 for (ip = fields; *ip != END_OF_FIELDS; ip++)
6988 sm_dprintf(" %d", *ip);
6992 map->map_db1 = (ARBPTR_T) map_p; /* dirty hack */
6997 regex_map_rewrite(map, s, slen, av)
7003 if (bitset(MF_MATCHONLY, map->map_mflags))
7004 return map_rewrite(map, av[0], strlen(av[0]), NULL);
7006 return map_rewrite(map, s, slen, av);
7010 regex_map_lookup(map, name, av, statp)
7017 struct regex_map *map_p;
7018 regmatch_t pmatch[MAX_MATCH];
7024 sm_dprintf("regex_map_lookup: key '%s'\n", name);
7025 for (cpp = av; cpp != NULL && *cpp != NULL; cpp++)
7026 sm_dprintf("regex_map_lookup: arg '%s'\n", *cpp);
7029 map_p = (struct regex_map *)(map->map_db1);
7030 reg_res = regexec(map_p->regex_pattern_buf,
7031 name, MAX_MATCH, pmatch, 0);
7033 if (bitset(MF_REGEX_NOT, map->map_mflags))
7036 if (reg_res == REG_NOMATCH)
7037 return regex_map_rewrite(map, "", (size_t) 0, av);
7041 if (reg_res == REG_NOMATCH)
7044 if (map_p->regex_subfields != NULL)
7047 static char retbuf[MAXNAME];
7048 int fields[MAX_MATCH + 1];
7050 int anglecnt = 0, cmntcnt = 0, spacecnt = 0;
7051 bool quotemode = false, bslashmode = false;
7052 register char *dp, *sp;
7057 ldp = retbuf + sizeof(retbuf) - 1;
7061 if (parse_fields(av[1], fields, MAX_MATCH + 1,
7062 (int) map_p->regex_pattern_buf->re_nsub + 1) == -1)
7070 ip = map_p->regex_subfields;
7072 for ( ; *ip != END_OF_FIELDS; ip++)
7076 for (sp = map_p->regex_delim; *sp; sp++)
7085 if (*ip >= MAX_MATCH ||
7086 pmatch[*ip].rm_so < 0 || pmatch[*ip].rm_eo < 0)
7089 sp = name + pmatch[*ip].rm_so;
7090 endp = name + pmatch[*ip].rm_eo;
7091 for (; endp > sp; sp++)
7100 else if (quotemode && *sp != '"' &&
7105 else switch (*dp++ = *sp)
7132 quotemode = !quotemode;
7138 if (anglecnt != 0 || cmntcnt != 0 || quotemode ||
7139 bslashmode || spacecnt != 0)
7141 sm_syslog(LOG_WARNING, NOQID,
7142 "Warning: regex may cause prescan() failure map=%s lookup=%s",
7143 map->map_mname, name);
7149 return regex_map_rewrite(map, retbuf, strlen(retbuf), av);
7151 return regex_map_rewrite(map, "", (size_t)0, av);
7153 #endif /* MAP_REGEX */
7160 # define _DATUM_DEFINED
7161 # include <ns_api.h>
7163 typedef struct ns_map_list
7165 ns_map_t *map; /* XXX ns_ ? */
7167 struct ns_map_list *next;
7171 ns_map_t_find(mapname)
7174 static ns_map_list_t *ns_maps = NULL;
7175 ns_map_list_t *ns_map;
7177 /* walk the list of maps looking for the correctly named map */
7178 for (ns_map = ns_maps; ns_map != NULL; ns_map = ns_map->next)
7180 if (strcmp(ns_map->mapname, mapname) == 0)
7184 /* if we are looking at a NULL ns_map_list_t, then create a new one */
7187 ns_map = (ns_map_list_t *) xalloc(sizeof(*ns_map));
7188 ns_map->mapname = newstr(mapname);
7189 ns_map->map = (ns_map_t *) xalloc(sizeof(*ns_map->map));
7190 memset(ns_map->map, '\0', sizeof(*ns_map->map));
7191 ns_map->next = ns_maps;
7198 nsd_map_lookup(map, name, av, statp)
7207 char keybuf[MAXNAME + 1];
7211 sm_dprintf("nsd_map_lookup(%s, %s)\n", map->map_mname, name);
7213 buflen = strlen(name);
7214 if (buflen > sizeof(keybuf) - 1)
7215 buflen = sizeof(keybuf) - 1; /* XXX simply cut off? */
7216 memmove(keybuf, name, buflen);
7217 keybuf[buflen] = '\0';
7218 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
7221 ns_map = ns_map_t_find(map->map_file);
7225 sm_dprintf("nsd_map_t_find failed\n");
7226 *statp = EX_UNAVAILABLE;
7229 r = ns_lookup(ns_map, NULL, map->map_file, keybuf, NULL,
7231 if (r == NS_UNAVAIL || r == NS_TRYAGAIN)
7233 *statp = EX_TEMPFAIL;
7239 # endif /* NS_NOPERM */
7245 if (r != NS_SUCCESS)
7247 *statp = EX_NOTFOUND;
7253 /* Null out trailing \n */
7254 if ((p = strchr(buf, '\n')) != NULL)
7257 return map_rewrite(map, buf, strlen(buf), av);
7259 #endif /* MAP_NSD */
7262 arith_map_lookup(map, name, av, statp)
7272 static char result[16];
7277 sm_dprintf("arith_map_lookup: key '%s'\n", name);
7278 for (cpp = av; cpp != NULL && *cpp != NULL; cpp++)
7279 sm_dprintf("arith_map_lookup: arg '%s'\n", *cpp);
7287 ** read arguments for arith map
7288 ** - no check is made whether they are really numbers
7289 ** - just ignores args after the second
7292 for (++cpp; cpp != NULL && *cpp != NULL && r < 2; cpp++)
7293 v[r++] = strtol(*cpp, NULL, 0);
7295 /* operator and (at least) two operands given? */
7296 if (name != NULL && r == 2)
7342 r = v[1] - v[0] + 1;
7345 r = get_random() % r + v[0];
7352 sm_syslog(LOG_WARNING, NOQID,
7353 "arith_map: unknown operator %c",
7354 (isascii(*name) && isprint(*name)) ?
7359 (void) sm_snprintf(result, sizeof(result),
7360 res ? "TRUE" : "FALSE");
7362 (void) sm_snprintf(result, sizeof(result), "%ld", r);
7371 # if NETINET || NETINET6
7372 # include <arpa/inet.h>
7373 # endif /* NETINET || NETINET6 */
7375 # define socket_map_next map_stack[0]
7378 ** SOCKET_MAP_OPEN -- open socket table
7382 socket_map_open(map, mode)
7388 SOCKADDR_LEN_T addrlen = 0;
7394 struct hostent *hp = NULL;
7398 sm_dprintf("socket_map_open(%s, %s, %d)\n",
7399 map->map_mname, map->map_file, mode);
7403 /* sendmail doesn't have the ability to write to SOCKET (yet) */
7404 if (mode != O_RDONLY)
7406 /* issue a pseudo-error message */
7407 errno = SM_EMAPCANTWRITE;
7411 if (*map->map_file == '\0')
7413 syserr("socket map \"%s\": empty or missing socket information",
7418 s = socket_map_findconn(map->map_file);
7419 if (s->s_socketmap != NULL)
7421 /* Copy open connection */
7422 map->map_db1 = s->s_socketmap->map_db1;
7424 /* Add this map as head of linked list */
7425 map->socket_map_next = s->s_socketmap;
7426 s->s_socketmap = map;
7429 sm_dprintf("using cached connection\n");
7434 sm_dprintf("opening new connection\n");
7436 /* following code is ripped from milter.c */
7437 /* XXX It should be put in a library... */
7439 /* protocol:filename or protocol:port@host */
7440 memset(&addr, '\0', sizeof(addr));
7442 colon = strchr(p, ':');
7450 /* default to AF_UNIX */
7451 addr.sa.sa_family = AF_UNIX;
7452 # else /* NETUNIX */
7454 /* default to AF_INET */
7455 addr.sa.sa_family = AF_INET;
7456 # else /* NETINET */
7458 /* default to AF_INET6 */
7459 addr.sa.sa_family = AF_INET6;
7460 # else /* NETINET6 */
7461 /* no protocols available */
7462 syserr("socket map \"%s\": no valid socket protocols available",
7465 # endif /* NETINET6 */
7466 # endif /* NETINET */
7467 # endif /* NETUNIX */
7470 else if (sm_strcasecmp(p, "unix") == 0 ||
7471 sm_strcasecmp(p, "local") == 0)
7472 addr.sa.sa_family = AF_UNIX;
7473 # endif /* NETUNIX */
7475 else if (sm_strcasecmp(p, "inet") == 0)
7476 addr.sa.sa_family = AF_INET;
7477 # endif /* NETINET */
7479 else if (sm_strcasecmp(p, "inet6") == 0)
7480 addr.sa.sa_family = AF_INET6;
7481 # endif /* NETINET6 */
7484 # ifdef EPROTONOSUPPORT
7485 errno = EPROTONOSUPPORT;
7486 # else /* EPROTONOSUPPORT */
7488 # endif /* EPROTONOSUPPORT */
7489 syserr("socket map \"%s\": unknown socket type %s",
7499 /* default to AF_UNIX */
7500 addr.sa.sa_family = AF_UNIX;
7503 /* default to AF_INET */
7504 addr.sa.sa_family = AF_INET;
7505 # else /* NETINET */
7507 /* default to AF_INET6 */
7508 addr.sa.sa_family = AF_INET6;
7509 # else /* NETINET6 */
7510 syserr("socket map \"%s\": unknown socket type %s",
7513 # endif /* NETINET6 */
7514 # endif /* NETINET */
7515 #endif /* NETUNIX */
7519 if (addr.sa.sa_family == AF_UNIX)
7521 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_EXECOK;
7524 if (strlen(colon) >= sizeof(addr.sunix.sun_path))
7526 syserr("socket map \"%s\": local socket name %s too long",
7527 map->map_mname, colon);
7530 errno = safefile(colon, RunAsUid, RunAsGid, RunAsUserName, sff,
7531 S_IRUSR|S_IWUSR, NULL);
7535 /* if not safe, don't create */
7536 syserr("socket map \"%s\": local socket name %s unsafe",
7537 map->map_mname, colon);
7541 (void) sm_strlcpy(addr.sunix.sun_path, colon,
7542 sizeof(addr.sunix.sun_path));
7543 addrlen = sizeof(struct sockaddr_un);
7546 # endif /* NETUNIX */
7547 # if NETINET || NETINET6
7550 || addr.sa.sa_family == AF_INET
7551 # endif /* NETINET */
7553 || addr.sa.sa_family == AF_INET6
7554 # endif /* NETINET6 */
7557 unsigned short port;
7559 /* Parse port@host */
7560 at = strchr(colon, '@');
7563 syserr("socket map \"%s\": bad address %s (expected port@host)",
7564 map->map_mname, colon);
7568 if (isascii(*colon) && isdigit(*colon))
7569 port = htons((unsigned short) atoi(colon));
7572 # ifdef NO_GETSERVBYNAME
7573 syserr("socket map \"%s\": invalid port number %s",
7574 map->map_mname, colon);
7576 # else /* NO_GETSERVBYNAME */
7577 register struct servent *sp;
7579 sp = getservbyname(colon, "tcp");
7582 syserr("socket map \"%s\": unknown port name %s",
7583 map->map_mname, colon);
7587 # endif /* NO_GETSERVBYNAME */
7594 end = strchr(at, ']');
7599 unsigned long hid = INADDR_NONE;
7600 # endif /* NETINET */
7602 struct sockaddr_in6 hid6;
7603 # endif /* NETINET6 */
7607 if (addr.sa.sa_family == AF_INET &&
7608 (hid = inet_addr(&at[1])) != INADDR_NONE)
7610 addr.sin.sin_addr.s_addr = hid;
7611 addr.sin.sin_port = port;
7614 # endif /* NETINET */
7616 (void) memset(&hid6, '\0', sizeof(hid6));
7617 if (addr.sa.sa_family == AF_INET6 &&
7618 anynet_pton(AF_INET6, &at[1],
7619 &hid6.sin6_addr) == 1)
7621 addr.sin6.sin6_addr = hid6.sin6_addr;
7622 addr.sin6.sin6_port = port;
7625 # endif /* NETINET6 */
7629 syserr("socket map \"%s\": Invalid numeric domain spec \"%s\"",
7630 map->map_mname, at);
7636 syserr("socket map \"%s\": Invalid numeric domain spec \"%s\"",
7637 map->map_mname, at);
7643 hp = sm_gethostbyname(at, addr.sa.sa_family);
7646 syserr("socket map \"%s\": Unknown host name %s",
7647 map->map_mname, at);
7650 addr.sa.sa_family = hp->h_addrtype;
7651 switch (hp->h_addrtype)
7655 memmove(&addr.sin.sin_addr,
7656 hp->h_addr, INADDRSZ);
7657 addr.sin.sin_port = port;
7658 addrlen = sizeof(struct sockaddr_in);
7661 # endif /* NETINET */
7665 memmove(&addr.sin6.sin6_addr,
7666 hp->h_addr, IN6ADDRSZ);
7667 addr.sin6.sin6_port = port;
7668 addrlen = sizeof(struct sockaddr_in6);
7671 # endif /* NETINET6 */
7674 syserr("socket map \"%s\": Unknown protocol for %s (%d)",
7675 map->map_mname, at, hp->h_addrtype);
7678 # endif /* NETINET6 */
7684 # endif /* NETINET || NETINET6 */
7686 syserr("socket map \"%s\": unknown socket protocol",
7691 /* nope, actually connecting */
7694 sock = socket(addr.sa.sa_family, SOCK_STREAM, 0);
7699 sm_dprintf("socket map \"%s\": error creating socket: %s\n",
7701 sm_errstring(save_errno));
7705 # endif /* NETINET6 */
7709 if (connect(sock, (struct sockaddr *) &addr, addrlen) >= 0)
7712 /* couldn't connect.... try next address */
7717 sm_dprintf("socket_open (%s): open %s failed: %s\n",
7718 map->map_mname, at, sm_errstring(save_errno));
7722 /* try next address */
7723 if (hp != NULL && hp->h_addr_list[addrno] != NULL)
7725 switch (addr.sa.sa_family)
7729 memmove(&addr.sin.sin_addr,
7730 hp->h_addr_list[addrno++],
7733 # endif /* NETINET */
7737 memmove(&addr.sin6.sin6_addr,
7738 hp->h_addr_list[addrno++],
7741 # endif /* NETINET6 */
7745 sm_dprintf("socket map \"%s\": Unknown protocol for %s (%d)\n",
7750 # endif /* NETINET6 */
7758 sm_dprintf("socket map \"%s\": error connecting to socket map: %s\n",
7759 map->map_mname, sm_errstring(save_errno));
7764 # endif /* NETINET6 */
7773 # endif /* NETINET6 */
7774 if ((map->map_db1 = (ARBPTR_T) sm_io_open(SmFtStdiofd,
7782 sm_dprintf("socket_open (%s): failed to create stream: %s\n",
7783 map->map_mname, sm_errstring(errno));
7787 /* Save connection for reuse */
7788 s->s_socketmap = map;
7793 ** SOCKET_MAP_FINDCONN -- find a SOCKET connection to the server
7795 ** Cache SOCKET connections based on the connection specifier
7796 ** and PID so we don't have multiple connections open to
7797 ** the same server for different maps. Need a separate connection
7798 ** per PID since a parent process may close the map before the
7799 ** child is done with it.
7802 ** conn -- SOCKET map connection specifier
7805 ** Symbol table entry for the SOCKET connection.
7809 socket_map_findconn(conn)
7813 STAB *SM_NONVOLATILE s = NULL;
7815 nbuf = sm_stringf_x("%s%c%d", conn, CONDELSE, (int) CurrentPid);
7817 s = stab(nbuf, ST_SOCKETMAP, ST_ENTER);
7825 ** SOCKET_MAP_CLOSE -- close the socket
7829 socket_map_close(map)
7836 sm_dprintf("socket_map_close(%s), pid=%ld\n", map->map_file,
7839 /* Check if already closed */
7840 if (map->map_db1 == NULL)
7843 sm_dprintf("socket_map_close(%s) already closed\n",
7847 sm_io_close((SM_FILE_T *)map->map_db1, SM_TIME_DEFAULT);
7849 /* Mark all the maps that share the connection as closed */
7850 s = socket_map_findconn(map->map_file);
7851 smap = s->s_socketmap;
7852 while (smap != NULL)
7856 if (tTd(38, 2) && smap != map)
7857 sm_dprintf("socket_map_close(%s): closed %s (shared SOCKET connection)\n",
7858 map->map_mname, smap->map_mname);
7860 smap->map_mflags &= ~(MF_OPEN|MF_WRITABLE);
7861 smap->map_db1 = NULL;
7862 next = smap->socket_map_next;
7863 smap->socket_map_next = NULL;
7866 s->s_socketmap = NULL;
7870 ** SOCKET_MAP_LOOKUP -- look up a datum in a SOCKET table
7874 socket_map_lookup(map, name, av, statp)
7880 unsigned int nettolen, replylen, recvlen;
7881 char *replybuf, *rval, *value, *status, *key;
7883 char keybuf[MAXNAME + 1];
7887 f = (SM_FILE_T *)map->map_db1;
7889 sm_dprintf("socket_map_lookup(%s, %s) %s\n",
7890 map->map_mname, name, map->map_file);
7892 if (!bitset(MF_NOFOLDCASE, map->map_mflags))
7894 nettolen = strlen(name);
7895 if (nettolen > sizeof(keybuf) - 1)
7896 nettolen = sizeof(keybuf) - 1;
7897 memmove(keybuf, name, nettolen);
7898 keybuf[nettolen] = '\0';
7905 nettolen = strlen(map->map_mname) + 1 + strlen(key);
7906 SM_ASSERT(nettolen > strlen(map->map_mname));
7907 SM_ASSERT(nettolen > strlen(key));
7908 if ((sm_io_fprintf(f, SM_TIME_DEFAULT, "%u:%s %s,",
7909 nettolen, map->map_mname, key) == SM_IO_EOF) ||
7910 (sm_io_flush(f, SM_TIME_DEFAULT) != 0) ||
7913 syserr("451 4.3.0 socket_map_lookup(%s): failed to send lookup request",
7915 *statp = EX_TEMPFAIL;
7919 if (sm_io_fscanf(f, SM_TIME_DEFAULT, "%9u", &replylen) != 1)
7921 syserr("451 4.3.0 socket_map_lookup(%s): failed to read length parameter of reply",
7923 *statp = EX_TEMPFAIL;
7926 if (replylen > SOCKETMAP_MAXL)
7928 syserr("451 4.3.0 socket_map_lookup(%s): reply too long: %u",
7929 map->map_mname, replylen);
7930 *statp = EX_TEMPFAIL;
7933 if (sm_io_getc(f, SM_TIME_DEFAULT) != ':')
7935 syserr("451 4.3.0 socket_map_lookup(%s): missing ':' in reply",
7937 *statp = EX_TEMPFAIL;
7941 replybuf = (char *) sm_malloc(replylen + 1);
7942 if (replybuf == NULL)
7944 syserr("451 4.3.0 socket_map_lookup(%s): can't allocate %u bytes",
7945 map->map_mname, replylen + 1);
7950 recvlen = sm_io_read(f, SM_TIME_DEFAULT, replybuf, replylen);
7951 if (recvlen < replylen)
7953 syserr("451 4.3.0 socket_map_lookup(%s): received only %u of %u reply characters",
7954 map->map_mname, recvlen, replylen);
7955 *statp = EX_TEMPFAIL;
7958 if (sm_io_getc(f, SM_TIME_DEFAULT) != ',')
7960 syserr("451 4.3.0 socket_map_lookup(%s): missing ',' in reply",
7962 *statp = EX_TEMPFAIL;
7966 replybuf[recvlen] = '\0';
7967 value = strchr(replybuf, ' ');
7973 if (strcmp(status, "OK") == 0)
7977 /* collect the return value */
7978 if (bitset(MF_MATCHONLY, map->map_mflags))
7979 rval = map_rewrite(map, key, strlen(key), NULL);
7981 rval = map_rewrite(map, value, strlen(value), av);
7983 else if (strcmp(status, "NOTFOUND") == 0)
7985 *statp = EX_NOTFOUND;
7987 sm_dprintf("socket_map_lookup(%s): %s not found\n",
7988 map->map_mname, key);
7993 sm_dprintf("socket_map_lookup(%s, %s): server returned error: type=%s, reason=%s\n",
7994 map->map_mname, key, status,
7995 value ? value : "");
7996 if ((strcmp(status, "TEMP") == 0) ||
7997 (strcmp(status, "TIMEOUT") == 0))
7998 *statp = EX_TEMPFAIL;
7999 else if(strcmp(status, "PERM") == 0)
8000 *statp = EX_UNAVAILABLE;
8002 *statp = EX_PROTOCOL;
8005 if (replybuf != NULL)
8010 socket_map_close(map);
8012 if (replybuf != NULL)
8016 #endif /* SOCKETMAP */