tcpip.c revision 69576
1/*
2 * $FreeBSD: head/usr.sbin/sysinstall/tcpip.c 69576 2000-12-04 18:06:49Z ume $
3 *
4 * Copyright (c) 1995
5 *      Gary J Palmer. All rights reserved.
6 * Copyright (c) 1996
7 *      Jordan K. Hubbard. All rights reserved.
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 *    verbatim and that no modifications are made prior to this
15 *    point in the file.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
26 * OF USE, DATA, LIFE OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
28 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 *
31 */
32
33/*
34 * All kinds of hacking also performed by jkh on this code.  Don't
35 * blame Gary for every bogosity you see here.. :-)
36 *
37 * -jkh
38 */
39
40#include "sysinstall.h"
41#include <sys/param.h>
42#include <sys/sysctl.h>
43#include <sys/socket.h>
44#include <netinet/in.h>
45#include <netdb.h>
46
47/* The help file for the TCP/IP setup screen */
48#define TCP_HELPFILE		"tcp"
49
50/* These are nasty, but they make the layout structure a lot easier ... */
51
52static char	hostname[HOSTNAME_FIELD_LEN], domainname[HOSTNAME_FIELD_LEN],
53		gateway[IPADDR_FIELD_LEN], nameserver[INET6_ADDRSTRLEN];
54static int	okbutton, cancelbutton;
55static char	ipaddr[IPADDR_FIELD_LEN], netmask[IPADDR_FIELD_LEN], extras[EXTRAS_FIELD_LEN];
56static char	ipv6addr[INET6_ADDRSTRLEN];
57
58/* What the screen size is meant to be */
59#define TCP_DIALOG_Y		0
60#define TCP_DIALOG_X		8
61#define TCP_DIALOG_WIDTH	COLS - 16
62#define TCP_DIALOG_HEIGHT	LINES - 2
63
64static Layout layout[] = {
65#define LAYOUT_HOSTNAME		0
66    { 1, 2, 25, HOSTNAME_FIELD_LEN - 1,
67      "Host:", "Your fully-qualified hostname, e.g. foo.bar.com",
68      hostname, STRINGOBJ, NULL },
69#define LAYOUT_DOMAINNAME	1
70    { 1, 35, 20, HOSTNAME_FIELD_LEN - 1,
71      "Domain:",
72      "The name of the domain that your machine is in, e.g. bar.com",
73      domainname, STRINGOBJ, NULL },
74#define LAYOUT_GATEWAY		2
75    { 5, 2, 18, IPADDR_FIELD_LEN - 1,
76      "IPv4 Gateway:",
77      "IPv4 address of host forwarding packets to non-local destinations",
78      gateway, STRINGOBJ, NULL },
79#define LAYOUT_NAMESERVER	3
80    { 5, 35, 18, INET6_ADDRSTRLEN - 1,
81      "Name server:", "IPv4 or IPv6 address of your local DNS server",
82      nameserver, STRINGOBJ, NULL },
83#define LAYOUT_IPADDR		4
84    { 10, 10, 18, IPADDR_FIELD_LEN - 1,
85      "IPv4 Address:",
86      "The IPv4 address to be used for this interface",
87      ipaddr, STRINGOBJ, NULL },
88#define LAYOUT_NETMASK		5
89    { 10, 35, 18, IPADDR_FIELD_LEN - 1,
90      "Netmask:",
91      "The netmask for this interface, e.g. 0xffffff00 for a class C network",
92      netmask, STRINGOBJ, NULL },
93#define LAYOUT_EXTRAS		6
94    { 14, 10, 37, HOSTNAME_FIELD_LEN - 1,
95      "Extra options to ifconfig:",
96      "Any interface-specific options to ifconfig you would like to add",
97      extras, STRINGOBJ, NULL },
98#define LAYOUT_OKBUTTON		7
99    { 19, 15, 0, 0,
100      "OK", "Select this if you are happy with these settings",
101      &okbutton, BUTTONOBJ, NULL },
102#define LAYOUT_CANCELBUTTON	8
103    { 19, 35, 0, 0,
104      "CANCEL", "Select this if you wish to cancel this screen",
105      &cancelbutton, BUTTONOBJ, NULL },
106    { NULL },
107};
108
109#define _validByte(b) ((b) >= 0 && (b) <= 255)
110
111/* whine */
112static void
113feepout(char *msg)
114{
115    beep();
116    msgConfirm(msg);
117}
118
119/* Very basic IP address integrity check - could be drastically improved */
120static int
121verifyIP(char *ip)
122{
123    int a, b, c, d;
124
125    if (ip && sscanf(ip, "%d.%d.%d.%d", &a, &b, &c, &d) == 4 &&
126	_validByte(a) && _validByte(b) && _validByte(c) &&
127	_validByte(d) && (d != 255))
128	return 1;
129    else
130	return 0;
131}
132
133static int
134verifyIP6(char *ip)
135{
136    struct addrinfo hints, *res;
137
138    memset(&hints, 0, sizeof(hints));
139    hints.ai_family = AF_INET6;
140    hints.ai_socktype = SOCK_STREAM;
141    hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
142    if (getaddrinfo(ip, NULL, &hints, &res) == 0) {
143	freeaddrinfo(res);
144	return 1;
145    }
146    return 0;
147}
148
149/* Check for the settings on the screen - the per-interface stuff is
150   moved to the main handling code now to do it on the fly - sigh */
151static int
152verifySettings(void)
153{
154    if (!hostname[0])
155	feepout("Must specify a host name of some sort!");
156    else if (gateway[0] && strcmp(gateway, "NO") && !verifyIP(gateway))
157	feepout("Invalid gateway IPv4 address specified");
158    else if (nameserver[0] && !verifyIP(nameserver) && !verifyIP6(nameserver))
159	feepout("Invalid name server IP address specified");
160    else if (netmask[0] && (netmask[0] < '0' && netmask[0] > '3'))
161	feepout("Invalid netmask value");
162    else if (ipaddr[0] && !verifyIP(ipaddr))
163	feepout("Invalid IPv4 address");
164    else
165	return 1;
166    return 0;
167}
168
169static void
170dhcpGetInfo(Device *devp)
171{
172    /* If it fails, do it the old-fashioned way */
173    if (dhcpParseLeases("/var/db/dhclient.leases", hostname, domainname,
174			 nameserver, ipaddr, gateway, netmask) == -1) {
175	FILE *ifp;
176	char *cp, cmd[256], data[2048];
177	int i, j;
178
179	/* Bah, now we have to kludge getting the information from ifconfig */
180	snprintf(cmd, sizeof cmd, "ifconfig %s", devp->name);
181	ifp = popen(cmd, "r");
182	if (ifp) {
183	    j = fread(data, 1, sizeof(data), ifp);
184	    fclose(ifp);
185	    if (j < 0)	/* paranoia */
186		j = 0;
187	    data[j] = '\0';
188	    if (isDebug())
189		msgDebug("DHCP configured interface returns %s\n", data);
190	    /* XXX This is gross as it assumes a certain ordering to
191	       ifconfig's output! XXX */
192	    if ((cp = strstr(data, "inet ")) != NULL) {
193		i = 0;
194		cp += 5;	/* move over keyword */
195		while (*cp != ' ')
196		    ipaddr[i++] = *(cp++);
197		ipaddr[i] = '\0';
198		if (!strncmp(++cp, "netmask", 7)) {
199		    i = 0;
200		    cp += 8;
201		    while (*cp != ' ')
202			netmask[i++] = *(cp++);
203		    netmask[i] = '\0';
204		}
205	    }
206	}
207    }
208
209    /* If we didn't get a name server value, hunt for it in resolv.conf */
210    if (!nameserver[0] && file_readable("/etc/resolv.conf"))
211	configEnvironmentResolv("/etc/resolv.conf");
212    if (hostname[0])
213	variable_set2(VAR_HOSTNAME, hostname, 0);
214}
215
216static void
217rtsolGetInfo(Device *devp)
218{
219    FILE *ifp;
220    char *cp, cmd[256], data[2048];
221    int i;
222
223    snprintf(cmd, sizeof cmd, "ifconfig %s", devp->name);
224    if ((ifp = popen(cmd, "r")) == NULL)
225	return;
226    while (fgets(data, sizeof(data), ifp) != NULL) {
227	if (isDebug())
228	    msgDebug("RTSOL configured interface returns %s", data);
229	if ((cp = strstr(data, "inet6 ")) != NULL) {
230	    cp += 6;	/* move over keyword */
231	    if (strncmp(cp, "fe80:", 5)) {
232		i = 0;
233		while (*cp != ' ')
234		    ipv6addr[i++] = *(cp++);
235		ipv6addr[i] = '\0';
236	    }
237	}
238    }
239    fclose(ifp);
240}
241
242/* This is it - how to get TCP setup values */
243int
244tcpOpenDialog(Device *devp)
245{
246    WINDOW              *ds_win, *save = NULL;
247    ComposeObj          *obj = NULL;
248    int                 n = 0, filled = 0, cancel = FALSE;
249    int			max, ret = DITEM_SUCCESS;
250    int			use_dhcp = FALSE;
251    int			use_rtsol = FALSE;
252    char                *tmp;
253    char		title[80];
254
255    save = savescr();
256    /* Initialise vars from previous device values */
257    if (devp->private) {
258	DevInfo *di = (DevInfo *)devp->private;
259
260	SAFE_STRCPY(ipaddr, di->ipaddr);
261	SAFE_STRCPY(netmask, di->netmask);
262	SAFE_STRCPY(extras, di->extras);
263	use_dhcp = di->use_dhcp;
264	use_rtsol = di->use_rtsol;
265    }
266    else { /* See if there are any defaults */
267	char *cp;
268
269	/* Try a RTSOL scan if such behavior is desired */
270	if (!variable_cmp(VAR_TRY_RTSOL, "YES") ||
271	    ((!variable_cmp(VAR_TRY_RTSOL, "NO")) && (!msgYesNo("Do you want to try IPv6 configuration of the interface?")))) {
272	    int i;
273	    int len;
274
275	    i = 0;
276	    sysctlbyname("net.inet6.ip6.forwarding", NULL, 0, &i, sizeof(i));
277	    i = 1;
278	    sysctlbyname("net.inet6.ip6.accept_rtadv", NULL, 0, &i, sizeof(i));
279	    vsystem("ifconfig %s up", devp->name);
280	    len = sizeof(i);
281	    sysctlbyname("net.inet6.ip6.dad_count", &i, &len, NULL, 0);
282	    sleep(i + 1);
283	    Mkdir("/var/run");
284	    msgNotify("Scanning for RA servers...");
285	    if (0 == vsystem("rtsol %s", devp->name)) {
286		len = sizeof(i);
287		sysctlbyname("net.inet6.ip6.dad_count", &i, &len, NULL, 0);
288		sleep(i + 1);
289		rtsolGetInfo(devp);
290		use_rtsol = TRUE;
291	    } else
292		use_rtsol = FALSE;
293	}
294
295	/* First try a DHCP scan if such behavior is desired */
296	if (!variable_cmp(VAR_TRY_DHCP, "YES") ||
297	    ((!variable_cmp(VAR_TRY_DHCP, "NO")) && (!msgYesNo("Do you want to try DHCP configuration of the interface?")))) {
298	    Mkdir("/var/db");
299	    Mkdir("/var/run");
300	    Mkdir("/tmp");
301	    msgNotify("Scanning for DHCP servers...");
302	    if (0 == vsystem("dhclient -1 %s", devp->name)) {
303		dhcpGetInfo(devp);
304		use_dhcp = TRUE;
305	    }
306	    else
307		use_dhcp = FALSE;
308	}
309
310	/* Special hack so it doesn't show up oddly in the tcpip setup menu */
311	if (!strcmp(gateway, "NO"))
312	    gateway[0] = '\0';
313
314	/* Get old IP address from variable space, if available */
315	if (!ipaddr[0]) {
316	    if ((cp = variable_get(VAR_IPADDR)) != NULL)
317		SAFE_STRCPY(ipaddr, cp);
318	    else if ((cp = variable_get(string_concat3(devp->name, "_", VAR_IPADDR))) != NULL)
319		SAFE_STRCPY(ipaddr, cp);
320	}
321
322	/* Get old netmask from variable space, if available */
323	if (!netmask[0]) {
324	    if ((cp = variable_get(VAR_NETMASK)) != NULL)
325		SAFE_STRCPY(netmask, cp);
326	    else if ((cp = variable_get(string_concat3(devp->name, "_", VAR_NETMASK))) != NULL)
327		SAFE_STRCPY(netmask, cp);
328	}
329
330	/* Get old extras string from variable space, if available */
331	if (!extras[0]) {
332	    if ((cp = variable_get(VAR_EXTRAS)) != NULL)
333		SAFE_STRCPY(extras, cp);
334	    else if ((cp = variable_get(string_concat3(devp->name, "_", VAR_EXTRAS))) != NULL)
335		SAFE_STRCPY(extras, cp);
336	}
337    }
338
339    /* Look up values already recorded with the system, or blank the string variables ready to accept some new data */
340    if (!hostname[0]) {
341	tmp = variable_get(VAR_HOSTNAME);
342	if (tmp)
343	    SAFE_STRCPY(hostname, tmp);
344    }
345    if (!domainname[0]) {
346	tmp = variable_get(VAR_DOMAINNAME);
347	if (tmp)
348	    SAFE_STRCPY(domainname, tmp);
349    }
350    if (!gateway[0]) {
351	tmp = variable_get(VAR_GATEWAY);
352	if (tmp && strcmp(tmp, "NO"))
353	    SAFE_STRCPY(gateway, tmp);
354    }
355    if (!nameserver[0]) {
356	tmp = variable_get(VAR_NAMESERVER);
357	if (tmp)
358	    SAFE_STRCPY(nameserver, tmp);
359    }
360
361    /* If non-interactive, jump straight over the dialog crap and into config section */
362    if (variable_get(VAR_NONINTERACTIVE) &&
363	!variable_get(VAR_NETINTERACTIVE)) {
364	if (!hostname[0])
365	    msgConfirm("WARNING: hostname variable not set and is a non-optional\n"
366		       "parameter.  Please add this to your installation script\n"
367		       "or set the netInteractive variable (see sysinstall man page)");
368	else
369	    goto netconfig;
370    }
371
372    /* Now do all the screen I/O */
373    dialog_clear_norefresh();
374
375    /* We need a curses window */
376    tmp = " Network Configuration ";
377    if (ipv6addr[0])
378	tmp = string_concat(tmp, "(IPv6 ready) ");
379    if (!(ds_win = openLayoutDialog(TCP_HELPFILE, tmp,
380				    TCP_DIALOG_X, TCP_DIALOG_Y, TCP_DIALOG_WIDTH, TCP_DIALOG_HEIGHT))) {
381	beep();
382	msgConfirm("Cannot open TCP/IP dialog window!!");
383	restorescr(save);
384	return DITEM_FAILURE;
385    }
386
387    /* Draw interface configuration box */
388    draw_box(ds_win, TCP_DIALOG_Y + 9, TCP_DIALOG_X + 8, TCP_DIALOG_HEIGHT - 13, TCP_DIALOG_WIDTH - 17,
389	     dialog_attr, border_attr);
390    wattrset(ds_win, dialog_attr);
391    sprintf(title, " Configuration for Interface %s ", devp->name);
392    mvwaddstr(ds_win, TCP_DIALOG_Y + 9, TCP_DIALOG_X + 14, title);
393
394    /* Some more initialisation before we go into the main input loop */
395    obj = initLayoutDialog(ds_win, layout, TCP_DIALOG_X, TCP_DIALOG_Y, &max);
396
397reenter:
398    cancelbutton = okbutton = 0;
399    while (layoutDialogLoop(ds_win, layout, &obj, &n, max, &cancelbutton, &cancel)) {
400	/* Prevent this from being irritating if user really means NO */
401	if (filled < 3) {
402	    /* Insert a default value for the netmask, 0xffffff00 is
403	     * the most appropriate one (entire class C, or subnetted
404	     * class A/B network).
405	     */
406	    if (!netmask[0]) {
407		strcpy(netmask, "255.255.255.0");
408		RefreshStringObj(layout[LAYOUT_NETMASK].obj);
409		++filled;
410	    }
411	    if (!index(hostname, '.') && domainname[0]) {
412		strcat(hostname, ".");
413		strcat(hostname, domainname);
414		RefreshStringObj(layout[LAYOUT_HOSTNAME].obj);
415		++filled;
416	    }
417	    else if (((tmp = index(hostname, '.')) != NULL) && !domainname[0]) {
418		SAFE_STRCPY(domainname, tmp + 1);
419		RefreshStringObj(layout[LAYOUT_DOMAINNAME].obj);
420		++filled;
421	    }
422	}
423    }
424    if (!cancel && !verifySettings())
425	goto reenter;
426
427    /* Clear this crap off the screen */
428    delwin(ds_win);
429    dialog_clear_norefresh();
430    use_helpfile(NULL);
431
432    /* We actually need to inform the rest of sysinstall about this
433       data now if the user hasn't selected cancel.  Save the stuff
434       out to the environment via the variable_set() mechanism */
435
436netconfig:
437    if (!cancel) {
438	DevInfo *di;
439	char temp[512], ifn[255];
440	char *ifaces;
441	char *pccard;
442	int ipv4_enable = FALSE;
443
444	if (hostname[0]) {
445	    variable_set2(VAR_HOSTNAME, hostname, 1);
446	    sethostname(hostname, strlen(hostname));
447	}
448	if (domainname[0])
449	    variable_set2(VAR_DOMAINNAME, domainname, 0);
450	if (gateway[0])
451	    variable_set2(VAR_GATEWAY, gateway, use_dhcp ? 0 : 1);
452	if (nameserver[0])
453	    variable_set2(VAR_NAMESERVER, nameserver, 0);
454	if (ipaddr[0])
455	    variable_set2(VAR_IPADDR, ipaddr, 0);
456	if (ipv6addr[0])
457	    variable_set2(VAR_IPV6ADDR, ipv6addr, 0);
458
459	if (!devp->private)
460	    devp->private = (DevInfo *)safe_malloc(sizeof(DevInfo));
461	di = devp->private;
462	SAFE_STRCPY(di->ipaddr, ipaddr);
463	SAFE_STRCPY(di->netmask, netmask);
464	SAFE_STRCPY(di->extras, extras);
465	di->use_dhcp = use_dhcp;
466	di->use_rtsol = use_rtsol;
467
468	if (use_dhcp || ipaddr[0])
469	    ipv4_enable = TRUE;
470	if (ipv4_enable) {
471	    sprintf(ifn, "%s%s", VAR_IFCONFIG, devp->name);
472	    if (use_dhcp)
473		sprintf(temp, "DHCP");
474	    else
475		sprintf(temp, "inet %s %s netmask %s",
476			ipaddr, extras, netmask);
477	    variable_set2(ifn, temp, 1);
478	}
479	pccard = variable_get("_pccard_install");
480	if (pccard && strcmp(pccard, "YES") == 0 && ipv4_enable) {
481	    variable_set2("pccard_ifconfig", temp, 1);
482	}
483	ifaces = variable_get(VAR_INTERFACES);
484	if (!ifaces)
485	    variable_set2(VAR_INTERFACES, ifaces = "lo0", 1);
486	/* Only add it if it's not there already */
487 	if (strcmp(ifaces, "auto") && !strstr(ifaces, devp->name)) {
488	    sprintf(ifn, "%s %s", devp->name, ifaces);
489	    variable_set2(VAR_INTERFACES, ifn, 1);
490	}
491	if (use_rtsol)
492	    variable_set2(VAR_IPV6_ENABLE, "YES", 1);
493	if (!use_dhcp)
494	    configResolv(NULL);	/* XXX this will do it on the MFS copy XXX */
495	ret = DITEM_SUCCESS;
496    }
497    else
498	ret = DITEM_FAILURE;
499    restorescr(save);
500    return ret;
501}
502
503static Device *NetDev;
504
505static int
506netHook(dialogMenuItem *self)
507{
508    Device **devs;
509
510    devs = deviceFindDescr(self->prompt, self->title, DEVICE_TYPE_NETWORK);
511    if (devs) {
512	if (DITEM_STATUS(tcpOpenDialog(devs[0])) != DITEM_FAILURE)
513	    NetDev = devs[0];
514	else
515	    NetDev = NULL;
516    }
517    return devs ? DITEM_LEAVE_MENU : DITEM_FAILURE;
518}
519
520/* Get a network device */
521Device *
522tcpDeviceSelect(void)
523{
524    DMenu *menu;
525    Device **devs, *rval;
526    int cnt;
527
528    devs = deviceFind(NULL, DEVICE_TYPE_NETWORK);
529    cnt = deviceCount(devs);
530    rval = NULL;
531
532    if (!cnt) {
533	msgConfirm("No network devices available!");
534	return NULL;
535    }
536    else if ((!RunningAsInit) && (variable_check("NETWORK_CONFIGURED=NO") != TRUE)) {
537	if (!msgYesNo("Running multi-user, assume that the network is already configured?"))
538	    return devs[0];
539    }
540    if (cnt == 1) {
541	if (DITEM_STATUS(tcpOpenDialog(devs[0]) == DITEM_SUCCESS))
542	    rval = devs[0];
543    }
544    else if (variable_get(VAR_NONINTERACTIVE) && variable_get(VAR_NETWORK_DEVICE)) {
545	devs = deviceFind(variable_get(VAR_NETWORK_DEVICE), DEVICE_TYPE_NETWORK);
546	cnt = deviceCount(devs);
547	if (cnt) {
548	    if (DITEM_STATUS(tcpOpenDialog(devs[0]) == DITEM_SUCCESS))
549		rval = devs[0];
550	}
551    }
552    else {
553	int status;
554
555	menu = deviceCreateMenu(&MenuNetworkDevice, DEVICE_TYPE_NETWORK, netHook, NULL);
556	if (!menu)
557	    msgFatal("Unable to create network device menu!  Argh!");
558	status = dmenuOpenSimple(menu, FALSE);
559	free(menu);
560	if (status)
561	    rval = NetDev;
562    }
563    return rval;
564}
565
566/* Do it from a menu that doesn't care about status */
567int
568tcpMenuSelect(dialogMenuItem *self)
569{
570    Device *tmp;
571    WINDOW *save;
572
573    variable_set("NETWORK_CONFIGURED=NO",0);
574    tmp = tcpDeviceSelect();
575    variable_unset("NETWORK_CONFIGURED");
576    save = savescr();
577    if (tmp && tmp->private && !((DevInfo *)tmp->private)->use_dhcp && !msgYesNo("Would you like to bring the %s interface up right now?", tmp->name))
578	if (!tmp->init(tmp))
579	    msgConfirm("Initialization of %s device failed.", tmp->name);
580    restorescr(save);
581    return DITEM_SUCCESS;
582}
583