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