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