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