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