xref: /openbsd-src/sys/net/if_spppsubr.c (revision d13be5d47e4149db2549a9828e244d59dbc43f15)
1 /*	$OpenBSD: if_spppsubr.c,v 1.94 2011/07/07 00:08:04 henning Exp $	*/
2 /*
3  * Synchronous PPP/Cisco link level subroutines.
4  * Keepalive protocol implemented in both Cisco and PPP modes.
5  *
6  * Copyright (C) 1994-1996 Cronyx Engineering Ltd.
7  * Author: Serge Vakulenko, <vak@cronyx.ru>
8  *
9  * Heavily revamped to conform to RFC 1661.
10  * Copyright (C) 1997, Joerg Wunsch.
11  *
12  * RFC2472 IPv6CP support.
13  * Copyright (C) 2000, Jun-ichiro itojun Hagino <itojun@iijlab.net>.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions are met:
17  * 1. Redistributions of source code must retain the above copyright notice,
18  *    this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright notice,
20  *    this list of conditions and the following disclaimer in the documentation
21  *    and/or other materials provided with the distribution.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``AS IS'' AND ANY
24  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  *
35  * From: Version 2.6, Tue May 12 17:10:39 MSD 1998
36  */
37 
38 #include <sys/param.h>
39 
40 #define HIDE
41 
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/sockio.h>
45 #include <sys/socket.h>
46 #include <sys/proc.h>
47 #include <sys/syslog.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/workq.h>
51 
52 #if defined (__OpenBSD__)
53 #include <sys/timeout.h>
54 #include <crypto/md5.h>
55 #else
56 #include <sys/md5.h>
57 #endif
58 
59 #include <net/if.h>
60 #include <net/netisr.h>
61 #include <net/if_types.h>
62 #include <net/route.h>
63 
64 /* for arc4random() */
65 #include <dev/rndvar.h>
66 
67 #if defined (__FreeBSD__) || defined(__OpenBSD_) || defined(__NetBSD__)
68 #include <machine/random.h>
69 #endif
70 #if defined (__NetBSD__) || defined (__OpenBSD__)
71 #include <machine/cpu.h> /* XXX for softnet */
72 #endif
73 #include <sys/stdarg.h>
74 
75 #ifdef INET
76 #include <netinet/in.h>
77 #include <netinet/in_systm.h>
78 #include <netinet/in_var.h>
79 #include <netinet/ip.h>
80 #include <netinet/tcp.h>
81 # if defined (__FreeBSD__) || defined (__OpenBSD__)
82 #  include <netinet/if_ether.h>
83 # else
84 #  include <net/ethertypes.h>
85 # endif
86 #endif
87 
88 #ifdef INET6
89 #include <netinet6/in6_var.h>
90 #endif
91 
92 #include <net/if_sppp.h>
93 
94 #if defined (__FreeBSD__)
95 # define UNTIMEOUT(fun, arg, handle)	\
96 	untimeout(fun, arg, handle)
97 #elif defined(__OpenBSD__)
98 # define UNTIMEOUT(fun, arg, handle)	\
99 	timeout_del(&(handle))
100 #else
101 # define UNTIMEOUT(fun, arg, handle)	\
102 	untimeout(fun, arg)
103 #endif
104 
105 #define LOOPALIVECNT     		3	/* loopback detection tries */
106 #define MAXALIVECNT    			3	/* max. missed alive packets */
107 #define	NORECV_TIME			15	/* before we get worried */
108 
109 /*
110  * Interface flags that can be set in an ifconfig command.
111  *
112  * Setting link0 will make the link passive, i.e. it will be marked
113  * as being administrative openable, but won't be opened to begin
114  * with.  Incoming calls will be answered, or subsequent calls with
115  * -link1 will cause the administrative open of the LCP layer.
116  *
117  * Setting link1 will cause the link to auto-dial only as packets
118  * arrive to be sent.
119  *
120  * Setting IFF_DEBUG will syslog the option negotiation and state
121  * transitions at level kern.debug.  Note: all logs consistently look
122  * like
123  *
124  *   <if-name><unit>: <proto-name> <additional info...>
125  *
126  * with <if-name><unit> being something like "bppp0", and <proto-name>
127  * being one of "lcp", "ipcp", "cisco", "chap", "pap", etc.
128  */
129 
130 #define IFF_PASSIVE	IFF_LINK0	/* wait passively for connection */
131 #define IFF_AUTO	IFF_LINK1	/* auto-dial on output */
132 
133 #define PPP_ALLSTATIONS 0xff		/* All-Stations broadcast address */
134 #define PPP_UI		0x03		/* Unnumbered Information */
135 #define PPP_IP		0x0021		/* Internet Protocol */
136 #define PPP_ISO		0x0023		/* ISO OSI Protocol */
137 #define PPP_XNS		0x0025		/* Xerox NS Protocol */
138 #define PPP_IPX		0x002b		/* Novell IPX Protocol */
139 #define PPP_IPV6	0x0057		/* Internet Protocol v6 */
140 #define PPP_LCP		0xc021		/* Link Control Protocol */
141 #define PPP_PAP		0xc023		/* Password Authentication Protocol */
142 #define PPP_CHAP	0xc223		/* Challenge-Handshake Auth Protocol */
143 #define PPP_IPCP	0x8021		/* Internet Protocol Control Protocol */
144 #define PPP_IPV6CP	0x8057		/* IPv6 Control Protocol */
145 
146 #define CONF_REQ	1		/* PPP configure request */
147 #define CONF_ACK	2		/* PPP configure acknowledge */
148 #define CONF_NAK	3		/* PPP configure negative ack */
149 #define CONF_REJ	4		/* PPP configure reject */
150 #define TERM_REQ	5		/* PPP terminate request */
151 #define TERM_ACK	6		/* PPP terminate acknowledge */
152 #define CODE_REJ	7		/* PPP code reject */
153 #define PROTO_REJ	8		/* PPP protocol reject */
154 #define ECHO_REQ	9		/* PPP echo request */
155 #define ECHO_REPLY	10		/* PPP echo reply */
156 #define DISC_REQ	11		/* PPP discard request */
157 
158 #define LCP_OPT_MRU		1	/* maximum receive unit */
159 #define LCP_OPT_ASYNC_MAP	2	/* async control character map */
160 #define LCP_OPT_AUTH_PROTO	3	/* authentication protocol */
161 #define LCP_OPT_QUAL_PROTO	4	/* quality protocol */
162 #define LCP_OPT_MAGIC		5	/* magic number */
163 #define LCP_OPT_RESERVED	6	/* reserved */
164 #define LCP_OPT_PROTO_COMP	7	/* protocol field compression */
165 #define LCP_OPT_ADDR_COMP	8	/* address/control field compression */
166 
167 #define IPCP_OPT_ADDRESSES	1	/* both IP addresses; deprecated */
168 #define IPCP_OPT_COMPRESSION	2	/* IP compression protocol (VJ) */
169 #define IPCP_OPT_ADDRESS	3	/* local IP address */
170 
171 #define IPV6CP_OPT_IFID		1	/* interface identifier */
172 #define IPV6CP_OPT_COMPRESSION	2	/* IPv6 compression protocol */
173 
174 #define PAP_REQ			1	/* PAP name/password request */
175 #define PAP_ACK			2	/* PAP acknowledge */
176 #define PAP_NAK			3	/* PAP fail */
177 
178 #define CHAP_CHALLENGE		1	/* CHAP challenge request */
179 #define CHAP_RESPONSE		2	/* CHAP challenge response */
180 #define CHAP_SUCCESS		3	/* CHAP response ok */
181 #define CHAP_FAILURE		4	/* CHAP response failed */
182 
183 #define CHAP_MD5		5	/* hash algorithm - MD5 */
184 
185 #define CISCO_MULTICAST		0x8f	/* Cisco multicast address */
186 #define CISCO_UNICAST		0x0f	/* Cisco unicast address */
187 #define CISCO_KEEPALIVE		0x8035	/* Cisco keepalive protocol */
188 #define CISCO_ADDR_REQ		0	/* Cisco address request */
189 #define CISCO_ADDR_REPLY	1	/* Cisco address reply */
190 #define CISCO_KEEPALIVE_REQ	2	/* Cisco keepalive request */
191 
192 /* states are named and numbered according to RFC 1661 */
193 #define STATE_INITIAL	0
194 #define STATE_STARTING	1
195 #define STATE_CLOSED	2
196 #define STATE_STOPPED	3
197 #define STATE_CLOSING	4
198 #define STATE_STOPPING	5
199 #define STATE_REQ_SENT	6
200 #define STATE_ACK_RCVD	7
201 #define STATE_ACK_SENT	8
202 #define STATE_OPENED	9
203 
204 struct ppp_header {
205 	u_char address;
206 	u_char control;
207 	u_short protocol;
208 };
209 #define PPP_HEADER_LEN          sizeof (struct ppp_header)
210 
211 struct lcp_header {
212 	u_char type;
213 	u_char ident;
214 	u_short len;
215 };
216 #define LCP_HEADER_LEN          sizeof (struct lcp_header)
217 
218 struct cisco_packet {
219 	u_int32_t type;
220 	u_int32_t par1;
221 	u_int32_t par2;
222 	u_short rel;
223 	u_short time0;
224 	u_short time1;
225 };
226 #define CISCO_PACKET_LEN 18
227 
228 /*
229  * We follow the spelling and capitalization of RFC 1661 here, to make
230  * it easier comparing with the standard.  Please refer to this RFC in
231  * case you can't make sense out of these abbreviation; it will also
232  * explain the semantics related to the various events and actions.
233  */
234 struct cp {
235 	u_short	proto;		/* PPP control protocol number */
236 	u_char protoidx;	/* index into state table in struct sppp */
237 	u_char flags;
238 #define CP_LCP		0x01	/* this is the LCP */
239 #define CP_AUTH		0x02	/* this is an authentication protocol */
240 #define CP_NCP		0x04	/* this is a NCP */
241 #define CP_QUAL		0x08	/* this is a quality reporting protocol */
242 	const char *name;	/* name of this control protocol */
243 	/* event handlers */
244 	void	(*Up)(struct sppp *sp);
245 	void	(*Down)(struct sppp *sp);
246 	void	(*Open)(struct sppp *sp);
247 	void	(*Close)(struct sppp *sp);
248 	void	(*TO)(void *sp);
249 	int	(*RCR)(struct sppp *sp, struct lcp_header *h, int len);
250 	void	(*RCN_rej)(struct sppp *sp, struct lcp_header *h, int len);
251 	void	(*RCN_nak)(struct sppp *sp, struct lcp_header *h, int len);
252 	/* actions */
253 	void	(*tlu)(struct sppp *sp);
254 	void	(*tld)(struct sppp *sp);
255 	void	(*tls)(struct sppp *sp);
256 	void	(*tlf)(struct sppp *sp);
257 	void	(*scr)(struct sppp *sp);
258 };
259 
260 static struct sppp *spppq;
261 #if defined (__OpenBSD__)
262 static struct timeout keepalive_ch;
263 #endif
264 #if defined (__FreeBSD__)
265 static struct callout_handle keepalive_ch;
266 #endif
267 
268 #if defined (__FreeBSD__)
269 #define	SPP_FMT		"%s%d: "
270 #define	SPP_ARGS(ifp)	(ifp)->if_name, (ifp)->if_unit
271 #else
272 #define	SPP_FMT		"%s: "
273 #define	SPP_ARGS(ifp)	(ifp)->if_xname
274 #endif
275 
276 /*
277  * The following disgusting hack gets around the problem that IP TOS
278  * can't be set yet.  We want to put "interactive" traffic on a high
279  * priority queue.  To decide if traffic is interactive, we check that
280  * a) it is TCP and b) one of its ports is telnet, rlogin or ftp control.
281  *
282  * XXX is this really still necessary?  - joerg -
283  */
284 static u_short interactive_ports[8] = {
285 	0,	513,	0,	0,
286 	0,	21,	0,	23,
287 };
288 #define INTERACTIVE(p) (interactive_ports[(p) & 7] == (p))
289 
290 /* almost every function needs these */
291 #define STDDCL							\
292 	struct ifnet *ifp = &sp->pp_if;				\
293 	int debug = ifp->if_flags & IFF_DEBUG
294 
295 HIDE int sppp_output(struct ifnet *ifp, struct mbuf *m,
296 		       struct sockaddr *dst, struct rtentry *rt);
297 
298 HIDE void sppp_cisco_send(struct sppp *sp, u_int32_t type, u_int32_t par1, u_int32_t par2);
299 HIDE void sppp_cisco_input(struct sppp *sp, struct mbuf *m);
300 
301 HIDE void sppp_cp_input(const struct cp *cp, struct sppp *sp,
302 			  struct mbuf *m);
303 HIDE void sppp_cp_send(struct sppp *sp, u_short proto, u_char type,
304 			 u_char ident, u_short len, void *data);
305 #ifdef notyet
306 HIDE void sppp_cp_timeout(void *arg);
307 #endif
308 HIDE void sppp_cp_change_state(const struct cp *cp, struct sppp *sp,
309 				 int newstate);
310 HIDE void sppp_auth_send(const struct cp *cp,
311 			   struct sppp *sp, unsigned int type, u_int id,
312 			   ...);
313 
314 HIDE void sppp_up_event(const struct cp *cp, struct sppp *sp);
315 HIDE void sppp_down_event(const struct cp *cp, struct sppp *sp);
316 HIDE void sppp_open_event(const struct cp *cp, struct sppp *sp);
317 HIDE void sppp_close_event(const struct cp *cp, struct sppp *sp);
318 HIDE void sppp_increasing_timeout(const struct cp *cp, struct sppp *sp);
319 HIDE void sppp_to_event(const struct cp *cp, struct sppp *sp);
320 
321 HIDE void sppp_null(struct sppp *sp);
322 
323 HIDE void sppp_lcp_init(struct sppp *sp);
324 HIDE void sppp_lcp_up(struct sppp *sp);
325 HIDE void sppp_lcp_down(struct sppp *sp);
326 HIDE void sppp_lcp_open(struct sppp *sp);
327 HIDE void sppp_lcp_close(struct sppp *sp);
328 HIDE void sppp_lcp_TO(void *sp);
329 HIDE int sppp_lcp_RCR(struct sppp *sp, struct lcp_header *h, int len);
330 HIDE void sppp_lcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len);
331 HIDE void sppp_lcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len);
332 HIDE void sppp_lcp_tlu(struct sppp *sp);
333 HIDE void sppp_lcp_tld(struct sppp *sp);
334 HIDE void sppp_lcp_tls(struct sppp *sp);
335 HIDE void sppp_lcp_tlf(struct sppp *sp);
336 HIDE void sppp_lcp_scr(struct sppp *sp);
337 HIDE void sppp_lcp_check_and_close(struct sppp *sp);
338 HIDE int sppp_ncp_check(struct sppp *sp);
339 
340 HIDE void sppp_ipcp_init(struct sppp *sp);
341 HIDE void sppp_ipcp_up(struct sppp *sp);
342 HIDE void sppp_ipcp_down(struct sppp *sp);
343 HIDE void sppp_ipcp_open(struct sppp *sp);
344 HIDE void sppp_ipcp_close(struct sppp *sp);
345 HIDE void sppp_ipcp_TO(void *sp);
346 HIDE int sppp_ipcp_RCR(struct sppp *sp, struct lcp_header *h, int len);
347 HIDE void sppp_ipcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len);
348 HIDE void sppp_ipcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len);
349 HIDE void sppp_ipcp_tlu(struct sppp *sp);
350 HIDE void sppp_ipcp_tld(struct sppp *sp);
351 HIDE void sppp_ipcp_tls(struct sppp *sp);
352 HIDE void sppp_ipcp_tlf(struct sppp *sp);
353 HIDE void sppp_ipcp_scr(struct sppp *sp);
354 
355 HIDE void sppp_ipv6cp_init(struct sppp *sp);
356 HIDE void sppp_ipv6cp_up(struct sppp *sp);
357 HIDE void sppp_ipv6cp_down(struct sppp *sp);
358 HIDE void sppp_ipv6cp_open(struct sppp *sp);
359 HIDE void sppp_ipv6cp_close(struct sppp *sp);
360 HIDE void sppp_ipv6cp_TO(void *sp);
361 HIDE int sppp_ipv6cp_RCR(struct sppp *sp, struct lcp_header *h, int len);
362 HIDE void sppp_ipv6cp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len);
363 HIDE void sppp_ipv6cp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len);
364 HIDE void sppp_ipv6cp_tlu(struct sppp *sp);
365 HIDE void sppp_ipv6cp_tld(struct sppp *sp);
366 HIDE void sppp_ipv6cp_tls(struct sppp *sp);
367 HIDE void sppp_ipv6cp_tlf(struct sppp *sp);
368 HIDE void sppp_ipv6cp_scr(struct sppp *sp);
369 HIDE const char *sppp_ipv6cp_opt_name(u_char opt);
370 HIDE void sppp_get_ip6_addrs(struct sppp *sp, struct in6_addr *src,
371 			       struct in6_addr *dst, struct in6_addr *srcmask);
372 HIDE void sppp_set_ip6_addr(struct sppp *sp, const struct in6_addr *src);
373 HIDE void sppp_gen_ip6_addr(struct sppp *sp, struct in6_addr *addr);
374 HIDE void sppp_suggest_ip6_addr(struct sppp *sp, struct in6_addr *suggest);
375 
376 HIDE void sppp_pap_input(struct sppp *sp, struct mbuf *m);
377 HIDE void sppp_pap_init(struct sppp *sp);
378 HIDE void sppp_pap_open(struct sppp *sp);
379 HIDE void sppp_pap_close(struct sppp *sp);
380 HIDE void sppp_pap_TO(void *sp);
381 HIDE void sppp_pap_my_TO(void *sp);
382 HIDE void sppp_pap_tlu(struct sppp *sp);
383 HIDE void sppp_pap_tld(struct sppp *sp);
384 HIDE void sppp_pap_scr(struct sppp *sp);
385 
386 HIDE void sppp_chap_input(struct sppp *sp, struct mbuf *m);
387 HIDE void sppp_chap_init(struct sppp *sp);
388 HIDE void sppp_chap_open(struct sppp *sp);
389 HIDE void sppp_chap_close(struct sppp *sp);
390 HIDE void sppp_chap_TO(void *sp);
391 HIDE void sppp_chap_tlu(struct sppp *sp);
392 HIDE void sppp_chap_tld(struct sppp *sp);
393 HIDE void sppp_chap_scr(struct sppp *sp);
394 
395 HIDE const char *sppp_auth_type_name(u_short proto, u_char type);
396 HIDE const char *sppp_cp_type_name(u_char type);
397 HIDE const char *sppp_dotted_quad(u_int32_t addr);
398 HIDE const char *sppp_ipcp_opt_name(u_char opt);
399 HIDE const char *sppp_lcp_opt_name(u_char opt);
400 HIDE const char *sppp_phase_name(enum ppp_phase phase);
401 HIDE const char *sppp_proto_name(u_short proto);
402 HIDE const char *sppp_state_name(int state);
403 HIDE int sppp_get_params(struct sppp *sp, struct ifreq *data);
404 HIDE int sppp_set_params(struct sppp *sp, struct ifreq *data);
405 HIDE void sppp_get_ip_addrs(struct sppp *sp, u_int32_t *src, u_int32_t *dst,
406 			      u_int32_t *srcmask);
407 HIDE void sppp_keepalive(void *dummy);
408 HIDE void sppp_phase_network(struct sppp *sp);
409 HIDE void sppp_print_bytes(const u_char *p, u_short len);
410 HIDE void sppp_print_string(const char *p, u_short len);
411 HIDE void sppp_qflush(struct ifqueue *ifq);
412 int sppp_update_gw_walker(struct radix_node *rn, void *arg, u_int);
413 void sppp_update_gw(struct ifnet *ifp);
414 HIDE void sppp_set_ip_addrs(void *, void *);
415 HIDE void sppp_clear_ip_addrs(struct sppp *sp);
416 HIDE void sppp_set_phase(struct sppp *sp);
417 
418 /* our control protocol descriptors */
419 static const struct cp lcp = {
420 	PPP_LCP, IDX_LCP, CP_LCP, "lcp",
421 	sppp_lcp_up, sppp_lcp_down, sppp_lcp_open, sppp_lcp_close,
422 	sppp_lcp_TO, sppp_lcp_RCR, sppp_lcp_RCN_rej, sppp_lcp_RCN_nak,
423 	sppp_lcp_tlu, sppp_lcp_tld, sppp_lcp_tls, sppp_lcp_tlf,
424 	sppp_lcp_scr
425 };
426 
427 static const struct cp ipcp = {
428 	PPP_IPCP, IDX_IPCP,
429 #ifdef INET	/* don't run IPCP if there's no IPv4 support */
430 	CP_NCP,
431 #else
432 	0,
433 #endif
434 	"ipcp",
435 	sppp_ipcp_up, sppp_ipcp_down, sppp_ipcp_open, sppp_ipcp_close,
436 	sppp_ipcp_TO, sppp_ipcp_RCR, sppp_ipcp_RCN_rej, sppp_ipcp_RCN_nak,
437 	sppp_ipcp_tlu, sppp_ipcp_tld, sppp_ipcp_tls, sppp_ipcp_tlf,
438 	sppp_ipcp_scr
439 };
440 
441 static const struct cp ipv6cp = {
442 	PPP_IPV6CP, IDX_IPV6CP,
443 #ifdef INET6	/*don't run IPv6CP if there's no IPv6 support*/
444 	CP_NCP,
445 #else
446 	0,
447 #endif
448 	"ipv6cp",
449 	sppp_ipv6cp_up, sppp_ipv6cp_down, sppp_ipv6cp_open, sppp_ipv6cp_close,
450 	sppp_ipv6cp_TO, sppp_ipv6cp_RCR, sppp_ipv6cp_RCN_rej, sppp_ipv6cp_RCN_nak,
451 	sppp_ipv6cp_tlu, sppp_ipv6cp_tld, sppp_ipv6cp_tls, sppp_ipv6cp_tlf,
452 	sppp_ipv6cp_scr
453 };
454 
455 static const struct cp pap = {
456 	PPP_PAP, IDX_PAP, CP_AUTH, "pap",
457 	sppp_null, sppp_null, sppp_pap_open, sppp_pap_close,
458 	sppp_pap_TO, 0, 0, 0,
459 	sppp_pap_tlu, sppp_pap_tld, sppp_null, sppp_null,
460 	sppp_pap_scr
461 };
462 
463 static const struct cp chap = {
464 	PPP_CHAP, IDX_CHAP, CP_AUTH, "chap",
465 	sppp_null, sppp_null, sppp_chap_open, sppp_chap_close,
466 	sppp_chap_TO, 0, 0, 0,
467 	sppp_chap_tlu, sppp_chap_tld, sppp_null, sppp_null,
468 	sppp_chap_scr
469 };
470 
471 static const struct cp *cps[IDX_COUNT] = {
472 	&lcp,			/* IDX_LCP */
473 	&ipcp,			/* IDX_IPCP */
474 	&ipv6cp,		/* IDX_IPV6CP */
475 	&pap,			/* IDX_PAP */
476 	&chap,			/* IDX_CHAP */
477 };
478 
479 
480 /*
481  * Exported functions, comprising our interface to the lower layer.
482  */
483 
484 #if defined(__OpenBSD__)
485 /* Workaround */
486 void
487 spppattach(struct ifnet *ifp)
488 {
489 }
490 #endif
491 
492 /*
493  * Process the received packet.
494  */
495 void
496 sppp_input(struct ifnet *ifp, struct mbuf *m)
497 {
498 	struct ppp_header *h, ht;
499 	struct ifqueue *inq = 0;
500 	struct sppp *sp = (struct sppp *)ifp;
501 	struct timeval tv;
502 	int debug = ifp->if_flags & IFF_DEBUG;
503 	int s;
504 
505 	if (ifp->if_flags & IFF_UP) {
506 		/* Count received bytes, add hardware framing */
507 		ifp->if_ibytes += m->m_pkthdr.len + sp->pp_framebytes;
508 		/* Note time of last receive */
509 		getmicrouptime(&tv);
510 		sp->pp_last_receive = tv.tv_sec;
511 	}
512 
513 	if (m->m_pkthdr.len <= PPP_HEADER_LEN) {
514 		/* Too small packet, drop it. */
515 		if (debug)
516 			log(LOG_DEBUG,
517 			    SPP_FMT "input packet is too small, %d bytes\n",
518 			    SPP_ARGS(ifp), m->m_pkthdr.len);
519 	  drop:
520 		++ifp->if_ierrors;
521 		++ifp->if_iqdrops;
522 		m_freem (m);
523 		return;
524 	}
525 
526 	/* mark incoming routing domain */
527 	m->m_pkthdr.rdomain = ifp->if_rdomain;
528 
529 	if (sp->pp_flags & PP_NOFRAMING) {
530 		memcpy(&ht.protocol, mtod(m, char *), sizeof(ht.protocol));
531 		m_adj(m, 2);
532 		ht.control = PPP_UI;
533 		ht.address = PPP_ALLSTATIONS;
534 		h = &ht;
535 	} else {
536 		/* Get PPP header. */
537 		h = mtod (m, struct ppp_header*);
538 		m_adj (m, PPP_HEADER_LEN);
539 	}
540 
541 	/* preserve the alignment */
542 	if (m->m_len < m->m_pkthdr.len) {
543 		m = m_pullup(m, m->m_pkthdr.len);
544 		if (m == NULL) {
545 			if (debug)
546 				log(LOG_DEBUG,
547 				    SPP_FMT "Failed to align packet!\n", SPP_ARGS(ifp));
548 			++ifp->if_ierrors;
549 			++ifp->if_iqdrops;
550 			return;
551 		}
552 	}
553 
554 	switch (h->address) {
555 	case PPP_ALLSTATIONS:
556 		if (h->control != PPP_UI)
557 			goto invalid;
558 		if (sp->pp_flags & PP_CISCO) {
559 			if (debug)
560 				log(LOG_DEBUG,
561 				    SPP_FMT "PPP packet in Cisco mode "
562 				    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
563 				    SPP_ARGS(ifp),
564 				    h->address, h->control, ntohs(h->protocol));
565 			goto drop;
566 		}
567 		switch (ntohs (h->protocol)) {
568 		default:
569 			if (sp->state[IDX_LCP] == STATE_OPENED)
570 				sppp_cp_send (sp, PPP_LCP, PROTO_REJ,
571 				    ++sp->pp_seq, 2, &h->protocol);
572 			if (debug)
573 				log(LOG_DEBUG,
574 				    SPP_FMT "invalid input protocol "
575 				    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
576 				    SPP_ARGS(ifp),
577 				    h->address, h->control, ntohs(h->protocol));
578 			++ifp->if_noproto;
579 			goto drop;
580 		case PPP_LCP:
581 			sppp_cp_input(&lcp, sp, m);
582 			m_freem (m);
583 			return;
584 		case PPP_PAP:
585 			if (sp->pp_phase >= PHASE_AUTHENTICATE)
586 				sppp_pap_input(sp, m);
587 			m_freem (m);
588 			return;
589 		case PPP_CHAP:
590 			if (sp->pp_phase >= PHASE_AUTHENTICATE)
591 				sppp_chap_input(sp, m);
592 			m_freem (m);
593 			return;
594 #ifdef INET
595 		case PPP_IPCP:
596 			if (sp->pp_phase == PHASE_NETWORK)
597 				sppp_cp_input(&ipcp, sp, m);
598 			m_freem (m);
599 			return;
600 		case PPP_IP:
601 			if (sp->state[IDX_IPCP] == STATE_OPENED) {
602 				schednetisr (NETISR_IP);
603 				inq = &ipintrq;
604 				sp->pp_last_activity = tv.tv_sec;
605 			}
606 			break;
607 #endif
608 #ifdef INET6
609 		case PPP_IPV6CP:
610 			if (sp->pp_phase == PHASE_NETWORK)
611 				sppp_cp_input(&ipv6cp, sp, m);
612 			m_freem (m);
613 			return;
614 		case PPP_IPV6:
615 			if (sp->state[IDX_IPV6CP] == STATE_OPENED) {
616 				schednetisr (NETISR_IPV6);
617 				inq = &ip6intrq;
618 				sp->pp_last_activity = tv.tv_sec;
619 			}
620 			break;
621 #endif
622 		}
623 		break;
624 	case CISCO_MULTICAST:
625 	case CISCO_UNICAST:
626 		/* Don't check the control field here (RFC 1547). */
627 		if (! (sp->pp_flags & PP_CISCO)) {
628 			if (debug)
629 				log(LOG_DEBUG,
630 				    SPP_FMT "Cisco packet in PPP mode "
631 				    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
632 				    SPP_ARGS(ifp),
633 				    h->address, h->control, ntohs(h->protocol));
634 			goto drop;
635 		}
636 		switch (ntohs (h->protocol)) {
637 		default:
638 			++ifp->if_noproto;
639 			goto invalid;
640 		case CISCO_KEEPALIVE:
641 			sppp_cisco_input ((struct sppp*) ifp, m);
642 			m_freem (m);
643 			return;
644 #ifdef INET
645 		case ETHERTYPE_IP:
646 			schednetisr (NETISR_IP);
647 			inq = &ipintrq;
648 			break;
649 #endif
650 #ifdef INET6
651 		case ETHERTYPE_IPV6:
652 			schednetisr (NETISR_IPV6);
653 			inq = &ip6intrq;
654 			break;
655 #endif
656 		}
657 		break;
658 	default:        /* Invalid PPP packet. */
659 	  invalid:
660 		if (debug)
661 			log(LOG_DEBUG,
662 			    SPP_FMT "invalid input packet "
663 			    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
664 			    SPP_ARGS(ifp),
665 			    h->address, h->control, ntohs(h->protocol));
666 		goto drop;
667 	}
668 
669 	if (! (ifp->if_flags & IFF_UP) || ! inq)
670 		goto drop;
671 
672 	/* Check queue. */
673 	s = splnet();
674 	if (IF_QFULL (inq)) {
675 		/* Queue overflow. */
676 		IF_DROP(inq);
677 		splx(s);
678 		if (debug)
679 			log(LOG_DEBUG, SPP_FMT "protocol queue overflow\n",
680 				SPP_ARGS(ifp));
681 		if (!inq->ifq_congestion)
682 			if_congestion(inq);
683 		goto drop;
684 	}
685 	IF_ENQUEUE(inq, m);
686 	splx(s);
687 }
688 
689 /*
690  * Enqueue transmit packet.
691  */
692 HIDE int
693 sppp_output(struct ifnet *ifp, struct mbuf *m,
694 	    struct sockaddr *dst, struct rtentry *rt)
695 {
696 	struct sppp *sp = (struct sppp*) ifp;
697 	struct ppp_header *h;
698 	struct ifqueue *ifq = NULL;
699 	struct timeval tv;
700 	int s, len, rv = 0;
701 	u_int16_t protocol;
702 
703 #ifdef DIAGNOSTIC
704 	if (ifp->if_rdomain != rtable_l2(m->m_pkthdr.rdomain)) {
705 		printf("%s: trying to send packet on wrong domain. "
706 		    "if %d vs. mbuf %d, AF %d\n", ifp->if_xname,
707 		    ifp->if_rdomain, rtable_l2(m->m_pkthdr.rdomain),
708 		    dst->sa_family);
709 	}
710 #endif
711 
712 	s = splnet();
713 
714 	getmicrouptime(&tv);
715 	sp->pp_last_activity = tv.tv_sec;
716 
717 	if ((ifp->if_flags & IFF_UP) == 0 ||
718 	    (ifp->if_flags & (IFF_RUNNING | IFF_AUTO)) == 0) {
719 		m_freem (m);
720 		splx (s);
721 		return (ENETDOWN);
722 	}
723 
724 	if ((ifp->if_flags & (IFF_RUNNING | IFF_AUTO)) == IFF_AUTO) {
725 		/*
726 		 * Interface is not yet running, but auto-dial.  Need
727 		 * to start LCP for it.
728 		 */
729 		ifp->if_flags |= IFF_RUNNING;
730 		splx(s);
731 		lcp.Open(sp);
732 		s = splnet();
733 	}
734 
735 #ifdef INET
736 	/*
737 	 * Put low delay, telnet, rlogin and ftp control packets
738 	 * in front of the queue.
739 	 */
740 	if (dst->sa_family == AF_INET) {
741 		struct ip *ip = NULL;
742 		struct tcphdr *th = NULL;
743 
744 		if (m->m_len >= sizeof(struct ip)) {
745 			ip = mtod(m, struct ip *);
746 			if (ip->ip_p == IPPROTO_TCP &&
747 			    m->m_len >= sizeof(struct ip) + (ip->ip_hl << 2) +
748 			    sizeof(struct tcphdr)) {
749 				th = (struct tcphdr *)
750 				    ((caddr_t)ip + (ip->ip_hl << 2));
751 			}
752 		}
753 		/*
754 		 * When using dynamic local IP address assignment by using
755 		 * 0.0.0.0 as a local address, the first TCP session will
756 		 * not connect because the local TCP checksum is computed
757 		 * using 0.0.0.0 which will later become our real IP address
758 		 * so the TCP checksum computed at the remote end will
759 		 * become invalid. So we
760 		 * - don't let packets with src ip addr 0 thru
761 		 * - we flag TCP packets with src ip 0 as an error
762 		 */
763 
764 		if(ip && ip->ip_src.s_addr == INADDR_ANY) {
765 			u_int8_t proto = ip->ip_p;
766 
767 			m_freem(m);
768 			splx(s);
769 			if(proto == IPPROTO_TCP)
770 				return (EADDRNOTAVAIL);
771 			else
772 				return (0);
773 		}
774 
775 		if (!IF_QFULL(&sp->pp_fastq) &&
776 		    ((ip && (ip->ip_tos & IPTOS_LOWDELAY)) ||
777 	    	      (th && (INTERACTIVE(ntohs(th->th_sport)) ||
778 	    	       INTERACTIVE(ntohs(th->th_dport))))))
779 			ifq = &sp->pp_fastq;
780 	}
781 #endif
782 
783 	if (sp->pp_flags & PP_NOFRAMING)
784 		goto skip_header;
785 	/*
786 	 * Prepend general data packet PPP header. For now, IP only.
787 	 */
788 	M_PREPEND (m, PPP_HEADER_LEN, M_DONTWAIT);
789 	if (!m) {
790 		if (ifp->if_flags & IFF_DEBUG)
791 			log(LOG_DEBUG, SPP_FMT "no memory for transmit header\n",
792 				SPP_ARGS(ifp));
793 		++ifp->if_oerrors;
794 		splx (s);
795 		return (ENOBUFS);
796 	}
797 	/*
798 	 * May want to check size of packet
799 	 * (albeit due to the implementation it's always enough)
800 	 */
801 	h = mtod (m, struct ppp_header*);
802 	if (sp->pp_flags & PP_CISCO) {
803 		h->address = CISCO_UNICAST;        /* unicast address */
804 		h->control = 0;
805 	} else {
806 		h->address = PPP_ALLSTATIONS;        /* broadcast address */
807 		h->control = PPP_UI;                 /* Unnumbered Info */
808 	}
809 
810  skip_header:
811 	switch (dst->sa_family) {
812 #ifdef INET
813 	case AF_INET:   /* Internet Protocol */
814 		if (sp->pp_flags & PP_CISCO)
815 			protocol = htons (ETHERTYPE_IP);
816 		else {
817 			/*
818 			 * Don't choke with an ENETDOWN early.  It's
819 			 * possible that we just started dialing out,
820 			 * so don't drop the packet immediately.  If
821 			 * we notice that we run out of buffer space
822 			 * below, we will however remember that we are
823 			 * not ready to carry IP packets, and return
824 			 * ENETDOWN, as opposed to ENOBUFS.
825 			 */
826 			protocol = htons(PPP_IP);
827 			if (sp->state[IDX_IPCP] != STATE_OPENED)
828 				rv = ENETDOWN;
829 		}
830 		break;
831 #endif
832 #ifdef INET6
833 	case AF_INET6:   /* Internet Protocol v6 */
834 		if (sp->pp_flags & PP_CISCO)
835 			protocol = htons (ETHERTYPE_IPV6);
836 		else {
837 			/*
838 			 * Don't choke with an ENETDOWN early.  It's
839 			 * possible that we just started dialing out,
840 			 * so don't drop the packet immediately.  If
841 			 * we notice that we run out of buffer space
842 			 * below, we will however remember that we are
843 			 * not ready to carry IPv6 packets, and return
844 			 * ENETDOWN, as opposed to ENOBUFS.
845 			 */
846 			protocol = htons(PPP_IPV6);
847 			if (sp->state[IDX_IPV6CP] != STATE_OPENED)
848 				rv = ENETDOWN;
849 		}
850 		break;
851 #endif
852 	default:
853 		m_freem(m);
854 		++ifp->if_oerrors;
855 		splx(s);
856 		return (EAFNOSUPPORT);
857 	}
858 
859 	if (sp->pp_flags & PP_NOFRAMING) {
860 		M_PREPEND(m, 2, M_DONTWAIT);
861 		if (m == NULL) {
862 			if (ifp->if_flags & IFF_DEBUG)
863 				log(LOG_DEBUG, SPP_FMT
864 				    "no memory for transmit header\n",
865 				    SPP_ARGS(ifp));
866 			++ifp->if_oerrors;
867 			splx(s);
868 			return (ENOBUFS);
869 		}
870 		*mtod(m, u_int16_t *) = protocol;
871 	} else
872 		h->protocol = protocol;
873 
874 	/*
875 	 * Queue message on interface, and start output if interface
876 	 * not yet active.
877 	 */
878 	len = m->m_pkthdr.len;
879 	if (ifq != NULL
880 #ifdef ALTQ
881 	    && ALTQ_IS_ENABLED(&ifp->if_snd) == 0
882 #endif
883 		) {
884 		if (IF_QFULL (ifq)) {
885 			IF_DROP (&ifp->if_snd);
886 			m_freem (m);
887 			if (rv == 0)
888 				rv = ENOBUFS;
889 		} else
890 			IF_ENQUEUE (ifq, m);
891 	} else
892 		IFQ_ENQUEUE(&ifp->if_snd, m, NULL, rv);
893 
894 	if (rv != 0) {
895 		++ifp->if_oerrors;
896 		splx (s);
897 		return (rv);
898 	}
899 
900 	if (!(ifp->if_flags & IFF_OACTIVE))
901 		(*ifp->if_start) (ifp);
902 
903 	/*
904 	 * Count output packets and bytes.
905 	 * The packet length includes header, FCS and 1 flag,
906 	 * according to RFC 1333.
907 	 */
908 	ifp->if_obytes += len + sp->pp_framebytes;
909 	splx (s);
910 	return (0);
911 }
912 
913 void
914 sppp_attach(struct ifnet *ifp)
915 {
916 	struct sppp *sp = (struct sppp*) ifp;
917 	int i;
918 
919 	/* Initialize keepalive handler. */
920 	if (! spppq) {
921 #if defined (__FreeBSD__)
922 		keepalive_ch = timeout(sppp_keepalive, 0, hz * 10);
923 #elif defined(__OpenBSD__)
924 		timeout_set(&keepalive_ch, sppp_keepalive, NULL);
925 		timeout_add_sec(&keepalive_ch, 10);
926 #endif
927 	}
928 
929 	/* Insert new entry into the keepalive list. */
930 	sp->pp_next = spppq;
931 	spppq = sp;
932 
933 	sp->pp_if.if_type = IFT_PPP;
934 	sp->pp_if.if_output = sppp_output;
935 	IFQ_SET_MAXLEN(&sp->pp_if.if_snd, 50);
936 	IFQ_SET_MAXLEN(&sp->pp_fastq, 50);
937 	IFQ_SET_MAXLEN(&sp->pp_cpq, 50);
938 	sp->pp_loopcnt = 0;
939 	sp->pp_alivecnt = 0;
940 	sp->pp_last_activity = 0;
941 	sp->pp_last_receive = 0;
942 	sp->pp_seq = 0;
943 	sp->pp_rseq = 0;
944 	sp->pp_phase = PHASE_DEAD;
945 	sp->pp_up = lcp.Up;
946 	sp->pp_down = lcp.Down;
947 
948 	for (i = 0; i < IDX_COUNT; i++)
949 		timeout_set(&sp->ch[i], (cps[i])->TO, (void *)sp);
950 	timeout_set(&sp->pap_my_to_ch, sppp_pap_my_TO, (void *)sp);
951 
952 	sppp_lcp_init(sp);
953 	sppp_ipcp_init(sp);
954 	sppp_ipv6cp_init(sp);
955 	sppp_pap_init(sp);
956 	sppp_chap_init(sp);
957 }
958 
959 void
960 sppp_detach(struct ifnet *ifp)
961 {
962 	struct sppp **q, *p, *sp = (struct sppp*) ifp;
963 	int i;
964 
965 	/* Remove the entry from the keepalive list. */
966 	for (q = &spppq; (p = *q); q = &p->pp_next)
967 		if (p == sp) {
968 			*q = p->pp_next;
969 			break;
970 		}
971 
972 	/* Stop keepalive handler. */
973 	if (! spppq)
974 		UNTIMEOUT(sppp_keepalive, 0, keepalive_ch);
975 
976 	for (i = 0; i < IDX_COUNT; i++)
977 		UNTIMEOUT((cps[i])->TO, (void *)sp, sp->ch[i]);
978 	UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
979 
980 	/* release authentication data */
981 	if (sp->myauth.name != NULL)
982 		free(sp->myauth.name, M_DEVBUF);
983 	if (sp->myauth.secret != NULL)
984 		free(sp->myauth.secret, M_DEVBUF);
985 	if (sp->hisauth.name != NULL)
986 		free(sp->hisauth.name, M_DEVBUF);
987 	if (sp->hisauth.secret != NULL)
988 		free(sp->hisauth.secret, M_DEVBUF);
989 }
990 
991 /*
992  * Flush the interface output queue.
993  */
994 void
995 sppp_flush(struct ifnet *ifp)
996 {
997 	struct sppp *sp = (struct sppp*) ifp;
998 
999 	IFQ_PURGE(&sp->pp_if.if_snd);
1000 	sppp_qflush (&sp->pp_fastq);
1001 	sppp_qflush (&sp->pp_cpq);
1002 }
1003 
1004 /*
1005  * Check if the output queue is empty.
1006  */
1007 int
1008 sppp_isempty(struct ifnet *ifp)
1009 {
1010 	struct sppp *sp = (struct sppp*) ifp;
1011 	int empty, s;
1012 
1013 	s = splnet();
1014 	empty = IF_IS_EMPTY(&sp->pp_fastq) && IF_IS_EMPTY(&sp->pp_cpq) &&
1015 		IFQ_IS_EMPTY(&sp->pp_if.if_snd);
1016 	splx(s);
1017 	return (empty);
1018 }
1019 
1020 /*
1021  * Get next packet to send.
1022  */
1023 struct mbuf *
1024 sppp_dequeue(struct ifnet *ifp)
1025 {
1026 	struct sppp *sp = (struct sppp*) ifp;
1027 	struct mbuf *m;
1028 	int s;
1029 
1030 	s = splnet();
1031 	/*
1032 	 * Process only the control protocol queue until we have at
1033 	 * least one NCP open.
1034 	 *
1035 	 * Do always serve all three queues in Cisco mode.
1036 	 */
1037 	IF_DEQUEUE(&sp->pp_cpq, m);
1038 	if (m == NULL &&
1039 	    (sppp_ncp_check(sp) || (sp->pp_flags & PP_CISCO) != 0)) {
1040 		IF_DEQUEUE(&sp->pp_fastq, m);
1041 		if (m == NULL)
1042 			IFQ_DEQUEUE (&sp->pp_if.if_snd, m);
1043 	}
1044 	splx(s);
1045 	return m;
1046 }
1047 
1048 /*
1049  * Pick the next packet, do not remove it from the queue.
1050  */
1051 struct mbuf *
1052 sppp_pick(struct ifnet *ifp)
1053 {
1054 	struct sppp *sp = (struct sppp*)ifp;
1055 	struct mbuf *m;
1056 	int s;
1057 
1058 	s = splnet();
1059 	IF_POLL(&sp->pp_cpq, m);
1060 	if (m == NULL &&
1061 	    (sp->pp_phase == PHASE_NETWORK ||
1062 	     (sp->pp_flags & PP_CISCO) != 0)) {
1063 		IF_POLL(&sp->pp_fastq, m);
1064 		if ((m) == NULL)
1065 			IFQ_POLL(&sp->pp_if.if_snd, m);
1066 	}
1067 	splx (s);
1068 	return (m);
1069 }
1070 
1071 /*
1072  * Process an ioctl request.  Called on low priority level.
1073  */
1074 int
1075 sppp_ioctl(struct ifnet *ifp, u_long cmd, void *data)
1076 {
1077 	struct ifreq *ifr = (struct ifreq*) data;
1078 	struct sppp *sp = (struct sppp*) ifp;
1079 	int s, rv, going_up, going_down, newmode;
1080 
1081 	s = splnet();
1082 	rv = 0;
1083 	switch (cmd) {
1084 	case SIOCAIFADDR:
1085 	case SIOCSIFDSTADDR:
1086 		break;
1087 
1088 	case SIOCSIFADDR:
1089 		if_up(ifp);
1090 		/* FALLTHROUGH */
1091 
1092 	case SIOCSIFFLAGS:
1093 		going_up = (ifp->if_flags & IFF_UP) &&
1094 			(ifp->if_flags & IFF_RUNNING) == 0;
1095 		going_down = (ifp->if_flags & IFF_UP) == 0 &&
1096 			(ifp->if_flags & IFF_RUNNING);
1097 		newmode = ifp->if_flags & (IFF_AUTO | IFF_PASSIVE);
1098 		if (newmode == (IFF_AUTO | IFF_PASSIVE)) {
1099 			/* sanity */
1100 			newmode = IFF_PASSIVE;
1101 			ifp->if_flags &= ~IFF_AUTO;
1102 		}
1103 
1104 		if (going_up || going_down)
1105 			if (!(sp->pp_flags & PP_CISCO))
1106 				lcp.Close(sp);
1107 
1108 		if (going_up && newmode == 0) {
1109 			/* neither auto-dial nor passive */
1110 			ifp->if_flags |= IFF_RUNNING;
1111 			if (!(sp->pp_flags & PP_CISCO))
1112 				lcp.Open(sp);
1113 		} else if (going_down) {
1114 			sppp_flush(ifp);
1115 			ifp->if_flags &= ~IFF_RUNNING;
1116 		}
1117 		break;
1118 
1119 #ifdef SIOCSIFMTU
1120 	case SIOCSIFMTU:
1121 		if (ifr->ifr_mtu < 128 || ifr->ifr_mtu > sp->lcp.their_mru) {
1122 			splx(s);
1123 			return (EINVAL);
1124 		}
1125 		ifp->if_mtu = ifr->ifr_mtu;
1126 		break;
1127 #endif
1128 #ifdef SLIOCSETMTU
1129 	case SLIOCSETMTU:
1130 		if (*(short*)data < 128 || *(short*)data > sp->lcp.their_mru) {
1131 			splx(s);
1132 			return (EINVAL);
1133 		}
1134 		ifp->if_mtu = *(short*)data;
1135 		break;
1136 #endif
1137 #ifdef SIOCGIFMTU
1138 	case SIOCGIFMTU:
1139 		ifr->ifr_mtu = ifp->if_mtu;
1140 		break;
1141 #endif
1142 #ifdef SLIOCGETMTU
1143 	case SLIOCGETMTU:
1144 		*(short*)data = ifp->if_mtu;
1145 		break;
1146 #endif
1147 	case SIOCADDMULTI:
1148 	case SIOCDELMULTI:
1149 		break;
1150 
1151 	case SIOCGIFGENERIC:
1152 		rv = sppp_get_params(sp, ifr);
1153 		break;
1154 
1155 	case SIOCSIFGENERIC:
1156 		rv = sppp_set_params(sp, ifr);
1157 		break;
1158 
1159 	default:
1160 		rv = ENOTTY;
1161 	}
1162 	splx(s);
1163 	return rv;
1164 }
1165 
1166 
1167 /*
1168  * Cisco framing implementation.
1169  */
1170 
1171 /*
1172  * Handle incoming Cisco keepalive protocol packets.
1173  */
1174 HIDE void
1175 sppp_cisco_input(struct sppp *sp, struct mbuf *m)
1176 {
1177 	STDDCL;
1178 	struct cisco_packet *h;
1179 	u_int32_t me, mymask;
1180 
1181 	if (m->m_pkthdr.len < CISCO_PACKET_LEN) {
1182 		if (debug)
1183 			log(LOG_DEBUG,
1184 			    SPP_FMT "cisco invalid packet length: %d bytes\n",
1185 			    SPP_ARGS(ifp), m->m_pkthdr.len);
1186 		return;
1187 	}
1188 	h = mtod (m, struct cisco_packet*);
1189 	if (debug)
1190 		log(LOG_DEBUG,
1191 		    SPP_FMT "cisco input: %d bytes "
1192 		    "<0x%x 0x%x 0x%x 0x%x 0x%x-0x%x>\n",
1193 		    SPP_ARGS(ifp), m->m_pkthdr.len,
1194 		    ntohl(h->type), h->par1, h->par2, (u_int)h->rel,
1195 		    (u_int)h->time0, (u_int)h->time1);
1196 	switch (ntohl (h->type)) {
1197 	default:
1198 		if (debug)
1199 			addlog(SPP_FMT "cisco unknown packet type: 0x%x\n",
1200 			       SPP_ARGS(ifp), ntohl(h->type));
1201 		break;
1202 	case CISCO_ADDR_REPLY:
1203 		/* Reply on address request, ignore */
1204 		break;
1205 	case CISCO_KEEPALIVE_REQ:
1206 		sp->pp_alivecnt = 0;
1207 		sp->pp_rseq = ntohl (h->par1);
1208 		if (sp->pp_seq == sp->pp_rseq) {
1209 			/* Local and remote sequence numbers are equal.
1210 			 * Probably, the line is in loopback mode. */
1211 			if (sp->pp_loopcnt >= LOOPALIVECNT) {
1212 				log(LOG_INFO, SPP_FMT "loopback\n",
1213 					SPP_ARGS(ifp));
1214 				sp->pp_loopcnt = 0;
1215 				if (ifp->if_flags & IFF_UP) {
1216 					if_down (ifp);
1217 					sppp_qflush (&sp->pp_cpq);
1218 				}
1219 			}
1220 			++sp->pp_loopcnt;
1221 
1222 			/* Generate new local sequence number */
1223 #if defined (__FreeBSD__) || defined (__NetBSD__) || defined(__OpenBSD__)
1224 			sp->pp_seq = arc4random();
1225 #else
1226 			sp->pp_seq ^= time.tv_sec ^ time.tv_usec;
1227 #endif
1228 			break;
1229 		}
1230 		sp->pp_loopcnt = 0;
1231 		if (! (ifp->if_flags & IFF_UP) &&
1232 		    (ifp->if_flags & IFF_RUNNING)) {
1233 			if_up(ifp);
1234 			if (debug)
1235 				log(LOG_INFO, SPP_FMT "up\n", SPP_ARGS(ifp));
1236 		}
1237 		break;
1238 	case CISCO_ADDR_REQ:
1239 		sppp_get_ip_addrs(sp, &me, 0, &mymask);
1240 		if (me != 0)
1241 			sppp_cisco_send(sp, CISCO_ADDR_REPLY, me, mymask);
1242 		break;
1243 	}
1244 }
1245 
1246 /*
1247  * Send Cisco keepalive packet.
1248  */
1249 HIDE void
1250 sppp_cisco_send(struct sppp *sp, u_int32_t type, u_int32_t par1, u_int32_t par2)
1251 {
1252 	STDDCL;
1253 	struct ppp_header *h;
1254 	struct cisco_packet *ch;
1255 	struct mbuf *m;
1256 	struct timeval tv;
1257 
1258 	getmicrouptime(&tv);
1259 
1260 	MGETHDR (m, M_DONTWAIT, MT_DATA);
1261 	if (! m)
1262 		return;
1263 	m->m_pkthdr.len = m->m_len = PPP_HEADER_LEN + CISCO_PACKET_LEN;
1264 	m->m_pkthdr.rcvif = 0;
1265 
1266 	h = mtod (m, struct ppp_header*);
1267 	h->address = CISCO_MULTICAST;
1268 	h->control = 0;
1269 	h->protocol = htons (CISCO_KEEPALIVE);
1270 
1271 	ch = (struct cisco_packet*) (h + 1);
1272 	ch->type = htonl (type);
1273 	ch->par1 = htonl (par1);
1274 	ch->par2 = htonl (par2);
1275 	ch->rel = -1;
1276 
1277 	ch->time0 = htons ((u_short) (tv.tv_sec >> 16));
1278 	ch->time1 = htons ((u_short) tv.tv_sec);
1279 
1280 	if (debug)
1281 		log(LOG_DEBUG, SPP_FMT
1282 		    "cisco output: <0x%lx 0x%lx 0x%lx 0x%x 0x%x-0x%x>\n",
1283 			SPP_ARGS(ifp), ntohl(ch->type), ch->par1, ch->par2,
1284 			(u_int)ch->rel, (u_int)ch->time0, (u_int)ch->time1);
1285 
1286 	if (IF_QFULL (&sp->pp_cpq)) {
1287 		IF_DROP (&sp->pp_fastq);
1288 		IF_DROP (&ifp->if_snd);
1289 		m_freem (m);
1290 		m = NULL;
1291 	} else
1292 		IF_ENQUEUE (&sp->pp_cpq, m);
1293 	if (! (ifp->if_flags & IFF_OACTIVE))
1294 		(*ifp->if_start) (ifp);
1295 	if (m != NULL)
1296 		ifp->if_obytes += m->m_pkthdr.len + sp->pp_framebytes;
1297 }
1298 
1299 /*
1300  * PPP protocol implementation.
1301  */
1302 
1303 /*
1304  * Send PPP control protocol packet.
1305  */
1306 HIDE void
1307 sppp_cp_send(struct sppp *sp, u_short proto, u_char type,
1308 	     u_char ident, u_short len, void *data)
1309 {
1310 	STDDCL;
1311 	struct ppp_header *h;
1312 	struct lcp_header *lh;
1313 	struct mbuf *m;
1314 	size_t pkthdrlen;
1315 
1316 	pkthdrlen = (sp->pp_flags & PP_NOFRAMING) ? 2 : PPP_HEADER_LEN;
1317 
1318 	if (len > MHLEN - pkthdrlen - LCP_HEADER_LEN)
1319 		len = MHLEN - pkthdrlen - LCP_HEADER_LEN;
1320 	MGETHDR (m, M_DONTWAIT, MT_DATA);
1321 	if (! m)
1322 		return;
1323 	m->m_pkthdr.len = m->m_len = pkthdrlen + LCP_HEADER_LEN + len;
1324 	m->m_pkthdr.rcvif = 0;
1325 
1326 	if (sp->pp_flags & PP_NOFRAMING) {
1327 		*mtod(m, u_int16_t *) = htons(proto);
1328 		lh = (struct lcp_header *)(mtod(m, u_int8_t *) + 2);
1329 	} else {
1330 		h = mtod (m, struct ppp_header*);
1331 		h->address = PPP_ALLSTATIONS;	/* broadcast address */
1332 		h->control = PPP_UI;		/* Unnumbered Info */
1333 		h->protocol = htons (proto);	/* Link Control Protocol */
1334 		lh = (struct lcp_header*) (h + 1);
1335 	}
1336 	lh->type = type;
1337 	lh->ident = ident;
1338 	lh->len = htons (LCP_HEADER_LEN + len);
1339 	if (len)
1340 		bcopy (data, lh+1, len);
1341 
1342 	if (debug) {
1343 		log(LOG_DEBUG, SPP_FMT "%s output <%s id=0x%x len=%d",
1344 		    SPP_ARGS(ifp),
1345 		    sppp_proto_name(proto),
1346 		    sppp_cp_type_name (lh->type), lh->ident,
1347 		    ntohs (lh->len));
1348 		if (len)
1349 			sppp_print_bytes ((u_char*) (lh+1), len);
1350 		addlog(">\n");
1351 	}
1352 	if (IF_QFULL (&sp->pp_cpq)) {
1353 		IF_DROP (&sp->pp_fastq);
1354 		IF_DROP (&ifp->if_snd);
1355 		m_freem (m);
1356 		++ifp->if_oerrors;
1357 		m = NULL;
1358 	} else
1359 		IF_ENQUEUE (&sp->pp_cpq, m);
1360 	if (!(ifp->if_flags & IFF_OACTIVE))
1361 		(*ifp->if_start) (ifp);
1362 	if (m != NULL)
1363 		ifp->if_obytes += m->m_pkthdr.len + sp->pp_framebytes;
1364 }
1365 
1366 /*
1367  * Handle incoming PPP control protocol packets.
1368  */
1369 HIDE void
1370 sppp_cp_input(const struct cp *cp, struct sppp *sp, struct mbuf *m)
1371 {
1372 	STDDCL;
1373 	struct lcp_header *h;
1374 	int len = m->m_pkthdr.len;
1375 	int rv;
1376 	u_char *p;
1377 	u_long nmagic;
1378 
1379 	if (len < 4) {
1380 		if (debug)
1381 			log(LOG_DEBUG,
1382 			    SPP_FMT "%s invalid packet length: %d bytes\n",
1383 			    SPP_ARGS(ifp), cp->name, len);
1384 		return;
1385 	}
1386 	h = mtod (m, struct lcp_header*);
1387 	if (debug) {
1388 		log(LOG_DEBUG,
1389 		    SPP_FMT "%s input(%s): <%s id=0x%x len=%d",
1390 		    SPP_ARGS(ifp), cp->name,
1391 		    sppp_state_name(sp->state[cp->protoidx]),
1392 		    sppp_cp_type_name (h->type), h->ident, ntohs (h->len));
1393 		if (len > 4)
1394 			sppp_print_bytes ((u_char*) (h+1), len-4);
1395 		addlog(">\n");
1396 	}
1397 	if (len > ntohs (h->len))
1398 		len = ntohs (h->len);
1399 	p = (u_char *)(h + 1);
1400 	switch (h->type) {
1401 	case CONF_REQ:
1402 		if (len < 4) {
1403 			if (debug)
1404 				addlog(SPP_FMT "%s invalid conf-req length %d\n",
1405 				       SPP_ARGS(ifp), cp->name,
1406 				       len);
1407 			++ifp->if_ierrors;
1408 			break;
1409 		}
1410 		/* handle states where RCR doesn't get a SCA/SCN */
1411 		switch (sp->state[cp->protoidx]) {
1412 		case STATE_CLOSING:
1413 		case STATE_STOPPING:
1414 			return;
1415 		case STATE_CLOSED:
1416 			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident,
1417 				     0, 0);
1418 			return;
1419 		}
1420 		rv = (cp->RCR)(sp, h, len);
1421 		/* silently drop illegal packets */
1422 		if (rv == -1)
1423 			return;
1424 		switch (sp->state[cp->protoidx]) {
1425 		case STATE_OPENED:
1426 			sppp_cp_change_state(cp, sp, rv?
1427 					     STATE_ACK_SENT: STATE_REQ_SENT);
1428 			(cp->tld)(sp);
1429 			(cp->scr)(sp);
1430 			break;
1431 		case STATE_ACK_SENT:
1432 		case STATE_REQ_SENT:
1433 			sppp_cp_change_state(cp, sp, rv?
1434 					     STATE_ACK_SENT: STATE_REQ_SENT);
1435 			break;
1436 		case STATE_STOPPED:
1437 			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1438 			sppp_cp_change_state(cp, sp, rv?
1439 					     STATE_ACK_SENT: STATE_REQ_SENT);
1440 			(cp->scr)(sp);
1441 			break;
1442 		case STATE_ACK_RCVD:
1443 			if (rv) {
1444 				sppp_cp_change_state(cp, sp, STATE_OPENED);
1445 				if (debug)
1446 					log(LOG_DEBUG, SPP_FMT "%s tlu\n",
1447 					    SPP_ARGS(ifp),
1448 					    cp->name);
1449 				(cp->tlu)(sp);
1450 			} else
1451 				sppp_cp_change_state(cp, sp, STATE_ACK_RCVD);
1452 			break;
1453 		default:
1454 			/* printf(SPP_FMT "%s illegal %s in state %s\n",
1455 			       SPP_ARGS(ifp), cp->name,
1456 			       sppp_cp_type_name(h->type),
1457 			       sppp_state_name(sp->state[cp->protoidx])); */
1458 			++ifp->if_ierrors;
1459 		}
1460 		break;
1461 	case CONF_ACK:
1462 		if (h->ident != sp->confid[cp->protoidx]) {
1463 			if (debug)
1464 				addlog(SPP_FMT "%s id mismatch 0x%x != 0x%x\n",
1465 				       SPP_ARGS(ifp), cp->name,
1466 				       h->ident, sp->confid[cp->protoidx]);
1467 			++ifp->if_ierrors;
1468 			break;
1469 		}
1470 		switch (sp->state[cp->protoidx]) {
1471 		case STATE_CLOSED:
1472 		case STATE_STOPPED:
1473 			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident, 0, 0);
1474 			break;
1475 		case STATE_CLOSING:
1476 		case STATE_STOPPING:
1477 			break;
1478 		case STATE_REQ_SENT:
1479 			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1480 			sppp_cp_change_state(cp, sp, STATE_ACK_RCVD);
1481 			break;
1482 		case STATE_OPENED:
1483 			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1484 			(cp->tld)(sp);
1485 			(cp->scr)(sp);
1486 			break;
1487 		case STATE_ACK_RCVD:
1488 			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1489 			(cp->scr)(sp);
1490 			break;
1491 		case STATE_ACK_SENT:
1492 			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1493 			sppp_cp_change_state(cp, sp, STATE_OPENED);
1494 			if (debug)
1495 				log(LOG_DEBUG, SPP_FMT "%s tlu\n",
1496 				       SPP_ARGS(ifp), cp->name);
1497 			(cp->tlu)(sp);
1498 			break;
1499 		default:
1500 			/* printf(SPP_FMT "%s illegal %s in state %s\n",
1501 			       SPP_ARGS(ifp), cp->name,
1502 			       sppp_cp_type_name(h->type),
1503 			       sppp_state_name(sp->state[cp->protoidx])); */
1504 			++ifp->if_ierrors;
1505 		}
1506 		break;
1507 	case CONF_NAK:
1508 	case CONF_REJ:
1509 		if (h->ident != sp->confid[cp->protoidx]) {
1510 			if (debug)
1511 				addlog(SPP_FMT "%s id mismatch 0x%x != 0x%x\n",
1512 				       SPP_ARGS(ifp), cp->name,
1513 				       h->ident, sp->confid[cp->protoidx]);
1514 			++ifp->if_ierrors;
1515 			break;
1516 		}
1517 		if (h->type == CONF_NAK)
1518 			(cp->RCN_nak)(sp, h, len);
1519 		else /* CONF_REJ */
1520 			(cp->RCN_rej)(sp, h, len);
1521 
1522 		switch (sp->state[cp->protoidx]) {
1523 		case STATE_CLOSED:
1524 		case STATE_STOPPED:
1525 			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident, 0, 0);
1526 			break;
1527 		case STATE_REQ_SENT:
1528 		case STATE_ACK_SENT:
1529 			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1530 			(cp->scr)(sp);
1531 			break;
1532 		case STATE_OPENED:
1533 			sppp_cp_change_state(cp, sp, STATE_ACK_SENT);
1534 			(cp->tld)(sp);
1535 			(cp->scr)(sp);
1536 			break;
1537 		case STATE_ACK_RCVD:
1538 			sppp_cp_change_state(cp, sp, STATE_ACK_SENT);
1539 			(cp->scr)(sp);
1540 			break;
1541 		case STATE_CLOSING:
1542 		case STATE_STOPPING:
1543 			break;
1544 		default:
1545 			/* printf(SPP_FMT "%s illegal %s in state %s\n",
1546 			       SPP_ARGS(ifp), cp->name,
1547 			       sppp_cp_type_name(h->type),
1548 			       sppp_state_name(sp->state[cp->protoidx])); */
1549 			++ifp->if_ierrors;
1550 		}
1551 		break;
1552 
1553 	case TERM_REQ:
1554 		switch (sp->state[cp->protoidx]) {
1555 		case STATE_ACK_RCVD:
1556 		case STATE_ACK_SENT:
1557 			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1558 			/* FALLTHROUGH */
1559 		case STATE_CLOSED:
1560 		case STATE_STOPPED:
1561 		case STATE_CLOSING:
1562 		case STATE_STOPPING:
1563 		case STATE_REQ_SENT:
1564 		  sta:
1565 			/* Send Terminate-Ack packet. */
1566 			if (debug)
1567 				log(LOG_DEBUG, SPP_FMT "%s send terminate-ack\n",
1568 				    SPP_ARGS(ifp), cp->name);
1569 			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident, 0, 0);
1570 			break;
1571 		case STATE_OPENED:
1572 			sp->rst_counter[cp->protoidx] = 0;
1573 			sppp_cp_change_state(cp, sp, STATE_STOPPING);
1574 			(cp->tld)(sp);
1575 			goto sta;
1576 			break;
1577 		default:
1578 			/* printf(SPP_FMT "%s illegal %s in state %s\n",
1579 			       SPP_ARGS(ifp), cp->name,
1580 			       sppp_cp_type_name(h->type),
1581 			       sppp_state_name(sp->state[cp->protoidx])); */
1582 			++ifp->if_ierrors;
1583 		}
1584 		break;
1585 	case TERM_ACK:
1586 		switch (sp->state[cp->protoidx]) {
1587 		case STATE_CLOSED:
1588 		case STATE_STOPPED:
1589 		case STATE_REQ_SENT:
1590 		case STATE_ACK_SENT:
1591 			break;
1592 		case STATE_CLOSING:
1593 			sppp_cp_change_state(cp, sp, STATE_CLOSED);
1594 			(cp->tlf)(sp);
1595 			break;
1596 		case STATE_STOPPING:
1597 			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1598 			(cp->tlf)(sp);
1599 			break;
1600 		case STATE_ACK_RCVD:
1601 			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1602 			break;
1603 		case STATE_OPENED:
1604 			sppp_cp_change_state(cp, sp, STATE_ACK_RCVD);
1605 			(cp->tld)(sp);
1606 			(cp->scr)(sp);
1607 			break;
1608 		default:
1609 			/* printf(SPP_FMT "%s illegal %s in state %s\n",
1610 			       SPP_ARGS(ifp), cp->name,
1611 			       sppp_cp_type_name(h->type),
1612 			       sppp_state_name(sp->state[cp->protoidx])); */
1613 			++ifp->if_ierrors;
1614 		}
1615 		break;
1616 	case CODE_REJ:
1617 	case PROTO_REJ:
1618 	    {
1619 		int catastrophic = 0;
1620 		const struct cp *upper = NULL;
1621 		int i;
1622 		u_int16_t proto;
1623 
1624 		if (len < 2) {
1625 			if (debug)
1626 				log(LOG_DEBUG, SPP_FMT "invalid proto-rej length\n",
1627 				       SPP_ARGS(ifp));
1628 			++ifp->if_ierrors;
1629 			break;
1630 		}
1631 
1632 		proto = ntohs(*((u_int16_t *)p));
1633 		for (i = 0; i < IDX_COUNT; i++) {
1634 			if (cps[i]->proto == proto) {
1635 				upper = cps[i];
1636 				break;
1637 			}
1638 		}
1639 		if (upper == NULL)
1640 			catastrophic++;
1641 
1642 		if (catastrophic || debug)
1643 			log(catastrophic? LOG_INFO: LOG_DEBUG,
1644 			    SPP_FMT "%s: RXJ%c (%s) for proto 0x%x (%s/%s)\n",
1645 			    SPP_ARGS(ifp), cp->name, catastrophic ? '-' : '+',
1646 			    sppp_cp_type_name(h->type), proto,
1647 			    upper ? upper->name : "unknown",
1648 			    upper ? sppp_state_name(sp->state[upper->protoidx]) : "?");
1649 
1650 		/*
1651 		 * if we got RXJ+ against conf-req, the peer does not implement
1652 		 * this particular protocol type.  terminate the protocol.
1653 		 */
1654 		if (upper) {
1655 			if (sp->state[upper->protoidx] == STATE_REQ_SENT) {
1656 				upper->Close(sp);
1657 				break;
1658 			}
1659 		}
1660 
1661 		/* XXX catastrophic rejects (RXJ-) aren't handled yet. */
1662 		switch (sp->state[cp->protoidx]) {
1663 		case STATE_CLOSED:
1664 		case STATE_STOPPED:
1665 		case STATE_REQ_SENT:
1666 		case STATE_ACK_SENT:
1667 		case STATE_CLOSING:
1668 		case STATE_STOPPING:
1669 		case STATE_OPENED:
1670 			break;
1671 		case STATE_ACK_RCVD:
1672 			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1673 			break;
1674 		default:
1675 			/* printf(SPP_FMT "%s illegal %s in state %s\n",
1676 			       SPP_ARGS(ifp), cp->name,
1677 			       sppp_cp_type_name(h->type),
1678 			       sppp_state_name(sp->state[cp->protoidx])); */
1679 			++ifp->if_ierrors;
1680 		}
1681 		break;
1682 	    }
1683 	case DISC_REQ:
1684 		if (cp->proto != PPP_LCP)
1685 			goto illegal;
1686 		/* Discard the packet. */
1687 		break;
1688 	case ECHO_REQ:
1689 		if (cp->proto != PPP_LCP)
1690 			goto illegal;
1691 		if (sp->state[cp->protoidx] != STATE_OPENED) {
1692 			if (debug)
1693 				addlog(SPP_FMT "lcp echo req but lcp closed\n",
1694 				       SPP_ARGS(ifp));
1695 			++ifp->if_ierrors;
1696 			break;
1697 		}
1698 		if (len < 8) {
1699 			if (debug)
1700 				addlog(SPP_FMT "invalid lcp echo request "
1701 				       "packet length: %d bytes\n",
1702 				       SPP_ARGS(ifp), len);
1703 			break;
1704 		}
1705 
1706 		nmagic = (u_long)p[0] << 24 |
1707 		    (u_long)p[1] << 16 | p[2] << 8 | p[3];
1708 
1709 		if (nmagic == sp->lcp.magic) {
1710 			/* Line loopback mode detected. */
1711 			log(LOG_INFO, SPP_FMT "loopback\n", SPP_ARGS(ifp));
1712 			/* Shut down the PPP link. */
1713  			lcp.Close(sp);
1714 			break;
1715 		}
1716 
1717 		p[0] = sp->lcp.magic >> 24;
1718 		p[1] = sp->lcp.magic >> 16;
1719 		p[2] = sp->lcp.magic >> 8;
1720 		p[3] = sp->lcp.magic;
1721 
1722 		if (debug)
1723 			addlog(SPP_FMT "got lcp echo req, sending echo rep\n",
1724 			       SPP_ARGS(ifp));
1725 		sppp_cp_send (sp, PPP_LCP, ECHO_REPLY, h->ident, len-4, h+1);
1726 		break;
1727 	case ECHO_REPLY:
1728 		if (cp->proto != PPP_LCP)
1729 			goto illegal;
1730 		if (h->ident != sp->lcp.echoid) {
1731 			++ifp->if_ierrors;
1732 			break;
1733 		}
1734 		if (len < 8) {
1735 			if (debug)
1736 				addlog(SPP_FMT "lcp invalid echo reply "
1737 				       "packet length: %d bytes\n",
1738 				       SPP_ARGS(ifp), len);
1739 			break;
1740 		}
1741 		if (debug)
1742 			addlog(SPP_FMT "lcp got echo rep\n",
1743 			       SPP_ARGS(ifp));
1744 
1745 		nmagic = (u_long)p[0] << 24 |
1746 		    (u_long)p[1] << 16 | p[2] << 8 | p[3];
1747 
1748 		if (nmagic != sp->lcp.magic)
1749 			sp->pp_alivecnt = 0;
1750 		break;
1751 	default:
1752 		/* Unknown packet type -- send Code-Reject packet. */
1753 	  illegal:
1754 		if (debug)
1755 			addlog(SPP_FMT "%s send code-rej for 0x%x\n",
1756 			       SPP_ARGS(ifp), cp->name, h->type);
1757 		sppp_cp_send(sp, cp->proto, CODE_REJ, ++sp->pp_seq,
1758 			     m->m_pkthdr.len, h);
1759 		++ifp->if_ierrors;
1760 	}
1761 }
1762 
1763 
1764 /*
1765  * The generic part of all Up/Down/Open/Close/TO event handlers.
1766  * Basically, the state transition handling in the automaton.
1767  */
1768 HIDE void
1769 sppp_up_event(const struct cp *cp, struct sppp *sp)
1770 {
1771 	STDDCL;
1772 
1773 	if (debug)
1774 		log(LOG_DEBUG, SPP_FMT "%s up(%s)\n",
1775 		    SPP_ARGS(ifp), cp->name,
1776 		    sppp_state_name(sp->state[cp->protoidx]));
1777 
1778 	switch (sp->state[cp->protoidx]) {
1779 	case STATE_INITIAL:
1780 		sppp_cp_change_state(cp, sp, STATE_CLOSED);
1781 		break;
1782 	case STATE_STARTING:
1783 		sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1784 		sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1785 		(cp->scr)(sp);
1786 		break;
1787 	default:
1788 		/* printf(SPP_FMT "%s illegal up in state %s\n",
1789 		       SPP_ARGS(ifp), cp->name,
1790 		       sppp_state_name(sp->state[cp->protoidx])); */
1791 		break;
1792 	}
1793 }
1794 
1795 HIDE void
1796 sppp_down_event(const struct cp *cp, struct sppp *sp)
1797 {
1798 	STDDCL;
1799 
1800 	if (debug)
1801 		log(LOG_DEBUG, SPP_FMT "%s down(%s)\n",
1802 		    SPP_ARGS(ifp), cp->name,
1803 		    sppp_state_name(sp->state[cp->protoidx]));
1804 
1805 	switch (sp->state[cp->protoidx]) {
1806 	case STATE_CLOSED:
1807 	case STATE_CLOSING:
1808 		sppp_cp_change_state(cp, sp, STATE_INITIAL);
1809 		break;
1810 	case STATE_STOPPED:
1811 		sppp_cp_change_state(cp, sp, STATE_STARTING);
1812 		(cp->tls)(sp);
1813 		break;
1814 	case STATE_STOPPING:
1815 	case STATE_REQ_SENT:
1816 	case STATE_ACK_RCVD:
1817 	case STATE_ACK_SENT:
1818 		sppp_cp_change_state(cp, sp, STATE_STARTING);
1819 		break;
1820 	case STATE_OPENED:
1821 		sppp_cp_change_state(cp, sp, STATE_STARTING);
1822 		(cp->tld)(sp);
1823 		break;
1824 	default:
1825 		/* printf(SPP_FMT "%s illegal down in state %s\n",
1826 		       SPP_ARGS(ifp), cp->name,
1827 		       sppp_state_name(sp->state[cp->protoidx])); */
1828 		break;
1829 	}
1830 }
1831 
1832 
1833 HIDE void
1834 sppp_open_event(const struct cp *cp, struct sppp *sp)
1835 {
1836 	STDDCL;
1837 
1838 	if (debug)
1839 		log(LOG_DEBUG, SPP_FMT "%s open(%s)\n",
1840 		    SPP_ARGS(ifp), cp->name,
1841 		    sppp_state_name(sp->state[cp->protoidx]));
1842 
1843 	switch (sp->state[cp->protoidx]) {
1844 	case STATE_INITIAL:
1845 		sppp_cp_change_state(cp, sp, STATE_STARTING);
1846 		(cp->tls)(sp);
1847 		break;
1848 	case STATE_STARTING:
1849 		break;
1850 	case STATE_CLOSED:
1851 		sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1852 		sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1853 		(cp->scr)(sp);
1854 		break;
1855 	case STATE_STOPPED:
1856 	case STATE_STOPPING:
1857 	case STATE_REQ_SENT:
1858 	case STATE_ACK_RCVD:
1859 	case STATE_ACK_SENT:
1860 	case STATE_OPENED:
1861 		break;
1862 	case STATE_CLOSING:
1863 		sppp_cp_change_state(cp, sp, STATE_STOPPING);
1864 		break;
1865 	}
1866 }
1867 
1868 
1869 HIDE void
1870 sppp_close_event(const struct cp *cp, struct sppp *sp)
1871 {
1872 	STDDCL;
1873 
1874 	if (debug)
1875 		log(LOG_DEBUG, SPP_FMT "%s close(%s)\n",
1876 		    SPP_ARGS(ifp), cp->name,
1877 		    sppp_state_name(sp->state[cp->protoidx]));
1878 
1879 	switch (sp->state[cp->protoidx]) {
1880 	case STATE_INITIAL:
1881 	case STATE_CLOSED:
1882 	case STATE_CLOSING:
1883 		break;
1884 	case STATE_STARTING:
1885 		sppp_cp_change_state(cp, sp, STATE_INITIAL);
1886 		(cp->tlf)(sp);
1887 		break;
1888 	case STATE_STOPPED:
1889 		sppp_cp_change_state(cp, sp, STATE_CLOSED);
1890 		break;
1891 	case STATE_STOPPING:
1892 		sppp_cp_change_state(cp, sp, STATE_CLOSING);
1893 		break;
1894 	case STATE_OPENED:
1895 		sppp_cp_change_state(cp, sp, STATE_CLOSING);
1896 		sp->rst_counter[cp->protoidx] = sp->lcp.max_terminate;
1897 		sppp_cp_send(sp, cp->proto, TERM_REQ, ++sp->pp_seq, 0, 0);
1898 		(cp->tld)(sp);
1899 		break;
1900 	case STATE_REQ_SENT:
1901 	case STATE_ACK_RCVD:
1902 	case STATE_ACK_SENT:
1903 		sp->rst_counter[cp->protoidx] = sp->lcp.max_terminate;
1904 		sppp_cp_send(sp, cp->proto, TERM_REQ, ++sp->pp_seq, 0, 0);
1905 		sppp_cp_change_state(cp, sp, STATE_CLOSING);
1906 		break;
1907 	}
1908 }
1909 
1910 HIDE void
1911 sppp_increasing_timeout (const struct cp *cp, struct sppp *sp)
1912 {
1913 	int timo;
1914 
1915 	timo = sp->lcp.max_configure - sp->rst_counter[cp->protoidx];
1916 	if (timo < 1)
1917 		timo = 1;
1918 #if defined(__FreeBSD__) && __FreeBSD__ >= 3
1919 	sp->ch[cp->protoidx] =
1920 	    timeout(cp->TO, (void *)sp, timo * sp->lcp.timeout);
1921 #elif defined(__OpenBSD__)
1922 	timeout_add(&sp->ch[cp->protoidx], timo * sp->lcp.timeout);
1923 #endif
1924 }
1925 
1926 HIDE void
1927 sppp_to_event(const struct cp *cp, struct sppp *sp)
1928 {
1929 	STDDCL;
1930 	int s;
1931 
1932 	s = splnet();
1933 	if (debug)
1934 		log(LOG_DEBUG, SPP_FMT "%s TO(%s) rst_counter = %d\n",
1935 		    SPP_ARGS(ifp), cp->name,
1936 		    sppp_state_name(sp->state[cp->protoidx]),
1937 		    sp->rst_counter[cp->protoidx]);
1938 
1939 	if (--sp->rst_counter[cp->protoidx] < 0)
1940 		/* TO- event */
1941 		switch (sp->state[cp->protoidx]) {
1942 		case STATE_CLOSING:
1943 			sppp_cp_change_state(cp, sp, STATE_CLOSED);
1944 			(cp->tlf)(sp);
1945 			break;
1946 		case STATE_STOPPING:
1947 			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1948 			(cp->tlf)(sp);
1949 			break;
1950 		case STATE_REQ_SENT:
1951 		case STATE_ACK_RCVD:
1952 		case STATE_ACK_SENT:
1953 			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1954 			(cp->tlf)(sp);
1955 			break;
1956 		}
1957 	else
1958 		/* TO+ event */
1959 		switch (sp->state[cp->protoidx]) {
1960 		case STATE_CLOSING:
1961 		case STATE_STOPPING:
1962 			sppp_cp_send(sp, cp->proto, TERM_REQ, ++sp->pp_seq,
1963 				     0, 0);
1964   			sppp_increasing_timeout (cp, sp);
1965 			break;
1966 		case STATE_REQ_SENT:
1967 		case STATE_ACK_RCVD:
1968 			/* sppp_cp_change_state() will restart the timer */
1969 			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1970 			(cp->scr)(sp);
1971 			break;
1972 		case STATE_ACK_SENT:
1973   			sppp_increasing_timeout (cp, sp);
1974 			(cp->scr)(sp);
1975 			break;
1976 		}
1977 
1978 	splx(s);
1979 }
1980 
1981 /*
1982  * Change the state of a control protocol in the state automaton.
1983  * Takes care of starting/stopping the restart timer.
1984  */
1985 void
1986 sppp_cp_change_state(const struct cp *cp, struct sppp *sp, int newstate)
1987 {
1988 	STDDCL;
1989 
1990 	if (debug && sp->state[cp->protoidx] != newstate)
1991 		log(LOG_DEBUG, SPP_FMT "%s %s->%s\n",
1992 		    SPP_ARGS(ifp), cp->name,
1993 		    sppp_state_name(sp->state[cp->protoidx]),
1994 		    sppp_state_name(newstate));
1995 	sp->state[cp->protoidx] = newstate;
1996 
1997 	switch (newstate) {
1998 	case STATE_INITIAL:
1999 	case STATE_STARTING:
2000 	case STATE_CLOSED:
2001 	case STATE_STOPPED:
2002 	case STATE_OPENED:
2003 		UNTIMEOUT(cp->TO, (void *)sp, sp->ch[cp->protoidx]);
2004 		break;
2005 	case STATE_CLOSING:
2006 	case STATE_STOPPING:
2007 	case STATE_REQ_SENT:
2008 	case STATE_ACK_RCVD:
2009 	case STATE_ACK_SENT:
2010 		if (!timeout_pending(&sp->ch[cp->protoidx]))
2011 			sppp_increasing_timeout (cp, sp);
2012 		break;
2013 	}
2014 }
2015 /*
2016  *--------------------------------------------------------------------------*
2017  *                                                                          *
2018  *                         The LCP implementation.                          *
2019  *                                                                          *
2020  *--------------------------------------------------------------------------*
2021  */
2022 HIDE void
2023 sppp_lcp_init(struct sppp *sp)
2024 {
2025 	sp->lcp.opts = (1 << LCP_OPT_MAGIC);
2026 	sp->lcp.magic = 0;
2027 	sp->state[IDX_LCP] = STATE_INITIAL;
2028 	sp->fail_counter[IDX_LCP] = 0;
2029 	sp->lcp.protos = 0;
2030 	sp->lcp.mru = sp->lcp.their_mru = sp->pp_if.if_mtu;
2031 
2032 	/*
2033 	 * Initialize counters and timeout values.  Note that we don't
2034 	 * use the 3 seconds suggested in RFC 1661 since we are likely
2035 	 * running on a fast link.  XXX We should probably implement
2036 	 * the exponential backoff option.  Note that these values are
2037 	 * relevant for all control protocols, not just LCP only.
2038 	 */
2039 	sp->lcp.timeout = 1 * hz;
2040 	sp->lcp.max_terminate = 2;
2041 	sp->lcp.max_configure = 10;
2042 	sp->lcp.max_failure = 10;
2043 #if defined (__FreeBSD__)
2044 	callout_handle_init(&sp->ch[IDX_LCP]);
2045 #endif
2046 }
2047 
2048 HIDE void
2049 sppp_lcp_up(struct sppp *sp)
2050 {
2051 	STDDCL;
2052 	struct timeval tv;
2053 
2054 	if (sp->pp_flags & PP_CISCO) {
2055 		int s = splsoftnet();
2056 		sp->pp_if.if_link_state = LINK_STATE_UP;
2057 		if_link_state_change(&sp->pp_if);
2058 		splx(s);
2059 		return;
2060 	}
2061 
2062  	sp->pp_alivecnt = 0;
2063  	sp->lcp.opts = (1 << LCP_OPT_MAGIC);
2064  	sp->lcp.magic = 0;
2065  	sp->lcp.protos = 0;
2066  	sp->lcp.mru = sp->lcp.their_mru = sp->pp_if.if_mtu;
2067 
2068 	getmicrouptime(&tv);
2069 	sp->pp_last_receive = sp->pp_last_activity = tv.tv_sec;
2070 
2071 	/*
2072 	 * If this interface is passive or dial-on-demand, and we are
2073 	 * still in Initial state, it means we've got an incoming
2074 	 * call.  Activate the interface.
2075 	 */
2076 	if ((ifp->if_flags & (IFF_AUTO | IFF_PASSIVE)) != 0) {
2077 		if (debug)
2078 			log(LOG_DEBUG,
2079 			    SPP_FMT "Up event", SPP_ARGS(ifp));
2080 		ifp->if_flags |= IFF_RUNNING;
2081 		if (sp->state[IDX_LCP] == STATE_INITIAL) {
2082 			if (debug)
2083 				addlog("(incoming call)\n");
2084 			sp->pp_flags |= PP_CALLIN;
2085 			lcp.Open(sp);
2086 		} else if (debug)
2087 			addlog("\n");
2088 	} else if ((ifp->if_flags & (IFF_AUTO | IFF_PASSIVE)) == 0 &&
2089 		   (sp->state[IDX_LCP] == STATE_INITIAL)) {
2090 			ifp->if_flags |= IFF_RUNNING;
2091 			lcp.Open(sp);
2092 	}
2093 
2094 	sppp_up_event(&lcp, sp);
2095 }
2096 
2097 HIDE void
2098 sppp_lcp_down(struct sppp *sp)
2099 {
2100 	STDDCL;
2101 
2102 	if (sp->pp_flags & PP_CISCO) {
2103 		int s = splsoftnet();
2104 		sp->pp_if.if_link_state = LINK_STATE_DOWN;
2105 		if_link_state_change(&sp->pp_if);
2106 		splx(s);
2107 		return;
2108 	}
2109 
2110 	sppp_down_event(&lcp, sp);
2111 
2112 	/*
2113 	 * If this is neither a dial-on-demand nor a passive
2114 	 * interface, simulate an ``ifconfig down'' action, so the
2115 	 * administrator can force a redial by another ``ifconfig
2116 	 * up''.  XXX For leased line operation, should we immediately
2117 	 * try to reopen the connection here?
2118 	 */
2119 	if ((ifp->if_flags & (IFF_AUTO | IFF_PASSIVE)) == 0) {
2120 		if (debug)
2121 			log(LOG_DEBUG, SPP_FMT "Down event (carrier loss), "
2122 			    "taking interface down.", SPP_ARGS(ifp));
2123 		if_down(ifp);
2124 	} else {
2125 		if (debug)
2126 			log(LOG_DEBUG, SPP_FMT "Down event (carrier loss)\n",
2127 			    SPP_ARGS(ifp));
2128 	}
2129 
2130 	if (sp->state[IDX_LCP] != STATE_INITIAL)
2131 		lcp.Close(sp);
2132  	sp->pp_flags &= ~PP_CALLIN;
2133 	ifp->if_flags &= ~IFF_RUNNING;
2134  	sppp_flush(ifp);
2135 }
2136 
2137 HIDE void
2138 sppp_lcp_open(struct sppp *sp)
2139 {
2140 	/*
2141 	 * If we are authenticator, negotiate LCP_AUTH
2142 	 */
2143 	if (sp->hisauth.proto != 0)
2144 		sp->lcp.opts |= (1 << LCP_OPT_AUTH_PROTO);
2145 	else
2146 		sp->lcp.opts &= ~(1 << LCP_OPT_AUTH_PROTO);
2147 	sp->pp_flags &= ~PP_NEEDAUTH;
2148 	sppp_open_event(&lcp, sp);
2149 }
2150 
2151 HIDE void
2152 sppp_lcp_close(struct sppp *sp)
2153 {
2154 	sppp_close_event(&lcp, sp);
2155 }
2156 
2157 HIDE void
2158 sppp_lcp_TO(void *cookie)
2159 {
2160 	sppp_to_event(&lcp, (struct sppp *)cookie);
2161 }
2162 
2163 /*
2164  * Analyze a configure request.  Return true if it was agreeable, and
2165  * caused action sca, false if it has been rejected or nak'ed, and
2166  * caused action scn.  (The return value is used to make the state
2167  * transition decision in the state automaton.)
2168  */
2169 HIDE int
2170 sppp_lcp_RCR(struct sppp *sp, struct lcp_header *h, int len)
2171 {
2172 	STDDCL;
2173 	u_char *buf, *r, *p;
2174 	int origlen, rlen;
2175 	u_long nmagic;
2176 	u_short authproto;
2177 
2178 	len -= 4;
2179 	origlen = len;
2180 	buf = r = malloc (len, M_TEMP, M_NOWAIT);
2181 	if (! buf)
2182 		return (0);
2183 
2184 	if (debug)
2185 		log(LOG_DEBUG, SPP_FMT "lcp parse opts: ",
2186 		    SPP_ARGS(ifp));
2187 
2188 	/* pass 1: check for things that need to be rejected */
2189 	p = (void*) (h+1);
2190 	for (rlen = 0; len > 1; len -= p[1], p += p[1]) {
2191 		if (p[1] < 2 || p[1] > len) {
2192 			free(buf, M_TEMP);
2193 			return (-1);
2194 		}
2195 		if (debug)
2196 			addlog("%s ", sppp_lcp_opt_name(*p));
2197 		switch (*p) {
2198 		case LCP_OPT_MAGIC:
2199 			/* Magic number. */
2200 			/* FALLTHROUGH, both are same length */
2201 		case LCP_OPT_ASYNC_MAP:
2202 			/* Async control character map. */
2203 			if (len >= 6 && p[1] == 6)
2204 				continue;
2205 			if (debug)
2206 				addlog("[invalid] ");
2207 			break;
2208 		case LCP_OPT_MRU:
2209 			/* Maximum receive unit. */
2210 			if (len >= 4 && p[1] == 4)
2211 				continue;
2212 			if (debug)
2213 				addlog("[invalid] ");
2214 			break;
2215 		case LCP_OPT_AUTH_PROTO:
2216 			if (len < 4) {
2217 				if (debug)
2218 					addlog("[invalid] ");
2219 				break;
2220 			}
2221 			authproto = (p[2] << 8) + p[3];
2222 			if (authproto == PPP_CHAP && p[1] != 5) {
2223 				if (debug)
2224 					addlog("[invalid chap len] ");
2225 				break;
2226 			}
2227 			if (sp->myauth.proto == 0) {
2228 				/* we are not configured to do auth */
2229 				if (debug)
2230 					addlog("[not configured] ");
2231 				break;
2232 			}
2233 			/*
2234 			 * Remote want us to authenticate, remember this,
2235 			 * so we stay in PHASE_AUTHENTICATE after LCP got
2236 			 * up.
2237 			 */
2238 			sp->pp_flags |= PP_NEEDAUTH;
2239 			continue;
2240 		default:
2241 			/* Others not supported. */
2242 			if (debug)
2243 				addlog("[rej] ");
2244 			break;
2245 		}
2246 		/* Add the option to rejected list. */
2247 		bcopy (p, r, p[1]);
2248 		r += p[1];
2249 		rlen += p[1];
2250 	}
2251 	if (rlen) {
2252 		if (debug)
2253 			addlog(" send conf-rej\n");
2254 		sppp_cp_send(sp, PPP_LCP, CONF_REJ, h->ident, rlen, buf);
2255 		goto end;
2256 	} else if (debug)
2257 		addlog("\n");
2258 
2259 	/*
2260 	 * pass 2: check for option values that are unacceptable and
2261 	 * thus require to be nak'ed.
2262 	 */
2263 	if (debug)
2264 		log(LOG_DEBUG, SPP_FMT "lcp parse opt values: ",
2265 		    SPP_ARGS(ifp));
2266 
2267 	p = (void*) (h+1);
2268 	len = origlen;
2269 	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2270 		if (debug)
2271 			addlog("%s ", sppp_lcp_opt_name(*p));
2272 		switch (*p) {
2273 		case LCP_OPT_MAGIC:
2274 			/* Magic number -- extract. */
2275 			nmagic = (u_long)p[2] << 24 |
2276 				(u_long)p[3] << 16 | p[4] << 8 | p[5];
2277 			if (nmagic != sp->lcp.magic) {
2278 				if (debug)
2279 					addlog("0x%lx ", nmagic);
2280 				continue;
2281 			}
2282 			if (debug)
2283 				addlog("[glitch] ");
2284 			++sp->pp_loopcnt;
2285 			/*
2286 			 * We negate our magic here, and NAK it.  If
2287 			 * we see it later in an NAK packet, we
2288 			 * suggest a new one.
2289 			 */
2290 			nmagic = ~sp->lcp.magic;
2291 			/* Gonna NAK it. */
2292 			p[2] = nmagic >> 24;
2293 			p[3] = nmagic >> 16;
2294 			p[4] = nmagic >> 8;
2295 			p[5] = nmagic;
2296 			break;
2297 
2298 		case LCP_OPT_ASYNC_MAP:
2299 			/* Async control character map -- check to be zero. */
2300 			if (! p[2] && ! p[3] && ! p[4] && ! p[5]) {
2301 				if (debug)
2302 					addlog("[empty] ");
2303 				continue;
2304 			}
2305 			if (debug)
2306 				addlog("[non-empty] ");
2307 			/* suggest a zero one */
2308 			p[2] = p[3] = p[4] = p[5] = 0;
2309 			break;
2310 
2311 		case LCP_OPT_MRU:
2312 			/*
2313 			 * Maximum receive unit.  Always agreeable,
2314 			 * but ignored by now.
2315 			 */
2316 			sp->lcp.their_mru = p[2] * 256 + p[3];
2317 			if (debug)
2318 				addlog("%lu ", sp->lcp.their_mru);
2319 			continue;
2320 
2321 		case LCP_OPT_AUTH_PROTO:
2322 			authproto = (p[2] << 8) + p[3];
2323 			if (sp->myauth.proto != authproto) {
2324 				/* not agreed, nak */
2325 				if (debug)
2326 					addlog("[mine %s != his %s] ",
2327 					       sppp_proto_name(sp->hisauth.proto),
2328 					       sppp_proto_name(authproto));
2329 				p[2] = sp->myauth.proto >> 8;
2330 				p[3] = sp->myauth.proto;
2331 				break;
2332 			}
2333 			if (authproto == PPP_CHAP && p[4] != CHAP_MD5) {
2334 				if (debug)
2335 					addlog("[chap not MD5] ");
2336 				p[4] = CHAP_MD5;
2337 				break;
2338 			}
2339 			continue;
2340 		}
2341 		/* Add the option to nak'ed list. */
2342 		bcopy (p, r, p[1]);
2343 		r += p[1];
2344 		rlen += p[1];
2345 	}
2346 	if (rlen) {
2347 		if (++sp->fail_counter[IDX_LCP] >= sp->lcp.max_failure) {
2348 			if (debug)
2349 				addlog(" max_failure (%d) exceeded, "
2350 				       "send conf-rej\n",
2351 				       sp->lcp.max_failure);
2352 			sppp_cp_send(sp, PPP_LCP, CONF_REJ, h->ident, rlen, buf);
2353 		} else {
2354 			if (debug)
2355 				addlog(" send conf-nak\n");
2356 			sppp_cp_send(sp, PPP_LCP, CONF_NAK, h->ident, rlen, buf);
2357 		}
2358 		goto end;
2359 	} else {
2360 		if (debug)
2361 			addlog("send conf-ack\n");
2362 		sp->fail_counter[IDX_LCP] = 0;
2363 		sp->pp_loopcnt = 0;
2364 		sppp_cp_send (sp, PPP_LCP, CONF_ACK,
2365 			      h->ident, origlen, h+1);
2366 	}
2367 
2368  end:
2369 	free(buf, M_TEMP);
2370 	return (rlen == 0);
2371 }
2372 
2373 /*
2374  * Analyze the LCP Configure-Reject option list, and adjust our
2375  * negotiation.
2376  */
2377 HIDE void
2378 sppp_lcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
2379 {
2380 	STDDCL;
2381 	u_char *p;
2382 
2383 	len -= 4;
2384 
2385 	if (debug)
2386 		log(LOG_DEBUG, SPP_FMT "lcp rej opts: ",
2387 		    SPP_ARGS(ifp));
2388 
2389 	p = (void*) (h+1);
2390 	for (; len > 1; len -= p[1], p += p[1]) {
2391 		if (p[1] < 2 || p[1] > len)
2392 			return;
2393 		if (debug)
2394 			addlog("%s ", sppp_lcp_opt_name(*p));
2395 		switch (*p) {
2396 		case LCP_OPT_MAGIC:
2397 			/* Magic number -- can't use it, use 0 */
2398 			sp->lcp.opts &= ~(1 << LCP_OPT_MAGIC);
2399 			sp->lcp.magic = 0;
2400 			break;
2401 		case LCP_OPT_MRU:
2402 			/*
2403 			 * Should not be rejected anyway, since we only
2404 			 * negotiate a MRU if explicitly requested by
2405 			 * peer.
2406 			 */
2407 			sp->lcp.opts &= ~(1 << LCP_OPT_MRU);
2408 			break;
2409 		case LCP_OPT_AUTH_PROTO:
2410 			/*
2411 			 * Peer doesn't want to authenticate himself,
2412 			 * deny unless this is a dialout call, and
2413 			 * AUTHFLAG_NOCALLOUT is set.
2414 			 */
2415 			if ((sp->pp_flags & PP_CALLIN) == 0 &&
2416 			    (sp->hisauth.flags & AUTHFLAG_NOCALLOUT) != 0) {
2417 				if (debug)
2418 					addlog("[don't insist on auth "
2419 					       "for callout]");
2420 				sp->lcp.opts &= ~(1 << LCP_OPT_AUTH_PROTO);
2421 				break;
2422 			}
2423 			if (debug)
2424 				addlog("[access denied]\n");
2425 			lcp.Close(sp);
2426 			break;
2427 		}
2428 	}
2429 	if (debug)
2430 		addlog("\n");
2431 }
2432 
2433 /*
2434  * Analyze the LCP Configure-NAK option list, and adjust our
2435  * negotiation.
2436  */
2437 HIDE void
2438 sppp_lcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
2439 {
2440 	STDDCL;
2441 	u_char *p;
2442 	u_long magic;
2443 
2444 	len -= 4;
2445 
2446 	if (debug)
2447 		log(LOG_DEBUG, SPP_FMT "lcp nak opts: ",
2448 		    SPP_ARGS(ifp));
2449 
2450 	p = (void*) (h+1);
2451 	for (; len > 1; len -= p[1], p += p[1]) {
2452 		if (p[1] < 2 || p[1] > len)
2453 			return;
2454 		if (debug)
2455 			addlog("%s ", sppp_lcp_opt_name(*p));
2456 		switch (*p) {
2457 		case LCP_OPT_MAGIC:
2458 			/* Magic number -- renegotiate */
2459 			if ((sp->lcp.opts & (1 << LCP_OPT_MAGIC)) &&
2460 			    len >= 6 && p[1] == 6) {
2461 				magic = (u_long)p[2] << 24 |
2462 					(u_long)p[3] << 16 | p[4] << 8 | p[5];
2463 				/*
2464 				 * If the remote magic is our negated one,
2465 				 * this looks like a loopback problem.
2466 				 * Suggest a new magic to make sure.
2467 				 */
2468 				if (magic == ~sp->lcp.magic) {
2469 					if (debug)
2470 						addlog("magic glitch ");
2471 					sp->lcp.magic = arc4random();
2472 				} else {
2473 					sp->lcp.magic = magic;
2474 					if (debug)
2475 						addlog("%lu ", magic);
2476 				}
2477 			}
2478 			break;
2479 		case LCP_OPT_MRU:
2480 			/*
2481 			 * Peer wants to advise us to negotiate an MRU.
2482 			 * Agree on it if it's reasonable, or use
2483 			 * default otherwise.
2484 			 */
2485 			if (len >= 4 && p[1] == 4) {
2486 				u_int mru = p[2] * 256 + p[3];
2487 				if (debug)
2488 					addlog("%d ", mru);
2489 				if (mru < PP_MIN_MRU)
2490 					mru = PP_MIN_MRU;
2491 				if (mru > PP_MAX_MRU)
2492 					mru = PP_MAX_MRU;
2493 				sp->lcp.mru = mru;
2494 				sp->lcp.opts |= (1 << LCP_OPT_MRU);
2495 			}
2496 			break;
2497 		case LCP_OPT_AUTH_PROTO:
2498 			/*
2499 			 * Peer doesn't like our authentication method,
2500 			 * deny.
2501 			 */
2502 			if (debug)
2503 				addlog("[access denied]\n");
2504 			lcp.Close(sp);
2505 			break;
2506 		}
2507 	}
2508 	if (debug)
2509 		addlog("\n");
2510 }
2511 
2512 HIDE void
2513 sppp_lcp_tlu(struct sppp *sp)
2514 {
2515 	struct ifnet *ifp = &sp->pp_if;
2516 	int i;
2517 	u_long mask;
2518 
2519 	/* XXX ? */
2520 	if (! (ifp->if_flags & IFF_UP) &&
2521 	    (ifp->if_flags & IFF_RUNNING)) {
2522 		/* Coming out of loopback mode. */
2523 		if_up(ifp);
2524 		if (ifp->if_flags & IFF_DEBUG)
2525 			log(LOG_INFO, SPP_FMT "up\n", SPP_ARGS(ifp));
2526 	}
2527 
2528 	for (i = 0; i < IDX_COUNT; i++)
2529 		if ((cps[i])->flags & CP_QUAL)
2530 			(cps[i])->Open(sp);
2531 
2532 	if ((sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0 ||
2533 	    (sp->pp_flags & PP_NEEDAUTH) != 0)
2534 		sp->pp_phase = PHASE_AUTHENTICATE;
2535 	else
2536 		sp->pp_phase = PHASE_NETWORK;
2537 
2538 	sppp_set_phase(sp);
2539 
2540 	/*
2541 	 * Open all authentication protocols.  This is even required
2542 	 * if we already proceeded to network phase, since it might be
2543 	 * that remote wants us to authenticate, so we might have to
2544 	 * send a PAP request.  Undesired authentication protocols
2545 	 * don't do anything when they get an Open event.
2546 	 */
2547 	for (i = 0; i < IDX_COUNT; i++)
2548 		if ((cps[i])->flags & CP_AUTH)
2549 			(cps[i])->Open(sp);
2550 
2551 	if (sp->pp_phase == PHASE_NETWORK) {
2552 		/* Notify all NCPs. */
2553 		for (i = 0; i < IDX_COUNT; i++)
2554 			if ((cps[i])->flags & CP_NCP)
2555 				(cps[i])->Open(sp);
2556 	}
2557 
2558 	/* Send Up events to all started protos. */
2559 	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2560 		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_LCP) == 0)
2561 			(cps[i])->Up(sp);
2562 
2563 	/* notify low-level driver of state change */
2564 	if (sp->pp_chg)
2565 		sp->pp_chg(sp, (int)sp->pp_phase);
2566 
2567 	if (sp->pp_phase == PHASE_NETWORK)
2568 		/* if no NCP is starting, close down */
2569 		sppp_lcp_check_and_close(sp);
2570 }
2571 
2572 HIDE void
2573 sppp_lcp_tld(struct sppp *sp)
2574 {
2575 	int i;
2576 	u_long mask;
2577 
2578 	sp->pp_phase = PHASE_TERMINATE;
2579 
2580 	sppp_set_phase(sp);
2581 
2582 	/*
2583 	 * Take upper layers down.  We send the Down event first and
2584 	 * the Close second to prevent the upper layers from sending
2585 	 * ``a flurry of terminate-request packets'', as the RFC
2586 	 * describes it.
2587 	 */
2588 	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2589 		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_LCP) == 0) {
2590 			(cps[i])->Down(sp);
2591 			(cps[i])->Close(sp);
2592 		}
2593 }
2594 
2595 HIDE void
2596 sppp_lcp_tls(struct sppp *sp)
2597 {
2598 	sp->pp_phase = PHASE_ESTABLISH;
2599 
2600 	sppp_set_phase(sp);
2601 
2602 	/* Notify lower layer if desired. */
2603 	if (sp->pp_tls)
2604 		(sp->pp_tls)(sp);
2605 }
2606 
2607 HIDE void
2608 sppp_lcp_tlf(struct sppp *sp)
2609 {
2610 	sp->pp_phase = PHASE_DEAD;
2611 	sppp_set_phase(sp);
2612 
2613 	/* Notify lower layer if desired. */
2614 	if (sp->pp_tlf)
2615 		(sp->pp_tlf)(sp);
2616 }
2617 
2618 HIDE void
2619 sppp_lcp_scr(struct sppp *sp)
2620 {
2621 	char opt[6 /* magicnum */ + 4 /* mru */ + 5 /* chap */];
2622 	int i = 0;
2623 	u_short authproto;
2624 
2625 	if (sp->lcp.opts & (1 << LCP_OPT_MAGIC)) {
2626 		if (! sp->lcp.magic)
2627 #if defined (__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
2628 			sp->lcp.magic = arc4random();
2629 #else
2630 			sp->lcp.magic = time.tv_sec + time.tv_usec;
2631 #endif
2632 		opt[i++] = LCP_OPT_MAGIC;
2633 		opt[i++] = 6;
2634 		opt[i++] = sp->lcp.magic >> 24;
2635 		opt[i++] = sp->lcp.magic >> 16;
2636 		opt[i++] = sp->lcp.magic >> 8;
2637 		opt[i++] = sp->lcp.magic;
2638 	}
2639 
2640 	if (sp->lcp.opts & (1 << LCP_OPT_MRU)) {
2641 		opt[i++] = LCP_OPT_MRU;
2642 		opt[i++] = 4;
2643 		opt[i++] = sp->lcp.mru >> 8;
2644 		opt[i++] = sp->lcp.mru;
2645 	}
2646 
2647 	if (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) {
2648 		authproto = sp->hisauth.proto;
2649 		opt[i++] = LCP_OPT_AUTH_PROTO;
2650 		opt[i++] = authproto == PPP_CHAP? 5: 4;
2651 		opt[i++] = authproto >> 8;
2652 		opt[i++] = authproto;
2653 		if (authproto == PPP_CHAP)
2654 			opt[i++] = CHAP_MD5;
2655 	}
2656 
2657 	sp->confid[IDX_LCP] = ++sp->pp_seq;
2658 	sppp_cp_send (sp, PPP_LCP, CONF_REQ, sp->confid[IDX_LCP], i, opt);
2659 }
2660 
2661 /*
2662  * Check the open NCPs, return true if at least one NCP is open.
2663  */
2664 HIDE int
2665 sppp_ncp_check(struct sppp *sp)
2666 {
2667 	int i, mask;
2668 
2669 	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2670 		if (sp->lcp.protos & mask && (cps[i])->flags & CP_NCP)
2671 			return 1;
2672 	return 0;
2673 }
2674 
2675 /*
2676  * Re-check the open NCPs and see if we should terminate the link.
2677  * Called by the NCPs during their tlf action handling.
2678  */
2679 HIDE void
2680 sppp_lcp_check_and_close(struct sppp *sp)
2681 {
2682 
2683 	if (sp->pp_phase < PHASE_NETWORK)
2684 		/* don't bother, we are already going down */
2685 		return;
2686 
2687 	if (sppp_ncp_check(sp))
2688 		return;
2689 
2690 	lcp.Close(sp);
2691 }
2692 /*
2693  *--------------------------------------------------------------------------*
2694  *                                                                          *
2695  *                        The IPCP implementation.                          *
2696  *                                                                          *
2697  *--------------------------------------------------------------------------*
2698  */
2699 
2700 HIDE void
2701 sppp_ipcp_init(struct sppp *sp)
2702 {
2703 	sp->ipcp.opts = 0;
2704 	sp->ipcp.flags = 0;
2705 	sp->state[IDX_IPCP] = STATE_INITIAL;
2706 	sp->fail_counter[IDX_IPCP] = 0;
2707 #if defined (__FreeBSD__)
2708 	callout_handle_init(&sp->ch[IDX_IPCP]);
2709 #endif
2710 }
2711 
2712 HIDE void
2713 sppp_ipcp_up(struct sppp *sp)
2714 {
2715 	sppp_up_event(&ipcp, sp);
2716 }
2717 
2718 HIDE void
2719 sppp_ipcp_down(struct sppp *sp)
2720 {
2721 	sppp_down_event(&ipcp, sp);
2722 }
2723 
2724 HIDE void
2725 sppp_ipcp_open(struct sppp *sp)
2726 {
2727 	sppp_open_event(&ipcp, sp);
2728 }
2729 
2730 HIDE void
2731 sppp_ipcp_close(struct sppp *sp)
2732 {
2733 	sppp_close_event(&ipcp, sp);
2734 }
2735 
2736 HIDE void
2737 sppp_ipcp_TO(void *cookie)
2738 {
2739 	sppp_to_event(&ipcp, (struct sppp *)cookie);
2740 }
2741 
2742 /*
2743  * Analyze a configure request.  Return true if it was agreeable, and
2744  * caused action sca, false if it has been rejected or nak'ed, and
2745  * caused action scn.  (The return value is used to make the state
2746  * transition decision in the state automaton.)
2747  */
2748 HIDE int
2749 sppp_ipcp_RCR(struct sppp *sp, struct lcp_header *h, int len)
2750 {
2751 	u_char *buf, *r, *p;
2752 	struct ifnet *ifp = &sp->pp_if;
2753 	int rlen, origlen, debug = ifp->if_flags & IFF_DEBUG;
2754 	u_int32_t hisaddr, desiredaddr;
2755 
2756 	len -= 4;
2757 	origlen = len;
2758 	/*
2759 	 * Make sure to allocate a buf that can at least hold a
2760 	 * conf-nak with an `address' option.  We might need it below.
2761 	 */
2762 	buf = r = malloc ((len < 6? 6: len), M_TEMP, M_NOWAIT);
2763 	if (! buf)
2764 		return (0);
2765 
2766 	/* pass 1: see if we can recognize them */
2767 	if (debug)
2768 		log(LOG_DEBUG, SPP_FMT "ipcp parse opts: ",
2769 		    SPP_ARGS(ifp));
2770 	p = (void*) (h+1);
2771 	for (rlen = 0; len > 1; len -= p[1], p += p[1]) {
2772 		if (p[1] < 2 || p[1] > len) {
2773 			free(buf, M_TEMP);
2774 			return (-1);
2775 		}
2776 		if (debug)
2777 			addlog("%s ", sppp_ipcp_opt_name(*p));
2778 		switch (*p) {
2779 #ifdef notyet
2780 		case IPCP_OPT_COMPRESSION:
2781 			if (len >= 6 && p[1] >= 6) {
2782 				/* correctly formed compress option */
2783 				continue;
2784 			}
2785 			if (debug)
2786 				addlog("[invalid] ");
2787 			break;
2788 #endif
2789 		case IPCP_OPT_ADDRESS:
2790 			if (len >= 6 && p[1] == 6) {
2791 				/* correctly formed address option */
2792 				continue;
2793 			}
2794 			if (debug)
2795 				addlog("[invalid] ");
2796 			break;
2797 		default:
2798 			/* Others not supported. */
2799 			if (debug)
2800 				addlog("[rej] ");
2801 			break;
2802 		}
2803 		/* Add the option to rejected list. */
2804 		bcopy (p, r, p[1]);
2805 		r += p[1];
2806 		rlen += p[1];
2807 	}
2808 	if (rlen) {
2809 		if (debug)
2810 			addlog(" send conf-rej\n");
2811 		sppp_cp_send(sp, PPP_IPCP, CONF_REJ, h->ident, rlen, buf);
2812 		goto end;
2813 	} else if (debug)
2814 		addlog("\n");
2815 
2816 	/* pass 2: parse option values */
2817 	if (sp->ipcp.flags & IPCP_HISADDR_SEEN)
2818 		hisaddr = sp->ipcp.req_hisaddr; /* we already agreed on that */
2819 	else
2820 		sppp_get_ip_addrs(sp, 0, &hisaddr, 0); /* user configuration */
2821 	if (debug)
2822 		log(LOG_DEBUG, SPP_FMT "ipcp parse opt values: ",
2823 		       SPP_ARGS(ifp));
2824 	p = (void*) (h+1);
2825 	len = origlen;
2826 	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2827 		if (debug)
2828 			addlog(" %s ", sppp_ipcp_opt_name(*p));
2829 		switch (*p) {
2830 #ifdef notyet
2831 		case IPCP_OPT_COMPRESSION:
2832 			continue;
2833 #endif
2834 		case IPCP_OPT_ADDRESS:
2835 			desiredaddr = p[2] << 24 | p[3] << 16 |
2836 				p[4] << 8 | p[5];
2837 			if (desiredaddr == hisaddr ||
2838 			    ((sp->ipcp.flags & IPCP_HISADDR_DYN) &&
2839 			    desiredaddr != 0)) {
2840 				/*
2841 				 * Peer's address is same as our value,
2842 				 * or we have set it to 0.0.0.1 to
2843 				 * indicate that we do not really care,
2844 				 * this is agreeable.  Gonna conf-ack
2845 				 * it.
2846 				 */
2847 				if (debug)
2848 					addlog("%s [ack] ",
2849 					       sppp_dotted_quad(desiredaddr));
2850 				/* record that we've seen it already */
2851 				sp->ipcp.flags |= IPCP_HISADDR_SEEN;
2852 				sp->ipcp.req_hisaddr = desiredaddr;
2853 				hisaddr = desiredaddr;
2854 				continue;
2855 			}
2856 			/*
2857 			 * The address wasn't agreeable.  This is either
2858 			 * he sent us 0.0.0.0, asking to assign him an
2859 			 * address, or he send us another address not
2860 			 * matching our value.  Either case, we gonna
2861 			 * conf-nak it with our value.
2862 			 */
2863 			if (debug) {
2864 				if (desiredaddr == 0)
2865 					addlog("[addr requested] ");
2866 				else
2867 					addlog("%s [not agreed] ",
2868 					       sppp_dotted_quad(desiredaddr));
2869 			}
2870 
2871 			p[2] = hisaddr >> 24;
2872 			p[3] = hisaddr >> 16;
2873 			p[4] = hisaddr >> 8;
2874 			p[5] = hisaddr;
2875 			break;
2876 		}
2877 		/* Add the option to nak'ed list. */
2878 		bcopy (p, r, p[1]);
2879 		r += p[1];
2880 		rlen += p[1];
2881 	}
2882 
2883 	/*
2884 	 * If we are about to conf-ack the request, but haven't seen
2885 	 * his address so far, gonna conf-nak it instead, with the
2886 	 * `address' option present and our idea of his address being
2887 	 * filled in there, to request negotiation of both addresses.
2888 	 *
2889 	 * XXX This can result in an endless req - nak loop if peer
2890 	 * doesn't want to send us his address.  Q: What should we do
2891 	 * about it?  XXX  A: implement the max-failure counter.
2892 	 */
2893 	if (rlen == 0 && !(sp->ipcp.flags & IPCP_HISADDR_SEEN)) {
2894 		buf[0] = IPCP_OPT_ADDRESS;
2895 		buf[1] = 6;
2896 		buf[2] = hisaddr >> 24;
2897 		buf[3] = hisaddr >> 16;
2898 		buf[4] = hisaddr >> 8;
2899 		buf[5] = hisaddr;
2900 		rlen = 6;
2901 		if (debug)
2902 			addlog("still need hisaddr ");
2903 	}
2904 
2905 	if (rlen) {
2906 		if (debug)
2907 			addlog(" send conf-nak\n");
2908 		sppp_cp_send (sp, PPP_IPCP, CONF_NAK, h->ident, rlen, buf);
2909 	} else {
2910 		if (debug)
2911 			addlog(" send conf-ack\n");
2912 		sppp_cp_send (sp, PPP_IPCP, CONF_ACK,
2913 			      h->ident, origlen, h+1);
2914 	}
2915 
2916  end:
2917 	free(buf, M_TEMP);
2918 	return (rlen == 0);
2919 }
2920 
2921 /*
2922  * Analyze the IPCP Configure-Reject option list, and adjust our
2923  * negotiation.
2924  */
2925 HIDE void
2926 sppp_ipcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
2927 {
2928 	u_char *p;
2929 	struct ifnet *ifp = &sp->pp_if;
2930 	int debug = ifp->if_flags & IFF_DEBUG;
2931 
2932 	len -= 4;
2933 
2934 	if (debug)
2935 		log(LOG_DEBUG, SPP_FMT "ipcp rej opts: ",
2936 		    SPP_ARGS(ifp));
2937 
2938 	p = (void*) (h+1);
2939 	for (; len > 1; len -= p[1], p += p[1]) {
2940 		if (p[1] < 2 || p[1] > len)
2941 			return;
2942 		if (debug)
2943 			addlog("%s ", sppp_ipcp_opt_name(*p));
2944 		switch (*p) {
2945 		case IPCP_OPT_ADDRESS:
2946 			/*
2947 			 * Peer doesn't grok address option.  This is
2948 			 * bad.  XXX  Should we better give up here?
2949 			 */
2950 			sp->ipcp.opts &= ~(1 << IPCP_OPT_ADDRESS);
2951 			break;
2952 #ifdef notyet
2953 		case IPCP_OPT_COMPRESS:
2954 			sp->ipcp.opts &= ~(1 << IPCP_OPT_COMPRESS);
2955 			break;
2956 #endif
2957 		}
2958 	}
2959 	if (debug)
2960 		addlog("\n");
2961 }
2962 
2963 /*
2964  * Analyze the IPCP Configure-NAK option list, and adjust our
2965  * negotiation.
2966  */
2967 HIDE void
2968 sppp_ipcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
2969 {
2970 	u_char *p;
2971 	struct ifnet *ifp = &sp->pp_if;
2972 	int debug = ifp->if_flags & IFF_DEBUG;
2973 	u_int32_t wantaddr;
2974 
2975 	len -= 4;
2976 
2977 	if (debug)
2978 		log(LOG_DEBUG, SPP_FMT "ipcp nak opts: ",
2979 		    SPP_ARGS(ifp));
2980 
2981 	p = (void*) (h+1);
2982 	for (; len > 1; len -= p[1], p += p[1]) {
2983 		if (p[1] < 2 || p[1] > len)
2984 			return;
2985 		if (debug)
2986 			addlog("%s ", sppp_ipcp_opt_name(*p));
2987 		switch (*p) {
2988 		case IPCP_OPT_ADDRESS:
2989 			/*
2990 			 * Peer doesn't like our local IP address.  See
2991 			 * if we can do something for him.  We'll drop
2992 			 * him our address then.
2993 			 */
2994 			if (len >= 6 && p[1] == 6) {
2995 				wantaddr = p[2] << 24 | p[3] << 16 |
2996 					p[4] << 8 | p[5];
2997 				sp->ipcp.opts |= (1 << IPCP_OPT_ADDRESS);
2998 				if (debug)
2999 					addlog("[wantaddr %s] ",
3000 					       sppp_dotted_quad(wantaddr));
3001 				/*
3002 				 * When doing dynamic address assignment,
3003 				 * we accept his offer.  Otherwise, we
3004 				 * ignore it and thus continue to negotiate
3005 				 * our already existing value.
3006 				 */
3007 				if (sp->ipcp.flags & IPCP_MYADDR_DYN) {
3008 					if (debug)
3009 						addlog("[agree] ");
3010 					sp->ipcp.flags |= IPCP_MYADDR_SEEN;
3011 					sp->ipcp.req_myaddr = wantaddr;
3012 				}
3013 			}
3014 			break;
3015 #ifdef notyet
3016 		case IPCP_OPT_COMPRESS:
3017 			/*
3018 			 * Peer wants different compression parameters.
3019 			 */
3020 			break;
3021 #endif
3022 		}
3023 	}
3024 	if (debug)
3025 		addlog("\n");
3026 }
3027 
3028 struct sppp_set_ip_addrs_args {
3029 	struct sppp *sp;
3030 	u_int32_t myaddr;
3031 	u_int32_t hisaddr;
3032 };
3033 
3034 HIDE void
3035 sppp_ipcp_tlu(struct sppp *sp)
3036 {
3037 	struct ifnet *ifp = &sp->pp_if;
3038 	struct sppp_set_ip_addrs_args *args;
3039 
3040 	args = malloc(sizeof(*args), M_TEMP, M_NOWAIT);
3041 	if (args == NULL)
3042 		return;
3043 
3044 	args->sp = sp;
3045 
3046 	/* we are up. Set addresses and notify anyone interested */
3047 	sppp_get_ip_addrs(sp, &args->myaddr, &args->hisaddr, 0);
3048 	if ((sp->ipcp.flags & IPCP_MYADDR_DYN) &&
3049 	    (sp->ipcp.flags & IPCP_MYADDR_SEEN))
3050 		args->myaddr = sp->ipcp.req_myaddr;
3051 	if ((sp->ipcp.flags & IPCP_HISADDR_DYN) &&
3052 	    (sp->ipcp.flags & IPCP_HISADDR_SEEN))
3053 		args->hisaddr = sp->ipcp.req_hisaddr;
3054 
3055 	if (workq_add_task(NULL, 0, sppp_set_ip_addrs, args, NULL)) {
3056 		free(args, M_TEMP);
3057 		printf("%s: workq_add_task failed, cannot set "
3058 		    "addresses\n", ifp->if_xname);
3059 	}
3060 }
3061 
3062 HIDE void
3063 sppp_ipcp_tld(struct sppp *sp)
3064 {
3065 }
3066 
3067 HIDE void
3068 sppp_ipcp_tls(struct sppp *sp)
3069 {
3070 	STDDCL;
3071 	u_int32_t myaddr, hisaddr;
3072 
3073 	sp->ipcp.flags &= ~(IPCP_HISADDR_SEEN|IPCP_MYADDR_SEEN|
3074 	    IPCP_MYADDR_DYN|IPCP_HISADDR_DYN);
3075 	sp->ipcp.req_myaddr = 0;
3076 	sp->ipcp.req_hisaddr = 0;
3077 
3078 	sppp_get_ip_addrs(sp, &myaddr, &hisaddr, 0);
3079 	/*
3080 	 * If we don't have his address, this probably means our
3081 	 * interface doesn't want to talk IP at all.  (This could
3082 	 * be the case if somebody wants to speak only IPX, for
3083 	 * example.)  Don't open IPCP in this case.
3084 	 */
3085 	if (hisaddr == 0) {
3086 		/* XXX this message should go away */
3087 		if (debug)
3088 			log(LOG_DEBUG, SPP_FMT "ipcp_open(): no IP interface\n",
3089 			    SPP_ARGS(ifp));
3090 		return;
3091 	}
3092 
3093 	if (myaddr == 0) {
3094 		/*
3095 		 * I don't have an assigned address, so i need to
3096 		 * negotiate my address.
3097 		 */
3098 		sp->ipcp.flags |= IPCP_MYADDR_DYN;
3099 		sp->ipcp.opts |= (1 << IPCP_OPT_ADDRESS);
3100 	}
3101 	if (hisaddr == 1) {
3102 		/*
3103 		 * XXX - remove this hack!
3104 		 * remote has no valid address, we need to get one assigned.
3105 		 */
3106 		sp->ipcp.flags |= IPCP_HISADDR_DYN;
3107 	}
3108 
3109 	/* indicate to LCP that it must stay alive */
3110 	sp->lcp.protos |= (1 << IDX_IPCP);
3111 }
3112 
3113 HIDE void
3114 sppp_ipcp_tlf(struct sppp *sp)
3115 {
3116 	if (sp->ipcp.flags & (IPCP_MYADDR_DYN|IPCP_HISADDR_DYN))
3117 		/* Some address was dynamic, clear it again. */
3118 		sppp_clear_ip_addrs(sp);
3119 
3120 	/* we no longer need LCP */
3121 	sp->lcp.protos &= ~(1 << IDX_IPCP);
3122 	sppp_lcp_check_and_close(sp);
3123 }
3124 
3125 HIDE void
3126 sppp_ipcp_scr(struct sppp *sp)
3127 {
3128 	char opt[6 /* compression */ + 6 /* address */];
3129 	u_int32_t ouraddr;
3130 	int i = 0;
3131 
3132 #ifdef notyet
3133 	if (sp->ipcp.opts & (1 << IPCP_OPT_COMPRESSION)) {
3134 		opt[i++] = IPCP_OPT_COMPRESSION;
3135 		opt[i++] = 6;
3136 		opt[i++] = 0;	/* VJ header compression */
3137 		opt[i++] = 0x2d; /* VJ header compression */
3138 		opt[i++] = max_slot_id;
3139 		opt[i++] = comp_slot_id;
3140 	}
3141 #endif
3142 
3143 	if (sp->ipcp.opts & (1 << IPCP_OPT_ADDRESS)) {
3144 		if (sp->ipcp.flags & IPCP_MYADDR_SEEN)
3145 			/* not sure if this can ever happen */
3146 			ouraddr = sp->ipcp.req_myaddr;
3147 		else
3148 			sppp_get_ip_addrs(sp, &ouraddr, 0, 0);
3149 		opt[i++] = IPCP_OPT_ADDRESS;
3150 		opt[i++] = 6;
3151 		opt[i++] = ouraddr >> 24;
3152 		opt[i++] = ouraddr >> 16;
3153 		opt[i++] = ouraddr >> 8;
3154 		opt[i++] = ouraddr;
3155 	}
3156 
3157 	sp->confid[IDX_IPCP] = ++sp->pp_seq;
3158 	sppp_cp_send(sp, PPP_IPCP, CONF_REQ, sp->confid[IDX_IPCP], i, opt);
3159 }
3160 
3161 /*
3162  *--------------------------------------------------------------------------*
3163  *                                                                          *
3164  *                      The IPv6CP implementation.                          *
3165  *                                                                          *
3166  *--------------------------------------------------------------------------*
3167  */
3168 
3169 #ifdef INET6
3170 HIDE void
3171 sppp_ipv6cp_init(struct sppp *sp)
3172 {
3173 	sp->ipv6cp.opts = 0;
3174 	sp->ipv6cp.flags = 0;
3175 	sp->state[IDX_IPV6CP] = STATE_INITIAL;
3176 	sp->fail_counter[IDX_IPV6CP] = 0;
3177 #if defined (__FreeBSD__)
3178 	callout_handle_init(&sp->ch[IDX_IPV6CP]);
3179 #endif
3180 }
3181 
3182 HIDE void
3183 sppp_ipv6cp_up(struct sppp *sp)
3184 {
3185 	sppp_up_event(&ipv6cp, sp);
3186 }
3187 
3188 HIDE void
3189 sppp_ipv6cp_down(struct sppp *sp)
3190 {
3191 	sppp_down_event(&ipv6cp, sp);
3192 }
3193 
3194 HIDE void
3195 sppp_ipv6cp_open(struct sppp *sp)
3196 {
3197 	STDDCL;
3198 	struct in6_addr myaddr, hisaddr;
3199 
3200 #ifdef IPV6CP_MYIFID_DYN
3201 	sp->ipv6cp.flags &= ~(IPV6CP_MYIFID_SEEN|IPV6CP_MYIFID_DYN);
3202 #else
3203 	sp->ipv6cp.flags &= ~IPV6CP_MYIFID_SEEN;
3204 #endif
3205 
3206 	sppp_get_ip6_addrs(sp, &myaddr, &hisaddr, 0);
3207 	/*
3208 	 * If we don't have our address, this probably means our
3209 	 * interface doesn't want to talk IPv6 at all.  (This could
3210 	 * be the case if somebody wants to speak only IPX, for
3211 	 * example.)  Don't open IPv6CP in this case.
3212 	 */
3213 	if (IN6_IS_ADDR_UNSPECIFIED(&myaddr)) {
3214 		/* XXX this message should go away */
3215 		if (debug)
3216 			log(LOG_DEBUG, SPP_FMT "ipv6cp_open(): no IPv6 interface\n",
3217 			    SPP_ARGS(ifp));
3218 		return;
3219 	}
3220 	sp->ipv6cp.flags |= IPV6CP_MYIFID_SEEN;
3221 	sp->ipv6cp.opts |= (1 << IPV6CP_OPT_IFID);
3222 	sppp_open_event(&ipv6cp, sp);
3223 }
3224 
3225 HIDE void
3226 sppp_ipv6cp_close(struct sppp *sp)
3227 {
3228 	sppp_close_event(&ipv6cp, sp);
3229 }
3230 
3231 HIDE void
3232 sppp_ipv6cp_TO(void *cookie)
3233 {
3234 	sppp_to_event(&ipv6cp, (struct sppp *)cookie);
3235 }
3236 
3237 HIDE int
3238 sppp_ipv6cp_RCR(struct sppp *sp, struct lcp_header *h, int len)
3239 {
3240 	u_char *buf, *r, *p;
3241 	struct ifnet *ifp = &sp->pp_if;
3242 	int rlen, origlen, debug = ifp->if_flags & IFF_DEBUG;
3243 	struct in6_addr myaddr, desiredaddr, suggestaddr;
3244 	int ifidcount;
3245 	int type;
3246 	int collision, nohisaddr;
3247 
3248 	len -= 4;
3249 	origlen = len;
3250 	/*
3251 	 * Make sure to allocate a buf that can at least hold a
3252 	 * conf-nak with an `address' option.  We might need it below.
3253 	 */
3254 	buf = r = malloc ((len < 6? 6: len), M_TEMP, M_NOWAIT);
3255 	if (! buf)
3256 		return (0);
3257 
3258 	/* pass 1: see if we can recognize them */
3259 	if (debug)
3260 		log(LOG_DEBUG, "%s: ipv6cp parse opts:",
3261 		    SPP_ARGS(ifp));
3262 	p = (void *)(h + 1);
3263 	ifidcount = 0;
3264 	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
3265 		/* Sanity check option length */
3266 		if (p[1] < 2 || p[1] > len) {
3267 			free(buf, M_TEMP);
3268 			return (-1);
3269 		}
3270 		if (debug)
3271 			addlog(" %s", sppp_ipv6cp_opt_name(*p));
3272 		switch (*p) {
3273 		case IPV6CP_OPT_IFID:
3274 			if (len >= 10 && p[1] == 10 && ifidcount == 0) {
3275 				/* correctly formed address option */
3276 				ifidcount++;
3277 				continue;
3278 			}
3279 			if (debug)
3280 				addlog(" [invalid]");
3281 			break;
3282 #ifdef notyet
3283 		case IPV6CP_OPT_COMPRESSION:
3284 			if (len >= 4 && p[1] >= 4) {
3285 				/* correctly formed compress option */
3286 				continue;
3287 			}
3288 			if (debug)
3289 				addlog(" [invalid]");
3290 			break;
3291 #endif
3292 		default:
3293 			/* Others not supported. */
3294 			if (debug)
3295 				addlog(" [rej]");
3296 			break;
3297 		}
3298 		/* Add the option to rejected list. */
3299 		bcopy (p, r, p[1]);
3300 		r += p[1];
3301 		rlen += p[1];
3302 	}
3303 	if (rlen) {
3304 		if (debug)
3305 			addlog(" send conf-rej\n");
3306 		sppp_cp_send(sp, PPP_IPV6CP, CONF_REJ, h->ident, rlen, buf);
3307 		goto end;
3308 	} else if (debug)
3309 		addlog("\n");
3310 
3311 	/* pass 2: parse option values */
3312 	sppp_get_ip6_addrs(sp, &myaddr, 0, 0);
3313 	if (debug)
3314 		log(LOG_DEBUG, "%s: ipv6cp parse opt values: ",
3315 		       SPP_ARGS(ifp));
3316 	p = (void *)(h + 1);
3317 	len = origlen;
3318 	type = CONF_ACK;
3319 	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
3320 		if (debug)
3321 			addlog(" %s", sppp_ipv6cp_opt_name(*p));
3322 		switch (*p) {
3323 #ifdef notyet
3324 		case IPV6CP_OPT_COMPRESSION:
3325 			continue;
3326 #endif
3327 		case IPV6CP_OPT_IFID:
3328 			memset(&desiredaddr, 0, sizeof(desiredaddr));
3329 			bcopy(&p[2], &desiredaddr.s6_addr[8], 8);
3330 			collision = (memcmp(&desiredaddr.s6_addr[8],
3331 					&myaddr.s6_addr[8], 8) == 0);
3332 			nohisaddr = IN6_IS_ADDR_UNSPECIFIED(&desiredaddr);
3333 
3334 			desiredaddr.s6_addr16[0] = htons(0xfe80);
3335 
3336 			if (!collision && !nohisaddr) {
3337 				/* no collision, hisaddr known - Conf-Ack */
3338 				type = CONF_ACK;
3339 
3340 				if (debug) {
3341 					addlog(" %s [%s]",
3342 					    ip6_sprintf(&desiredaddr),
3343 					    sppp_cp_type_name(type));
3344 				}
3345 				continue;
3346 			}
3347 
3348 			memset(&suggestaddr, 0, sizeof(suggestaddr));
3349 			if (collision && nohisaddr) {
3350 				/* collision, hisaddr unknown - Conf-Rej */
3351 				type = CONF_REJ;
3352 				memset(&p[2], 0, 8);
3353 			} else {
3354 				/*
3355 				 * - no collision, hisaddr unknown, or
3356 				 * - collision, hisaddr known
3357 				 * Conf-Nak, suggest hisaddr
3358 				 */
3359 				type = CONF_NAK;
3360 				sppp_suggest_ip6_addr(sp, &suggestaddr);
3361 				bcopy(&suggestaddr.s6_addr[8], &p[2], 8);
3362 			}
3363 			if (debug)
3364 				addlog(" %s [%s]", ip6_sprintf(&desiredaddr),
3365 				    sppp_cp_type_name(type));
3366 			break;
3367 		}
3368 		/* Add the option to nak'ed list. */
3369 		bcopy (p, r, p[1]);
3370 		r += p[1];
3371 		rlen += p[1];
3372 	}
3373 
3374 	if (rlen == 0 && type == CONF_ACK) {
3375 		if (debug)
3376 			addlog(" send %s\n", sppp_cp_type_name(type));
3377 		sppp_cp_send(sp, PPP_IPV6CP, type, h->ident, origlen, h + 1);
3378 	} else {
3379 #ifdef notdef
3380 		if (type == CONF_ACK)
3381 			panic("IPv6CP RCR: CONF_ACK with non-zero rlen");
3382 #endif
3383 
3384 		if (debug) {
3385 			addlog(" send %s suggest %s\n",
3386 			    sppp_cp_type_name(type), ip6_sprintf(&suggestaddr));
3387 		}
3388 		sppp_cp_send(sp, PPP_IPV6CP, type, h->ident, rlen, buf);
3389 	}
3390 
3391 end:
3392 	free(buf, M_TEMP);
3393 	return (rlen == 0);
3394 }
3395 
3396 HIDE void
3397 sppp_ipv6cp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
3398 {
3399 	u_char *p;
3400 	struct ifnet *ifp = &sp->pp_if;
3401 	int debug = ifp->if_flags & IFF_DEBUG;
3402 
3403 	len -= 4;
3404 
3405 	if (debug)
3406 		log(LOG_DEBUG, "%s: ipv6cp rej opts:",
3407 		    SPP_ARGS(ifp));
3408 
3409 	p = (void *)(h + 1);
3410 	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
3411 		if (p[1] < 2 || p[1] > len)
3412 			return;
3413 		if (debug)
3414 			addlog(" %s", sppp_ipv6cp_opt_name(*p));
3415 		switch (*p) {
3416 		case IPV6CP_OPT_IFID:
3417 			/*
3418 			 * Peer doesn't grok address option.  This is
3419 			 * bad.  XXX  Should we better give up here?
3420 			 */
3421 			sp->ipv6cp.opts &= ~(1 << IPV6CP_OPT_IFID);
3422 			break;
3423 #ifdef notyet
3424 		case IPV6CP_OPT_COMPRESS:
3425 			sp->ipv6cp.opts &= ~(1 << IPV6CP_OPT_COMPRESS);
3426 			break;
3427 #endif
3428 		}
3429 	}
3430 	if (debug)
3431 		addlog("\n");
3432 	return;
3433 }
3434 
3435 HIDE void
3436 sppp_ipv6cp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
3437 {
3438 	u_char *p;
3439 	struct ifnet *ifp = &sp->pp_if;
3440 	int debug = ifp->if_flags & IFF_DEBUG;
3441 	struct in6_addr suggestaddr;
3442 
3443 	len -= 4;
3444 
3445 	if (debug)
3446 		log(LOG_DEBUG, SPP_FMT "ipv6cp nak opts: ",
3447 		    SPP_ARGS(ifp));
3448 
3449 	p = (void*) (h+1);
3450 	for (; len > 1; len -= p[1], p += p[1]) {
3451 		if (p[1] < 2 || p[1] > len)
3452 			return;
3453 		if (debug)
3454 			addlog("%s ", sppp_ipv6cp_opt_name(*p));
3455 		switch (*p) {
3456 		case IPV6CP_OPT_IFID:
3457 			/*
3458 			 * Peer doesn't like our local ifid.  See
3459 			 * if we can do something for him.  We'll drop
3460 			 * him our address then.
3461 			 */
3462 			if (len < 10 || p[1] != 10)
3463 				break;
3464 			memset(&suggestaddr, 0, sizeof(suggestaddr));
3465 			suggestaddr.s6_addr16[0] = htons(0xfe80);
3466 			bcopy(&p[2], &suggestaddr.s6_addr[8], 8);
3467 
3468 			sp->ipv6cp.opts |= (1 << IPV6CP_OPT_IFID);
3469 			if (debug)
3470 				addlog(" [suggestaddr %s]",
3471 				       ip6_sprintf(&suggestaddr));
3472 #ifdef IPV6CP_MYIFID_DYN
3473 			/*
3474 			 * When doing dynamic address assignment,
3475 			 * we accept his offer.
3476 			 */
3477 			if (sp->ipv6cp.flags & IPV6CP_MYIFID_DYN) {
3478 				struct in6_addr lastsuggest;
3479 				/*
3480 				 * If <suggested myaddr from peer> equals to
3481 				 * <hisaddr we have suggested last time>,
3482 				 * we have a collision.  generate new random
3483 				 * ifid.
3484 				 */
3485 				sppp_suggest_ip6_addr(sp,&lastsuggest);
3486 				if (IN6_ARE_ADDR_EQUAL(&suggestaddr,
3487 						 &lastsuggest)) {
3488 					if (debug)
3489 						addlog(" [random]");
3490 					sppp_gen_ip6_addr(sp, &suggestaddr);
3491 				}
3492 				sppp_set_ip6_addr(sp, &suggestaddr);
3493 				if (debug)
3494 					addlog(" [agree]");
3495 				sp->ipv6cp.flags |= IPV6CP_MYIFID_SEEN;
3496 			}
3497 #else
3498 			/*
3499 			 * Since we do not do dynamic address assignment,
3500 			 * we ignore it and thus continue to negotiate
3501 			 * our already existing value.  This can possibly
3502 			 * go into infinite request-reject loop.
3503 			 *
3504 			 * This is not likely because we normally use
3505 			 * ifid based on MAC-address.
3506 			 * If you have no ethernet card on the node, too bad.
3507 			 * XXX should we use fail_counter?
3508 			 */
3509 #endif
3510 			break;
3511 #ifdef notyet
3512 		case IPV6CP_OPT_COMPRESS:
3513 			/*
3514 			 * Peer wants different compression parameters.
3515 			 */
3516 			break;
3517 #endif
3518 		}
3519 	}
3520 	if (debug)
3521 		addlog("\n");
3522 }
3523 
3524 HIDE void
3525 sppp_ipv6cp_tlu(struct sppp *sp)
3526 {
3527 }
3528 
3529 HIDE void
3530 sppp_ipv6cp_tld(struct sppp *sp)
3531 {
3532 }
3533 
3534 HIDE void
3535 sppp_ipv6cp_tls(struct sppp *sp)
3536 {
3537 	/* indicate to LCP that it must stay alive */
3538 	sp->lcp.protos |= (1 << IDX_IPV6CP);
3539 }
3540 
3541 HIDE void
3542 sppp_ipv6cp_tlf(struct sppp *sp)
3543 {
3544 	/* we no longer need LCP */
3545 	sp->lcp.protos &= ~(1 << IDX_IPV6CP);
3546 	sppp_lcp_check_and_close(sp);
3547 }
3548 
3549 HIDE void
3550 sppp_ipv6cp_scr(struct sppp *sp)
3551 {
3552 	char opt[10 /* ifid */ + 4 /* compression, minimum */];
3553 	struct in6_addr ouraddr;
3554 	int i = 0;
3555 
3556 	if (sp->ipv6cp.opts & (1 << IPV6CP_OPT_IFID)) {
3557 		sppp_get_ip6_addrs(sp, &ouraddr, 0, 0);
3558 		opt[i++] = IPV6CP_OPT_IFID;
3559 		opt[i++] = 10;
3560 		bcopy(&ouraddr.s6_addr[8], &opt[i], 8);
3561 		i += 8;
3562 	}
3563 
3564 #ifdef notyet
3565 	if (sp->ipv6cp.opts & (1 << IPV6CP_OPT_COMPRESSION)) {
3566 		opt[i++] = IPV6CP_OPT_COMPRESSION;
3567 		opt[i++] = 4;
3568 p		opt[i++] = 0;   /* TBD */
3569 		opt[i++] = 0;   /* TBD */
3570 		/* variable length data may follow */
3571 	}
3572 #endif
3573 
3574 	sp->confid[IDX_IPV6CP] = ++sp->pp_seq;
3575 	sppp_cp_send(sp, PPP_IPV6CP, CONF_REQ, sp->confid[IDX_IPV6CP], i, opt);
3576 }
3577 #else /*INET6*/
3578 HIDE void
3579 sppp_ipv6cp_init(struct sppp *sp)
3580 {
3581 }
3582 
3583 HIDE void
3584 sppp_ipv6cp_up(struct sppp *sp)
3585 {
3586 }
3587 
3588 HIDE void
3589 sppp_ipv6cp_down(struct sppp *sp)
3590 {
3591 }
3592 
3593 HIDE void
3594 sppp_ipv6cp_open(struct sppp *sp)
3595 {
3596 }
3597 
3598 HIDE void
3599 sppp_ipv6cp_close(struct sppp *sp)
3600 {
3601 }
3602 
3603 HIDE void
3604 sppp_ipv6cp_TO(void *sp)
3605 {
3606 }
3607 
3608 HIDE int
3609 sppp_ipv6cp_RCR(struct sppp *sp, struct lcp_header *h,
3610 		int len)
3611 {
3612 	return 0;
3613 }
3614 
3615 HIDE void
3616 sppp_ipv6cp_RCN_rej(struct sppp *sp, struct lcp_header *h,
3617 		    int len)
3618 {
3619 }
3620 
3621 HIDE void
3622 sppp_ipv6cp_RCN_nak(struct sppp *sp, struct lcp_header *h,
3623 		    int len)
3624 {
3625 }
3626 
3627 HIDE void
3628 sppp_ipv6cp_tlu(struct sppp *sp)
3629 {
3630 }
3631 
3632 HIDE void
3633 sppp_ipv6cp_tld(struct sppp *sp)
3634 {
3635 }
3636 
3637 HIDE void
3638 sppp_ipv6cp_tls(struct sppp *sp)
3639 {
3640 }
3641 
3642 HIDE void
3643 sppp_ipv6cp_tlf(struct sppp *sp)
3644 {
3645 }
3646 
3647 HIDE void
3648 sppp_ipv6cp_scr(struct sppp *sp)
3649 {
3650 }
3651 #endif /*INET6*/
3652 
3653 /*
3654  *--------------------------------------------------------------------------*
3655  *                                                                          *
3656  *                        The CHAP implementation.                          *
3657  *                                                                          *
3658  *--------------------------------------------------------------------------*
3659  */
3660 
3661 /*
3662  * The authentication protocols don't employ a full-fledged state machine as
3663  * the control protocols do, since they do have Open and Close events, but
3664  * not Up and Down, nor are they explicitly terminated.  Also, use of the
3665  * authentication protocols may be different in both directions (this makes
3666  * sense, think of a machine that never accepts incoming calls but only
3667  * calls out, it doesn't require the called party to authenticate itself).
3668  *
3669  * Our state machine for the local authentication protocol (we are requesting
3670  * the peer to authenticate) looks like:
3671  *
3672  *						    RCA-
3673  *	      +--------------------------------------------+
3674  *	      V					    scn,tld|
3675  *	  +--------+			       Close   +---------+ RCA+
3676  *	  |	   |<----------------------------------|	 |------+
3677  *   +--->| Closed |				TO*    | Opened	 | sca	|
3678  *   |	  |	   |-----+		       +-------|	 |<-----+
3679  *   |	  +--------+ irc |		       |       +---------+
3680  *   |	    ^		 |		       |	   ^
3681  *   |	    |		 |		       |	   |
3682  *   |	    |		 |		       |	   |
3683  *   |	 TO-|		 |		       |	   |
3684  *   |	    |tld  TO+	 V		       |	   |
3685  *   |	    |	+------->+		       |	   |
3686  *   |	    |	|	 |		       |	   |
3687  *   |	  +--------+	 V		       |	   |
3688  *   |	  |	   |<----+<--------------------+	   |
3689  *   |	  | Req-   | scr				   |
3690  *   |	  | Sent   |					   |
3691  *   |	  |	   |					   |
3692  *   |	  +--------+					   |
3693  *   | RCA- |	| RCA+					   |
3694  *   +------+	+------------------------------------------+
3695  *   scn,tld	  sca,irc,ict,tlu
3696  *
3697  *
3698  *   with:
3699  *
3700  *	Open:	LCP reached authentication phase
3701  *	Close:	LCP reached terminate phase
3702  *
3703  *	RCA+:	received reply (pap-req, chap-response), acceptable
3704  *	RCN:	received reply (pap-req, chap-response), not acceptable
3705  *	TO+:	timeout with restart counter >= 0
3706  *	TO-:	timeout with restart counter < 0
3707  *	TO*:	reschedule timeout for CHAP
3708  *
3709  *	scr:	send request packet (none for PAP, chap-challenge)
3710  *	sca:	send ack packet (pap-ack, chap-success)
3711  *	scn:	send nak packet (pap-nak, chap-failure)
3712  *	ict:	initialize re-challenge timer (CHAP only)
3713  *
3714  *	tlu:	this-layer-up, LCP reaches network phase
3715  *	tld:	this-layer-down, LCP enters terminate phase
3716  *
3717  * Note that in CHAP mode, after sending a new challenge, while the state
3718  * automaton falls back into Req-Sent state, it doesn't signal a tld
3719  * event to LCP, so LCP remains in network phase.  Only after not getting
3720  * any response (or after getting an unacceptable response), CHAP closes,
3721  * causing LCP to enter terminate phase.
3722  *
3723  * With PAP, there is no initial request that can be sent.  The peer is
3724  * expected to send one based on the successful negotiation of PAP as
3725  * the authentication protocol during the LCP option negotiation.
3726  *
3727  * Incoming authentication protocol requests (remote requests
3728  * authentication, we are peer) don't employ a state machine at all,
3729  * they are simply answered.  Some peers [Ascend P50 firmware rev
3730  * 4.50] react allergically when sending IPCP requests while they are
3731  * still in authentication phase (thereby violating the standard that
3732  * demands that these NCP packets are to be discarded), so we keep
3733  * track of the peer demanding us to authenticate, and only proceed to
3734  * phase network once we've seen a positive acknowledge for the
3735  * authentication.
3736  */
3737 
3738 /*
3739  * Handle incoming CHAP packets.
3740  */
3741 void
3742 sppp_chap_input(struct sppp *sp, struct mbuf *m)
3743 {
3744 	STDDCL;
3745 	struct lcp_header *h;
3746 	int len, x;
3747 	u_char *value, *name, digest[AUTHCHALEN], dsize;
3748 	int value_len, name_len;
3749 	MD5_CTX ctx;
3750 
3751 	len = m->m_pkthdr.len;
3752 	if (len < 4) {
3753 		if (debug)
3754 			log(LOG_DEBUG,
3755 			    SPP_FMT "chap invalid packet length: %d bytes\n",
3756 			    SPP_ARGS(ifp), len);
3757 		return;
3758 	}
3759 	h = mtod (m, struct lcp_header*);
3760 	if (len > ntohs (h->len))
3761 		len = ntohs (h->len);
3762 
3763 	switch (h->type) {
3764 	/* challenge, failure and success are his authproto */
3765 	case CHAP_CHALLENGE:
3766 		value = 1 + (u_char*)(h+1);
3767 		value_len = value[-1];
3768 		name = value + value_len;
3769 		name_len = len - value_len - 5;
3770 		if (name_len < 0) {
3771 			if (debug) {
3772 				log(LOG_DEBUG,
3773 				    SPP_FMT "chap corrupted challenge "
3774 				    "<%s id=0x%x len=%d",
3775 				    SPP_ARGS(ifp),
3776 				    sppp_auth_type_name(PPP_CHAP, h->type),
3777 				    h->ident, ntohs(h->len));
3778 				if (len > 4)
3779 					sppp_print_bytes((u_char*) (h+1), len-4);
3780 				addlog(">\n");
3781 			}
3782 			break;
3783 		}
3784 
3785 		if (debug) {
3786 			log(LOG_DEBUG,
3787 			    SPP_FMT "chap input <%s id=0x%x len=%d name=",
3788 			    SPP_ARGS(ifp),
3789 			    sppp_auth_type_name(PPP_CHAP, h->type), h->ident,
3790 			    ntohs(h->len));
3791 			sppp_print_string((char*) name, name_len);
3792 			addlog(" value-size=%d value=", value_len);
3793 			sppp_print_bytes(value, value_len);
3794 			addlog(">\n");
3795 		}
3796 
3797 		/* Compute reply value. */
3798 		MD5Init(&ctx);
3799 		MD5Update(&ctx, &h->ident, 1);
3800 		MD5Update(&ctx, sp->myauth.secret, strlen(sp->myauth.secret));
3801 		MD5Update(&ctx, value, value_len);
3802 		MD5Final(digest, &ctx);
3803 		dsize = sizeof digest;
3804 
3805 		sppp_auth_send(&chap, sp, CHAP_RESPONSE, h->ident,
3806 			       sizeof dsize, (const char *)&dsize,
3807 			       sizeof digest, digest,
3808 			       strlen(sp->myauth.name),
3809 			       sp->myauth.name,
3810 			       0);
3811 		break;
3812 
3813 	case CHAP_SUCCESS:
3814 		if (debug) {
3815 			log(LOG_DEBUG, SPP_FMT "chap success",
3816 			    SPP_ARGS(ifp));
3817 			if (len > 4) {
3818 				addlog(": ");
3819 				sppp_print_string((char*)(h + 1), len - 4);
3820 			}
3821 			addlog("\n");
3822 		}
3823 		x = splnet();
3824 		sp->pp_flags &= ~PP_NEEDAUTH;
3825 		if (sp->myauth.proto == PPP_CHAP &&
3826 		    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) &&
3827 		    (sp->lcp.protos & (1 << IDX_CHAP)) == 0) {
3828 			/*
3829 			 * We are authenticator for CHAP but didn't
3830 			 * complete yet.  Leave it to tlu to proceed
3831 			 * to network phase.
3832 			 */
3833 			splx(x);
3834 			break;
3835 		}
3836 		splx(x);
3837 		sppp_phase_network(sp);
3838 		break;
3839 
3840 	case CHAP_FAILURE:
3841 		if (debug) {
3842 			log(LOG_INFO, SPP_FMT "chap failure",
3843 			    SPP_ARGS(ifp));
3844 			if (len > 4) {
3845 				addlog(": ");
3846 				sppp_print_string((char*)(h + 1), len - 4);
3847 			}
3848 			addlog("\n");
3849 		} else
3850 			log(LOG_INFO, SPP_FMT "chap failure\n",
3851 			    SPP_ARGS(ifp));
3852 		/* await LCP shutdown by authenticator */
3853 		break;
3854 
3855 	/* response is my authproto */
3856 	case CHAP_RESPONSE:
3857 		value = 1 + (u_char*)(h+1);
3858 		value_len = value[-1];
3859 		name = value + value_len;
3860 		name_len = len - value_len - 5;
3861 		if (name_len < 0) {
3862 			if (debug) {
3863 				log(LOG_DEBUG,
3864 				    SPP_FMT "chap corrupted response "
3865 				    "<%s id=0x%x len=%d",
3866 				    SPP_ARGS(ifp),
3867 				    sppp_auth_type_name(PPP_CHAP, h->type),
3868 				    h->ident, ntohs(h->len));
3869 				if (len > 4)
3870 					sppp_print_bytes((u_char*)(h+1), len-4);
3871 				addlog(">\n");
3872 			}
3873 			break;
3874 		}
3875 		if (h->ident != sp->confid[IDX_CHAP]) {
3876 			if (debug)
3877 				log(LOG_DEBUG,
3878 				    SPP_FMT "chap dropping response for old ID "
3879 				    "(got %d, expected %d)\n",
3880 				    SPP_ARGS(ifp),
3881 				    h->ident, sp->confid[IDX_CHAP]);
3882 			break;
3883 		}
3884 		if (name_len != strlen(sp->hisauth.name)
3885 		    || bcmp(name, sp->hisauth.name, name_len) != 0) {
3886 			log(LOG_INFO, SPP_FMT "chap response, his name ",
3887 			    SPP_ARGS(ifp));
3888 			sppp_print_string(name, name_len);
3889 			addlog(" != expected ");
3890 			sppp_print_string(sp->hisauth.name,
3891 			    strlen(sp->hisauth.name));
3892 			addlog("\n");
3893 		}
3894 		if (debug) {
3895 			log(LOG_DEBUG, SPP_FMT "chap input(%s) "
3896 			    "<%s id=0x%x len=%d name=",
3897 			    SPP_ARGS(ifp),
3898 			    sppp_state_name(sp->state[IDX_CHAP]),
3899 			    sppp_auth_type_name(PPP_CHAP, h->type),
3900 			    h->ident, ntohs (h->len));
3901 			sppp_print_string((char*)name, name_len);
3902 			addlog(" value-size=%d value=", value_len);
3903 			sppp_print_bytes(value, value_len);
3904 			addlog(">\n");
3905 		}
3906 		if (value_len != AUTHCHALEN) {
3907 			if (debug)
3908 				log(LOG_DEBUG,
3909 				    SPP_FMT "chap bad hash value length: "
3910 				    "%d bytes, should be %d\n",
3911 				    SPP_ARGS(ifp), value_len,
3912 				    AUTHCHALEN);
3913 			break;
3914 		}
3915 
3916 		MD5Init(&ctx);
3917 		MD5Update(&ctx, &h->ident, 1);
3918 		MD5Update(&ctx, sp->hisauth.secret, strlen(sp->hisauth.secret));
3919 		MD5Update(&ctx, sp->chap_challenge, AUTHCHALEN);
3920 		MD5Final(digest, &ctx);
3921 
3922 #define FAILMSG "Failed..."
3923 #define SUCCMSG "Welcome!"
3924 
3925 		if (value_len != sizeof digest ||
3926 		    timingsafe_bcmp(digest, value, value_len) != 0) {
3927 			/* action scn, tld */
3928 			sppp_auth_send(&chap, sp, CHAP_FAILURE, h->ident,
3929 				       sizeof(FAILMSG) - 1, (u_char *)FAILMSG,
3930 				       0);
3931 			chap.tld(sp);
3932 			break;
3933 		}
3934 		/* action sca, perhaps tlu */
3935 		if (sp->state[IDX_CHAP] == STATE_REQ_SENT ||
3936 		    sp->state[IDX_CHAP] == STATE_OPENED)
3937 			sppp_auth_send(&chap, sp, CHAP_SUCCESS, h->ident,
3938 				       sizeof(SUCCMSG) - 1, (u_char *)SUCCMSG,
3939 				       0);
3940 		if (sp->state[IDX_CHAP] == STATE_REQ_SENT) {
3941 			sppp_cp_change_state(&chap, sp, STATE_OPENED);
3942 			chap.tlu(sp);
3943 		}
3944 		break;
3945 
3946 	default:
3947 		/* Unknown CHAP packet type -- ignore. */
3948 		if (debug) {
3949 			log(LOG_DEBUG, SPP_FMT "chap unknown input(%s) "
3950 			    "<0x%x id=0x%xh len=%d",
3951 			    SPP_ARGS(ifp),
3952 			    sppp_state_name(sp->state[IDX_CHAP]),
3953 			    h->type, h->ident, ntohs(h->len));
3954 			if (len > 4)
3955 				sppp_print_bytes((u_char*)(h+1), len-4);
3956 			addlog(">\n");
3957 		}
3958 		break;
3959 
3960 	}
3961 }
3962 
3963 HIDE void
3964 sppp_chap_init(struct sppp *sp)
3965 {
3966 	/* Chap doesn't have STATE_INITIAL at all. */
3967 	sp->state[IDX_CHAP] = STATE_CLOSED;
3968 	sp->fail_counter[IDX_CHAP] = 0;
3969 #if defined (__FreeBSD__)
3970 	callout_handle_init(&sp->ch[IDX_CHAP]);
3971 #endif
3972 }
3973 
3974 HIDE void
3975 sppp_chap_open(struct sppp *sp)
3976 {
3977 	if (sp->myauth.proto == PPP_CHAP &&
3978 	    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0) {
3979 		/* we are authenticator for CHAP, start it */
3980 		chap.scr(sp);
3981 		sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3982 		sppp_cp_change_state(&chap, sp, STATE_REQ_SENT);
3983 	}
3984 	/* nothing to be done if we are peer, await a challenge */
3985 }
3986 
3987 HIDE void
3988 sppp_chap_close(struct sppp *sp)
3989 {
3990 	if (sp->state[IDX_CHAP] != STATE_CLOSED)
3991 		sppp_cp_change_state(&chap, sp, STATE_CLOSED);
3992 }
3993 
3994 HIDE void
3995 sppp_chap_TO(void *cookie)
3996 {
3997 	struct sppp *sp = (struct sppp *)cookie;
3998 	STDDCL;
3999 	int s;
4000 
4001 	s = splnet();
4002 	if (debug)
4003 		log(LOG_DEBUG, SPP_FMT "chap TO(%s) rst_counter = %d\n",
4004 		    SPP_ARGS(ifp),
4005 		    sppp_state_name(sp->state[IDX_CHAP]),
4006 		    sp->rst_counter[IDX_CHAP]);
4007 
4008 	if (--sp->rst_counter[IDX_CHAP] < 0)
4009 		/* TO- event */
4010 		switch (sp->state[IDX_CHAP]) {
4011 		case STATE_REQ_SENT:
4012 			chap.tld(sp);
4013 			sppp_cp_change_state(&chap, sp, STATE_CLOSED);
4014 			break;
4015 		}
4016 	else
4017 		/* TO+ (or TO*) event */
4018 		switch (sp->state[IDX_CHAP]) {
4019 		case STATE_OPENED:
4020 			/* TO* event */
4021 			sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
4022 			/* FALLTHROUGH */
4023 		case STATE_REQ_SENT:
4024 			chap.scr(sp);
4025 			/* sppp_cp_change_state() will restart the timer */
4026 			sppp_cp_change_state(&chap, sp, STATE_REQ_SENT);
4027 			break;
4028 		}
4029 
4030 	splx(s);
4031 }
4032 
4033 HIDE void
4034 sppp_chap_tlu(struct sppp *sp)
4035 {
4036 	STDDCL;
4037 	int i = 0, x;
4038 
4039 	i = 0;
4040 	sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
4041 
4042 	/*
4043 	 * Some broken CHAP implementations (Conware CoNet, firmware
4044 	 * 4.0.?) don't want to re-authenticate their CHAP once the
4045 	 * initial challenge-response exchange has taken place.
4046 	 * Provide for an option to avoid rechallenges.
4047 	 */
4048 	if ((sp->hisauth.flags & AUTHFLAG_NORECHALLENGE) == 0) {
4049 		/*
4050 		 * Compute the re-challenge timeout.  This will yield
4051 		 * a number between 300 and 810 seconds.
4052 		 */
4053 		i = 300 + (arc4random() & 0x01fe);
4054 
4055 #if defined (__FreeBSD__)
4056 		sp->ch[IDX_CHAP] = timeout(chap.TO, (void *)sp, i * hz);
4057 #elif defined(__OpenBSD__)
4058 		timeout_add_sec(&sp->ch[IDX_CHAP], i);
4059 #endif
4060 	}
4061 
4062 	if (debug) {
4063 		log(LOG_DEBUG,
4064 		    SPP_FMT "chap %s, ",
4065 		    SPP_ARGS(ifp),
4066 		    sp->pp_phase == PHASE_NETWORK? "reconfirmed": "tlu");
4067 		if ((sp->hisauth.flags & AUTHFLAG_NORECHALLENGE) == 0)
4068 			addlog("next re-challenge in %d seconds\n", i);
4069 		else
4070 			addlog("re-challenging suppressed\n");
4071 	}
4072 
4073 	x = splnet();
4074 	/* indicate to LCP that we need to be closed down */
4075 	sp->lcp.protos |= (1 << IDX_CHAP);
4076 
4077 	if (sp->pp_flags & PP_NEEDAUTH) {
4078 		/*
4079 		 * Remote is authenticator, but his auth proto didn't
4080 		 * complete yet.  Defer the transition to network
4081 		 * phase.
4082 		 */
4083 		splx(x);
4084 		return;
4085 	}
4086 	splx(x);
4087 
4088 	/*
4089 	 * If we are already in phase network, we are done here.  This
4090 	 * is the case if this is a dummy tlu event after a re-challenge.
4091 	 */
4092 	if (sp->pp_phase != PHASE_NETWORK)
4093 		sppp_phase_network(sp);
4094 }
4095 
4096 HIDE void
4097 sppp_chap_tld(struct sppp *sp)
4098 {
4099 	STDDCL;
4100 
4101 	if (debug)
4102 		log(LOG_DEBUG, SPP_FMT "chap tld\n", SPP_ARGS(ifp));
4103 	UNTIMEOUT(chap.TO, (void *)sp, sp->ch[IDX_CHAP]);
4104 	sp->lcp.protos &= ~(1 << IDX_CHAP);
4105 
4106 	lcp.Close(sp);
4107 }
4108 
4109 HIDE void
4110 sppp_chap_scr(struct sppp *sp)
4111 {
4112 	u_char clen;
4113 
4114 	/* Compute random challenge. */
4115 	arc4random_buf(sp->chap_challenge, sizeof(sp->chap_challenge));
4116 	clen = AUTHCHALEN;
4117 
4118 	sp->confid[IDX_CHAP] = ++sp->pp_seq;
4119 
4120 	sppp_auth_send(&chap, sp, CHAP_CHALLENGE, sp->confid[IDX_CHAP],
4121 		       sizeof clen, (const char *)&clen,
4122 		       (size_t)AUTHCHALEN, sp->chap_challenge,
4123 		       strlen(sp->myauth.name),
4124 		       sp->myauth.name,
4125 		       0);
4126 }
4127 /*
4128  *--------------------------------------------------------------------------*
4129  *                                                                          *
4130  *                        The PAP implementation.                           *
4131  *                                                                          *
4132  *--------------------------------------------------------------------------*
4133  */
4134 /*
4135  * For PAP, we need to keep a little state also if we are the peer, not the
4136  * authenticator.  This is since we don't get a request to authenticate, but
4137  * have to repeatedly authenticate ourself until we got a response (or the
4138  * retry counter is expired).
4139  */
4140 
4141 /*
4142  * Handle incoming PAP packets.  */
4143 HIDE void
4144 sppp_pap_input(struct sppp *sp, struct mbuf *m)
4145 {
4146 	STDDCL;
4147 	struct lcp_header *h;
4148 	int len, x;
4149 	u_char *name, *passwd, mlen;
4150 	int name_len, passwd_len;
4151 
4152 	len = m->m_pkthdr.len;
4153 	if (len < 5) {
4154 		if (debug)
4155 			log(LOG_DEBUG,
4156 			    SPP_FMT "pap invalid packet length: %d bytes\n",
4157 			    SPP_ARGS(ifp), len);
4158 		return;
4159 	}
4160 	h = mtod (m, struct lcp_header*);
4161 	if (len > ntohs (h->len))
4162 		len = ntohs (h->len);
4163 	switch (h->type) {
4164 	/* PAP request is my authproto */
4165 	case PAP_REQ:
4166 		name = 1 + (u_char*)(h+1);
4167 		name_len = name[-1];
4168 		passwd = name + name_len + 1;
4169 		if (name_len > len - 6 ||
4170 		    (passwd_len = passwd[-1]) > len - 6 - name_len) {
4171 			if (debug) {
4172 				log(LOG_DEBUG, SPP_FMT "pap corrupted input "
4173 				    "<%s id=0x%x len=%d",
4174 				    SPP_ARGS(ifp),
4175 				    sppp_auth_type_name(PPP_PAP, h->type),
4176 				    h->ident, ntohs(h->len));
4177 				if (len > 4)
4178 					sppp_print_bytes((u_char*)(h+1), len-4);
4179 				addlog(">\n");
4180 			}
4181 			break;
4182 		}
4183 		if (debug) {
4184 			log(LOG_DEBUG, SPP_FMT "pap input(%s) "
4185 			    "<%s id=0x%x len=%d name=",
4186 			    SPP_ARGS(ifp),
4187 			    sppp_state_name(sp->state[IDX_PAP]),
4188 			    sppp_auth_type_name(PPP_PAP, h->type),
4189 			    h->ident, ntohs(h->len));
4190 			sppp_print_string((char*)name, name_len);
4191 			addlog(" passwd=");
4192 			sppp_print_string((char*)passwd, passwd_len);
4193 			addlog(">\n");
4194 		}
4195 		if (name_len > AUTHMAXLEN ||
4196 		    passwd_len > AUTHMAXLEN ||
4197 		    bcmp(name, sp->hisauth.name, name_len) != 0 ||
4198 		    bcmp(passwd, sp->hisauth.secret, passwd_len) != 0) {
4199 			/* action scn, tld */
4200 			mlen = sizeof(FAILMSG) - 1;
4201 			sppp_auth_send(&pap, sp, PAP_NAK, h->ident,
4202 				       sizeof mlen, (const char *)&mlen,
4203 				       sizeof(FAILMSG) - 1, (u_char *)FAILMSG,
4204 				       0);
4205 			pap.tld(sp);
4206 			break;
4207 		}
4208 		/* action sca, perhaps tlu */
4209 		if (sp->state[IDX_PAP] == STATE_REQ_SENT ||
4210 		    sp->state[IDX_PAP] == STATE_OPENED) {
4211 			mlen = sizeof(SUCCMSG) - 1;
4212 			sppp_auth_send(&pap, sp, PAP_ACK, h->ident,
4213 				       sizeof mlen, (const char *)&mlen,
4214 				       sizeof(SUCCMSG) - 1, (u_char *)SUCCMSG,
4215 				       0);
4216 		}
4217 		if (sp->state[IDX_PAP] == STATE_REQ_SENT) {
4218 			sppp_cp_change_state(&pap, sp, STATE_OPENED);
4219 			pap.tlu(sp);
4220 		}
4221 		break;
4222 
4223 	/* ack and nak are his authproto */
4224 	case PAP_ACK:
4225 		UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
4226 		if (debug) {
4227 			log(LOG_DEBUG, SPP_FMT "pap success",
4228 			    SPP_ARGS(ifp));
4229 			name_len = *((char *)h);
4230 			if (len > 5 && name_len) {
4231 				addlog(": ");
4232 				sppp_print_string((char*)(h+1), name_len);
4233 			}
4234 			addlog("\n");
4235 		}
4236 		x = splnet();
4237 		sp->pp_flags &= ~PP_NEEDAUTH;
4238 		if (sp->myauth.proto == PPP_PAP &&
4239 		    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) &&
4240 		    (sp->lcp.protos & (1 << IDX_PAP)) == 0) {
4241 			/*
4242 			 * We are authenticator for PAP but didn't
4243 			 * complete yet.  Leave it to tlu to proceed
4244 			 * to network phase.
4245 			 */
4246 			splx(x);
4247 			break;
4248 		}
4249 		splx(x);
4250 		sppp_phase_network(sp);
4251 		break;
4252 
4253 	case PAP_NAK:
4254 		UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
4255 		if (debug) {
4256 			log(LOG_INFO, SPP_FMT "pap failure",
4257 			    SPP_ARGS(ifp));
4258 			name_len = *((char *)h);
4259 			if (len > 5 && name_len) {
4260 				addlog(": ");
4261 				sppp_print_string((char*)(h+1), name_len);
4262 			}
4263 			addlog("\n");
4264 		} else
4265 			log(LOG_INFO, SPP_FMT "pap failure\n",
4266 			    SPP_ARGS(ifp));
4267 		/* await LCP shutdown by authenticator */
4268 		break;
4269 
4270 	default:
4271 		/* Unknown PAP packet type -- ignore. */
4272 		if (debug) {
4273 			log(LOG_DEBUG, SPP_FMT "pap corrupted input "
4274 			    "<0x%x id=0x%x len=%d",
4275 			    SPP_ARGS(ifp),
4276 			    h->type, h->ident, ntohs(h->len));
4277 			if (len > 4)
4278 				sppp_print_bytes((u_char*)(h+1), len-4);
4279 			addlog(">\n");
4280 		}
4281 		break;
4282 
4283 	}
4284 }
4285 
4286 HIDE void
4287 sppp_pap_init(struct sppp *sp)
4288 {
4289 	/* PAP doesn't have STATE_INITIAL at all. */
4290 	sp->state[IDX_PAP] = STATE_CLOSED;
4291 	sp->fail_counter[IDX_PAP] = 0;
4292 #if defined (__FreeBSD__)
4293 	callout_handle_init(&sp->ch[IDX_PAP]);
4294 	callout_handle_init(&sp->pap_my_to_ch);
4295 #endif
4296 }
4297 
4298 HIDE void
4299 sppp_pap_open(struct sppp *sp)
4300 {
4301 	if (sp->hisauth.proto == PPP_PAP &&
4302 	    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0) {
4303 		/* we are authenticator for PAP, start our timer */
4304 		sp->rst_counter[IDX_PAP] = sp->lcp.max_configure;
4305 		sppp_cp_change_state(&pap, sp, STATE_REQ_SENT);
4306 	}
4307 	if (sp->myauth.proto == PPP_PAP) {
4308 		/* we are peer, send a request, and start a timer */
4309 		pap.scr(sp);
4310 #if defined (__FreeBSD__)
4311 		sp->pap_my_to_ch =
4312 		    timeout(sppp_pap_my_TO, (void *)sp, sp->lcp.timeout);
4313 #elif defined (__OpenBSD__)
4314 		timeout_add(&sp->pap_my_to_ch, sp->lcp.timeout);
4315 #endif
4316 	}
4317 }
4318 
4319 HIDE void
4320 sppp_pap_close(struct sppp *sp)
4321 {
4322 	if (sp->state[IDX_PAP] != STATE_CLOSED)
4323 		sppp_cp_change_state(&pap, sp, STATE_CLOSED);
4324 }
4325 
4326 /*
4327  * That's the timeout routine if we are authenticator.  Since the
4328  * authenticator is basically passive in PAP, we can't do much here.
4329  */
4330 HIDE void
4331 sppp_pap_TO(void *cookie)
4332 {
4333 	struct sppp *sp = (struct sppp *)cookie;
4334 	STDDCL;
4335 	int s;
4336 
4337 	s = splnet();
4338 	if (debug)
4339 		log(LOG_DEBUG, SPP_FMT "pap TO(%s) rst_counter = %d\n",
4340 		    SPP_ARGS(ifp),
4341 		    sppp_state_name(sp->state[IDX_PAP]),
4342 		    sp->rst_counter[IDX_PAP]);
4343 
4344 	if (--sp->rst_counter[IDX_PAP] < 0)
4345 		/* TO- event */
4346 		switch (sp->state[IDX_PAP]) {
4347 		case STATE_REQ_SENT:
4348 			pap.tld(sp);
4349 			sppp_cp_change_state(&pap, sp, STATE_CLOSED);
4350 			break;
4351 		}
4352 	else
4353 		/* TO+ event, not very much we could do */
4354 		switch (sp->state[IDX_PAP]) {
4355 		case STATE_REQ_SENT:
4356 			/* sppp_cp_change_state() will restart the timer */
4357 			sppp_cp_change_state(&pap, sp, STATE_REQ_SENT);
4358 			break;
4359 		}
4360 
4361 	splx(s);
4362 }
4363 
4364 /*
4365  * That's the timeout handler if we are peer.  Since the peer is active,
4366  * we need to retransmit our PAP request since it is apparently lost.
4367  * XXX We should impose a max counter.
4368  */
4369 HIDE void
4370 sppp_pap_my_TO(void *cookie)
4371 {
4372 	struct sppp *sp = (struct sppp *)cookie;
4373 	STDDCL;
4374 
4375 	if (debug)
4376 		log(LOG_DEBUG, SPP_FMT "pap peer TO\n",
4377 		    SPP_ARGS(ifp));
4378 
4379 	pap.scr(sp);
4380 }
4381 
4382 HIDE void
4383 sppp_pap_tlu(struct sppp *sp)
4384 {
4385 	STDDCL;
4386 	int x;
4387 
4388 	sp->rst_counter[IDX_PAP] = sp->lcp.max_configure;
4389 
4390 	if (debug)
4391 		log(LOG_DEBUG, SPP_FMT "%s tlu\n",
4392 		    SPP_ARGS(ifp), pap.name);
4393 
4394 	x = splnet();
4395 	/* indicate to LCP that we need to be closed down */
4396 	sp->lcp.protos |= (1 << IDX_PAP);
4397 
4398 	if (sp->pp_flags & PP_NEEDAUTH) {
4399 		/*
4400 		 * Remote is authenticator, but his auth proto didn't
4401 		 * complete yet.  Defer the transition to network
4402 		 * phase.
4403 		 */
4404 		splx(x);
4405 		return;
4406 	}
4407 	splx(x);
4408 	sppp_phase_network(sp);
4409 }
4410 
4411 HIDE void
4412 sppp_pap_tld(struct sppp *sp)
4413 {
4414 	STDDCL;
4415 
4416 	if (debug)
4417 		log(LOG_DEBUG, SPP_FMT "pap tld\n", SPP_ARGS(ifp));
4418 	UNTIMEOUT(pap.TO, (void *)sp, sp->ch[IDX_PAP]);
4419 	UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
4420 	sp->lcp.protos &= ~(1 << IDX_PAP);
4421 
4422 	lcp.Close(sp);
4423 }
4424 
4425 HIDE void
4426 sppp_pap_scr(struct sppp *sp)
4427 {
4428 	u_char idlen, pwdlen;
4429 
4430 	sp->confid[IDX_PAP] = ++sp->pp_seq;
4431 	pwdlen = strlen(sp->myauth.secret);
4432 	idlen = strlen(sp->myauth.name);
4433 
4434 	sppp_auth_send(&pap, sp, PAP_REQ, sp->confid[IDX_PAP],
4435 		       sizeof idlen, (const char *)&idlen,
4436 		       (size_t)idlen, sp->myauth.name,
4437 		       sizeof pwdlen, (const char *)&pwdlen,
4438 		       (size_t)pwdlen, sp->myauth.secret,
4439 		       0);
4440 }
4441 /*
4442  * Random miscellaneous functions.
4443  */
4444 
4445 /*
4446  * Send a PAP or CHAP proto packet.
4447  *
4448  * Varadic function, each of the elements for the ellipsis is of type
4449  * ``size_t mlen, const u_char *msg''.  Processing will stop iff
4450  * mlen == 0.
4451  */
4452 
4453 HIDE void
4454 sppp_auth_send(const struct cp *cp, struct sppp *sp,
4455 		unsigned int type, u_int id, ...)
4456 {
4457 	STDDCL;
4458 	struct ppp_header *h;
4459 	struct lcp_header *lh;
4460 	struct mbuf *m;
4461 	u_char *p;
4462 	int len;
4463 	size_t pkthdrlen;
4464 	unsigned int mlen;
4465 	const char *msg;
4466 	va_list ap;
4467 
4468 	MGETHDR (m, M_DONTWAIT, MT_DATA);
4469 	if (! m)
4470 		return;
4471 	m->m_pkthdr.rcvif = 0;
4472 
4473 	if (sp->pp_flags & PP_NOFRAMING) {
4474 		*mtod(m, u_int16_t *) = htons(cp->proto);
4475 		pkthdrlen = 2;
4476 		lh = (struct lcp_header *)(mtod(m, u_int8_t *) + 2);
4477 	} else {
4478 		h = mtod (m, struct ppp_header*);
4479 		h->address = PPP_ALLSTATIONS;	/* broadcast address */
4480 		h->control = PPP_UI;		/* Unnumbered Info */
4481 		h->protocol = htons(cp->proto);
4482 		pkthdrlen = PPP_HEADER_LEN;
4483 		lh = (struct lcp_header*)(h + 1);
4484 	}
4485 
4486 	lh->type = type;
4487 	lh->ident = id;
4488 	p = (u_char*) (lh+1);
4489 
4490 	va_start(ap, id);
4491 	len = 0;
4492 
4493 	while ((mlen = (unsigned int)va_arg(ap, size_t)) != 0) {
4494 		msg = va_arg(ap, const char *);
4495 		len += mlen;
4496 		if (len > MHLEN - pkthdrlen - LCP_HEADER_LEN) {
4497 			va_end(ap);
4498 			m_freem(m);
4499 			return;
4500 		}
4501 
4502 		bcopy(msg, p, mlen);
4503 		p += mlen;
4504 	}
4505 	va_end(ap);
4506 
4507 	m->m_pkthdr.len = m->m_len = pkthdrlen + LCP_HEADER_LEN + len;
4508 	lh->len = htons (LCP_HEADER_LEN + len);
4509 
4510 	if (debug) {
4511 		log(LOG_DEBUG, SPP_FMT "%s output <%s id=0x%x len=%d",
4512 		    SPP_ARGS(ifp), cp->name,
4513 		    sppp_auth_type_name(cp->proto, lh->type),
4514 		    lh->ident, ntohs(lh->len));
4515 		if (len)
4516 			sppp_print_bytes((u_char*) (lh+1), len);
4517 		addlog(">\n");
4518 	}
4519 	if (IF_QFULL (&sp->pp_cpq)) {
4520 		IF_DROP (&sp->pp_fastq);
4521 		IF_DROP (&ifp->if_snd);
4522 		m_freem (m);
4523 		++ifp->if_oerrors;
4524 		m = NULL;
4525 	} else
4526 		IF_ENQUEUE (&sp->pp_cpq, m);
4527 	if (! (ifp->if_flags & IFF_OACTIVE))
4528 		(*ifp->if_start) (ifp);
4529 	if (m != NULL)
4530 		ifp->if_obytes += m->m_pkthdr.len + sp->pp_framebytes;
4531 }
4532 
4533 /*
4534  * Flush interface queue.
4535  */
4536 HIDE void
4537 sppp_qflush(struct ifqueue *ifq)
4538 {
4539 	IF_PURGE(ifq);
4540 }
4541 
4542 /*
4543  * Send keepalive packets, every 10 seconds.
4544  */
4545 HIDE void
4546 sppp_keepalive(void *dummy)
4547 {
4548 	struct sppp *sp;
4549 	int s;
4550 	struct timeval tv;
4551 
4552 	s = splnet();
4553 	getmicrouptime(&tv);
4554 	for (sp=spppq; sp; sp=sp->pp_next) {
4555 		struct ifnet *ifp = &sp->pp_if;
4556 
4557 		/* Keepalive mode disabled or channel down? */
4558 		if (! (sp->pp_flags & PP_KEEPALIVE) ||
4559 		    ! (ifp->if_flags & IFF_RUNNING))
4560 			continue;
4561 
4562 		/* No keepalive in PPP mode if LCP not opened yet. */
4563 		if (! (sp->pp_flags & PP_CISCO) &&
4564 		    sp->pp_phase < PHASE_AUTHENTICATE)
4565 			continue;
4566 
4567 		/* No echo reply, but maybe user data passed through? */
4568 		if (!(sp->pp_flags & PP_CISCO) &&
4569 		    (tv.tv_sec - sp->pp_last_receive) < NORECV_TIME) {
4570 			sp->pp_alivecnt = 0;
4571 			continue;
4572 		}
4573 
4574 		if (sp->pp_alivecnt >= MAXALIVECNT) {
4575 			/* No keepalive packets got.  Stop the interface. */
4576 			if_down (ifp);
4577 			sppp_qflush (&sp->pp_cpq);
4578 			if (! (sp->pp_flags & PP_CISCO)) {
4579 				log(LOG_INFO, SPP_FMT "LCP keepalive timeout\n",
4580 				    SPP_ARGS(ifp));
4581 				sp->pp_alivecnt = 0;
4582 
4583 				/* we are down, close all open protocols */
4584 				lcp.Close(sp);
4585 
4586 				/* And now prepare LCP to reestablish the link, if configured to do so. */
4587 				sppp_cp_change_state(&lcp, sp, STATE_STOPPED);
4588 
4589 				/* Close connection immediately, completition of this
4590 				 * will summon the magic needed to reestablish it. */
4591 				if (sp->pp_tlf)
4592 					sp->pp_tlf(sp);
4593 				continue;
4594 			}
4595 		}
4596 		if (sp->pp_alivecnt < MAXALIVECNT)
4597 			++sp->pp_alivecnt;
4598 		if (sp->pp_flags & PP_CISCO)
4599 			sppp_cisco_send (sp, CISCO_KEEPALIVE_REQ, ++sp->pp_seq,
4600 				sp->pp_rseq);
4601 		else if (sp->pp_phase >= PHASE_AUTHENTICATE) {
4602 			unsigned long nmagic = htonl (sp->lcp.magic);
4603 			sp->lcp.echoid = ++sp->pp_seq;
4604 			sppp_cp_send (sp, PPP_LCP, ECHO_REQ,
4605 				sp->lcp.echoid, 4, &nmagic);
4606 		}
4607 	}
4608 	splx(s);
4609 #if defined (__FreeBSD__)
4610 	keepalive_ch = timeout(sppp_keepalive, 0, hz * 10);
4611 #endif
4612 #if defined (__OpenBSD__)
4613 	timeout_add_sec(&keepalive_ch, 10);
4614 #endif
4615 }
4616 
4617 /*
4618  * Get both IP addresses.
4619  */
4620 HIDE void
4621 sppp_get_ip_addrs(struct sppp *sp, u_int32_t *src, u_int32_t *dst,
4622     u_int32_t *srcmask)
4623 {
4624 	struct ifnet *ifp = &sp->pp_if;
4625 	struct ifaddr *ifa;
4626 	struct sockaddr_in *si, *sm = 0;
4627 	u_int32_t ssrc, ddst;
4628 
4629 	sm = NULL;
4630 	ssrc = ddst = 0;
4631 	/*
4632 	 * Pick the first AF_INET address from the list,
4633 	 * aliases don't make any sense on a p2p link anyway.
4634 	 */
4635 #if defined (__FreeBSD__)
4636 	for (ifa = ifp->if_addrhead.tqh_first, si = 0;
4637 	     ifa;
4638 	     ifa = ifa->ifa_link.tqe_next)
4639 #else
4640 	si = 0;
4641 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
4642 #endif
4643 	{
4644 		if (ifa->ifa_addr->sa_family == AF_INET) {
4645 			si = (struct sockaddr_in *)ifa->ifa_addr;
4646 			sm = (struct sockaddr_in *)ifa->ifa_netmask;
4647 			if (si)
4648 				break;
4649 		}
4650 	}
4651 	if (ifa) {
4652 		if (si && si->sin_addr.s_addr) {
4653 			ssrc = si->sin_addr.s_addr;
4654 			if (srcmask)
4655 				*srcmask = ntohl(sm->sin_addr.s_addr);
4656 		}
4657 
4658 		si = (struct sockaddr_in *)ifa->ifa_dstaddr;
4659 		if (si && si->sin_addr.s_addr)
4660 			ddst = si->sin_addr.s_addr;
4661 	}
4662 
4663 	if (dst) *dst = ntohl(ddst);
4664 	if (src) *src = ntohl(ssrc);
4665 }
4666 
4667 int
4668 sppp_update_gw_walker(struct radix_node *rn, void *arg, u_int id)
4669 {
4670 	struct ifnet *ifp = arg;
4671 	struct rtentry *rt = (struct rtentry *)rn;
4672 
4673 	if (rt->rt_ifp == ifp) {
4674 		if (rt->rt_ifa->ifa_dstaddr->sa_family !=
4675 		    rt->rt_gateway->sa_family ||
4676 		    (rt->rt_flags & RTF_GATEWAY) == 0)
4677 			return (0);	/* do not modify non-gateway routes */
4678 		bcopy(rt->rt_ifa->ifa_dstaddr, rt->rt_gateway,
4679 		    rt->rt_ifa->ifa_dstaddr->sa_len);
4680 	}
4681 	return (0);
4682 }
4683 
4684 void
4685 sppp_update_gw(struct ifnet *ifp)
4686 {
4687         struct radix_node_head *rnh;
4688 	u_int tid;
4689 
4690 	/* update routing table */
4691 	for (tid = 0; tid <= RT_TABLEID_MAX; tid++) {
4692 		if ((rnh = rt_gettable(AF_INET, tid)) != NULL) {
4693 			while ((*rnh->rnh_walktree)(rnh,
4694 			    sppp_update_gw_walker, ifp) == EAGAIN)
4695 				;	/* nothing */
4696 		}
4697 	}
4698 }
4699 
4700 /*
4701  * Work queue task adding addresses from process context.
4702  * If an address is 0, leave it the way it is.
4703  */
4704 HIDE void
4705 sppp_set_ip_addrs(void *arg1, void *arg2)
4706 {
4707 	struct sppp_set_ip_addrs_args *args = arg1;
4708 	struct sppp *sp = args->sp;
4709 	u_int32_t myaddr = args->myaddr;
4710 	u_int32_t hisaddr = args->hisaddr;
4711 	struct ifnet *ifp = &sp->pp_if;
4712 	int debug = ifp->if_flags & IFF_DEBUG;
4713  	struct ifaddr *ifa;
4714  	struct sockaddr_in *si;
4715 	struct sockaddr_in *dest;
4716 	int s;
4717 
4718 	/* Arguments are now on local stack so free temporary storage. */
4719 	free(args, M_TEMP);
4720 
4721 	s = splsoftnet();
4722 
4723 	/*
4724 	 * Pick the first AF_INET address from the list,
4725 	 * aliases don't make any sense on a p2p link anyway.
4726 	 */
4727 
4728 #if defined (__FreeBSD__)
4729 	for (ifa = ifp->if_addrhead.tqh_first, si = 0;
4730 	     ifa;
4731 	     ifa = ifa->ifa_link.tqe_next)
4732 #else
4733 	si = 0;
4734 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
4735 #endif
4736 	{
4737 		if (ifa->ifa_addr->sa_family == AF_INET)
4738 		{
4739 			si = (struct sockaddr_in *)ifa->ifa_addr;
4740 			dest = (struct sockaddr_in *)ifa->ifa_dstaddr;
4741 			if (si)
4742 				break;
4743 		}
4744 	}
4745 
4746 	if (ifa && si) {
4747 		int error;
4748 		struct sockaddr_in new_sin = *si;
4749 		struct sockaddr_in new_dst = *dest;
4750 
4751 		/*
4752 		 * Scrub old routes now instead of calling in_ifinit with
4753 		 * scrub=1, because we may change the dstaddr
4754 		 * before the call to in_ifinit.
4755 		 */
4756 		in_ifscrub(ifp, ifatoia(ifa));
4757 
4758 		if (myaddr != 0)
4759 			new_sin.sin_addr.s_addr = htonl(myaddr);
4760 		if (hisaddr != 0) {
4761 			new_dst.sin_addr.s_addr = htonl(hisaddr);
4762 			if (new_dst.sin_addr.s_addr != dest->sin_addr.s_addr) {
4763 				sp->ipcp.saved_hisaddr = dest->sin_addr.s_addr;
4764 				*dest = new_dst; /* fix dstaddr in place */
4765 			}
4766 		}
4767 		if (!(error = in_ifinit(ifp, ifatoia(ifa), &new_sin, 0, 0)))
4768 			dohooks(ifp->if_addrhooks, 0);
4769 		if (debug && error) {
4770 			log(LOG_DEBUG, SPP_FMT "sppp_set_ip_addrs: in_ifinit "
4771 			" failed, error=%d\n", SPP_ARGS(ifp), error);
4772 			splx(s);
4773 			return;
4774 		}
4775 		sppp_update_gw(ifp);
4776 	}
4777 	splx(s);
4778 }
4779 
4780 /*
4781  * Clear IP addresses.  Must be called at splnet.
4782  */
4783 HIDE void
4784 sppp_clear_ip_addrs(struct sppp *sp)
4785 {
4786 	struct ifnet *ifp = &sp->pp_if;
4787 	struct ifaddr *ifa;
4788 	struct sockaddr_in *si;
4789 	struct sockaddr_in *dest;
4790 
4791 	u_int32_t remote;
4792 	if (sp->ipcp.flags & IPCP_HISADDR_DYN)
4793 		remote = sp->ipcp.saved_hisaddr;
4794 	else
4795 		sppp_get_ip_addrs(sp, 0, &remote, 0);
4796 
4797 	/*
4798 	 * Pick the first AF_INET address from the list,
4799 	 * aliases don't make any sense on a p2p link anyway.
4800 	 */
4801 
4802 	si = 0;
4803 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
4804 		if (ifa->ifa_addr->sa_family == AF_INET) {
4805 			si = (struct sockaddr_in *)ifa->ifa_addr;
4806 			dest = (struct sockaddr_in *)ifa->ifa_dstaddr;
4807 			if (si)
4808 				break;
4809 		}
4810 	}
4811 
4812 	if (ifa && si) {
4813 		struct sockaddr_in new_sin = *si;
4814 
4815 		in_ifscrub(ifp, ifatoia(ifa));
4816 		if (sp->ipcp.flags & IPCP_MYADDR_DYN)
4817 			new_sin.sin_addr.s_addr = 0;
4818 		if (sp->ipcp.flags & IPCP_HISADDR_DYN)
4819 			/* replace peer addr in place */
4820 			dest->sin_addr.s_addr = sp->ipcp.saved_hisaddr;
4821 		if (!in_ifinit(ifp, ifatoia(ifa), &new_sin, 0, 0))
4822 			dohooks(ifp->if_addrhooks, 0);
4823 		sppp_update_gw(ifp);
4824 	}
4825 }
4826 
4827 
4828 #ifdef INET6
4829 /*
4830  * Get both IPv6 addresses.
4831  */
4832 HIDE void
4833 sppp_get_ip6_addrs(struct sppp *sp, struct in6_addr *src, struct in6_addr *dst,
4834 		   struct in6_addr *srcmask)
4835 {
4836 	struct ifnet *ifp = &sp->pp_if;
4837 	struct ifaddr *ifa;
4838 	struct sockaddr_in6 *si, *sm;
4839 	struct in6_addr ssrc, ddst;
4840 
4841 	sm = NULL;
4842 	bzero(&ssrc, sizeof(ssrc));
4843 	bzero(&ddst, sizeof(ddst));
4844 	/*
4845 	 * Pick the first link-local AF_INET6 address from the list,
4846 	 * aliases don't make any sense on a p2p link anyway.
4847 	 */
4848 	si = 0;
4849 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
4850 		if (ifa->ifa_addr->sa_family == AF_INET6) {
4851 			si = (struct sockaddr_in6 *)ifa->ifa_addr;
4852 			sm = (struct sockaddr_in6 *)ifa->ifa_netmask;
4853 			if (si && IN6_IS_ADDR_LINKLOCAL(&si->sin6_addr))
4854 				break;
4855 		}
4856 	}
4857 
4858 	if (ifa) {
4859 		if (si && !IN6_IS_ADDR_UNSPECIFIED(&si->sin6_addr)) {
4860 			bcopy(&si->sin6_addr, &ssrc, sizeof(ssrc));
4861 			if (srcmask) {
4862 				bcopy(&sm->sin6_addr, srcmask,
4863 				    sizeof(*srcmask));
4864 			}
4865 		}
4866 
4867 		si = (struct sockaddr_in6 *)ifa->ifa_dstaddr;
4868 		if (si && !IN6_IS_ADDR_UNSPECIFIED(&si->sin6_addr))
4869 			bcopy(&si->sin6_addr, &ddst, sizeof(ddst));
4870 	}
4871 
4872 	if (dst)
4873 		bcopy(&ddst, dst, sizeof(*dst));
4874 	if (src)
4875 		bcopy(&ssrc, src, sizeof(*src));
4876 }
4877 
4878 #ifdef IPV6CP_MYIFID_DYN
4879 /*
4880  * Generate random ifid.
4881  */
4882 HIDE void
4883 sppp_gen_ip6_addr(struct sppp *sp, struct in6_addr *addr)
4884 {
4885 	/* TBD */
4886 }
4887 
4888 /*
4889  * Set my IPv6 address.  Must be called at splnet.
4890  */
4891 HIDE void
4892 sppp_set_ip6_addr(struct sppp *sp, const struct in6_addr *src)
4893 {
4894 	struct ifnet *ifp = &sp->pp_if;
4895 	struct ifaddr *ifa;
4896 	struct sockaddr_in6 *sin6;
4897 
4898 	/*
4899 	 * Pick the first link-local AF_INET6 address from the list,
4900 	 * aliases don't make any sense on a p2p link anyway.
4901 	 */
4902 
4903 	sin6 = NULL;
4904 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
4905 		if (ifa->ifa_addr->sa_family == AF_INET6) {
4906 			sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
4907 			if (sin6 && IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))
4908 				break;
4909 		}
4910 	}
4911 
4912 	if (ifa && sin6) {
4913 		struct sockaddr_in6 new_sin6 = *sin6;
4914 		bcopy(src, &new_sin6.sin6_addr, sizeof(new_sin6.sin6_addr));
4915 		dohooks(ifp->if_addrhooks, 0);
4916 	}
4917 }
4918 #endif
4919 
4920 /*
4921  * Suggest a candidate address to be used by peer.
4922  */
4923 HIDE void
4924 sppp_suggest_ip6_addr(struct sppp *sp, struct in6_addr *suggest)
4925 {
4926 	struct in6_addr myaddr;
4927 	struct timeval tv;
4928 
4929 	sppp_get_ip6_addrs(sp, &myaddr, 0, 0);
4930 
4931 	myaddr.s6_addr[8] &= ~0x02;	/* u bit to "local" */
4932 	getmicrouptime(&tv);
4933 	if ((tv.tv_usec & 0xff) == 0 && (tv.tv_sec & 0xff) == 0) {
4934 		myaddr.s6_addr[14] ^= 0xff;
4935 		myaddr.s6_addr[15] ^= 0xff;
4936 	} else {
4937 		myaddr.s6_addr[14] ^= (tv.tv_usec & 0xff);
4938 		myaddr.s6_addr[15] ^= (tv.tv_sec & 0xff);
4939 	}
4940 	if (suggest)
4941 		bcopy(&myaddr, suggest, sizeof(myaddr));
4942 }
4943 #endif /*INET6*/
4944 
4945 HIDE int
4946 sppp_get_params(struct sppp *sp, struct ifreq *ifr)
4947 {
4948 	int cmd;
4949 
4950 	if (copyin((caddr_t)ifr->ifr_data, &cmd, sizeof cmd) != 0)
4951 		return EFAULT;
4952 
4953 	switch (cmd) {
4954 	case SPPPIOGDEFS:
4955 	{
4956 		struct spppreq *spr;
4957 
4958 		spr = malloc(sizeof(*spr), M_DEVBUF, M_WAITOK);
4959 
4960 		/*
4961 		 * We copy over the entire current state, but clean
4962 		 * out some of the stuff we don't wanna pass up.
4963 		 * Remember, SIOCGIFGENERIC is unprotected, and can be
4964 		 * called by any user.  No need to ever get PAP or
4965 		 * CHAP secrets back to userland anyway.
4966 		 */
4967 
4968 		spr->cmd = cmd;
4969 		bcopy(sp, &spr->defs, sizeof(struct sppp));
4970 
4971 		explicit_bzero(&spr->defs.myauth, sizeof(spr->defs.myauth));
4972 		explicit_bzero(&spr->defs.hisauth, sizeof(spr->defs.hisauth));
4973 		explicit_bzero(&spr->defs.chap_challenge,
4974 		    sizeof(spr->defs.chap_challenge));
4975 
4976 		if (copyout(spr, (caddr_t)ifr->ifr_data, sizeof(*spr)) != 0) {
4977 			free(spr, M_DEVBUF);
4978 			return EFAULT;
4979 		}
4980 		free(spr, M_DEVBUF);
4981 		break;
4982 	}
4983 	case SPPPIOGMAUTH:
4984 	case SPPPIOGHAUTH:
4985 	{
4986 		struct sauthreq *spa;
4987 		struct sauth *auth;
4988 
4989 		spa = malloc(sizeof(*spa), M_DEVBUF, M_WAITOK);
4990 		auth = (cmd == SPPPIOGMAUTH) ? &sp->myauth : &sp->hisauth;
4991 		bzero(spa, sizeof(*spa));
4992 		spa->proto = auth->proto;
4993 		spa->flags = auth->flags;
4994 
4995 		/* do not copy the secret, and only let root know the name */
4996 		if (auth->name != NULL && suser(curproc, 0) == 0)
4997 			strlcpy(spa->name, auth->name, sizeof(spa->name));
4998 
4999 		if (copyout(spa, (caddr_t)ifr->ifr_data, sizeof(*spa)) != 0) {
5000 			free(spa, M_DEVBUF);
5001 			return EFAULT;
5002 		}
5003 		free(spa, M_DEVBUF);
5004 		break;
5005 	}
5006 	default:
5007 		return EINVAL;
5008 	}
5009 
5010 	return 0;
5011 }
5012 
5013 
5014 HIDE int
5015 sppp_set_params(struct sppp *sp, struct ifreq *ifr)
5016 {
5017 	int cmd;
5018 
5019 	if (copyin((caddr_t)ifr->ifr_data, &cmd, sizeof cmd) != 0)
5020 		return EFAULT;
5021 
5022 	/*
5023 	 * We have a very specific idea of which fields we allow
5024 	 * being passed back from userland, so to not clobber our
5025 	 * current state.  For one, we only allow setting
5026 	 * anything if LCP is in dead phase.  Once the LCP
5027 	 * negotiations started, the authentication settings must
5028 	 * not be changed again.  (The administrator can force an
5029 	 * ifconfig down in order to get LCP back into dead
5030 	 * phase.)
5031 	 */
5032 	if (sp->pp_phase != PHASE_DEAD)
5033 		return EBUSY;
5034 
5035 	switch (cmd) {
5036 	case SPPPIOSDEFS:
5037 	{
5038 		struct spppreq *spr;
5039 
5040 		spr = malloc(sizeof(*spr), M_DEVBUF, M_WAITOK);
5041 
5042 		if (copyin((caddr_t)ifr->ifr_data, spr, sizeof(*spr)) != 0) {
5043 			free(spr, M_DEVBUF);
5044 			return EFAULT;
5045 		}
5046 		/*
5047 		 * Also, we only allow for authentication parameters to be
5048 		 * specified.
5049 		 *
5050 		 * XXX Should allow to set or clear pp_flags.
5051 		 */
5052 		free(spr, M_DEVBUF);
5053 		break;
5054 	}
5055 	case SPPPIOSMAUTH:
5056 	case SPPPIOSHAUTH:
5057 	{
5058 		/*
5059 		 * Finally, if the respective authentication protocol to
5060 		 * be used is set differently than 0, but the secret is
5061 		 * passed as all zeros, we don't trash the existing secret.
5062 		 * This allows an administrator to change the system name
5063 		 * only without clobbering the secret (which he didn't get
5064 		 * back in a previous SPPPIOGXAUTH call).  However, the
5065 		 * secrets are cleared if the authentication protocol is
5066 		 * reset to 0.
5067 		 */
5068 
5069 		struct sauthreq *spa;
5070 		struct sauth *auth;
5071 		char *p;
5072 		int len;
5073 
5074 		spa = malloc(sizeof(*spa), M_DEVBUF, M_WAITOK);
5075 
5076 		auth = (cmd == SPPPIOSMAUTH) ? &sp->myauth : &sp->hisauth;
5077 
5078 		if (copyin((caddr_t)ifr->ifr_data, spa, sizeof(*spa)) != 0) {
5079 			free(spa, M_DEVBUF);
5080 			return EFAULT;
5081 		}
5082 
5083 		if (spa->proto != 0 && spa->proto != PPP_PAP &&
5084 		    spa->proto != PPP_CHAP) {
5085 			free(spa, M_DEVBUF);
5086 			return EINVAL;
5087 		}
5088 
5089 		if (spa->proto == 0) {
5090 			/* resetting auth */
5091 			if (auth->name != NULL)
5092 				free(auth->name, M_DEVBUF);
5093 			if (auth->secret != NULL)
5094 				free(auth->secret, M_DEVBUF);
5095 			bzero(auth, sizeof *auth);
5096 			explicit_bzero(sp->chap_challenge, sizeof sp->chap_challenge);
5097 		} else {
5098 			/* setting/changing auth */
5099 			auth->proto = spa->proto;
5100 			auth->flags = spa->flags;
5101 
5102 			spa->name[AUTHMAXLEN - 1] = '\0';
5103 			len = strlen(spa->name) + 1;
5104 			p = malloc(len, M_DEVBUF, M_WAITOK);
5105 			strlcpy(p, spa->name, len);
5106 			if (auth->name != NULL)
5107 				free(auth->name, M_DEVBUF);
5108 			auth->name = p;
5109 
5110 			if (spa->secret[0] != '\0') {
5111 				spa->secret[AUTHMAXLEN - 1] = '\0';
5112 				len = strlen(spa->secret) + 1;
5113 				p = malloc(len, M_DEVBUF, M_WAITOK);
5114 				strlcpy(p, spa->secret, len);
5115 				if (auth->secret != NULL)
5116 					free(auth->secret, M_DEVBUF);
5117 				auth->secret = p;
5118 			} else if (!auth->secret) {
5119 				p = malloc(1, M_DEVBUF, M_WAITOK);
5120 				p[0] = '\0';
5121 				auth->secret = p;
5122 			}
5123 		}
5124 		free(spa, M_DEVBUF);
5125 		break;
5126 	}
5127 	default:
5128 		return EINVAL;
5129 	}
5130 
5131 	return 0;
5132 }
5133 
5134 HIDE void
5135 sppp_phase_network(struct sppp *sp)
5136 {
5137 	int i;
5138 	u_long mask;
5139 
5140 	sp->pp_phase = PHASE_NETWORK;
5141 
5142 	sppp_set_phase(sp);
5143 
5144 	/* Notify NCPs now. */
5145 	for (i = 0; i < IDX_COUNT; i++)
5146 		if ((cps[i])->flags & CP_NCP)
5147 			(cps[i])->Open(sp);
5148 
5149 	/* Send Up events to all NCPs. */
5150 	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
5151 		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_NCP))
5152 			(cps[i])->Up(sp);
5153 
5154 	/* if no NCP is starting, all this was in vain, close down */
5155 	sppp_lcp_check_and_close(sp);
5156 }
5157 
5158 
5159 HIDE const char *
5160 sppp_cp_type_name(u_char type)
5161 {
5162 	static char buf[12];
5163 	switch (type) {
5164 	case CONF_REQ:   return "conf-req";
5165 	case CONF_ACK:   return "conf-ack";
5166 	case CONF_NAK:   return "conf-nak";
5167 	case CONF_REJ:   return "conf-rej";
5168 	case TERM_REQ:   return "term-req";
5169 	case TERM_ACK:   return "term-ack";
5170 	case CODE_REJ:   return "code-rej";
5171 	case PROTO_REJ:  return "proto-rej";
5172 	case ECHO_REQ:   return "echo-req";
5173 	case ECHO_REPLY: return "echo-reply";
5174 	case DISC_REQ:   return "discard-req";
5175 	}
5176 	snprintf (buf, sizeof buf, "0x%x", type);
5177 	return buf;
5178 }
5179 
5180 HIDE const char *
5181 sppp_auth_type_name(u_short proto, u_char type)
5182 {
5183 	static char buf[12];
5184 	switch (proto) {
5185 	case PPP_CHAP:
5186 		switch (type) {
5187 		case CHAP_CHALLENGE:	return "challenge";
5188 		case CHAP_RESPONSE:	return "response";
5189 		case CHAP_SUCCESS:	return "success";
5190 		case CHAP_FAILURE:	return "failure";
5191 		}
5192 	case PPP_PAP:
5193 		switch (type) {
5194 		case PAP_REQ:		return "req";
5195 		case PAP_ACK:		return "ack";
5196 		case PAP_NAK:		return "nak";
5197 		}
5198 	}
5199 	snprintf (buf, sizeof buf, "0x%x", type);
5200 	return buf;
5201 }
5202 
5203 HIDE const char *
5204 sppp_lcp_opt_name(u_char opt)
5205 {
5206 	static char buf[12];
5207 	switch (opt) {
5208 	case LCP_OPT_MRU:		return "mru";
5209 	case LCP_OPT_ASYNC_MAP:		return "async-map";
5210 	case LCP_OPT_AUTH_PROTO:	return "auth-proto";
5211 	case LCP_OPT_QUAL_PROTO:	return "qual-proto";
5212 	case LCP_OPT_MAGIC:		return "magic";
5213 	case LCP_OPT_PROTO_COMP:	return "proto-comp";
5214 	case LCP_OPT_ADDR_COMP:		return "addr-comp";
5215 	}
5216 	snprintf (buf, sizeof buf, "0x%x", opt);
5217 	return buf;
5218 }
5219 
5220 HIDE const char *
5221 sppp_ipcp_opt_name(u_char opt)
5222 {
5223 	static char buf[12];
5224 	switch (opt) {
5225 	case IPCP_OPT_ADDRESSES:	return "addresses";
5226 	case IPCP_OPT_COMPRESSION:	return "compression";
5227 	case IPCP_OPT_ADDRESS:		return "address";
5228 	}
5229 	snprintf (buf, sizeof buf, "0x%x", opt);
5230 	return buf;
5231 }
5232 
5233 #ifdef INET6
5234 HIDE const char *
5235 sppp_ipv6cp_opt_name(u_char opt)
5236 {
5237 	static char buf[12];
5238 	switch (opt) {
5239 	case IPV6CP_OPT_IFID:		return "ifid";
5240 	case IPV6CP_OPT_COMPRESSION:	return "compression";
5241 	}
5242 	snprintf (buf, sizeof buf, "0x%x", opt);
5243 	return buf;
5244 }
5245 #endif
5246 
5247 HIDE const char *
5248 sppp_state_name(int state)
5249 {
5250 	switch (state) {
5251 	case STATE_INITIAL:	return "initial";
5252 	case STATE_STARTING:	return "starting";
5253 	case STATE_CLOSED:	return "closed";
5254 	case STATE_STOPPED:	return "stopped";
5255 	case STATE_CLOSING:	return "closing";
5256 	case STATE_STOPPING:	return "stopping";
5257 	case STATE_REQ_SENT:	return "req-sent";
5258 	case STATE_ACK_RCVD:	return "ack-rcvd";
5259 	case STATE_ACK_SENT:	return "ack-sent";
5260 	case STATE_OPENED:	return "opened";
5261 	}
5262 	return "illegal";
5263 }
5264 
5265 HIDE const char *
5266 sppp_phase_name(enum ppp_phase phase)
5267 {
5268 	switch (phase) {
5269 	case PHASE_DEAD:	return "dead";
5270 	case PHASE_ESTABLISH:	return "establish";
5271 	case PHASE_TERMINATE:	return "terminate";
5272 	case PHASE_AUTHENTICATE: return "authenticate";
5273 	case PHASE_NETWORK:	return "network";
5274 	}
5275 	return "illegal";
5276 }
5277 
5278 HIDE const char *
5279 sppp_proto_name(u_short proto)
5280 {
5281 	static char buf[12];
5282 	switch (proto) {
5283 	case PPP_LCP:	return "lcp";
5284 	case PPP_IPCP:	return "ipcp";
5285 	case PPP_PAP:	return "pap";
5286 	case PPP_CHAP:	return "chap";
5287 	}
5288 	snprintf(buf, sizeof buf, "0x%x", (unsigned)proto);
5289 	return buf;
5290 }
5291 
5292 HIDE void
5293 sppp_print_bytes(const u_char *p, u_short len)
5294 {
5295 	addlog(" %02x", *p++);
5296 	while (--len > 0)
5297 		addlog("-%02x", *p++);
5298 }
5299 
5300 HIDE void
5301 sppp_print_string(const char *p, u_short len)
5302 {
5303 	u_char c;
5304 
5305 	while (len-- > 0) {
5306 		c = *p++;
5307 		/*
5308 		 * Print only ASCII chars directly.  RFC 1994 recommends
5309 		 * using only them, but we don't rely on it.  */
5310 		if (c < ' ' || c > '~')
5311 			addlog("\\x%x", c);
5312 		else
5313 			addlog("%c", c);
5314 	}
5315 }
5316 
5317 HIDE const char *
5318 sppp_dotted_quad(u_int32_t addr)
5319 {
5320 	static char s[16];
5321 	snprintf(s, sizeof s, "%d.%d.%d.%d",
5322 		(int)((addr >> 24) & 0xff),
5323 		(int)((addr >> 16) & 0xff),
5324 		(int)((addr >> 8) & 0xff),
5325 		(int)(addr & 0xff));
5326 	return s;
5327 }
5328 
5329 /* a dummy, used to drop uninteresting events */
5330 HIDE void
5331 sppp_null(struct sppp *unused)
5332 {
5333 	/* do just nothing */
5334 }
5335 /*
5336  * This file is large.  Tell emacs to highlight it nevertheless.
5337  *
5338  * Local Variables:
5339  * hilit-auto-highlight-maxout: 120000
5340  * End:
5341  */
5342 
5343 HIDE void
5344 sppp_set_phase(struct sppp *sp)
5345 {
5346 	STDDCL;
5347 	int lstate, s;
5348 
5349 	if (debug)
5350 		log(LOG_INFO, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
5351 		    sppp_phase_name(sp->pp_phase));
5352 
5353 	/* set link state */
5354 	if (sp->pp_phase == PHASE_NETWORK)
5355 		lstate = LINK_STATE_UP;
5356 	else
5357 		lstate = LINK_STATE_DOWN;
5358 
5359 	if (ifp->if_link_state != lstate) {
5360 		ifp->if_link_state = lstate;
5361 		s = splsoftnet();
5362 		if_link_state_change(ifp);
5363 		splx(s);
5364 	}
5365 }
5366