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