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