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