tcpip.c revision 51735
1/*
2 * $FreeBSD: head/usr.sbin/sysinstall/tcpip.c 51735 1999-09-27 21:48:28Z jkh $
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 <netdb.h>
43
44/* The help file for the TCP/IP setup screen */
45#define TCP_HELPFILE		"tcp"
46
47/* These are nasty, but they make the layout structure a lot easier ... */
48
49static char	hostname[HOSTNAME_FIELD_LEN], domainname[HOSTNAME_FIELD_LEN],
50		gateway[IPADDR_FIELD_LEN], nameserver[IPADDR_FIELD_LEN];
51static int	okbutton, cancelbutton;
52static char	ipaddr[IPADDR_FIELD_LEN], netmask[IPADDR_FIELD_LEN], extras[EXTRAS_FIELD_LEN];
53
54/* What the screen size is meant to be */
55#define TCP_DIALOG_Y		0
56#define TCP_DIALOG_X		8
57#define TCP_DIALOG_WIDTH	COLS - 16
58#define TCP_DIALOG_HEIGHT	LINES - 2
59
60static Layout layout[] = {
61#define LAYOUT_HOSTNAME		0
62    { 1, 2, 25, HOSTNAME_FIELD_LEN - 1,
63      "Host:", "Your fully-qualified hostname, e.g. foo.bar.com",
64      hostname, STRINGOBJ, NULL },
65#define LAYOUT_DOMAINNAME	1
66    { 1, 35, 20, HOSTNAME_FIELD_LEN - 1,
67      "Domain:",
68      "The name of the domain that your machine is in, e.g. bar.com",
69      domainname, STRINGOBJ, NULL },
70#define LAYOUT_GATEWAY		2
71    { 5, 2, 18, IPADDR_FIELD_LEN - 1,
72      "Gateway:",
73      "IP address of host forwarding packets to non-local destinations",
74      gateway, STRINGOBJ, NULL },
75#define LAYOUT_NAMESERVER	3
76    { 5, 35, 18, IPADDR_FIELD_LEN - 1,
77      "Name server:", "IP address of your local DNS server",
78      nameserver, STRINGOBJ, NULL },
79#define LAYOUT_IPADDR		4
80    { 10, 10, 18, IPADDR_FIELD_LEN - 1,
81      "IP Address:",
82      "The IP address to be used for this interface",
83      ipaddr, STRINGOBJ, NULL },
84#define LAYOUT_NETMASK		5
85    { 10, 35, 18, IPADDR_FIELD_LEN - 1,
86      "Netmask:",
87      "The netmask for this interface, e.g. 0xffffff00 for a class C network",
88      netmask, STRINGOBJ, NULL },
89#define LAYOUT_EXTRAS		6
90    { 14, 10, 37, HOSTNAME_FIELD_LEN - 1,
91      "Extra options to ifconfig:",
92      "Any interface-specific options to ifconfig you would like to add",
93      extras, STRINGOBJ, NULL },
94#define LAYOUT_OKBUTTON		7
95    { 19, 15, 0, 0,
96      "OK", "Select this if you are happy with these settings",
97      &okbutton, BUTTONOBJ, NULL },
98#define LAYOUT_CANCELBUTTON	8
99    { 19, 35, 0, 0,
100      "CANCEL", "Select this if you wish to cancel this screen",
101      &cancelbutton, BUTTONOBJ, NULL },
102    { NULL },
103};
104
105#define _validByte(b) ((b) >= 0 && (b) <= 255)
106
107/* whine */
108static void
109feepout(char *msg)
110{
111    beep();
112    msgConfirm(msg);
113}
114
115/* Very basic IP address integrity check - could be drastically improved */
116static int
117verifyIP(char *ip)
118{
119    int a, b, c, d;
120
121    if (ip && sscanf(ip, "%d.%d.%d.%d", &a, &b, &c, &d) == 4 &&
122	_validByte(a) && _validByte(b) && _validByte(c) &&
123	_validByte(d) && (d != 255))
124	return 1;
125    else
126	return 0;
127}
128
129/* Check for the settings on the screen - the per-interface stuff is
130   moved to the main handling code now to do it on the fly - sigh */
131static int
132verifySettings(void)
133{
134    if (!hostname[0])
135	feepout("Must specify a host name of some sort!");
136    else if (gateway[0] && strcmp(gateway, "NO") && !verifyIP(gateway))
137	feepout("Invalid gateway IP address specified");
138    else if (nameserver[0] && !verifyIP(nameserver))
139	feepout("Invalid name server IP address specified");
140    else if (netmask[0] && (netmask[0] < '0' && netmask[0] > '3'))
141	feepout("Invalid netmask value");
142    else if (ipaddr[0] && !verifyIP(ipaddr))
143	feepout("Invalid IP address");
144    else
145	return 1;
146    return 0;
147}
148
149static void
150dhcpGetInfo(Device *devp)
151{
152    /* If it fails, do it the old-fashioned way */
153    if (dhcpParseLeases("/var/db/dhclient.leases", hostname, domainname,
154			 nameserver, ipaddr, gateway, netmask) == -1) {
155	FILE *ifp;
156	char *cp, cmd[256], data[2048];
157	int i, j;
158
159	/* Bah, now we have to kludge getting the information from ifconfig */
160	snprintf(cmd, sizeof cmd, "ifconfig %s", devp->name);
161	ifp = popen(cmd, "r");
162	if (ifp) {
163	    j = fread(data, 1, sizeof(data), ifp);
164	    fclose(ifp);
165	    if (j < 0)	/* paranoia */
166		j = 0;
167	    data[j] = '\0';
168	    if (isDebug())
169		msgDebug("DHCP configured interface returns %s\n", data);
170	    /* XXX This is gross as it assumes a certain ordering to
171	       ifconfig's output! XXX */
172	    if ((cp = strstr(data, "inet")) != NULL) {
173		i = 0;
174		cp += 5;	/* move over keyword */
175		while (*cp != ' ')
176		    ipaddr[i++] = *(cp++);
177		ipaddr[i] = '\0';
178		if (!strncmp(++cp, "netmask", 7)) {
179		    i = 0;
180		    cp += 8;
181		    while (*cp != ' ')
182			netmask[i++] = *(cp++);
183		    netmask[i] = '\0';
184		}
185	    }
186	}
187    }
188
189    /* If we didn't get a name server value, hunt for it in resolv.conf */
190    if (!nameserver[0] && file_readable("/etc/resolv.conf"))
191	configEnvironmentResolv("/etc/resolv.conf");
192    if (hostname[0])
193	variable_set2(VAR_HOSTNAME, hostname, 0);
194}
195
196/* This is it - how to get TCP setup values */
197int
198tcpOpenDialog(Device *devp)
199{
200    WINDOW              *ds_win, *save = NULL;
201    ComposeObj          *obj = NULL;
202    int                 n = 0, filled = 0, cancel = FALSE;
203    int			max, ret = DITEM_SUCCESS;
204    int			use_dhcp = FALSE;
205    char                *tmp;
206    char		title[80];
207
208    /* Initialise vars from previous device values */
209    if (devp->private) {
210	DevInfo *di = (DevInfo *)devp->private;
211
212	SAFE_STRCPY(ipaddr, di->ipaddr);
213	SAFE_STRCPY(netmask, di->netmask);
214	SAFE_STRCPY(extras, di->extras);
215	use_dhcp = di->use_dhcp;
216    }
217    else { /* See if there are any defaults */
218	char *cp;
219
220	/* First try a DHCP scan if such behavior is desired */
221	if (!variable_cmp(VAR_TRY_DHCP, "YES") || !msgYesNo("Do you want to try DHCP configuration of the interface?")) {
222	    int k;
223
224	    Mkdir("/var/db");
225	    Mkdir("/var/run");
226	    Mkdir("/tmp");
227	    msgNotify("Scanning for DHCP servers...");
228	    if (0 == vsystem("dhclient -1 %s", devp->name)) {
229		dhcpGetInfo(devp);
230		use_dhcp = TRUE;
231	    }
232	    else
233		use_dhcp = FALSE;
234	}
235
236	/* Special hack so it doesn't show up oddly in the tcpip setup menu */
237	if (!strcmp(gateway, "NO"))
238	    gateway[0] = '\0';
239
240	/* Get old IP address from variable space, if available */
241	if (!ipaddr[0]) {
242	    if ((cp = variable_get(VAR_IPADDR)) != NULL)
243		SAFE_STRCPY(ipaddr, cp);
244	    else if ((cp = variable_get(string_concat3(devp->name, "_", VAR_IPADDR))) != NULL)
245		SAFE_STRCPY(ipaddr, cp);
246	}
247
248	/* Get old netmask from variable space, if available */
249	if (!netmask[0]) {
250	    if ((cp = variable_get(VAR_NETMASK)) != NULL)
251		SAFE_STRCPY(netmask, cp);
252	    else if ((cp = variable_get(string_concat3(devp->name, "_", VAR_NETMASK))) != NULL)
253		SAFE_STRCPY(netmask, cp);
254	}
255
256	/* Get old extras string from variable space, if available */
257	if (!extras[0]) {
258	    if ((cp = variable_get(VAR_EXTRAS)) != NULL)
259		SAFE_STRCPY(extras, cp);
260	    else if ((cp = variable_get(string_concat3(devp->name, "_", VAR_EXTRAS))) != NULL)
261		SAFE_STRCPY(extras, cp);
262	}
263    }
264
265    /* Look up values already recorded with the system, or blank the string variables ready to accept some new data */
266    if (!hostname[0]) {
267	tmp = variable_get(VAR_HOSTNAME);
268	if (tmp)
269	    SAFE_STRCPY(hostname, tmp);
270    }
271    if (!domainname[0]) {
272	tmp = variable_get(VAR_DOMAINNAME);
273	if (tmp)
274	    SAFE_STRCPY(domainname, tmp);
275    }
276    if (!gateway[0]) {
277	tmp = variable_get(VAR_GATEWAY);
278	if (tmp && strcmp(tmp, "NO"))
279	    SAFE_STRCPY(gateway, tmp);
280    }
281    if (!nameserver[0]) {
282	tmp = variable_get(VAR_NAMESERVER);
283	if (tmp)
284	    SAFE_STRCPY(nameserver, tmp);
285    }
286
287    save = savescr();
288    /* If non-interactive, jump straight over the dialog crap and into config section */
289    if (variable_get(VAR_NONINTERACTIVE) &&
290	!variable_get(VAR_NETINTERACTIVE)) {
291	if (!hostname[0])
292	    msgConfirm("WARNING: hostname variable not set and is a non-optional\n"
293		       "parameter.  Please add this to your installation script\n"
294		       "or set the netInteractive variable (see sysinstall man page)");
295	else
296	    goto netconfig;
297    }
298
299    /* Now do all the screen I/O */
300    dialog_clear_norefresh();
301
302    /* We need a curses window */
303    if (!(ds_win = openLayoutDialog(TCP_HELPFILE, " Network Configuration ",
304				    TCP_DIALOG_X, TCP_DIALOG_Y, TCP_DIALOG_WIDTH, TCP_DIALOG_HEIGHT))) {
305	beep();
306	msgConfirm("Cannot open TCP/IP dialog window!!");
307	restorescr(save);
308	return DITEM_FAILURE;
309    }
310
311    /* Draw interface configuration box */
312    draw_box(ds_win, TCP_DIALOG_Y + 9, TCP_DIALOG_X + 8, TCP_DIALOG_HEIGHT - 13, TCP_DIALOG_WIDTH - 17,
313	     dialog_attr, border_attr);
314    wattrset(ds_win, dialog_attr);
315    sprintf(title, " Configuration for Interface %s ", devp->name);
316    mvwaddstr(ds_win, TCP_DIALOG_Y + 9, TCP_DIALOG_X + 14, title);
317
318    /* Some more initialisation before we go into the main input loop */
319    obj = initLayoutDialog(ds_win, layout, TCP_DIALOG_X, TCP_DIALOG_Y, &max);
320
321reenter:
322    cancelbutton = okbutton = 0;
323    while (layoutDialogLoop(ds_win, layout, &obj, &n, max, &cancelbutton, &cancel)) {
324	/* Prevent this from being irritating if user really means NO */
325	if (filled < 3) {
326	    /* Insert a default value for the netmask, 0xffffff00 is
327	     * the most appropriate one (entire class C, or subnetted
328	     * class A/B network).
329	     */
330	    if (!netmask[0]) {
331		strcpy(netmask, "255.255.255.0");
332		RefreshStringObj(layout[LAYOUT_NETMASK].obj);
333		++filled;
334	    }
335	    if (!index(hostname, '.') && domainname[0]) {
336		strcat(hostname, ".");
337		strcat(hostname, domainname);
338		RefreshStringObj(layout[LAYOUT_HOSTNAME].obj);
339		++filled;
340	    }
341	    else if (((tmp = index(hostname, '.')) != NULL) && !domainname[0]) {
342		SAFE_STRCPY(domainname, tmp + 1);
343		RefreshStringObj(layout[LAYOUT_DOMAINNAME].obj);
344		++filled;
345	    }
346	}
347    }
348    if (!cancel && !verifySettings())
349	goto reenter;
350
351    /* Clear this crap off the screen */
352    delwin(ds_win);
353    dialog_clear_norefresh();
354    use_helpfile(NULL);
355
356    /* We actually need to inform the rest of sysinstall about this
357       data now if the user hasn't selected cancel.  Save the stuff
358       out to the environment via the variable_set() mechanism */
359
360netconfig:
361    if (!cancel) {
362	DevInfo *di;
363	char temp[512], ifn[255];
364	char *ifaces;
365
366	if (hostname[0]) {
367	    variable_set2(VAR_HOSTNAME, hostname, use_dhcp ? 0 : 1);
368	    sethostname(hostname, strlen(hostname));
369	}
370	if (domainname[0])
371	    variable_set2(VAR_DOMAINNAME, domainname, 0);
372	if (gateway[0])
373	    variable_set2(VAR_GATEWAY, gateway, use_dhcp ? 0 : 1);
374	if (nameserver[0])
375	    variable_set2(VAR_NAMESERVER, nameserver, 0);
376	if (ipaddr[0])
377	    variable_set2(VAR_IPADDR, ipaddr, 0);
378
379	if (!devp->private)
380	    devp->private = (DevInfo *)safe_malloc(sizeof(DevInfo));
381	di = devp->private;
382	SAFE_STRCPY(di->ipaddr, ipaddr);
383	SAFE_STRCPY(di->netmask, netmask);
384	SAFE_STRCPY(di->extras, extras);
385	di->use_dhcp = use_dhcp;
386
387	sprintf(ifn, "%s%s", VAR_IFCONFIG, devp->name);
388	if (use_dhcp)
389	    sprintf(temp, "DHCP");
390	else
391	    sprintf(temp, "inet %s %s netmask %s", ipaddr, extras, netmask);
392	variable_set2(ifn, temp, 1);
393	ifaces = variable_get(VAR_INTERFACES);
394	if (!ifaces || (ifaces && !strcmp(ifaces, "auto")))
395	    variable_set2(VAR_INTERFACES, ifaces = "lo0", 1);
396	/* Only add it if it's not there already */
397	if (!strstr(ifaces, devp->name)) {
398	    sprintf(ifn, "%s %s", devp->name, ifaces);
399	    variable_set2(VAR_INTERFACES, ifn, 1);
400	}
401	if (!use_dhcp)
402	    configResolv(NULL);	/* XXX this will do it on the MFS copy XXX */
403	ret = DITEM_SUCCESS;
404    }
405    else
406	ret = DITEM_FAILURE;
407    restorescr(save);
408    return ret;
409}
410
411static Device *NetDev;
412
413static int
414netHook(dialogMenuItem *self)
415{
416    Device **devs;
417
418    devs = deviceFindDescr(self->prompt, self->title, DEVICE_TYPE_NETWORK);
419    if (devs) {
420	if (DITEM_STATUS(tcpOpenDialog(devs[0])) != DITEM_FAILURE)
421	    NetDev = devs[0];
422	else
423	    NetDev = NULL;
424    }
425    return devs ? DITEM_LEAVE_MENU : DITEM_FAILURE;
426}
427
428/* Get a network device */
429Device *
430tcpDeviceSelect(void)
431{
432    DMenu *menu;
433    Device **devs, *rval;
434    int cnt;
435
436    devs = deviceFind(NULL, DEVICE_TYPE_NETWORK);
437    cnt = deviceCount(devs);
438    rval = NULL;
439
440    if (!cnt) {
441	msgConfirm("No network devices available!");
442	return NULL;
443    }
444    else if (!RunningAsInit) {
445	if (!msgYesNo("Running multi-user, assume that the network is already configured?"))
446	    return devs[0];
447    }
448    if (cnt == 1) {
449	if (DITEM_STATUS(tcpOpenDialog(devs[0]) == DITEM_SUCCESS))
450	    rval = devs[0];
451    }
452    else if (variable_get(VAR_NONINTERACTIVE) && variable_get(VAR_NETWORK_DEVICE)) {
453	devs = deviceFind(variable_get(VAR_NETWORK_DEVICE), DEVICE_TYPE_NETWORK);
454	cnt = deviceCount(devs);
455	if (cnt) {
456	    if (DITEM_STATUS(tcpOpenDialog(devs[0]) == DITEM_SUCCESS))
457		rval = devs[0];
458	}
459    }
460    else {
461	int status;
462
463	menu = deviceCreateMenu(&MenuNetworkDevice, DEVICE_TYPE_NETWORK, netHook, NULL);
464	if (!menu)
465	    msgFatal("Unable to create network device menu!  Argh!");
466	status = dmenuOpenSimple(menu, FALSE);
467	free(menu);
468	if (status)
469	    rval = NetDev;
470    }
471    return rval;
472}
473
474/* Do it from a menu that doesn't care about status */
475int
476tcpMenuSelect(dialogMenuItem *self)
477{
478    Device *tmp;
479
480    tmp = tcpDeviceSelect();
481    if (tmp && !((DevInfo *)tmp->private)->use_dhcp && !msgYesNo("Would you like to bring the %s interface up right now?", tmp->name))
482	if (!tmp->init(tmp))
483	    msgConfirm("Initialization of %s device failed.", tmp->name);
484    return DITEM_SUCCESS | DITEM_RESTORE;
485}
486