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