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