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