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