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