xref: /freebsd/usr.sbin/tzsetup/tzsetup.c (revision a0b9e2e854027e6ff61fb075a1309dbc71c42b54)
1 /*
2  * Copyright 1996 Massachusetts Institute of Technology
3  *
4  * Permission to use, copy, modify, and distribute this software and
5  * its documentation for any purpose and without fee is hereby
6  * granted, provided that both the above copyright notice and this
7  * permission notice appear in all copies, that both the above
8  * copyright notice and this permission notice appear in all
9  * supporting documentation, and that the name of M.I.T. not be used
10  * in advertising or publicity pertaining to distribution of the
11  * software without specific, written prior permission.  M.I.T. makes
12  * no representations about the suitability of this software for any
13  * purpose.  It is provided "as is" without express or implied
14  * warranty.
15  *
16  * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''.  M.I.T. DISCLAIMS
17  * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
18  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
20  * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
26  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * Second attempt at a `tzmenu' program, using the separate description
32  * files provided in newer tzdata releases.
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include <err.h>
39 #include <errno.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <time.h>
44 #include <unistd.h>
45 
46 #include <sys/fcntl.h>
47 #include <sys/param.h>
48 #include <sys/queue.h>
49 #include <sys/stat.h>
50 #include <sys/sysctl.h>
51 
52 #ifdef HAVE_DIALOG
53 #include <dialog.h>
54 #endif
55 
56 #define	_PATH_ZONETAB		"/usr/share/zoneinfo/zone1970.tab"
57 #define	_PATH_ISO3166		"/usr/share/misc/iso3166"
58 #define	_PATH_ZONEINFO		"/usr/share/zoneinfo"
59 #define	_PATH_LOCALTIME		"/etc/localtime"
60 #define	_PATH_DB		"/var/db/zoneinfo"
61 #define	_PATH_WALL_CMOS_CLOCK	"/etc/wall_cmos_clock"
62 
63 #ifdef PATH_MAX
64 #define	SILLY_BUFFER_SIZE	2*PATH_MAX
65 #else
66 #warning "Somebody needs to fix this to dynamically size this buffer."
67 #define	SILLY_BUFFER_SIZE	2048
68 #endif
69 
70 /* special return codes for `fire' actions */
71 #define DITEM_FAILURE           1
72 
73 /* flags - returned in upper 16 bits of return status */
74 #define DITEM_LEAVE_MENU        (1 << 16)
75 #define DITEM_RECREATE          (1 << 18)
76 
77 static char	path_zonetab[MAXPATHLEN], path_iso3166[MAXPATHLEN],
78 		path_zoneinfo[MAXPATHLEN], path_localtime[MAXPATHLEN],
79 		path_db[MAXPATHLEN], path_wall_cmos_clock[MAXPATHLEN];
80 
81 static int reallydoit = 1;
82 static int reinstall = 0;
83 static char *chrootenv = NULL;
84 
85 static void	usage(void);
86 static int	install_zoneinfo(const char *zoneinfo);
87 static int	install_zoneinfo_file(const char *zoneinfo_file);
88 
89 #ifdef HAVE_DIALOG
90 /* for use in describing more exotic behaviors */
91 typedef struct dialogMenuItem {
92 	char *prompt;
93 	char *title;
94 	int (*fire)(struct dialogMenuItem *self);
95 	void *data;
96 } dialogMenuItem;
97 
98 static int
99 xdialog_count_rows(const char *p)
100 {
101 	int rows = 0;
102 
103 	while ((p = strchr(p, '\n')) != NULL) {
104 		p++;
105 		if (*p == '\0')
106 			break;
107 		rows++;
108 	}
109 
110 	return (rows ? rows : 1);
111 }
112 
113 static int
114 xdialog_count_columns(const char *p)
115 {
116 	int len;
117 	int max_len = 0;
118 	const char *q;
119 
120 	for (; (q = strchr(p, '\n')) != NULL; p = q + 1) {
121 		len = q - p;
122 		max_len = MAX(max_len, len);
123 	}
124 
125 	len = strlen(p);
126 	max_len = MAX(max_len, len);
127 	return (max_len);
128 }
129 
130 static int
131 xdialog_menu(const char *title, const char *cprompt, int height, int width,
132 	     int menu_height, int item_no, dialogMenuItem *ditems)
133 {
134 	int i, result, choice = 0;
135 	DIALOG_LISTITEM *listitems;
136 	DIALOG_VARS save_vars;
137 
138 	dlg_save_vars(&save_vars);
139 
140 	/* initialize list items */
141 	listitems = dlg_calloc(DIALOG_LISTITEM, item_no + 1);
142 	assert_ptr(listitems, "xdialog_menu");
143 	for (i = 0; i < item_no; i++) {
144 		listitems[i].name = ditems[i].prompt;
145 		listitems[i].text = ditems[i].title;
146 	}
147 
148 	/* calculate height */
149 	if (height < 0)
150 		height = xdialog_count_rows(cprompt) + menu_height + 4 + 2;
151 	if (height > LINES)
152 		height = LINES;
153 
154 	/* calculate width */
155 	if (width < 0) {
156 		int tag_x = 0;
157 
158 		for (i = 0; i < item_no; i++) {
159 			int j, l;
160 
161 			l = strlen(listitems[i].name);
162 			for (j = 0; j < item_no; j++) {
163 				int k = strlen(listitems[j].text);
164 				tag_x = MAX(tag_x, l + k + 2);
165 			}
166 		}
167 		width = MAX(xdialog_count_columns(cprompt), title != NULL ?
168 		    xdialog_count_columns(title) : 0);
169 		width = MAX(width, tag_x + 4) + 4;
170 	}
171 	width = MAX(width, 24);
172 	if (width > COLS)
173 		width = COLS;
174 
175 again:
176 	dialog_vars.default_item = listitems[choice].name;
177 	result = dlg_menu(title, cprompt, height, width,
178 	    menu_height, item_no, listitems, &choice, NULL);
179 	switch (result) {
180 	case DLG_EXIT_ESC:
181 		result = -1;
182 		break;
183 	case DLG_EXIT_OK:
184 		if (ditems[choice].fire != NULL) {
185 			int status;
186 
187 			status = ditems[choice].fire(ditems + choice);
188 			if (status & DITEM_RECREATE) {
189 				dlg_clear();
190 				goto again;
191 			}
192 		}
193 		result = 0;
194 		break;
195 	case DLG_EXIT_CANCEL:
196 	default:
197 		result = 1;
198 		break;
199 	}
200 
201 	free(listitems);
202 	dlg_restore_vars(&save_vars);
203 	return (result);
204 }
205 
206 static int usedialog = 1;
207 
208 static int	confirm_zone(const char *filename);
209 static int	continent_country_menu(dialogMenuItem *);
210 static int	set_zone_multi(dialogMenuItem *);
211 static int	set_zone_whole_country(dialogMenuItem *);
212 static int	set_zone_menu(dialogMenuItem *);
213 static int	set_zone_utc(void);
214 
215 struct continent {
216 	dialogMenuItem *menu;
217 	int		nitems;
218 };
219 
220 static struct continent	africa, america, antarctica, asia, atlantic;
221 static struct continent	australia, europe, indian, pacific, utc;
222 
223 static struct continent_names {
224 	const char	*name;
225 	struct continent *continent;
226 } continent_names[] = {
227 	{ "Africa",	&africa },
228 	{ "America",	&america },
229 	{ "Antarctica",	&antarctica },
230 	{ "Asia",	&asia },
231 	{ "Atlantic",	&atlantic },
232 	{ "Australia",	&australia },
233 	{ "Europe",	&europe },
234 	{ "Indian",	&indian },
235 	{ "Pacific",	&pacific },
236 	{ "UTC",	&utc }
237 };
238 
239 static struct continent_items {
240 	char		prompt[2];
241 	char		title[30];
242 } continent_items[] = {
243 	{ "1",	"Africa" },
244 	{ "2",	"America -- North and South" },
245 	{ "3",	"Antarctica" },
246 	{ "4",	"Asia" },
247 	{ "5",	"Atlantic Ocean" },
248 	{ "6",	"Australia" },
249 	{ "7",	"Europe" },
250 	{ "8",	"Indian Ocean" },
251 	{ "9",	"Pacific Ocean" },
252 	{ "0",	"UTC" }
253 };
254 
255 #define	NCONTINENTS	\
256     (int)((sizeof(continent_items)) / (sizeof(continent_items[0])))
257 static dialogMenuItem continents[NCONTINENTS];
258 
259 #define	OCEANP(x)	((x) == 4 || (x) == 7 || (x) == 8)
260 
261 static int
262 continent_country_menu(dialogMenuItem *continent)
263 {
264 	char		title[64], prompt[64];
265 	struct continent *contp = continent->data;
266 	int		isocean = OCEANP(continent - continents);
267 	int		menulen;
268 	int		rv;
269 
270 	if (strcmp(continent->title, "UTC") == 0)
271 		return (set_zone_utc());
272 
273 	/* Short cut -- if there's only one country, don't post a menu. */
274 	if (contp->nitems == 1)
275 		return (contp->menu[0].fire(&contp->menu[0]));
276 
277 	/* It's amazing how much good grammar really matters... */
278 	if (!isocean) {
279 		snprintf(title, sizeof(title), "Countries in %s",
280 		    continent->title);
281 		snprintf(prompt, sizeof(prompt), "Select a country or region");
282 	} else {
283 		snprintf(title, sizeof(title), "Islands and groups in the %s",
284 		    continent->title);
285 		snprintf(prompt, sizeof(prompt), "Select an island or group");
286 	}
287 
288 	menulen = contp->nitems < 16 ? contp->nitems : 16;
289 	rv = xdialog_menu(title, prompt, -1, -1, menulen, contp->nitems,
290 	    contp->menu);
291 	if (rv == 0)
292 		return (DITEM_LEAVE_MENU);
293 	return (DITEM_RECREATE);
294 }
295 
296 static struct continent *
297 find_continent(const char *name)
298 {
299 	int		i;
300 
301 	for (i = 0; i < NCONTINENTS; i++)
302 		if (strcmp(name, continent_names[i].name) == 0)
303 			return (continent_names[i].continent);
304 	return (0);
305 }
306 
307 struct country {
308 	char		*name;
309 	char		*tlc;
310 	int		nzones;
311 	char		*filename;	/* use iff nzones < 0 */
312 	struct continent *continent;	/* use iff nzones < 0 */
313 	TAILQ_HEAD(, zone) zones;	/* use iff nzones > 0 */
314 	dialogMenuItem	*submenu;	/* use iff nzones > 0 */
315 };
316 
317 struct zone {
318 	TAILQ_ENTRY(zone) link;
319 	char		*descr;
320 	char		*filename;
321 	struct continent *continent;
322 };
323 
324 /*
325  * This is the easiest organization... we use ISO 3166 country codes,
326  * of the two-letter variety, so we just size this array to suit.
327  * Beats worrying about dynamic allocation.
328  */
329 #define	NCOUNTRIES	(26 * 26)
330 static struct country countries[NCOUNTRIES];
331 
332 #define	CODE2INT(s)	((s[0] - 'A') * 26 + (s[1] - 'A'))
333 
334 /*
335  * Read the ISO 3166 country code database in _PATH_ISO3166
336  * (/usr/share/misc/iso3166).  On error, exit via err(3).
337  */
338 static void
339 read_iso3166_table(void)
340 {
341 	FILE		*fp;
342 	struct country	*cp;
343 	size_t		len;
344 	char		*s, *t, *name;
345 	int		lineno;
346 
347 	fp = fopen(path_iso3166, "r");
348 	if (!fp)
349 		err(1, "%s", path_iso3166);
350 	lineno = 0;
351 
352 	while ((s = fgetln(fp, &len)) != NULL) {
353 		lineno++;
354 		if (s[len - 1] != '\n')
355 			errx(1, "%s:%d: invalid format", path_iso3166, lineno);
356 		s[len - 1] = '\0';
357 		if (s[0] == '#' || strspn(s, " \t") == len - 1)
358 			continue;
359 
360 		/* Isolate the two-letter code. */
361 		t = strsep(&s, "\t");
362 		if (t == NULL || strlen(t) != 2)
363 			errx(1, "%s:%d: invalid format", path_iso3166, lineno);
364 		if (t[0] < 'A' || t[0] > 'Z' || t[1] < 'A' || t[1] > 'Z')
365 			errx(1, "%s:%d: invalid code `%s'", path_iso3166,
366 			    lineno, t);
367 
368 		/* Now skip past the three-letter and numeric codes. */
369 		name = strsep(&s, "\t");	/* 3-let */
370 		if (name == NULL || strlen(name) != 3)
371 			errx(1, "%s:%d: invalid format", path_iso3166, lineno);
372 		name = strsep(&s, "\t");	/* numeric */
373 		if (name == NULL || strlen(name) != 3)
374 			errx(1, "%s:%d: invalid format", path_iso3166, lineno);
375 
376 		name = s;
377 
378 		cp = &countries[CODE2INT(t)];
379 		if (cp->name)
380 			errx(1, "%s:%d: country code `%s' multiply defined: %s",
381 			    path_iso3166, lineno, t, cp->name);
382 		cp->name = strdup(name);
383 		if (cp->name == NULL)
384 			errx(1, "malloc failed");
385 		cp->tlc = strdup(t);
386 		if (cp->tlc == NULL)
387 			errx(1, "malloc failed");
388 	}
389 
390 	fclose(fp);
391 }
392 
393 static void
394 add_zone_to_country(int lineno, const char *tlc, const char *descr,
395     const char *file, struct continent *cont)
396 {
397 	struct zone	*zp;
398 	struct country	*cp;
399 
400 	if (tlc[0] < 'A' || tlc[0] > 'Z' || tlc[1] < 'A' || tlc[1] > 'Z')
401 		errx(1, "%s:%d: country code `%s' invalid", path_zonetab,
402 		    lineno, tlc);
403 
404 	cp = &countries[CODE2INT(tlc)];
405 	if (cp->name == 0)
406 		errx(1, "%s:%d: country code `%s' unknown", path_zonetab,
407 		    lineno, tlc);
408 
409 	if (descr) {
410 		if (cp->nzones < 0)
411 			errx(1, "%s:%d: conflicting zone definition",
412 			    path_zonetab, lineno);
413 
414 		zp = malloc(sizeof(*zp));
415 		if (zp == NULL)
416 			errx(1, "malloc(%zu)", sizeof(*zp));
417 
418 		if (cp->nzones == 0)
419 			TAILQ_INIT(&cp->zones);
420 
421 		zp->descr = strdup(descr);
422 		if (zp->descr == NULL)
423 			errx(1, "malloc failed");
424 		zp->filename = strdup(file);
425 		if (zp->filename == NULL)
426 			errx(1, "malloc failed");
427 		zp->continent = cont;
428 		TAILQ_INSERT_TAIL(&cp->zones, zp, link);
429 		cp->nzones++;
430 	} else {
431 		if (cp->nzones > 0)
432 			errx(1, "%s:%d: zone must have description",
433 			    path_zonetab, lineno);
434 		if (cp->nzones < 0)
435 			errx(1, "%s:%d: zone multiply defined",
436 			    path_zonetab, lineno);
437 		cp->nzones = -1;
438 		cp->filename = strdup(file);
439 		if (cp->filename == NULL)
440 			errx(1, "malloc failed");
441 		cp->continent = cont;
442 	}
443 }
444 
445 /*
446  * This comparison function intentionally sorts all of the null-named
447  * ``countries''---i.e., the codes that don't correspond to a real
448  * country---to the end.  Everything else is lexical by country name.
449  */
450 static int
451 compare_countries(const void *xa, const void *xb)
452 {
453 	const struct country *a = xa, *b = xb;
454 
455 	if (a->name == 0 && b->name == 0)
456 		return (0);
457 	if (a->name == 0 && b->name != 0)
458 		return (1);
459 	if (b->name == 0)
460 		return (-1);
461 
462 	return (strcmp(a->name, b->name));
463 }
464 
465 /*
466  * This must be done AFTER all zone descriptions are read, since it breaks
467  * CODE2INT().
468  */
469 static void
470 sort_countries(void)
471 {
472 
473 	qsort(countries, NCOUNTRIES, sizeof(countries[0]), compare_countries);
474 }
475 
476 static void
477 read_zones(void)
478 {
479 	char		contbuf[16];
480 	FILE		*fp;
481 	struct continent *cont;
482 	size_t		len, contlen;
483 	char		*line, *country_list, *tlc, *file, *descr, *p;
484 	int		lineno;
485 
486 	fp = fopen(path_zonetab, "r");
487 	if (!fp)
488 		err(1, "%s", path_zonetab);
489 	lineno = 0;
490 
491 	while ((line = fgetln(fp, &len)) != NULL) {
492 		lineno++;
493 		if (line[len - 1] != '\n')
494 			errx(1, "%s:%d: invalid format", path_zonetab, lineno);
495 		line[len - 1] = '\0';
496 		if (line[0] == '#')
497 			continue;
498 
499 		country_list = strsep(&line, "\t");
500 		/* coord = */ strsep(&line, "\t");	 /* Unused */
501 		file = strsep(&line, "\t");
502 		/* get continent portion from continent/country */
503 		p = strchr(file, '/');
504 		if (p == NULL)
505 			errx(1, "%s:%d: invalid zone name `%s'", path_zonetab,
506 			    lineno, file);
507 		contlen = p - file + 1;		/* trailing nul */
508 		if (contlen > sizeof(contbuf))
509 			errx(1, "%s:%d: continent name in zone name `%s' too long",
510 			    path_zonetab, lineno, file);
511 		strlcpy(contbuf, file, contlen);
512 		cont = find_continent(contbuf);
513 		if (!cont)
514 			errx(1, "%s:%d: invalid region `%s'", path_zonetab,
515 			    lineno, contbuf);
516 
517 		descr = (line != NULL && *line != '\0') ? line : NULL;
518 
519 		while (country_list != NULL) {
520 			tlc = strsep(&country_list, ",");
521 			if (strlen(tlc) != 2)
522 				errx(1, "%s:%d: invalid country code `%s'",
523 				    path_zonetab, lineno, tlc);
524 			add_zone_to_country(lineno, tlc, descr, file, cont);
525 		}
526 	}
527 	fclose(fp);
528 }
529 
530 static void
531 make_menus(void)
532 {
533 	struct country	*cp;
534 	struct zone	*zp, *zp2;
535 	struct continent *cont;
536 	dialogMenuItem	*dmi;
537 	int		i;
538 
539 	/*
540 	 * First, count up all the countries in each continent/ocean.
541 	 * Be careful to count those countries which have multiple zones
542 	 * only once for each.  NB: some countries are in multiple
543 	 * continents/oceans.
544 	 */
545 	for (cp = countries; cp->name; cp++) {
546 		if (cp->nzones == 0)
547 			continue;
548 		if (cp->nzones < 0) {
549 			cp->continent->nitems++;
550 		} else {
551 			TAILQ_FOREACH(zp, &cp->zones, link) {
552 				cont = zp->continent;
553 				for (zp2 = TAILQ_FIRST(&cp->zones);
554 				    zp2->continent != cont;
555 				    zp2 = TAILQ_NEXT(zp2, link))
556 					;
557 				if (zp2 == zp)
558 					zp->continent->nitems++;
559 			}
560 		}
561 	}
562 
563 	/*
564 	 * Now allocate memory for the country menus and initialize
565 	 * continent menus.  We set nitems back to zero so that we can
566 	 * use it for counting again when we actually build the menus.
567 	 */
568 	memset(continents, 0, sizeof(continents));
569 	for (i = 0; i < NCONTINENTS; i++) {
570 		continent_names[i].continent->menu =
571 		    malloc(sizeof(dialogMenuItem) *
572 		    continent_names[i].continent->nitems);
573 		if (continent_names[i].continent->menu == NULL)
574 			errx(1, "malloc for continent menu");
575 		continent_names[i].continent->nitems = 0;
576 		continents[i].prompt = continent_items[i].prompt;
577 		continents[i].title = continent_items[i].title;
578 		continents[i].fire = continent_country_menu;
579 		continents[i].data = continent_names[i].continent;
580 	}
581 
582 	/*
583 	 * Now that memory is allocated, create the menu items for
584 	 * each continent.  For multiple-zone countries, also create
585 	 * the country's zone submenu.
586 	 */
587 	for (cp = countries; cp->name; cp++) {
588 		if (cp->nzones == 0)
589 			continue;
590 		if (cp->nzones < 0) {
591 			dmi = &cp->continent->menu[cp->continent->nitems];
592 			memset(dmi, 0, sizeof(*dmi));
593 			asprintf(&dmi->prompt, "%d", ++cp->continent->nitems);
594 			dmi->title = cp->name;
595 			dmi->fire = set_zone_whole_country;
596 			dmi->data = cp;
597 		} else {
598 			cp->submenu = malloc(cp->nzones * sizeof(*dmi));
599 			if (cp->submenu == 0)
600 				errx(1, "malloc for submenu");
601 			cp->nzones = 0;
602 			TAILQ_FOREACH(zp, &cp->zones, link) {
603 				cont = zp->continent;
604 				dmi = &cp->submenu[cp->nzones];
605 				memset(dmi, 0, sizeof(*dmi));
606 				asprintf(&dmi->prompt, "%d", ++cp->nzones);
607 				dmi->title = zp->descr;
608 				dmi->fire = set_zone_multi;
609 				dmi->data = zp;
610 
611 				for (zp2 = TAILQ_FIRST(&cp->zones);
612 				    zp2->continent != cont;
613 				    zp2 = TAILQ_NEXT(zp2, link))
614 					;
615 				if (zp2 != zp)
616 					continue;
617 
618 				dmi = &cont->menu[cont->nitems];
619 				memset(dmi, 0, sizeof(*dmi));
620 				asprintf(&dmi->prompt, "%d", ++cont->nitems);
621 				dmi->title = cp->name;
622 				dmi->fire = set_zone_menu;
623 				dmi->data = cp;
624 			}
625 		}
626 	}
627 }
628 
629 static int
630 set_zone_menu(dialogMenuItem *dmi)
631 {
632 	char		title[64], prompt[64];
633 	struct country	*cp = dmi->data;
634 	int		menulen;
635 	int		rv;
636 
637 	snprintf(title, sizeof(title), "%s Time Zones", cp->name);
638 	snprintf(prompt, sizeof(prompt),
639 	    "Select a zone which observes the same time as your locality.");
640 	menulen = cp->nzones < 16 ? cp->nzones : 16;
641 	rv = xdialog_menu(title, prompt, -1, -1, menulen, cp->nzones,
642 	    cp->submenu);
643 	if (rv != 0)
644 		return (DITEM_RECREATE);
645 	return (DITEM_LEAVE_MENU);
646 }
647 
648 static int
649 set_zone_utc(void)
650 {
651 	if (!confirm_zone("UTC"))
652 		return (DITEM_FAILURE | DITEM_RECREATE);
653 
654 	return (install_zoneinfo("UTC"));
655 }
656 
657 static int
658 confirm_zone(const char *filename)
659 {
660 	char		title[64], prompt[64];
661 	time_t		t = time(0);
662 	struct tm	*tm;
663 	int		rv;
664 
665 	setenv("TZ", filename, 1);
666 	tzset();
667 	tm = localtime(&t);
668 
669 	snprintf(title, sizeof(title), "Confirmation");
670 	snprintf(prompt, sizeof(prompt),
671 	    "Does the abbreviation `%s' look reasonable?", tm->tm_zone);
672 	rv = !dialog_yesno(title, prompt, 5, 72);
673 	return (rv);
674 }
675 
676 static int
677 set_zone_multi(dialogMenuItem *dmi)
678 {
679 	struct zone	*zp = dmi->data;
680 	int		rv;
681 
682 	if (!confirm_zone(zp->filename))
683 		return (DITEM_FAILURE | DITEM_RECREATE);
684 
685 	rv = install_zoneinfo(zp->filename);
686 	return (rv);
687 }
688 
689 static int
690 set_zone_whole_country(dialogMenuItem *dmi)
691 {
692 	struct country	*cp = dmi->data;
693 	int		rv;
694 
695 	if (!confirm_zone(cp->filename))
696 		return (DITEM_FAILURE | DITEM_RECREATE);
697 
698 	rv = install_zoneinfo(cp->filename);
699 	return (rv);
700 }
701 
702 #endif
703 
704 static int
705 install_zoneinfo_file(const char *zoneinfo_file)
706 {
707 	char		buf[1024];
708 	char		title[64], prompt[SILLY_BUFFER_SIZE];
709 	struct stat	sb;
710 	ssize_t		len;
711 	int		fd1, fd2, copymode;
712 
713 	if (lstat(path_localtime, &sb) < 0) {
714 		/* Nothing there yet... */
715 		copymode = 1;
716 	} else if (S_ISLNK(sb.st_mode))
717 		copymode = 0;
718 	else
719 		copymode = 1;
720 
721 #ifdef VERBOSE
722 	snprintf(title, sizeof(title), "Info");
723 	if (copymode)
724 		snprintf(prompt, sizeof(prompt),
725 		    "Copying %s to %s", zoneinfo_file, path_localtime);
726 	else
727 		snprintf(prompt, sizeof(prompt),
728 		    "Creating symbolic link %s to %s",
729 		    path_localtime, zoneinfo_file);
730 #ifdef HAVE_DIALOG
731 	if (usedialog)
732 		dialog_msgbox(title, prompt, 8, 72, 1);
733 	else
734 #endif
735 		fprintf(stderr, "%s\n", prompt);
736 #endif
737 
738 	if (reallydoit) {
739 		if (copymode) {
740 			fd1 = open(zoneinfo_file, O_RDONLY, 0);
741 			if (fd1 < 0) {
742 				snprintf(title, sizeof(title), "Error");
743 				snprintf(prompt, sizeof(prompt),
744 				    "Could not open %s: %s", zoneinfo_file,
745 				    strerror(errno));
746 #ifdef HAVE_DIALOG
747 				if (usedialog)
748 					dialog_msgbox(title, prompt, 8, 72, 1);
749 				else
750 #endif
751 					fprintf(stderr, "%s\n", prompt);
752 				return (DITEM_FAILURE | DITEM_RECREATE);
753 			}
754 
755 			if (unlink(path_localtime) < 0 && errno != ENOENT) {
756 				snprintf(prompt, sizeof(prompt),
757 				    "Could not delete %s: %s",
758 				    path_localtime, strerror(errno));
759 #ifdef HAVE_DIALOG
760 				if (usedialog) {
761 					snprintf(title, sizeof(title), "Error");
762 					dialog_msgbox(title, prompt, 8, 72, 1);
763 				} else
764 #endif
765 					fprintf(stderr, "%s\n", prompt);
766 				return (DITEM_FAILURE | DITEM_RECREATE);
767 			}
768 
769 			fd2 = open(path_localtime, O_CREAT | O_EXCL | O_WRONLY,
770 			    S_IRUSR | S_IRGRP | S_IROTH);
771 			if (fd2 < 0) {
772 				snprintf(title, sizeof(title), "Error");
773 				snprintf(prompt, sizeof(prompt),
774 				    "Could not open %s: %s",
775 				    path_localtime, strerror(errno));
776 #ifdef HAVE_DIALOG
777 				if (usedialog)
778 					dialog_msgbox(title, prompt, 8, 72, 1);
779 				else
780 #endif
781 					fprintf(stderr, "%s\n", prompt);
782 				return (DITEM_FAILURE | DITEM_RECREATE);
783 			}
784 
785 			while ((len = read(fd1, buf, sizeof(buf))) > 0)
786 				if ((len = write(fd2, buf, len)) < 0)
787 					break;
788 
789 			if (len == -1) {
790 				snprintf(title, sizeof(title), "Error");
791 				snprintf(prompt, sizeof(prompt),
792 				    "Error copying %s to %s %s", zoneinfo_file,
793 				    path_localtime, strerror(errno));
794 #ifdef HAVE_DIALOG
795 				if (usedialog)
796 					dialog_msgbox(title, prompt, 8, 72, 1);
797 				else
798 #endif
799 					fprintf(stderr, "%s\n", prompt);
800 				/* Better to leave none than a corrupt one. */
801 				unlink(path_localtime);
802 				return (DITEM_FAILURE | DITEM_RECREATE);
803 			}
804 			close(fd1);
805 			close(fd2);
806 		} else {
807 			if (access(zoneinfo_file, R_OK) != 0) {
808 				snprintf(title, sizeof(title), "Error");
809 				snprintf(prompt, sizeof(prompt),
810 				    "Cannot access %s: %s", zoneinfo_file,
811 				    strerror(errno));
812 #ifdef HAVE_DIALOG
813 				if (usedialog)
814 					dialog_msgbox(title, prompt, 8, 72, 1);
815 				else
816 #endif
817 					fprintf(stderr, "%s\n", prompt);
818 				return (DITEM_FAILURE | DITEM_RECREATE);
819 			}
820 			if (unlink(path_localtime) < 0 && errno != ENOENT) {
821 				snprintf(prompt, sizeof(prompt),
822 				    "Could not delete %s: %s",
823 				    path_localtime, strerror(errno));
824 #ifdef HAVE_DIALOG
825 				if (usedialog) {
826 					snprintf(title, sizeof(title), "Error");
827 					dialog_msgbox(title, prompt, 8, 72, 1);
828 				} else
829 #endif
830 					fprintf(stderr, "%s\n", prompt);
831 				return (DITEM_FAILURE | DITEM_RECREATE);
832 			}
833 			if (symlink(zoneinfo_file, path_localtime) < 0) {
834 				snprintf(title, sizeof(title), "Error");
835 				snprintf(prompt, sizeof(prompt),
836 				    "Cannot create symbolic link %s to %s: %s",
837 				    path_localtime, zoneinfo_file,
838 				    strerror(errno));
839 #ifdef HAVE_DIALOG
840 				if (usedialog)
841 					dialog_msgbox(title, prompt, 8, 72, 1);
842 				else
843 #endif
844 					fprintf(stderr, "%s\n", prompt);
845 				return (DITEM_FAILURE | DITEM_RECREATE);
846 			}
847 		}
848 
849 #ifdef VERBOSE
850 		snprintf(title, sizeof(title), "Done");
851 		if (copymode)
852 			snprintf(prompt, sizeof(prompt),
853 			    "Copied timezone file from %s to %s",
854 			    zoneinfo_file, path_localtime);
855 		else
856 			snprintf(prompt, sizeof(prompt),
857 			    "Created symbolic link from %s to %s",
858 			    zoneinfo_file, path_localtime);
859 #ifdef HAVE_DIALOG
860 		if (usedialog)
861 			dialog_msgbox(title, prompt, 8, 72, 1);
862 		else
863 #endif
864 			fprintf(stderr, "%s\n", prompt);
865 #endif
866 	} /* reallydoit */
867 
868 	return (DITEM_LEAVE_MENU);
869 }
870 
871 static int
872 install_zoneinfo(const char *zoneinfo)
873 {
874 	int		rv;
875 	FILE		*f;
876 	char		path_zoneinfo_file[MAXPATHLEN];
877 
878 	if ((size_t)snprintf(path_zoneinfo_file, sizeof(path_zoneinfo_file),
879 	    "%s/%s", path_zoneinfo, zoneinfo) >= sizeof(path_zoneinfo_file))
880 		errx(1, "%s/%s name too long", path_zoneinfo, zoneinfo);
881 	rv = install_zoneinfo_file(path_zoneinfo_file);
882 
883 	/* Save knowledge for later */
884 	if (reallydoit && (rv & DITEM_FAILURE) == 0) {
885 		if ((f = fopen(path_db, "w")) != NULL) {
886 			fprintf(f, "%s\n", zoneinfo);
887 			fclose(f);
888 		}
889 	}
890 
891 	return (rv);
892 }
893 
894 static void
895 usage(void)
896 {
897 
898 	fprintf(stderr, "usage: tzsetup [-nrs] [-C chroot_directory]"
899 	    " [zoneinfo_file | zoneinfo_name]\n");
900 	exit(1);
901 }
902 
903 int
904 main(int argc, char **argv)
905 {
906 #ifdef HAVE_DIALOG
907 	char		title[64], prompt[128];
908 	int		fd;
909 #endif
910 	int		c, rv, skiputc;
911 	char		vm_guest[16] = "";
912 	size_t		len = sizeof(vm_guest);
913 
914 	skiputc = 0;
915 
916 	/* Default skiputc to 1 for VM guests */
917 	if (sysctlbyname("kern.vm_guest", vm_guest, &len, NULL, 0) == 0 &&
918 	    strcmp(vm_guest, "none") != 0)
919 		skiputc = 1;
920 
921 	while ((c = getopt(argc, argv, "C:nrs")) != -1) {
922 		switch(c) {
923 		case 'C':
924 			chrootenv = optarg;
925 			break;
926 		case 'n':
927 			reallydoit = 0;
928 			break;
929 		case 'r':
930 			reinstall = 1;
931 #ifdef HAVE_DIALOG
932 			usedialog = 0;
933 #endif
934 			break;
935 		case 's':
936 			skiputc = 1;
937 			break;
938 		default:
939 			usage();
940 		}
941 	}
942 
943 	if (argc - optind > 1)
944 		usage();
945 
946 	if (chrootenv == NULL) {
947 		strcpy(path_zonetab, _PATH_ZONETAB);
948 		strcpy(path_iso3166, _PATH_ISO3166);
949 		strcpy(path_zoneinfo, _PATH_ZONEINFO);
950 		strcpy(path_localtime, _PATH_LOCALTIME);
951 		strcpy(path_db, _PATH_DB);
952 		strcpy(path_wall_cmos_clock, _PATH_WALL_CMOS_CLOCK);
953 	} else {
954 		sprintf(path_zonetab, "%s/%s", chrootenv, _PATH_ZONETAB);
955 		sprintf(path_iso3166, "%s/%s", chrootenv, _PATH_ISO3166);
956 		sprintf(path_zoneinfo, "%s/%s", chrootenv, _PATH_ZONEINFO);
957 		sprintf(path_localtime, "%s/%s", chrootenv, _PATH_LOCALTIME);
958 		sprintf(path_db, "%s/%s", chrootenv, _PATH_DB);
959 		sprintf(path_wall_cmos_clock, "%s/%s", chrootenv,
960 		    _PATH_WALL_CMOS_CLOCK);
961 	}
962 
963 	/* Override the user-supplied umask. */
964 	(void)umask(S_IWGRP | S_IWOTH);
965 
966 	if (reinstall == 1) {
967 		FILE *f;
968 		char zoneinfo[MAXPATHLEN];
969 
970 		if ((f = fopen(path_db, "r")) != NULL) {
971 			if (fgets(zoneinfo, sizeof(zoneinfo), f) != NULL) {
972 				zoneinfo[sizeof(zoneinfo) - 1] = 0;
973 				if (strlen(zoneinfo) > 0) {
974 					zoneinfo[strlen(zoneinfo) - 1] = 0;
975 					rv = install_zoneinfo(zoneinfo);
976 					exit(rv & ~DITEM_LEAVE_MENU);
977 				}
978 				errx(1, "Error reading %s.\n", path_db);
979 			}
980 			fclose(f);
981 			errx(1,
982 			    "Unable to determine earlier installed zoneinfo "
983 			    "name. Check %s", path_db);
984 		}
985 		errx(1, "Cannot open %s for reading. Does it exist?", path_db);
986 	}
987 
988 	/*
989 	 * If the arguments on the command-line do not specify a file,
990 	 * then interpret it as a zoneinfo name
991 	 */
992 	if (optind == argc - 1) {
993 		struct stat sb;
994 
995 		if (stat(argv[optind], &sb) != 0) {
996 #ifdef HAVE_DIALOG
997 			usedialog = 0;
998 #endif
999 			rv = install_zoneinfo(argv[optind]);
1000 			exit(rv & ~DITEM_LEAVE_MENU);
1001 		}
1002 		/* FALLTHROUGH */
1003 	}
1004 #ifdef HAVE_DIALOG
1005 
1006 	read_iso3166_table();
1007 	read_zones();
1008 	sort_countries();
1009 	make_menus();
1010 
1011 	init_dialog(stdin, stdout);
1012 	if (skiputc == 0) {
1013 		DIALOG_VARS save_vars;
1014 		int yesno;
1015 
1016 		snprintf(title, sizeof(title),
1017 		    "Select local or UTC (Greenwich Mean Time) clock");
1018 		snprintf(prompt, sizeof(prompt),
1019 		    "Is this machine's CMOS clock set to UTC?  "
1020 		    "If it is set to local time,\n"
1021 		    "or you don't know, please choose NO here!");
1022 		dlg_save_vars(&save_vars);
1023 		dialog_vars.defaultno = TRUE;
1024 		yesno = dialog_yesno(title, prompt, 7, 73);
1025 		dlg_restore_vars(&save_vars);
1026 		if (!yesno) {
1027 			if (reallydoit)
1028 				unlink(path_wall_cmos_clock);
1029 		} else {
1030 			if (reallydoit) {
1031 				fd = open(path_wall_cmos_clock,
1032 				    O_WRONLY | O_CREAT | O_TRUNC,
1033 				    S_IRUSR | S_IRGRP | S_IROTH);
1034 				if (fd < 0) {
1035 					end_dialog();
1036 					err(1, "create %s",
1037 					    path_wall_cmos_clock);
1038 				}
1039 				close(fd);
1040 			}
1041 		}
1042 		dlg_clear();
1043 	}
1044 	if (optind == argc - 1) {
1045 		snprintf(title, sizeof(title), "Default timezone provided");
1046 		snprintf(prompt, sizeof(prompt),
1047 		    "\nUse the default `%s' zone?", argv[optind]);
1048 		if (!dialog_yesno(title, prompt, 7, 72)) {
1049 			rv = install_zoneinfo_file(argv[optind]);
1050 			dlg_clear();
1051 			end_dialog();
1052 			exit(rv & ~DITEM_LEAVE_MENU);
1053 		}
1054 		dlg_clear();
1055 	}
1056 	snprintf(title, sizeof(title), "Time Zone Selector");
1057 	snprintf(prompt, sizeof(prompt), "Select a region");
1058 	xdialog_menu(title, prompt, -1, -1, NCONTINENTS, NCONTINENTS,
1059 	    continents);
1060 
1061 	dlg_clear();
1062 	end_dialog();
1063 #else
1064 	usage();
1065 #endif
1066 	return (0);
1067 }
1068