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