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