xref: /netbsd-src/external/ibm-public/postfix/dist/src/postalias/postalias.c (revision 4d342c046e3288fb5a1edcd33cfec48c41c80664)
1 /*	$NetBSD: postalias.c,v 1.3 2020/03/18 19:05:17 christos Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	postalias 1
6 /* SUMMARY
7 /*	Postfix alias database maintenance
8 /* SYNOPSIS
9 /* .fi
10 /*	\fBpostalias\fR [\fB-Nfinoprsuvw\fR] [\fB-c \fIconfig_dir\fR]
11 /*	[\fB-d \fIkey\fR] [\fB-q \fIkey\fR]
12 /*		[\fIfile_type\fR:]\fIfile_name\fR ...
13 /* DESCRIPTION
14 /*	The \fBpostalias\fR(1) command creates or queries one or more Postfix
15 /*	alias databases, or updates an existing one. The input and output
16 /*	file formats are expected to be compatible with Sendmail version 8,
17 /*	and are expected to be suitable for the use as NIS alias maps.
18 /*
19 /*	If the result files do not exist they will be created with the
20 /*	same group and other read permissions as their source file.
21 /*
22 /*	While a database update is in progress, signal delivery is
23 /*	postponed, and an exclusive, advisory, lock is placed on the
24 /*	entire database, in order to avoid surprises in spectator
25 /*	processes.
26 /*
27 /*	The format of Postfix alias input files is described in
28 /*	\fBaliases\fR(5).
29 /*
30 /*	By default the lookup key is mapped to lowercase to make
31 /*	the lookups case insensitive; as of Postfix 2.3 this case
32 /*	folding happens only with tables whose lookup keys are
33 /*	fixed-case strings such as btree:, dbm: or hash:. With
34 /*	earlier versions, the lookup key is folded even with tables
35 /*	where a lookup field can match both upper and lower case
36 /*	text, such as regexp: and pcre:. This resulted in loss of
37 /*	information with $\fInumber\fR substitutions.
38 /*
39 /*	Options:
40 /* .IP "\fB-c \fIconfig_dir\fR"
41 /*	Read the \fBmain.cf\fR configuration file in the named directory
42 /*	instead of the default configuration directory.
43 /* .IP "\fB-d \fIkey\fR"
44 /*	Search the specified maps for \fIkey\fR and remove one entry per map.
45 /*	The exit status is zero when the requested information was found.
46 /*
47 /*	If a key value of \fB-\fR is specified, the program reads key
48 /*	values from the standard input stream. The exit status is zero
49 /*	when at least one of the requested keys was found.
50 /* .IP \fB-f\fR
51 /*	Do not fold the lookup key to lower case while creating or querying
52 /*	a table.
53 /*
54 /*	With Postfix version 2.3 and later, this option has no
55 /*	effect for regular expression tables. There, case folding
56 /*	is controlled by appending a flag to a pattern.
57 /* .IP \fB-i\fR
58 /*	Incremental mode. Read entries from standard input and do not
59 /*	truncate an existing database. By default, \fBpostalias\fR(1) creates
60 /*	a new database from the entries in \fIfile_name\fR.
61 /* .IP \fB-N\fR
62 /*	Include the terminating null character that terminates lookup keys
63 /*	and values. By default, \fBpostalias\fR(1) does whatever
64 /*	is the default for
65 /*	the host operating system.
66 /* .IP \fB-n\fR
67 /*	Don't include the terminating null character that terminates lookup
68 /*	keys and values. By default, \fBpostalias\fR(1) does whatever
69 /*	is the default for
70 /*	the host operating system.
71 /* .IP \fB-o\fR
72 /*	Do not release root privileges when processing a non-root
73 /*	input file. By default, \fBpostalias\fR(1) drops root privileges
74 /*	and runs as the source file owner instead.
75 /* .IP \fB-p\fR
76 /*	Do not inherit the file access permissions from the input file
77 /*	when creating a new file.  Instead, create a new file with default
78 /*	access permissions (mode 0644).
79 /* .IP "\fB-q \fIkey\fR"
80 /*	Search the specified maps for \fIkey\fR and write the first value
81 /*	found to the standard output stream. The exit status is zero
82 /*	when the requested information was found.
83 /*
84 /*	Note: this performs a single query with the key as specified,
85 /*	and does not make iterative queries with substrings of the
86 /*	key as described in the aliases(5) manual page.
87 /*
88 /*	If a key value of \fB-\fR is specified, the program reads key
89 /*	values from the standard input stream and writes one line of
90 /*	\fIkey: value\fR output for each key that was found. The exit
91 /*	status is zero when at least one of the requested keys was found.
92 /* .IP \fB-r\fR
93 /*	When updating a table, do not complain about attempts to update
94 /*	existing entries, and make those updates anyway.
95 /* .IP \fB-s\fR
96 /*	Retrieve all database elements, and write one line of
97 /*	\fIkey: value\fR output for each element. The elements are
98 /*	printed in database order, which is not necessarily the same
99 /*	as the original input order.
100 /*	This feature is available in Postfix version 2.2 and later,
101 /*	and is not available for all database types.
102 /* .IP \fB-u\fR
103 /*	Disable UTF-8 support. UTF-8 support is enabled by default
104 /*	when "smtputf8_enable = yes". It requires that keys and
105 /*	values are valid UTF-8 strings.
106 /* .IP \fB-v\fR
107 /*	Enable verbose logging for debugging purposes. Multiple \fB-v\fR
108 /*	options make the software increasingly verbose.
109 /* .IP \fB-w\fR
110 /*	When updating a table, do not complain about attempts to update
111 /*	existing entries, and ignore those attempts.
112 /* .PP
113 /*	Arguments:
114 /* .IP \fIfile_type\fR
115 /*	The database type. To find out what types are supported, use
116 /*	the "\fBpostconf -m\fR" command.
117 /*
118 /*	The \fBpostalias\fR(1) command can query any supported file type,
119 /*	but it can create only the following file types:
120 /* .RS
121 /* .IP \fBbtree\fR
122 /*	The output is a btree file, named \fIfile_name\fB.db\fR.
123 /*	This is available on systems with support for \fBdb\fR databases.
124 /* .IP \fBcdb\fR
125 /*	The output is one file named \fIfile_name\fB.cdb\fR.
126 /*	This is available on systems with support for \fBcdb\fR databases.
127 /* .IP \fBdbm\fR
128 /*	The output consists of two files, named \fIfile_name\fB.pag\fR and
129 /*	\fIfile_name\fB.dir\fR.
130 /*	This is available on systems with support for \fBdbm\fR databases.
131 /* .IP \fBhash\fR
132 /*	The output is a hashed file, named \fIfile_name\fB.db\fR.
133 /*	This is available on systems with support for \fBdb\fR databases.
134 /* .IP \fBfail\fR
135 /*	A table that reliably fails all requests. The lookup table
136 /*	name is used for logging only. This table exists to simplify
137 /*	Postfix error tests.
138 /* .IP \fBsdbm\fR
139 /*	The output consists of two files, named \fIfile_name\fB.pag\fR and
140 /*	\fIfile_name\fB.dir\fR.
141 /*	This is available on systems with support for \fBsdbm\fR databases.
142 /* .PP
143 /*	When no \fIfile_type\fR is specified, the software uses the database
144 /*	type specified via the \fBdefault_database_type\fR configuration
145 /*	parameter.
146 /*	The default value for this parameter depends on the host environment.
147 /* .RE
148 /* .IP \fIfile_name\fR
149 /*	The name of the alias database source file when creating a database.
150 /* DIAGNOSTICS
151 /*	Problems are logged to the standard error stream and to
152 /*	\fBsyslogd\fR(8) or \fBpostlogd\fR(8). No output means that
153 /*	no problems were detected. Duplicate entries are skipped and are
154 /*	flagged with a warning.
155 /*
156 /*	\fBpostalias\fR(1) terminates with zero exit status in case of success
157 /*	(including successful "\fBpostalias -q\fR" lookup) and terminates
158 /*	with non-zero exit status in case of failure.
159 /* ENVIRONMENT
160 /* .ad
161 /* .fi
162 /* .IP \fBMAIL_CONFIG\fR
163 /*	Directory with Postfix configuration files.
164 /* .IP \fBMAIL_VERBOSE\fR
165 /*	Enable verbose logging for debugging purposes.
166 /* CONFIGURATION PARAMETERS
167 /* .ad
168 /* .fi
169 /*	The following \fBmain.cf\fR parameters are especially relevant to
170 /*	this program.
171 /*
172 /*	The text below provides only a parameter summary. See
173 /*	\fBpostconf\fR(5) for more details including examples.
174 /* .IP "\fBalias_database (see 'postconf -d' output)\fR"
175 /*	The alias databases for \fBlocal\fR(8) delivery that are updated with
176 /*	"\fBnewaliases\fR" or with "\fBsendmail -bi\fR".
177 /* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
178 /*	The default location of the Postfix main.cf and master.cf
179 /*	configuration files.
180 /* .IP "\fBberkeley_db_create_buffer_size (16777216)\fR"
181 /*	The per-table I/O buffer size for programs that create Berkeley DB
182 /*	hash or btree tables.
183 /* .IP "\fBberkeley_db_read_buffer_size (131072)\fR"
184 /*	The per-table I/O buffer size for programs that read Berkeley DB
185 /*	hash or btree tables.
186 /* .IP "\fBdefault_database_type (see 'postconf -d' output)\fR"
187 /*	The default database type for use in \fBnewaliases\fR(1), \fBpostalias\fR(1)
188 /*	and \fBpostmap\fR(1) commands.
189 /* .IP "\fBimport_environment (see 'postconf -d' output)\fR"
190 /*	The list of environment parameters that a privileged Postfix
191 /*	process will import from a non-Postfix parent process, or name=value
192 /*	environment overrides.
193 /* .IP "\fBsmtputf8_enable (yes)\fR"
194 /*	Enable preliminary SMTPUTF8 support for the protocols described
195 /*	in RFC 6531..6533.
196 /* .IP "\fBsyslog_facility (mail)\fR"
197 /*	The syslog facility of Postfix logging.
198 /* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
199 /*	A prefix that is prepended to the process name in syslog
200 /*	records, so that, for example, "smtpd" becomes "prefix/smtpd".
201 /* STANDARDS
202 /*	RFC 822 (ARPA Internet Text Messages)
203 /* SEE ALSO
204 /*	aliases(5), format of alias database input file.
205 /*	local(8), Postfix local delivery agent.
206 /*	postconf(1), supported database types
207 /*	postconf(5), configuration parameters
208 /*	postmap(1), create/update/query lookup tables
209 /*	newaliases(1), Sendmail compatibility interface.
210 /*	postlogd(8), Postfix logging
211 /*	syslogd(8), system logging
212 /* README FILES
213 /* .ad
214 /* .fi
215 /*	Use "\fBpostconf readme_directory\fR" or
216 /*	"\fBpostconf html_directory\fR" to locate this information.
217 /* .na
218 /* .nf
219 /*	DATABASE_README, Postfix lookup table overview
220 /* LICENSE
221 /* .ad
222 /* .fi
223 /*	The Secure Mailer license must be distributed with this software.
224 /* AUTHOR(S)
225 /*	Wietse Venema
226 /*	IBM T.J. Watson Research
227 /*	P.O. Box 704
228 /*	Yorktown Heights, NY 10598, USA
229 /*
230 /*	Wietse Venema
231 /*	Google, Inc.
232 /*	111 8th Avenue
233 /*	New York, NY 10011, USA
234 /*--*/
235 
236 /* System library. */
237 
238 #include <sys_defs.h>
239 #include <sys/stat.h>
240 #include <stdlib.h>
241 #include <unistd.h>
242 #include <fcntl.h>
243 #include <ctype.h>
244 #include <string.h>
245 
246 /* Utility library. */
247 
248 #include <msg.h>
249 #include <mymalloc.h>
250 #include <vstring.h>
251 #include <vstream.h>
252 #include <msg_vstream.h>
253 #include <readlline.h>
254 #include <stringops.h>
255 #include <split_at.h>
256 #include <vstring_vstream.h>
257 #include <set_eugid.h>
258 #include <warn_stat.h>
259 #include <clean_env.h>
260 
261 /* Global library. */
262 
263 #include <tok822.h>
264 #include <mail_conf.h>
265 #include <mail_dict.h>
266 #include <mail_params.h>
267 #include <mail_version.h>
268 #include <mkmap.h>
269 #include <mail_task.h>
270 #include <dict_proxy.h>
271 #include <mail_parm_split.h>
272 #include <maillog_client.h>
273 
274 /* Application-specific. */
275 
276 #define STR	vstring_str
277 #define LEN	VSTRING_LEN
278 
279 #define POSTALIAS_FLAG_AS_OWNER	(1<<0)	/* open dest as owner of source */
280 #define POSTALIAS_FLAG_SAVE_PERM	(1<<1)	/* copy access permission
281 						 * from source */
282 
283 /* postalias - create or update alias database */
284 
285 static void postalias(char *map_type, char *path_name, int postalias_flags,
286 		              int open_flags, int dict_flags)
287 {
288     VSTREAM *NOCLOBBER source_fp;
289     VSTRING *line_buffer;
290     MKMAP  *mkmap;
291     int     lineno;
292     int     last_line;
293     VSTRING *key_buffer;
294     VSTRING *value_buffer;
295     TOK822 *tok_list;
296     TOK822 *key_list;
297     TOK822 *colon;
298     TOK822 *value_list;
299     struct stat st;
300     mode_t  saved_mask;
301 
302     /*
303      * Initialize.
304      */
305     line_buffer = vstring_alloc(100);
306     key_buffer = vstring_alloc(100);
307     value_buffer = vstring_alloc(100);
308     if ((open_flags & O_TRUNC) == 0) {
309 	/* Incremental mode. */
310 	source_fp = VSTREAM_IN;
311 	vstream_control(source_fp, CA_VSTREAM_CTL_PATH("stdin"), CA_VSTREAM_CTL_END);
312     } else {
313 	/* Create database. */
314 	if (strcmp(map_type, DICT_TYPE_PROXY) == 0)
315 	    msg_fatal("can't create maps via the proxy service");
316 	dict_flags |= DICT_FLAG_BULK_UPDATE;
317 	if ((source_fp = vstream_fopen(path_name, O_RDONLY, 0)) == 0)
318 	    msg_fatal("open %s: %m", path_name);
319     }
320     if (fstat(vstream_fileno(source_fp), &st) < 0)
321 	msg_fatal("fstat %s: %m", path_name);
322 
323     /*
324      * Turn off group/other read permissions as indicated in the source file.
325      */
326     if ((postalias_flags & POSTALIAS_FLAG_SAVE_PERM) && S_ISREG(st.st_mode))
327 	saved_mask = umask(022 | (~st.st_mode & 077));
328 
329     /*
330      * If running as root, run as the owner of the source file, so that the
331      * result shows proper ownership, and so that a bug in postalias does not
332      * allow privilege escalation.
333      */
334     if ((postalias_flags & POSTALIAS_FLAG_AS_OWNER) && getuid() == 0
335 	&& (st.st_uid != geteuid() || st.st_gid != getegid()))
336 	set_eugid(st.st_uid, st.st_gid);
337 
338     /*
339      * Open the database, create it when it does not exist, truncate it when
340      * it does exist, and lock out any spectators.
341      */
342     mkmap = mkmap_open(map_type, path_name, open_flags, dict_flags);
343 
344     /*
345      * And restore the umask, in case it matters.
346      */
347     if ((postalias_flags & POSTALIAS_FLAG_SAVE_PERM) && S_ISREG(st.st_mode))
348 	umask(saved_mask);
349 
350     /*
351      * Trap "exceptions" so that we can restart a bulk-mode update after a
352      * recoverable error.
353      */
354     for (;;) {
355 	if (dict_isjmp(mkmap->dict) != 0
356 	    && dict_setjmp(mkmap->dict) != 0
357 	    && vstream_fseek(source_fp, SEEK_SET, 0) < 0)
358 	    msg_fatal("seek %s: %m", VSTREAM_PATH(source_fp));
359 
360 	/*
361 	 * Add records to the database.
362 	 */
363 	last_line = 0;
364 	while (readllines(line_buffer, source_fp, &last_line, &lineno)) {
365 
366 	    /*
367 	     * First some UTF-8 checks sans casefolding.
368 	     */
369 	    if ((mkmap->dict->flags & DICT_FLAG_UTF8_ACTIVE)
370 		&& !allascii(STR(line_buffer))
371 		&& !valid_utf8_string(STR(line_buffer), LEN(line_buffer))) {
372 		msg_warn("%s, line %d: non-UTF-8 input \"%s\""
373 			 " -- ignoring this line",
374 			 VSTREAM_PATH(source_fp), lineno, STR(line_buffer));
375 		continue;
376 	    }
377 
378 	    /*
379 	     * Tokenize the input, so that we do the right thing when a
380 	     * quoted localpart contains special characters such as "@", ":"
381 	     * and so on.
382 	     */
383 	    if ((tok_list = tok822_scan(STR(line_buffer), (TOK822 **) 0)) == 0)
384 		continue;
385 
386 	    /*
387 	     * Enforce the key:value format. Disallow missing keys,
388 	     * multi-address keys, or missing values. In order to specify an
389 	     * empty string or value, enclose it in double quotes.
390 	     */
391 	    if ((colon = tok822_find_type(tok_list, ':')) == 0
392 		|| colon->prev == 0 || colon->next == 0
393 		|| tok822_rfind_type(colon, ',')) {
394 		msg_warn("%s, line %d: need name:value pair",
395 			 VSTREAM_PATH(source_fp), lineno);
396 		tok822_free_tree(tok_list);
397 		continue;
398 	    }
399 
400 	    /*
401 	     * Key must be local. XXX We should use the Postfix rewriting and
402 	     * resolving services to handle all address forms correctly.
403 	     * However, we can't count on the mail system being up when the
404 	     * alias database is being built, so we're guessing a bit.
405 	     */
406 	    if (tok822_rfind_type(colon, '@') || tok822_rfind_type(colon, '%')) {
407 		msg_warn("%s, line %d: name must be local",
408 			 VSTREAM_PATH(source_fp), lineno);
409 		tok822_free_tree(tok_list);
410 		continue;
411 	    }
412 
413 	    /*
414 	     * Split the input into key and value parts, and convert from
415 	     * token representation back to string representation. Convert
416 	     * the key to internal (unquoted) form, because the resolver
417 	     * produces addresses in internal form. Convert the value to
418 	     * external (quoted) form, because it will have to be re-parsed
419 	     * upon lookup. Discard the token representation when done.
420 	     */
421 	    key_list = tok_list;
422 	    tok_list = 0;
423 	    value_list = tok822_cut_after(colon);
424 	    tok822_unlink(colon);
425 	    tok822_free(colon);
426 
427 	    tok822_internalize(key_buffer, key_list, TOK822_STR_DEFL);
428 	    tok822_free_tree(key_list);
429 
430 	    tok822_externalize(value_buffer, value_list, TOK822_STR_DEFL);
431 	    tok822_free_tree(value_list);
432 
433 	    /*
434 	     * Store the value under a case-insensitive key.
435 	     */
436 	    mkmap_append(mkmap, STR(key_buffer), STR(value_buffer));
437 	    if (mkmap->dict->error)
438 		msg_fatal("table %s:%s: write error: %m",
439 			  mkmap->dict->type, mkmap->dict->name);
440 	}
441 	break;
442     }
443 
444     /*
445      * Update or append sendmail and NIS signatures.
446      */
447     if ((open_flags & O_TRUNC) == 0)
448 	mkmap->dict->flags |= DICT_FLAG_DUP_REPLACE;
449 
450     /*
451      * Sendmail compatibility: add the @:@ signature to indicate that the
452      * database is complete. This might be needed by NIS clients running
453      * sendmail.
454      */
455     mkmap_append(mkmap, "@", "@");
456     if (mkmap->dict->error)
457 	msg_fatal("table %s:%s: write error: %m",
458 		  mkmap->dict->type, mkmap->dict->name);
459 
460     /*
461      * NIS compatibility: add time and master info. Unlike other information,
462      * this information MUST be written without a trailing null appended to
463      * key or value.
464      */
465     mkmap->dict->flags &= ~DICT_FLAG_TRY1NULL;
466     mkmap->dict->flags |= DICT_FLAG_TRY0NULL;
467     vstring_sprintf(value_buffer, "%010ld", (long) time((time_t *) 0));
468 #if (defined(HAS_NIS) || defined(HAS_NISPLUS))
469     mkmap->dict->flags &= ~DICT_FLAG_FOLD_FIX;
470     mkmap_append(mkmap, "YP_LAST_MODIFIED", STR(value_buffer));
471     mkmap_append(mkmap, "YP_MASTER_NAME", var_myhostname);
472 #endif
473 
474     /*
475      * Close the alias database, and release the lock.
476      */
477     mkmap_close(mkmap);
478 
479     /*
480      * Cleanup. We're about to terminate, but it is a good sanity check.
481      */
482     vstring_free(value_buffer);
483     vstring_free(key_buffer);
484     vstring_free(line_buffer);
485     if (source_fp != VSTREAM_IN)
486 	vstream_fclose(source_fp);
487 }
488 
489 /* postalias_queries - apply multiple requests from stdin */
490 
491 static int postalias_queries(VSTREAM *in, char **maps, const int map_count,
492 			             const int dict_flags)
493 {
494     int     found = 0;
495     VSTRING *keybuf = vstring_alloc(100);
496     DICT  **dicts;
497     const char *map_name;
498     const char *value;
499     int     n;
500 
501     /*
502      * Sanity check.
503      */
504     if (map_count <= 0)
505 	msg_panic("postalias_queries: bad map count");
506 
507     /*
508      * Prepare to open maps lazily.
509      */
510     dicts = (DICT **) mymalloc(sizeof(*dicts) * map_count);
511     for (n = 0; n < map_count; n++)
512 	dicts[n] = 0;
513 
514     /*
515      * Perform all queries. Open maps on the fly, to avoid opening
516      * unnecessary maps.
517      */
518     while (vstring_get_nonl(keybuf, in) != VSTREAM_EOF) {
519 	for (n = 0; n < map_count; n++) {
520 	    if (dicts[n] == 0)
521 		dicts[n] = ((map_name = split_at(maps[n], ':')) != 0 ?
522 		       dict_open3(maps[n], map_name, O_RDONLY, dict_flags) :
523 		    dict_open3(var_db_type, maps[n], O_RDONLY, dict_flags));
524 	    if ((value = dict_get(dicts[n], STR(keybuf))) != 0) {
525 		if (*value == 0) {
526 		    msg_warn("table %s:%s: key %s: empty string result is not allowed",
527 			     dicts[n]->type, dicts[n]->name, STR(keybuf));
528 		    msg_warn("table %s:%s should return NO RESULT in case of NOT FOUND",
529 			     dicts[n]->type, dicts[n]->name);
530 		}
531 		vstream_printf("%s:	%s\n", STR(keybuf), value);
532 		found = 1;
533 		break;
534 	    }
535 	    if (dicts[n]->error)
536 		msg_fatal("table %s:%s: query error: %m",
537 			  dicts[n]->type, dicts[n]->name);
538 	}
539     }
540     if (found)
541 	vstream_fflush(VSTREAM_OUT);
542 
543     /*
544      * Cleanup.
545      */
546     for (n = 0; n < map_count; n++)
547 	if (dicts[n])
548 	    dict_close(dicts[n]);
549     myfree((void *) dicts);
550     vstring_free(keybuf);
551 
552     return (found);
553 }
554 
555 /* postalias_query - query a map and print the result to stdout */
556 
557 static int postalias_query(const char *map_type, const char *map_name,
558 			           const char *key, int dict_flags)
559 {
560     DICT   *dict;
561     const char *value;
562 
563     dict = dict_open3(map_type, map_name, O_RDONLY, dict_flags);
564     if ((value = dict_get(dict, key)) != 0) {
565 	if (*value == 0) {
566 	    msg_warn("table %s:%s: key %s: empty string result is not allowed",
567 		     map_type, map_name, key);
568 	    msg_warn("table %s:%s should return NO RESULT in case of NOT FOUND",
569 		     map_type, map_name);
570 	}
571 	vstream_printf("%s\n", value);
572     }
573     if (dict->error)
574 	msg_fatal("table %s:%s: query error: %m", dict->type, dict->name);
575     vstream_fflush(VSTREAM_OUT);
576     dict_close(dict);
577     return (value != 0);
578 }
579 
580 /* postalias_deletes - apply multiple requests from stdin */
581 
582 static int postalias_deletes(VSTREAM *in, char **maps, const int map_count,
583 			             int dict_flags)
584 {
585     int     found = 0;
586     VSTRING *keybuf = vstring_alloc(100);
587     DICT  **dicts;
588     const char *map_name;
589     int     n;
590     int     open_flags;
591 
592     /*
593      * Sanity check.
594      */
595     if (map_count <= 0)
596 	msg_panic("postalias_deletes: bad map count");
597 
598     /*
599      * Open maps ahead of time.
600      */
601     dicts = (DICT **) mymalloc(sizeof(*dicts) * map_count);
602     for (n = 0; n < map_count; n++) {
603 	map_name = split_at(maps[n], ':');
604 	if (map_name && strcmp(maps[n], DICT_TYPE_PROXY) == 0)
605 	    open_flags = O_RDWR | O_CREAT;	/* XXX */
606 	else
607 	    open_flags = O_RDWR;
608 	dicts[n] = (map_name != 0 ?
609 		    dict_open3(maps[n], map_name, open_flags, dict_flags) :
610 		  dict_open3(var_db_type, maps[n], open_flags, dict_flags));
611     }
612 
613     /*
614      * Perform all requests.
615      */
616     while (vstring_get_nonl(keybuf, in) != VSTREAM_EOF) {
617 	for (n = 0; n < map_count; n++) {
618 	    found |= (dict_del(dicts[n], STR(keybuf)) == 0);
619 	    if (dicts[n]->error)
620 		msg_fatal("table %s:%s: delete error: %m",
621 			  dicts[n]->type, dicts[n]->name);
622 	}
623     }
624 
625     /*
626      * Cleanup.
627      */
628     for (n = 0; n < map_count; n++)
629 	if (dicts[n])
630 	    dict_close(dicts[n]);
631     myfree((void *) dicts);
632     vstring_free(keybuf);
633 
634     return (found);
635 }
636 
637 /* postalias_delete - delete a key value pair from a map */
638 
639 static int postalias_delete(const char *map_type, const char *map_name,
640 			            const char *key, int dict_flags)
641 {
642     DICT   *dict;
643     int     status;
644     int     open_flags;
645 
646     if (strcmp(map_type, DICT_TYPE_PROXY) == 0)
647 	open_flags = O_RDWR | O_CREAT;		/* XXX */
648     else
649 	open_flags = O_RDWR;
650     dict = dict_open3(map_type, map_name, open_flags, dict_flags);
651     status = dict_del(dict, key);
652     if (dict->error)
653 	msg_fatal("table %s:%s: delete error: %m", dict->type, dict->name);
654     dict_close(dict);
655     return (status == 0);
656 }
657 
658 /* postalias_seq - print all map entries to stdout */
659 
660 static void postalias_seq(const char *map_type, const char *map_name,
661 			          int dict_flags)
662 {
663     DICT   *dict;
664     const char *key;
665     const char *value;
666     int     func;
667 
668     if (strcmp(map_type, DICT_TYPE_PROXY) == 0)
669 	msg_fatal("can't sequence maps via the proxy service");
670     dict = dict_open3(map_type, map_name, O_RDONLY, dict_flags);
671     for (func = DICT_SEQ_FUN_FIRST; /* void */ ; func = DICT_SEQ_FUN_NEXT) {
672 	if (dict_seq(dict, func, &key, &value) != 0)
673 	    break;
674 	if (*key == 0) {
675 	    msg_warn("table %s:%s: empty lookup key value is not allowed",
676 		     map_type, map_name);
677 	} else if (*value == 0) {
678 	    msg_warn("table %s:%s: key %s: empty string result is not allowed",
679 		     map_type, map_name, key);
680 	    msg_warn("table %s:%s should return NO RESULT in case of NOT FOUND",
681 		     map_type, map_name);
682 	}
683 	vstream_printf("%s:	%s\n", key, value);
684     }
685     if (dict->error)
686 	msg_fatal("table %s:%s: sequence error: %m", dict->type, dict->name);
687     vstream_fflush(VSTREAM_OUT);
688     dict_close(dict);
689 }
690 
691 /* usage - explain */
692 
693 static NORETURN usage(char *myname)
694 {
695     msg_fatal("usage: %s [-Nfinoprsuvw] [-c config_dir] [-d key] [-q key] [map_type:]file...",
696 	      myname);
697 }
698 
699 MAIL_VERSION_STAMP_DECLARE;
700 
701 int     main(int argc, char **argv)
702 {
703     char   *path_name;
704     int     ch;
705     int     fd;
706     char   *slash;
707     struct stat st;
708     int     postalias_flags = POSTALIAS_FLAG_AS_OWNER | POSTALIAS_FLAG_SAVE_PERM;
709     int     open_flags = O_RDWR | O_CREAT | O_TRUNC;
710     int     dict_flags = (DICT_FLAG_DUP_WARN | DICT_FLAG_FOLD_FIX
711 			  | DICT_FLAG_UTF8_REQUEST);
712     char   *query = 0;
713     char   *delkey = 0;
714     int     sequence = 0;
715     int     found;
716     ARGV   *import_env;
717 
718     /*
719      * Fingerprint executables and core dumps.
720      */
721     MAIL_VERSION_STAMP_ALLOCATE;
722 
723     /*
724      * Be consistent with file permissions.
725      */
726     umask(022);
727 
728     /*
729      * To minimize confusion, make sure that the standard file descriptors
730      * are open before opening anything else. XXX Work around for 44BSD where
731      * fstat can return EBADF on an open file descriptor.
732      */
733     for (fd = 0; fd < 3; fd++)
734 	if (fstat(fd, &st) == -1
735 	    && (close(fd), open("/dev/null", O_RDWR, 0)) != fd)
736 	    msg_fatal("open /dev/null: %m");
737 
738     /*
739      * Process environment options as early as we can. We are not set-uid,
740      * and we are supposed to be running in a controlled environment.
741      */
742     if (getenv(CONF_ENV_VERB))
743 	msg_verbose = 1;
744 
745     /*
746      * Initialize. Set up logging. Read the global configuration file after
747      * parsing command-line arguments.
748      */
749     if ((slash = strrchr(argv[0], '/')) != 0 && slash[1])
750 	argv[0] = slash + 1;
751     msg_vstream_init(argv[0], VSTREAM_ERR);
752     maillog_client_init(mail_task(argv[0]), MAILLOG_CLIENT_FLAG_NONE);
753 
754     /*
755      * Check the Postfix library version as soon as we enable logging.
756      */
757     MAIL_VERSION_CHECK;
758 
759     /*
760      * Parse JCL.
761      */
762     while ((ch = GETOPT(argc, argv, "Nc:d:finopq:rsuvw")) > 0) {
763 	switch (ch) {
764 	default:
765 	    usage(argv[0]);
766 	    break;
767 	case 'N':
768 	    dict_flags |= DICT_FLAG_TRY1NULL;
769 	    dict_flags &= ~DICT_FLAG_TRY0NULL;
770 	    break;
771 	case 'c':
772 	    if (setenv(CONF_ENV_PATH, optarg, 1) < 0)
773 		msg_fatal("out of memory");
774 	    break;
775 	case 'd':
776 	    if (sequence || query || delkey)
777 		msg_fatal("specify only one of -s -q or -d");
778 	    delkey = optarg;
779 	    break;
780 	case 'f':
781 	    dict_flags &= ~DICT_FLAG_FOLD_FIX;
782 	    break;
783 	case 'i':
784 	    open_flags &= ~O_TRUNC;
785 	    break;
786 	case 'n':
787 	    dict_flags |= DICT_FLAG_TRY0NULL;
788 	    dict_flags &= ~DICT_FLAG_TRY1NULL;
789 	    break;
790 	case 'o':
791 	    postalias_flags &= ~POSTALIAS_FLAG_AS_OWNER;
792 	    break;
793 	case 'p':
794 	    postalias_flags &= ~POSTALIAS_FLAG_SAVE_PERM;
795 	    break;
796 	case 'q':
797 	    if (sequence || query || delkey)
798 		msg_fatal("specify only one of -s -q or -d");
799 	    query = optarg;
800 	    break;
801 	case 'r':
802 	    dict_flags &= ~(DICT_FLAG_DUP_WARN | DICT_FLAG_DUP_IGNORE);
803 	    dict_flags |= DICT_FLAG_DUP_REPLACE;
804 	    break;
805 	case 's':
806 	    if (query || delkey)
807 		msg_fatal("specify only one of -s or -q or -d");
808 	    sequence = 1;
809 	    break;
810 	case 'u':
811 	    dict_flags &= ~DICT_FLAG_UTF8_REQUEST;
812 	    break;
813 	case 'v':
814 	    msg_verbose++;
815 	    break;
816 	case 'w':
817 	    dict_flags &= ~(DICT_FLAG_DUP_WARN | DICT_FLAG_DUP_REPLACE);
818 	    dict_flags |= DICT_FLAG_DUP_IGNORE;
819 	    break;
820 	}
821     }
822     mail_conf_read();
823     /* Enforce consistent operation of different Postfix parts. */
824     import_env = mail_parm_split(VAR_IMPORT_ENVIRON, var_import_environ);
825     update_env(import_env->argv);
826     argv_free(import_env);
827     /* Re-evaluate mail_task() after reading main.cf. */
828     maillog_client_init(mail_task(argv[0]), MAILLOG_CLIENT_FLAG_NONE);
829     mail_dict_init();
830 
831     /*
832      * Use the map type specified by the user, or fall back to a default
833      * database type.
834      */
835     if (delkey) {				/* remove entry */
836 	if (optind + 1 > argc)
837 	    usage(argv[0]);
838 	if (strcmp(delkey, "-") == 0)
839 	    exit(postalias_deletes(VSTREAM_IN, argv + optind, argc - optind,
840 				   dict_flags | DICT_FLAG_LOCK) == 0);
841 	found = 0;
842 	while (optind < argc) {
843 	    if ((path_name = split_at(argv[optind], ':')) != 0) {
844 		found |= postalias_delete(argv[optind], path_name, delkey,
845 					  dict_flags | DICT_FLAG_LOCK);
846 	    } else {
847 		found |= postalias_delete(var_db_type, argv[optind], delkey,
848 					  dict_flags | DICT_FLAG_LOCK);
849 	    }
850 	    optind++;
851 	}
852 	exit(found ? 0 : 1);
853     } else if (query) {				/* query map(s) */
854 	if (optind + 1 > argc)
855 	    usage(argv[0]);
856 	if (strcmp(query, "-") == 0)
857 	    exit(postalias_queries(VSTREAM_IN, argv + optind, argc - optind,
858 				   dict_flags | DICT_FLAG_LOCK) == 0);
859 	while (optind < argc) {
860 	    if ((path_name = split_at(argv[optind], ':')) != 0) {
861 		found = postalias_query(argv[optind], path_name, query,
862 					dict_flags | DICT_FLAG_LOCK);
863 	    } else {
864 		found = postalias_query(var_db_type, argv[optind], query,
865 					dict_flags | DICT_FLAG_LOCK);
866 	    }
867 	    if (found)
868 		exit(0);
869 	    optind++;
870 	}
871 	exit(1);
872     } else if (sequence) {
873 	while (optind < argc) {
874 	    if ((path_name = split_at(argv[optind], ':')) != 0) {
875 		postalias_seq(argv[optind], path_name,
876 			      dict_flags | DICT_FLAG_LOCK);
877 	    } else {
878 		postalias_seq(var_db_type, argv[optind],
879 			      dict_flags | DICT_FLAG_LOCK);
880 	    }
881 	    exit(0);
882 	}
883 	exit(1);
884     } else {					/* create/update map(s) */
885 	if (optind + 1 > argc)
886 	    usage(argv[0]);
887 	while (optind < argc) {
888 	    if ((path_name = split_at(argv[optind], ':')) != 0) {
889 		postalias(argv[optind], path_name, postalias_flags,
890 			  open_flags, dict_flags);
891 	    } else {
892 		postalias(var_db_type, argv[optind], postalias_flags,
893 			  open_flags, dict_flags);
894 	    }
895 	    optind++;
896 	}
897 	exit(0);
898     }
899 }
900