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