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