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