xref: /freebsd/sys/nfs/bootp_subr.c (revision 16038816)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1995 Gordon Ross, Adam Glass
5  * Copyright (c) 1992 Regents of the University of California.
6  * All rights reserved.
7  *
8  * This software was developed by the Computer Systems Engineering group
9  * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
10  * contributed to Berkeley.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the University of
23  *	California, Lawrence Berkeley Laboratory and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  *
40  * based on:
41  *      nfs/krpc_subr.c
42  *	$NetBSD: krpc_subr.c,v 1.10 1995/08/08 20:43:43 gwr Exp $
43  */
44 
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47 
48 #include "opt_bootp.h"
49 #include "opt_nfs.h"
50 #include "opt_rootdevname.h"
51 
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/endian.h>
55 #include <sys/jail.h>
56 #include <sys/kernel.h>
57 #include <sys/sockio.h>
58 #include <sys/malloc.h>
59 #include <sys/mount.h>
60 #include <sys/mbuf.h>
61 #include <sys/proc.h>
62 #include <sys/reboot.h>
63 #include <sys/socket.h>
64 #include <sys/socketvar.h>
65 #include <sys/sysctl.h>
66 #include <sys/uio.h>
67 
68 #include <net/if.h>
69 #include <net/if_var.h>
70 #include <net/route.h>
71 #include <net/route/route_ctl.h>
72 
73 #include <netinet/in.h>
74 #include <netinet/in_var.h>
75 #include <net/if_types.h>
76 #include <net/if_dl.h>
77 #include <net/vnet.h>
78 
79 #include <nfs/nfsproto.h>
80 #include <nfsclient/nfs.h>
81 #include <nfs/nfsdiskless.h>
82 #include <nfs/krpc.h>
83 #include <nfs/xdr_subs.h>
84 
85 #define BOOTP_MIN_LEN		300	/* Minimum size of bootp udp packet */
86 
87 #ifndef BOOTP_SETTLE_DELAY
88 #define BOOTP_SETTLE_DELAY 3
89 #endif
90 
91 /*
92  * Wait 10 seconds for interface appearance
93  * USB ethernet adapters might require some time to pop up
94  */
95 #ifndef	BOOTP_IFACE_WAIT_TIMEOUT
96 #define	BOOTP_IFACE_WAIT_TIMEOUT	10
97 #endif
98 
99 /*
100  * What is the longest we will wait before re-sending a request?
101  * Note this is also the frequency of "RPC timeout" messages.
102  * The re-send loop count sup linearly to this maximum, so the
103  * first complaint will happen after (1+2+3+4+5)=15 seconds.
104  */
105 #define	MAX_RESEND_DELAY 5	/* seconds */
106 
107 /* Definitions from RFC951 */
108 struct bootp_packet {
109 	u_int8_t op;
110 	u_int8_t htype;
111 	u_int8_t hlen;
112 	u_int8_t hops;
113 	u_int32_t xid;
114 	u_int16_t secs;
115 	u_int16_t flags;
116 	struct in_addr ciaddr;
117 	struct in_addr yiaddr;
118 	struct in_addr siaddr;
119 	struct in_addr giaddr;
120 	unsigned char chaddr[16];
121 	char sname[64];
122 	char file[128];
123 	unsigned char vend[1222];
124 };
125 
126 struct bootpc_ifcontext {
127 	STAILQ_ENTRY(bootpc_ifcontext) next;
128 	struct bootp_packet call;
129 	struct bootp_packet reply;
130 	int replylen;
131 	int overload;
132 	union {
133 		struct ifreq _ifreq;
134 		struct in_aliasreq _in_alias_req;
135 	} _req;
136 #define	ireq	_req._ifreq
137 #define	iareq	_req._in_alias_req
138 	struct ifnet *ifp;
139 	struct sockaddr_dl *sdl;
140 	struct sockaddr_in myaddr;
141 	struct sockaddr_in netmask;
142 	struct sockaddr_in gw;
143 	int gotgw;
144 	int gotnetmask;
145 	int gotrootpath;
146 	int outstanding;
147 	int sentmsg;
148 	u_int32_t xid;
149 	enum {
150 		IF_BOOTP_UNRESOLVED,
151 		IF_BOOTP_RESOLVED,
152 		IF_BOOTP_FAILED,
153 		IF_DHCP_UNRESOLVED,
154 		IF_DHCP_OFFERED,
155 		IF_DHCP_RESOLVED,
156 		IF_DHCP_FAILED,
157 	} state;
158 	int dhcpquerytype;		/* dhcp type sent */
159 	struct in_addr dhcpserver;
160 	int gotdhcpserver;
161 	uint16_t mtu;
162 };
163 
164 #define TAG_MAXLEN 1024
165 struct bootpc_tagcontext {
166 	char buf[TAG_MAXLEN + 1];
167 	int overload;
168 	int badopt;
169 	int badtag;
170 	int foundopt;
171 	int taglen;
172 };
173 
174 struct bootpc_globalcontext {
175 	STAILQ_HEAD(, bootpc_ifcontext) interfaces;
176 	u_int32_t xid;
177 	int any_root_overrides;
178 	int gotrootpath;
179 	int gotgw;
180 	int ifnum;
181 	int secs;
182 	int starttime;
183 	struct bootp_packet reply;
184 	int replylen;
185 	struct bootpc_ifcontext *setrootfs;
186 	struct bootpc_ifcontext *sethostname;
187 	struct bootpc_tagcontext tmptag;
188 	struct bootpc_tagcontext tag;
189 };
190 
191 #define IPPORT_BOOTPC 68
192 #define IPPORT_BOOTPS 67
193 
194 #define BOOTP_REQUEST 1
195 #define BOOTP_REPLY 2
196 
197 /* Common tags */
198 #define TAG_PAD		  0  /* Pad option, implicit length 1 */
199 #define TAG_SUBNETMASK	  1  /* RFC 950 subnet mask */
200 #define TAG_ROUTERS	  3  /* Routers (in order of preference) */
201 #define TAG_HOSTNAME	 12  /* Client host name */
202 #define TAG_ROOT	 17  /* Root path */
203 #define TAG_INTF_MTU	 26  /* Interface MTU Size (RFC2132) */
204 
205 /* DHCP specific tags */
206 #define TAG_OVERLOAD	 52  /* Option Overload */
207 #define TAG_MAXMSGSIZE   57  /* Maximum DHCP Message Size */
208 
209 #define TAG_END		255  /* End Option (i.e. no more options) */
210 
211 /* Overload values */
212 #define OVERLOAD_FILE     1
213 #define OVERLOAD_SNAME    2
214 
215 /* Site specific tags: */
216 #define TAG_ROOTOPTS	130
217 #define TAG_COOKIE	134	/* ascii info for userland, via sysctl */
218 
219 #define TAG_DHCP_MSGTYPE 53
220 #define TAG_DHCP_REQ_ADDR 50
221 #define TAG_DHCP_SERVERID 54
222 #define TAG_DHCP_LEASETIME 51
223 
224 #define TAG_VENDOR_INDENTIFIER 60
225 
226 #define DHCP_NOMSG    0
227 #define DHCP_DISCOVER 1
228 #define DHCP_OFFER    2
229 #define DHCP_REQUEST  3
230 #define DHCP_ACK      5
231 
232 /* NFS read/write block size */
233 #ifndef BOOTP_BLOCKSIZE
234 #define	BOOTP_BLOCKSIZE	8192
235 #endif
236 
237 static char bootp_cookie[128];
238 static struct socket *bootp_so;
239 SYSCTL_STRING(_kern, OID_AUTO, bootp_cookie, CTLFLAG_RD,
240 	bootp_cookie, 0, "Cookie (T134) supplied by bootp server");
241 
242 /* mountd RPC */
243 static int	md_mount(struct sockaddr_in *mdsin, char *path, u_char *fhp,
244 		    int *fhsizep, struct nfs_args *args, struct thread *td);
245 static int	setfs(struct sockaddr_in *addr, char *path, char *p,
246 		    const struct in_addr *siaddr);
247 static int	getdec(char **ptr);
248 static int	getip(char **ptr, struct in_addr *ip);
249 static void	mountopts(struct nfs_args *args, char *p);
250 static int	xdr_opaque_decode(struct mbuf **ptr, u_char *buf, int len);
251 static int	xdr_int_decode(struct mbuf **ptr, int *iptr);
252 static void	print_in_addr(struct in_addr addr);
253 static void	print_sin_addr(struct sockaddr_in *addr);
254 static void	clear_sinaddr(struct sockaddr_in *sin);
255 static void	allocifctx(struct bootpc_globalcontext *gctx);
256 static void	bootpc_compose_query(struct bootpc_ifcontext *ifctx,
257 		    struct thread *td);
258 static unsigned char *bootpc_tag(struct bootpc_tagcontext *tctx,
259 		    struct bootp_packet *bp, int len, int tag);
260 static void bootpc_tag_helper(struct bootpc_tagcontext *tctx,
261 		    unsigned char *start, int len, int tag);
262 
263 #ifdef BOOTP_DEBUG
264 void bootpboot_p_if(struct ifnet *ifp, struct ifaddr *ifa);
265 void bootpboot_p_iflist(void);
266 #endif
267 
268 static int	bootpc_call(struct bootpc_globalcontext *gctx,
269 		    struct thread *td);
270 
271 static void	bootpc_fakeup_interface(struct bootpc_ifcontext *ifctx,
272 		    struct thread *td);
273 
274 static void	bootpc_adjust_interface(struct bootpc_ifcontext *ifctx,
275 		    struct bootpc_globalcontext *gctx, struct thread *td);
276 
277 static void	bootpc_decode_reply(struct nfsv3_diskless *nd,
278 		    struct bootpc_ifcontext *ifctx,
279 		    struct bootpc_globalcontext *gctx);
280 
281 static int	bootpc_received(struct bootpc_globalcontext *gctx,
282 		    struct bootpc_ifcontext *ifctx);
283 
284 static __inline int bootpc_ifctx_isresolved(struct bootpc_ifcontext *ifctx);
285 static __inline int bootpc_ifctx_isunresolved(struct bootpc_ifcontext *ifctx);
286 static __inline int bootpc_ifctx_isfailed(struct bootpc_ifcontext *ifctx);
287 
288 /*
289  * In order to have multiple active interfaces with address 0.0.0.0
290  * and be able to send data to a selected interface, we first set
291  * mask to /8 on all interfaces, and temporarily set it to /0 when
292  * doing sosend().
293  */
294 
295 #ifdef BOOTP_DEBUG
296 void
297 bootpboot_p_if(struct ifnet *ifp, struct ifaddr *ifa)
298 {
299 
300 	printf("%s flags %x, addr ",
301 	       ifp->if_xname, ifp->if_flags);
302 	print_sin_addr((struct sockaddr_in *) ifa->ifa_addr);
303 	printf(", broadcast ");
304 	print_sin_addr((struct sockaddr_in *) ifa->ifa_dstaddr);
305 	printf(", netmask ");
306 	print_sin_addr((struct sockaddr_in *) ifa->ifa_netmask);
307 	printf("\n");
308 }
309 
310 void
311 bootpboot_p_iflist(void)
312 {
313 	struct ifnet *ifp;
314 	struct ifaddr *ifa;
315 
316 	printf("Interface list:\n");
317 	IFNET_RLOCK();
318 	for (ifp = CK_STAILQ_FIRST(&V_ifnet);
319 	     ifp != NULL;
320 	     ifp = CK_STAILQ_NEXT(ifp, if_link)) {
321 		for (ifa = CK_STAILQ_FIRST(&ifp->if_addrhead);
322 		     ifa != NULL;
323 		     ifa = CK_STAILQ_NEXT(ifa, ifa_link))
324 			if (ifa->ifa_addr->sa_family == AF_INET)
325 				bootpboot_p_if(ifp, ifa);
326 	}
327 	IFNET_RUNLOCK();
328 }
329 #endif /* defined(BOOTP_DEBUG) */
330 
331 static void
332 clear_sinaddr(struct sockaddr_in *sin)
333 {
334 
335 	bzero(sin, sizeof(*sin));
336 	sin->sin_len = sizeof(*sin);
337 	sin->sin_family = AF_INET;
338 	sin->sin_addr.s_addr = INADDR_ANY; /* XXX: htonl(INAADDR_ANY) ? */
339 	sin->sin_port = 0;
340 }
341 
342 static void
343 allocifctx(struct bootpc_globalcontext *gctx)
344 {
345 	struct bootpc_ifcontext *ifctx;
346 
347 	ifctx = malloc(sizeof(*ifctx), M_TEMP, M_WAITOK | M_ZERO);
348 	ifctx->xid = gctx->xid;
349 #ifdef BOOTP_NO_DHCP
350 	ifctx->state = IF_BOOTP_UNRESOLVED;
351 #else
352 	ifctx->state = IF_DHCP_UNRESOLVED;
353 #endif
354 	gctx->xid += 0x100;
355 	STAILQ_INSERT_TAIL(&gctx->interfaces, ifctx, next);
356 }
357 
358 static __inline int
359 bootpc_ifctx_isresolved(struct bootpc_ifcontext *ifctx)
360 {
361 
362 	if (ifctx->state == IF_BOOTP_RESOLVED ||
363 	    ifctx->state == IF_DHCP_RESOLVED)
364 		return 1;
365 	return 0;
366 }
367 
368 static __inline int
369 bootpc_ifctx_isunresolved(struct bootpc_ifcontext *ifctx)
370 {
371 
372 	if (ifctx->state == IF_BOOTP_UNRESOLVED ||
373 	    ifctx->state == IF_DHCP_UNRESOLVED)
374 		return 1;
375 	return 0;
376 }
377 
378 static __inline int
379 bootpc_ifctx_isfailed(struct bootpc_ifcontext *ifctx)
380 {
381 
382 	if (ifctx->state == IF_BOOTP_FAILED ||
383 	    ifctx->state == IF_DHCP_FAILED)
384 		return 1;
385 	return 0;
386 }
387 
388 static int
389 bootpc_received(struct bootpc_globalcontext *gctx,
390     struct bootpc_ifcontext *ifctx)
391 {
392 	unsigned char dhcpreplytype;
393 	char *p;
394 
395 	/*
396 	 * Need timeout for fallback to less
397 	 * desirable alternative.
398 	 */
399 
400 	/* This call used for the side effect (badopt flag) */
401 	(void) bootpc_tag(&gctx->tmptag, &gctx->reply,
402 			  gctx->replylen,
403 			  TAG_END);
404 
405 	/* If packet is invalid, ignore it */
406 	if (gctx->tmptag.badopt != 0)
407 		return 0;
408 
409 	p = bootpc_tag(&gctx->tmptag, &gctx->reply,
410 		       gctx->replylen, TAG_DHCP_MSGTYPE);
411 	if (p != NULL)
412 		dhcpreplytype = *p;
413 	else
414 		dhcpreplytype = DHCP_NOMSG;
415 
416 	switch (ifctx->dhcpquerytype) {
417 	case DHCP_DISCOVER:
418 		if (dhcpreplytype != DHCP_OFFER 	/* Normal DHCP offer */
419 #ifndef BOOTP_FORCE_DHCP
420 		    && dhcpreplytype != DHCP_NOMSG	/* Fallback to BOOTP */
421 #endif
422 			)
423 			return 0;
424 		break;
425 	case DHCP_REQUEST:
426 		if (dhcpreplytype != DHCP_ACK)
427 			return 0;
428 	case DHCP_NOMSG:
429 		break;
430 	}
431 
432 	/* Ignore packet unless it gives us a root tag we didn't have */
433 
434 	if ((ifctx->state == IF_BOOTP_RESOLVED ||
435 	     (ifctx->dhcpquerytype == DHCP_DISCOVER &&
436 	      (ifctx->state == IF_DHCP_OFFERED ||
437 	       ifctx->state == IF_DHCP_RESOLVED))) &&
438 	    (bootpc_tag(&gctx->tmptag, &ifctx->reply,
439 			ifctx->replylen,
440 			TAG_ROOT) != NULL ||
441 	     bootpc_tag(&gctx->tmptag, &gctx->reply,
442 			gctx->replylen,
443 			TAG_ROOT) == NULL))
444 		return 0;
445 
446 	bcopy(&gctx->reply, &ifctx->reply, gctx->replylen);
447 	ifctx->replylen = gctx->replylen;
448 
449 	/* XXX: Only reset if 'perfect' response */
450 	if (ifctx->state == IF_BOOTP_UNRESOLVED)
451 		ifctx->state = IF_BOOTP_RESOLVED;
452 	else if (ifctx->state == IF_DHCP_UNRESOLVED &&
453 		 ifctx->dhcpquerytype == DHCP_DISCOVER) {
454 		if (dhcpreplytype == DHCP_OFFER)
455 			ifctx->state = IF_DHCP_OFFERED;
456 		else
457 			ifctx->state = IF_BOOTP_RESOLVED;	/* Fallback */
458 	} else if (ifctx->state == IF_DHCP_OFFERED &&
459 		   ifctx->dhcpquerytype == DHCP_REQUEST)
460 		ifctx->state = IF_DHCP_RESOLVED;
461 
462 	if (ifctx->dhcpquerytype == DHCP_DISCOVER &&
463 	    ifctx->state != IF_BOOTP_RESOLVED) {
464 		p = bootpc_tag(&gctx->tmptag, &ifctx->reply,
465 			       ifctx->replylen, TAG_DHCP_SERVERID);
466 		if (p != NULL && gctx->tmptag.taglen == 4) {
467 			memcpy(&ifctx->dhcpserver, p, 4);
468 			ifctx->gotdhcpserver = 1;
469 		} else
470 			ifctx->gotdhcpserver = 0;
471 		return 1;
472 	}
473 
474 	ifctx->gotrootpath = (bootpc_tag(&gctx->tmptag, &ifctx->reply,
475 					 ifctx->replylen,
476 					 TAG_ROOT) != NULL);
477 	ifctx->gotgw = (bootpc_tag(&gctx->tmptag, &ifctx->reply,
478 				   ifctx->replylen,
479 				   TAG_ROUTERS) != NULL);
480 	ifctx->gotnetmask = (bootpc_tag(&gctx->tmptag, &ifctx->reply,
481 					ifctx->replylen,
482 					TAG_SUBNETMASK) != NULL);
483 	return 1;
484 }
485 
486 static int
487 bootpc_call(struct bootpc_globalcontext *gctx, struct thread *td)
488 {
489 	struct sockaddr_in *sin, dst;
490 	struct uio auio;
491 	struct sockopt sopt;
492 	struct iovec aio;
493 	int error, on, rcvflg, timo, len;
494 	time_t atimo;
495 	time_t rtimo;
496 	struct timeval tv;
497 	struct bootpc_ifcontext *ifctx;
498 	int outstanding;
499 	int gotrootpath;
500 	int retry;
501 	const char *s;
502 
503 	tv.tv_sec = 1;
504 	tv.tv_usec = 0;
505 	bzero(&sopt, sizeof(sopt));
506 	sopt.sopt_dir = SOPT_SET;
507 	sopt.sopt_level = SOL_SOCKET;
508 	sopt.sopt_name = SO_RCVTIMEO;
509 	sopt.sopt_val = &tv;
510 	sopt.sopt_valsize = sizeof tv;
511 
512 	error = sosetopt(bootp_so, &sopt);
513 	if (error != 0)
514 		goto out;
515 
516 	/*
517 	 * Enable broadcast.
518 	 */
519 	on = 1;
520 	sopt.sopt_name = SO_BROADCAST;
521 	sopt.sopt_val = &on;
522 	sopt.sopt_valsize = sizeof on;
523 
524 	error = sosetopt(bootp_so, &sopt);
525 	if (error != 0)
526 		goto out;
527 
528 	/*
529 	 * Disable routing.
530 	 */
531 
532 	on = 1;
533 	sopt.sopt_name = SO_DONTROUTE;
534 	sopt.sopt_val = &on;
535 	sopt.sopt_valsize = sizeof on;
536 
537 	error = sosetopt(bootp_so, &sopt);
538 	if (error != 0)
539 		goto out;
540 
541 	/*
542 	 * Bind the local endpoint to a bootp client port.
543 	 */
544 	sin = &dst;
545 	clear_sinaddr(sin);
546 	sin->sin_port = htons(IPPORT_BOOTPC);
547 	error = sobind(bootp_so, (struct sockaddr *)sin, td);
548 	if (error != 0) {
549 		printf("bind failed\n");
550 		goto out;
551 	}
552 
553 	/*
554 	 * Setup socket address for the server.
555 	 */
556 	sin = &dst;
557 	clear_sinaddr(sin);
558 	sin->sin_addr.s_addr = INADDR_BROADCAST;
559 	sin->sin_port = htons(IPPORT_BOOTPS);
560 
561 	/*
562 	 * Send it, repeatedly, until a reply is received,
563 	 * but delay each re-send by an increasing amount.
564 	 * If the delay hits the maximum, start complaining.
565 	 */
566 	timo = 0;
567 	rtimo = 0;
568 	for (;;) {
569 		outstanding = 0;
570 		gotrootpath = 0;
571 
572 		STAILQ_FOREACH(ifctx, &gctx->interfaces, next) {
573 			if (bootpc_ifctx_isresolved(ifctx) != 0 &&
574 			    bootpc_tag(&gctx->tmptag, &ifctx->reply,
575 				       ifctx->replylen,
576 				       TAG_ROOT) != NULL)
577 				gotrootpath = 1;
578 		}
579 
580 		STAILQ_FOREACH(ifctx, &gctx->interfaces, next) {
581 			struct in_aliasreq *ifra = &ifctx->iareq;
582 			sin = (struct sockaddr_in *)&ifra->ifra_mask;
583 
584 			ifctx->outstanding = 0;
585 			if (bootpc_ifctx_isresolved(ifctx)  != 0 &&
586 			    gotrootpath != 0) {
587 				continue;
588 			}
589 			if (bootpc_ifctx_isfailed(ifctx) != 0)
590 				continue;
591 
592 			outstanding++;
593 			ifctx->outstanding = 1;
594 
595 			/* Proceed to next step in DHCP negotiation */
596 			if ((ifctx->state == IF_DHCP_OFFERED &&
597 			     ifctx->dhcpquerytype != DHCP_REQUEST) ||
598 			    (ifctx->state == IF_DHCP_UNRESOLVED &&
599 			     ifctx->dhcpquerytype != DHCP_DISCOVER) ||
600 			    (ifctx->state == IF_BOOTP_UNRESOLVED &&
601 			     ifctx->dhcpquerytype != DHCP_NOMSG)) {
602 				ifctx->sentmsg = 0;
603 				bootpc_compose_query(ifctx, td);
604 			}
605 
606 			/* Send BOOTP request (or re-send). */
607 
608 			if (ifctx->sentmsg == 0) {
609 				switch(ifctx->dhcpquerytype) {
610 				case DHCP_DISCOVER:
611 					s = "DHCP Discover";
612 					break;
613 				case DHCP_REQUEST:
614 					s = "DHCP Request";
615 					break;
616 				case DHCP_NOMSG:
617 				default:
618 					s = "BOOTP Query";
619 					break;
620 				}
621 				printf("Sending %s packet from "
622 				       "interface %s (%*D)\n",
623 				       s,
624 				       ifctx->ireq.ifr_name,
625 				       ifctx->sdl->sdl_alen,
626 				       (unsigned char *) LLADDR(ifctx->sdl),
627 				       ":");
628 				ifctx->sentmsg = 1;
629 			}
630 
631 			aio.iov_base = (caddr_t) &ifctx->call;
632 			aio.iov_len = sizeof(ifctx->call);
633 
634 			auio.uio_iov = &aio;
635 			auio.uio_iovcnt = 1;
636 			auio.uio_segflg = UIO_SYSSPACE;
637 			auio.uio_rw = UIO_WRITE;
638 			auio.uio_offset = 0;
639 			auio.uio_resid = sizeof(ifctx->call);
640 			auio.uio_td = td;
641 
642 			/* Set netmask to 0.0.0.0 */
643 			clear_sinaddr(sin);
644 			error = ifioctl(bootp_so, SIOCAIFADDR, (caddr_t)ifra,
645 			    td);
646 			if (error != 0)
647 				panic("%s: SIOCAIFADDR, error=%d", __func__,
648 				    error);
649 
650 			error = sosend(bootp_so, (struct sockaddr *) &dst,
651 				       &auio, NULL, NULL, 0, td);
652 			if (error != 0)
653 				printf("%s: sosend: %d state %08x\n", __func__,
654 				    error, (int )bootp_so->so_state);
655 
656 			/* Set netmask to 255.0.0.0 */
657 			sin->sin_addr.s_addr = htonl(IN_CLASSA_NET);
658 			error = ifioctl(bootp_so, SIOCAIFADDR, (caddr_t)ifra,
659 			    td);
660 			if (error != 0)
661 				panic("%s: SIOCAIFADDR, error=%d", __func__,
662 				    error);
663 		}
664 
665 		if (outstanding == 0 &&
666 		    (rtimo == 0 || time_second >= rtimo)) {
667 			error = 0;
668 			goto out;
669 		}
670 
671 		/* Determine new timeout. */
672 		if (timo < MAX_RESEND_DELAY)
673 			timo++;
674 		else {
675 			printf("DHCP/BOOTP timeout for server ");
676 			print_sin_addr(&dst);
677 			printf("\n");
678 		}
679 
680 		/*
681 		 * Wait for up to timo seconds for a reply.
682 		 * The socket receive timeout was set to 1 second.
683 		 */
684 		atimo = timo + time_second;
685 		while (time_second < atimo) {
686 			aio.iov_base = (caddr_t) &gctx->reply;
687 			aio.iov_len = sizeof(gctx->reply);
688 
689 			auio.uio_iov = &aio;
690 			auio.uio_iovcnt = 1;
691 			auio.uio_segflg = UIO_SYSSPACE;
692 			auio.uio_rw = UIO_READ;
693 			auio.uio_offset = 0;
694 			auio.uio_resid = sizeof(gctx->reply);
695 			auio.uio_td = td;
696 
697 			rcvflg = 0;
698 			error = soreceive(bootp_so, NULL, &auio,
699 					  NULL, NULL, &rcvflg);
700 			gctx->secs = time_second - gctx->starttime;
701 			STAILQ_FOREACH(ifctx, &gctx->interfaces, next) {
702 				if (bootpc_ifctx_isresolved(ifctx) != 0 ||
703 				    bootpc_ifctx_isfailed(ifctx) != 0)
704 					continue;
705 
706 				ifctx->call.secs = htons(gctx->secs);
707 			}
708 			if (error == EWOULDBLOCK)
709 				continue;
710 			if (error != 0)
711 				goto out;
712 			len = sizeof(gctx->reply) - auio.uio_resid;
713 
714 			/* Do we have the required number of bytes ? */
715 			if (len < BOOTP_MIN_LEN)
716 				continue;
717 			gctx->replylen = len;
718 
719 			/* Is it a reply? */
720 			if (gctx->reply.op != BOOTP_REPLY)
721 				continue;
722 
723 			/* Is this an answer to our query */
724 			STAILQ_FOREACH(ifctx, &gctx->interfaces, next) {
725 				if (gctx->reply.xid != ifctx->call.xid)
726 					continue;
727 
728 				/* Same HW address size ? */
729 				if (gctx->reply.hlen != ifctx->call.hlen)
730 					continue;
731 
732 				/* Correct HW address ? */
733 				if (bcmp(gctx->reply.chaddr,
734 					 ifctx->call.chaddr,
735 					 ifctx->call.hlen) != 0)
736 					continue;
737 
738 				break;
739 			}
740 
741 			if (ifctx != NULL) {
742 				s =  bootpc_tag(&gctx->tmptag,
743 						&gctx->reply,
744 						gctx->replylen,
745 						TAG_DHCP_MSGTYPE);
746 				if (s != NULL) {
747 					switch (*s) {
748 					case DHCP_OFFER:
749 						s = "DHCP Offer";
750 						break;
751 					case DHCP_ACK:
752 						s = "DHCP Ack";
753 						break;
754 					default:
755 						s = "DHCP (unexpected)";
756 						break;
757 					}
758 				} else
759 					s = "BOOTP Reply";
760 
761 				printf("Received %s packet"
762 				       " on %s from ",
763 				       s,
764 				       ifctx->ireq.ifr_name);
765 				print_in_addr(gctx->reply.siaddr);
766 				if (gctx->reply.giaddr.s_addr !=
767 				    htonl(INADDR_ANY)) {
768 					printf(" via ");
769 					print_in_addr(gctx->reply.giaddr);
770 				}
771 				if (bootpc_received(gctx, ifctx) != 0) {
772 					printf(" (accepted)");
773 					if (ifctx->outstanding) {
774 						ifctx->outstanding = 0;
775 						outstanding--;
776 					}
777 					/* Network settle delay */
778 					if (outstanding == 0)
779 						atimo = time_second +
780 							BOOTP_SETTLE_DELAY;
781 				} else
782 					printf(" (ignored)");
783 				if (ifctx->gotrootpath ||
784 				    gctx->any_root_overrides) {
785 					gotrootpath = 1;
786 					rtimo = time_second +
787 						BOOTP_SETTLE_DELAY;
788 					if (ifctx->gotrootpath)
789 						printf(" (got root path)");
790 				}
791 				printf("\n");
792 			}
793 		} /* while secs */
794 #ifdef BOOTP_TIMEOUT
795 		if (gctx->secs > BOOTP_TIMEOUT && BOOTP_TIMEOUT > 0)
796 			break;
797 #endif
798 		/* Force a retry if halfway in DHCP negotiation */
799 		retry = 0;
800 		STAILQ_FOREACH(ifctx, &gctx->interfaces, next)
801 			if (ifctx->state == IF_DHCP_OFFERED) {
802 				if (ifctx->dhcpquerytype == DHCP_DISCOVER)
803 					retry = 1;
804 				else
805 					ifctx->state = IF_DHCP_UNRESOLVED;
806 			}
807 
808 		if (retry != 0)
809 			continue;
810 
811 		if (gotrootpath != 0) {
812 			gctx->gotrootpath = gotrootpath;
813 			if (rtimo != 0 && time_second >= rtimo)
814 				break;
815 		}
816 	} /* forever send/receive */
817 
818 	/*
819 	 * XXX: These are errors of varying seriousness being silently
820 	 * ignored
821 	 */
822 
823 	STAILQ_FOREACH(ifctx, &gctx->interfaces, next)
824 		if (bootpc_ifctx_isresolved(ifctx) == 0) {
825 			printf("%s timeout for interface %s\n",
826 			       ifctx->dhcpquerytype != DHCP_NOMSG ?
827 			       "DHCP" : "BOOTP",
828 			       ifctx->ireq.ifr_name);
829 		}
830 
831 	if (gctx->gotrootpath != 0) {
832 #if 0
833 		printf("Got a root path, ignoring remaining timeout\n");
834 #endif
835 		error = 0;
836 		goto out;
837 	}
838 #ifndef BOOTP_NFSROOT
839 	STAILQ_FOREACH(ifctx, &gctx->interfaces, next)
840 		if (bootpc_ifctx_isresolved(ifctx) != 0) {
841 			error = 0;
842 			goto out;
843 		}
844 #endif
845 	error = ETIMEDOUT;
846 
847 out:
848 	return (error);
849 }
850 
851 static void
852 bootpc_fakeup_interface(struct bootpc_ifcontext *ifctx, struct thread *td)
853 {
854 	struct ifreq *ifr;
855 	struct in_aliasreq *ifra;
856 	struct sockaddr_in *sin;
857 	int error;
858 
859 	ifr = &ifctx->ireq;
860 	ifra = &ifctx->iareq;
861 
862 	/*
863 	 * Bring up the interface.
864 	 *
865 	 * Get the old interface flags and or IFF_UP into them; if
866 	 * IFF_UP set blindly, interface selection can be clobbered.
867 	 */
868 	error = ifioctl(bootp_so, SIOCGIFFLAGS, (caddr_t)ifr, td);
869 	if (error != 0)
870 		panic("%s: SIOCGIFFLAGS, error=%d", __func__, error);
871 	ifr->ifr_flags |= IFF_UP;
872 	error = ifioctl(bootp_so, SIOCSIFFLAGS, (caddr_t)ifr, td);
873 	if (error != 0)
874 		panic("%s: SIOCSIFFLAGS, error=%d", __func__, error);
875 
876 	/*
877 	 * Do enough of ifconfig(8) so that the chosen interface
878 	 * can talk to the servers. Set address to 0.0.0.0/8 and
879 	 * broadcast address to local broadcast.
880 	 */
881 	sin = (struct sockaddr_in *)&ifra->ifra_addr;
882 	clear_sinaddr(sin);
883 	sin = (struct sockaddr_in *)&ifra->ifra_mask;
884 	clear_sinaddr(sin);
885 	sin->sin_addr.s_addr = htonl(IN_CLASSA_NET);
886 	sin = (struct sockaddr_in *)&ifra->ifra_broadaddr;
887 	clear_sinaddr(sin);
888 	sin->sin_addr.s_addr = htonl(INADDR_BROADCAST);
889 	error = ifioctl(bootp_so, SIOCAIFADDR, (caddr_t)ifra, td);
890 	if (error != 0)
891 		panic("%s: SIOCAIFADDR, error=%d", __func__, error);
892 }
893 
894 static void
895 bootpc_shutdown_interface(struct bootpc_ifcontext *ifctx, struct thread *td)
896 {
897 	struct ifreq *ifr;
898 	struct sockaddr_in *sin;
899 	int error;
900 
901 	ifr = &ifctx->ireq;
902 
903 	printf("Shutdown interface %s\n", ifctx->ireq.ifr_name);
904 	error = ifioctl(bootp_so, SIOCGIFFLAGS, (caddr_t)ifr, td);
905 	if (error != 0)
906 		panic("%s: SIOCGIFFLAGS, error=%d", __func__, error);
907 	ifr->ifr_flags &= ~IFF_UP;
908 	error = ifioctl(bootp_so, SIOCSIFFLAGS, (caddr_t)ifr, td);
909 	if (error != 0)
910 		panic("%s: SIOCSIFFLAGS, error=%d", __func__, error);
911 
912 	sin = (struct sockaddr_in *) &ifr->ifr_addr;
913 	clear_sinaddr(sin);
914 	error = ifioctl(bootp_so, SIOCDIFADDR, (caddr_t) ifr, td);
915 	if (error != 0)
916 		panic("%s: SIOCDIFADDR, error=%d", __func__, error);
917 }
918 
919 static void
920 bootpc_adjust_interface(struct bootpc_ifcontext *ifctx,
921     struct bootpc_globalcontext *gctx, struct thread *td)
922 {
923 	int error;
924 	struct sockaddr_in *sin;
925 	struct ifreq *ifr;
926 	struct in_aliasreq *ifra;
927 	struct sockaddr_in *myaddr;
928 	struct sockaddr_in *netmask;
929 
930 	ifr = &ifctx->ireq;
931 	ifra = &ifctx->iareq;
932 	myaddr = &ifctx->myaddr;
933 	netmask = &ifctx->netmask;
934 
935 	if (bootpc_ifctx_isresolved(ifctx) == 0) {
936 		/* Shutdown interfaces where BOOTP failed */
937 		bootpc_shutdown_interface(ifctx, td);
938 		return;
939 	}
940 
941 	printf("Adjusted interface %s", ifctx->ireq.ifr_name);
942 
943 	/* Do BOOTP interface options */
944 	if (ifctx->mtu != 0) {
945 		printf(" (MTU=%d%s)", ifctx->mtu,
946 		    (ifctx->mtu > 1514) ? "/JUMBO" : "");
947 		ifr->ifr_mtu = ifctx->mtu;
948 		error = ifioctl(bootp_so, SIOCSIFMTU, (caddr_t) ifr, td);
949 		if (error != 0)
950 			panic("%s: SIOCSIFMTU, error=%d", __func__, error);
951 	}
952 	printf("\n");
953 
954 	/*
955 	 * Do enough of ifconfig(8) so that the chosen interface
956 	 * can talk to the servers.  (just set the address)
957 	 */
958 	sin = (struct sockaddr_in *) &ifr->ifr_addr;
959 	clear_sinaddr(sin);
960 	error = ifioctl(bootp_so, SIOCDIFADDR, (caddr_t) ifr, td);
961 	if (error != 0)
962 		panic("%s: SIOCDIFADDR, error=%d", __func__, error);
963 
964 	bcopy(myaddr, &ifra->ifra_addr, sizeof(*myaddr));
965 	bcopy(netmask, &ifra->ifra_mask, sizeof(*netmask));
966 	clear_sinaddr(&ifra->ifra_broadaddr);
967 	ifra->ifra_broadaddr.sin_addr.s_addr = myaddr->sin_addr.s_addr |
968 	    ~netmask->sin_addr.s_addr;
969 
970 	error = ifioctl(bootp_so, SIOCAIFADDR, (caddr_t)ifra, td);
971 	if (error != 0)
972 		panic("%s: SIOCAIFADDR, error=%d", __func__, error);
973 }
974 
975 static void
976 bootpc_add_default_route(struct bootpc_ifcontext *ifctx)
977 {
978 	int error;
979 	struct sockaddr_in defdst;
980 	struct sockaddr_in defmask;
981 	struct rt_addrinfo info;
982 	struct rib_cmd_info rc;
983 
984 	if (ifctx->gw.sin_addr.s_addr == htonl(INADDR_ANY))
985 		return;
986 
987 	clear_sinaddr(&defdst);
988 	clear_sinaddr(&defmask);
989 
990 	bzero((caddr_t)&info, sizeof(info));
991 	info.rti_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC;
992 	info.rti_info[RTAX_DST] = (struct sockaddr *)&defdst;
993 	info.rti_info[RTAX_NETMASK] = (struct sockaddr *)&defmask;
994 	info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&ifctx->gw;
995 
996 	error = rib_action(RT_DEFAULT_FIB, RTM_ADD, &info, &rc);
997 
998 	if (error != 0) {
999 		printf("%s: RTM_ADD, error=%d\n", __func__, error);
1000 	}
1001 }
1002 
1003 static void
1004 bootpc_remove_default_route(struct bootpc_ifcontext *ifctx)
1005 {
1006 	int error;
1007 	struct sockaddr_in defdst;
1008 	struct sockaddr_in defmask;
1009 	struct rt_addrinfo info;
1010 	struct rib_cmd_info rc;
1011 
1012 	if (ifctx->gw.sin_addr.s_addr == htonl(INADDR_ANY))
1013 		return;
1014 
1015 	clear_sinaddr(&defdst);
1016 	clear_sinaddr(&defmask);
1017 
1018 	bzero((caddr_t)&info, sizeof(info));
1019 	info.rti_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC;
1020 	info.rti_info[RTAX_DST] = (struct sockaddr *)&defdst;
1021 	info.rti_info[RTAX_NETMASK] = (struct sockaddr *)&defmask;
1022 	info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&ifctx->gw;
1023 
1024 	error = rib_action(RT_DEFAULT_FIB, RTM_DELETE, &info, &rc);
1025 	if (error != 0) {
1026 		printf("%s: RTM_DELETE, error=%d\n", __func__, error);
1027 	}
1028 }
1029 
1030 static int
1031 setfs(struct sockaddr_in *addr, char *path, char *p,
1032     const struct in_addr *siaddr)
1033 {
1034 
1035 	if (getip(&p, &addr->sin_addr) == 0) {
1036 		if (siaddr != NULL && *p == '/')
1037 			bcopy(siaddr, &addr->sin_addr, sizeof(struct in_addr));
1038 		else
1039 			return 0;
1040 	} else {
1041 		if (*p != ':')
1042 			return 0;
1043 		p++;
1044 	}
1045 
1046 	addr->sin_len = sizeof(struct sockaddr_in);
1047 	addr->sin_family = AF_INET;
1048 
1049 	strlcpy(path, p, MNAMELEN);
1050 	return 1;
1051 }
1052 
1053 static int
1054 getip(char **ptr, struct in_addr *addr)
1055 {
1056 	char *p;
1057 	unsigned int ip;
1058 	int val;
1059 
1060 	p = *ptr;
1061 	ip = 0;
1062 	if (((val = getdec(&p)) < 0) || (val > 255))
1063 		return 0;
1064 	ip = val << 24;
1065 	if (*p != '.')
1066 		return 0;
1067 	p++;
1068 	if (((val = getdec(&p)) < 0) || (val > 255))
1069 		return 0;
1070 	ip |= (val << 16);
1071 	if (*p != '.')
1072 		return 0;
1073 	p++;
1074 	if (((val = getdec(&p)) < 0) || (val > 255))
1075 		return 0;
1076 	ip |= (val << 8);
1077 	if (*p != '.')
1078 		return 0;
1079 	p++;
1080 	if (((val = getdec(&p)) < 0) || (val > 255))
1081 		return 0;
1082 	ip |= val;
1083 
1084 	addr->s_addr = htonl(ip);
1085 	*ptr = p;
1086 	return 1;
1087 }
1088 
1089 static int
1090 getdec(char **ptr)
1091 {
1092 	char *p;
1093 	int ret;
1094 
1095 	p = *ptr;
1096 	ret = 0;
1097 	if ((*p < '0') || (*p > '9'))
1098 		return -1;
1099 	while ((*p >= '0') && (*p <= '9')) {
1100 		ret = ret * 10 + (*p - '0');
1101 		p++;
1102 	}
1103 	*ptr = p;
1104 	return ret;
1105 }
1106 
1107 static void
1108 mountopts(struct nfs_args *args, char *p)
1109 {
1110 	args->version = NFS_ARGSVERSION;
1111 	args->rsize = BOOTP_BLOCKSIZE;
1112 	args->wsize = BOOTP_BLOCKSIZE;
1113 	args->flags = NFSMNT_RSIZE | NFSMNT_WSIZE | NFSMNT_RESVPORT;
1114 	args->sotype = SOCK_DGRAM;
1115 	if (p != NULL)
1116 		nfs_parse_options(p, args);
1117 }
1118 
1119 static int
1120 xdr_opaque_decode(struct mbuf **mptr, u_char *buf, int len)
1121 {
1122 	struct mbuf *m;
1123 	int alignedlen;
1124 
1125 	m = *mptr;
1126 	alignedlen = ( len + 3 ) & ~3;
1127 
1128 	if (m->m_len < alignedlen) {
1129 		m = m_pullup(m, alignedlen);
1130 		if (m == NULL) {
1131 			*mptr = NULL;
1132 			return EBADRPC;
1133 		}
1134 	}
1135 	bcopy(mtod(m, u_char *), buf, len);
1136 	m_adj(m, alignedlen);
1137 	*mptr = m;
1138 	return 0;
1139 }
1140 
1141 static int
1142 xdr_int_decode(struct mbuf **mptr, int *iptr)
1143 {
1144 	u_int32_t i;
1145 
1146 	if (xdr_opaque_decode(mptr, (u_char *) &i, sizeof(u_int32_t)) != 0)
1147 		return EBADRPC;
1148 	*iptr = fxdr_unsigned(u_int32_t, i);
1149 	return 0;
1150 }
1151 
1152 static void
1153 print_sin_addr(struct sockaddr_in *sin)
1154 {
1155 
1156 	print_in_addr(sin->sin_addr);
1157 }
1158 
1159 static void
1160 print_in_addr(struct in_addr addr)
1161 {
1162 	unsigned int ip;
1163 
1164 	ip = ntohl(addr.s_addr);
1165 	printf("%d.%d.%d.%d",
1166 	       ip >> 24, (ip >> 16) & 255, (ip >> 8) & 255, ip & 255);
1167 }
1168 
1169 static void
1170 bootpc_compose_query(struct bootpc_ifcontext *ifctx, struct thread *td)
1171 {
1172 	unsigned char *vendp;
1173 	unsigned char vendor_client[64];
1174 	uint32_t leasetime;
1175 	uint8_t vendor_client_len;
1176 
1177 	ifctx->gotrootpath = 0;
1178 
1179 	bzero((caddr_t) &ifctx->call, sizeof(ifctx->call));
1180 
1181 	/* bootpc part */
1182 	ifctx->call.op = BOOTP_REQUEST; 	/* BOOTREQUEST */
1183 	ifctx->call.htype = 1;			/* 10mb ethernet */
1184 	ifctx->call.hlen = ifctx->sdl->sdl_alen;/* Hardware address length */
1185 	ifctx->call.hops = 0;
1186 	if (bootpc_ifctx_isunresolved(ifctx) != 0)
1187 		ifctx->xid++;
1188 	ifctx->call.xid = txdr_unsigned(ifctx->xid);
1189 	bcopy(LLADDR(ifctx->sdl), &ifctx->call.chaddr, ifctx->sdl->sdl_alen);
1190 
1191 	vendp = ifctx->call.vend;
1192 	*vendp++ = 99;		/* RFC1048 cookie */
1193 	*vendp++ = 130;
1194 	*vendp++ = 83;
1195 	*vendp++ = 99;
1196 	*vendp++ = TAG_MAXMSGSIZE;
1197 	*vendp++ = 2;
1198 	*vendp++ = (sizeof(struct bootp_packet) >> 8) & 255;
1199 	*vendp++ = sizeof(struct bootp_packet) & 255;
1200 
1201 	snprintf(vendor_client, sizeof(vendor_client), "%s:%s:%s",
1202 		ostype, MACHINE, osrelease);
1203 	vendor_client_len = strlen(vendor_client);
1204 	*vendp++ = TAG_VENDOR_INDENTIFIER;
1205 	*vendp++ = vendor_client_len;
1206 	memcpy(vendp, vendor_client, vendor_client_len);
1207 	vendp += vendor_client_len;
1208 	ifctx->dhcpquerytype = DHCP_NOMSG;
1209 	switch (ifctx->state) {
1210 	case IF_DHCP_UNRESOLVED:
1211 		*vendp++ = TAG_DHCP_MSGTYPE;
1212 		*vendp++ = 1;
1213 		*vendp++ = DHCP_DISCOVER;
1214 		ifctx->dhcpquerytype = DHCP_DISCOVER;
1215 		ifctx->gotdhcpserver = 0;
1216 		break;
1217 	case IF_DHCP_OFFERED:
1218 		*vendp++ = TAG_DHCP_MSGTYPE;
1219 		*vendp++ = 1;
1220 		*vendp++ = DHCP_REQUEST;
1221 		ifctx->dhcpquerytype = DHCP_REQUEST;
1222 		*vendp++ = TAG_DHCP_REQ_ADDR;
1223 		*vendp++ = 4;
1224 		memcpy(vendp, &ifctx->reply.yiaddr, 4);
1225 		vendp += 4;
1226 		if (ifctx->gotdhcpserver != 0) {
1227 			*vendp++ = TAG_DHCP_SERVERID;
1228 			*vendp++ = 4;
1229 			memcpy(vendp, &ifctx->dhcpserver, 4);
1230 			vendp += 4;
1231 		}
1232 		*vendp++ = TAG_DHCP_LEASETIME;
1233 		*vendp++ = 4;
1234 		leasetime = htonl(300);
1235 		memcpy(vendp, &leasetime, 4);
1236 		vendp += 4;
1237 		break;
1238 	default:
1239 		break;
1240 	}
1241 	*vendp = TAG_END;
1242 
1243 	ifctx->call.secs = 0;
1244 	ifctx->call.flags = htons(0x8000); /* We need a broadcast answer */
1245 }
1246 
1247 static int
1248 bootpc_hascookie(struct bootp_packet *bp)
1249 {
1250 
1251 	return (bp->vend[0] == 99 && bp->vend[1] == 130 &&
1252 		bp->vend[2] == 83 && bp->vend[3] == 99);
1253 }
1254 
1255 static void
1256 bootpc_tag_helper(struct bootpc_tagcontext *tctx,
1257     unsigned char *start, int len, int tag)
1258 {
1259 	unsigned char *j;
1260 	unsigned char *ej;
1261 	unsigned char code;
1262 
1263 	if (tctx->badtag != 0 || tctx->badopt != 0)
1264 		return;
1265 
1266 	j = start;
1267 	ej = j + len;
1268 
1269 	while (j < ej) {
1270 		code = *j++;
1271 		if (code == TAG_PAD)
1272 			continue;
1273 		if (code == TAG_END)
1274 			return;
1275 		if (j >= ej || j + *j + 1 > ej) {
1276 			tctx->badopt = 1;
1277 			return;
1278 		}
1279 		len = *j++;
1280 		if (code == tag) {
1281 			if (tctx->taglen + len > TAG_MAXLEN) {
1282 				tctx->badtag = 1;
1283 				return;
1284 			}
1285 			tctx->foundopt = 1;
1286 			if (len > 0)
1287 				memcpy(tctx->buf + tctx->taglen,
1288 				       j, len);
1289 			tctx->taglen += len;
1290 		}
1291 		if (code == TAG_OVERLOAD)
1292 			tctx->overload = *j;
1293 
1294 		j += len;
1295 	}
1296 }
1297 
1298 static unsigned char *
1299 bootpc_tag(struct bootpc_tagcontext *tctx,
1300     struct bootp_packet *bp, int len, int tag)
1301 {
1302 	tctx->overload = 0;
1303 	tctx->badopt = 0;
1304 	tctx->badtag = 0;
1305 	tctx->foundopt = 0;
1306 	tctx->taglen = 0;
1307 
1308 	if (bootpc_hascookie(bp) == 0)
1309 		return NULL;
1310 
1311 	bootpc_tag_helper(tctx, &bp->vend[4],
1312 			  (unsigned char *) bp + len - &bp->vend[4], tag);
1313 
1314 	if ((tctx->overload & OVERLOAD_FILE) != 0)
1315 		bootpc_tag_helper(tctx,
1316 				  (unsigned char *) bp->file,
1317 				  sizeof(bp->file),
1318 				  tag);
1319 	if ((tctx->overload & OVERLOAD_SNAME) != 0)
1320 		bootpc_tag_helper(tctx,
1321 				  (unsigned char *) bp->sname,
1322 				  sizeof(bp->sname),
1323 				  tag);
1324 
1325 	if (tctx->badopt != 0 || tctx->badtag != 0 || tctx->foundopt == 0)
1326 		return NULL;
1327 	tctx->buf[tctx->taglen] = '\0';
1328 	return tctx->buf;
1329 }
1330 
1331 static void
1332 bootpc_decode_reply(struct nfsv3_diskless *nd, struct bootpc_ifcontext *ifctx,
1333     struct bootpc_globalcontext *gctx)
1334 {
1335 	char *p, *s;
1336 	unsigned int ip;
1337 
1338 	ifctx->gotgw = 0;
1339 	ifctx->gotnetmask = 0;
1340 
1341 	clear_sinaddr(&ifctx->myaddr);
1342 	clear_sinaddr(&ifctx->netmask);
1343 	clear_sinaddr(&ifctx->gw);
1344 
1345 	ifctx->myaddr.sin_addr = ifctx->reply.yiaddr;
1346 
1347 	ip = ntohl(ifctx->myaddr.sin_addr.s_addr);
1348 
1349 	printf("%s at ", ifctx->ireq.ifr_name);
1350 	print_sin_addr(&ifctx->myaddr);
1351 	printf(" server ");
1352 	print_in_addr(ifctx->reply.siaddr);
1353 
1354 	ifctx->gw.sin_addr = ifctx->reply.giaddr;
1355 	if (ifctx->reply.giaddr.s_addr != htonl(INADDR_ANY)) {
1356 		printf(" via gateway ");
1357 		print_in_addr(ifctx->reply.giaddr);
1358 	}
1359 
1360 	/* This call used for the side effect (overload flag) */
1361 	(void) bootpc_tag(&gctx->tmptag,
1362 			  &ifctx->reply, ifctx->replylen, TAG_END);
1363 
1364 	if ((gctx->tmptag.overload & OVERLOAD_SNAME) == 0)
1365 		if (ifctx->reply.sname[0] != '\0')
1366 			printf(" server name %s", ifctx->reply.sname);
1367 	if ((gctx->tmptag.overload & OVERLOAD_FILE) == 0)
1368 		if (ifctx->reply.file[0] != '\0')
1369 			printf(" boot file %s", ifctx->reply.file);
1370 
1371 	printf("\n");
1372 
1373 	p = bootpc_tag(&gctx->tag, &ifctx->reply, ifctx->replylen,
1374 		       TAG_SUBNETMASK);
1375 	if (p != NULL) {
1376 		if (gctx->tag.taglen != 4)
1377 			panic("bootpc: subnet mask len is %d",
1378 			      gctx->tag.taglen);
1379 		bcopy(p, &ifctx->netmask.sin_addr, 4);
1380 		ifctx->gotnetmask = 1;
1381 		printf("subnet mask ");
1382 		print_sin_addr(&ifctx->netmask);
1383 		printf(" ");
1384 	}
1385 
1386 	p = bootpc_tag(&gctx->tag, &ifctx->reply, ifctx->replylen,
1387 		       TAG_ROUTERS);
1388 	if (p != NULL) {
1389 		/* Routers */
1390 		if (gctx->tag.taglen % 4)
1391 			panic("bootpc: Router Len is %d", gctx->tag.taglen);
1392 		if (gctx->tag.taglen > 0) {
1393 			bcopy(p, &ifctx->gw.sin_addr, 4);
1394 			printf("router ");
1395 			print_sin_addr(&ifctx->gw);
1396 			printf(" ");
1397 			ifctx->gotgw = 1;
1398 			gctx->gotgw = 1;
1399 		}
1400 	}
1401 
1402 	/*
1403 	 * Choose a root filesystem.  If a value is forced in the environment
1404 	 * and it contains "nfs:", use it unconditionally.  Otherwise, if the
1405 	 * kernel is compiled with the ROOTDEVNAME option, then use it if:
1406 	 *  - The server doesn't provide a pathname.
1407 	 *  - The boothowto flags include RB_DFLTROOT (user said to override
1408 	 *    the server value).
1409 	 */
1410 	p = NULL;
1411 	if ((s = kern_getenv("vfs.root.mountfrom")) != NULL) {
1412 		if ((p = strstr(s, "nfs:")) != NULL)
1413 			p = strdup(p + 4, M_TEMP);
1414 		freeenv(s);
1415 	}
1416 	if (p == NULL) {
1417 		p = bootpc_tag(&gctx->tag, &ifctx->reply, ifctx->replylen,
1418 		       TAG_ROOT);
1419 		if (p != NULL)
1420 			ifctx->gotrootpath = 1;
1421 	}
1422 #ifdef ROOTDEVNAME
1423 	if ((p == NULL || (boothowto & RB_DFLTROOT) != 0) &&
1424 	    (p = strstr(ROOTDEVNAME, "nfs:")) != NULL) {
1425 		p += 4;
1426 	}
1427 #endif
1428 	if (p != NULL) {
1429 		if (gctx->setrootfs != NULL) {
1430 			printf("rootfs %s (ignored) ", p);
1431 		} else 	if (setfs(&nd->root_saddr,
1432 				  nd->root_hostnam, p, &ifctx->reply.siaddr)) {
1433 			if (*p == '/') {
1434 				printf("root_server ");
1435 				print_sin_addr(&nd->root_saddr);
1436 				printf(" ");
1437 			}
1438 			printf("rootfs %s ", p);
1439 			gctx->gotrootpath = 1;
1440 			gctx->setrootfs = ifctx;
1441 
1442 			p = bootpc_tag(&gctx->tag, &ifctx->reply,
1443 				       ifctx->replylen,
1444 				       TAG_ROOTOPTS);
1445 			if (p != NULL) {
1446 				mountopts(&nd->root_args, p);
1447 				printf("rootopts %s ", p);
1448 			}
1449 		} else
1450 			panic("Failed to set rootfs to %s", p);
1451 	}
1452 
1453 	p = bootpc_tag(&gctx->tag, &ifctx->reply, ifctx->replylen,
1454 		       TAG_HOSTNAME);
1455 	if (p != NULL) {
1456 		if (gctx->tag.taglen >= MAXHOSTNAMELEN)
1457 			panic("bootpc: hostname >= %d bytes",
1458 			      MAXHOSTNAMELEN);
1459 		if (gctx->sethostname != NULL) {
1460 			printf("hostname %s (ignored) ", p);
1461 		} else {
1462 			strcpy(nd->my_hostnam, p);
1463 			mtx_lock(&prison0.pr_mtx);
1464 			strcpy(prison0.pr_hostname, p);
1465 			mtx_unlock(&prison0.pr_mtx);
1466 			printf("hostname %s ", p);
1467 			gctx->sethostname = ifctx;
1468 		}
1469 	}
1470 	p = bootpc_tag(&gctx->tag, &ifctx->reply, ifctx->replylen,
1471 			TAG_COOKIE);
1472 	if (p != NULL) {        /* store in a sysctl variable */
1473 		int i, l = sizeof(bootp_cookie) - 1;
1474 		for (i = 0; i < l && p[i] != '\0'; i++)
1475 			bootp_cookie[i] = p[i];
1476 		p[i] = '\0';
1477 	}
1478 
1479 	p = bootpc_tag(&gctx->tag, &ifctx->reply, ifctx->replylen,
1480 		       TAG_INTF_MTU);
1481 	if (p != NULL) {
1482 		ifctx->mtu = be16dec(p);
1483 	}
1484 
1485 	printf("\n");
1486 
1487 	if (ifctx->gotnetmask == 0) {
1488 		if (IN_CLASSA(ntohl(ifctx->myaddr.sin_addr.s_addr)))
1489 			ifctx->netmask.sin_addr.s_addr = htonl(IN_CLASSA_NET);
1490 		else if (IN_CLASSB(ntohl(ifctx->myaddr.sin_addr.s_addr)))
1491 			ifctx->netmask.sin_addr.s_addr = htonl(IN_CLASSB_NET);
1492 		else
1493 			ifctx->netmask.sin_addr.s_addr = htonl(IN_CLASSC_NET);
1494 	}
1495 }
1496 
1497 void
1498 bootpc_init(void)
1499 {
1500 	struct bootpc_ifcontext *ifctx;		/* Interface BOOTP contexts */
1501 	struct bootpc_globalcontext *gctx; 	/* Global BOOTP context */
1502 	struct ifnet *ifp;
1503 	struct sockaddr_dl *sdl;
1504 	struct ifaddr *ifa;
1505 	int error;
1506 #ifndef BOOTP_WIRED_TO
1507 	int ifcnt;
1508 #endif
1509 	struct nfsv3_diskless *nd;
1510 	struct thread *td;
1511 	int timeout;
1512 	int delay;
1513 
1514 	timeout = BOOTP_IFACE_WAIT_TIMEOUT * hz;
1515 	delay = hz / 10;
1516 
1517 	nd = &nfsv3_diskless;
1518 	td = curthread;
1519 
1520 	/*
1521 	 * If already filled in, don't touch it here
1522 	 */
1523 	if (nfs_diskless_valid != 0)
1524 		return;
1525 
1526 	gctx = malloc(sizeof(*gctx), M_TEMP, M_WAITOK | M_ZERO);
1527 	STAILQ_INIT(&gctx->interfaces);
1528 	gctx->xid = ~0xFFFF;
1529 	gctx->starttime = time_second;
1530 
1531 	/*
1532 	 * If ROOTDEVNAME is defined or vfs.root.mountfrom is set then we have
1533 	 * root-path overrides that can potentially let us boot even if we don't
1534 	 * get a root path from the server, so we can treat that as a non-error.
1535 	 */
1536 #ifdef ROOTDEVNAME
1537 	gctx->any_root_overrides = 1;
1538 #else
1539 	gctx->any_root_overrides = testenv("vfs.root.mountfrom");
1540 #endif
1541 
1542 	/*
1543 	 * Find a network interface.
1544 	 */
1545 	CURVNET_SET(TD_TO_VNET(td));
1546 #ifdef BOOTP_WIRED_TO
1547 	printf("%s: wired to interface '%s'\n", __func__,
1548 	       __XSTRING(BOOTP_WIRED_TO));
1549 	allocifctx(gctx);
1550 #else
1551 	/*
1552 	 * Preallocate interface context storage, if another interface
1553 	 * attaches and wins the race, it won't be eligible for bootp.
1554 	 */
1555 	ifcnt = 0;
1556 	IFNET_RLOCK();
1557 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1558 		if ((ifp->if_flags &
1559 		     (IFF_LOOPBACK | IFF_POINTOPOINT | IFF_BROADCAST)) !=
1560 		    IFF_BROADCAST)
1561 			continue;
1562 		switch (ifp->if_alloctype) {
1563 			case IFT_ETHER:
1564 				break;
1565 			default:
1566 				continue;
1567 		}
1568 		ifcnt++;
1569 	}
1570 	IFNET_RUNLOCK();
1571 	if (ifcnt == 0)
1572 		panic("%s: no eligible interfaces", __func__);
1573 	for (; ifcnt > 0; ifcnt--)
1574 		allocifctx(gctx);
1575 #endif
1576 
1577 retry:
1578 	ifctx = STAILQ_FIRST(&gctx->interfaces);
1579 	IFNET_RLOCK();
1580 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1581 		if (ifctx == NULL)
1582 			break;
1583 #ifdef BOOTP_WIRED_TO
1584 		if (strcmp(ifp->if_xname, __XSTRING(BOOTP_WIRED_TO)) != 0)
1585 			continue;
1586 #else
1587 		if ((ifp->if_flags &
1588 		     (IFF_LOOPBACK | IFF_POINTOPOINT | IFF_BROADCAST)) !=
1589 		    IFF_BROADCAST)
1590 			continue;
1591 		switch (ifp->if_alloctype) {
1592 			case IFT_ETHER:
1593 				break;
1594 			default:
1595 				continue;
1596 		}
1597 #endif
1598 		strlcpy(ifctx->ireq.ifr_name, ifp->if_xname,
1599 		    sizeof(ifctx->ireq.ifr_name));
1600 		ifctx->ifp = ifp;
1601 
1602 		/* Get HW address */
1603 		sdl = NULL;
1604 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1605 			if (ifa->ifa_addr->sa_family == AF_LINK) {
1606 				sdl = (struct sockaddr_dl *)ifa->ifa_addr;
1607 				if (sdl->sdl_type == IFT_ETHER)
1608 					break;
1609 			}
1610 		if (sdl == NULL)
1611 			panic("bootpc: Unable to find HW address for %s",
1612 			    ifctx->ireq.ifr_name);
1613 		ifctx->sdl = sdl;
1614 
1615 		ifctx = STAILQ_NEXT(ifctx, next);
1616 	}
1617 	IFNET_RUNLOCK();
1618 	CURVNET_RESTORE();
1619 
1620 	if (STAILQ_EMPTY(&gctx->interfaces) ||
1621 	    STAILQ_FIRST(&gctx->interfaces)->ifp == NULL) {
1622 		if (timeout > 0) {
1623 			pause("bootpc", delay);
1624 			timeout -= delay;
1625 			goto retry;
1626 		}
1627 #ifdef BOOTP_WIRED_TO
1628 		panic("%s: Could not find interface specified "
1629 		      "by BOOTP_WIRED_TO: "
1630 		      __XSTRING(BOOTP_WIRED_TO), __func__);
1631 #else
1632 		panic("%s: no suitable interface", __func__);
1633 #endif
1634 	}
1635 
1636 	error = socreate(AF_INET, &bootp_so, SOCK_DGRAM, 0, td->td_ucred, td);
1637 	if (error != 0)
1638 		panic("%s: socreate, error=%d", __func__, error);
1639 
1640 	STAILQ_FOREACH(ifctx, &gctx->interfaces, next)
1641 		bootpc_fakeup_interface(ifctx, td);
1642 
1643 	STAILQ_FOREACH(ifctx, &gctx->interfaces, next)
1644 		bootpc_compose_query(ifctx, td);
1645 
1646 	error = bootpc_call(gctx, td);
1647 	if (error != 0) {
1648 		printf("BOOTP call failed\n");
1649 	}
1650 
1651 	mountopts(&nd->root_args, NULL);
1652 
1653 	STAILQ_FOREACH(ifctx, &gctx->interfaces, next)
1654 		if (bootpc_ifctx_isresolved(ifctx) != 0)
1655 			bootpc_decode_reply(nd, ifctx, gctx);
1656 
1657 #ifdef BOOTP_NFSROOT
1658 	if (gctx->gotrootpath == 0 && gctx->any_root_overrides == 0)
1659 		panic("bootpc: No root path offered");
1660 #endif
1661 
1662 	STAILQ_FOREACH(ifctx, &gctx->interfaces, next)
1663 		bootpc_adjust_interface(ifctx, gctx, td);
1664 
1665 	soclose(bootp_so);
1666 
1667 	STAILQ_FOREACH(ifctx, &gctx->interfaces, next)
1668 		if (ifctx->gotrootpath != 0)
1669 			break;
1670 	if (ifctx == NULL) {
1671 		STAILQ_FOREACH(ifctx, &gctx->interfaces, next)
1672 			if (bootpc_ifctx_isresolved(ifctx) != 0)
1673 				break;
1674 	}
1675 	if (ifctx == NULL)
1676 		goto out;
1677 
1678 	if (gctx->gotrootpath != 0) {
1679 		struct epoch_tracker et;
1680 
1681 		kern_setenv("boot.netif.name", ifctx->ifp->if_xname);
1682 
1683 		NET_EPOCH_ENTER(et);
1684 		bootpc_add_default_route(ifctx);
1685 		NET_EPOCH_EXIT(et);
1686 		error = md_mount(&nd->root_saddr, nd->root_hostnam,
1687 				 nd->root_fh, &nd->root_fhsize,
1688 				 &nd->root_args, td);
1689 		NET_EPOCH_ENTER(et);
1690 		bootpc_remove_default_route(ifctx);
1691 		NET_EPOCH_EXIT(et);
1692 		if (error != 0) {
1693 			if (gctx->any_root_overrides == 0)
1694 				panic("nfs_boot: mount root, error=%d", error);
1695 			else
1696 				goto out;
1697 		}
1698 		rootdevnames[0] = "nfs:";
1699 		nfs_diskless_valid = 3;
1700 	}
1701 
1702 	strcpy(nd->myif.ifra_name, ifctx->ireq.ifr_name);
1703 	bcopy(&ifctx->myaddr, &nd->myif.ifra_addr, sizeof(ifctx->myaddr));
1704 	bcopy(&ifctx->myaddr, &nd->myif.ifra_broadaddr, sizeof(ifctx->myaddr));
1705 	((struct sockaddr_in *) &nd->myif.ifra_broadaddr)->sin_addr.s_addr =
1706 		ifctx->myaddr.sin_addr.s_addr |
1707 		~ ifctx->netmask.sin_addr.s_addr;
1708 	bcopy(&ifctx->netmask, &nd->myif.ifra_mask, sizeof(ifctx->netmask));
1709 	bcopy(&ifctx->gw, &nd->mygateway, sizeof(ifctx->gw));
1710 
1711 out:
1712 	while((ifctx = STAILQ_FIRST(&gctx->interfaces)) != NULL) {
1713 		STAILQ_REMOVE_HEAD(&gctx->interfaces, next);
1714 		free(ifctx, M_TEMP);
1715 	}
1716 	free(gctx, M_TEMP);
1717 }
1718 
1719 /*
1720  * RPC: mountd/mount
1721  * Given a server pathname, get an NFS file handle.
1722  * Also, sets sin->sin_port to the NFS service port.
1723  */
1724 static int
1725 md_mount(struct sockaddr_in *mdsin, char *path, u_char *fhp, int *fhsizep,
1726     struct nfs_args *args, struct thread *td)
1727 {
1728 	struct mbuf *m;
1729 	int error;
1730 	int authunixok;
1731 	int authcount;
1732 	int authver;
1733 
1734 #define	RPCPROG_MNT	100005
1735 #define	RPCMNT_VER1	1
1736 #define RPCMNT_VER3	3
1737 #define	RPCMNT_MOUNT	1
1738 #define	AUTH_SYS	1		/* unix style (uid, gids) */
1739 #define AUTH_UNIX	AUTH_SYS
1740 
1741 	/* XXX honor v2/v3 flags in args->flags? */
1742 #ifdef BOOTP_NFSV3
1743 	/* First try NFS v3 */
1744 	/* Get port number for MOUNTD. */
1745 	error = krpc_portmap(mdsin, RPCPROG_MNT, RPCMNT_VER3,
1746 			     &mdsin->sin_port, td);
1747 	if (error == 0) {
1748 		m = xdr_string_encode(path, strlen(path));
1749 
1750 		/* Do RPC to mountd. */
1751 		error = krpc_call(mdsin, RPCPROG_MNT, RPCMNT_VER3,
1752 				  RPCMNT_MOUNT, &m, NULL, td);
1753 	}
1754 	if (error == 0) {
1755 		args->flags |= NFSMNT_NFSV3;
1756 	} else {
1757 #endif
1758 		/* Fallback to NFS v2 */
1759 
1760 		/* Get port number for MOUNTD. */
1761 		error = krpc_portmap(mdsin, RPCPROG_MNT, RPCMNT_VER1,
1762 				     &mdsin->sin_port, td);
1763 		if (error != 0)
1764 			return error;
1765 
1766 		m = xdr_string_encode(path, strlen(path));
1767 
1768 		/* Do RPC to mountd. */
1769 		error = krpc_call(mdsin, RPCPROG_MNT, RPCMNT_VER1,
1770 				  RPCMNT_MOUNT, &m, NULL, td);
1771 		if (error != 0)
1772 			return error;	/* message already freed */
1773 
1774 #ifdef BOOTP_NFSV3
1775 	}
1776 #endif
1777 
1778 	if (xdr_int_decode(&m, &error) != 0 || error != 0)
1779 		goto bad;
1780 
1781 	if ((args->flags & NFSMNT_NFSV3) != 0) {
1782 		if (xdr_int_decode(&m, fhsizep) != 0 ||
1783 		    *fhsizep > NFSX_V3FHMAX ||
1784 		    *fhsizep <= 0)
1785 			goto bad;
1786 	} else
1787 		*fhsizep = NFSX_V2FH;
1788 
1789 	if (xdr_opaque_decode(&m, fhp, *fhsizep) != 0)
1790 		goto bad;
1791 
1792 	if (args->flags & NFSMNT_NFSV3) {
1793 		if (xdr_int_decode(&m, &authcount) != 0)
1794 			goto bad;
1795 		authunixok = 0;
1796 		if (authcount < 0 || authcount > 100)
1797 			goto bad;
1798 		while (authcount > 0) {
1799 			if (xdr_int_decode(&m, &authver) != 0)
1800 				goto bad;
1801 			if (authver == AUTH_UNIX)
1802 				authunixok = 1;
1803 			authcount--;
1804 		}
1805 		if (authunixok == 0)
1806 			goto bad;
1807 	}
1808 
1809 	/* Set port number for NFS use. */
1810 	error = krpc_portmap(mdsin, NFS_PROG,
1811 			     (args->flags &
1812 			      NFSMNT_NFSV3) ? NFS_VER3 : NFS_VER2,
1813 			     &mdsin->sin_port, td);
1814 
1815 	goto out;
1816 
1817 bad:
1818 	error = EBADRPC;
1819 
1820 out:
1821 	m_freem(m);
1822 	return error;
1823 }
1824 
1825 SYSINIT(bootp_rootconf, SI_SUB_ROOT_CONF, SI_ORDER_FIRST, bootpc_init, NULL);
1826