xref: /openbsd-src/sys/net/if_spppsubr.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$OpenBSD: if_spppsubr.c,v 1.10 2001/07/10 11:09:07 espie 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  * This software is distributed with NO WARRANTIES, not even the implied
13  * warranties for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14  *
15  * Authors grant any other persons or organisations permission to use
16  * or modify this software as long as this message is kept with the software,
17  * all derivative works or modified versions.
18  *
19  * Version 2.6, Tue May 12 17:10:39 MSD 1998
20  *
21  */
22 
23 #include <sys/param.h>
24 
25 #if defined (__FreeBSD__)
26 #include "opt_inet.h"
27 #include "opt_ipx.h"
28 #endif
29 
30 #ifdef NetBSD1_3
31 #  if NetBSD1_3 > 6
32 #      include "opt_inet.h"
33 #      include "opt_iso.h"
34 #  endif
35 #endif
36 
37 #ifdef __OpenBSD__
38 #define HIDE
39 #else
40 #define HIDE static
41 #endif
42 
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/sockio.h>
46 #include <sys/socket.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 <sys/md5k.h>
54 #else
55 #include <sys/md5.h>
56 #endif
57 
58 #include <net/if.h>
59 #include <net/netisr.h>
60 #include <net/if_types.h>
61 
62 #if defined (__FreeBSD__) || defined(__OpenBSD_) || defined(__NetBSD__)
63 #include <machine/random.h>
64 #endif
65 #if defined (__NetBSD__) || defined (__OpenBSD__)
66 #include <machine/cpu.h> /* XXX for softnet */
67 #endif
68 #include <machine/stdarg.h>
69 
70 #ifdef INET
71 #include <netinet/in.h>
72 #include <netinet/in_systm.h>
73 #include <netinet/in_var.h>
74 #include <netinet/ip.h>
75 #include <netinet/tcp.h>
76 # if defined (__FreeBSD__) || defined (__OpenBSD__)
77 #  include <netinet/if_ether.h>
78 # else
79 #  include <net/ethertypes.h>
80 # endif
81 #else
82 # error Huh? sppp without INET?
83 #endif
84 
85 #ifdef IPX
86 #include <netipx/ipx.h>
87 #include <netipx/ipx_if.h>
88 #endif
89 
90 #ifdef NS
91 #include <netns/ns.h>
92 #include <netns/ns_if.h>
93 #endif
94 
95 #ifdef ISO
96 #include <netiso/argo_debug.h>
97 #include <netiso/iso.h>
98 #include <netiso/iso_var.h>
99 #include <netiso/iso_snpac.h>
100 #endif
101 
102 #include <net/if_sppp.h>
103 
104 #if defined (__FreeBSD__)
105 # define UNTIMEOUT(fun, arg, handle)	\
106 	untimeout(fun, arg, handle)
107 #elif defined(__OpenBSD__)
108 # define UNTIMEOUT(fun, arg, handle)	\
109 	timeout_del(&(handle))
110 #else
111 # define UNTIMEOUT(fun, arg, handle)	\
112 	untimeout(fun, arg)
113 #endif
114 #define MAXALIVECNT     3               /* max. alive packets */
115 
116 /*
117  * Interface flags that can be set in an ifconfig command.
118  *
119  * Setting link0 will make the link passive, i.e. it will be marked
120  * as being administrative openable, but won't be opened to begin
121  * with.  Incoming calls will be answered, or subsequent calls with
122  * -link1 will cause the administrative open of the LCP layer.
123  *
124  * Setting link1 will cause the link to auto-dial only as packets
125  * arrive to be sent.
126  *
127  * Setting IFF_DEBUG will syslog the option negotiation and state
128  * transitions at level kern.debug.  Note: all logs consistently look
129  * like
130  *
131  *   <if-name><unit>: <proto-name> <additional info...>
132  *
133  * with <if-name><unit> being something like "bppp0", and <proto-name>
134  * being one of "lcp", "ipcp", "cisco", "chap", "pap", etc.
135  */
136 
137 #define IFF_PASSIVE	IFF_LINK0	/* wait passively for connection */
138 #define IFF_AUTO	IFF_LINK1	/* auto-dial on output */
139 
140 #define PPP_ALLSTATIONS 0xff		/* All-Stations broadcast address */
141 #define PPP_UI		0x03		/* Unnumbered Information */
142 #define PPP_IP		0x0021		/* Internet Protocol */
143 #define PPP_ISO		0x0023		/* ISO OSI Protocol */
144 #define PPP_XNS		0x0025		/* Xerox NS Protocol */
145 #define PPP_IPX		0x002b		/* Novell IPX Protocol */
146 #define PPP_LCP		0xc021		/* Link Control Protocol */
147 #define PPP_PAP		0xc023		/* Password Authentication Protocol */
148 #define PPP_CHAP	0xc223		/* Challenge-Handshake Auth Protocol */
149 #define PPP_IPCP	0x8021		/* Internet Protocol Control Protocol */
150 
151 #define CONF_REQ	1		/* PPP configure request */
152 #define CONF_ACK	2		/* PPP configure acknowledge */
153 #define CONF_NAK	3		/* PPP configure negative ack */
154 #define CONF_REJ	4		/* PPP configure reject */
155 #define TERM_REQ	5		/* PPP terminate request */
156 #define TERM_ACK	6		/* PPP terminate acknowledge */
157 #define CODE_REJ	7		/* PPP code reject */
158 #define PROTO_REJ	8		/* PPP protocol reject */
159 #define ECHO_REQ	9		/* PPP echo request */
160 #define ECHO_REPLY	10		/* PPP echo reply */
161 #define DISC_REQ	11		/* PPP discard request */
162 
163 #define LCP_OPT_MRU		1	/* maximum receive unit */
164 #define LCP_OPT_ASYNC_MAP	2	/* async control character map */
165 #define LCP_OPT_AUTH_PROTO	3	/* authentication protocol */
166 #define LCP_OPT_QUAL_PROTO	4	/* quality protocol */
167 #define LCP_OPT_MAGIC		5	/* magic number */
168 #define LCP_OPT_RESERVED	6	/* reserved */
169 #define LCP_OPT_PROTO_COMP	7	/* protocol field compression */
170 #define LCP_OPT_ADDR_COMP	8	/* address/control field compression */
171 
172 #define IPCP_OPT_ADDRESSES	1	/* both IP addresses; deprecated */
173 #define IPCP_OPT_COMPRESSION	2	/* IP compression protocol (VJ) */
174 #define IPCP_OPT_ADDRESS	3	/* local IP address */
175 
176 #define PAP_REQ			1	/* PAP name/password request */
177 #define PAP_ACK			2	/* PAP acknowledge */
178 #define PAP_NAK			3	/* PAP fail */
179 
180 #define CHAP_CHALLENGE		1	/* CHAP challenge request */
181 #define CHAP_RESPONSE		2	/* CHAP challenge response */
182 #define CHAP_SUCCESS		3	/* CHAP response ok */
183 #define CHAP_FAILURE		4	/* CHAP response failed */
184 
185 #define CHAP_MD5		5	/* hash algorithm - MD5 */
186 
187 #define CISCO_MULTICAST		0x8f	/* Cisco multicast address */
188 #define CISCO_UNICAST		0x0f	/* Cisco unicast address */
189 #define CISCO_KEEPALIVE		0x8035	/* Cisco keepalive protocol */
190 #define CISCO_ADDR_REQ		0	/* Cisco address request */
191 #define CISCO_ADDR_REPLY	1	/* Cisco address reply */
192 #define CISCO_KEEPALIVE_REQ	2	/* Cisco keepalive request */
193 
194 /* states are named and numbered according to RFC 1661 */
195 #define STATE_INITIAL	0
196 #define STATE_STARTING	1
197 #define STATE_CLOSED	2
198 #define STATE_STOPPED	3
199 #define STATE_CLOSING	4
200 #define STATE_STOPPING	5
201 #define STATE_REQ_SENT	6
202 #define STATE_ACK_RCVD	7
203 #define STATE_ACK_SENT	8
204 #define STATE_OPENED	9
205 
206 struct ppp_header {
207 	u_char address;
208 	u_char control;
209 	u_short protocol;
210 };
211 #define PPP_HEADER_LEN          sizeof (struct ppp_header)
212 
213 struct lcp_header {
214 	u_char type;
215 	u_char ident;
216 	u_short len;
217 };
218 #define LCP_HEADER_LEN          sizeof (struct lcp_header)
219 
220 struct cisco_packet {
221 	u_long type;
222 	u_long par1;
223 	u_long par2;
224 	u_short rel;
225 	u_short time0;
226 	u_short time1;
227 };
228 #define CISCO_PACKET_LEN 18
229 
230 /*
231  * We follow the spelling and capitalization of RFC 1661 here, to make
232  * it easier comparing with the standard.  Please refer to this RFC in
233  * case you can't make sense out of these abbreviation; it will also
234  * explain the semantics related to the various events and actions.
235  */
236 struct cp {
237 	u_short	proto;		/* PPP control protocol number */
238 	u_char protoidx;	/* index into state table in struct sppp */
239 	u_char flags;
240 #define CP_LCP		0x01	/* this is the LCP */
241 #define CP_AUTH		0x02	/* this is an authentication protocol */
242 #define CP_NCP		0x04	/* this is a NCP */
243 #define CP_QUAL		0x08	/* this is a quality reporting protocol */
244 	const char *name;	/* name of this control protocol */
245 	/* event handlers */
246 	void	(*Up)(struct sppp *sp);
247 	void	(*Down)(struct sppp *sp);
248 	void	(*Open)(struct sppp *sp);
249 	void	(*Close)(struct sppp *sp);
250 	void	(*TO)(void *sp);
251 	int	(*RCR)(struct sppp *sp, struct lcp_header *h, int len);
252 	void	(*RCN_rej)(struct sppp *sp, struct lcp_header *h, int len);
253 	void	(*RCN_nak)(struct sppp *sp, struct lcp_header *h, int len);
254 	/* actions */
255 	void	(*tlu)(struct sppp *sp);
256 	void	(*tld)(struct sppp *sp);
257 	void	(*tls)(struct sppp *sp);
258 	void	(*tlf)(struct sppp *sp);
259 	void	(*scr)(struct sppp *sp);
260 };
261 
262 static struct sppp *spppq;
263 #if defined (__OpenBSD__)
264 static struct timeout keepalive_ch;
265 #endif
266 #if defined (__FreeBSD__)
267 static struct callout_handle keepalive_ch;
268 #endif
269 
270 #if defined (__FreeBSD__)
271 #define	SPP_FMT		"%s%d: "
272 #define	SPP_ARGS(ifp)	(ifp)->if_name, (ifp)->if_unit
273 #else
274 #define	SPP_FMT		"%s: "
275 #define	SPP_ARGS(ifp)	(ifp)->if_xname
276 #endif
277 
278 /*
279  * The following disgusting hack gets around the problem that IP TOS
280  * can't be set yet.  We want to put "interactive" traffic on a high
281  * priority queue.  To decide if traffic is interactive, we check that
282  * a) it is TCP and b) one of its ports is telnet, rlogin or ftp control.
283  *
284  * XXX is this really still necessary?  - joerg -
285  */
286 static u_short interactive_ports[8] = {
287 	0,	513,	0,	0,
288 	0,	21,	0,	23,
289 };
290 #define INTERACTIVE(p) (interactive_ports[(p) & 7] == (p))
291 
292 /* almost every function needs these */
293 #define STDDCL							\
294 	struct ifnet *ifp = &sp->pp_if;				\
295 	int debug = ifp->if_flags & IFF_DEBUG
296 
297 HIDE int sppp_output(struct ifnet *ifp, struct mbuf *m,
298 		       struct sockaddr *dst, struct rtentry *rt);
299 
300 HIDE void sppp_cisco_send(struct sppp *sp, int type, long par1, long par2);
301 HIDE void sppp_cisco_input(struct sppp *sp, struct mbuf *m);
302 
303 HIDE void sppp_cp_input(const struct cp *cp, struct sppp *sp,
304 			  struct mbuf *m);
305 HIDE void sppp_cp_send(struct sppp *sp, u_short proto, u_char type,
306 			 u_char ident, u_short len, void *data);
307 #ifdef notyet
308 HIDE void sppp_cp_timeout(void *arg);
309 #endif
310 HIDE void sppp_cp_change_state(const struct cp *cp, struct sppp *sp,
311 				 int newstate);
312 HIDE void sppp_auth_send(const struct cp *cp,
313 			   struct sppp *sp, u_char type, u_char id,
314 			   ...);
315 
316 HIDE void sppp_up_event(const struct cp *cp, struct sppp *sp);
317 HIDE void sppp_down_event(const struct cp *cp, struct sppp *sp);
318 HIDE void sppp_open_event(const struct cp *cp, struct sppp *sp);
319 HIDE void sppp_close_event(const struct cp *cp, struct sppp *sp);
320 HIDE void sppp_increasing_timeout(const struct cp *cp, struct sppp *sp);
321 HIDE void sppp_to_event(const struct cp *cp, struct sppp *sp);
322 
323 HIDE void sppp_null(struct sppp *sp);
324 
325 HIDE void sppp_lcp_init(struct sppp *sp);
326 HIDE void sppp_lcp_up(struct sppp *sp);
327 HIDE void sppp_lcp_down(struct sppp *sp);
328 HIDE void sppp_lcp_open(struct sppp *sp);
329 HIDE void sppp_lcp_close(struct sppp *sp);
330 HIDE void sppp_lcp_TO(void *sp);
331 HIDE int sppp_lcp_RCR(struct sppp *sp, struct lcp_header *h, int len);
332 HIDE void sppp_lcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len);
333 HIDE void sppp_lcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len);
334 HIDE void sppp_lcp_tlu(struct sppp *sp);
335 HIDE void sppp_lcp_tld(struct sppp *sp);
336 HIDE void sppp_lcp_tls(struct sppp *sp);
337 HIDE void sppp_lcp_tlf(struct sppp *sp);
338 HIDE void sppp_lcp_scr(struct sppp *sp);
339 HIDE void sppp_lcp_check_and_close(struct sppp *sp);
340 HIDE int sppp_ncp_check(struct sppp *sp);
341 
342 HIDE void sppp_ipcp_init(struct sppp *sp);
343 HIDE void sppp_ipcp_up(struct sppp *sp);
344 HIDE void sppp_ipcp_down(struct sppp *sp);
345 HIDE void sppp_ipcp_open(struct sppp *sp);
346 HIDE void sppp_ipcp_close(struct sppp *sp);
347 HIDE void sppp_ipcp_TO(void *sp);
348 HIDE int sppp_ipcp_RCR(struct sppp *sp, struct lcp_header *h, int len);
349 HIDE void sppp_ipcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len);
350 HIDE void sppp_ipcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len);
351 HIDE void sppp_ipcp_tlu(struct sppp *sp);
352 HIDE void sppp_ipcp_tld(struct sppp *sp);
353 HIDE void sppp_ipcp_tls(struct sppp *sp);
354 HIDE void sppp_ipcp_tlf(struct sppp *sp);
355 HIDE void sppp_ipcp_scr(struct sppp *sp);
356 
357 HIDE void sppp_pap_input(struct sppp *sp, struct mbuf *m);
358 HIDE void sppp_pap_init(struct sppp *sp);
359 HIDE void sppp_pap_open(struct sppp *sp);
360 HIDE void sppp_pap_close(struct sppp *sp);
361 HIDE void sppp_pap_TO(void *sp);
362 HIDE void sppp_pap_my_TO(void *sp);
363 HIDE void sppp_pap_tlu(struct sppp *sp);
364 HIDE void sppp_pap_tld(struct sppp *sp);
365 HIDE void sppp_pap_scr(struct sppp *sp);
366 
367 HIDE void sppp_chap_input(struct sppp *sp, struct mbuf *m);
368 HIDE void sppp_chap_init(struct sppp *sp);
369 HIDE void sppp_chap_open(struct sppp *sp);
370 HIDE void sppp_chap_close(struct sppp *sp);
371 HIDE void sppp_chap_TO(void *sp);
372 HIDE void sppp_chap_tlu(struct sppp *sp);
373 HIDE void sppp_chap_tld(struct sppp *sp);
374 HIDE void sppp_chap_scr(struct sppp *sp);
375 
376 HIDE const char *sppp_auth_type_name(u_short proto, u_char type);
377 HIDE const char *sppp_cp_type_name(u_char type);
378 HIDE const char *sppp_dotted_quad(u_long addr);
379 HIDE const char *sppp_ipcp_opt_name(u_char opt);
380 HIDE const char *sppp_lcp_opt_name(u_char opt);
381 HIDE const char *sppp_phase_name(enum ppp_phase phase);
382 HIDE const char *sppp_proto_name(u_short proto);
383 HIDE const char *sppp_state_name(int state);
384 HIDE int sppp_params(struct sppp *sp, u_long cmd, void *data);
385 HIDE int sppp_strnlen(u_char *p, int max);
386 HIDE void sppp_get_ip_addrs(struct sppp *sp, u_long *src, u_long *dst,
387 			      u_long *srcmask);
388 HIDE void sppp_keepalive(void *dummy);
389 HIDE void sppp_phase_network(struct sppp *sp);
390 HIDE void sppp_print_bytes(const u_char *p, u_short len);
391 HIDE void sppp_print_string(const char *p, u_short len);
392 HIDE void sppp_qflush(struct ifqueue *ifq);
393 HIDE void sppp_set_ip_addr(struct sppp *sp, u_long src);
394 
395 /* our control protocol descriptors */
396 static const struct cp lcp = {
397 	PPP_LCP, IDX_LCP, CP_LCP, "lcp",
398 	sppp_lcp_up, sppp_lcp_down, sppp_lcp_open, sppp_lcp_close,
399 	sppp_lcp_TO, sppp_lcp_RCR, sppp_lcp_RCN_rej, sppp_lcp_RCN_nak,
400 	sppp_lcp_tlu, sppp_lcp_tld, sppp_lcp_tls, sppp_lcp_tlf,
401 	sppp_lcp_scr
402 };
403 
404 static const struct cp ipcp = {
405 	PPP_IPCP, IDX_IPCP, CP_NCP, "ipcp",
406 	sppp_ipcp_up, sppp_ipcp_down, sppp_ipcp_open, sppp_ipcp_close,
407 	sppp_ipcp_TO, sppp_ipcp_RCR, sppp_ipcp_RCN_rej, sppp_ipcp_RCN_nak,
408 	sppp_ipcp_tlu, sppp_ipcp_tld, sppp_ipcp_tls, sppp_ipcp_tlf,
409 	sppp_ipcp_scr
410 };
411 
412 static const struct cp pap = {
413 	PPP_PAP, IDX_PAP, CP_AUTH, "pap",
414 	sppp_null, sppp_null, sppp_pap_open, sppp_pap_close,
415 	sppp_pap_TO, 0, 0, 0,
416 	sppp_pap_tlu, sppp_pap_tld, sppp_null, sppp_null,
417 	sppp_pap_scr
418 };
419 
420 static const struct cp chap = {
421 	PPP_CHAP, IDX_CHAP, CP_AUTH, "chap",
422 	sppp_null, sppp_null, sppp_chap_open, sppp_chap_close,
423 	sppp_chap_TO, 0, 0, 0,
424 	sppp_chap_tlu, sppp_chap_tld, sppp_null, sppp_null,
425 	sppp_chap_scr
426 };
427 
428 static const struct cp *cps[IDX_COUNT] = {
429 	&lcp,			/* IDX_LCP */
430 	&ipcp,			/* IDX_IPCP */
431 	&pap,			/* IDX_PAP */
432 	&chap,			/* IDX_CHAP */
433 };
434 
435 
436 /*
437  * Exported functions, comprising our interface to the lower layer.
438  */
439 
440 #if defined(__OpenBSD__)
441 /* Workaround */
442 void
443 spppattach(struct ifnet *ifp)
444 {
445 }
446 #endif
447 
448 /*
449  * Process the received packet.
450  */
451 void
452 sppp_input(struct ifnet *ifp, struct mbuf *m)
453 {
454 	struct ppp_header *h;
455 	struct ifqueue *inq = 0;
456 	int s;
457 	struct sppp *sp = (struct sppp *)ifp;
458 	int debug = ifp->if_flags & IFF_DEBUG;
459 
460 	if (ifp->if_flags & IFF_UP)
461 		/* Count received bytes, add FCS and one flag */
462 		ifp->if_ibytes += m->m_pkthdr.len + 3;
463 
464 	if (m->m_pkthdr.len <= PPP_HEADER_LEN) {
465 		/* Too small packet, drop it. */
466 		if (debug)
467 			log(LOG_DEBUG,
468 			    SPP_FMT "input packet is too small, %d bytes\n",
469 			    SPP_ARGS(ifp), m->m_pkthdr.len);
470 	  drop:
471 		++ifp->if_ierrors;
472 		++ifp->if_iqdrops;
473 		m_freem (m);
474 		return;
475 	}
476 
477 	/* Get PPP header. */
478 	h = mtod (m, struct ppp_header*);
479 	m_adj (m, PPP_HEADER_LEN);
480 
481 	switch (h->address) {
482 	case PPP_ALLSTATIONS:
483 		if (h->control != PPP_UI)
484 			goto invalid;
485 		if (sp->pp_flags & PP_CISCO) {
486 			if (debug)
487 				log(LOG_DEBUG,
488 				    SPP_FMT "PPP packet in Cisco mode "
489 				    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
490 				    SPP_ARGS(ifp),
491 				    h->address, h->control, ntohs(h->protocol));
492 			goto drop;
493 		}
494 		switch (ntohs (h->protocol)) {
495 		default:
496 			if (sp->state[IDX_LCP] == STATE_OPENED)
497 				sppp_cp_send (sp, PPP_LCP, PROTO_REJ,
498 					++sp->pp_seq, m->m_pkthdr.len + 2,
499 					&h->protocol);
500 			if (debug)
501 				log(LOG_DEBUG,
502 				    SPP_FMT "invalid input protocol "
503 				    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
504 				    SPP_ARGS(ifp),
505 				    h->address, h->control, ntohs(h->protocol));
506 			++ifp->if_noproto;
507 			goto drop;
508 		case PPP_LCP:
509 			sppp_cp_input(&lcp, sp, m);
510 			m_freem (m);
511 			return;
512 		case PPP_PAP:
513 			if (sp->pp_phase >= PHASE_AUTHENTICATE)
514 				sppp_pap_input(sp, m);
515 			m_freem (m);
516 			return;
517 		case PPP_CHAP:
518 			if (sp->pp_phase >= PHASE_AUTHENTICATE)
519 				sppp_chap_input(sp, m);
520 			m_freem (m);
521 			return;
522 #ifdef INET
523 		case PPP_IPCP:
524 			if (sp->pp_phase == PHASE_NETWORK)
525 				sppp_cp_input(&ipcp, sp, m);
526 			m_freem (m);
527 			return;
528 		case PPP_IP:
529 			if (sp->state[IDX_IPCP] == STATE_OPENED) {
530 				schednetisr (NETISR_IP);
531 				inq = &ipintrq;
532 			}
533 			break;
534 #endif
535 #ifdef IPX
536 		case PPP_IPX:
537 			/* IPX IPXCP not implemented yet */
538 			if (sp->pp_phase == PHASE_NETWORK) {
539 				schednetisr (NETISR_IPX);
540 				inq = &ipxintrq;
541 			}
542 			break;
543 #endif
544 #ifdef NS
545 		case PPP_XNS:
546 			/* XNS IDPCP not implemented yet */
547 			if (sp->pp_phase == PHASE_NETWORK) {
548 				schednetisr (NETISR_NS);
549 				inq = &nsintrq;
550 			}
551 			break;
552 #endif
553 #ifdef ISO
554 		case PPP_ISO:
555 			/* OSI NLCP not implemented yet */
556 			if (sp->pp_phase == PHASE_NETWORK) {
557 				schednetisr (NETISR_ISO);
558 				inq = &clnlintrq;
559 			}
560 			break;
561 #endif
562 		}
563 		break;
564 	case CISCO_MULTICAST:
565 	case CISCO_UNICAST:
566 		/* Don't check the control field here (RFC 1547). */
567 		if (! (sp->pp_flags & PP_CISCO)) {
568 			if (debug)
569 				log(LOG_DEBUG,
570 				    SPP_FMT "Cisco packet in PPP mode "
571 				    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
572 				    SPP_ARGS(ifp),
573 				    h->address, h->control, ntohs(h->protocol));
574 			goto drop;
575 		}
576 		switch (ntohs (h->protocol)) {
577 		default:
578 			++ifp->if_noproto;
579 			goto invalid;
580 		case CISCO_KEEPALIVE:
581 			sppp_cisco_input ((struct sppp*) ifp, m);
582 			m_freem (m);
583 			return;
584 #ifdef INET
585 		case ETHERTYPE_IP:
586 			schednetisr (NETISR_IP);
587 			inq = &ipintrq;
588 			break;
589 #endif
590 #ifdef IPX
591 		case ETHERTYPE_IPX:
592 			schednetisr (NETISR_IPX);
593 			inq = &ipxintrq;
594 			break;
595 #endif
596 #ifdef NS
597 		case ETHERTYPE_NS:
598 			schednetisr (NETISR_NS);
599 			inq = &nsintrq;
600 			break;
601 #endif
602 		}
603 		break;
604 	default:        /* Invalid PPP packet. */
605 	  invalid:
606 		if (debug)
607 			log(LOG_DEBUG,
608 			    SPP_FMT "invalid input packet "
609 			    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
610 			    SPP_ARGS(ifp),
611 			    h->address, h->control, ntohs(h->protocol));
612 		goto drop;
613 	}
614 
615 	if (! (ifp->if_flags & IFF_UP) || ! inq)
616 		goto drop;
617 
618 	/* Check queue. */
619 	s = splimp();
620 	if (IF_QFULL (inq)) {
621 		/* Queue overflow. */
622 		IF_DROP(inq);
623 		splx(s);
624 		if (debug)
625 			log(LOG_DEBUG, SPP_FMT "protocol queue overflow\n",
626 				SPP_ARGS(ifp));
627 		goto drop;
628 	}
629 	IF_ENQUEUE(inq, m);
630 	splx(s);
631 }
632 
633 /*
634  * Enqueue transmit packet.
635  */
636 HIDE int
637 sppp_output(struct ifnet *ifp, struct mbuf *m,
638 	    struct sockaddr *dst, struct rtentry *rt)
639 {
640 	struct sppp *sp = (struct sppp*) ifp;
641 	struct ppp_header *h;
642 	struct ifqueue *ifq = NULL;
643 	int s, len, rv = 0;
644 	ALTQ_DECL(struct altq_pktattr pktattr;)
645 
646 	s = splimp();
647 
648 	if ((ifp->if_flags & IFF_UP) == 0 ||
649 	    (ifp->if_flags & (IFF_RUNNING | IFF_AUTO)) == 0) {
650 		m_freem (m);
651 		splx (s);
652 		return (ENETDOWN);
653 	}
654 
655 	if ((ifp->if_flags & (IFF_RUNNING | IFF_AUTO)) == IFF_AUTO) {
656 		/*
657 		 * Interface is not yet running, but auto-dial.  Need
658 		 * to start LCP for it.
659 		 */
660 		ifp->if_flags |= IFF_RUNNING;
661 		splx(s);
662 		lcp.Open(sp);
663 		s = splimp();
664 	}
665 
666 	/*
667 	 * if the queueing discipline needs packet classification,
668 	 * do it before prepending link headers.
669 	 */
670 	IFQ_CLASSIFY(&ifp->if_snd, m, dst->sa_family, &pktattr);
671 
672 #ifdef INET
673 	/*
674 	 * Put low delay, telnet, rlogin and ftp control packets
675 	 * in front of the queue.
676 	 */
677 	if (dst->sa_family == AF_INET) {
678 		/* XXX Check mbuf length here? */
679 		struct ip *ip = mtod (m, struct ip*);
680 		struct tcphdr *tcp = (struct tcphdr*) ((long*)ip + ip->ip_hl);
681 
682 		/*
683 		 * When using dynamic local IP address assignment by using
684 		 * 0.0.0.0 as a local address, the first TCP session will
685 		 * not connect because the local TCP checksum is computed
686 		 * using 0.0.0.0 which will later become our real IP address
687 		 * so the TCP checksum computed at the remote end will
688 		 * become invalid. So we
689 		 * - don't let packets with src ip addr 0 thru
690 		 * - we flag TCP packets with src ip 0 as an error
691 		 */
692 
693 		if(ip->ip_src.s_addr == INADDR_ANY)     /* -hm */
694 		{
695 			m_freem(m);
696 			splx(s);
697 			if(ip->ip_p == IPPROTO_TCP)
698 				return(EADDRNOTAVAIL);
699 			else
700 				return(0);
701 		}
702 
703 
704 		if (! IF_QFULL (&sp->pp_fastq) &&
705 		    ((ip->ip_tos & IPTOS_LOWDELAY) ||
706 	    	    ((ip->ip_p == IPPROTO_TCP &&
707 	    	    m->m_len >= sizeof (struct ip) + sizeof (struct tcphdr) &&
708 	    	    (INTERACTIVE (ntohs (tcp->th_sport)))) ||
709 	    	    INTERACTIVE (ntohs (tcp->th_dport)))))
710 			ifq = &sp->pp_fastq;
711 	}
712 #endif
713 
714 	/*
715 	 * Prepend general data packet PPP header. For now, IP only.
716 	 */
717 	M_PREPEND (m, PPP_HEADER_LEN, M_DONTWAIT);
718 	if (! m) {
719 		if (ifp->if_flags & IFF_DEBUG)
720 			log(LOG_DEBUG, SPP_FMT "no memory for transmit header\n",
721 				SPP_ARGS(ifp));
722 		++ifp->if_oerrors;
723 		splx (s);
724 		return (ENOBUFS);
725 	}
726 	/*
727 	 * May want to check size of packet
728 	 * (albeit due to the implementation it's always enough)
729 	 */
730 	h = mtod (m, struct ppp_header*);
731 	if (sp->pp_flags & PP_CISCO) {
732 		h->address = CISCO_UNICAST;        /* unicast address */
733 		h->control = 0;
734 	} else {
735 		h->address = PPP_ALLSTATIONS;        /* broadcast address */
736 		h->control = PPP_UI;                 /* Unnumbered Info */
737 	}
738 
739 	switch (dst->sa_family) {
740 #ifdef INET
741 	case AF_INET:   /* Internet Protocol */
742 		if (sp->pp_flags & PP_CISCO)
743 			h->protocol = htons (ETHERTYPE_IP);
744 		else {
745 			/*
746 			 * Don't choke with an ENETDOWN early.  It's
747 			 * possible that we just started dialing out,
748 			 * so don't drop the packet immediately.  If
749 			 * we notice that we run out of buffer space
750 			 * below, we will however remember that we are
751 			 * not ready to carry IP packets, and return
752 			 * ENETDOWN, as opposed to ENOBUFS.
753 			 */
754 			h->protocol = htons(PPP_IP);
755 			if (sp->state[IDX_IPCP] != STATE_OPENED)
756 				rv = ENETDOWN;
757 		}
758 		break;
759 #endif
760 #ifdef NS
761 	case AF_NS:     /* Xerox NS Protocol */
762 		h->protocol = htons ((sp->pp_flags & PP_CISCO) ?
763 			ETHERTYPE_NS : PPP_XNS);
764 		break;
765 #endif
766 #ifdef IPX
767 	case AF_IPX:     /* Novell IPX Protocol */
768 		h->protocol = htons ((sp->pp_flags & PP_CISCO) ?
769 			ETHERTYPE_IPX : PPP_IPX);
770 		break;
771 #endif
772 #ifdef ISO
773 	case AF_ISO:    /* ISO OSI Protocol */
774 		if (sp->pp_flags & PP_CISCO)
775 			goto nosupport;
776 		h->protocol = htons (PPP_ISO);
777 		break;
778 nosupport:
779 #endif
780 	default:
781 		m_freem (m);
782 		++ifp->if_oerrors;
783 		splx (s);
784 		return (EAFNOSUPPORT);
785 	}
786 
787 	/*
788 	 * Queue message on interface, and start output if interface
789 	 * not yet active.
790 	 */
791 	len = m->m_pkthdr.len;
792 	if (ifq != NULL
793 #ifdef ALTQ
794 	    && ALTQ_IS_ENABLED(&ifp->if_snd) == 0
795 #endif
796 		) {
797 		if (IF_QFULL (ifq)) {
798 			IF_DROP (&ifp->if_snd);
799 			m_freem (m);
800 			if (rv == 0)
801 				rv = ENOBUFS;
802 		}
803 		IF_ENQUEUE (ifq, m);
804 	}
805 	else
806 		IFQ_ENQUEUE(&ifp->if_snd, m, &pktattr, rv);
807 	if (rv != 0) {
808 		++ifp->if_oerrors;
809 		splx (s);
810 		return (rv);
811 	}
812 
813 	if (! (ifp->if_flags & IFF_OACTIVE))
814 		(*ifp->if_start) (ifp);
815 
816 	/*
817 	 * Count output packets and bytes.
818 	 * The packet length includes header, FCS and 1 flag,
819 	 * according to RFC 1333.
820 	 */
821 	ifp->if_obytes += len + 3;
822 	splx (s);
823 	return (0);
824 }
825 
826 void
827 sppp_attach(struct ifnet *ifp)
828 {
829 	struct sppp *sp = (struct sppp*) ifp;
830 
831 	/* Initialize keepalive handler. */
832 	if (! spppq)
833 #if defined (__FreeBSD__)
834 		keepalive_ch = timeout(sppp_keepalive, 0, hz * 10);
835 #elif defined(__OpenBSD__)
836 		timeout_set(&keepalive_ch, sppp_keepalive, NULL);
837 		timeout_add(&keepalive_ch, hz * 10);
838 #endif
839 
840 	/* Insert new entry into the keepalive list. */
841 	sp->pp_next = spppq;
842 	spppq = sp;
843 
844 	sp->pp_if.if_type = IFT_PPP;
845 	sp->pp_if.if_output = sppp_output;
846 	IFQ_SET_MAXLEN(&sp->pp_if.if_snd, 50);
847 	sp->pp_fastq.ifq_maxlen = 50;
848 	sp->pp_cpq.ifq_maxlen = 50;
849 	sp->pp_loopcnt = 0;
850 	sp->pp_alivecnt = 0;
851 	sp->pp_seq = 0;
852 	sp->pp_rseq = 0;
853 	sp->pp_phase = PHASE_DEAD;
854 	sp->pp_up = lcp.Up;
855 	sp->pp_down = lcp.Down;
856 
857 	sppp_lcp_init(sp);
858 	sppp_ipcp_init(sp);
859 	sppp_pap_init(sp);
860 	sppp_chap_init(sp);
861 }
862 
863 void
864 sppp_detach(struct ifnet *ifp)
865 {
866 	struct sppp **q, *p, *sp = (struct sppp*) ifp;
867 	int i;
868 
869 	/* Remove the entry from the keepalive list. */
870 	for (q = &spppq; (p = *q); q = &p->pp_next)
871 		if (p == sp) {
872 			*q = p->pp_next;
873 			break;
874 		}
875 
876 	/* Stop keepalive handler. */
877 	if (! spppq)
878 		UNTIMEOUT(sppp_keepalive, 0, keepalive_ch);
879 
880 	for (i = 0; i < IDX_COUNT; i++)
881 		UNTIMEOUT((cps[i])->TO, (void *)sp, sp->ch[i]);
882 	UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
883 }
884 
885 /*
886  * Flush the interface output queue.
887  */
888 void
889 sppp_flush(struct ifnet *ifp)
890 {
891 	struct sppp *sp = (struct sppp*) ifp;
892 
893 	IFQ_PURGE(&sp->pp_if.if_snd);
894 	sppp_qflush (&sp->pp_fastq);
895 	sppp_qflush (&sp->pp_cpq);
896 }
897 
898 /*
899  * Check if the output queue is empty.
900  */
901 int
902 sppp_isempty(struct ifnet *ifp)
903 {
904 	struct sppp *sp = (struct sppp*) ifp;
905 	int empty, s;
906 
907 	s = splimp();
908 	empty = !sp->pp_fastq.ifq_head && !sp->pp_cpq.ifq_head &&
909 		IFQ_IS_EMPTY(&sp->pp_if.if_snd);
910 	splx(s);
911 	return (empty);
912 }
913 
914 /*
915  * Get next packet to send.
916  */
917 struct mbuf *
918 sppp_dequeue(struct ifnet *ifp)
919 {
920 	struct sppp *sp = (struct sppp*) ifp;
921 	struct mbuf *m;
922 	int s;
923 
924 	s = splimp();
925 	/*
926 	 * Process only the control protocol queue until we have at
927 	 * least one NCP open.
928 	 *
929 	 * Do always serve all three queues in Cisco mode.
930 	 */
931 	IF_DEQUEUE(&sp->pp_cpq, m);
932 	if (m == NULL &&
933 	    (sppp_ncp_check(sp) || (sp->pp_flags & PP_CISCO) != 0)) {
934 		IF_DEQUEUE(&sp->pp_fastq, m);
935 		if (m == NULL)
936 			IFQ_DEQUEUE (&sp->pp_if.if_snd, m);
937 	}
938 	splx(s);
939 	return m;
940 }
941 
942 /*
943  * Pick the next packet, do not remove it from the queue.
944  */
945 struct mbuf *
946 sppp_pick(struct ifnet *ifp)
947 {
948 	struct sppp *sp = (struct sppp*)ifp;
949 	struct mbuf *m;
950 	int s;
951 
952 	s= splimp ();
953 
954 	m = sp->pp_cpq.ifq_head;
955 	if (m == NULL &&
956 	    (sp->pp_phase == PHASE_NETWORK ||
957 	     (sp->pp_flags & PP_CISCO) != 0))
958 		if ((m = sp->pp_fastq.ifq_head) == NULL)
959 			IFQ_POLL(&sp->pp_if.if_snd, m);
960 	splx (s);
961 	return (m);
962 }
963 
964 /*
965  * Process an ioctl request.  Called on low priority level.
966  */
967 int
968 sppp_ioctl(struct ifnet *ifp, u_long cmd, void *data)
969 {
970 	struct ifreq *ifr = (struct ifreq*) data;
971 	struct sppp *sp = (struct sppp*) ifp;
972 	int s, rv, going_up, going_down;
973 
974 	s = splimp();
975 	rv = 0;
976 	switch (cmd) {
977 	case SIOCAIFADDR:
978 	case SIOCSIFDSTADDR:
979 		break;
980 
981 	case SIOCSIFADDR:
982 		if_up(ifp);
983 		/* fall through... */
984 
985 	case SIOCSIFFLAGS:
986 			/* sanity */
987 		if (ifp->if_flags & IFF_PASSIVE)
988 			ifp->if_flags &= ~IFF_AUTO;
989 
990 		going_up = (ifp->if_flags & IFF_UP) && ! (ifp->if_flags &
991 			(IFF_RUNNING | IFF_AUTO | IFF_PASSIVE));
992 		going_down = ! (ifp->if_flags & IFF_UP) &&
993 			(ifp->if_flags & IFF_RUNNING);
994 
995 		if (going_up || going_down) {
996 			if (! (sp->pp_flags & PP_CISCO))
997 			lcp.Close(sp);
998 			else {
999 				sppp_flush(ifp);
1000 				ifp->if_flags &= ~IFF_RUNNING;
1001 			}
1002 		}
1003 		if (going_up) {
1004 			/* neither auto-dial nor passive */
1005 			ifp->if_flags |= IFF_RUNNING;
1006 			if (!(sp->pp_flags & PP_CISCO))
1007 				lcp.Open(sp);
1008 		}
1009 		break;
1010 
1011 #ifdef SIOCSIFMTU
1012 	case SIOCSIFMTU:
1013 		if (ifr->ifr_mtu < 128 || ifr->ifr_mtu > sp->lcp.their_mru) {
1014 			splx(s);
1015 			return (EINVAL);
1016 		}
1017 		ifp->if_mtu = ifr->ifr_mtu;
1018 		break;
1019 #endif
1020 #ifdef SLIOCSETMTU
1021 	case SLIOCSETMTU:
1022 		if (*(short*)data < 128 || *(short*)data > sp->lcp.their_mru) {
1023 			splx(s);
1024 			return (EINVAL);
1025 		}
1026 		ifp->if_mtu = *(short*)data;
1027 		break;
1028 #endif
1029 #ifdef SIOCGIFMTU
1030 	case SIOCGIFMTU:
1031 		ifr->ifr_mtu = ifp->if_mtu;
1032 		break;
1033 #endif
1034 #ifdef SLIOCGETMTU
1035 	case SLIOCGETMTU:
1036 		*(short*)data = ifp->if_mtu;
1037 		break;
1038 #endif
1039 	case SIOCADDMULTI:
1040 	case SIOCDELMULTI:
1041 		break;
1042 
1043 	case SIOCGIFGENERIC:
1044 	case SIOCSIFGENERIC:
1045 		rv = sppp_params(sp, cmd, data);
1046 		break;
1047 
1048 	default:
1049 		rv = ENOTTY;
1050 	}
1051 	splx(s);
1052 	return rv;
1053 }
1054 
1055 
1056 /*
1057  * Cisco framing implementation.
1058  */
1059 
1060 /*
1061  * Handle incoming Cisco keepalive protocol packets.
1062  */
1063 HIDE void
1064 sppp_cisco_input(struct sppp *sp, struct mbuf *m)
1065 {
1066 	STDDCL;
1067 	struct cisco_packet *h;
1068 	u_long me, mymask;
1069 
1070 	if (m->m_pkthdr.len < CISCO_PACKET_LEN) {
1071 		if (debug)
1072 			log(LOG_DEBUG,
1073 			    SPP_FMT "cisco invalid packet length: %d bytes\n",
1074 			    SPP_ARGS(ifp), m->m_pkthdr.len);
1075 		return;
1076 	}
1077 	h = mtod (m, struct cisco_packet*);
1078 	if (debug)
1079 		log(LOG_DEBUG,
1080 		    SPP_FMT "cisco input: %d bytes "
1081 		    "<0x%lx 0x%lx 0x%lx 0x%x 0x%x-0x%x>\n",
1082 		    SPP_ARGS(ifp), m->m_pkthdr.len,
1083 		    (u_long)ntohl (h->type), (u_long)h->par1, (u_long)h->par2, (u_int)h->rel,
1084 		    (u_int)h->time0, (u_int)h->time1);
1085 	switch (ntohl (h->type)) {
1086 	default:
1087 		if (debug)
1088 			addlog(SPP_FMT "cisco unknown packet type: 0x%lx\n",
1089 			       SPP_ARGS(ifp), (u_long)ntohl (h->type));
1090 		break;
1091 	case CISCO_ADDR_REPLY:
1092 		/* Reply on address request, ignore */
1093 		break;
1094 	case CISCO_KEEPALIVE_REQ:
1095 		sp->pp_alivecnt = 0;
1096 		sp->pp_rseq = ntohl (h->par1);
1097 		if (sp->pp_seq == sp->pp_rseq) {
1098 			/* Local and remote sequence numbers are equal.
1099 			 * Probably, the line is in loopback mode. */
1100 			if (sp->pp_loopcnt >= MAXALIVECNT) {
1101 				printf (SPP_FMT "loopback\n",
1102 					SPP_ARGS(ifp));
1103 				sp->pp_loopcnt = 0;
1104 				if (ifp->if_flags & IFF_UP) {
1105 					if_down (ifp);
1106 					sppp_qflush (&sp->pp_cpq);
1107 				}
1108 			}
1109 			++sp->pp_loopcnt;
1110 
1111 			/* Generate new local sequence number */
1112 #if defined (__FreeBSD__) || defined (__NetBSD__) || defined(__OpenBSD__)
1113 			sp->pp_seq = random();
1114 #else
1115 			sp->pp_seq ^= time.tv_sec ^ time.tv_usec;
1116 #endif
1117 			break;
1118 		}
1119 		sp->pp_loopcnt = 0;
1120 		if (! (ifp->if_flags & IFF_UP) &&
1121 		    (ifp->if_flags & IFF_RUNNING)) {
1122 			if_up(ifp);
1123 			printf (SPP_FMT "up\n", SPP_ARGS(ifp));
1124 		}
1125 		break;
1126 	case CISCO_ADDR_REQ:
1127 		sppp_get_ip_addrs(sp, &me, 0, &mymask);
1128 		if (me != 0L)
1129 			sppp_cisco_send(sp, CISCO_ADDR_REPLY, me, mymask);
1130 		break;
1131 	}
1132 }
1133 
1134 /*
1135  * Send Cisco keepalive packet.
1136  */
1137 HIDE void
1138 sppp_cisco_send(struct sppp *sp, int type, long par1, long par2)
1139 {
1140 	STDDCL;
1141 	struct ppp_header *h;
1142 	struct cisco_packet *ch;
1143 	struct mbuf *m;
1144 #if defined (__FreeBSD__)
1145 	struct timeval tv;
1146 #else
1147 	u_long t = (time.tv_sec - boottime.tv_sec) * 1000;
1148 #endif
1149 
1150 #if defined (__FreeBSD__)
1151 	getmicrouptime(&tv);
1152 #endif
1153 
1154 	MGETHDR (m, M_DONTWAIT, MT_DATA);
1155 	if (! m)
1156 		return;
1157 	m->m_pkthdr.len = m->m_len = PPP_HEADER_LEN + CISCO_PACKET_LEN;
1158 	m->m_pkthdr.rcvif = 0;
1159 
1160 	h = mtod (m, struct ppp_header*);
1161 	h->address = CISCO_MULTICAST;
1162 	h->control = 0;
1163 	h->protocol = htons (CISCO_KEEPALIVE);
1164 
1165 	ch = (struct cisco_packet*) (h + 1);
1166 	ch->type = htonl (type);
1167 	ch->par1 = htonl (par1);
1168 	ch->par2 = htonl (par2);
1169 	ch->rel = -1;
1170 
1171 #if defined (__FreeBSD__)
1172 	ch->time0 = htons ((u_short) (tv.tv_sec >> 16));
1173 	ch->time1 = htons ((u_short) tv.tv_sec);
1174 #else
1175 	ch->time0 = htons ((u_short) (t >> 16));
1176 	ch->time1 = htons ((u_short) t);
1177 #endif
1178 
1179 	if (debug)
1180 		log(LOG_DEBUG,
1181 		    SPP_FMT "cisco output: <0x%lx 0x%lx 0x%lx 0x%x 0x%x-0x%x>\n",
1182 			SPP_ARGS(ifp), (u_long)ntohl (ch->type), (u_long)ch->par1,
1183 			(u_long)ch->par2, (u_int)ch->rel, (u_int)ch->time0, (u_int)ch->time1);
1184 
1185 	if (IF_QFULL (&sp->pp_cpq)) {
1186 		IF_DROP (&sp->pp_fastq);
1187 		IF_DROP (&ifp->if_snd);
1188 		m_freem (m);
1189 		m = NULL;
1190 	} else
1191 		IF_ENQUEUE (&sp->pp_cpq, m);
1192 	if (! (ifp->if_flags & IFF_OACTIVE))
1193 		(*ifp->if_start) (ifp);
1194 	if (m != NULL)
1195 		ifp->if_obytes += m->m_pkthdr.len + 3;
1196 }
1197 
1198 /*
1199  * PPP protocol implementation.
1200  */
1201 
1202 /*
1203  * Send PPP control protocol packet.
1204  */
1205 HIDE void
1206 sppp_cp_send(struct sppp *sp, u_short proto, u_char type,
1207 	     u_char ident, u_short len, void *data)
1208 {
1209 	STDDCL;
1210 	struct ppp_header *h;
1211 	struct lcp_header *lh;
1212 	struct mbuf *m;
1213 
1214 	if (len > MHLEN - PPP_HEADER_LEN - LCP_HEADER_LEN)
1215 		len = MHLEN - PPP_HEADER_LEN - LCP_HEADER_LEN;
1216 	MGETHDR (m, M_DONTWAIT, MT_DATA);
1217 	if (! m)
1218 		return;
1219 	m->m_pkthdr.len = m->m_len = PPP_HEADER_LEN + LCP_HEADER_LEN + len;
1220 	m->m_pkthdr.rcvif = 0;
1221 
1222 	h = mtod (m, struct ppp_header*);
1223 	h->address = PPP_ALLSTATIONS;        /* broadcast address */
1224 	h->control = PPP_UI;                 /* Unnumbered Info */
1225 	h->protocol = htons (proto);         /* Link Control Protocol */
1226 
1227 	lh = (struct lcp_header*) (h + 1);
1228 	lh->type = type;
1229 	lh->ident = ident;
1230 	lh->len = htons (LCP_HEADER_LEN + len);
1231 	if (len)
1232 		bcopy (data, lh+1, len);
1233 
1234 	if (debug) {
1235 		log(LOG_DEBUG, SPP_FMT "%s output <%s id=0x%x len=%d",
1236 		    SPP_ARGS(ifp),
1237 		    sppp_proto_name(proto),
1238 		    sppp_cp_type_name (lh->type), lh->ident,
1239 		    ntohs (lh->len));
1240 		if (len)
1241 			sppp_print_bytes ((u_char*) (lh+1), len);
1242 		addlog(">\n");
1243 	}
1244 	if (IF_QFULL (&sp->pp_cpq)) {
1245 		IF_DROP (&sp->pp_fastq);
1246 		IF_DROP (&ifp->if_snd);
1247 		m_freem (m);
1248 		++ifp->if_oerrors;
1249 		m = NULL;
1250 	} else
1251 		IF_ENQUEUE (&sp->pp_cpq, m);
1252 	if (! (ifp->if_flags & IFF_OACTIVE))
1253 		(*ifp->if_start) (ifp);
1254 	if (m != NULL)
1255 		ifp->if_obytes += m->m_pkthdr.len + 3;
1256 }
1257 
1258 /*
1259  * Handle incoming PPP control protocol packets.
1260  */
1261 HIDE void
1262 sppp_cp_input(const struct cp *cp, struct sppp *sp, struct mbuf *m)
1263 {
1264 	STDDCL;
1265 	struct lcp_header *h;
1266 	int len = m->m_pkthdr.len;
1267 	int rv;
1268 	u_char *p;
1269 
1270 	if (len < 4) {
1271 		if (debug)
1272 			log(LOG_DEBUG,
1273 			    SPP_FMT "%s invalid packet length: %d bytes\n",
1274 			    SPP_ARGS(ifp), cp->name, len);
1275 		return;
1276 	}
1277 	h = mtod (m, struct lcp_header*);
1278 	if (debug) {
1279 		log(LOG_DEBUG,
1280 		    SPP_FMT "%s input(%s): <%s id=0x%x len=%d",
1281 		    SPP_ARGS(ifp), cp->name,
1282 		    sppp_state_name(sp->state[cp->protoidx]),
1283 		    sppp_cp_type_name (h->type), h->ident, ntohs (h->len));
1284 		if (len > 4)
1285 			sppp_print_bytes ((u_char*) (h+1), len-4);
1286 		addlog(">\n");
1287 	}
1288 	if (len > ntohs (h->len))
1289 		len = ntohs (h->len);
1290 	p = (u_char *)(h + 1);
1291 	switch (h->type) {
1292 	case CONF_REQ:
1293 		if (len < 4) {
1294 			if (debug)
1295 				addlog(SPP_FMT "%s invalid conf-req length %d\n",
1296 				       SPP_ARGS(ifp), cp->name,
1297 				       len);
1298 			++ifp->if_ierrors;
1299 			break;
1300 		}
1301 		/* handle states where RCR doesn't get a SCA/SCN */
1302 		switch (sp->state[cp->protoidx]) {
1303 		case STATE_CLOSING:
1304 		case STATE_STOPPING:
1305 			return;
1306 		case STATE_CLOSED:
1307 			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident,
1308 				     0, 0);
1309 			return;
1310 		}
1311 		rv = (cp->RCR)(sp, h, len);
1312 		switch (sp->state[cp->protoidx]) {
1313 		case STATE_OPENED:
1314 			sppp_cp_change_state(cp, sp, rv?
1315 					     STATE_ACK_SENT: STATE_REQ_SENT);
1316 			(cp->tld)(sp);
1317 			(cp->scr)(sp);
1318 			break;
1319 		case STATE_ACK_SENT:
1320 		case STATE_REQ_SENT:
1321 			sppp_cp_change_state(cp, sp, rv?
1322 					     STATE_ACK_SENT: STATE_REQ_SENT);
1323 			break;
1324 		case STATE_STOPPED:
1325 			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1326 			sppp_cp_change_state(cp, sp, rv?
1327 					     STATE_ACK_SENT: STATE_REQ_SENT);
1328 			(cp->scr)(sp);
1329 			break;
1330 		case STATE_ACK_RCVD:
1331 			if (rv) {
1332 				sppp_cp_change_state(cp, sp, STATE_OPENED);
1333 				if (debug)
1334 					log(LOG_DEBUG, SPP_FMT "%s tlu\n",
1335 					    SPP_ARGS(ifp),
1336 					    cp->name);
1337 				(cp->tlu)(sp);
1338 			} else
1339 				sppp_cp_change_state(cp, sp, STATE_ACK_RCVD);
1340 			break;
1341 		default:
1342 			/* printf(SPP_FMT "%s illegal %s in state %s\n",
1343 			       SPP_ARGS(ifp), cp->name,
1344 			       sppp_cp_type_name(h->type),
1345 			       sppp_state_name(sp->state[cp->protoidx])); */
1346 			++ifp->if_ierrors;
1347 		}
1348 		break;
1349 	case CONF_ACK:
1350 		if (h->ident != sp->confid[cp->protoidx]) {
1351 			if (debug)
1352 				addlog(SPP_FMT "%s id mismatch 0x%x != 0x%x\n",
1353 				       SPP_ARGS(ifp), cp->name,
1354 				       h->ident, sp->confid[cp->protoidx]);
1355 			++ifp->if_ierrors;
1356 			break;
1357 		}
1358 		switch (sp->state[cp->protoidx]) {
1359 		case STATE_CLOSED:
1360 		case STATE_STOPPED:
1361 			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident, 0, 0);
1362 			break;
1363 		case STATE_CLOSING:
1364 		case STATE_STOPPING:
1365 			break;
1366 		case STATE_REQ_SENT:
1367 			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1368 			sppp_cp_change_state(cp, sp, STATE_ACK_RCVD);
1369 			break;
1370 		case STATE_OPENED:
1371 			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1372 			(cp->tld)(sp);
1373 			(cp->scr)(sp);
1374 			break;
1375 		case STATE_ACK_RCVD:
1376 			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1377 			(cp->scr)(sp);
1378 			break;
1379 		case STATE_ACK_SENT:
1380 			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1381 			sppp_cp_change_state(cp, sp, STATE_OPENED);
1382 			if (debug)
1383 				log(LOG_DEBUG, SPP_FMT "%s tlu\n",
1384 				       SPP_ARGS(ifp), cp->name);
1385 			(cp->tlu)(sp);
1386 			break;
1387 		default:
1388 			/* printf(SPP_FMT "%s illegal %s in state %s\n",
1389 			       SPP_ARGS(ifp), cp->name,
1390 			       sppp_cp_type_name(h->type),
1391 			       sppp_state_name(sp->state[cp->protoidx])); */
1392 			++ifp->if_ierrors;
1393 		}
1394 		break;
1395 	case CONF_NAK:
1396 	case CONF_REJ:
1397 		if (h->ident != sp->confid[cp->protoidx]) {
1398 			if (debug)
1399 				addlog(SPP_FMT "%s id mismatch 0x%x != 0x%x\n",
1400 				       SPP_ARGS(ifp), cp->name,
1401 				       h->ident, sp->confid[cp->protoidx]);
1402 			++ifp->if_ierrors;
1403 			break;
1404 		}
1405 		if (h->type == CONF_NAK)
1406 			(cp->RCN_nak)(sp, h, len);
1407 		else /* CONF_REJ */
1408 			(cp->RCN_rej)(sp, h, len);
1409 
1410 		switch (sp->state[cp->protoidx]) {
1411 		case STATE_CLOSED:
1412 		case STATE_STOPPED:
1413 			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident, 0, 0);
1414 			break;
1415 		case STATE_REQ_SENT:
1416 		case STATE_ACK_SENT:
1417 			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1418 			(cp->scr)(sp);
1419 			break;
1420 		case STATE_OPENED:
1421 			sppp_cp_change_state(cp, sp, STATE_ACK_SENT);
1422 			(cp->tld)(sp);
1423 			(cp->scr)(sp);
1424 			break;
1425 		case STATE_ACK_RCVD:
1426 			sppp_cp_change_state(cp, sp, STATE_ACK_SENT);
1427 			(cp->scr)(sp);
1428 			break;
1429 		case STATE_CLOSING:
1430 		case STATE_STOPPING:
1431 			break;
1432 		default:
1433 			/* printf(SPP_FMT "%s illegal %s in state %s\n",
1434 			       SPP_ARGS(ifp), cp->name,
1435 			       sppp_cp_type_name(h->type),
1436 			       sppp_state_name(sp->state[cp->protoidx])); */
1437 			++ifp->if_ierrors;
1438 		}
1439 		break;
1440 
1441 	case TERM_REQ:
1442 		switch (sp->state[cp->protoidx]) {
1443 		case STATE_ACK_RCVD:
1444 		case STATE_ACK_SENT:
1445 			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1446 			/* fall through */
1447 		case STATE_CLOSED:
1448 		case STATE_STOPPED:
1449 		case STATE_CLOSING:
1450 		case STATE_STOPPING:
1451 		case STATE_REQ_SENT:
1452 		  sta:
1453 			/* Send Terminate-Ack packet. */
1454 			if (debug)
1455 				log(LOG_DEBUG, SPP_FMT "%s send terminate-ack\n",
1456 				    SPP_ARGS(ifp), cp->name);
1457 			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident, 0, 0);
1458 			break;
1459 		case STATE_OPENED:
1460 			sp->rst_counter[cp->protoidx] = 0;
1461 			sppp_cp_change_state(cp, sp, STATE_STOPPING);
1462 			(cp->tld)(sp);
1463 			goto sta;
1464 			break;
1465 		default:
1466 			/* printf(SPP_FMT "%s illegal %s in state %s\n",
1467 			       SPP_ARGS(ifp), cp->name,
1468 			       sppp_cp_type_name(h->type),
1469 			       sppp_state_name(sp->state[cp->protoidx])); */
1470 			++ifp->if_ierrors;
1471 		}
1472 		break;
1473 	case TERM_ACK:
1474 		switch (sp->state[cp->protoidx]) {
1475 		case STATE_CLOSED:
1476 		case STATE_STOPPED:
1477 		case STATE_REQ_SENT:
1478 		case STATE_ACK_SENT:
1479 			break;
1480 		case STATE_CLOSING:
1481 			sppp_cp_change_state(cp, sp, STATE_CLOSED);
1482 			(cp->tlf)(sp);
1483 			break;
1484 		case STATE_STOPPING:
1485 			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1486 			(cp->tlf)(sp);
1487 			break;
1488 		case STATE_ACK_RCVD:
1489 			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1490 			break;
1491 		case STATE_OPENED:
1492 			sppp_cp_change_state(cp, sp, STATE_ACK_RCVD);
1493 			(cp->tld)(sp);
1494 			(cp->scr)(sp);
1495 			break;
1496 		default:
1497 			/* printf(SPP_FMT "%s illegal %s in state %s\n",
1498 			       SPP_ARGS(ifp), cp->name,
1499 			       sppp_cp_type_name(h->type),
1500 			       sppp_state_name(sp->state[cp->protoidx])); */
1501 			++ifp->if_ierrors;
1502 		}
1503 		break;
1504 	case CODE_REJ:
1505 	case PROTO_REJ:
1506 		/* XXX catastrophic rejects (RXJ-) aren't handled yet. */
1507 		log(LOG_INFO,
1508 		    SPP_FMT "%s: ignoring RXJ (%s) for proto 0x%x, "
1509 		    "danger will robinson\n",
1510 		    SPP_ARGS(ifp), cp->name,
1511 		    sppp_cp_type_name(h->type), ntohs(*((u_short *)p)));
1512 		switch (sp->state[cp->protoidx]) {
1513 		case STATE_CLOSED:
1514 		case STATE_STOPPED:
1515 		case STATE_REQ_SENT:
1516 		case STATE_ACK_SENT:
1517 		case STATE_CLOSING:
1518 		case STATE_STOPPING:
1519 		case STATE_OPENED:
1520 			break;
1521 		case STATE_ACK_RCVD:
1522 			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1523 			break;
1524 		default:
1525 			/* printf(SPP_FMT "%s illegal %s in state %s\n",
1526 			       SPP_ARGS(ifp), cp->name,
1527 			       sppp_cp_type_name(h->type),
1528 			       sppp_state_name(sp->state[cp->protoidx])); */
1529 			++ifp->if_ierrors;
1530 		}
1531 		break;
1532 	case DISC_REQ:
1533 		if (cp->proto != PPP_LCP)
1534 			goto illegal;
1535 		/* Discard the packet. */
1536 		break;
1537 	case ECHO_REQ:
1538 		if (cp->proto != PPP_LCP)
1539 			goto illegal;
1540 		if (sp->state[cp->protoidx] != STATE_OPENED) {
1541 			if (debug)
1542 				addlog(SPP_FMT "lcp echo req but lcp closed\n",
1543 				       SPP_ARGS(ifp));
1544 			++ifp->if_ierrors;
1545 			break;
1546 		}
1547 		if (len < 8) {
1548 			if (debug)
1549 				addlog(SPP_FMT "invalid lcp echo request "
1550 				       "packet length: %d bytes\n",
1551 				       SPP_ARGS(ifp), len);
1552 			break;
1553 		}
1554 		if (ntohl (*(long*)(h+1)) == sp->lcp.magic) {
1555 			/* Line loopback mode detected. */
1556 			printf(SPP_FMT "loopback\n", SPP_ARGS(ifp));
1557 			/* Shut down the PPP link. */
1558  			lcp.Close(sp);
1559 			break;
1560 		}
1561 		*(long*)(h+1) = htonl (sp->lcp.magic);
1562 		if (debug)
1563 			addlog(SPP_FMT "got lcp echo req, sending echo rep\n",
1564 			       SPP_ARGS(ifp));
1565 		sppp_cp_send (sp, PPP_LCP, ECHO_REPLY, h->ident, len-4, h+1);
1566 		break;
1567 	case ECHO_REPLY:
1568 		if (cp->proto != PPP_LCP)
1569 			goto illegal;
1570 		if (h->ident != sp->lcp.echoid) {
1571 			++ifp->if_ierrors;
1572 			break;
1573 		}
1574 		if (len < 8) {
1575 			if (debug)
1576 				addlog(SPP_FMT "lcp invalid echo reply "
1577 				       "packet length: %d bytes\n",
1578 				       SPP_ARGS(ifp), len);
1579 			break;
1580 		}
1581 		if (debug)
1582 			addlog(SPP_FMT "lcp got echo rep\n",
1583 			       SPP_ARGS(ifp));
1584 		if (ntohl (*(long*)(h+1)) != sp->lcp.magic)
1585 			sp->pp_alivecnt = 0;
1586 		break;
1587 	default:
1588 		/* Unknown packet type -- send Code-Reject packet. */
1589 	  illegal:
1590 		if (debug)
1591 			addlog(SPP_FMT "%s send code-rej for 0x%x\n",
1592 			       SPP_ARGS(ifp), cp->name, h->type);
1593 		sppp_cp_send(sp, cp->proto, CODE_REJ, ++sp->pp_seq,
1594 			     m->m_pkthdr.len, h);
1595 		++ifp->if_ierrors;
1596 	}
1597 }
1598 
1599 
1600 /*
1601  * The generic part of all Up/Down/Open/Close/TO event handlers.
1602  * Basically, the state transition handling in the automaton.
1603  */
1604 HIDE void
1605 sppp_up_event(const struct cp *cp, struct sppp *sp)
1606 {
1607 	STDDCL;
1608 
1609 	if (debug)
1610 		log(LOG_DEBUG, SPP_FMT "%s up(%s)\n",
1611 		    SPP_ARGS(ifp), cp->name,
1612 		    sppp_state_name(sp->state[cp->protoidx]));
1613 
1614 	switch (sp->state[cp->protoidx]) {
1615 	case STATE_INITIAL:
1616 		sppp_cp_change_state(cp, sp, STATE_CLOSED);
1617 		break;
1618 	case STATE_STARTING:
1619 		sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1620 		sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1621 		(cp->scr)(sp);
1622 		break;
1623 	default:
1624 		/* printf(SPP_FMT "%s illegal up in state %s\n",
1625 		       SPP_ARGS(ifp), cp->name,
1626 		       sppp_state_name(sp->state[cp->protoidx])); */
1627 		break;
1628 	}
1629 }
1630 
1631 HIDE void
1632 sppp_down_event(const struct cp *cp, struct sppp *sp)
1633 {
1634 	STDDCL;
1635 
1636 	if (debug)
1637 		log(LOG_DEBUG, SPP_FMT "%s down(%s)\n",
1638 		    SPP_ARGS(ifp), cp->name,
1639 		    sppp_state_name(sp->state[cp->protoidx]));
1640 
1641 	switch (sp->state[cp->protoidx]) {
1642 	case STATE_CLOSED:
1643 	case STATE_CLOSING:
1644 		sppp_cp_change_state(cp, sp, STATE_INITIAL);
1645 		break;
1646 	case STATE_STOPPED:
1647 		sppp_cp_change_state(cp, sp, STATE_STARTING);
1648 		(cp->tls)(sp);
1649 		break;
1650 	case STATE_STOPPING:
1651 	case STATE_REQ_SENT:
1652 	case STATE_ACK_RCVD:
1653 	case STATE_ACK_SENT:
1654 		sppp_cp_change_state(cp, sp, STATE_STARTING);
1655 		break;
1656 	case STATE_OPENED:
1657 		sppp_cp_change_state(cp, sp, STATE_STARTING);
1658 		(cp->tld)(sp);
1659 		break;
1660 	default:
1661 		/* printf(SPP_FMT "%s illegal down in state %s\n",
1662 		       SPP_ARGS(ifp), cp->name,
1663 		       sppp_state_name(sp->state[cp->protoidx])); */
1664 		break;
1665 	}
1666 }
1667 
1668 
1669 HIDE void
1670 sppp_open_event(const struct cp *cp, struct sppp *sp)
1671 {
1672 	STDDCL;
1673 
1674 	if (debug)
1675 		log(LOG_DEBUG, SPP_FMT "%s open(%s)\n",
1676 		    SPP_ARGS(ifp), cp->name,
1677 		    sppp_state_name(sp->state[cp->protoidx]));
1678 
1679 	switch (sp->state[cp->protoidx]) {
1680 	case STATE_INITIAL:
1681 		sppp_cp_change_state(cp, sp, STATE_STARTING);
1682 		(cp->tls)(sp);
1683 		break;
1684 	case STATE_STARTING:
1685 		break;
1686 	case STATE_CLOSED:
1687 		sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1688 		sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1689 		(cp->scr)(sp);
1690 		break;
1691 	case STATE_STOPPED:
1692 	case STATE_STOPPING:
1693 	case STATE_REQ_SENT:
1694 	case STATE_ACK_RCVD:
1695 	case STATE_ACK_SENT:
1696 	case STATE_OPENED:
1697 		break;
1698 	case STATE_CLOSING:
1699 		sppp_cp_change_state(cp, sp, STATE_STOPPING);
1700 		break;
1701 	}
1702 }
1703 
1704 
1705 HIDE void
1706 sppp_close_event(const struct cp *cp, struct sppp *sp)
1707 {
1708 	STDDCL;
1709 
1710 	if (debug)
1711 		log(LOG_DEBUG, SPP_FMT "%s close(%s)\n",
1712 		    SPP_ARGS(ifp), cp->name,
1713 		    sppp_state_name(sp->state[cp->protoidx]));
1714 
1715 	switch (sp->state[cp->protoidx]) {
1716 	case STATE_INITIAL:
1717 	case STATE_CLOSED:
1718 	case STATE_CLOSING:
1719 		break;
1720 	case STATE_STARTING:
1721 		sppp_cp_change_state(cp, sp, STATE_INITIAL);
1722 		(cp->tlf)(sp);
1723 		break;
1724 	case STATE_STOPPED:
1725 		sppp_cp_change_state(cp, sp, STATE_CLOSED);
1726 		break;
1727 	case STATE_STOPPING:
1728 		sppp_cp_change_state(cp, sp, STATE_CLOSING);
1729 		break;
1730 	case STATE_OPENED:
1731 		sppp_cp_change_state(cp, sp, STATE_CLOSING);
1732 		sp->rst_counter[cp->protoidx] = sp->lcp.max_terminate;
1733 		sppp_cp_send(sp, cp->proto, TERM_REQ, ++sp->pp_seq, 0, 0);
1734 		(cp->tld)(sp);
1735 		break;
1736 	case STATE_REQ_SENT:
1737 	case STATE_ACK_RCVD:
1738 	case STATE_ACK_SENT:
1739 		sp->rst_counter[cp->protoidx] = sp->lcp.max_terminate;
1740 		sppp_cp_send(sp, cp->proto, TERM_REQ, ++sp->pp_seq, 0, 0);
1741 		sppp_cp_change_state(cp, sp, STATE_CLOSING);
1742 		break;
1743 	}
1744 }
1745 
1746 HIDE void
1747 sppp_increasing_timeout (const struct cp *cp, struct sppp *sp)
1748 {
1749 	int timo;
1750 
1751 	timo = sp->lcp.max_configure - sp->rst_counter[cp->protoidx];
1752 	if (timo < 1)
1753 		timo = 1;
1754 #if defined(__FreeBSD__) && __FreeBSD__ >= 3
1755 	sp->ch[cp->protoidx] =
1756 	    timeout(cp->TO, (void *)sp, timo * sp->lcp.timeout);
1757 #elif defined(__OpenBSD__)
1758 	timeout_set(&sp->ch[cp->protoidx], cp->TO, (void *)sp);
1759 	timeout_add(&sp->ch[cp->protoidx], timo * sp->lcp.timeout);
1760 #endif
1761 }
1762 
1763 HIDE void
1764 sppp_to_event(const struct cp *cp, struct sppp *sp)
1765 {
1766 	STDDCL;
1767 	int s;
1768 
1769 	s = splimp();
1770 	if (debug)
1771 		log(LOG_DEBUG, SPP_FMT "%s TO(%s) rst_counter = %d\n",
1772 		    SPP_ARGS(ifp), cp->name,
1773 		    sppp_state_name(sp->state[cp->protoidx]),
1774 		    sp->rst_counter[cp->protoidx]);
1775 
1776 	if (--sp->rst_counter[cp->protoidx] < 0)
1777 		/* TO- event */
1778 		switch (sp->state[cp->protoidx]) {
1779 		case STATE_CLOSING:
1780 			sppp_cp_change_state(cp, sp, STATE_CLOSED);
1781 			(cp->tlf)(sp);
1782 			break;
1783 		case STATE_STOPPING:
1784 			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1785 			(cp->tlf)(sp);
1786 			break;
1787 		case STATE_REQ_SENT:
1788 		case STATE_ACK_RCVD:
1789 		case STATE_ACK_SENT:
1790 			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1791 			(cp->tlf)(sp);
1792 			break;
1793 		}
1794 	else
1795 		/* TO+ event */
1796 		switch (sp->state[cp->protoidx]) {
1797 		case STATE_CLOSING:
1798 		case STATE_STOPPING:
1799 			sppp_cp_send(sp, cp->proto, TERM_REQ, ++sp->pp_seq,
1800 				     0, 0);
1801   			sppp_increasing_timeout (cp, sp);
1802 			break;
1803 		case STATE_REQ_SENT:
1804 		case STATE_ACK_RCVD:
1805 			/* sppp_cp_change_state() will restart the timer */
1806 			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1807 			(cp->scr)(sp);
1808 			break;
1809 		case STATE_ACK_SENT:
1810   			sppp_increasing_timeout (cp, sp);
1811 			(cp->scr)(sp);
1812 			break;
1813 		}
1814 
1815 	splx(s);
1816 }
1817 
1818 /*
1819  * Change the state of a control protocol in the state automaton.
1820  * Takes care of starting/stopping the restart timer.
1821  */
1822 void
1823 sppp_cp_change_state(const struct cp *cp, struct sppp *sp, int newstate)
1824 {
1825 	STDDCL;
1826 
1827 	if (debug && sp->state[cp->protoidx] != newstate)
1828 		log(LOG_DEBUG, SPP_FMT "%s %s->%s\n",
1829 		    SPP_ARGS(ifp), cp->name,
1830 		    sppp_state_name(sp->state[cp->protoidx]),
1831 		    sppp_state_name(newstate));
1832 	sp->state[cp->protoidx] = newstate;
1833 
1834 	UNTIMEOUT(cp->TO, (void *)sp, sp->ch[cp->protoidx]);
1835 	switch (newstate) {
1836 	case STATE_INITIAL:
1837 	case STATE_STARTING:
1838 	case STATE_CLOSED:
1839 	case STATE_STOPPED:
1840 	case STATE_OPENED:
1841 		break;
1842 	case STATE_CLOSING:
1843 	case STATE_STOPPING:
1844 	case STATE_REQ_SENT:
1845 	case STATE_ACK_RCVD:
1846 	case STATE_ACK_SENT:
1847  		sppp_increasing_timeout (cp, sp);
1848 		break;
1849 	}
1850 }
1851 /*
1852  *--------------------------------------------------------------------------*
1853  *                                                                          *
1854  *                         The LCP implementation.                          *
1855  *                                                                          *
1856  *--------------------------------------------------------------------------*
1857  */
1858 HIDE void
1859 sppp_lcp_init(struct sppp *sp)
1860 {
1861 	sp->lcp.opts = (1 << LCP_OPT_MAGIC);
1862 	sp->lcp.magic = 0;
1863 	sp->state[IDX_LCP] = STATE_INITIAL;
1864 	sp->fail_counter[IDX_LCP] = 0;
1865 	sp->lcp.protos = 0;
1866 	sp->lcp.mru = sp->lcp.their_mru = PP_MTU;
1867 
1868 	/*
1869 	 * Initialize counters and timeout values.  Note that we don't
1870 	 * use the 3 seconds suggested in RFC 1661 since we are likely
1871 	 * running on a fast link.  XXX We should probably implement
1872 	 * the exponential backoff option.  Note that these values are
1873 	 * relevant for all control protocols, not just LCP only.
1874 	 */
1875 	sp->lcp.timeout = 1 * hz;
1876 	sp->lcp.max_terminate = 2;
1877 	sp->lcp.max_configure = 10;
1878 	sp->lcp.max_failure = 10;
1879 #if defined (__FreeBSD__)
1880 	callout_handle_init(&sp->ch[IDX_LCP]);
1881 #endif
1882 }
1883 
1884 HIDE void
1885 sppp_lcp_up(struct sppp *sp)
1886 {
1887 	STDDCL;
1888 
1889  	sp->pp_alivecnt = 0;
1890  	sp->lcp.opts = (1 << LCP_OPT_MAGIC);
1891  	sp->lcp.magic = 0;
1892  	sp->lcp.protos = 0;
1893  	sp->lcp.mru = sp->lcp.their_mru = PP_MTU;
1894 	/*
1895 	 * If this interface is passive or dial-on-demand, and we are
1896 	 * still in Initial state, it means we've got an incoming
1897 	 * call.  Activate the interface.
1898 	 */
1899 	ifp->if_flags |= IFF_RUNNING;
1900 	if ((ifp->if_flags & (IFF_AUTO | IFF_PASSIVE)) != 0) {
1901 		if (debug)
1902 			log(LOG_DEBUG,
1903 			    SPP_FMT "Up event", SPP_ARGS(ifp));
1904 		if (sp->state[IDX_LCP] == STATE_INITIAL) {
1905 			if (debug)
1906 				addlog("(incoming call)\n");
1907 			sp->pp_flags |= PP_CALLIN;
1908 			lcp.Open(sp);
1909 		} else if (debug)
1910 			addlog("\n");
1911 	}
1912 
1913 	sppp_up_event(&lcp, sp);
1914 }
1915 
1916 HIDE void
1917 sppp_lcp_down(struct sppp *sp)
1918 {
1919 	STDDCL;
1920 
1921 		if (debug)
1922 		log(LOG_DEBUG, SPP_FMT "Down event (carrier loss)\n",
1923 			    SPP_ARGS(ifp));
1924   	sppp_down_event(&lcp, sp);
1925 
1926  	if ((ifp->if_flags & (IFF_AUTO | IFF_PASSIVE)) != 0)
1927 		lcp.Close(sp);
1928  	sp->pp_flags &= ~PP_CALLIN;
1929 	ifp->if_flags &= ~IFF_RUNNING;
1930  	sppp_flush(ifp);
1931 }
1932 
1933 HIDE void
1934 sppp_lcp_open(struct sppp *sp)
1935 {
1936 	/*
1937 	 * If we are authenticator, negotiate LCP_AUTH
1938 	 */
1939 	if (sp->hisauth.proto != 0)
1940 		sp->lcp.opts |= (1 << LCP_OPT_AUTH_PROTO);
1941 	else
1942 		sp->lcp.opts &= ~(1 << LCP_OPT_AUTH_PROTO);
1943 	sp->pp_flags &= ~PP_NEEDAUTH;
1944 	sppp_open_event(&lcp, sp);
1945 }
1946 
1947 HIDE void
1948 sppp_lcp_close(struct sppp *sp)
1949 {
1950 	sppp_close_event(&lcp, sp);
1951 }
1952 
1953 HIDE void
1954 sppp_lcp_TO(void *cookie)
1955 {
1956 	sppp_to_event(&lcp, (struct sppp *)cookie);
1957 }
1958 
1959 /*
1960  * Analyze a configure request.  Return true if it was agreeable, and
1961  * caused action sca, false if it has been rejected or nak'ed, and
1962  * caused action scn.  (The return value is used to make the state
1963  * transition decision in the state automaton.)
1964  */
1965 HIDE int
1966 sppp_lcp_RCR(struct sppp *sp, struct lcp_header *h, int len)
1967 {
1968 	STDDCL;
1969 	u_char *buf, *r, *p;
1970 	int origlen, rlen;
1971 	u_long nmagic;
1972 	u_short authproto;
1973 
1974 	len -= 4;
1975 	origlen = len;
1976 	buf = r = malloc (len, M_TEMP, M_NOWAIT);
1977 	if (! buf)
1978 		return (0);
1979 
1980 	if (debug)
1981 		log(LOG_DEBUG, SPP_FMT "lcp parse opts: ",
1982 		    SPP_ARGS(ifp));
1983 
1984 	/* pass 1: check for things that need to be rejected */
1985 	p = (void*) (h+1);
1986 	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
1987 		if (debug)
1988 			addlog("%s ", sppp_lcp_opt_name(*p));
1989 		switch (*p) {
1990 		case LCP_OPT_MAGIC:
1991 			/* Magic number. */
1992 			if (len >= 6 && p[1] == 6)
1993 				continue;
1994 			if (debug)
1995 				addlog("[invalid] ");
1996 			break;
1997 		case LCP_OPT_ASYNC_MAP:
1998 			/* Async control character map. */
1999 			if (len >= 6 && p[1] == 6)
2000 				continue;
2001 			if (debug)
2002 				addlog("[invalid] ");
2003 			break;
2004 		case LCP_OPT_MRU:
2005 			/* Maximum receive unit. */
2006 			if (len >= 4 && p[1] == 4)
2007 				continue;
2008 			if (debug)
2009 				addlog("[invalid] ");
2010 			break;
2011 		case LCP_OPT_AUTH_PROTO:
2012 			if (len < 4) {
2013 				if (debug)
2014 					addlog("[invalid] ");
2015 				break;
2016 			}
2017 			authproto = (p[2] << 8) + p[3];
2018 			if (authproto == PPP_CHAP && p[1] != 5) {
2019 				if (debug)
2020 					addlog("[invalid chap len] ");
2021 				break;
2022 			}
2023 			if (sp->myauth.proto == 0) {
2024 				/* we are not configured to do auth */
2025 				if (debug)
2026 					addlog("[not configured] ");
2027 				break;
2028 			}
2029 			/*
2030 			 * Remote want us to authenticate, remember this,
2031 			 * so we stay in PHASE_AUTHENTICATE after LCP got
2032 			 * up.
2033 			 */
2034 			sp->pp_flags |= PP_NEEDAUTH;
2035 			continue;
2036 		default:
2037 			/* Others not supported. */
2038 			if (debug)
2039 				addlog("[rej] ");
2040 			break;
2041 		}
2042 		/* Add the option to rejected list. */
2043 		bcopy (p, r, p[1]);
2044 		r += p[1];
2045 		rlen += p[1];
2046 	}
2047 	if (rlen) {
2048 		if (debug)
2049 			addlog(" send conf-rej\n");
2050 		sppp_cp_send (sp, PPP_LCP, CONF_REJ, h->ident, rlen, buf);
2051 		return 0;
2052 	} else if (debug)
2053 		addlog("\n");
2054 
2055 	/*
2056 	 * pass 2: check for option values that are unacceptable and
2057 	 * thus require to be nak'ed.
2058 	 */
2059 	if (debug)
2060 		log(LOG_DEBUG, SPP_FMT "lcp parse opt values: ",
2061 		    SPP_ARGS(ifp));
2062 
2063 	p = (void*) (h+1);
2064 	len = origlen;
2065 	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2066 		if (debug)
2067 			addlog("%s ", sppp_lcp_opt_name(*p));
2068 		switch (*p) {
2069 		case LCP_OPT_MAGIC:
2070 			/* Magic number -- extract. */
2071 			nmagic = (u_long)p[2] << 24 |
2072 				(u_long)p[3] << 16 | p[4] << 8 | p[5];
2073 			if (nmagic != sp->lcp.magic) {
2074 				if (debug)
2075 					addlog("0x%lx ", nmagic);
2076 				continue;
2077 			}
2078 			if (debug)
2079 				addlog("[glitch] ");
2080 			++sp->pp_loopcnt;
2081 			/*
2082 			 * We negate our magic here, and NAK it.  If
2083 			 * we see it later in an NAK packet, we
2084 			 * suggest a new one.
2085 			 */
2086 			nmagic = ~sp->lcp.magic;
2087 			/* Gonna NAK it. */
2088 			p[2] = nmagic >> 24;
2089 			p[3] = nmagic >> 16;
2090 			p[4] = nmagic >> 8;
2091 			p[5] = nmagic;
2092 			break;
2093 
2094 		case LCP_OPT_ASYNC_MAP:
2095 			/* Async control character map -- check to be zero. */
2096 			if (! p[2] && ! p[3] && ! p[4] && ! p[5]) {
2097 				if (debug)
2098 					addlog("[empty] ");
2099 				continue;
2100 			}
2101 			if (debug)
2102 				addlog("[non-empty] ");
2103 			/* suggest a zero one */
2104 			p[2] = p[3] = p[4] = p[5] = 0;
2105 			break;
2106 
2107 		case LCP_OPT_MRU:
2108 			/*
2109 			 * Maximum receive unit.  Always agreeable,
2110 			 * but ignored by now.
2111 			 */
2112 			sp->lcp.their_mru = p[2] * 256 + p[3];
2113 			if (debug)
2114 				addlog("%lu ", sp->lcp.their_mru);
2115 			continue;
2116 
2117 		case LCP_OPT_AUTH_PROTO:
2118 			authproto = (p[2] << 8) + p[3];
2119 			if (sp->myauth.proto != authproto) {
2120 				/* not agreed, nak */
2121 				if (debug)
2122 					addlog("[mine %s != his %s] ",
2123 					       sppp_proto_name(sp->hisauth.proto),
2124 					       sppp_proto_name(authproto));
2125 				p[2] = sp->myauth.proto >> 8;
2126 				p[3] = sp->myauth.proto;
2127 				break;
2128 			}
2129 			if (authproto == PPP_CHAP && p[4] != CHAP_MD5) {
2130 				if (debug)
2131 					addlog("[chap not MD5] ");
2132 				p[4] = CHAP_MD5;
2133 				break;
2134 			}
2135 			continue;
2136 		}
2137 		/* Add the option to nak'ed list. */
2138 		bcopy (p, r, p[1]);
2139 		r += p[1];
2140 		rlen += p[1];
2141 	}
2142 	if (rlen) {
2143 		if (++sp->fail_counter[IDX_LCP] < sp->lcp.max_failure) {
2144 			if (debug)
2145 				addlog("send conf-nak\n");
2146 			sppp_cp_send (sp, PPP_LCP, CONF_NAK, h->ident, rlen, buf);
2147 			return 0;
2148 		}
2149 		if (debug)
2150 			addlog("max_failure (%d) exceeded, closing\n",
2151 			       sp->lcp.max_failure);
2152 		if (sp->pp_loopcnt >= MAXALIVECNT)
2153 			printf (SPP_FMT "loopback\n", SPP_ARGS(ifp));
2154 		lcp.Close(sp);
2155 		sp->fail_counter[IDX_LCP] = 0;
2156 		sp->pp_loopcnt = 0;
2157 		return 0;
2158 	} else {
2159 		if (debug)
2160 			addlog("send conf-ack\n");
2161 		sp->fail_counter[IDX_LCP] = 0;
2162 		sp->pp_loopcnt = 0;
2163 		sppp_cp_send (sp, PPP_LCP, CONF_ACK,
2164 			      h->ident, origlen, h+1);
2165 	}
2166 
2167 	free (buf, M_TEMP);
2168 	return (rlen == 0);
2169 }
2170 
2171 /*
2172  * Analyze the LCP Configure-Reject option list, and adjust our
2173  * negotiation.
2174  */
2175 HIDE void
2176 sppp_lcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
2177 {
2178 	STDDCL;
2179 	u_char *buf, *p;
2180 
2181 	len -= 4;
2182 	buf = malloc (len, M_TEMP, M_NOWAIT);
2183 	if (!buf)
2184 		return;
2185 
2186 	if (debug)
2187 		log(LOG_DEBUG, SPP_FMT "lcp rej opts: ",
2188 		    SPP_ARGS(ifp));
2189 
2190 	p = (void*) (h+1);
2191 	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2192 		if (debug)
2193 			addlog("%s ", sppp_lcp_opt_name(*p));
2194 		switch (*p) {
2195 		case LCP_OPT_MAGIC:
2196 			/* Magic number -- can't use it, use 0 */
2197 			sp->lcp.opts &= ~(1 << LCP_OPT_MAGIC);
2198 			sp->lcp.magic = 0;
2199 			break;
2200 		case LCP_OPT_MRU:
2201 			/*
2202 			 * Should not be rejected anyway, since we only
2203 			 * negotiate a MRU if explicitly requested by
2204 			 * peer.
2205 			 */
2206 			sp->lcp.opts &= ~(1 << LCP_OPT_MRU);
2207 			break;
2208 		case LCP_OPT_AUTH_PROTO:
2209 			/*
2210 			 * Peer doesn't want to authenticate himself,
2211 			 * deny unless this is a dialout call, and
2212 			 * AUTHFLAG_NOCALLOUT is set.
2213 			 */
2214 			if ((sp->pp_flags & PP_CALLIN) == 0 &&
2215 			    (sp->hisauth.flags & AUTHFLAG_NOCALLOUT) != 0) {
2216 				if (debug)
2217 					addlog("[don't insist on auth "
2218 					       "for callout]");
2219 				sp->lcp.opts &= ~(1 << LCP_OPT_AUTH_PROTO);
2220 				break;
2221 			}
2222 			if (debug)
2223 				addlog("[access denied]\n");
2224 			lcp.Close(sp);
2225 			break;
2226 		}
2227 	}
2228 	if (debug)
2229 		addlog("\n");
2230 	free (buf, M_TEMP);
2231 	return;
2232 }
2233 
2234 /*
2235  * Analyze the LCP Configure-NAK option list, and adjust our
2236  * negotiation.
2237  */
2238 HIDE void
2239 sppp_lcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
2240 {
2241 	STDDCL;
2242 	u_char *buf, *p;
2243 	u_long magic;
2244 
2245 	len -= 4;
2246 	buf = malloc (len, M_TEMP, M_NOWAIT);
2247 	if (!buf)
2248 		return;
2249 
2250 	if (debug)
2251 		log(LOG_DEBUG, SPP_FMT "lcp nak opts: ",
2252 		    SPP_ARGS(ifp));
2253 
2254 	p = (void*) (h+1);
2255 	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2256 		if (debug)
2257 			addlog("%s ", sppp_lcp_opt_name(*p));
2258 		switch (*p) {
2259 		case LCP_OPT_MAGIC:
2260 			/* Magic number -- renegotiate */
2261 			if ((sp->lcp.opts & (1 << LCP_OPT_MAGIC)) &&
2262 			    len >= 6 && p[1] == 6) {
2263 				magic = (u_long)p[2] << 24 |
2264 					(u_long)p[3] << 16 | p[4] << 8 | p[5];
2265 				/*
2266 				 * If the remote magic is our negated one,
2267 				 * this looks like a loopback problem.
2268 				 * Suggest a new magic to make sure.
2269 				 */
2270 				if (magic == ~sp->lcp.magic) {
2271 					if (debug)
2272 						addlog("magic glitch ");
2273 #if defined (__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
2274 					sp->lcp.magic = random();
2275 #else
2276 					sp->lcp.magic = time.tv_sec + time.tv_usec;
2277 #endif
2278 				} else {
2279 					sp->lcp.magic = magic;
2280 					if (debug)
2281 						addlog("%lu ", magic);
2282 				}
2283 			}
2284 			break;
2285 		case LCP_OPT_MRU:
2286 			/*
2287 			 * Peer wants to advise us to negotiate an MRU.
2288 			 * Agree on it if it's reasonable, or use
2289 			 * default otherwise.
2290 			 */
2291 			if (len >= 4 && p[1] == 4) {
2292 				u_int mru = p[2] * 256 + p[3];
2293 				if (debug)
2294 					addlog("%d ", mru);
2295 				if (mru < PP_MTU || mru > PP_MAX_MRU)
2296 					mru = PP_MTU;
2297 				sp->lcp.mru = mru;
2298 				sp->lcp.opts |= (1 << LCP_OPT_MRU);
2299 			}
2300 			break;
2301 		case LCP_OPT_AUTH_PROTO:
2302 			/*
2303 			 * Peer doesn't like our authentication method,
2304 			 * deny.
2305 			 */
2306 			if (debug)
2307 				addlog("[access denied]\n");
2308 			lcp.Close(sp);
2309 			break;
2310 		}
2311 	}
2312 	if (debug)
2313 		addlog("\n");
2314 	free (buf, M_TEMP);
2315 	return;
2316 }
2317 
2318 HIDE void
2319 sppp_lcp_tlu(struct sppp *sp)
2320 {
2321 	struct ifnet *ifp = &sp->pp_if;
2322 	int i;
2323 	u_long mask;
2324 
2325 	/* XXX ? */
2326 	if (! (ifp->if_flags & IFF_UP) &&
2327 	    (ifp->if_flags & IFF_RUNNING)) {
2328 		/* Coming out of loopback mode. */
2329 		if_up(ifp);
2330 		printf (SPP_FMT "up\n", SPP_ARGS(ifp));
2331 	}
2332 
2333 	for (i = 0; i < IDX_COUNT; i++)
2334 		if ((cps[i])->flags & CP_QUAL)
2335 			(cps[i])->Open(sp);
2336 
2337 	if ((sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0 ||
2338 	    (sp->pp_flags & PP_NEEDAUTH) != 0)
2339 		sp->pp_phase = PHASE_AUTHENTICATE;
2340 	else
2341 		sp->pp_phase = PHASE_NETWORK;
2342 
2343 	log(LOG_INFO, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2344 	    sppp_phase_name(sp->pp_phase));
2345 
2346 	/*
2347 	 * Open all authentication protocols.  This is even required
2348 	 * if we already proceeded to network phase, since it might be
2349 	 * that remote wants us to authenticate, so we might have to
2350 	 * send a PAP request.  Undesired authentication protocols
2351 	 * don't do anything when they get an Open event.
2352 	 */
2353 	for (i = 0; i < IDX_COUNT; i++)
2354 		if ((cps[i])->flags & CP_AUTH)
2355 			(cps[i])->Open(sp);
2356 
2357 	if (sp->pp_phase == PHASE_NETWORK) {
2358 		/* Notify all NCPs. */
2359 		for (i = 0; i < IDX_COUNT; i++)
2360 			if ((cps[i])->flags & CP_NCP)
2361 				(cps[i])->Open(sp);
2362 	}
2363 
2364 	/* Send Up events to all started protos. */
2365 	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2366 		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_LCP) == 0)
2367 			(cps[i])->Up(sp);
2368 
2369 	if (sp->pp_phase == PHASE_NETWORK)
2370 		/* if no NCP is starting, close down */
2371 		sppp_lcp_check_and_close(sp);
2372 }
2373 
2374 HIDE void
2375 sppp_lcp_tld(struct sppp *sp)
2376 {
2377 	struct ifnet *ifp = &sp->pp_if;
2378 	int i;
2379 	u_long mask;
2380 
2381 	sp->pp_phase = PHASE_TERMINATE;
2382 
2383 	log(LOG_INFO, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2384 	    sppp_phase_name(sp->pp_phase));
2385 
2386 	/*
2387 	 * Take upper layers down.  We send the Down event first and
2388 	 * the Close second to prevent the upper layers from sending
2389 	 * ``a flurry of terminate-request packets'', as the RFC
2390 	 * describes it.
2391 	 */
2392 	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2393 		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_LCP) == 0) {
2394 			(cps[i])->Down(sp);
2395 			(cps[i])->Close(sp);
2396 		}
2397 }
2398 
2399 HIDE void
2400 sppp_lcp_tls(struct sppp *sp)
2401 {
2402 	struct ifnet *ifp = &sp->pp_if;
2403 
2404 	sp->pp_phase = PHASE_ESTABLISH;
2405 
2406 	log(LOG_INFO, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2407 	    sppp_phase_name(sp->pp_phase));
2408 
2409 	/* Notify lower layer if desired. */
2410 	if (sp->pp_tls)
2411 		(sp->pp_tls)(sp);
2412 }
2413 
2414 HIDE void
2415 sppp_lcp_tlf(struct sppp *sp)
2416 {
2417 	struct ifnet *ifp = &sp->pp_if;
2418 
2419 	sp->pp_phase = PHASE_DEAD;
2420 	log(LOG_INFO, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2421 	    sppp_phase_name(sp->pp_phase));
2422 
2423 	/* Notify lower layer if desired. */
2424 	if (sp->pp_tlf)
2425 		(sp->pp_tlf)(sp);
2426 }
2427 
2428 HIDE void
2429 sppp_lcp_scr(struct sppp *sp)
2430 {
2431 	char opt[6 /* magicnum */ + 4 /* mru */ + 5 /* chap */];
2432 	int i = 0;
2433 	u_short authproto;
2434 
2435 	if (sp->lcp.opts & (1 << LCP_OPT_MAGIC)) {
2436 		if (! sp->lcp.magic)
2437 #if defined (__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
2438 			sp->lcp.magic = random();
2439 #else
2440 			sp->lcp.magic = time.tv_sec + time.tv_usec;
2441 #endif
2442 		opt[i++] = LCP_OPT_MAGIC;
2443 		opt[i++] = 6;
2444 		opt[i++] = sp->lcp.magic >> 24;
2445 		opt[i++] = sp->lcp.magic >> 16;
2446 		opt[i++] = sp->lcp.magic >> 8;
2447 		opt[i++] = sp->lcp.magic;
2448 	}
2449 
2450 	if (sp->lcp.opts & (1 << LCP_OPT_MRU)) {
2451 		opt[i++] = LCP_OPT_MRU;
2452 		opt[i++] = 4;
2453 		opt[i++] = sp->lcp.mru >> 8;
2454 		opt[i++] = sp->lcp.mru;
2455 	}
2456 
2457 	if (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) {
2458 		authproto = sp->hisauth.proto;
2459 		opt[i++] = LCP_OPT_AUTH_PROTO;
2460 		opt[i++] = authproto == PPP_CHAP? 5: 4;
2461 		opt[i++] = authproto >> 8;
2462 		opt[i++] = authproto;
2463 		if (authproto == PPP_CHAP)
2464 			opt[i++] = CHAP_MD5;
2465 	}
2466 
2467 	sp->confid[IDX_LCP] = ++sp->pp_seq;
2468 	sppp_cp_send (sp, PPP_LCP, CONF_REQ, sp->confid[IDX_LCP], i, &opt);
2469 }
2470 
2471 /*
2472  * Check the open NCPs, return true if at least one NCP is open.
2473  */
2474 HIDE int
2475 sppp_ncp_check(struct sppp *sp)
2476 {
2477 	int i, mask;
2478 
2479 	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2480 		if (sp->lcp.protos & mask && (cps[i])->flags & CP_NCP)
2481 			return 1;
2482 	return 0;
2483 }
2484 
2485 /*
2486  * Re-check the open NCPs and see if we should terminate the link.
2487  * Called by the NCPs during their tlf action handling.
2488  */
2489 HIDE void
2490 sppp_lcp_check_and_close(struct sppp *sp)
2491 {
2492 
2493 	if (sp->pp_phase < PHASE_NETWORK)
2494 		/* don't bother, we are already going down */
2495 		return;
2496 
2497 	if (sppp_ncp_check(sp))
2498 		return;
2499 
2500 	lcp.Close(sp);
2501 }
2502 /*
2503  *--------------------------------------------------------------------------*
2504  *                                                                          *
2505  *                        The IPCP implementation.                          *
2506  *                                                                          *
2507  *--------------------------------------------------------------------------*
2508  */
2509 
2510 HIDE void
2511 sppp_ipcp_init(struct sppp *sp)
2512 {
2513 	sp->ipcp.opts = 0;
2514 	sp->ipcp.flags = 0;
2515 	sp->state[IDX_IPCP] = STATE_INITIAL;
2516 	sp->fail_counter[IDX_IPCP] = 0;
2517 #if defined (__FreeBSD__)
2518 	callout_handle_init(&sp->ch[IDX_IPCP]);
2519 #endif
2520 }
2521 
2522 HIDE void
2523 sppp_ipcp_up(struct sppp *sp)
2524 {
2525 	sppp_up_event(&ipcp, sp);
2526 }
2527 
2528 HIDE void
2529 sppp_ipcp_down(struct sppp *sp)
2530 {
2531 	sppp_down_event(&ipcp, sp);
2532 }
2533 
2534 HIDE void
2535 sppp_ipcp_open(struct sppp *sp)
2536 {
2537 	STDDCL;
2538 	u_long myaddr, hisaddr;
2539 
2540 	sppp_get_ip_addrs(sp, &myaddr, &hisaddr, 0);
2541 	/*
2542 	 * If we don't have his address, this probably means our
2543 	 * interface doesn't want to talk IP at all.  (This could
2544 	 * be the case if somebody wants to speak only IPX, for
2545 	 * example.)  Don't open IPCP in this case.
2546 	 */
2547 	if (hisaddr == 0L) {
2548 		/* XXX this message should go away */
2549 		if (debug)
2550 			log(LOG_DEBUG, SPP_FMT "ipcp_open(): no IP interface\n",
2551 			    SPP_ARGS(ifp));
2552 		return;
2553 	}
2554 
2555 	if (myaddr == 0L) {
2556 		/*
2557 		 * I don't have an assigned address, so i need to
2558 		 * negotiate my address.
2559 		 */
2560 		sp->ipcp.flags |= IPCP_MYADDR_DYN;
2561 		sp->ipcp.opts |= (1 << IPCP_OPT_ADDRESS);
2562 	}
2563 	sppp_open_event(&ipcp, sp);
2564 }
2565 
2566 HIDE void
2567 sppp_ipcp_close(struct sppp *sp)
2568 {
2569 	sppp_close_event(&ipcp, sp);
2570 	if (sp->ipcp.flags & IPCP_MYADDR_DYN)
2571 		/*
2572 		 * My address was dynamic, clear it again.
2573 		 */
2574 		sppp_set_ip_addr(sp, 0L);
2575 }
2576 
2577 HIDE void
2578 sppp_ipcp_TO(void *cookie)
2579 {
2580 	sppp_to_event(&ipcp, (struct sppp *)cookie);
2581 }
2582 
2583 /*
2584  * Analyze a configure request.  Return true if it was agreeable, and
2585  * caused action sca, false if it has been rejected or nak'ed, and
2586  * caused action scn.  (The return value is used to make the state
2587  * transition decision in the state automaton.)
2588  */
2589 HIDE int
2590 sppp_ipcp_RCR(struct sppp *sp, struct lcp_header *h, int len)
2591 {
2592 	u_char *buf, *r, *p;
2593 	struct ifnet *ifp = &sp->pp_if;
2594 	int rlen, origlen, debug = ifp->if_flags & IFF_DEBUG;
2595 	u_long hisaddr, desiredaddr;
2596 
2597 	len -= 4;
2598 	origlen = len;
2599 	/*
2600 	 * Make sure to allocate a buf that can at least hold a
2601 	 * conf-nak with an `address' option.  We might need it below.
2602 	 */
2603 	buf = r = malloc ((len < 6? 6: len), M_TEMP, M_NOWAIT);
2604 	if (! buf)
2605 		return (0);
2606 
2607 	/* pass 1: see if we can recognize them */
2608 	if (debug)
2609 		log(LOG_DEBUG, SPP_FMT "ipcp parse opts: ",
2610 		    SPP_ARGS(ifp));
2611 	p = (void*) (h+1);
2612 	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2613 		if (debug)
2614 			addlog("%s ", sppp_ipcp_opt_name(*p));
2615 		switch (*p) {
2616 #ifdef notyet
2617 		case IPCP_OPT_COMPRESSION:
2618 			if (len >= 6 && p[1] >= 6) {
2619 				/* correctly formed compress option */
2620 				continue;
2621 			}
2622 			if (debug)
2623 				addlog("[invalid] ");
2624 			break;
2625 #endif
2626 		case IPCP_OPT_ADDRESS:
2627 			if (len >= 6 && p[1] == 6) {
2628 				/* correctly formed address option */
2629 				continue;
2630 			}
2631 			if (debug)
2632 				addlog("[invalid] ");
2633 			break;
2634 		default:
2635 			/* Others not supported. */
2636 			if (debug)
2637 				addlog("[rej] ");
2638 			break;
2639 		}
2640 		/* Add the option to rejected list. */
2641 		bcopy (p, r, p[1]);
2642 		r += p[1];
2643 		rlen += p[1];
2644 	}
2645 	if (rlen) {
2646 		if (debug)
2647 			addlog(" send conf-rej\n");
2648 		sppp_cp_send (sp, PPP_IPCP, CONF_REJ, h->ident, rlen, buf);
2649 		return 0;
2650 	} else if (debug)
2651 		addlog("\n");
2652 
2653 	/* pass 2: parse option values */
2654 	sppp_get_ip_addrs(sp, 0, &hisaddr, 0);
2655 	if (debug)
2656 		log(LOG_DEBUG, SPP_FMT "ipcp parse opt values: ",
2657 		       SPP_ARGS(ifp));
2658 	p = (void*) (h+1);
2659 	len = origlen;
2660 	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2661 		if (debug)
2662 			addlog(" %s ", sppp_ipcp_opt_name(*p));
2663 		switch (*p) {
2664 #ifdef notyet
2665 		case IPCP_OPT_COMPRESSION:
2666 			continue;
2667 #endif
2668 		case IPCP_OPT_ADDRESS:
2669 			desiredaddr = p[2] << 24 | p[3] << 16 |
2670 				p[4] << 8 | p[5];
2671 			if (desiredaddr == hisaddr ||
2672 			    (hisaddr == 1 && desiredaddr != 0)) {
2673 				/*
2674 				 * Peer's address is same as our value,
2675 				 * or we have set it to 0.0.0.1 to
2676 				 * indicate that we do not really care,
2677 				 * this is agreeable.  Gonna conf-ack
2678 				 * it.
2679 				 */
2680 				if (debug)
2681 					addlog("%s [ack] ",
2682 					       sppp_dotted_quad(desiredaddr));
2683 				/* record that we've seen it already */
2684 				sp->ipcp.flags |= IPCP_HISADDR_SEEN;
2685 				continue;
2686 			}
2687 			/*
2688 			 * The address wasn't agreeable.  This is either
2689 			 * he sent us 0.0.0.0, asking to assign him an
2690 			 * address, or he send us another address not
2691 			 * matching our value.  Either case, we gonna
2692 			 * conf-nak it with our value.
2693 			 */
2694 			if (debug) {
2695 				if (desiredaddr == 0)
2696 					addlog("[addr requested] ");
2697 				else
2698 					addlog("%s [not agreed] ",
2699 					       sppp_dotted_quad(desiredaddr));
2700 
2701 				p[2] = hisaddr >> 24;
2702 				p[3] = hisaddr >> 16;
2703 				p[4] = hisaddr >> 8;
2704 				p[5] = hisaddr;
2705 			}
2706 			break;
2707 		}
2708 		/* Add the option to nak'ed list. */
2709 		bcopy (p, r, p[1]);
2710 		r += p[1];
2711 		rlen += p[1];
2712 	}
2713 
2714 	/*
2715 	 * If we are about to conf-ack the request, but haven't seen
2716 	 * his address so far, gonna conf-nak it instead, with the
2717 	 * `address' option present and our idea of his address being
2718 	 * filled in there, to request negotiation of both addresses.
2719 	 *
2720 	 * XXX This can result in an endless req - nak loop if peer
2721 	 * doesn't want to send us his address.  Q: What should we do
2722 	 * about it?  XXX  A: implement the max-failure counter.
2723 	 */
2724 	if (rlen == 0 && !(sp->ipcp.flags & IPCP_HISADDR_SEEN)) {
2725 		buf[0] = IPCP_OPT_ADDRESS;
2726 		buf[1] = 6;
2727 		buf[2] = hisaddr >> 24;
2728 		buf[3] = hisaddr >> 16;
2729 		buf[4] = hisaddr >> 8;
2730 		buf[5] = hisaddr;
2731 		rlen = 6;
2732 		if (debug)
2733 			addlog("still need hisaddr ");
2734 	}
2735 
2736 	if (rlen) {
2737 		if (debug)
2738 			addlog(" send conf-nak\n");
2739 		sppp_cp_send (sp, PPP_IPCP, CONF_NAK, h->ident, rlen, buf);
2740 	} else {
2741 		if (debug)
2742 			addlog(" send conf-ack\n");
2743 		sppp_cp_send (sp, PPP_IPCP, CONF_ACK,
2744 			      h->ident, origlen, h+1);
2745 	}
2746 
2747 	free (buf, M_TEMP);
2748 	return (rlen == 0);
2749 }
2750 
2751 /*
2752  * Analyze the IPCP Configure-Reject option list, and adjust our
2753  * negotiation.
2754  */
2755 HIDE void
2756 sppp_ipcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
2757 {
2758 	u_char *buf, *p;
2759 	struct ifnet *ifp = &sp->pp_if;
2760 	int debug = ifp->if_flags & IFF_DEBUG;
2761 
2762 	len -= 4;
2763 	buf = malloc (len, M_TEMP, M_NOWAIT);
2764 	if (!buf)
2765 		return;
2766 
2767 	if (debug)
2768 		log(LOG_DEBUG, SPP_FMT "ipcp rej opts: ",
2769 		    SPP_ARGS(ifp));
2770 
2771 	p = (void*) (h+1);
2772 	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2773 		if (debug)
2774 			addlog("%s ", sppp_ipcp_opt_name(*p));
2775 		switch (*p) {
2776 		case IPCP_OPT_ADDRESS:
2777 			/*
2778 			 * Peer doesn't grok address option.  This is
2779 			 * bad.  XXX  Should we better give up here?
2780 			 */
2781 			sp->ipcp.opts &= ~(1 << IPCP_OPT_ADDRESS);
2782 			break;
2783 #ifdef notyet
2784 		case IPCP_OPT_COMPRESS:
2785 			sp->ipcp.opts &= ~(1 << IPCP_OPT_COMPRESS);
2786 			break;
2787 #endif
2788 		}
2789 	}
2790 	if (debug)
2791 		addlog("\n");
2792 	free (buf, M_TEMP);
2793 	return;
2794 }
2795 
2796 /*
2797  * Analyze the IPCP Configure-NAK option list, and adjust our
2798  * negotiation.
2799  */
2800 HIDE void
2801 sppp_ipcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
2802 {
2803 	u_char *buf, *p;
2804 	struct ifnet *ifp = &sp->pp_if;
2805 	int debug = ifp->if_flags & IFF_DEBUG;
2806 	u_long wantaddr;
2807 
2808 	len -= 4;
2809 	buf = malloc (len, M_TEMP, M_NOWAIT);
2810 	if (!buf)
2811 		return;
2812 
2813 	if (debug)
2814 		log(LOG_DEBUG, SPP_FMT "ipcp nak opts: ",
2815 		    SPP_ARGS(ifp));
2816 
2817 	p = (void*) (h+1);
2818 	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2819 		if (debug)
2820 			addlog("%s ", sppp_ipcp_opt_name(*p));
2821 		switch (*p) {
2822 		case IPCP_OPT_ADDRESS:
2823 			/*
2824 			 * Peer doesn't like our local IP address.  See
2825 			 * if we can do something for him.  We'll drop
2826 			 * him our address then.
2827 			 */
2828 			if (len >= 6 && p[1] == 6) {
2829 				wantaddr = p[2] << 24 | p[3] << 16 |
2830 					p[4] << 8 | p[5];
2831 				sp->ipcp.opts |= (1 << IPCP_OPT_ADDRESS);
2832 				if (debug)
2833 					addlog("[wantaddr %s] ",
2834 					       sppp_dotted_quad(wantaddr));
2835 				/*
2836 				 * When doing dynamic address assignment,
2837 				 * we accept his offer.  Otherwise, we
2838 				 * ignore it and thus continue to negotiate
2839 				 * our already existing value.
2840 				 */
2841 				if (sp->ipcp.flags & IPCP_MYADDR_DYN) {
2842 					sppp_set_ip_addr(sp, wantaddr);
2843 					if (debug)
2844 						addlog("[agree] ");
2845 				}
2846 			}
2847 			break;
2848 #ifdef notyet
2849 		case IPCP_OPT_COMPRESS:
2850 			/*
2851 			 * Peer wants different compression parameters.
2852 			 */
2853 			break;
2854 #endif
2855 		}
2856 	}
2857 	if (debug)
2858 		addlog("\n");
2859 	free (buf, M_TEMP);
2860 	return;
2861 }
2862 
2863 HIDE void
2864 sppp_ipcp_tlu(struct sppp *sp)
2865 {
2866 }
2867 
2868 HIDE void
2869 sppp_ipcp_tld(struct sppp *sp)
2870 {
2871 }
2872 
2873 HIDE void
2874 sppp_ipcp_tls(struct sppp *sp)
2875 {
2876 	/* indicate to LCP that it must stay alive */
2877 	sp->lcp.protos |= (1 << IDX_IPCP);
2878 }
2879 
2880 HIDE void
2881 sppp_ipcp_tlf(struct sppp *sp)
2882 {
2883 	/* we no longer need LCP */
2884 	sp->lcp.protos &= ~(1 << IDX_IPCP);
2885 	sppp_lcp_check_and_close(sp);
2886 }
2887 
2888 HIDE void
2889 sppp_ipcp_scr(struct sppp *sp)
2890 {
2891 	char opt[6 /* compression */ + 6 /* address */];
2892 	u_long ouraddr;
2893 	int i = 0;
2894 
2895 #ifdef notyet
2896 	if (sp->ipcp.opts & (1 << IPCP_OPT_COMPRESSION)) {
2897 		opt[i++] = IPCP_OPT_COMPRESSION;
2898 		opt[i++] = 6;
2899 		opt[i++] = 0;	/* VJ header compression */
2900 		opt[i++] = 0x2d; /* VJ header compression */
2901 		opt[i++] = max_slot_id;
2902 		opt[i++] = comp_slot_id;
2903 	}
2904 #endif
2905 
2906 	if (sp->ipcp.opts & (1 << IPCP_OPT_ADDRESS)) {
2907 		sppp_get_ip_addrs(sp, &ouraddr, 0, 0);
2908 		opt[i++] = IPCP_OPT_ADDRESS;
2909 		opt[i++] = 6;
2910 		opt[i++] = ouraddr >> 24;
2911 		opt[i++] = ouraddr >> 16;
2912 		opt[i++] = ouraddr >> 8;
2913 		opt[i++] = ouraddr;
2914 	}
2915 
2916 	sp->confid[IDX_IPCP] = ++sp->pp_seq;
2917 	sppp_cp_send(sp, PPP_IPCP, CONF_REQ, sp->confid[IDX_IPCP], i, &opt);
2918 }
2919 
2920 
2921 /*
2922  *--------------------------------------------------------------------------*
2923  *                                                                          *
2924  *                        The CHAP implementation.                          *
2925  *                                                                          *
2926  *--------------------------------------------------------------------------*
2927  */
2928 
2929 /*
2930  * The authentication protocols don't employ a full-fledged state machine as
2931  * the control protocols do, since they do have Open and Close events, but
2932  * not Up and Down, nor are they explicitly terminated.  Also, use of the
2933  * authentication protocols may be different in both directions (this makes
2934  * sense, think of a machine that never accepts incoming calls but only
2935  * calls out, it doesn't require the called party to authenticate itself).
2936  *
2937  * Our state machine for the local authentication protocol (we are requesting
2938  * the peer to authenticate) looks like:
2939  *
2940  *						    RCA-
2941  *	      +--------------------------------------------+
2942  *	      V					    scn,tld|
2943  *	  +--------+			       Close   +---------+ RCA+
2944  *	  |	   |<----------------------------------|	 |------+
2945  *   +--->| Closed |				TO*    | Opened	 | sca	|
2946  *   |	  |	   |-----+		       +-------|	 |<-----+
2947  *   |	  +--------+ irc |		       |       +---------+
2948  *   |	    ^		 |		       |	   ^
2949  *   |	    |		 |		       |	   |
2950  *   |	    |		 |		       |	   |
2951  *   |	 TO-|		 |		       |	   |
2952  *   |	    |tld  TO+	 V		       |	   |
2953  *   |	    |	+------->+		       |	   |
2954  *   |	    |	|	 |		       |	   |
2955  *   |	  +--------+	 V		       |	   |
2956  *   |	  |	   |<----+<--------------------+	   |
2957  *   |	  | Req-   | scr				   |
2958  *   |	  | Sent   |					   |
2959  *   |	  |	   |					   |
2960  *   |	  +--------+					   |
2961  *   | RCA- |	| RCA+					   |
2962  *   +------+	+------------------------------------------+
2963  *   scn,tld	  sca,irc,ict,tlu
2964  *
2965  *
2966  *   with:
2967  *
2968  *	Open:	LCP reached authentication phase
2969  *	Close:	LCP reached terminate phase
2970  *
2971  *	RCA+:	received reply (pap-req, chap-response), acceptable
2972  *	RCN:	received reply (pap-req, chap-response), not acceptable
2973  *	TO+:	timeout with restart counter >= 0
2974  *	TO-:	timeout with restart counter < 0
2975  *	TO*:	reschedule timeout for CHAP
2976  *
2977  *	scr:	send request packet (none for PAP, chap-challenge)
2978  *	sca:	send ack packet (pap-ack, chap-success)
2979  *	scn:	send nak packet (pap-nak, chap-failure)
2980  *	ict:	initialize re-challenge timer (CHAP only)
2981  *
2982  *	tlu:	this-layer-up, LCP reaches network phase
2983  *	tld:	this-layer-down, LCP enters terminate phase
2984  *
2985  * Note that in CHAP mode, after sending a new challenge, while the state
2986  * automaton falls back into Req-Sent state, it doesn't signal a tld
2987  * event to LCP, so LCP remains in network phase.  Only after not getting
2988  * any response (or after getting an unacceptable response), CHAP closes,
2989  * causing LCP to enter terminate phase.
2990  *
2991  * With PAP, there is no initial request that can be sent.  The peer is
2992  * expected to send one based on the successful negotiation of PAP as
2993  * the authentication protocol during the LCP option negotiation.
2994  *
2995  * Incoming authentication protocol requests (remote requests
2996  * authentication, we are peer) don't employ a state machine at all,
2997  * they are simply answered.  Some peers [Ascend P50 firmware rev
2998  * 4.50] react allergically when sending IPCP requests while they are
2999  * still in authentication phase (thereby violating the standard that
3000  * demands that these NCP packets are to be discarded), so we keep
3001  * track of the peer demanding us to authenticate, and only proceed to
3002  * phase network once we've seen a positive acknowledge for the
3003  * authentication.
3004  */
3005 
3006 /*
3007  * Handle incoming CHAP packets.
3008  */
3009 void
3010 sppp_chap_input(struct sppp *sp, struct mbuf *m)
3011 {
3012 	STDDCL;
3013 	struct lcp_header *h;
3014 	int len, x;
3015 	u_char *value, *name, digest[AUTHKEYLEN], dsize;
3016 	int value_len, name_len;
3017 	MD5_CTX ctx;
3018 
3019 	len = m->m_pkthdr.len;
3020 	if (len < 4) {
3021 		if (debug)
3022 			log(LOG_DEBUG,
3023 			    SPP_FMT "chap invalid packet length: %d bytes\n",
3024 			    SPP_ARGS(ifp), len);
3025 		return;
3026 	}
3027 	h = mtod (m, struct lcp_header*);
3028 	if (len > ntohs (h->len))
3029 		len = ntohs (h->len);
3030 
3031 	switch (h->type) {
3032 	/* challenge, failure and success are his authproto */
3033 	case CHAP_CHALLENGE:
3034 		value = 1 + (u_char*)(h+1);
3035 		value_len = value[-1];
3036 		name = value + value_len;
3037 		name_len = len - value_len - 5;
3038 		if (name_len < 0) {
3039 			if (debug) {
3040 				log(LOG_DEBUG,
3041 				    SPP_FMT "chap corrupted challenge "
3042 				    "<%s id=0x%x len=%d",
3043 				    SPP_ARGS(ifp),
3044 				    sppp_auth_type_name(PPP_CHAP, h->type),
3045 				    h->ident, ntohs(h->len));
3046 				if (len > 4)
3047 					sppp_print_bytes((u_char*) (h+1), len-4);
3048 				addlog(">\n");
3049 			}
3050 			break;
3051 		}
3052 
3053 		if (debug) {
3054 			log(LOG_DEBUG,
3055 			    SPP_FMT "chap input <%s id=0x%x len=%d name=",
3056 			    SPP_ARGS(ifp),
3057 			    sppp_auth_type_name(PPP_CHAP, h->type), h->ident,
3058 			    ntohs(h->len));
3059 			sppp_print_string((char*) name, name_len);
3060 			addlog(" value-size=%d value=", value_len);
3061 			sppp_print_bytes(value, value_len);
3062 			addlog(">\n");
3063 		}
3064 
3065 		/* Compute reply value. */
3066 		MD5Init(&ctx);
3067 		MD5Update(&ctx, &h->ident, 1);
3068 		MD5Update(&ctx, sp->myauth.secret,
3069 			  sppp_strnlen(sp->myauth.secret, AUTHKEYLEN));
3070 		MD5Update(&ctx, value, value_len);
3071 		MD5Final(digest, &ctx);
3072 		dsize = sizeof digest;
3073 
3074 		sppp_auth_send(&chap, sp, CHAP_RESPONSE, h->ident,
3075 			       sizeof dsize, (const char *)&dsize,
3076 			       sizeof digest, digest,
3077 			       (size_t)sppp_strnlen(sp->myauth.name, AUTHNAMELEN),
3078 			       sp->myauth.name,
3079 			       0);
3080 		break;
3081 
3082 	case CHAP_SUCCESS:
3083 		if (debug) {
3084 			log(LOG_DEBUG, SPP_FMT "chap success",
3085 			    SPP_ARGS(ifp));
3086 			if (len > 4) {
3087 				addlog(": ");
3088 				sppp_print_string((char*)(h + 1), len - 4);
3089 			}
3090 			addlog("\n");
3091 		}
3092 		x = splimp();
3093 		sp->pp_flags &= ~PP_NEEDAUTH;
3094 		if (sp->myauth.proto == PPP_CHAP &&
3095 		    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) &&
3096 		    (sp->lcp.protos & (1 << IDX_CHAP)) == 0) {
3097 			/*
3098 			 * We are authenticator for CHAP but didn't
3099 			 * complete yet.  Leave it to tlu to proceed
3100 			 * to network phase.
3101 			 */
3102 			splx(x);
3103 			break;
3104 		}
3105 		splx(x);
3106 		sppp_phase_network(sp);
3107 		break;
3108 
3109 	case CHAP_FAILURE:
3110 		if (debug) {
3111 			log(LOG_INFO, SPP_FMT "chap failure",
3112 			    SPP_ARGS(ifp));
3113 			if (len > 4) {
3114 				addlog(": ");
3115 				sppp_print_string((char*)(h + 1), len - 4);
3116 			}
3117 			addlog("\n");
3118 		} else
3119 			log(LOG_INFO, SPP_FMT "chap failure\n",
3120 			    SPP_ARGS(ifp));
3121 		/* await LCP shutdown by authenticator */
3122 		break;
3123 
3124 	/* response is my authproto */
3125 	case CHAP_RESPONSE:
3126 		value = 1 + (u_char*)(h+1);
3127 		value_len = value[-1];
3128 		name = value + value_len;
3129 		name_len = len - value_len - 5;
3130 		if (name_len < 0) {
3131 			if (debug) {
3132 				log(LOG_DEBUG,
3133 				    SPP_FMT "chap corrupted response "
3134 				    "<%s id=0x%x len=%d",
3135 				    SPP_ARGS(ifp),
3136 				    sppp_auth_type_name(PPP_CHAP, h->type),
3137 				    h->ident, ntohs(h->len));
3138 				if (len > 4)
3139 					sppp_print_bytes((u_char*)(h+1), len-4);
3140 				addlog(">\n");
3141 			}
3142 			break;
3143 		}
3144 		if (h->ident != sp->confid[IDX_CHAP]) {
3145 			if (debug)
3146 				log(LOG_DEBUG,
3147 				    SPP_FMT "chap dropping response for old ID "
3148 				    "(got %d, expected %d)\n",
3149 				    SPP_ARGS(ifp),
3150 				    h->ident, sp->confid[IDX_CHAP]);
3151 			break;
3152 		}
3153 		if (name_len != sppp_strnlen(sp->hisauth.name, AUTHNAMELEN)
3154 		    || bcmp(name, sp->hisauth.name, name_len) != 0) {
3155 			log(LOG_INFO, SPP_FMT "chap response, his name ",
3156 			    SPP_ARGS(ifp));
3157 			sppp_print_string(name, name_len);
3158 			addlog(" != expected ");
3159 			sppp_print_string(sp->hisauth.name,
3160 					  sppp_strnlen(sp->hisauth.name, AUTHNAMELEN));
3161 			addlog("\n");
3162 		}
3163 		if (debug) {
3164 			log(LOG_DEBUG, SPP_FMT "chap input(%s) "
3165 			    "<%s id=0x%x len=%d name=",
3166 			    SPP_ARGS(ifp),
3167 			    sppp_state_name(sp->state[IDX_CHAP]),
3168 			    sppp_auth_type_name(PPP_CHAP, h->type),
3169 			    h->ident, ntohs (h->len));
3170 			sppp_print_string((char*)name, name_len);
3171 			addlog(" value-size=%d value=", value_len);
3172 			sppp_print_bytes(value, value_len);
3173 			addlog(">\n");
3174 		}
3175 		if (value_len != AUTHKEYLEN) {
3176 			if (debug)
3177 				log(LOG_DEBUG,
3178 				    SPP_FMT "chap bad hash value length: "
3179 				    "%d bytes, should be %d\n",
3180 				    SPP_ARGS(ifp), value_len,
3181 				    AUTHKEYLEN);
3182 			break;
3183 		}
3184 
3185 		MD5Init(&ctx);
3186 		MD5Update(&ctx, &h->ident, 1);
3187 		MD5Update(&ctx, sp->hisauth.secret,
3188 			  sppp_strnlen(sp->hisauth.secret, AUTHKEYLEN));
3189 		MD5Update(&ctx, sp->myauth.challenge, AUTHKEYLEN);
3190 		MD5Final(digest, &ctx);
3191 
3192 #define FAILMSG "Failed..."
3193 #define SUCCMSG "Welcome!"
3194 
3195 		if (value_len != sizeof digest ||
3196 		    bcmp(digest, value, value_len) != 0) {
3197 			/* action scn, tld */
3198 			sppp_auth_send(&chap, sp, CHAP_FAILURE, h->ident,
3199 				       sizeof(FAILMSG) - 1, (u_char *)FAILMSG,
3200 				       0);
3201 			chap.tld(sp);
3202 			break;
3203 		}
3204 		/* action sca, perhaps tlu */
3205 		if (sp->state[IDX_CHAP] == STATE_REQ_SENT ||
3206 		    sp->state[IDX_CHAP] == STATE_OPENED)
3207 			sppp_auth_send(&chap, sp, CHAP_SUCCESS, h->ident,
3208 				       sizeof(SUCCMSG) - 1, (u_char *)SUCCMSG,
3209 				       0);
3210 		if (sp->state[IDX_CHAP] == STATE_REQ_SENT) {
3211 			sppp_cp_change_state(&chap, sp, STATE_OPENED);
3212 			chap.tlu(sp);
3213 		}
3214 		break;
3215 
3216 	default:
3217 		/* Unknown CHAP packet type -- ignore. */
3218 		if (debug) {
3219 			log(LOG_DEBUG, SPP_FMT "chap unknown input(%s) "
3220 			    "<0x%x id=0x%xh len=%d",
3221 			    SPP_ARGS(ifp),
3222 			    sppp_state_name(sp->state[IDX_CHAP]),
3223 			    h->type, h->ident, ntohs(h->len));
3224 			if (len > 4)
3225 				sppp_print_bytes((u_char*)(h+1), len-4);
3226 			addlog(">\n");
3227 		}
3228 		break;
3229 
3230 	}
3231 }
3232 
3233 HIDE void
3234 sppp_chap_init(struct sppp *sp)
3235 {
3236 	/* Chap doesn't have STATE_INITIAL at all. */
3237 	sp->state[IDX_CHAP] = STATE_CLOSED;
3238 	sp->fail_counter[IDX_CHAP] = 0;
3239 #if defined (__FreeBSD__)
3240 	callout_handle_init(&sp->ch[IDX_CHAP]);
3241 #endif
3242 }
3243 
3244 HIDE void
3245 sppp_chap_open(struct sppp *sp)
3246 {
3247 	if (sp->myauth.proto == PPP_CHAP &&
3248 	    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0) {
3249 		/* we are authenticator for CHAP, start it */
3250 		chap.scr(sp);
3251 		sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3252 		sppp_cp_change_state(&chap, sp, STATE_REQ_SENT);
3253 	}
3254 	/* nothing to be done if we are peer, await a challenge */
3255 }
3256 
3257 HIDE void
3258 sppp_chap_close(struct sppp *sp)
3259 {
3260 	if (sp->state[IDX_CHAP] != STATE_CLOSED)
3261 		sppp_cp_change_state(&chap, sp, STATE_CLOSED);
3262 }
3263 
3264 HIDE void
3265 sppp_chap_TO(void *cookie)
3266 {
3267 	struct sppp *sp = (struct sppp *)cookie;
3268 	STDDCL;
3269 	int s;
3270 
3271 	s = splimp();
3272 	if (debug)
3273 		log(LOG_DEBUG, SPP_FMT "chap TO(%s) rst_counter = %d\n",
3274 		    SPP_ARGS(ifp),
3275 		    sppp_state_name(sp->state[IDX_CHAP]),
3276 		    sp->rst_counter[IDX_CHAP]);
3277 
3278 	if (--sp->rst_counter[IDX_CHAP] < 0)
3279 		/* TO- event */
3280 		switch (sp->state[IDX_CHAP]) {
3281 		case STATE_REQ_SENT:
3282 			chap.tld(sp);
3283 			sppp_cp_change_state(&chap, sp, STATE_CLOSED);
3284 			break;
3285 		}
3286 	else
3287 		/* TO+ (or TO*) event */
3288 		switch (sp->state[IDX_CHAP]) {
3289 		case STATE_OPENED:
3290 			/* TO* event */
3291 			sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3292 			/* fall through */
3293 		case STATE_REQ_SENT:
3294 			chap.scr(sp);
3295 			/* sppp_cp_change_state() will restart the timer */
3296 			sppp_cp_change_state(&chap, sp, STATE_REQ_SENT);
3297 			break;
3298 		}
3299 
3300 	splx(s);
3301 }
3302 
3303 HIDE void
3304 sppp_chap_tlu(struct sppp *sp)
3305 {
3306 	STDDCL;
3307 	int i = 0, x;
3308 
3309 	i = 0;
3310 	sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3311 
3312 	/*
3313 	 * Some broken CHAP implementations (Conware CoNet, firmware
3314 	 * 4.0.?) don't want to re-authenticate their CHAP once the
3315 	 * initial challenge-response exchange has taken place.
3316 	 * Provide for an option to avoid rechallenges.
3317 	 */
3318 	if ((sp->hisauth.flags & AUTHFLAG_NORECHALLENGE) == 0) {
3319 		/*
3320 		 * Compute the re-challenge timeout.  This will yield
3321 		 * a number between 300 and 810 seconds.
3322 		 */
3323 		i = 300 + ((unsigned)(random() & 0xff00) >> 7);
3324 
3325 #if defined (__FreeBSD__)
3326 		sp->ch[IDX_CHAP] = timeout(chap.TO, (void *)sp, i * hz);
3327 #elif defined(__OpenBSD__)
3328 		timeout_set(&sp->ch[IDX_CHAP], chap.TO, (void *)sp);
3329 		timeout_add(&sp->ch[IDX_CHAP], i * hz);
3330 #endif
3331 	}
3332 
3333 	if (debug) {
3334 		log(LOG_DEBUG,
3335 		    SPP_FMT "chap %s, ",
3336 		    SPP_ARGS(ifp),
3337 		    sp->pp_phase == PHASE_NETWORK? "reconfirmed": "tlu");
3338 		if ((sp->hisauth.flags & AUTHFLAG_NORECHALLENGE) == 0)
3339 			addlog("next re-challenge in %d seconds\n", i);
3340 		else
3341 			addlog("re-challenging supressed\n");
3342 	}
3343 
3344 	x = splimp();
3345 	/* indicate to LCP that we need to be closed down */
3346 	sp->lcp.protos |= (1 << IDX_CHAP);
3347 
3348 	if (sp->pp_flags & PP_NEEDAUTH) {
3349 		/*
3350 		 * Remote is authenticator, but his auth proto didn't
3351 		 * complete yet.  Defer the transition to network
3352 		 * phase.
3353 		 */
3354 		splx(x);
3355 		return;
3356 	}
3357 	splx(x);
3358 
3359 	/*
3360 	 * If we are already in phase network, we are done here.  This
3361 	 * is the case if this is a dummy tlu event after a re-challenge.
3362 	 */
3363 	if (sp->pp_phase != PHASE_NETWORK)
3364 		sppp_phase_network(sp);
3365 }
3366 
3367 HIDE void
3368 sppp_chap_tld(struct sppp *sp)
3369 {
3370 	STDDCL;
3371 
3372 	if (debug)
3373 		log(LOG_DEBUG, SPP_FMT "chap tld\n", SPP_ARGS(ifp));
3374 	UNTIMEOUT(chap.TO, (void *)sp, sp->ch[IDX_CHAP]);
3375 	sp->lcp.protos &= ~(1 << IDX_CHAP);
3376 
3377 	lcp.Close(sp);
3378 }
3379 
3380 HIDE void
3381 sppp_chap_scr(struct sppp *sp)
3382 {
3383 	u_long *ch, seed;
3384 	u_char clen;
3385 #if defined (__NetBSD__) || defined (__OpenBSD__)
3386 	struct timeval tv;
3387 #endif
3388 
3389 	/* Compute random challenge. */
3390 	ch = (u_long *)sp->myauth.challenge;
3391 #if defined (__FreeBSD__)
3392 	read_random(&seed, sizeof seed);
3393 #else
3394 	microtime(&tv);
3395 	seed = tv.tv_sec ^ tv.tv_usec;
3396 #endif
3397 	ch[0] = seed ^ random();
3398 	ch[1] = seed ^ random();
3399 	ch[2] = seed ^ random();
3400 	ch[3] = seed ^ random();
3401 	clen = AUTHKEYLEN;
3402 
3403 	sp->confid[IDX_CHAP] = ++sp->pp_seq;
3404 
3405 	sppp_auth_send(&chap, sp, CHAP_CHALLENGE, sp->confid[IDX_CHAP],
3406 		       sizeof clen, (const char *)&clen,
3407 		       (size_t)AUTHKEYLEN, sp->myauth.challenge,
3408 		       (size_t)sppp_strnlen(sp->myauth.name, AUTHNAMELEN),
3409 		       sp->myauth.name,
3410 		       0);
3411 }
3412 /*
3413  *--------------------------------------------------------------------------*
3414  *                                                                          *
3415  *                        The PAP implementation.                           *
3416  *                                                                          *
3417  *--------------------------------------------------------------------------*
3418  */
3419 /*
3420  * For PAP, we need to keep a little state also if we are the peer, not the
3421  * authenticator.  This is since we don't get a request to authenticate, but
3422  * have to repeatedly authenticate ourself until we got a response (or the
3423  * retry counter is expired).
3424  */
3425 
3426 /*
3427  * Handle incoming PAP packets.  */
3428 HIDE void
3429 sppp_pap_input(struct sppp *sp, struct mbuf *m)
3430 {
3431 	STDDCL;
3432 	struct lcp_header *h;
3433 	int len, x;
3434 	u_char *name, *passwd, mlen;
3435 	int name_len, passwd_len;
3436 
3437 	len = m->m_pkthdr.len;
3438 	if (len < 5) {
3439 		if (debug)
3440 			log(LOG_DEBUG,
3441 			    SPP_FMT "pap invalid packet length: %d bytes\n",
3442 			    SPP_ARGS(ifp), len);
3443 		return;
3444 	}
3445 	h = mtod (m, struct lcp_header*);
3446 	if (len > ntohs (h->len))
3447 		len = ntohs (h->len);
3448 	switch (h->type) {
3449 	/* PAP request is my authproto */
3450 	case PAP_REQ:
3451 		name = 1 + (u_char*)(h+1);
3452 		name_len = name[-1];
3453 		passwd = name + name_len + 1;
3454 		if (name_len > len - 6 ||
3455 		    (passwd_len = passwd[-1]) > len - 6 - name_len) {
3456 			if (debug) {
3457 				log(LOG_DEBUG, SPP_FMT "pap corrupted input "
3458 				    "<%s id=0x%x len=%d",
3459 				    SPP_ARGS(ifp),
3460 				    sppp_auth_type_name(PPP_PAP, h->type),
3461 				    h->ident, ntohs(h->len));
3462 				if (len > 4)
3463 					sppp_print_bytes((u_char*)(h+1), len-4);
3464 				addlog(">\n");
3465 			}
3466 			break;
3467 		}
3468 		if (debug) {
3469 			log(LOG_DEBUG, SPP_FMT "pap input(%s) "
3470 			    "<%s id=0x%x len=%d name=",
3471 			    SPP_ARGS(ifp),
3472 			    sppp_state_name(sp->state[IDX_PAP]),
3473 			    sppp_auth_type_name(PPP_PAP, h->type),
3474 			    h->ident, ntohs(h->len));
3475 			sppp_print_string((char*)name, name_len);
3476 			addlog(" passwd=");
3477 			sppp_print_string((char*)passwd, passwd_len);
3478 			addlog(">\n");
3479 		}
3480 		if (name_len > AUTHNAMELEN ||
3481 		    passwd_len > AUTHKEYLEN ||
3482 		    bcmp(name, sp->hisauth.name, name_len) != 0 ||
3483 		    bcmp(passwd, sp->hisauth.secret, passwd_len) != 0) {
3484 			/* action scn, tld */
3485 			mlen = sizeof(FAILMSG) - 1;
3486 			sppp_auth_send(&pap, sp, PAP_NAK, h->ident,
3487 				       sizeof mlen, (const char *)&mlen,
3488 				       sizeof(FAILMSG) - 1, (u_char *)FAILMSG,
3489 				       0);
3490 			pap.tld(sp);
3491 			break;
3492 		}
3493 		/* action sca, perhaps tlu */
3494 		if (sp->state[IDX_PAP] == STATE_REQ_SENT ||
3495 		    sp->state[IDX_PAP] == STATE_OPENED) {
3496 			mlen = sizeof(SUCCMSG) - 1;
3497 			sppp_auth_send(&pap, sp, PAP_ACK, h->ident,
3498 				       sizeof mlen, (const char *)&mlen,
3499 				       sizeof(SUCCMSG) - 1, (u_char *)SUCCMSG,
3500 				       0);
3501 		}
3502 		if (sp->state[IDX_PAP] == STATE_REQ_SENT) {
3503 			sppp_cp_change_state(&pap, sp, STATE_OPENED);
3504 			pap.tlu(sp);
3505 		}
3506 		break;
3507 
3508 	/* ack and nak are his authproto */
3509 	case PAP_ACK:
3510 		UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
3511 		if (debug) {
3512 			log(LOG_DEBUG, SPP_FMT "pap success",
3513 			    SPP_ARGS(ifp));
3514 			name_len = *((char *)h);
3515 			if (len > 5 && name_len) {
3516 				addlog(": ");
3517 				sppp_print_string((char*)(h+1), name_len);
3518 			}
3519 			addlog("\n");
3520 		}
3521 		x = splimp();
3522 		sp->pp_flags &= ~PP_NEEDAUTH;
3523 		if (sp->myauth.proto == PPP_PAP &&
3524 		    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) &&
3525 		    (sp->lcp.protos & (1 << IDX_PAP)) == 0) {
3526 			/*
3527 			 * We are authenticator for PAP but didn't
3528 			 * complete yet.  Leave it to tlu to proceed
3529 			 * to network phase.
3530 			 */
3531 			splx(x);
3532 			break;
3533 		}
3534 		splx(x);
3535 		sppp_phase_network(sp);
3536 		break;
3537 
3538 	case PAP_NAK:
3539 		UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
3540 		if (debug) {
3541 			log(LOG_INFO, SPP_FMT "pap failure",
3542 			    SPP_ARGS(ifp));
3543 			name_len = *((char *)h);
3544 			if (len > 5 && name_len) {
3545 				addlog(": ");
3546 				sppp_print_string((char*)(h+1), name_len);
3547 			}
3548 			addlog("\n");
3549 		} else
3550 			log(LOG_INFO, SPP_FMT "pap failure\n",
3551 			    SPP_ARGS(ifp));
3552 		/* await LCP shutdown by authenticator */
3553 		break;
3554 
3555 	default:
3556 		/* Unknown PAP packet type -- ignore. */
3557 		if (debug) {
3558 			log(LOG_DEBUG, SPP_FMT "pap corrupted input "
3559 			    "<0x%x id=0x%x len=%d",
3560 			    SPP_ARGS(ifp),
3561 			    h->type, h->ident, ntohs(h->len));
3562 			if (len > 4)
3563 				sppp_print_bytes((u_char*)(h+1), len-4);
3564 			addlog(">\n");
3565 		}
3566 		break;
3567 
3568 	}
3569 }
3570 
3571 HIDE void
3572 sppp_pap_init(struct sppp *sp)
3573 {
3574 	/* PAP doesn't have STATE_INITIAL at all. */
3575 	sp->state[IDX_PAP] = STATE_CLOSED;
3576 	sp->fail_counter[IDX_PAP] = 0;
3577 #if defined (__FreeBSD__)
3578 	callout_handle_init(&sp->ch[IDX_PAP]);
3579 	callout_handle_init(&sp->pap_my_to_ch);
3580 #endif
3581 }
3582 
3583 HIDE void
3584 sppp_pap_open(struct sppp *sp)
3585 {
3586 	if (sp->hisauth.proto == PPP_PAP &&
3587 	    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0) {
3588 		/* we are authenticator for PAP, start our timer */
3589 		sp->rst_counter[IDX_PAP] = sp->lcp.max_configure;
3590 		sppp_cp_change_state(&pap, sp, STATE_REQ_SENT);
3591 	}
3592 	if (sp->myauth.proto == PPP_PAP) {
3593 		/* we are peer, send a request, and start a timer */
3594 		pap.scr(sp);
3595 #if defined (__FreeBSD__)
3596 		sp->pap_my_to_ch =
3597 		    timeout(sppp_pap_my_TO, (void *)sp, sp->lcp.timeout);
3598 #elif defined (__OpenBSD__)
3599 		timeout_set(&sp->pap_my_to_ch, sppp_pap_my_TO, (void *)sp);
3600 		timeout_add(&sp->pap_my_to_ch, sp->lcp.timeout);
3601 #endif
3602 	}
3603 }
3604 
3605 HIDE void
3606 sppp_pap_close(struct sppp *sp)
3607 {
3608 	if (sp->state[IDX_PAP] != STATE_CLOSED)
3609 		sppp_cp_change_state(&pap, sp, STATE_CLOSED);
3610 }
3611 
3612 /*
3613  * That's the timeout routine if we are authenticator.  Since the
3614  * authenticator is basically passive in PAP, we can't do much here.
3615  */
3616 HIDE void
3617 sppp_pap_TO(void *cookie)
3618 {
3619 	struct sppp *sp = (struct sppp *)cookie;
3620 	STDDCL;
3621 	int s;
3622 
3623 	s = splimp();
3624 	if (debug)
3625 		log(LOG_DEBUG, SPP_FMT "pap TO(%s) rst_counter = %d\n",
3626 		    SPP_ARGS(ifp),
3627 		    sppp_state_name(sp->state[IDX_PAP]),
3628 		    sp->rst_counter[IDX_PAP]);
3629 
3630 	if (--sp->rst_counter[IDX_PAP] < 0)
3631 		/* TO- event */
3632 		switch (sp->state[IDX_PAP]) {
3633 		case STATE_REQ_SENT:
3634 			pap.tld(sp);
3635 			sppp_cp_change_state(&pap, sp, STATE_CLOSED);
3636 			break;
3637 		}
3638 	else
3639 		/* TO+ event, not very much we could do */
3640 		switch (sp->state[IDX_PAP]) {
3641 		case STATE_REQ_SENT:
3642 			/* sppp_cp_change_state() will restart the timer */
3643 			sppp_cp_change_state(&pap, sp, STATE_REQ_SENT);
3644 			break;
3645 		}
3646 
3647 	splx(s);
3648 }
3649 
3650 /*
3651  * That's the timeout handler if we are peer.  Since the peer is active,
3652  * we need to retransmit our PAP request since it is apparently lost.
3653  * XXX We should impose a max counter.
3654  */
3655 HIDE void
3656 sppp_pap_my_TO(void *cookie)
3657 {
3658 	struct sppp *sp = (struct sppp *)cookie;
3659 	STDDCL;
3660 
3661 	if (debug)
3662 		log(LOG_DEBUG, SPP_FMT "pap peer TO\n",
3663 		    SPP_ARGS(ifp));
3664 
3665 	pap.scr(sp);
3666 }
3667 
3668 HIDE void
3669 sppp_pap_tlu(struct sppp *sp)
3670 {
3671 	STDDCL;
3672 	int x;
3673 
3674 	sp->rst_counter[IDX_PAP] = sp->lcp.max_configure;
3675 
3676 	if (debug)
3677 		log(LOG_DEBUG, SPP_FMT "%s tlu\n",
3678 		    SPP_ARGS(ifp), pap.name);
3679 
3680 	x = splimp();
3681 	/* indicate to LCP that we need to be closed down */
3682 	sp->lcp.protos |= (1 << IDX_PAP);
3683 
3684 	if (sp->pp_flags & PP_NEEDAUTH) {
3685 		/*
3686 		 * Remote is authenticator, but his auth proto didn't
3687 		 * complete yet.  Defer the transition to network
3688 		 * phase.
3689 		 */
3690 		splx(x);
3691 		return;
3692 	}
3693 	splx(x);
3694 	sppp_phase_network(sp);
3695 }
3696 
3697 HIDE void
3698 sppp_pap_tld(struct sppp *sp)
3699 {
3700 	STDDCL;
3701 
3702 	if (debug)
3703 		log(LOG_DEBUG, SPP_FMT "pap tld\n", SPP_ARGS(ifp));
3704 	UNTIMEOUT(pap.TO, (void *)sp, sp->ch[IDX_PAP]);
3705 	UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
3706 	sp->lcp.protos &= ~(1 << IDX_PAP);
3707 
3708 	lcp.Close(sp);
3709 }
3710 
3711 HIDE void
3712 sppp_pap_scr(struct sppp *sp)
3713 {
3714 	u_char idlen, pwdlen;
3715 
3716 	sp->confid[IDX_PAP] = ++sp->pp_seq;
3717 	pwdlen = sppp_strnlen(sp->myauth.secret, AUTHKEYLEN);
3718 	idlen = sppp_strnlen(sp->myauth.name, AUTHNAMELEN);
3719 
3720 	sppp_auth_send(&pap, sp, PAP_REQ, sp->confid[IDX_PAP],
3721 		       sizeof idlen, (const char *)&idlen,
3722 		       (size_t)idlen, sp->myauth.name,
3723 		       sizeof pwdlen, (const char *)&pwdlen,
3724 		       (size_t)pwdlen, sp->myauth.secret,
3725 		       0);
3726 }
3727 /*
3728  * Random miscellaneous functions.
3729  */
3730 
3731 /*
3732  * Send a PAP or CHAP proto packet.
3733  *
3734  * Varadic function, each of the elements for the ellipsis is of type
3735  * ``size_t mlen, const u_char *msg''.  Processing will stop iff
3736  * mlen == 0.
3737  */
3738 
3739 HIDE void
3740 sppp_auth_send(const struct cp *cp, struct sppp *sp, u_char type, u_char id,
3741 	       ...)
3742 {
3743 	STDDCL;
3744 	struct ppp_header *h;
3745 	struct lcp_header *lh;
3746 	struct mbuf *m;
3747 	u_char *p;
3748 	int len;
3749 	size_t mlen;
3750 	const char *msg;
3751 	va_list ap;
3752 
3753 	MGETHDR (m, M_DONTWAIT, MT_DATA);
3754 	if (! m)
3755 		return;
3756 	m->m_pkthdr.rcvif = 0;
3757 
3758 	h = mtod (m, struct ppp_header*);
3759 	h->address = PPP_ALLSTATIONS;		/* broadcast address */
3760 	h->control = PPP_UI;			/* Unnumbered Info */
3761 	h->protocol = htons(cp->proto);
3762 
3763 	lh = (struct lcp_header*)(h + 1);
3764 	lh->type = type;
3765 	lh->ident = id;
3766 	p = (u_char*) (lh+1);
3767 
3768 	va_start(ap, id);
3769 	len = 0;
3770 
3771 	while ((mlen = va_arg(ap, size_t)) != 0) {
3772 		msg = va_arg(ap, const char *);
3773 		len += mlen;
3774 		if (len > MHLEN - PPP_HEADER_LEN - LCP_HEADER_LEN) {
3775 			va_end(ap);
3776 			m_freem(m);
3777 			return;
3778 		}
3779 
3780 		bcopy(msg, p, mlen);
3781 		p += mlen;
3782 	}
3783 	va_end(ap);
3784 
3785 	m->m_pkthdr.len = m->m_len = PPP_HEADER_LEN + LCP_HEADER_LEN + len;
3786 	lh->len = htons (LCP_HEADER_LEN + len);
3787 
3788 	if (debug) {
3789 		log(LOG_DEBUG, SPP_FMT "%s output <%s id=0x%x len=%d",
3790 		    SPP_ARGS(ifp), cp->name,
3791 		    sppp_auth_type_name(cp->proto, lh->type),
3792 		    lh->ident, ntohs(lh->len));
3793 		if (len)
3794 			sppp_print_bytes((u_char*) (lh+1), len);
3795 		addlog(">\n");
3796 	}
3797 	if (IF_QFULL (&sp->pp_cpq)) {
3798 		IF_DROP (&sp->pp_fastq);
3799 		IF_DROP (&ifp->if_snd);
3800 		m_freem (m);
3801 		++ifp->if_oerrors;
3802 		m = NULL;
3803 	} else
3804 		IF_ENQUEUE (&sp->pp_cpq, m);
3805 	if (! (ifp->if_flags & IFF_OACTIVE))
3806 		(*ifp->if_start) (ifp);
3807 	if (m != NULL)
3808 		ifp->if_obytes += m->m_pkthdr.len + 3;
3809 }
3810 
3811 /*
3812  * Flush interface queue.
3813  */
3814 HIDE void
3815 sppp_qflush(struct ifqueue *ifq)
3816 {
3817 	struct mbuf *m, *n;
3818 
3819 	n = ifq->ifq_head;
3820 	while ((m = n)) {
3821 		n = m->m_act;
3822 		m_freem (m);
3823 	}
3824 	ifq->ifq_head = 0;
3825 	ifq->ifq_tail = 0;
3826 	ifq->ifq_len = 0;
3827 }
3828 
3829 /*
3830  * Send keepalive packets, every 10 seconds.
3831  */
3832 HIDE void
3833 sppp_keepalive(void *dummy)
3834 {
3835 	struct sppp *sp;
3836 	int s;
3837 
3838 	s = splimp();
3839 	for (sp=spppq; sp; sp=sp->pp_next) {
3840 		struct ifnet *ifp = &sp->pp_if;
3841 
3842 		/* Keepalive mode disabled or channel down? */
3843 		if (! (sp->pp_flags & PP_KEEPALIVE) ||
3844 		    ! (ifp->if_flags & IFF_RUNNING))
3845 			continue;
3846 
3847 		/* No keepalive in PPP mode if LCP not opened yet. */
3848 		if (! (sp->pp_flags & PP_CISCO) &&
3849 		    sp->pp_phase < PHASE_AUTHENTICATE)
3850 			continue;
3851 
3852 		if (sp->pp_alivecnt == MAXALIVECNT) {
3853 			/* No keepalive packets got.  Stop the interface. */
3854 			printf (SPP_FMT "down\n", SPP_ARGS(ifp));
3855  			if (sp->pp_flags & PP_CISCO) {
3856 			if_down (ifp);
3857 			sppp_qflush (&sp->pp_cpq);
3858  			} else {
3859 				/* Shut down the PPP link. */
3860  				lcp.Close(sp);
3861 			}
3862 		}
3863 		if (sp->pp_alivecnt <= MAXALIVECNT)
3864 			++sp->pp_alivecnt;
3865 		if (sp->pp_flags & PP_CISCO)
3866 			sppp_cisco_send (sp, CISCO_KEEPALIVE_REQ, ++sp->pp_seq,
3867 				sp->pp_rseq);
3868 		else if (sp->pp_phase >= PHASE_AUTHENTICATE) {
3869 			long nmagic = htonl (sp->lcp.magic);
3870 			sp->lcp.echoid = ++sp->pp_seq;
3871 			sppp_cp_send (sp, PPP_LCP, ECHO_REQ,
3872 				sp->lcp.echoid, 4, &nmagic);
3873 		}
3874 	}
3875 	splx(s);
3876 #if defined (__FreeBSD__)
3877 	keepalive_ch = timeout(sppp_keepalive, 0, hz * 10);
3878 #endif
3879 #if defined (__OpenBSD__)
3880 	timeout_add(&keepalive_ch, hz * 10);
3881 #endif
3882 }
3883 
3884 /*
3885  * Get both IP addresses.
3886  */
3887 HIDE void
3888 sppp_get_ip_addrs(struct sppp *sp, u_long *src, u_long *dst, u_long *srcmask)
3889 {
3890 	struct ifnet *ifp = &sp->pp_if;
3891 	struct ifaddr *ifa;
3892 	struct sockaddr_in *si, *sm = 0;
3893 	u_long ssrc, ddst;
3894 
3895 	sm = NULL;
3896 	ssrc = ddst = 0L;
3897 	/*
3898 	 * Pick the first AF_INET address from the list,
3899 	 * aliases don't make any sense on a p2p link anyway.
3900 	 */
3901 #if defined (__FreeBSD__)
3902 	for (ifa = ifp->if_addrhead.tqh_first, si = 0;
3903 	     ifa;
3904 	     ifa = ifa->ifa_link.tqe_next)
3905 #else
3906 	for (ifa = ifp->if_addrlist.tqh_first, si = 0;
3907 	     ifa;
3908 	     ifa = ifa->ifa_list.tqe_next)
3909 #endif
3910 		if (ifa->ifa_addr->sa_family == AF_INET) {
3911 			si = (struct sockaddr_in *)ifa->ifa_addr;
3912 			sm = (struct sockaddr_in *)ifa->ifa_netmask;
3913 			if (si)
3914 				break;
3915 		}
3916 	if (ifa) {
3917 		if (si && si->sin_addr.s_addr) {
3918 			ssrc = si->sin_addr.s_addr;
3919 			if (srcmask)
3920 				*srcmask = ntohl(sm->sin_addr.s_addr);
3921 		}
3922 
3923 		si = (struct sockaddr_in *)ifa->ifa_dstaddr;
3924 		if (si && si->sin_addr.s_addr)
3925 			ddst = si->sin_addr.s_addr;
3926 	}
3927 
3928 	if (dst) *dst = ntohl(ddst);
3929 	if (src) *src = ntohl(ssrc);
3930 }
3931 
3932 /*
3933  * Set my IP address.  Must be called at splimp.
3934  */
3935 HIDE void
3936 sppp_set_ip_addr(struct sppp *sp, u_long src)
3937 {
3938 	struct ifnet *ifp = &sp->pp_if;
3939 	struct ifaddr *ifa;
3940 	struct sockaddr_in *si;
3941 
3942 	/*
3943 	 * Pick the first AF_INET address from the list,
3944 	 * aliases don't make any sense on a p2p link anyway.
3945 	 */
3946 
3947 #if defined (__FreeBSD__)
3948 	for (ifa = ifp->if_addrhead.tqh_first, si = 0;
3949 	     ifa;
3950 	     ifa = ifa->ifa_link.tqe_next)
3951 #else
3952 	for (ifa = ifp->if_addrlist.tqh_first, si = 0;
3953 	     ifa;
3954 	     ifa = ifa->ifa_list.tqe_next)
3955 #endif
3956 	{
3957 		if (ifa->ifa_addr->sa_family == AF_INET)
3958 		{
3959 			si = (struct sockaddr_in *)ifa->ifa_addr;
3960 			if (si)
3961 				break;
3962 		}
3963 	}
3964 
3965 	if (ifa && si)
3966 		si->sin_addr.s_addr = htonl(src);
3967 }
3968 
3969 HIDE int
3970 sppp_params(struct sppp *sp, u_long cmd, void *data)
3971 {
3972 	struct ifreq *ifr = (struct ifreq *)data;
3973 	struct spppreq spr;
3974 
3975 	if (copyin((caddr_t)ifr->ifr_data, &spr, sizeof spr) != 0)
3976 		return EFAULT;
3977 
3978 	switch (spr.cmd) {
3979 	case (int)SPPPIOGDEFS:
3980 		if (cmd != SIOCGIFGENERIC)
3981 			return EINVAL;
3982 		/*
3983 		 * We copy over the entire current state, but clean
3984 		 * out some of the stuff we don't wanna pass up.
3985 		 * Remember, SIOCGIFGENERIC is unprotected, and can be
3986 		 * called by any user.  No need to ever get PAP or
3987 		 * CHAP secrets back to userland anyway.
3988 		 */
3989 		bcopy(sp, &spr.defs, sizeof(struct sppp));
3990 		bzero(spr.defs.myauth.secret, AUTHKEYLEN);
3991 		bzero(spr.defs.myauth.challenge, AUTHKEYLEN);
3992 		bzero(spr.defs.hisauth.secret, AUTHKEYLEN);
3993 		bzero(spr.defs.hisauth.challenge, AUTHKEYLEN);
3994 		return copyout(&spr, (caddr_t)ifr->ifr_data, sizeof spr);
3995 
3996 	case (int)SPPPIOSDEFS:
3997 		if (cmd != SIOCSIFGENERIC)
3998 			return EINVAL;
3999 		/*
4000 		 * We have a very specific idea of which fields we allow
4001 		 * being passed back from userland, so to not clobber our
4002 		 * current state.  For one, we only allow setting
4003 		 * anything if LCP is in dead phase.  Once the LCP
4004 		 * negotiations started, the authentication settings must
4005 		 * not be changed again.  (The administrator can force an
4006 		 * ifconfig down in order to get LCP back into dead
4007 		 * phase.)
4008 		 *
4009 		 * Also, we only allow for authentication parameters to be
4010 		 * specified.
4011 		 *
4012 		 * XXX Should allow to set or clear pp_flags.
4013 		 *
4014 		 * Finally, if the respective authentication protocol to
4015 		 * be used is set differently than 0, but the secret is
4016 		 * passed as all zeros, we don't trash the existing secret.
4017 		 * This allows an administrator to change the system name
4018 		 * only without clobbering the secret (which he didn't get
4019 		 * back in a previous SPPPIOGDEFS call).  However, the
4020 		 * secrets are cleared if the authentication protocol is
4021 		 * reset to 0.
4022 		 */
4023 		if (sp->pp_phase != PHASE_DEAD)
4024 			return EBUSY;
4025 
4026 		if ((spr.defs.myauth.proto != 0 && spr.defs.myauth.proto != PPP_PAP &&
4027 		     spr.defs.myauth.proto != PPP_CHAP) ||
4028 		    (spr.defs.hisauth.proto != 0 && spr.defs.hisauth.proto != PPP_PAP &&
4029 		     spr.defs.hisauth.proto != PPP_CHAP))
4030 			return EINVAL;
4031 
4032 		if (spr.defs.myauth.proto == 0)
4033 			/* resetting myauth */
4034 			bzero(&sp->myauth, sizeof sp->myauth);
4035 		else {
4036 			/* setting/changing myauth */
4037 			sp->myauth.proto = spr.defs.myauth.proto;
4038 			bcopy(spr.defs.myauth.name, sp->myauth.name, AUTHNAMELEN);
4039 			if (spr.defs.myauth.secret[0] != '\0')
4040 				bcopy(spr.defs.myauth.secret, sp->myauth.secret,
4041 				      AUTHKEYLEN);
4042 		}
4043 		if (spr.defs.hisauth.proto == 0)
4044 			/* resetting hisauth */
4045 			bzero(&sp->hisauth, sizeof sp->hisauth);
4046 		else {
4047 			/* setting/changing hisauth */
4048 			sp->hisauth.proto = spr.defs.hisauth.proto;
4049 			sp->hisauth.flags = spr.defs.hisauth.flags;
4050 			bcopy(spr.defs.hisauth.name, sp->hisauth.name, AUTHNAMELEN);
4051 			if (spr.defs.hisauth.secret[0] != '\0')
4052 				bcopy(spr.defs.hisauth.secret, sp->hisauth.secret,
4053 				      AUTHKEYLEN);
4054 		}
4055 		break;
4056 
4057 	default:
4058 		return EINVAL;
4059 	}
4060 
4061 	return 0;
4062 }
4063 
4064 HIDE void
4065 sppp_phase_network(struct sppp *sp)
4066 {
4067 	struct ifnet *ifp = &sp->pp_if;
4068 	int i;
4069 	u_long mask;
4070 
4071 	sp->pp_phase = PHASE_NETWORK;
4072 
4073 	log(LOG_INFO, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
4074 	    sppp_phase_name(sp->pp_phase));
4075 
4076 	/* Notify NCPs now. */
4077 	for (i = 0; i < IDX_COUNT; i++)
4078 		if ((cps[i])->flags & CP_NCP)
4079 			(cps[i])->Open(sp);
4080 
4081 	/* Send Up events to all NCPs. */
4082 	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
4083 		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_NCP))
4084 			(cps[i])->Up(sp);
4085 
4086 	/* if no NCP is starting, all this was in vain, close down */
4087 	sppp_lcp_check_and_close(sp);
4088 }
4089 
4090 
4091 HIDE const char *
4092 sppp_cp_type_name(u_char type)
4093 {
4094 	static char buf[12];
4095 	switch (type) {
4096 	case CONF_REQ:   return "conf-req";
4097 	case CONF_ACK:   return "conf-ack";
4098 	case CONF_NAK:   return "conf-nak";
4099 	case CONF_REJ:   return "conf-rej";
4100 	case TERM_REQ:   return "term-req";
4101 	case TERM_ACK:   return "term-ack";
4102 	case CODE_REJ:   return "code-rej";
4103 	case PROTO_REJ:  return "proto-rej";
4104 	case ECHO_REQ:   return "echo-req";
4105 	case ECHO_REPLY: return "echo-reply";
4106 	case DISC_REQ:   return "discard-req";
4107 	}
4108 	sprintf (buf, "0x%x", type);
4109 	return buf;
4110 }
4111 
4112 HIDE const char *
4113 sppp_auth_type_name(u_short proto, u_char type)
4114 {
4115 	static char buf[12];
4116 	switch (proto) {
4117 	case PPP_CHAP:
4118 		switch (type) {
4119 		case CHAP_CHALLENGE:	return "challenge";
4120 		case CHAP_RESPONSE:	return "response";
4121 		case CHAP_SUCCESS:	return "success";
4122 		case CHAP_FAILURE:	return "failure";
4123 		}
4124 	case PPP_PAP:
4125 		switch (type) {
4126 		case PAP_REQ:		return "req";
4127 		case PAP_ACK:		return "ack";
4128 		case PAP_NAK:		return "nak";
4129 		}
4130 	}
4131 	sprintf (buf, "0x%x", type);
4132 	return buf;
4133 }
4134 
4135 HIDE const char *
4136 sppp_lcp_opt_name(u_char opt)
4137 {
4138 	static char buf[12];
4139 	switch (opt) {
4140 	case LCP_OPT_MRU:		return "mru";
4141 	case LCP_OPT_ASYNC_MAP:		return "async-map";
4142 	case LCP_OPT_AUTH_PROTO:	return "auth-proto";
4143 	case LCP_OPT_QUAL_PROTO:	return "qual-proto";
4144 	case LCP_OPT_MAGIC:		return "magic";
4145 	case LCP_OPT_PROTO_COMP:	return "proto-comp";
4146 	case LCP_OPT_ADDR_COMP:		return "addr-comp";
4147 	}
4148 	sprintf (buf, "0x%x", opt);
4149 	return buf;
4150 }
4151 
4152 HIDE const char *
4153 sppp_ipcp_opt_name(u_char opt)
4154 {
4155 	static char buf[12];
4156 	switch (opt) {
4157 	case IPCP_OPT_ADDRESSES:	return "addresses";
4158 	case IPCP_OPT_COMPRESSION:	return "compression";
4159 	case IPCP_OPT_ADDRESS:		return "address";
4160 	}
4161 	sprintf (buf, "0x%x", opt);
4162 	return buf;
4163 }
4164 
4165 HIDE const char *
4166 sppp_state_name(int state)
4167 {
4168 	switch (state) {
4169 	case STATE_INITIAL:	return "initial";
4170 	case STATE_STARTING:	return "starting";
4171 	case STATE_CLOSED:	return "closed";
4172 	case STATE_STOPPED:	return "stopped";
4173 	case STATE_CLOSING:	return "closing";
4174 	case STATE_STOPPING:	return "stopping";
4175 	case STATE_REQ_SENT:	return "req-sent";
4176 	case STATE_ACK_RCVD:	return "ack-rcvd";
4177 	case STATE_ACK_SENT:	return "ack-sent";
4178 	case STATE_OPENED:	return "opened";
4179 	}
4180 	return "illegal";
4181 }
4182 
4183 HIDE const char *
4184 sppp_phase_name(enum ppp_phase phase)
4185 {
4186 	switch (phase) {
4187 	case PHASE_DEAD:	return "dead";
4188 	case PHASE_ESTABLISH:	return "establish";
4189 	case PHASE_TERMINATE:	return "terminate";
4190 	case PHASE_AUTHENTICATE: return "authenticate";
4191 	case PHASE_NETWORK:	return "network";
4192 	}
4193 	return "illegal";
4194 }
4195 
4196 HIDE const char *
4197 sppp_proto_name(u_short proto)
4198 {
4199 	static char buf[12];
4200 	switch (proto) {
4201 	case PPP_LCP:	return "lcp";
4202 	case PPP_IPCP:	return "ipcp";
4203 	case PPP_PAP:	return "pap";
4204 	case PPP_CHAP:	return "chap";
4205 	}
4206 	sprintf(buf, "0x%x", (unsigned)proto);
4207 	return buf;
4208 }
4209 
4210 HIDE void
4211 sppp_print_bytes(const u_char *p, u_short len)
4212 {
4213 	addlog(" %02x", *p++);
4214 	while (--len > 0)
4215 		addlog("-%02x", *p++);
4216 }
4217 
4218 HIDE void
4219 sppp_print_string(const char *p, u_short len)
4220 {
4221 	u_char c;
4222 
4223 	while (len-- > 0) {
4224 		c = *p++;
4225 		/*
4226 		 * Print only ASCII chars directly.  RFC 1994 recommends
4227 		 * using only them, but we don't rely on it.  */
4228 		if (c < ' ' || c > '~')
4229 			addlog("\\x%x", c);
4230 		else
4231 			addlog("%c", c);
4232 	}
4233 }
4234 
4235 HIDE const char *
4236 sppp_dotted_quad(u_long addr)
4237 {
4238 	static char s[16];
4239 	sprintf(s, "%d.%d.%d.%d",
4240 		(int)((addr >> 24) & 0xff),
4241 		(int)((addr >> 16) & 0xff),
4242 		(int)((addr >> 8) & 0xff),
4243 		(int)(addr & 0xff));
4244 	return s;
4245 }
4246 
4247 HIDE int
4248 sppp_strnlen(u_char *p, int max)
4249 {
4250 	int len;
4251 
4252 	for (len = 0; len < max && *p; ++p)
4253 		++len;
4254 	return len;
4255 }
4256 
4257 /* a dummy, used to drop uninteresting events */
4258 HIDE void
4259 sppp_null(struct sppp *unused)
4260 {
4261 	/* do just nothing */
4262 }
4263 /*
4264  * This file is large.  Tell emacs to highlight it nevertheless.
4265  *
4266  * Local Variables:
4267  * hilit-auto-highlight-maxout: 120000
4268  * End:
4269  */
4270