Home | History | Annotate | Line # | Download | only in sysinst
net.c revision 1.21
      1 /*	$NetBSD: net.c,v 1.21 2015/05/21 01:09:00 ozaki-r Exp $	*/
      2 
      3 /*
      4  * Copyright 1997 Piermont Information Systems Inc.
      5  * All rights reserved.
      6  *
      7  * Written by Philip A. Nelson for Piermont Information Systems Inc.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. The name of Piermont Information Systems Inc. may not be used to endorse
     18  *    or promote products derived from this software without specific prior
     19  *    written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY PIERMONT INFORMATION SYSTEMS INC. ``AS IS''
     22  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED. IN NO EVENT SHALL PIERMONT INFORMATION SYSTEMS INC. BE
     25  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
     31  * THE POSSIBILITY OF SUCH DAMAGE.
     32  *
     33  */
     34 
     35 /* net.c -- routines to fetch files off the network. */
     36 
     37 #include <sys/ioctl.h>
     38 #include <sys/param.h>
     39 #include <sys/resource.h>
     40 #include <sys/socket.h>
     41 #include <sys/stat.h>
     42 #include <sys/statvfs.h>
     43 #include <sys/statvfs.h>
     44 #include <sys/sysctl.h>
     45 #include <sys/wait.h>
     46 #include <arpa/inet.h>
     47 #include <net/if.h>
     48 #include <net/if_media.h>
     49 #include <netinet/in.h>
     50 
     51 #include <err.h>
     52 #include <stdio.h>
     53 #include <stdlib.h>
     54 #include <string.h>
     55 #include <curses.h>
     56 #include <time.h>
     57 #include <unistd.h>
     58 
     59 #include "defs.h"
     60 #include "md.h"
     61 #include "msg_defs.h"
     62 #include "menu_defs.h"
     63 #include "txtwalk.h"
     64 
     65 int network_up = 0;
     66 /* Access to network information */
     67 #define MAX_NETS 15
     68 struct net_desc {
     69 	char if_dev[STRSIZE];
     70 	char name[STRSIZE]; // TODO
     71 };
     72 
     73 static char net_dev[STRSIZE];
     74 static char net_domain[STRSIZE];
     75 static char net_host[STRSIZE];
     76 static char net_ip[SSTRSIZE];
     77 static char net_srv_ip[SSTRSIZE];
     78 static char net_mask[SSTRSIZE];
     79 char net_namesvr[STRSIZE];
     80 static char net_defroute[STRSIZE];
     81 static char net_media[STRSIZE];
     82 static char sl_flags[STRSIZE];
     83 static int net_dhcpconf;
     84 #define DHCPCONF_IPADDR         0x01
     85 #define DHCPCONF_NAMESVR        0x02
     86 #define DHCPCONF_HOST           0x04
     87 #define DHCPCONF_DOMAIN         0x08
     88 #ifdef INET6
     89 static char net_ip6[STRSIZE];
     90 #define IP6CONF_AUTOHOST        0x01
     91 #endif
     92 
     93 
     94 /* URL encode unsafe characters.  */
     95 
     96 static char *url_encode (char *dst, const char *src, const char *ep,
     97 				const char *safe_chars,
     98 				int encode_leading_slash);
     99 
    100 static void write_etc_hosts(FILE *f);
    101 
    102 #define DHCPCD "/sbin/dhcpcd"
    103 #include <signal.h>
    104 static int config_dhcp(char *);
    105 
    106 #ifdef INET6
    107 static int is_v6kernel (void);
    108 #endif
    109 
    110 /*
    111  * URL encode unsafe characters.  See RFC 1738.
    112  *
    113  * Copies src string to dst, encoding unsafe or reserved characters
    114  * in %hex form as it goes, and returning a pointer to the result.
    115  * The result is always a nul-terminated string even if it had to be
    116  * truncated to avoid overflowing the available space.
    117  *
    118  * This url_encode() function does not operate on complete URLs, it
    119  * operates on strings that make up parts of URLs.  For example, in a
    120  * URL like "ftp://username:password@host/path", the username, password,
    121  * host and path should each be encoded separately before they are
    122  * joined together with the punctuation characters.
    123  *
    124  * In most ordinary use, the path portion of a URL does not start with
    125  * a slash; the slash is a separator between the host portion and the
    126  * path portion, and is dealt with by software outside the url_encode()
    127  * function.  However, it is valid for url_encode() to be passed a
    128  * string that does begin with a slash.  For example, the string might
    129  * represent a password, or a path part of a URL that the user really
    130  * does want to begin with a slash.
    131  *
    132  * len is the length of the destination buffer.  The result will be
    133  * truncated if necessary to fit in the destination buffer.
    134  *
    135  * safe_chars is a string of characters that should not be encoded.  If
    136  * safe_chars is non-NULL, any characters in safe_chars as well as any
    137  * alphanumeric characters will be copied from src to dst without
    138  * encoding.  Some potentially useful settings for this parameter are:
    139  *
    140  *	NULL		Everything is encoded (even alphanumerics)
    141  *	""		Everything except alphanumerics are encoded
    142  *	"/"		Alphanumerics and '/' remain unencoded
    143  *	"$-_.+!*'(),"	Consistent with a strict reading of RFC 1738
    144  *	"$-_.+!*'(),/"	As above, except '/' is not encoded
    145  *	"-_.+!,/"	As above, except shell special characters are encoded
    146  *
    147  * encode_leading_slash is a flag that determines whether or not to
    148  * encode a leading slash in a string.  If this flag is set, and if the
    149  * first character in the src string is '/', then the leading slash will
    150  * be encoded (as "%2F"), even if '/' is one of the characters in the
    151  * safe_chars string.  Note that only the first character of the src
    152  * string is affected by this flag, and that leading slashes are never
    153  * deleted, but either retained unchanged or encoded.
    154  *
    155  * Unsafe and reserved characters are defined in RFC 1738 section 2.2.
    156  * The most important parts are:
    157  *
    158  *      The characters ";", "/", "?", ":", "@", "=" and "&" are the
    159  *      characters which may be reserved for special meaning within a
    160  *      scheme. No other characters may be reserved within a scheme.
    161  *      [...]
    162  *
    163  *      Thus, only alphanumerics, the special characters "$-_.+!*'(),",
    164  *      and reserved characters used for their reserved purposes may be
    165  *      used unencoded within a URL.
    166  *
    167  */
    168 
    169 #define RFC1738_SAFE				"$-_.+!*'(),"
    170 #define RFC1738_SAFE_LESS_SHELL			"-_.+!,"
    171 #define RFC1738_SAFE_LESS_SHELL_PLUS_SLASH	"-_.+!,/"
    172 
    173 static char *
    174 url_encode(char *dst, const char *src, const char *ep,
    175 	const char *safe_chars, int encode_leading_slash)
    176 {
    177 	int ch;
    178 
    179 	ep--;
    180 
    181 	for (; dst < ep; src++) {
    182 		ch = *src & 0xff;
    183 		if (ch == 0)
    184 			break;
    185 		if (safe_chars != NULL &&
    186 		    (ch != '/' || !encode_leading_slash) &&
    187 		    (isalnum(ch) || strchr(safe_chars, ch))) {
    188 			*dst++ = ch;
    189 		} else {
    190 			/* encode this char */
    191 			if (ep - dst < 3)
    192 				break;
    193 			snprintf(dst, ep - dst, "%%%02X", ch);
    194 			dst += 3;
    195 		}
    196 		encode_leading_slash = 0;
    197 	}
    198 	*dst = '\0';
    199 	return dst;
    200 }
    201 
    202 static const char *ignored_if_names[] = {
    203 	"gre",			/* net */
    204 	"ipip",			/* netinet */
    205 	"gif",			/* netinet6 */
    206 	"faith",		/* netinet6 */
    207 	"lo",			/* net */
    208 	"lo0",			/* net */
    209 #if 0
    210 	"mdecap",		/* netinet -- never in IF list (?) XXX */
    211 #endif
    212 	"ppp",			/* net */
    213 #if 0
    214 	"sl",			/* net */
    215 #endif
    216 	"strip",		/* net */
    217 	"tun",			/* net */
    218 	/* XXX others? */
    219 	NULL,
    220 };
    221 
    222 static int
    223 get_ifconfig_info(struct net_desc *devs)
    224 {
    225 	char *buf_in;
    226 	char *buf_tmp;
    227 	const char **ignore;
    228 	char *buf;
    229 	char *tmp;
    230 	int textsize;
    231 	int i;
    232 
    233 	/* Get ifconfig information */
    234 	textsize = collect(T_OUTPUT, &buf_in, "/sbin/ifconfig -l 2>/dev/null");
    235 	if (textsize < 0) {
    236 		if (logfp)
    237 			(void)fprintf(logfp,
    238 			    "Aborting: Could not run ifconfig.\n");
    239 		(void)fprintf(stderr, "Could not run ifconfig.");
    240 		exit(1);
    241 	}
    242 
    243 	buf = malloc (STRSIZE * sizeof(char));
    244 	for (i = 0, buf_tmp = buf_in; strlen(buf_tmp) > 0 && buf_tmp < buf_in +
    245 	     strlen(buf_in);) {
    246 		tmp = stpncpy(buf, buf_tmp, strcspn(buf_tmp," \n"));
    247 		*tmp='\0';
    248 		buf_tmp += (strcspn(buf_tmp, " \n") + 1) * sizeof(char);
    249 
    250 		/* Skip ignored interfaces */
    251 		for (ignore = ignored_if_names; *ignore != NULL; ignore++) {
    252 			size_t len = strlen(*ignore);
    253 			if (strncmp(buf, *ignore, len) == 0 &&
    254 			    isdigit((unsigned char)buf[len]))
    255 				break;
    256 		}
    257 		if (*ignore != NULL)
    258 			continue;
    259 
    260 		strlcpy (devs[i].if_dev, buf, STRSIZE);
    261 		i++;
    262 	}
    263 	strcpy(devs[i].if_dev, "\0");
    264 
    265 	free(buf);
    266 	free(buf_in);
    267 	return i;
    268 }
    269 
    270 static int
    271 do_ifreq(struct ifreq *ifr, unsigned long cmd)
    272 {
    273 	int sock;
    274 	int rval;
    275 
    276 	sock = socket(PF_INET, SOCK_DGRAM, 0);
    277 	if (sock == -1)
    278 		return -1;
    279 
    280 	memset(ifr, 0, sizeof *ifr);
    281 	strncpy(ifr->ifr_name, net_dev, sizeof ifr->ifr_name);
    282 	rval = ioctl(sock, cmd, ifr);
    283 	close(sock);
    284 
    285 	return rval;
    286 }
    287 
    288 static int
    289 do_ifmreq(struct ifmediareq *ifmr, unsigned long cmd)
    290 {
    291 	int sock;
    292 	int rval;
    293 
    294 	sock = socket(PF_INET, SOCK_DGRAM, 0);
    295 	if (sock == -1)
    296 		return -1;
    297 
    298 	memset(ifmr, 0, sizeof *ifmr);
    299 	strncpy(ifmr->ifm_name, net_dev, sizeof ifmr->ifm_name);
    300 	rval = ioctl(sock, cmd, ifmr);
    301 	close(sock);
    302 
    303 	return rval;
    304 }
    305 
    306 /* Fill in defaults network values for the selected interface */
    307 static void
    308 get_ifinterface_info(void)
    309 {
    310 	struct ifreq ifr;
    311 	struct ifmediareq ifmr;
    312 	struct sockaddr_in *sa_in = (void*)&ifr.ifr_addr;
    313 	int modew;
    314 	const char *media_opt;
    315 	const char *sep;
    316 
    317 	if (do_ifreq(&ifr, SIOCGIFADDR) == 0 && sa_in->sin_addr.s_addr != 0)
    318 		strlcpy(net_ip, inet_ntoa(sa_in->sin_addr), sizeof net_ip);
    319 
    320 	if (do_ifreq(&ifr, SIOCGIFNETMASK) == 0 && sa_in->sin_addr.s_addr != 0)
    321 		strlcpy(net_mask, inet_ntoa(sa_in->sin_addr), sizeof net_mask);
    322 
    323 	if (do_ifmreq(&ifmr, SIOCGIFMEDIA) == 0) {
    324 		/* Get the name of the media word */
    325 		modew = ifmr.ifm_current;
    326 		strlcpy(net_media, get_media_subtype_string(modew),
    327 		    sizeof net_media);
    328 		/* and add any media options */
    329 		sep = " mediaopt ";
    330 		while ((media_opt = get_media_option_string(&modew)) != NULL) {
    331 			strlcat(net_media, sep, sizeof net_media);
    332 			strlcat(net_media, media_opt, sizeof net_media);
    333 			sep = ",";
    334 		}
    335 	}
    336 }
    337 
    338 #ifndef INET6
    339 #define get_if6interface_info()
    340 #else
    341 static void
    342 get_if6interface_info(void)
    343 {
    344 	char *textbuf, *t;
    345 	int textsize;
    346 
    347 	textsize = collect(T_OUTPUT, &textbuf,
    348 	    "/sbin/ifconfig %s inet6 2>/dev/null", net_dev);
    349 	if (textsize >= 0) {
    350 		char *p;
    351 
    352 		(void)strtok(textbuf, "\n"); /* ignore first line */
    353 		while ((t = strtok(NULL, "\n")) != NULL) {
    354 			if (strncmp(t, "\tinet6 ", 7) != 0)
    355 				continue;
    356 			t += 7;
    357 			if (strstr(t, "tentative") || strstr(t, "duplicated"))
    358 				continue;
    359 			if (strncmp(t, "fe80:", 5) == 0)
    360 				continue;
    361 
    362 			p = t;
    363 			while (*p && *p != ' ' && *p != '\n')
    364 				p++;
    365 			*p = '\0';
    366 			strlcpy(net_ip6, t, sizeof(net_ip6));
    367 			break;
    368 		}
    369 	}
    370 	free(textbuf);
    371 }
    372 #endif
    373 
    374 static void
    375 get_host_info(void)
    376 {
    377 	char hostname[MAXHOSTNAMELEN + 1];
    378 	char *dot;
    379 
    380 	/* Check host (and domain?) name */
    381 	if (gethostname(hostname, sizeof(hostname)) == 0 && hostname[0] != 0) {
    382 		hostname[sizeof(hostname) - 1] = 0;
    383 		/* check for a . */
    384 		dot = strchr(hostname, '.');
    385 		if (dot == NULL) {
    386 			/* if not found its just a host, punt on domain */
    387 			strlcpy(net_host, hostname, sizeof net_host);
    388 		} else {
    389 			/* split hostname into host/domain parts */
    390 			*dot++ = 0;
    391 			strlcpy(net_host, hostname, sizeof net_host);
    392 			strlcpy(net_domain, dot, sizeof net_domain);
    393 		}
    394 	}
    395 }
    396 
    397 /*
    398  * recombine name parts split in get_host_info and config_network
    399  * (common code moved here from write_etc_hosts)
    400  */
    401 static char *
    402 recombine_host_domain(void)
    403 {
    404 	static char recombined[MAXHOSTNAMELEN + 1];
    405 	int l = strlen(net_host) - strlen(net_domain);
    406 
    407 	strlcpy(recombined, net_host, sizeof(recombined));
    408 
    409 	if (strlen(net_domain) != 0 && (l <= 0 ||
    410 	    net_host[l - 1] != '.' ||
    411 	    strcasecmp(net_domain, net_host + l) != 0)) {
    412 		/* net_host isn't an FQDN. */
    413 		strlcat(recombined, ".", sizeof(recombined));
    414 		strlcat(recombined, net_domain, sizeof(recombined));
    415 	}
    416 	return recombined;
    417 }
    418 
    419 #ifdef INET6
    420 static int
    421 is_v6kernel(void)
    422 {
    423 	int s;
    424 
    425 	s = socket(PF_INET6, SOCK_DGRAM, 0);
    426 	if (s < 0)
    427 		return 0;
    428 	close(s);
    429 	return 1;
    430 }
    431 #endif
    432 
    433 static int
    434 handle_license(const char *dev)
    435 {
    436 	static struct {
    437 		const char *dev;
    438 		const char *lic;
    439 	} licdev[] = {
    440 		{ "iwi", "/libdata/firmware/if_iwi/LICENSE.ipw2200-fw" },
    441 		{ "ipw", "/libdata/firmware/if_ipw/LICENSE" },
    442 	};
    443 
    444 	size_t i;
    445 
    446 	for (i = 0; i < __arraycount(licdev); i++)
    447 		if (strncmp(dev, licdev[i].dev, 3) == 0) {
    448 			char buf[64];
    449 			int val;
    450 			size_t len = sizeof(int);
    451 			(void)snprintf(buf, sizeof(buf), "hw.%s.accept_eula",
    452 			    licdev[i].dev);
    453 			if (sysctlbyname(buf, &val, &len, NULL, 0) != -1
    454 			    && val != 0)
    455 				return 1;
    456 			msg_display(MSG_license, dev, licdev[i].lic);
    457 			if (ask_yesno(NULL)) {
    458 				val = 1;
    459 				if (sysctlbyname(buf, NULL, NULL, &val,
    460 				    0) == -1)
    461 					return 0;
    462 				add_sysctl_conf("%s=1", buf);
    463 				return 1;
    464 			} else
    465 				return 0;
    466 		}
    467 	return 1;
    468 }
    469 
    470 /*
    471  * Get the information to configure the network, configure it and
    472  * make sure both the gateway and the name server are up.
    473  */
    474 int
    475 config_network(void)
    476 {
    477 	char *textbuf;
    478 	int  octet0;
    479 	int  dhcp_config;
    480 	int  nfs_root = 0;
    481  	int  slip = 0;
    482  	int  pid, status;
    483  	char **ap, *slcmd[10], *in_buf;
    484  	char buffer[STRSIZE];
    485  	struct statvfs sb;
    486 	struct net_desc net_devs[MAX_NETS];
    487 	menu_ent net_menu[5];
    488 	int menu_no;
    489 	int num_devs;
    490 	int selected_net;
    491 	int i;
    492 #ifdef INET6
    493 	int v6config = 1, rv;
    494 #endif
    495 
    496 	FILE *f;
    497 	time_t now;
    498 
    499 	if (network_up)
    500 		return (1);
    501 
    502 	num_devs = get_ifconfig_info(net_devs);
    503 
    504 	if (num_devs < 1) {
    505 		/* No network interfaces found! */
    506 		msg_display(MSG_nonet);
    507 		process_menu(MENU_ok, NULL);
    508 		return (-1);
    509 	}
    510 
    511 	for (i = 0; i < num_devs; i++) {
    512 		net_menu[i].opt_name = net_devs[i].if_dev;
    513 		net_menu[i].opt_menu = OPT_NOMENU;
    514 		net_menu[i].opt_flags = OPT_EXIT;
    515 		net_menu[i].opt_action = set_menu_select;
    516 	}
    517 again:
    518 	selected_net = -1;
    519 	menu_no = new_menu(MSG_netdevs,
    520 		net_menu, num_devs, -1, 4, 0, 0,
    521 		MC_SCROLL,
    522 		NULL, NULL, NULL, NULL, NULL);
    523 	msg_display(MSG_asknetdev, "");
    524 	process_menu(menu_no, &selected_net);
    525 	free_menu(menu_no);
    526 
    527 	if (selected_net == -1)
    528 	    return 0;
    529 
    530 	network_up = 1;
    531 	dhcp_config = 0;
    532 
    533 	strncpy(net_dev, net_devs[selected_net].if_dev, STRSIZE);
    534 
    535 	if (!handle_license(net_dev))
    536 		goto done;
    537 
    538 	slip = net_dev[0] == 's' && net_dev[1] == 'l' &&
    539 	    isdigit((unsigned char)net_dev[2]);
    540 
    541 	/* If root is on NFS do not reconfigure the interface. */
    542 	if (statvfs("/", &sb) == 0 && strcmp(sb.f_fstypename, "nfs") == 0) {
    543 		nfs_root = 1;
    544 		get_ifinterface_info();
    545 		get_if6interface_info();
    546 		get_host_info();
    547 	} else if (!slip) {
    548 		/* Preload any defaults we can find */
    549 		get_ifinterface_info();
    550 		get_if6interface_info();
    551 		get_host_info();
    552 
    553 		/* domain and host */
    554 		msg_display(MSG_netinfo);
    555 
    556 		/* ethernet medium */
    557 		for (;;) {
    558 			msg_prompt_add(MSG_net_media, net_media, net_media,
    559 					sizeof net_media);
    560 
    561 			/*
    562 			 * ifconfig does not allow media specifiers on
    563 			 * IFM_MANUAL interfaces.  Our UI gives no way
    564 			 * to set an option back
    565 			 * to null-string if it gets accidentally set.
    566 			 * Check for plausible alternatives.
    567 			 */
    568 			if (strcmp(net_media, "<default>") == 0 ||
    569 			    strcmp(net_media, "default") == 0 ||
    570 			    strcmp(net_media, "<manual>") == 0 ||
    571 			    strcmp(net_media, "manual") == 0 ||
    572 			    strcmp(net_media, "<none>") == 0 ||
    573 			    strcmp(net_media, "none") == 0 ||
    574 			    strcmp(net_media, " ") == 0) {
    575 				*net_media = '\0';
    576 			}
    577 
    578 			if (*net_media == '\0')
    579 				break;
    580 			/*
    581 			 * We must set the media type here - to give dhcp
    582 			 * a chance
    583 			 */
    584 			if (run_program(0, "/sbin/ifconfig %s media %s",
    585 				    net_dev, net_media) == 0)
    586 				break;
    587 			/* Failed to set - output the supported values */
    588 			if (collect(T_OUTPUT, &textbuf, "/sbin/ifconfig -m %s |"
    589 				    "while IFS=; read line;"
    590 				    " do [ \"$line\" = \"${line#*media}\" ] || "
    591 				    "echo $line;"
    592 				    " done", net_dev ) > 0)
    593 				msg_display(textbuf);
    594 			free(textbuf);
    595 		}
    596 
    597 		net_dhcpconf = 0;
    598 		/* try a dhcp configuration */
    599 		dhcp_config = config_dhcp(net_dev);
    600 		if (dhcp_config) {
    601 			char *nline;
    602 
    603 			/* Get newly configured data off interface. */
    604 			get_ifinterface_info();
    605 			get_if6interface_info();
    606 			get_host_info();
    607 
    608 			net_dhcpconf |= DHCPCONF_IPADDR;
    609 
    610 			/*
    611 			 * Extract default route from output of
    612 			 * 'route -n show'
    613 			 */
    614 			if (collect(T_OUTPUT, &textbuf,
    615 			    "/sbin/route -n show | "
    616 			    "while read dest gateway flags;"
    617 			    " do [ \"$dest\" = default ] && {"
    618 			    " echo \"$gateway\"; break; };"
    619 			    " done" ) > 0)
    620 				strlcpy(net_defroute, textbuf,
    621 				    sizeof net_defroute);
    622 			free(textbuf);
    623 			if ((nline = strchr(net_defroute, '\n')))
    624 				*nline = '\0';
    625 
    626 			/* pull nameserver info out of /etc/resolv.conf */
    627 			if (collect(T_OUTPUT, &textbuf,
    628 			    "cat /etc/resolv.conf 2>/dev/null |"
    629 			    " while read keyword address rest;"
    630 			    " do [ \"$keyword\" = nameserver ] &&"
    631 			    " { echo \"$address\"; break; };"
    632 			    " done" ) > 0)
    633 				strlcpy(net_namesvr, textbuf,
    634 				    sizeof net_namesvr);
    635 			free(textbuf);
    636 			if ((nline = strchr(net_namesvr, '\n')))
    637 				*nline = '\0';
    638 			if (net_namesvr[0] != '\0')
    639 				net_dhcpconf |= DHCPCONF_NAMESVR;
    640 
    641 			/* pull domain info out of /etc/resolv.conf */
    642 			if (collect(T_OUTPUT, &textbuf,
    643 			    "cat /etc/resolv.conf 2>/dev/null |"
    644 			    " while read keyword domain rest;"
    645 			    " do [ \"$keyword\" = domain ] &&"
    646 			    " { echo \"$domain\"; break; };"
    647 			    " done" ) > 0)
    648 				strlcpy(net_domain, textbuf,
    649 				    sizeof net_domain);
    650 			free(textbuf);
    651 			if (net_domain[0] == '\0') {
    652 				/* pull domain info out of /etc/resolv.conf */
    653 				if (collect(T_OUTPUT, &textbuf,
    654 				    "cat /etc/resolv.conf 2>/dev/null |"
    655 				    " while read keyword search rest;"
    656 				    " do [ \"$keyword\" = search ] &&"
    657 				    " { echo \"$search\"; break; };"
    658 				    " done" ) > 0)
    659 					strlcpy(net_domain, textbuf,
    660 					    sizeof net_domain);
    661 				free(textbuf);
    662 			}
    663 			if ((nline = strchr(net_domain, '\n')))
    664 				*nline = '\0';
    665 			if (net_domain[0] != '\0')
    666 				net_dhcpconf |= DHCPCONF_DOMAIN;
    667 
    668 			if (gethostname(net_host, sizeof(net_host)) == 0 &&
    669 			    net_host[0] != 0)
    670 				net_dhcpconf |= DHCPCONF_HOST;
    671 		}
    672 	}
    673 
    674 	if (!(net_dhcpconf & DHCPCONF_HOST))
    675 		msg_prompt_add(MSG_net_host, net_host, net_host,
    676 		    sizeof net_host);
    677 
    678 	if (!(net_dhcpconf & DHCPCONF_DOMAIN))
    679 		msg_prompt_add(MSG_net_domain, net_domain, net_domain,
    680 		    sizeof net_domain);
    681 
    682 	if (!dhcp_config) {
    683 		/* Manually configure IPv4 */
    684 		if (!nfs_root)
    685 			msg_prompt_add(MSG_net_ip, net_ip, net_ip,
    686 			    sizeof net_ip);
    687 		if (slip)
    688 			msg_prompt_add(MSG_net_srv_ip, net_srv_ip, net_srv_ip,
    689 			    sizeof net_srv_ip);
    690 		else if (!nfs_root) {
    691 			/* We don't want netmasks for SLIP */
    692 			octet0 = atoi(net_ip);
    693 			if (!net_mask[0]) {
    694 				if (0 <= octet0 && octet0 <= 127)
    695 					strlcpy(net_mask, "0xff000000",
    696 				    	sizeof(net_mask));
    697 				else if (128 <= octet0 && octet0 <= 191)
    698 					strlcpy(net_mask, "0xffff0000",
    699 				    	sizeof(net_mask));
    700 				else if (192 <= octet0 && octet0 <= 223)
    701 					strlcpy(net_mask, "0xffffff00",
    702 				    	sizeof(net_mask));
    703 			}
    704 			msg_prompt_add(MSG_net_mask, net_mask, net_mask,
    705 			    sizeof net_mask);
    706 		}
    707 		msg_prompt_add(MSG_net_defroute, net_defroute, net_defroute,
    708 		    sizeof net_defroute);
    709 	}
    710 
    711 	if (!(net_dhcpconf & DHCPCONF_NAMESVR)) {
    712 #ifdef INET6
    713 		if (v6config) {
    714 			rv = 0;
    715 			process_menu(MENU_namesrv6, &rv);
    716 			if (!rv)
    717 				msg_prompt_add(MSG_net_namesrv, net_namesvr,
    718 				    net_namesvr, sizeof net_namesvr);
    719 		} else
    720 #endif
    721 		msg_prompt_add(MSG_net_namesrv, net_namesvr, net_namesvr,
    722 		    sizeof net_namesvr);
    723 	}
    724 
    725 	/* confirm the setting */
    726 	if (slip)
    727 		msg_display(MSG_netok_slip, net_domain, net_host,
    728 		    *net_namesvr == '\0' ? "<none>" : net_namesvr,
    729 		    net_dev,
    730 		    *net_media == '\0' ? "<default>" : net_media,
    731 		    *net_ip == '\0' ? "<none>" : net_ip,
    732 		    *net_srv_ip == '\0' ? "<none>" : net_srv_ip,
    733 		    *net_mask == '\0' ? "<none>" : net_mask,
    734 		    *net_defroute == '\0' ? "<none>" : net_defroute);
    735 	else
    736 		msg_display(MSG_netok, net_domain, net_host,
    737 		    *net_namesvr == '\0' ? "<none>" : net_namesvr,
    738 		    net_dev,
    739 		    *net_media == '\0' ? "<default>" : net_media,
    740 		    *net_ip == '\0' ? "<none>" : net_ip,
    741 		    *net_mask == '\0' ? "<none>" : net_mask,
    742 		    *net_defroute == '\0' ? "<none>" : net_defroute);
    743 #ifdef INET6
    744 	msg_display_add(MSG_netokv6,
    745 		     !is_v6kernel() ? "<not supported>" : net_ip6);
    746 #endif
    747 done:
    748 	if (!ask_yesno(MSG_netok_ok))
    749 		goto again;
    750 
    751 	run_program(0, "/sbin/ifconfig lo0 127.0.0.1");
    752 
    753 	/* dhcpcd will have configured it all for us */
    754 	if (dhcp_config) {
    755 		fflush(NULL);
    756 		network_up = 1;
    757 		return network_up;
    758 	}
    759 
    760 	/*
    761 	 * we may want to perform checks against inconsistent configuration,
    762 	 * like IPv4 DNS server without IPv4 configuration.
    763 	 */
    764 
    765 	/* Create /etc/resolv.conf if a nameserver was given */
    766 	if (net_namesvr[0] != '\0') {
    767 		f = fopen("/etc/resolv.conf", "w");
    768 		if (f == NULL) {
    769 			if (logfp)
    770 				(void)fprintf(logfp,
    771 				    "%s", msg_string(MSG_resolv));
    772 			(void)fprintf(stderr, "%s", msg_string(MSG_resolv));
    773 			exit(1);
    774 		}
    775 		scripting_fprintf(NULL, "cat <<EOF >/etc/resolv.conf\n");
    776 		time(&now);
    777 		scripting_fprintf(f, ";\n; BIND data file\n; %s %s;\n",
    778 		    "Created by NetBSD sysinst on", safectime(&now));
    779 		if (net_domain[0] != '\0')
    780 			scripting_fprintf(f, "search %s\n", net_domain);
    781 		if (net_namesvr[0] != '\0')
    782 			scripting_fprintf(f, "nameserver %s\n", net_namesvr);
    783 		scripting_fprintf(NULL, "EOF\n");
    784 		fflush(NULL);
    785 		fclose(f);
    786 	}
    787 
    788 	if (net_ip[0] != '\0') {
    789 		if (slip) {
    790 			/* XXX: needs 'ifconfig sl0 create' much earlier */
    791 			/* Set SLIP interface UP */
    792 			run_program(0, "/sbin/ifconfig %s inet %s %s up",
    793 			    net_dev, net_ip, net_srv_ip);
    794 			strcpy(sl_flags, "-s 115200 -l /dev/tty00");
    795 			msg_prompt_win(MSG_slattach, -1, 12, 70, 0,
    796 				sl_flags, sl_flags, 255);
    797 
    798 			/* XXX: wtf isn't run_program() used here? */
    799 			pid = fork();
    800 			if (pid == 0) {
    801 				strcpy(buffer, "/sbin/slattach ");
    802 				strcat(buffer, sl_flags);
    803 				in_buf = buffer;
    804 
    805 				for (ap = slcmd; (*ap = strsep(&in_buf, " ")) != NULL;)
    806 				if (**ap != '\0')
    807 					++ap;
    808 
    809 				execvp(slcmd[0], slcmd);
    810 			} else
    811 				wait4(pid, &status, WNOHANG, 0);
    812 		} else if (!nfs_root) {
    813 			if (net_mask[0] != '\0') {
    814 				run_program(0, "/sbin/ifconfig %s inet %s netmask %s",
    815 				    net_dev, net_ip, net_mask);
    816 			} else {
    817 				run_program(0, "/sbin/ifconfig %s inet %s",
    818 			    	net_dev, net_ip);
    819 			}
    820 		}
    821 	}
    822 
    823 	/* Set host name */
    824 	if (net_host[0] != '\0')
    825 	  	sethostname(net_host, strlen(net_host));
    826 
    827 	/* Set a default route if one was given */
    828 	if (!nfs_root && net_defroute[0] != '\0') {
    829 		run_program(RUN_DISPLAY | RUN_PROGRESS,
    830 				"/sbin/route -n flush -inet");
    831 		run_program(RUN_DISPLAY | RUN_PROGRESS,
    832 				"/sbin/route -n add default %s", net_defroute);
    833 	}
    834 
    835 	/*
    836 	 * wait a couple of seconds for the interface to go live.
    837 	 */
    838 	if (!nfs_root) {
    839 		msg_display_add(MSG_wait_network);
    840 		sleep(5);
    841 	}
    842 
    843 	/*
    844 	 * ping should be verbose, so users can see the cause
    845 	 * of a network failure.
    846 	 */
    847 	if (net_defroute[0] != '\0' && network_up)
    848 		network_up = !run_program(RUN_DISPLAY | RUN_PROGRESS,
    849 		    "/sbin/ping -v -c 5 -w 5 -o -n %s", net_defroute);
    850 	if (net_namesvr[0] != '\0' && network_up) {
    851 #ifdef INET6
    852 		if (strchr(net_namesvr, ':'))
    853 			network_up = !run_program(RUN_DISPLAY | RUN_PROGRESS,
    854 			    "/sbin/ping6 -v -c 3 -n %s", net_namesvr);
    855 		else
    856 #endif
    857 			network_up = !run_program(RUN_DISPLAY | RUN_PROGRESS,
    858 			    "/sbin/ping -v -c 5 -w 5 -o -n %s", net_namesvr);
    859 	}
    860 	fflush(NULL);
    861 
    862 	return network_up;
    863 }
    864 
    865 void
    866 make_url(char *urlbuffer, struct ftpinfo *f, const char *dir)
    867 {
    868 	char ftp_user_encoded[STRSIZE];
    869 	char ftp_dir_encoded[STRSIZE];
    870 	char *cp;
    871 	const char *dir2;
    872 
    873 	/*
    874 	 * f->pass is quite likely to contain unsafe characters
    875 	 * that need to be encoded in the URL (for example,
    876 	 * "@", ":" and "/" need quoting).  Let's be
    877 	 * paranoid and also encode f->user and f->dir.  (For
    878 	 * example, f->dir could easily contain '~', which is
    879 	 * unsafe by a strict reading of RFC 1738).
    880 	 */
    881 	if (strcmp("ftp", f->user) == 0 && f->pass[0] == 0) {
    882 		ftp_user_encoded[0] = 0;
    883 	} else {
    884 		cp = url_encode(ftp_user_encoded, f->user,
    885 			ftp_user_encoded + sizeof ftp_user_encoded - 1,
    886 			RFC1738_SAFE_LESS_SHELL, 0);
    887 		*cp++ = ':';
    888 		cp = url_encode(cp, f->pass,
    889 			ftp_user_encoded + sizeof ftp_user_encoded - 1,
    890 			NULL, 0);
    891 		*cp++ = '@';
    892 		*cp = 0;
    893 	}
    894 	cp = url_encode(ftp_dir_encoded, f->dir,
    895 			ftp_dir_encoded + sizeof ftp_dir_encoded - 1,
    896 			RFC1738_SAFE_LESS_SHELL_PLUS_SLASH, 1);
    897 	if (cp != ftp_dir_encoded && cp[-1] != '/')
    898 		*cp++ = '/';
    899 
    900 	dir2 = dir;
    901 	while (*dir2 == '/')
    902 		++dir2;
    903 
    904 	url_encode(cp, dir2,
    905 			ftp_dir_encoded + sizeof ftp_dir_encoded,
    906 			RFC1738_SAFE_LESS_SHELL_PLUS_SLASH, 0);
    907 
    908 	snprintf(urlbuffer, STRSIZE, "%s://%s%s/%s", f->xfer_type,
    909 	    ftp_user_encoded, f->host, ftp_dir_encoded);
    910 }
    911 
    912 
    913 /* ftp_fetch() and pkgsrc_fetch() are essentially the same, with a different
    914  * ftpinfo var. */
    915 static int do_ftp_fetch(const char *, struct ftpinfo *);
    916 
    917 static int
    918 ftp_fetch(const char *set_name)
    919 {
    920 	return do_ftp_fetch(set_name, &ftp);
    921 }
    922 
    923 static int
    924 pkgsrc_fetch(const char *set_name)
    925 {
    926 	return do_ftp_fetch(set_name, &pkgsrc);
    927 }
    928 
    929 static int
    930 do_ftp_fetch(const char *set_name, struct ftpinfo *f)
    931 {
    932 	const char *ftp_opt;
    933 	char url[STRSIZE];
    934 	int rval;
    935 
    936 	/*
    937 	 * Invoke ftp to fetch the file.
    938 	 */
    939 	if (strcmp("ftp", f->user) == 0 && f->pass[0] == 0) {
    940 		/* do anon ftp */
    941 		ftp_opt = "-a ";
    942 	} else {
    943 		ftp_opt = "";
    944 	}
    945 
    946 	make_url(url, f, set_dir_for_set(set_name));
    947 	rval = run_program(RUN_DISPLAY | RUN_PROGRESS | RUN_XFER_DIR,
    948 		    "/usr/bin/ftp %s%s/%s%s",
    949 		    ftp_opt, url, set_name, dist_postfix);
    950 
    951 	return rval ? SET_RETRY : SET_OK;
    952 }
    953 
    954 
    955 // XXX: check MSG_netnotup_continueanyway and MSG_netnotup
    956 
    957 int
    958 get_pkgsrc(void)
    959 {
    960 	int rv = -1;
    961 
    962 	process_menu(MENU_pkgsrc, &rv);
    963 
    964 	if (rv == SET_SKIP)
    965 		return SET_SKIP;
    966 
    967 	fetch_fn = pkgsrc_fetch;
    968 	snprintf(ext_dir_pkgsrc, sizeof ext_dir_pkgsrc, "%s/%s",
    969 	    target_prefix(), xfer_dir + (*xfer_dir == '/'));
    970 
    971 	return SET_OK;
    972 }
    973 
    974 int
    975 get_via_ftp(const char *xfer_type)
    976 {
    977 	arg_rv arg;
    978 
    979 	arg.rv = -1;
    980 	arg.arg = deconst(xfer_type);
    981 	process_menu(MENU_ftpsource, &arg);
    982 
    983 	if (arg.rv == SET_RETRY)
    984 		return SET_RETRY;
    985 
    986 	/* We'll fetch each file just before installing it */
    987 	fetch_fn = ftp_fetch;
    988 	ftp.xfer_type = xfer_type;
    989 	snprintf(ext_dir_bin, sizeof ext_dir_bin, "%s/%s", target_prefix(),
    990 	    xfer_dir + (*xfer_dir == '/'));
    991 	snprintf(ext_dir_src, sizeof ext_dir_src, "%s/%s", target_prefix(),
    992 	    xfer_dir + (*xfer_dir == '/'));
    993 
    994 	return SET_OK;
    995 }
    996 
    997 int
    998 get_via_nfs(void)
    999 {
   1000 	struct statvfs sb;
   1001 	int rv;
   1002 
   1003 	/* If root is on NFS and we have sets, skip this step. */
   1004 	if (statvfs(set_dir_bin, &sb) == 0 &&
   1005 	    strcmp(sb.f_fstypename, "nfs") == 0) {
   1006 	    	strlcpy(ext_dir_bin, set_dir_bin, sizeof ext_dir_bin);
   1007 	    	strlcpy(ext_dir_src, set_dir_src, sizeof ext_dir_src);
   1008 		return SET_OK;
   1009 	}
   1010 
   1011 	/* Get server and filepath */
   1012 	rv = -1;
   1013 	process_menu(MENU_nfssource, &rv);
   1014 
   1015 	if (rv == SET_RETRY)
   1016 		return SET_RETRY;
   1017 
   1018 	/* Mount it */
   1019 	if (run_program(0, "/sbin/mount -r -o -2,-i,-r=1024 -t nfs %s:%s /mnt2",
   1020 	    nfs_host, nfs_dir))
   1021 		return SET_RETRY;
   1022 
   1023 	mnt2_mounted = 1;
   1024 
   1025 	snprintf(ext_dir_bin, sizeof ext_dir_bin, "/mnt2/%s", set_dir_bin);
   1026 	snprintf(ext_dir_src, sizeof ext_dir_src, "/mnt2/%s", set_dir_src);
   1027 
   1028 	/* return location, don't clean... */
   1029 	return SET_OK;
   1030 }
   1031 
   1032 /*
   1033  * write the new contents of /etc/hosts to the specified file
   1034  */
   1035 static void
   1036 write_etc_hosts(FILE *f)
   1037 {
   1038 	scripting_fprintf(f, "#\n");
   1039 	scripting_fprintf(f, "# Added by NetBSD sysinst\n");
   1040 	scripting_fprintf(f, "#\n");
   1041 
   1042 	if (net_domain[0] != '\0')
   1043 		scripting_fprintf(f, "127.0.0.1	localhost.%s\n", net_domain);
   1044 
   1045 	scripting_fprintf(f, "%s\t", net_ip);
   1046 	if (net_domain[0] != '\0')
   1047 		scripting_fprintf(f, "%s ", recombine_host_domain());
   1048 	scripting_fprintf(f, "%s\n", net_host);
   1049 }
   1050 
   1051 /*
   1052  * Write the network config info the user entered via menus into the
   1053  * config files in the target disk.  Be careful not to lose any
   1054  * information we don't immediately add back, in case the install
   1055  * target is the currently-active root.
   1056  */
   1057 void
   1058 mnt_net_config(void)
   1059 {
   1060 	char ifconfig_fn[STRSIZE];
   1061 	FILE *ifconf = NULL;
   1062 
   1063 	if (!network_up)
   1064 		return;
   1065 	if (!ask_yesno(MSG_mntnetconfig))
   1066 		return;
   1067 
   1068 	/* Write hostname to /etc/rc.conf */
   1069 	if ((net_dhcpconf & DHCPCONF_HOST) == 0)
   1070 		if (del_rc_conf("hostname") == 0)
   1071 			add_rc_conf("hostname=%s\n", recombine_host_domain());
   1072 
   1073 	/* Copy resolv.conf to target.  If DHCP was used to create it,
   1074 	 * it will be replaced on next boot anyway. */
   1075 	if (net_namesvr[0] != '\0')
   1076 		dup_file_into_target("/etc/resolv.conf");
   1077 
   1078 	/*
   1079 	 * bring the interface up, it will be necessary for IPv6, and
   1080 	 * it won't make trouble with IPv4 case either
   1081 	 */
   1082 	snprintf(ifconfig_fn, sizeof ifconfig_fn, "/etc/ifconfig.%s", net_dev);
   1083 	ifconf = target_fopen(ifconfig_fn, "w");
   1084 	if (ifconf != NULL) {
   1085 		scripting_fprintf(NULL, "cat <<EOF >>%s%s\n",
   1086 		    target_prefix(), ifconfig_fn);
   1087 		scripting_fprintf(ifconf, "up\n");
   1088 		if (*net_media != '\0')
   1089 			scripting_fprintf(ifconf, "media %s\n", net_media);
   1090 		scripting_fprintf(NULL, "EOF\n");
   1091 	}
   1092 
   1093 	if ((net_dhcpconf & DHCPCONF_IPADDR) == 0) {
   1094 		FILE *hosts;
   1095 
   1096 		/* Write IPaddr and netmask to /etc/ifconfig.if[0-9] */
   1097 		if (ifconf != NULL) {
   1098 			scripting_fprintf(NULL, "cat <<EOF >>%s%s\n",
   1099 			    target_prefix(), ifconfig_fn);
   1100 			if (*net_media != '\0')
   1101 				scripting_fprintf(ifconf,
   1102 				    "%s netmask %s media %s\n",
   1103 				    net_ip, net_mask, net_media);
   1104 			else
   1105 				scripting_fprintf(ifconf, "%s netmask %s\n",
   1106 				    net_ip, net_mask);
   1107 			scripting_fprintf(NULL, "EOF\n");
   1108 		}
   1109 
   1110 		/*
   1111 		 * Add IPaddr/hostname to  /etc/hosts.
   1112 		 * Be careful not to clobber any existing contents.
   1113 		 * Relies on ordered search of /etc/hosts. XXX YP?
   1114 		 */
   1115 		hosts = target_fopen("/etc/hosts", "a");
   1116 		if (hosts != 0) {
   1117 			scripting_fprintf(NULL, "cat <<EOF >>%s/etc/hosts\n",
   1118 			    target_prefix());
   1119 			write_etc_hosts(hosts);
   1120 			(void)fclose(hosts);
   1121 			scripting_fprintf(NULL, "EOF\n");
   1122 		}
   1123 
   1124 		if (del_rc_conf("defaultroute") == 0)
   1125 			add_rc_conf("defaultroute=\"%s\"\n", net_defroute);
   1126 	} else {
   1127 		/*
   1128 		 * Start dhcpcd quietly and in master mode, but restrict
   1129 		 * it to our interface
   1130 		 */
   1131 		add_rc_conf("dhcpcd=YES\n");
   1132 		add_rc_conf("dhcpcd_flags=\"-qM %s\"\n", net_dev);
   1133         }
   1134 
   1135 	if (ifconf)
   1136 		fclose(ifconf);
   1137 
   1138 	fflush(NULL);
   1139 }
   1140 
   1141 int
   1142 config_dhcp(char *inter)
   1143 {
   1144 	int dhcpautoconf;
   1145 
   1146 	/*
   1147 	 * Don't bother checking for an existing instance of dhcpcd, just
   1148 	 * ask it to renew the lease.  It will fork and daemonize if there
   1149 	 * wasn't already an instance.
   1150 	 */
   1151 
   1152 	if (!file_mode_match(DHCPCD, S_IFREG))
   1153 		return 0;
   1154 	if (ask_yesno(MSG_Perform_autoconfiguration)) {
   1155 		/* spawn off dhcpcd and wait for parent to exit */
   1156 		dhcpautoconf = run_program(RUN_DISPLAY | RUN_PROGRESS,
   1157 		    "%s -d -n %s", DHCPCD, inter);
   1158 		return dhcpautoconf ? 0 : 1;
   1159 	}
   1160 	return 0;
   1161 }
   1162