if_spppsubr.c revision 88506
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 88506 2001-12-26 22:00:13Z 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			/*
2218			 * Async control character map -- just ignore it.
2219			 *
2220			 * Quote from RFC 1662, chapter 6:
2221			 * To enable this functionality, synchronous PPP
2222			 * implementations MUST always respond to the
2223			 * Async-Control-Character-Map Configuration
2224			 * Option with the LCP Configure-Ack.  However,
2225			 * acceptance of the Configuration Option does
2226			 * not imply that the synchronous implementation
2227			 * will do any ACCM mapping.  Instead, all such
2228			 * octet mapping will be performed by the
2229			 * asynchronous-to-synchronous converter.
2230			 */
2231			continue;
2232
2233		case LCP_OPT_MRU:
2234			/*
2235			 * Maximum receive unit.  Always agreeable,
2236			 * but ignored by now.
2237			 */
2238			sp->lcp.their_mru = p[2] * 256 + p[3];
2239			if (debug)
2240				log(-1, "%lu ", sp->lcp.their_mru);
2241			continue;
2242
2243		case LCP_OPT_AUTH_PROTO:
2244			authproto = (p[2] << 8) + p[3];
2245			if (sp->myauth.proto != authproto) {
2246				/* not agreed, nak */
2247				if (debug)
2248					log(-1, "[mine %s != his %s] ",
2249					       sppp_proto_name(sp->hisauth.proto),
2250					       sppp_proto_name(authproto));
2251				p[2] = sp->myauth.proto >> 8;
2252				p[3] = sp->myauth.proto;
2253				break;
2254			}
2255			if (authproto == PPP_CHAP && p[4] != CHAP_MD5) {
2256				if (debug)
2257					log(-1, "[chap not MD5] ");
2258				p[4] = CHAP_MD5;
2259				break;
2260			}
2261			continue;
2262		}
2263		/* Add the option to nak'ed list. */
2264		bcopy (p, r, p[1]);
2265		r += p[1];
2266		rlen += p[1];
2267	}
2268	if (rlen) {
2269		/*
2270		 * Local and remote magics equal -- loopback?
2271		 */
2272		if (sp->pp_loopcnt >= MAXALIVECNT*5) {
2273			if (sp->pp_loopcnt == MAXALIVECNT*5)
2274				printf (SPP_FMT "loopback\n",
2275					SPP_ARGS(ifp));
2276			if (ifp->if_flags & IFF_UP) {
2277				if_down(ifp);
2278				sppp_qflush(&sp->pp_cpq);
2279				/* XXX ? */
2280				lcp.Down(sp);
2281				lcp.Up(sp);
2282			}
2283		} else if (++sp->fail_counter[IDX_LCP] >= sp->lcp.max_failure) {
2284			if (debug)
2285				log(-1, " max_failure (%d) exceeded, "
2286				       "send conf-rej\n",
2287				       sp->lcp.max_failure);
2288			sppp_cp_send(sp, PPP_LCP, CONF_REJ, h->ident, rlen, buf);
2289		} else {
2290			if (debug)
2291				log(-1, " send conf-nak\n");
2292			sppp_cp_send (sp, PPP_LCP, CONF_NAK, h->ident, rlen, buf);
2293		}
2294	} else {
2295		if (debug)
2296			log(-1, " send conf-ack\n");
2297		sp->fail_counter[IDX_LCP] = 0;
2298		sp->pp_loopcnt = 0;
2299		sppp_cp_send (sp, PPP_LCP, CONF_ACK,
2300			      h->ident, origlen, h+1);
2301	}
2302
2303	free (buf, M_TEMP);
2304	return (rlen == 0);
2305}
2306
2307/*
2308 * Analyze the LCP Configure-Reject option list, and adjust our
2309 * negotiation.
2310 */
2311static void
2312sppp_lcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
2313{
2314	STDDCL;
2315	u_char *buf, *p;
2316
2317	len -= 4;
2318	buf = malloc (len, M_TEMP, M_NOWAIT);
2319	if (!buf)
2320		return;
2321
2322	if (debug)
2323		log(LOG_DEBUG, SPP_FMT "lcp rej opts: ",
2324		    SPP_ARGS(ifp));
2325
2326	p = (void*) (h+1);
2327	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2328		if (debug)
2329			log(-1, " %s ", sppp_lcp_opt_name(*p));
2330		switch (*p) {
2331		case LCP_OPT_MAGIC:
2332			/* Magic number -- can't use it, use 0 */
2333			sp->lcp.opts &= ~(1 << LCP_OPT_MAGIC);
2334			sp->lcp.magic = 0;
2335			break;
2336		case LCP_OPT_MRU:
2337			/*
2338			 * Should not be rejected anyway, since we only
2339			 * negotiate a MRU if explicitly requested by
2340			 * peer.
2341			 */
2342			sp->lcp.opts &= ~(1 << LCP_OPT_MRU);
2343			break;
2344		case LCP_OPT_AUTH_PROTO:
2345			/*
2346			 * Peer doesn't want to authenticate himself,
2347			 * deny unless this is a dialout call, and
2348			 * AUTHFLAG_NOCALLOUT is set.
2349			 */
2350			if ((sp->pp_flags & PP_CALLIN) == 0 &&
2351			    (sp->hisauth.flags & AUTHFLAG_NOCALLOUT) != 0) {
2352				if (debug)
2353					log(-1, "[don't insist on auth "
2354					       "for callout]");
2355				sp->lcp.opts &= ~(1 << LCP_OPT_AUTH_PROTO);
2356				break;
2357			}
2358			if (debug)
2359				log(-1, "[access denied]\n");
2360			lcp.Close(sp);
2361			break;
2362		}
2363	}
2364	if (debug)
2365		log(-1, "\n");
2366	free (buf, M_TEMP);
2367	return;
2368}
2369
2370/*
2371 * Analyze the LCP Configure-NAK option list, and adjust our
2372 * negotiation.
2373 */
2374static void
2375sppp_lcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
2376{
2377	STDDCL;
2378	u_char *buf, *p;
2379	u_long magic;
2380
2381	len -= 4;
2382	buf = malloc (len, M_TEMP, M_NOWAIT);
2383	if (!buf)
2384		return;
2385
2386	if (debug)
2387		log(LOG_DEBUG, SPP_FMT "lcp nak opts: ",
2388		    SPP_ARGS(ifp));
2389
2390	p = (void*) (h+1);
2391	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2392		if (debug)
2393			log(-1, " %s ", sppp_lcp_opt_name(*p));
2394		switch (*p) {
2395		case LCP_OPT_MAGIC:
2396			/* Magic number -- renegotiate */
2397			if ((sp->lcp.opts & (1 << LCP_OPT_MAGIC)) &&
2398			    len >= 6 && p[1] == 6) {
2399				magic = (u_long)p[2] << 24 |
2400					(u_long)p[3] << 16 | p[4] << 8 | p[5];
2401				/*
2402				 * If the remote magic is our negated one,
2403				 * this looks like a loopback problem.
2404				 * Suggest a new magic to make sure.
2405				 */
2406				if (magic == ~sp->lcp.magic) {
2407					if (debug)
2408						log(-1, "magic glitch ");
2409#if defined(__FreeBSD__) && __FreeBSD__ >= 3
2410					sp->lcp.magic = random();
2411#else
2412					sp->lcp.magic = time.tv_sec + time.tv_usec;
2413#endif
2414				} else {
2415					sp->lcp.magic = magic;
2416					if (debug)
2417						log(-1, "%lu ", magic);
2418				}
2419			}
2420			break;
2421		case LCP_OPT_MRU:
2422			/*
2423			 * Peer wants to advise us to negotiate an MRU.
2424			 * Agree on it if it's reasonable, or use
2425			 * default otherwise.
2426			 */
2427			if (len >= 4 && p[1] == 4) {
2428				u_int mru = p[2] * 256 + p[3];
2429				if (debug)
2430					log(-1, "%d ", mru);
2431				if (mru < PP_MTU || mru > PP_MAX_MRU)
2432					mru = PP_MTU;
2433				sp->lcp.mru = mru;
2434				sp->lcp.opts |= (1 << LCP_OPT_MRU);
2435			}
2436			break;
2437		case LCP_OPT_AUTH_PROTO:
2438			/*
2439			 * Peer doesn't like our authentication method,
2440			 * deny.
2441			 */
2442			if (debug)
2443				log(-1, "[access denied]\n");
2444			lcp.Close(sp);
2445			break;
2446		}
2447	}
2448	if (debug)
2449		log(-1, "\n");
2450	free (buf, M_TEMP);
2451	return;
2452}
2453
2454static void
2455sppp_lcp_tlu(struct sppp *sp)
2456{
2457	STDDCL;
2458	int i;
2459	u_long mask;
2460
2461	/* XXX ? */
2462	if (! (ifp->if_flags & IFF_UP) &&
2463	    (ifp->if_flags & IFF_RUNNING)) {
2464		/* Coming out of loopback mode. */
2465		if_up(ifp);
2466		printf (SPP_FMT "up\n", SPP_ARGS(ifp));
2467	}
2468
2469	for (i = 0; i < IDX_COUNT; i++)
2470		if ((cps[i])->flags & CP_QUAL)
2471			(cps[i])->Open(sp);
2472
2473	if ((sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0 ||
2474	    (sp->pp_flags & PP_NEEDAUTH) != 0)
2475		sp->pp_phase = PHASE_AUTHENTICATE;
2476	else
2477		sp->pp_phase = PHASE_NETWORK;
2478
2479	if (debug)
2480		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2481		    sppp_phase_name(sp->pp_phase));
2482
2483	/*
2484	 * Open all authentication protocols.  This is even required
2485	 * if we already proceeded to network phase, since it might be
2486	 * that remote wants us to authenticate, so we might have to
2487	 * send a PAP request.  Undesired authentication protocols
2488	 * don't do anything when they get an Open event.
2489	 */
2490	for (i = 0; i < IDX_COUNT; i++)
2491		if ((cps[i])->flags & CP_AUTH)
2492			(cps[i])->Open(sp);
2493
2494	if (sp->pp_phase == PHASE_NETWORK) {
2495		/* Notify all NCPs. */
2496		for (i = 0; i < IDX_COUNT; i++)
2497			if ((cps[i])->flags & CP_NCP)
2498				(cps[i])->Open(sp);
2499	}
2500
2501	/* Send Up events to all started protos. */
2502	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2503		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_LCP) == 0)
2504			(cps[i])->Up(sp);
2505
2506	/* notify low-level driver of state change */
2507	if (sp->pp_chg)
2508		sp->pp_chg(sp, (int)sp->pp_phase);
2509
2510	if (sp->pp_phase == PHASE_NETWORK)
2511		/* if no NCP is starting, close down */
2512		sppp_lcp_check_and_close(sp);
2513}
2514
2515static void
2516sppp_lcp_tld(struct sppp *sp)
2517{
2518	STDDCL;
2519	int i;
2520	u_long mask;
2521
2522	sp->pp_phase = PHASE_TERMINATE;
2523
2524	if (debug)
2525		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2526		    sppp_phase_name(sp->pp_phase));
2527
2528	/*
2529	 * Take upper layers down.  We send the Down event first and
2530	 * the Close second to prevent the upper layers from sending
2531	 * ``a flurry of terminate-request packets'', as the RFC
2532	 * describes it.
2533	 */
2534	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2535		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_LCP) == 0) {
2536			(cps[i])->Down(sp);
2537			(cps[i])->Close(sp);
2538		}
2539}
2540
2541static void
2542sppp_lcp_tls(struct sppp *sp)
2543{
2544	STDDCL;
2545
2546	sp->pp_phase = PHASE_ESTABLISH;
2547
2548	if (debug)
2549		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2550		    sppp_phase_name(sp->pp_phase));
2551
2552	/* Notify lower layer if desired. */
2553	if (sp->pp_tls)
2554		(sp->pp_tls)(sp);
2555	else
2556		(sp->pp_up)(sp);
2557}
2558
2559static void
2560sppp_lcp_tlf(struct sppp *sp)
2561{
2562	STDDCL;
2563
2564	sp->pp_phase = PHASE_DEAD;
2565	if (debug)
2566		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2567		    sppp_phase_name(sp->pp_phase));
2568
2569	/* Notify lower layer if desired. */
2570	if (sp->pp_tlf)
2571		(sp->pp_tlf)(sp);
2572	else
2573		(sp->pp_down)(sp);
2574}
2575
2576static void
2577sppp_lcp_scr(struct sppp *sp)
2578{
2579	char opt[6 /* magicnum */ + 4 /* mru */ + 5 /* chap */];
2580	int i = 0;
2581	u_short authproto;
2582
2583	if (sp->lcp.opts & (1 << LCP_OPT_MAGIC)) {
2584		if (! sp->lcp.magic)
2585#if defined(__FreeBSD__) && __FreeBSD__ >= 3
2586			sp->lcp.magic = random();
2587#else
2588			sp->lcp.magic = time.tv_sec + time.tv_usec;
2589#endif
2590		opt[i++] = LCP_OPT_MAGIC;
2591		opt[i++] = 6;
2592		opt[i++] = sp->lcp.magic >> 24;
2593		opt[i++] = sp->lcp.magic >> 16;
2594		opt[i++] = sp->lcp.magic >> 8;
2595		opt[i++] = sp->lcp.magic;
2596	}
2597
2598	if (sp->lcp.opts & (1 << LCP_OPT_MRU)) {
2599		opt[i++] = LCP_OPT_MRU;
2600		opt[i++] = 4;
2601		opt[i++] = sp->lcp.mru >> 8;
2602		opt[i++] = sp->lcp.mru;
2603	}
2604
2605	if (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) {
2606		authproto = sp->hisauth.proto;
2607		opt[i++] = LCP_OPT_AUTH_PROTO;
2608		opt[i++] = authproto == PPP_CHAP? 5: 4;
2609		opt[i++] = authproto >> 8;
2610		opt[i++] = authproto;
2611		if (authproto == PPP_CHAP)
2612			opt[i++] = CHAP_MD5;
2613	}
2614
2615	sp->confid[IDX_LCP] = ++sp->pp_seq[IDX_LCP];
2616	sppp_cp_send (sp, PPP_LCP, CONF_REQ, sp->confid[IDX_LCP], i, &opt);
2617}
2618
2619/*
2620 * Check the open NCPs, return true if at least one NCP is open.
2621 */
2622static int
2623sppp_ncp_check(struct sppp *sp)
2624{
2625	int i, mask;
2626
2627	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2628		if (sp->lcp.protos & mask && (cps[i])->flags & CP_NCP)
2629			return 1;
2630	return 0;
2631}
2632
2633/*
2634 * Re-check the open NCPs and see if we should terminate the link.
2635 * Called by the NCPs during their tlf action handling.
2636 */
2637static void
2638sppp_lcp_check_and_close(struct sppp *sp)
2639{
2640
2641	if (sp->pp_phase < PHASE_NETWORK)
2642		/* don't bother, we are already going down */
2643		return;
2644
2645	if (sppp_ncp_check(sp))
2646		return;
2647
2648	lcp.Close(sp);
2649}
2650
2651/*
2652 *--------------------------------------------------------------------------*
2653 *                                                                          *
2654 *                        The IPCP implementation.                          *
2655 *                                                                          *
2656 *--------------------------------------------------------------------------*
2657 */
2658
2659static void
2660sppp_ipcp_init(struct sppp *sp)
2661{
2662	sp->ipcp.opts = 0;
2663	sp->ipcp.flags = 0;
2664	sp->state[IDX_IPCP] = STATE_INITIAL;
2665	sp->fail_counter[IDX_IPCP] = 0;
2666	sp->pp_seq[IDX_IPCP] = 0;
2667	sp->pp_rseq[IDX_IPCP] = 0;
2668#if defined(__FreeBSD__) && __FreeBSD__ >= 3
2669	callout_handle_init(&sp->ch[IDX_IPCP]);
2670#endif
2671}
2672
2673static void
2674sppp_ipcp_up(struct sppp *sp)
2675{
2676	sppp_up_event(&ipcp, sp);
2677}
2678
2679static void
2680sppp_ipcp_down(struct sppp *sp)
2681{
2682	sppp_down_event(&ipcp, sp);
2683}
2684
2685static void
2686sppp_ipcp_open(struct sppp *sp)
2687{
2688	STDDCL;
2689	u_long myaddr, hisaddr;
2690
2691	sp->ipcp.flags &= ~(IPCP_HISADDR_SEEN|IPCP_MYADDR_SEEN|IPCP_MYADDR_DYN);
2692
2693	sppp_get_ip_addrs(sp, &myaddr, &hisaddr, 0);
2694	/*
2695	 * If we don't have his address, this probably means our
2696	 * interface doesn't want to talk IP at all.  (This could
2697	 * be the case if somebody wants to speak only IPX, for
2698	 * example.)  Don't open IPCP in this case.
2699	 */
2700	if (hisaddr == 0L) {
2701		/* XXX this message should go away */
2702		if (debug)
2703			log(LOG_DEBUG, SPP_FMT "ipcp_open(): no IP interface\n",
2704			    SPP_ARGS(ifp));
2705		return;
2706	}
2707
2708	if (myaddr == 0L) {
2709		/*
2710		 * I don't have an assigned address, so i need to
2711		 * negotiate my address.
2712		 */
2713		sp->ipcp.flags |= IPCP_MYADDR_DYN;
2714		sp->ipcp.opts |= (1 << IPCP_OPT_ADDRESS);
2715	} else
2716		sp->ipcp.flags |= IPCP_MYADDR_SEEN;
2717	sppp_open_event(&ipcp, sp);
2718}
2719
2720static void
2721sppp_ipcp_close(struct sppp *sp)
2722{
2723	sppp_close_event(&ipcp, sp);
2724	if (sp->ipcp.flags & IPCP_MYADDR_DYN)
2725		/*
2726		 * My address was dynamic, clear it again.
2727		 */
2728		sppp_set_ip_addr(sp, 0L);
2729}
2730
2731static void
2732sppp_ipcp_TO(void *cookie)
2733{
2734	sppp_to_event(&ipcp, (struct sppp *)cookie);
2735}
2736
2737/*
2738 * Analyze a configure request.  Return true if it was agreeable, and
2739 * caused action sca, false if it has been rejected or nak'ed, and
2740 * caused action scn.  (The return value is used to make the state
2741 * transition decision in the state automaton.)
2742 */
2743static int
2744sppp_ipcp_RCR(struct sppp *sp, struct lcp_header *h, int len)
2745{
2746	u_char *buf, *r, *p;
2747	struct ifnet *ifp = &sp->pp_if;
2748	int rlen, origlen, debug = ifp->if_flags & IFF_DEBUG;
2749	u_long hisaddr, desiredaddr;
2750	int gotmyaddr = 0;
2751
2752	len -= 4;
2753	origlen = len;
2754	/*
2755	 * Make sure to allocate a buf that can at least hold a
2756	 * conf-nak with an `address' option.  We might need it below.
2757	 */
2758	buf = r = malloc ((len < 6? 6: len), M_TEMP, M_NOWAIT);
2759	if (! buf)
2760		return (0);
2761
2762	/* pass 1: see if we can recognize them */
2763	if (debug)
2764		log(LOG_DEBUG, SPP_FMT "ipcp parse opts: ",
2765		    SPP_ARGS(ifp));
2766	p = (void*) (h+1);
2767	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2768		if (debug)
2769			log(-1, " %s ", sppp_ipcp_opt_name(*p));
2770		switch (*p) {
2771		case IPCP_OPT_ADDRESS:
2772			if (len >= 6 && p[1] == 6) {
2773				/* correctly formed address option */
2774				continue;
2775			}
2776			if (debug)
2777				log(-1, "[invalid] ");
2778			break;
2779		default:
2780			/* Others not supported. */
2781			if (debug)
2782				log(-1, "[rej] ");
2783			break;
2784		}
2785		/* Add the option to rejected list. */
2786		bcopy (p, r, p[1]);
2787		r += p[1];
2788		rlen += p[1];
2789	}
2790	if (rlen) {
2791		if (debug)
2792			log(-1, " send conf-rej\n");
2793		sppp_cp_send (sp, PPP_IPCP, CONF_REJ, h->ident, rlen, buf);
2794		return 0;
2795	} else if (debug)
2796		log(-1, "\n");
2797
2798	/* pass 2: parse option values */
2799	sppp_get_ip_addrs(sp, 0, &hisaddr, 0);
2800	if (debug)
2801		log(LOG_DEBUG, SPP_FMT "ipcp parse opt values: ",
2802		       SPP_ARGS(ifp));
2803	p = (void*) (h+1);
2804	len = origlen;
2805	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2806		if (debug)
2807			log(-1, " %s ", sppp_ipcp_opt_name(*p));
2808		switch (*p) {
2809		case IPCP_OPT_ADDRESS:
2810			/* This is the address he wants in his end */
2811			desiredaddr = p[2] << 24 | p[3] << 16 |
2812				p[4] << 8 | p[5];
2813			if (desiredaddr == hisaddr ||
2814			    (hisaddr == 1 && desiredaddr != 0)) {
2815				/*
2816				 * Peer's address is same as our value,
2817				 * or we have set it to 0.0.0.1 to
2818				 * indicate that we do not really care,
2819				 * this is agreeable.  Gonna conf-ack
2820				 * it.
2821				 */
2822				if (debug)
2823					log(-1, "%s [ack] ",
2824						sppp_dotted_quad(hisaddr));
2825				/* record that we've seen it already */
2826				sp->ipcp.flags |= IPCP_HISADDR_SEEN;
2827				continue;
2828			}
2829			/*
2830			 * The address wasn't agreeable.  This is either
2831			 * he sent us 0.0.0.0, asking to assign him an
2832			 * address, or he send us another address not
2833			 * matching our value.  Either case, we gonna
2834			 * conf-nak it with our value.
2835			 * XXX: we should "rej" if hisaddr == 0
2836			 */
2837			if (debug) {
2838				if (desiredaddr == 0)
2839					log(-1, "[addr requested] ");
2840				else
2841					log(-1, "%s [not agreed] ",
2842						sppp_dotted_quad(desiredaddr));
2843
2844			}
2845			p[2] = hisaddr >> 24;
2846			p[3] = hisaddr >> 16;
2847			p[4] = hisaddr >> 8;
2848			p[5] = hisaddr;
2849			break;
2850		}
2851		/* Add the option to nak'ed list. */
2852		bcopy (p, r, p[1]);
2853		r += p[1];
2854		rlen += p[1];
2855	}
2856
2857	/*
2858	 * If we are about to conf-ack the request, but haven't seen
2859	 * his address so far, gonna conf-nak it instead, with the
2860	 * `address' option present and our idea of his address being
2861	 * filled in there, to request negotiation of both addresses.
2862	 *
2863	 * XXX This can result in an endless req - nak loop if peer
2864	 * doesn't want to send us his address.  Q: What should we do
2865	 * about it?  XXX  A: implement the max-failure counter.
2866	 */
2867	if (rlen == 0 && !(sp->ipcp.flags & IPCP_HISADDR_SEEN) && !gotmyaddr) {
2868		buf[0] = IPCP_OPT_ADDRESS;
2869		buf[1] = 6;
2870		buf[2] = hisaddr >> 24;
2871		buf[3] = hisaddr >> 16;
2872		buf[4] = hisaddr >> 8;
2873		buf[5] = hisaddr;
2874		rlen = 6;
2875		if (debug)
2876			log(-1, "still need hisaddr ");
2877	}
2878
2879	if (rlen) {
2880		if (debug)
2881			log(-1, " send conf-nak\n");
2882		sppp_cp_send (sp, PPP_IPCP, CONF_NAK, h->ident, rlen, buf);
2883	} else {
2884		if (debug)
2885			log(-1, " send conf-ack\n");
2886		sppp_cp_send (sp, PPP_IPCP, CONF_ACK,
2887			      h->ident, origlen, h+1);
2888	}
2889
2890	free (buf, M_TEMP);
2891	return (rlen == 0);
2892}
2893
2894/*
2895 * Analyze the IPCP Configure-Reject option list, and adjust our
2896 * negotiation.
2897 */
2898static void
2899sppp_ipcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
2900{
2901	u_char *buf, *p;
2902	struct ifnet *ifp = &sp->pp_if;
2903	int debug = ifp->if_flags & IFF_DEBUG;
2904
2905	len -= 4;
2906	buf = malloc (len, M_TEMP, M_NOWAIT);
2907	if (!buf)
2908		return;
2909
2910	if (debug)
2911		log(LOG_DEBUG, SPP_FMT "ipcp rej opts: ",
2912		    SPP_ARGS(ifp));
2913
2914	p = (void*) (h+1);
2915	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2916		if (debug)
2917			log(-1, " %s ", sppp_ipcp_opt_name(*p));
2918		switch (*p) {
2919		case IPCP_OPT_ADDRESS:
2920			/*
2921			 * Peer doesn't grok address option.  This is
2922			 * bad.  XXX  Should we better give up here?
2923			 * XXX We could try old "addresses" option...
2924			 */
2925			sp->ipcp.opts &= ~(1 << IPCP_OPT_ADDRESS);
2926			break;
2927		}
2928	}
2929	if (debug)
2930		log(-1, "\n");
2931	free (buf, M_TEMP);
2932	return;
2933}
2934
2935/*
2936 * Analyze the IPCP Configure-NAK option list, and adjust our
2937 * negotiation.
2938 */
2939static void
2940sppp_ipcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
2941{
2942	u_char *buf, *p;
2943	struct ifnet *ifp = &sp->pp_if;
2944	int debug = ifp->if_flags & IFF_DEBUG;
2945	u_long wantaddr;
2946
2947	len -= 4;
2948	buf = malloc (len, M_TEMP, M_NOWAIT);
2949	if (!buf)
2950		return;
2951
2952	if (debug)
2953		log(LOG_DEBUG, SPP_FMT "ipcp nak opts: ",
2954		    SPP_ARGS(ifp));
2955
2956	p = (void*) (h+1);
2957	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2958		if (debug)
2959			log(-1, " %s ", sppp_ipcp_opt_name(*p));
2960		switch (*p) {
2961		case IPCP_OPT_ADDRESS:
2962			/*
2963			 * Peer doesn't like our local IP address.  See
2964			 * if we can do something for him.  We'll drop
2965			 * him our address then.
2966			 */
2967			if (len >= 6 && p[1] == 6) {
2968				wantaddr = p[2] << 24 | p[3] << 16 |
2969					p[4] << 8 | p[5];
2970				sp->ipcp.opts |= (1 << IPCP_OPT_ADDRESS);
2971				if (debug)
2972					log(-1, "[wantaddr %s] ",
2973					       sppp_dotted_quad(wantaddr));
2974				/*
2975				 * When doing dynamic address assignment,
2976				 * we accept his offer.  Otherwise, we
2977				 * ignore it and thus continue to negotiate
2978				 * our already existing value.
2979			 	 * XXX: Bogus, if he said no once, he'll
2980				 * just say no again, might as well die.
2981				 */
2982				if (sp->ipcp.flags & IPCP_MYADDR_DYN) {
2983					sppp_set_ip_addr(sp, wantaddr);
2984					if (debug)
2985						log(-1, "[agree] ");
2986					sp->ipcp.flags |= IPCP_MYADDR_SEEN;
2987				}
2988			}
2989			break;
2990		}
2991	}
2992	if (debug)
2993		log(-1, "\n");
2994	free (buf, M_TEMP);
2995	return;
2996}
2997
2998static void
2999sppp_ipcp_tlu(struct sppp *sp)
3000{
3001	/* we are up - notify isdn daemon */
3002	if (sp->pp_con)
3003		sp->pp_con(sp);
3004}
3005
3006static void
3007sppp_ipcp_tld(struct sppp *sp)
3008{
3009}
3010
3011static void
3012sppp_ipcp_tls(struct sppp *sp)
3013{
3014	/* indicate to LCP that it must stay alive */
3015	sp->lcp.protos |= (1 << IDX_IPCP);
3016}
3017
3018static void
3019sppp_ipcp_tlf(struct sppp *sp)
3020{
3021	/* we no longer need LCP */
3022	sp->lcp.protos &= ~(1 << IDX_IPCP);
3023	sppp_lcp_check_and_close(sp);
3024}
3025
3026static void
3027sppp_ipcp_scr(struct sppp *sp)
3028{
3029	char opt[6 /* compression */ + 6 /* address */];
3030	u_long ouraddr;
3031	int i = 0;
3032
3033	if (sp->ipcp.opts & (1 << IPCP_OPT_ADDRESS)) {
3034		sppp_get_ip_addrs(sp, &ouraddr, 0, 0);
3035		opt[i++] = IPCP_OPT_ADDRESS;
3036		opt[i++] = 6;
3037		opt[i++] = ouraddr >> 24;
3038		opt[i++] = ouraddr >> 16;
3039		opt[i++] = ouraddr >> 8;
3040		opt[i++] = ouraddr;
3041	}
3042
3043	sp->confid[IDX_IPCP] = ++sp->pp_seq[IDX_IPCP];
3044	sppp_cp_send(sp, PPP_IPCP, CONF_REQ, sp->confid[IDX_IPCP], i, &opt);
3045}
3046
3047/*
3048 *--------------------------------------------------------------------------*
3049 *                                                                          *
3050 *                      The IPv6CP implementation.                          *
3051 *                                                                          *
3052 *--------------------------------------------------------------------------*
3053 */
3054
3055#ifdef INET6
3056static void
3057sppp_ipv6cp_init(struct sppp *sp)
3058{
3059	sp->ipv6cp.opts = 0;
3060	sp->ipv6cp.flags = 0;
3061	sp->state[IDX_IPV6CP] = STATE_INITIAL;
3062	sp->fail_counter[IDX_IPV6CP] = 0;
3063	sp->pp_seq[IDX_IPV6CP] = 0;
3064	sp->pp_rseq[IDX_IPV6CP] = 0;
3065#if defined(__NetBSD__)
3066	callout_init(&sp->ch[IDX_IPV6CP]);
3067#endif
3068#if defined(__FreeBSD__) && __FreeBSD__ >= 3
3069	callout_handle_init(&sp->ch[IDX_IPV6CP]);
3070#endif
3071}
3072
3073static void
3074sppp_ipv6cp_up(struct sppp *sp)
3075{
3076	sppp_up_event(&ipv6cp, sp);
3077}
3078
3079static void
3080sppp_ipv6cp_down(struct sppp *sp)
3081{
3082	sppp_down_event(&ipv6cp, sp);
3083}
3084
3085static void
3086sppp_ipv6cp_open(struct sppp *sp)
3087{
3088	STDDCL;
3089	struct in6_addr myaddr, hisaddr;
3090
3091#ifdef IPV6CP_MYIFID_DYN
3092	sp->ipv6cp.flags &= ~(IPV6CP_MYIFID_SEEN|IPV6CP_MYIFID_DYN);
3093#else
3094	sp->ipv6cp.flags &= ~IPV6CP_MYIFID_SEEN;
3095#endif
3096
3097	sppp_get_ip6_addrs(sp, &myaddr, &hisaddr, 0);
3098	/*
3099	 * If we don't have our address, this probably means our
3100	 * interface doesn't want to talk IPv6 at all.  (This could
3101	 * be the case if somebody wants to speak only IPX, for
3102	 * example.)  Don't open IPv6CP in this case.
3103	 */
3104	if (IN6_IS_ADDR_UNSPECIFIED(&myaddr)) {
3105		/* XXX this message should go away */
3106		if (debug)
3107			log(LOG_DEBUG, SPP_FMT "ipv6cp_open(): no IPv6 interface\n",
3108			    SPP_ARGS(ifp));
3109		return;
3110	}
3111
3112	sp->ipv6cp.flags |= IPV6CP_MYIFID_SEEN;
3113	sp->ipv6cp.opts |= (1 << IPV6CP_OPT_IFID);
3114	sppp_open_event(&ipv6cp, sp);
3115}
3116
3117static void
3118sppp_ipv6cp_close(struct sppp *sp)
3119{
3120	sppp_close_event(&ipv6cp, sp);
3121}
3122
3123static void
3124sppp_ipv6cp_TO(void *cookie)
3125{
3126	sppp_to_event(&ipv6cp, (struct sppp *)cookie);
3127}
3128
3129/*
3130 * Analyze a configure request.  Return true if it was agreeable, and
3131 * caused action sca, false if it has been rejected or nak'ed, and
3132 * caused action scn.  (The return value is used to make the state
3133 * transition decision in the state automaton.)
3134 */
3135static int
3136sppp_ipv6cp_RCR(struct sppp *sp, struct lcp_header *h, int len)
3137{
3138	u_char *buf, *r, *p;
3139	struct ifnet *ifp = &sp->pp_if;
3140	int rlen, origlen, debug = ifp->if_flags & IFF_DEBUG;
3141	struct in6_addr myaddr, desiredaddr, suggestaddr;
3142	int ifidcount;
3143	int type;
3144	int collision, nohisaddr;
3145
3146	len -= 4;
3147	origlen = len;
3148	/*
3149	 * Make sure to allocate a buf that can at least hold a
3150	 * conf-nak with an `address' option.  We might need it below.
3151	 */
3152	buf = r = malloc ((len < 6? 6: len), M_TEMP, M_NOWAIT);
3153	if (! buf)
3154		return (0);
3155
3156	/* pass 1: see if we can recognize them */
3157	if (debug)
3158		log(LOG_DEBUG, SPP_FMT "ipv6cp parse opts:",
3159		    SPP_ARGS(ifp));
3160	p = (void*) (h+1);
3161	ifidcount = 0;
3162	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
3163		if (debug)
3164			log(-1, " %s", sppp_ipv6cp_opt_name(*p));
3165		switch (*p) {
3166		case IPV6CP_OPT_IFID:
3167			if (len >= 10 && p[1] == 10 && ifidcount == 0) {
3168				/* correctly formed address option */
3169				ifidcount++;
3170				continue;
3171			}
3172			if (debug)
3173				log(-1, " [invalid]");
3174			break;
3175#ifdef notyet
3176		case IPV6CP_OPT_COMPRESSION:
3177			if (len >= 4 && p[1] >= 4) {
3178				/* correctly formed compress option */
3179				continue;
3180			}
3181			if (debug)
3182				log(-1, " [invalid]");
3183			break;
3184#endif
3185		default:
3186			/* Others not supported. */
3187			if (debug)
3188				log(-1, " [rej]");
3189			break;
3190		}
3191		/* Add the option to rejected list. */
3192		bcopy (p, r, p[1]);
3193		r += p[1];
3194		rlen += p[1];
3195	}
3196	if (rlen) {
3197		if (debug)
3198			log(-1, " send conf-rej\n");
3199		sppp_cp_send (sp, PPP_IPV6CP, CONF_REJ, h->ident, rlen, buf);
3200		goto end;
3201	} else if (debug)
3202		log(-1, "\n");
3203
3204	/* pass 2: parse option values */
3205	sppp_get_ip6_addrs(sp, &myaddr, 0, 0);
3206	if (debug)
3207		log(LOG_DEBUG, SPP_FMT "ipv6cp parse opt values: ",
3208		    SPP_ARGS(ifp));
3209	p = (void*) (h+1);
3210	len = origlen;
3211	type = CONF_ACK;
3212	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
3213		if (debug)
3214			log(-1, " %s", sppp_ipv6cp_opt_name(*p));
3215		switch (*p) {
3216#ifdef notyet
3217		case IPV6CP_OPT_COMPRESSION:
3218			continue;
3219#endif
3220		case IPV6CP_OPT_IFID:
3221			bzero(&desiredaddr, sizeof(desiredaddr));
3222			bcopy(&p[2], &desiredaddr.s6_addr[8], 8);
3223			collision = (bcmp(&desiredaddr.s6_addr[8],
3224					  &myaddr.s6_addr[8], 8) == 0);
3225			nohisaddr = IN6_IS_ADDR_UNSPECIFIED(&desiredaddr);
3226
3227			desiredaddr.s6_addr16[0] = htons(0xfe80);
3228			desiredaddr.s6_addr16[1] = htons(sp->pp_if.if_index);
3229
3230			if (!collision && !nohisaddr) {
3231				/* no collision, hisaddr known - Conf-Ack */
3232				type = CONF_ACK;
3233
3234				if (debug) {
3235					log(-1, " %s [%s]",
3236					       ip6_sprintf(&desiredaddr),
3237					       sppp_cp_type_name(type));
3238				}
3239				continue;
3240			}
3241
3242			bzero(&suggestaddr, sizeof(&suggestaddr));
3243			if (collision && nohisaddr) {
3244				/* collision, hisaddr unknown - Conf-Rej */
3245				type = CONF_REJ;
3246				bzero(&p[2], 8);
3247			} else {
3248				/*
3249				 * - no collision, hisaddr unknown, or
3250				 * - collision, hisaddr known
3251				 * Conf-Nak, suggest hisaddr
3252				 */
3253				type = CONF_NAK;
3254				sppp_suggest_ip6_addr(sp, &suggestaddr);
3255				bcopy(&suggestaddr.s6_addr[8], &p[2], 8);
3256			}
3257			if (debug)
3258				log(-1, " %s [%s]", ip6_sprintf(&desiredaddr),
3259				       sppp_cp_type_name(type));
3260			break;
3261		}
3262		/* Add the option to nak'ed list. */
3263		bcopy (p, r, p[1]);
3264		r += p[1];
3265		rlen += p[1];
3266	}
3267
3268	if (rlen == 0 && type == CONF_ACK) {
3269		if (debug)
3270			log(-1, " send %s\n", sppp_cp_type_name(type));
3271		sppp_cp_send (sp, PPP_IPV6CP, type, h->ident, origlen, h+1);
3272	} else {
3273#ifdef DIAGNOSTIC
3274		if (type == CONF_ACK)
3275			panic("IPv6CP RCR: CONF_ACK with non-zero rlen");
3276#endif
3277
3278		if (debug) {
3279			log(-1, " send %s suggest %s\n",
3280			       sppp_cp_type_name(type), ip6_sprintf(&suggestaddr));
3281		}
3282		sppp_cp_send (sp, PPP_IPV6CP, type, h->ident, rlen, buf);
3283	}
3284
3285 end:
3286	free (buf, M_TEMP);
3287	return (rlen == 0);
3288}
3289
3290/*
3291 * Analyze the IPv6CP Configure-Reject option list, and adjust our
3292 * negotiation.
3293 */
3294static void
3295sppp_ipv6cp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
3296{
3297	u_char *buf, *p;
3298	struct ifnet *ifp = &sp->pp_if;
3299	int debug = ifp->if_flags & IFF_DEBUG;
3300
3301	len -= 4;
3302	buf = malloc (len, M_TEMP, M_NOWAIT);
3303	if (!buf)
3304		return;
3305
3306	if (debug)
3307		log(LOG_DEBUG, SPP_FMT "ipv6cp rej opts:",
3308		    SPP_ARGS(ifp));
3309
3310	p = (void*) (h+1);
3311	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
3312		if (debug)
3313			log(-1, " %s", sppp_ipv6cp_opt_name(*p));
3314		switch (*p) {
3315		case IPV6CP_OPT_IFID:
3316			/*
3317			 * Peer doesn't grok address option.  This is
3318			 * bad.  XXX  Should we better give up here?
3319			 */
3320			sp->ipv6cp.opts &= ~(1 << IPV6CP_OPT_IFID);
3321			break;
3322#ifdef notyet
3323		case IPV6CP_OPT_COMPRESS:
3324			sp->ipv6cp.opts &= ~(1 << IPV6CP_OPT_COMPRESS);
3325			break;
3326#endif
3327		}
3328	}
3329	if (debug)
3330		log(-1, "\n");
3331	free (buf, M_TEMP);
3332	return;
3333}
3334
3335/*
3336 * Analyze the IPv6CP Configure-NAK option list, and adjust our
3337 * negotiation.
3338 */
3339static void
3340sppp_ipv6cp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
3341{
3342	u_char *buf, *p;
3343	struct ifnet *ifp = &sp->pp_if;
3344	int debug = ifp->if_flags & IFF_DEBUG;
3345	struct in6_addr suggestaddr;
3346
3347	len -= 4;
3348	buf = malloc (len, M_TEMP, M_NOWAIT);
3349	if (!buf)
3350		return;
3351
3352	if (debug)
3353		log(LOG_DEBUG, SPP_FMT "ipv6cp nak opts:",
3354		    SPP_ARGS(ifp));
3355
3356	p = (void*) (h+1);
3357	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
3358		if (debug)
3359			log(-1, " %s", sppp_ipv6cp_opt_name(*p));
3360		switch (*p) {
3361		case IPV6CP_OPT_IFID:
3362			/*
3363			 * Peer doesn't like our local ifid.  See
3364			 * if we can do something for him.  We'll drop
3365			 * him our address then.
3366			 */
3367			if (len < 10 || p[1] != 10)
3368				break;
3369			bzero(&suggestaddr, sizeof(suggestaddr));
3370			suggestaddr.s6_addr16[0] = htons(0xfe80);
3371			suggestaddr.s6_addr16[1] = htons(sp->pp_if.if_index);
3372			bcopy(&p[2], &suggestaddr.s6_addr[8], 8);
3373
3374			sp->ipv6cp.opts |= (1 << IPV6CP_OPT_IFID);
3375			if (debug)
3376				log(-1, " [suggestaddr %s]",
3377				       ip6_sprintf(&suggestaddr));
3378#ifdef IPV6CP_MYIFID_DYN
3379			/*
3380			 * When doing dynamic address assignment,
3381			 * we accept his offer.
3382			 */
3383			if (sp->ipv6cp.flags & IPV6CP_MYIFID_DYN) {
3384				struct in6_addr lastsuggest;
3385				/*
3386				 * If <suggested myaddr from peer> equals to
3387				 * <hisaddr we have suggested last time>,
3388				 * we have a collision.  generate new random
3389				 * ifid.
3390				 */
3391				sppp_suggest_ip6_addr(&lastsuggest);
3392				if (IN6_ARE_ADDR_EQUAL(&suggestaddr,
3393						       lastsuggest)) {
3394					if (debug)
3395						log(-1, " [random]");
3396					sppp_gen_ip6_addr(sp, &suggestaddr);
3397				}
3398				sppp_set_ip6_addr(sp, &suggestaddr, 0);
3399				if (debug)
3400					log(-1, " [agree]");
3401				sp->ipv6cp.flags |= IPV6CP_MYIFID_SEEN;
3402			}
3403#else
3404			/*
3405			 * Since we do not do dynamic address assignment,
3406			 * we ignore it and thus continue to negotiate
3407			 * our already existing value.  This can possibly
3408			 * go into infinite request-reject loop.
3409			 *
3410			 * This is not likely because we normally use
3411			 * ifid based on MAC-address.
3412			 * If you have no ethernet card on the node, too bad.
3413			 * XXX should we use fail_counter?
3414			 */
3415#endif
3416			break;
3417#ifdef notyet
3418		case IPV6CP_OPT_COMPRESS:
3419			/*
3420			 * Peer wants different compression parameters.
3421			 */
3422			break;
3423#endif
3424		}
3425	}
3426	if (debug)
3427		log(-1, "\n");
3428	free (buf, M_TEMP);
3429	return;
3430}
3431static void
3432sppp_ipv6cp_tlu(struct sppp *sp)
3433{
3434	/* we are up - notify isdn daemon */
3435	if (sp->pp_con)
3436		sp->pp_con(sp);
3437}
3438
3439static void
3440sppp_ipv6cp_tld(struct sppp *sp)
3441{
3442}
3443
3444static void
3445sppp_ipv6cp_tls(struct sppp *sp)
3446{
3447	/* indicate to LCP that it must stay alive */
3448	sp->lcp.protos |= (1 << IDX_IPV6CP);
3449}
3450
3451static void
3452sppp_ipv6cp_tlf(struct sppp *sp)
3453{
3454
3455#if 0	/* need #if 0 to close IPv6CP properly */
3456	/* we no longer need LCP */
3457	sp->lcp.protos &= ~(1 << IDX_IPV6CP);
3458	sppp_lcp_check_and_close(sp);
3459#endif
3460}
3461
3462static void
3463sppp_ipv6cp_scr(struct sppp *sp)
3464{
3465	char opt[10 /* ifid */ + 4 /* compression, minimum */];
3466	struct in6_addr ouraddr;
3467	int i = 0;
3468
3469	if (sp->ipv6cp.opts & (1 << IPV6CP_OPT_IFID)) {
3470		sppp_get_ip6_addrs(sp, &ouraddr, 0, 0);
3471		opt[i++] = IPV6CP_OPT_IFID;
3472		opt[i++] = 10;
3473		bcopy(&ouraddr.s6_addr[8], &opt[i], 8);
3474		i += 8;
3475	}
3476
3477#ifdef notyet
3478	if (sp->ipv6cp.opts & (1 << IPV6CP_OPT_COMPRESSION)) {
3479		opt[i++] = IPV6CP_OPT_COMPRESSION;
3480		opt[i++] = 4;
3481		opt[i++] = 0;   /* TBD */
3482		opt[i++] = 0;   /* TBD */
3483		/* variable length data may follow */
3484	}
3485#endif
3486
3487	sp->confid[IDX_IPV6CP] = ++sp->pp_seq[IDX_IPV6CP];
3488	sppp_cp_send(sp, PPP_IPV6CP, CONF_REQ, sp->confid[IDX_IPV6CP], i, &opt);
3489}
3490#else /*INET6*/
3491static void sppp_ipv6cp_init(struct sppp *sp)
3492{
3493}
3494
3495static void sppp_ipv6cp_up(struct sppp *sp)
3496{
3497}
3498
3499static void sppp_ipv6cp_down(struct sppp *sp)
3500{
3501}
3502
3503
3504static void sppp_ipv6cp_open(struct sppp *sp)
3505{
3506}
3507
3508static void sppp_ipv6cp_close(struct sppp *sp)
3509{
3510}
3511
3512static void sppp_ipv6cp_TO(void *sp)
3513{
3514}
3515
3516static int sppp_ipv6cp_RCR(struct sppp *sp, struct lcp_header *h, int len)
3517{
3518	return 0;
3519}
3520
3521static void sppp_ipv6cp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
3522{
3523}
3524
3525static void sppp_ipv6cp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
3526{
3527}
3528
3529static void sppp_ipv6cp_tlu(struct sppp *sp)
3530{
3531}
3532
3533static void sppp_ipv6cp_tld(struct sppp *sp)
3534{
3535}
3536
3537static void sppp_ipv6cp_tls(struct sppp *sp)
3538{
3539}
3540
3541static void sppp_ipv6cp_tlf(struct sppp *sp)
3542{
3543}
3544
3545static void sppp_ipv6cp_scr(struct sppp *sp)
3546{
3547}
3548#endif /*INET6*/
3549
3550/*
3551 *--------------------------------------------------------------------------*
3552 *                                                                          *
3553 *                        The CHAP implementation.                          *
3554 *                                                                          *
3555 *--------------------------------------------------------------------------*
3556 */
3557
3558/*
3559 * The authentication protocols don't employ a full-fledged state machine as
3560 * the control protocols do, since they do have Open and Close events, but
3561 * not Up and Down, nor are they explicitly terminated.  Also, use of the
3562 * authentication protocols may be different in both directions (this makes
3563 * sense, think of a machine that never accepts incoming calls but only
3564 * calls out, it doesn't require the called party to authenticate itself).
3565 *
3566 * Our state machine for the local authentication protocol (we are requesting
3567 * the peer to authenticate) looks like:
3568 *
3569 *						    RCA-
3570 *	      +--------------------------------------------+
3571 *	      V					    scn,tld|
3572 *	  +--------+			       Close   +---------+ RCA+
3573 *	  |	   |<----------------------------------|	 |------+
3574 *   +--->| Closed |				TO*    | Opened	 | sca	|
3575 *   |	  |	   |-----+		       +-------|	 |<-----+
3576 *   |	  +--------+ irc |		       |       +---------+
3577 *   |	    ^		 |		       |	   ^
3578 *   |	    |		 |		       |	   |
3579 *   |	    |		 |		       |	   |
3580 *   |	 TO-|		 |		       |	   |
3581 *   |	    |tld  TO+	 V		       |	   |
3582 *   |	    |	+------->+		       |	   |
3583 *   |	    |	|	 |		       |	   |
3584 *   |	  +--------+	 V		       |	   |
3585 *   |	  |	   |<----+<--------------------+	   |
3586 *   |	  | Req-   | scr				   |
3587 *   |	  | Sent   |					   |
3588 *   |	  |	   |					   |
3589 *   |	  +--------+					   |
3590 *   | RCA- |	| RCA+					   |
3591 *   +------+	+------------------------------------------+
3592 *   scn,tld	  sca,irc,ict,tlu
3593 *
3594 *
3595 *   with:
3596 *
3597 *	Open:	LCP reached authentication phase
3598 *	Close:	LCP reached terminate phase
3599 *
3600 *	RCA+:	received reply (pap-req, chap-response), acceptable
3601 *	RCN:	received reply (pap-req, chap-response), not acceptable
3602 *	TO+:	timeout with restart counter >= 0
3603 *	TO-:	timeout with restart counter < 0
3604 *	TO*:	reschedule timeout for CHAP
3605 *
3606 *	scr:	send request packet (none for PAP, chap-challenge)
3607 *	sca:	send ack packet (pap-ack, chap-success)
3608 *	scn:	send nak packet (pap-nak, chap-failure)
3609 *	ict:	initialize re-challenge timer (CHAP only)
3610 *
3611 *	tlu:	this-layer-up, LCP reaches network phase
3612 *	tld:	this-layer-down, LCP enters terminate phase
3613 *
3614 * Note that in CHAP mode, after sending a new challenge, while the state
3615 * automaton falls back into Req-Sent state, it doesn't signal a tld
3616 * event to LCP, so LCP remains in network phase.  Only after not getting
3617 * any response (or after getting an unacceptable response), CHAP closes,
3618 * causing LCP to enter terminate phase.
3619 *
3620 * With PAP, there is no initial request that can be sent.  The peer is
3621 * expected to send one based on the successful negotiation of PAP as
3622 * the authentication protocol during the LCP option negotiation.
3623 *
3624 * Incoming authentication protocol requests (remote requests
3625 * authentication, we are peer) don't employ a state machine at all,
3626 * they are simply answered.  Some peers [Ascend P50 firmware rev
3627 * 4.50] react allergically when sending IPCP requests while they are
3628 * still in authentication phase (thereby violating the standard that
3629 * demands that these NCP packets are to be discarded), so we keep
3630 * track of the peer demanding us to authenticate, and only proceed to
3631 * phase network once we've seen a positive acknowledge for the
3632 * authentication.
3633 */
3634
3635/*
3636 * Handle incoming CHAP packets.
3637 */
3638void
3639sppp_chap_input(struct sppp *sp, struct mbuf *m)
3640{
3641	STDDCL;
3642	struct lcp_header *h;
3643	int len, x;
3644	u_char *value, *name, digest[AUTHKEYLEN], dsize;
3645	int value_len, name_len;
3646	MD5_CTX ctx;
3647
3648	len = m->m_pkthdr.len;
3649	if (len < 4) {
3650		if (debug)
3651			log(LOG_DEBUG,
3652			    SPP_FMT "chap invalid packet length: %d bytes\n",
3653			    SPP_ARGS(ifp), len);
3654		return;
3655	}
3656	h = mtod (m, struct lcp_header*);
3657	if (len > ntohs (h->len))
3658		len = ntohs (h->len);
3659
3660	switch (h->type) {
3661	/* challenge, failure and success are his authproto */
3662	case CHAP_CHALLENGE:
3663		value = 1 + (u_char*)(h+1);
3664		value_len = value[-1];
3665		name = value + value_len;
3666		name_len = len - value_len - 5;
3667		if (name_len < 0) {
3668			if (debug) {
3669				log(LOG_DEBUG,
3670				    SPP_FMT "chap corrupted challenge "
3671				    "<%s id=0x%x len=%d",
3672				    SPP_ARGS(ifp),
3673				    sppp_auth_type_name(PPP_CHAP, h->type),
3674				    h->ident, ntohs(h->len));
3675				sppp_print_bytes((u_char*) (h+1), len-4);
3676				log(-1, ">\n");
3677			}
3678			break;
3679		}
3680
3681		if (debug) {
3682			log(LOG_DEBUG,
3683			    SPP_FMT "chap input <%s id=0x%x len=%d name=",
3684			    SPP_ARGS(ifp),
3685			    sppp_auth_type_name(PPP_CHAP, h->type), h->ident,
3686			    ntohs(h->len));
3687			sppp_print_string((char*) name, name_len);
3688			log(-1, " value-size=%d value=", value_len);
3689			sppp_print_bytes(value, value_len);
3690			log(-1, ">\n");
3691		}
3692
3693		/* Compute reply value. */
3694		MD5Init(&ctx);
3695		MD5Update(&ctx, &h->ident, 1);
3696		MD5Update(&ctx, sp->myauth.secret,
3697			  sppp_strnlen(sp->myauth.secret, AUTHKEYLEN));
3698		MD5Update(&ctx, value, value_len);
3699		MD5Final(digest, &ctx);
3700		dsize = sizeof digest;
3701
3702		sppp_auth_send(&chap, sp, CHAP_RESPONSE, h->ident,
3703			       sizeof dsize, (const char *)&dsize,
3704			       sizeof digest, digest,
3705			       (size_t)sppp_strnlen(sp->myauth.name, AUTHNAMELEN),
3706			       sp->myauth.name,
3707			       0);
3708		break;
3709
3710	case CHAP_SUCCESS:
3711		if (debug) {
3712			log(LOG_DEBUG, SPP_FMT "chap success",
3713			    SPP_ARGS(ifp));
3714			if (len > 4) {
3715				log(-1, ": ");
3716				sppp_print_string((char*)(h + 1), len - 4);
3717			}
3718			log(-1, "\n");
3719		}
3720		x = splimp();
3721		sp->pp_flags &= ~PP_NEEDAUTH;
3722		if (sp->myauth.proto == PPP_CHAP &&
3723		    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) &&
3724		    (sp->lcp.protos & (1 << IDX_CHAP)) == 0) {
3725			/*
3726			 * We are authenticator for CHAP but didn't
3727			 * complete yet.  Leave it to tlu to proceed
3728			 * to network phase.
3729			 */
3730			splx(x);
3731			break;
3732		}
3733		splx(x);
3734		sppp_phase_network(sp);
3735		break;
3736
3737	case CHAP_FAILURE:
3738		if (debug) {
3739			log(LOG_INFO, SPP_FMT "chap failure",
3740			    SPP_ARGS(ifp));
3741			if (len > 4) {
3742				log(-1, ": ");
3743				sppp_print_string((char*)(h + 1), len - 4);
3744			}
3745			log(-1, "\n");
3746		} else
3747			log(LOG_INFO, SPP_FMT "chap failure\n",
3748			    SPP_ARGS(ifp));
3749		/* await LCP shutdown by authenticator */
3750		break;
3751
3752	/* response is my authproto */
3753	case CHAP_RESPONSE:
3754		value = 1 + (u_char*)(h+1);
3755		value_len = value[-1];
3756		name = value + value_len;
3757		name_len = len - value_len - 5;
3758		if (name_len < 0) {
3759			if (debug) {
3760				log(LOG_DEBUG,
3761				    SPP_FMT "chap corrupted response "
3762				    "<%s id=0x%x len=%d",
3763				    SPP_ARGS(ifp),
3764				    sppp_auth_type_name(PPP_CHAP, h->type),
3765				    h->ident, ntohs(h->len));
3766				sppp_print_bytes((u_char*)(h+1), len-4);
3767				log(-1, ">\n");
3768			}
3769			break;
3770		}
3771		if (h->ident != sp->confid[IDX_CHAP]) {
3772			if (debug)
3773				log(LOG_DEBUG,
3774				    SPP_FMT "chap dropping response for old ID "
3775				    "(got %d, expected %d)\n",
3776				    SPP_ARGS(ifp),
3777				    h->ident, sp->confid[IDX_CHAP]);
3778			break;
3779		}
3780		if (name_len != sppp_strnlen(sp->hisauth.name, AUTHNAMELEN)
3781		    || bcmp(name, sp->hisauth.name, name_len) != 0) {
3782			log(LOG_INFO, SPP_FMT "chap response, his name ",
3783			    SPP_ARGS(ifp));
3784			sppp_print_string(name, name_len);
3785			log(-1, " != expected ");
3786			sppp_print_string(sp->hisauth.name,
3787					  sppp_strnlen(sp->hisauth.name, AUTHNAMELEN));
3788			log(-1, "\n");
3789		}
3790		if (debug) {
3791			log(LOG_DEBUG, SPP_FMT "chap input(%s) "
3792			    "<%s id=0x%x len=%d name=",
3793			    SPP_ARGS(ifp),
3794			    sppp_state_name(sp->state[IDX_CHAP]),
3795			    sppp_auth_type_name(PPP_CHAP, h->type),
3796			    h->ident, ntohs (h->len));
3797			sppp_print_string((char*)name, name_len);
3798			log(-1, " value-size=%d value=", value_len);
3799			sppp_print_bytes(value, value_len);
3800			log(-1, ">\n");
3801		}
3802		if (value_len != AUTHKEYLEN) {
3803			if (debug)
3804				log(LOG_DEBUG,
3805				    SPP_FMT "chap bad hash value length: "
3806				    "%d bytes, should be %d\n",
3807				    SPP_ARGS(ifp), value_len,
3808				    AUTHKEYLEN);
3809			break;
3810		}
3811
3812		MD5Init(&ctx);
3813		MD5Update(&ctx, &h->ident, 1);
3814		MD5Update(&ctx, sp->hisauth.secret,
3815			  sppp_strnlen(sp->hisauth.secret, AUTHKEYLEN));
3816		MD5Update(&ctx, sp->myauth.challenge, AUTHKEYLEN);
3817		MD5Final(digest, &ctx);
3818
3819#define FAILMSG "Failed..."
3820#define SUCCMSG "Welcome!"
3821
3822		if (value_len != sizeof digest ||
3823		    bcmp(digest, value, value_len) != 0) {
3824			/* action scn, tld */
3825			sppp_auth_send(&chap, sp, CHAP_FAILURE, h->ident,
3826				       sizeof(FAILMSG) - 1, (u_char *)FAILMSG,
3827				       0);
3828			chap.tld(sp);
3829			break;
3830		}
3831		/* action sca, perhaps tlu */
3832		if (sp->state[IDX_CHAP] == STATE_REQ_SENT ||
3833		    sp->state[IDX_CHAP] == STATE_OPENED)
3834			sppp_auth_send(&chap, sp, CHAP_SUCCESS, h->ident,
3835				       sizeof(SUCCMSG) - 1, (u_char *)SUCCMSG,
3836				       0);
3837		if (sp->state[IDX_CHAP] == STATE_REQ_SENT) {
3838			sppp_cp_change_state(&chap, sp, STATE_OPENED);
3839			chap.tlu(sp);
3840		}
3841		break;
3842
3843	default:
3844		/* Unknown CHAP packet type -- ignore. */
3845		if (debug) {
3846			log(LOG_DEBUG, SPP_FMT "chap unknown input(%s) "
3847			    "<0x%x id=0x%xh len=%d",
3848			    SPP_ARGS(ifp),
3849			    sppp_state_name(sp->state[IDX_CHAP]),
3850			    h->type, h->ident, ntohs(h->len));
3851			sppp_print_bytes((u_char*)(h+1), len-4);
3852			log(-1, ">\n");
3853		}
3854		break;
3855
3856	}
3857}
3858
3859static void
3860sppp_chap_init(struct sppp *sp)
3861{
3862	/* Chap doesn't have STATE_INITIAL at all. */
3863	sp->state[IDX_CHAP] = STATE_CLOSED;
3864	sp->fail_counter[IDX_CHAP] = 0;
3865	sp->pp_seq[IDX_CHAP] = 0;
3866	sp->pp_rseq[IDX_CHAP] = 0;
3867#if defined(__FreeBSD__) && __FreeBSD__ >= 3
3868	callout_handle_init(&sp->ch[IDX_CHAP]);
3869#endif
3870}
3871
3872static void
3873sppp_chap_open(struct sppp *sp)
3874{
3875	if (sp->myauth.proto == PPP_CHAP &&
3876	    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0) {
3877		/* we are authenticator for CHAP, start it */
3878		chap.scr(sp);
3879		sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3880		sppp_cp_change_state(&chap, sp, STATE_REQ_SENT);
3881	}
3882	/* nothing to be done if we are peer, await a challenge */
3883}
3884
3885static void
3886sppp_chap_close(struct sppp *sp)
3887{
3888	if (sp->state[IDX_CHAP] != STATE_CLOSED)
3889		sppp_cp_change_state(&chap, sp, STATE_CLOSED);
3890}
3891
3892static void
3893sppp_chap_TO(void *cookie)
3894{
3895	struct sppp *sp = (struct sppp *)cookie;
3896	STDDCL;
3897	int s;
3898
3899	s = splimp();
3900	if (debug)
3901		log(LOG_DEBUG, SPP_FMT "chap TO(%s) rst_counter = %d\n",
3902		    SPP_ARGS(ifp),
3903		    sppp_state_name(sp->state[IDX_CHAP]),
3904		    sp->rst_counter[IDX_CHAP]);
3905
3906	if (--sp->rst_counter[IDX_CHAP] < 0)
3907		/* TO- event */
3908		switch (sp->state[IDX_CHAP]) {
3909		case STATE_REQ_SENT:
3910			chap.tld(sp);
3911			sppp_cp_change_state(&chap, sp, STATE_CLOSED);
3912			break;
3913		}
3914	else
3915		/* TO+ (or TO*) event */
3916		switch (sp->state[IDX_CHAP]) {
3917		case STATE_OPENED:
3918			/* TO* event */
3919			sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3920			/* fall through */
3921		case STATE_REQ_SENT:
3922			chap.scr(sp);
3923			/* sppp_cp_change_state() will restart the timer */
3924			sppp_cp_change_state(&chap, sp, STATE_REQ_SENT);
3925			break;
3926		}
3927
3928	splx(s);
3929}
3930
3931static void
3932sppp_chap_tlu(struct sppp *sp)
3933{
3934	STDDCL;
3935	int i, x;
3936
3937	i = 0;
3938	sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3939
3940	/*
3941	 * Some broken CHAP implementations (Conware CoNet, firmware
3942	 * 4.0.?) don't want to re-authenticate their CHAP once the
3943	 * initial challenge-response exchange has taken place.
3944	 * Provide for an option to avoid rechallenges.
3945	 */
3946	if ((sp->hisauth.flags & AUTHFLAG_NORECHALLENGE) == 0) {
3947		/*
3948		 * Compute the re-challenge timeout.  This will yield
3949		 * a number between 300 and 810 seconds.
3950		 */
3951		i = 300 + ((unsigned)(random() & 0xff00) >> 7);
3952		TIMEOUT(chap.TO, (void *)sp, i * hz, sp->ch[IDX_CHAP]);
3953	}
3954
3955	if (debug) {
3956		log(LOG_DEBUG,
3957		    SPP_FMT "chap %s, ",
3958		    SPP_ARGS(ifp),
3959		    sp->pp_phase == PHASE_NETWORK? "reconfirmed": "tlu");
3960		if ((sp->hisauth.flags & AUTHFLAG_NORECHALLENGE) == 0)
3961			log(-1, "next re-challenge in %d seconds\n", i);
3962		else
3963			log(-1, "re-challenging supressed\n");
3964	}
3965
3966	x = splimp();
3967	/* indicate to LCP that we need to be closed down */
3968	sp->lcp.protos |= (1 << IDX_CHAP);
3969
3970	if (sp->pp_flags & PP_NEEDAUTH) {
3971		/*
3972		 * Remote is authenticator, but his auth proto didn't
3973		 * complete yet.  Defer the transition to network
3974		 * phase.
3975		 */
3976		splx(x);
3977		return;
3978	}
3979	splx(x);
3980
3981	/*
3982	 * If we are already in phase network, we are done here.  This
3983	 * is the case if this is a dummy tlu event after a re-challenge.
3984	 */
3985	if (sp->pp_phase != PHASE_NETWORK)
3986		sppp_phase_network(sp);
3987}
3988
3989static void
3990sppp_chap_tld(struct sppp *sp)
3991{
3992	STDDCL;
3993
3994	if (debug)
3995		log(LOG_DEBUG, SPP_FMT "chap tld\n", SPP_ARGS(ifp));
3996	UNTIMEOUT(chap.TO, (void *)sp, sp->ch[IDX_CHAP]);
3997	sp->lcp.protos &= ~(1 << IDX_CHAP);
3998
3999	lcp.Close(sp);
4000}
4001
4002static void
4003sppp_chap_scr(struct sppp *sp)
4004{
4005	u_long *ch, seed;
4006	u_char clen;
4007
4008	/* Compute random challenge. */
4009	ch = (u_long *)sp->myauth.challenge;
4010#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4011	read_random(&seed, sizeof seed);
4012#else
4013	{
4014	struct timeval tv;
4015	microtime(&tv);
4016	seed = tv.tv_sec ^ tv.tv_usec;
4017	}
4018#endif
4019	ch[0] = seed ^ random();
4020	ch[1] = seed ^ random();
4021	ch[2] = seed ^ random();
4022	ch[3] = seed ^ random();
4023	clen = AUTHKEYLEN;
4024
4025	sp->confid[IDX_CHAP] = ++sp->pp_seq[IDX_CHAP];
4026
4027	sppp_auth_send(&chap, sp, CHAP_CHALLENGE, sp->confid[IDX_CHAP],
4028		       sizeof clen, (const char *)&clen,
4029		       (size_t)AUTHKEYLEN, sp->myauth.challenge,
4030		       (size_t)sppp_strnlen(sp->myauth.name, AUTHNAMELEN),
4031		       sp->myauth.name,
4032		       0);
4033}
4034
4035/*
4036 *--------------------------------------------------------------------------*
4037 *                                                                          *
4038 *                        The PAP implementation.                           *
4039 *                                                                          *
4040 *--------------------------------------------------------------------------*
4041 */
4042/*
4043 * For PAP, we need to keep a little state also if we are the peer, not the
4044 * authenticator.  This is since we don't get a request to authenticate, but
4045 * have to repeatedly authenticate ourself until we got a response (or the
4046 * retry counter is expired).
4047 */
4048
4049/*
4050 * Handle incoming PAP packets.  */
4051static void
4052sppp_pap_input(struct sppp *sp, struct mbuf *m)
4053{
4054	STDDCL;
4055	struct lcp_header *h;
4056	int len, x;
4057	u_char *name, *passwd, mlen;
4058	int name_len, passwd_len;
4059
4060	len = m->m_pkthdr.len;
4061	if (len < 5) {
4062		if (debug)
4063			log(LOG_DEBUG,
4064			    SPP_FMT "pap invalid packet length: %d bytes\n",
4065			    SPP_ARGS(ifp), len);
4066		return;
4067	}
4068	h = mtod (m, struct lcp_header*);
4069	if (len > ntohs (h->len))
4070		len = ntohs (h->len);
4071	switch (h->type) {
4072	/* PAP request is my authproto */
4073	case PAP_REQ:
4074		name = 1 + (u_char*)(h+1);
4075		name_len = name[-1];
4076		passwd = name + name_len + 1;
4077		if (name_len > len - 6 ||
4078		    (passwd_len = passwd[-1]) > len - 6 - name_len) {
4079			if (debug) {
4080				log(LOG_DEBUG, SPP_FMT "pap corrupted input "
4081				    "<%s id=0x%x len=%d",
4082				    SPP_ARGS(ifp),
4083				    sppp_auth_type_name(PPP_PAP, h->type),
4084				    h->ident, ntohs(h->len));
4085				sppp_print_bytes((u_char*)(h+1), len-4);
4086				log(-1, ">\n");
4087			}
4088			break;
4089		}
4090		if (debug) {
4091			log(LOG_DEBUG, SPP_FMT "pap input(%s) "
4092			    "<%s id=0x%x len=%d name=",
4093			    SPP_ARGS(ifp),
4094			    sppp_state_name(sp->state[IDX_PAP]),
4095			    sppp_auth_type_name(PPP_PAP, h->type),
4096			    h->ident, ntohs(h->len));
4097			sppp_print_string((char*)name, name_len);
4098			log(-1, " passwd=");
4099			sppp_print_string((char*)passwd, passwd_len);
4100			log(-1, ">\n");
4101		}
4102		if (name_len != sppp_strnlen(sp->hisauth.name, AUTHNAMELEN) ||
4103		    passwd_len != sppp_strnlen(sp->hisauth.secret, AUTHKEYLEN) ||
4104		    bcmp(name, sp->hisauth.name, name_len) != 0 ||
4105		    bcmp(passwd, sp->hisauth.secret, passwd_len) != 0) {
4106			/* action scn, tld */
4107			mlen = sizeof(FAILMSG) - 1;
4108			sppp_auth_send(&pap, sp, PAP_NAK, h->ident,
4109				       sizeof mlen, (const char *)&mlen,
4110				       sizeof(FAILMSG) - 1, (u_char *)FAILMSG,
4111				       0);
4112			pap.tld(sp);
4113			break;
4114		}
4115		/* action sca, perhaps tlu */
4116		if (sp->state[IDX_PAP] == STATE_REQ_SENT ||
4117		    sp->state[IDX_PAP] == STATE_OPENED) {
4118			mlen = sizeof(SUCCMSG) - 1;
4119			sppp_auth_send(&pap, sp, PAP_ACK, h->ident,
4120				       sizeof mlen, (const char *)&mlen,
4121				       sizeof(SUCCMSG) - 1, (u_char *)SUCCMSG,
4122				       0);
4123		}
4124		if (sp->state[IDX_PAP] == STATE_REQ_SENT) {
4125			sppp_cp_change_state(&pap, sp, STATE_OPENED);
4126			pap.tlu(sp);
4127		}
4128		break;
4129
4130	/* ack and nak are his authproto */
4131	case PAP_ACK:
4132		UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
4133		if (debug) {
4134			log(LOG_DEBUG, SPP_FMT "pap success",
4135			    SPP_ARGS(ifp));
4136			name_len = *((char *)h);
4137			if (len > 5 && name_len) {
4138				log(-1, ": ");
4139				sppp_print_string((char*)(h+1), name_len);
4140			}
4141			log(-1, "\n");
4142		}
4143		x = splimp();
4144		sp->pp_flags &= ~PP_NEEDAUTH;
4145		if (sp->myauth.proto == PPP_PAP &&
4146		    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) &&
4147		    (sp->lcp.protos & (1 << IDX_PAP)) == 0) {
4148			/*
4149			 * We are authenticator for PAP but didn't
4150			 * complete yet.  Leave it to tlu to proceed
4151			 * to network phase.
4152			 */
4153			splx(x);
4154			break;
4155		}
4156		splx(x);
4157		sppp_phase_network(sp);
4158		break;
4159
4160	case PAP_NAK:
4161		UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
4162		if (debug) {
4163			log(LOG_INFO, SPP_FMT "pap failure",
4164			    SPP_ARGS(ifp));
4165			name_len = *((char *)h);
4166			if (len > 5 && name_len) {
4167				log(-1, ": ");
4168				sppp_print_string((char*)(h+1), name_len);
4169			}
4170			log(-1, "\n");
4171		} else
4172			log(LOG_INFO, SPP_FMT "pap failure\n",
4173			    SPP_ARGS(ifp));
4174		/* await LCP shutdown by authenticator */
4175		break;
4176
4177	default:
4178		/* Unknown PAP packet type -- ignore. */
4179		if (debug) {
4180			log(LOG_DEBUG, SPP_FMT "pap corrupted input "
4181			    "<0x%x id=0x%x len=%d",
4182			    SPP_ARGS(ifp),
4183			    h->type, h->ident, ntohs(h->len));
4184			sppp_print_bytes((u_char*)(h+1), len-4);
4185			log(-1, ">\n");
4186		}
4187		break;
4188
4189	}
4190}
4191
4192static void
4193sppp_pap_init(struct sppp *sp)
4194{
4195	/* PAP doesn't have STATE_INITIAL at all. */
4196	sp->state[IDX_PAP] = STATE_CLOSED;
4197	sp->fail_counter[IDX_PAP] = 0;
4198	sp->pp_seq[IDX_PAP] = 0;
4199	sp->pp_rseq[IDX_PAP] = 0;
4200#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4201	callout_handle_init(&sp->ch[IDX_PAP]);
4202	callout_handle_init(&sp->pap_my_to_ch);
4203#endif
4204}
4205
4206static void
4207sppp_pap_open(struct sppp *sp)
4208{
4209	if (sp->hisauth.proto == PPP_PAP &&
4210	    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0) {
4211		/* we are authenticator for PAP, start our timer */
4212		sp->rst_counter[IDX_PAP] = sp->lcp.max_configure;
4213		sppp_cp_change_state(&pap, sp, STATE_REQ_SENT);
4214	}
4215	if (sp->myauth.proto == PPP_PAP) {
4216		/* we are peer, send a request, and start a timer */
4217		pap.scr(sp);
4218		TIMEOUT(sppp_pap_my_TO, (void *)sp, sp->lcp.timeout,
4219		    sp->pap_my_to_ch);
4220	}
4221}
4222
4223static void
4224sppp_pap_close(struct sppp *sp)
4225{
4226	if (sp->state[IDX_PAP] != STATE_CLOSED)
4227		sppp_cp_change_state(&pap, sp, STATE_CLOSED);
4228}
4229
4230/*
4231 * That's the timeout routine if we are authenticator.  Since the
4232 * authenticator is basically passive in PAP, we can't do much here.
4233 */
4234static void
4235sppp_pap_TO(void *cookie)
4236{
4237	struct sppp *sp = (struct sppp *)cookie;
4238	STDDCL;
4239	int s;
4240
4241	s = splimp();
4242	if (debug)
4243		log(LOG_DEBUG, SPP_FMT "pap TO(%s) rst_counter = %d\n",
4244		    SPP_ARGS(ifp),
4245		    sppp_state_name(sp->state[IDX_PAP]),
4246		    sp->rst_counter[IDX_PAP]);
4247
4248	if (--sp->rst_counter[IDX_PAP] < 0)
4249		/* TO- event */
4250		switch (sp->state[IDX_PAP]) {
4251		case STATE_REQ_SENT:
4252			pap.tld(sp);
4253			sppp_cp_change_state(&pap, sp, STATE_CLOSED);
4254			break;
4255		}
4256	else
4257		/* TO+ event, not very much we could do */
4258		switch (sp->state[IDX_PAP]) {
4259		case STATE_REQ_SENT:
4260			/* sppp_cp_change_state() will restart the timer */
4261			sppp_cp_change_state(&pap, sp, STATE_REQ_SENT);
4262			break;
4263		}
4264
4265	splx(s);
4266}
4267
4268/*
4269 * That's the timeout handler if we are peer.  Since the peer is active,
4270 * we need to retransmit our PAP request since it is apparently lost.
4271 * XXX We should impose a max counter.
4272 */
4273static void
4274sppp_pap_my_TO(void *cookie)
4275{
4276	struct sppp *sp = (struct sppp *)cookie;
4277	STDDCL;
4278
4279	if (debug)
4280		log(LOG_DEBUG, SPP_FMT "pap peer TO\n",
4281		    SPP_ARGS(ifp));
4282
4283	pap.scr(sp);
4284}
4285
4286static void
4287sppp_pap_tlu(struct sppp *sp)
4288{
4289	STDDCL;
4290	int x;
4291
4292	sp->rst_counter[IDX_PAP] = sp->lcp.max_configure;
4293
4294	if (debug)
4295		log(LOG_DEBUG, SPP_FMT "%s tlu\n",
4296		    SPP_ARGS(ifp), pap.name);
4297
4298	x = splimp();
4299	/* indicate to LCP that we need to be closed down */
4300	sp->lcp.protos |= (1 << IDX_PAP);
4301
4302	if (sp->pp_flags & PP_NEEDAUTH) {
4303		/*
4304		 * Remote is authenticator, but his auth proto didn't
4305		 * complete yet.  Defer the transition to network
4306		 * phase.
4307		 */
4308		splx(x);
4309		return;
4310	}
4311	splx(x);
4312	sppp_phase_network(sp);
4313}
4314
4315static void
4316sppp_pap_tld(struct sppp *sp)
4317{
4318	STDDCL;
4319
4320	if (debug)
4321		log(LOG_DEBUG, SPP_FMT "pap tld\n", SPP_ARGS(ifp));
4322	UNTIMEOUT(pap.TO, (void *)sp, sp->ch[IDX_PAP]);
4323	UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
4324	sp->lcp.protos &= ~(1 << IDX_PAP);
4325
4326	lcp.Close(sp);
4327}
4328
4329static void
4330sppp_pap_scr(struct sppp *sp)
4331{
4332	u_char idlen, pwdlen;
4333
4334	sp->confid[IDX_PAP] = ++sp->pp_seq[IDX_PAP];
4335	pwdlen = sppp_strnlen(sp->myauth.secret, AUTHKEYLEN);
4336	idlen = sppp_strnlen(sp->myauth.name, AUTHNAMELEN);
4337
4338	sppp_auth_send(&pap, sp, PAP_REQ, sp->confid[IDX_PAP],
4339		       sizeof idlen, (const char *)&idlen,
4340		       (size_t)idlen, sp->myauth.name,
4341		       sizeof pwdlen, (const char *)&pwdlen,
4342		       (size_t)pwdlen, sp->myauth.secret,
4343		       0);
4344}
4345
4346/*
4347 * Random miscellaneous functions.
4348 */
4349
4350/*
4351 * Send a PAP or CHAP proto packet.
4352 *
4353 * Varadic function, each of the elements for the ellipsis is of type
4354 * ``size_t mlen, const u_char *msg''.  Processing will stop iff
4355 * mlen == 0.
4356 * NOTE: never declare variadic functions with types subject to type
4357 * promotion (i.e. u_char). This is asking for big trouble depending
4358 * on the architecture you are on...
4359 */
4360
4361static void
4362sppp_auth_send(const struct cp *cp, struct sppp *sp,
4363               unsigned int type, unsigned int id,
4364	       ...)
4365{
4366	STDDCL;
4367	struct ppp_header *h;
4368	struct lcp_header *lh;
4369	struct mbuf *m;
4370	u_char *p;
4371	int len;
4372	unsigned int mlen;
4373	const char *msg;
4374	va_list ap;
4375
4376	MGETHDR (m, M_DONTWAIT, MT_DATA);
4377	if (! m)
4378		return;
4379	m->m_pkthdr.rcvif = 0;
4380
4381	h = mtod (m, struct ppp_header*);
4382	h->address = PPP_ALLSTATIONS;		/* broadcast address */
4383	h->control = PPP_UI;			/* Unnumbered Info */
4384	h->protocol = htons(cp->proto);
4385
4386	lh = (struct lcp_header*)(h + 1);
4387	lh->type = type;
4388	lh->ident = id;
4389	p = (u_char*) (lh+1);
4390
4391	va_start(ap, id);
4392	len = 0;
4393
4394	while ((mlen = (unsigned int)va_arg(ap, size_t)) != 0) {
4395		msg = va_arg(ap, const char *);
4396		len += mlen;
4397		if (len > MHLEN - PPP_HEADER_LEN - LCP_HEADER_LEN) {
4398			va_end(ap);
4399			m_freem(m);
4400			return;
4401		}
4402
4403		bcopy(msg, p, mlen);
4404		p += mlen;
4405	}
4406	va_end(ap);
4407
4408	m->m_pkthdr.len = m->m_len = PPP_HEADER_LEN + LCP_HEADER_LEN + len;
4409	lh->len = htons (LCP_HEADER_LEN + len);
4410
4411	if (debug) {
4412		log(LOG_DEBUG, SPP_FMT "%s output <%s id=0x%x len=%d",
4413		    SPP_ARGS(ifp), cp->name,
4414		    sppp_auth_type_name(cp->proto, lh->type),
4415		    lh->ident, ntohs(lh->len));
4416		sppp_print_bytes((u_char*) (lh+1), len);
4417		log(-1, ">\n");
4418	}
4419	if (! IF_HANDOFF_ADJ(&sp->pp_cpq, m, ifp, 3))
4420		ifp->if_oerrors++;
4421}
4422
4423/*
4424 * Flush interface queue.
4425 */
4426static void
4427sppp_qflush(struct ifqueue *ifq)
4428{
4429	struct mbuf *m, *n;
4430
4431	n = ifq->ifq_head;
4432	while ((m = n)) {
4433		n = m->m_act;
4434		m_freem (m);
4435	}
4436	ifq->ifq_head = 0;
4437	ifq->ifq_tail = 0;
4438	ifq->ifq_len = 0;
4439}
4440
4441/*
4442 * Send keepalive packets, every 10 seconds.
4443 */
4444static void
4445sppp_keepalive(void *dummy)
4446{
4447	struct sppp *sp;
4448	int s;
4449
4450	s = splimp();
4451	for (sp=spppq; sp; sp=sp->pp_next) {
4452		struct ifnet *ifp = &sp->pp_if;
4453
4454		/* Keepalive mode disabled or channel down? */
4455		if (! (sp->pp_flags & PP_KEEPALIVE) ||
4456		    ! (ifp->if_flags & IFF_RUNNING))
4457			continue;
4458
4459		/* No keepalive in PPP mode if LCP not opened yet. */
4460		if (sp->pp_mode != IFF_CISCO &&
4461		    sp->pp_phase < PHASE_AUTHENTICATE)
4462			continue;
4463
4464		if (sp->pp_alivecnt == MAXALIVECNT) {
4465			/* No keepalive packets got.  Stop the interface. */
4466			printf (SPP_FMT "down\n", SPP_ARGS(ifp));
4467			if_down (ifp);
4468			sppp_qflush (&sp->pp_cpq);
4469			if (sp->pp_mode != IFF_CISCO) {
4470				/* XXX */
4471				/* Shut down the PPP link. */
4472				lcp.Down(sp);
4473				/* Initiate negotiation. XXX */
4474				lcp.Up(sp);
4475			}
4476		}
4477		if (sp->pp_alivecnt <= MAXALIVECNT)
4478			++sp->pp_alivecnt;
4479		if (sp->pp_mode == IFF_CISCO)
4480			sppp_cisco_send (sp, CISCO_KEEPALIVE_REQ,
4481				 ++sp->pp_seq[IDX_LCP],	sp->pp_rseq[IDX_LCP]);
4482		else if (sp->pp_phase >= PHASE_AUTHENTICATE) {
4483			long nmagic = htonl (sp->lcp.magic);
4484			sp->lcp.echoid = ++sp->pp_seq[IDX_LCP];
4485			sppp_cp_send (sp, PPP_LCP, ECHO_REQ,
4486				sp->lcp.echoid, 4, &nmagic);
4487		}
4488	}
4489	splx(s);
4490	TIMEOUT(sppp_keepalive, 0, hz * 10, keepalive_ch);
4491}
4492
4493/*
4494 * Get both IP addresses.
4495 */
4496static void
4497sppp_get_ip_addrs(struct sppp *sp, u_long *src, u_long *dst, u_long *srcmask)
4498{
4499	struct ifnet *ifp = &sp->pp_if;
4500	struct ifaddr *ifa;
4501	struct sockaddr_in *si, *sm;
4502	u_long ssrc, ddst;
4503
4504	sm = NULL;
4505	ssrc = ddst = 0L;
4506	/*
4507	 * Pick the first AF_INET address from the list,
4508	 * aliases don't make any sense on a p2p link anyway.
4509	 */
4510	si = 0;
4511#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4512	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
4513#elif defined(__NetBSD__) || defined (__OpenBSD__)
4514	for (ifa = TAILQ_FIRST(&ifp->if_addrlist);
4515	     ifa;
4516	     ifa = TAILQ_NEXT(ifa, ifa_list))
4517#else
4518	for (ifa = ifp->if_addrlist;
4519	     ifa;
4520	     ifa = ifa->ifa_next)
4521#endif
4522		if (ifa->ifa_addr->sa_family == AF_INET) {
4523			si = (struct sockaddr_in *)ifa->ifa_addr;
4524			sm = (struct sockaddr_in *)ifa->ifa_netmask;
4525			if (si)
4526				break;
4527		}
4528	if (ifa) {
4529		if (si && si->sin_addr.s_addr) {
4530			ssrc = si->sin_addr.s_addr;
4531			if (srcmask)
4532				*srcmask = ntohl(sm->sin_addr.s_addr);
4533		}
4534
4535		si = (struct sockaddr_in *)ifa->ifa_dstaddr;
4536		if (si && si->sin_addr.s_addr)
4537			ddst = si->sin_addr.s_addr;
4538	}
4539
4540	if (dst) *dst = ntohl(ddst);
4541	if (src) *src = ntohl(ssrc);
4542}
4543
4544/*
4545 * Set my IP address.  Must be called at splimp.
4546 */
4547static void
4548sppp_set_ip_addr(struct sppp *sp, u_long src)
4549{
4550	STDDCL;
4551	struct ifaddr *ifa;
4552	struct sockaddr_in *si;
4553	struct in_ifaddr *ia;
4554
4555	/*
4556	 * Pick the first AF_INET address from the list,
4557	 * aliases don't make any sense on a p2p link anyway.
4558	 */
4559	si = 0;
4560#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4561	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
4562#elif defined(__NetBSD__) || defined (__OpenBSD__)
4563	for (ifa = TAILQ_FIRST(&ifp->if_addrlist);
4564	     ifa;
4565	     ifa = TAILQ_NEXT(ifa, ifa_list))
4566#else
4567	for (ifa = ifp->if_addrlist;
4568	     ifa;
4569	     ifa = ifa->ifa_next)
4570#endif
4571	{
4572		if (ifa->ifa_addr->sa_family == AF_INET)
4573		{
4574			si = (struct sockaddr_in *)ifa->ifa_addr;
4575			if (si)
4576				break;
4577		}
4578	}
4579
4580	if (ifa && si)
4581	{
4582		int error;
4583#if __NetBSD_Version__ >= 103080000
4584		struct sockaddr_in new_sin = *si;
4585
4586		new_sin.sin_addr.s_addr = htonl(src);
4587		error = in_ifinit(ifp, ifatoia(ifa), &new_sin, 1);
4588		if(debug && error)
4589		{
4590			log(LOG_DEBUG, SPP_FMT "sppp_set_ip_addr: in_ifinit "
4591			" failed, error=%d\n", SPP_ARGS(ifp), error);
4592		}
4593#else
4594		/* delete old route */
4595		error = rtinit(ifa, (int)RTM_DELETE, RTF_HOST);
4596		if(debug && error)
4597		{
4598			log(LOG_DEBUG, SPP_FMT "sppp_set_ip_addr: rtinit DEL failed, error=%d\n",
4599		    		SPP_ARGS(ifp), error);
4600		}
4601
4602		/* set new address */
4603		si->sin_addr.s_addr = htonl(src);
4604		ia = ifatoia(ifa);
4605		LIST_REMOVE(ia, ia_hash);
4606		LIST_INSERT_HEAD(INADDR_HASH(si->sin_addr.s_addr), ia, ia_hash);
4607
4608		/* add new route */
4609		error = rtinit(ifa, (int)RTM_ADD, RTF_HOST);
4610		if (debug && error)
4611		{
4612			log(LOG_DEBUG, SPP_FMT "sppp_set_ip_addr: rtinit ADD failed, error=%d",
4613		    		SPP_ARGS(ifp), error);
4614		}
4615#endif
4616	}
4617}
4618
4619#ifdef INET6
4620/*
4621 * Get both IPv6 addresses.
4622 */
4623static void
4624sppp_get_ip6_addrs(struct sppp *sp, struct in6_addr *src, struct in6_addr *dst,
4625		   struct in6_addr *srcmask)
4626{
4627	struct ifnet *ifp = &sp->pp_if;
4628	struct ifaddr *ifa;
4629	struct sockaddr_in6 *si, *sm;
4630	struct in6_addr ssrc, ddst;
4631
4632	sm = NULL;
4633	bzero(&ssrc, sizeof(ssrc));
4634	bzero(&ddst, sizeof(ddst));
4635	/*
4636	 * Pick the first link-local AF_INET6 address from the list,
4637	 * aliases don't make any sense on a p2p link anyway.
4638	 */
4639#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4640	for (ifa = ifp->if_addrhead.tqh_first, si = 0;
4641	     ifa;
4642	     ifa = ifa->ifa_link.tqe_next)
4643#elif defined(__NetBSD__) || defined (__OpenBSD__)
4644	for (ifa = ifp->if_addrlist.tqh_first, si = 0;
4645	     ifa;
4646	     ifa = ifa->ifa_list.tqe_next)
4647#else
4648	for (ifa = ifp->if_addrlist, si = 0;
4649	     ifa;
4650	     ifa = ifa->ifa_next)
4651#endif
4652		if (ifa->ifa_addr->sa_family == AF_INET6) {
4653			si = (struct sockaddr_in6 *)ifa->ifa_addr;
4654			sm = (struct sockaddr_in6 *)ifa->ifa_netmask;
4655			if (si && IN6_IS_ADDR_LINKLOCAL(&si->sin6_addr))
4656				break;
4657		}
4658	if (ifa) {
4659		if (si && !IN6_IS_ADDR_UNSPECIFIED(&si->sin6_addr)) {
4660			bcopy(&si->sin6_addr, &ssrc, sizeof(ssrc));
4661			if (srcmask) {
4662				bcopy(&sm->sin6_addr, srcmask,
4663				      sizeof(*srcmask));
4664			}
4665		}
4666
4667		si = (struct sockaddr_in6 *)ifa->ifa_dstaddr;
4668		if (si && !IN6_IS_ADDR_UNSPECIFIED(&si->sin6_addr))
4669			bcopy(&si->sin6_addr, &ddst, sizeof(ddst));
4670	}
4671
4672	if (dst)
4673		bcopy(&ddst, dst, sizeof(*dst));
4674	if (src)
4675		bcopy(&ssrc, src, sizeof(*src));
4676}
4677
4678#ifdef IPV6CP_MYIFID_DYN
4679/*
4680 * Generate random ifid.
4681 */
4682static void
4683sppp_gen_ip6_addr(struct sppp *sp, struct in6_addr *addr)
4684{
4685	/* TBD */
4686}
4687
4688/*
4689 * Set my IPv6 address.  Must be called at splimp.
4690 */
4691static void
4692sppp_set_ip6_addr(struct sppp *sp, const struct in6_addr *src)
4693{
4694	STDDCL;
4695	struct ifaddr *ifa;
4696	struct sockaddr_in6 *sin6;
4697
4698	/*
4699	 * Pick the first link-local AF_INET6 address from the list,
4700	 * aliases don't make any sense on a p2p link anyway.
4701	 */
4702
4703	sin6 = NULL;
4704#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4705	for (ifa = ifp->if_addrhead.tqh_first;
4706	     ifa;
4707	     ifa = ifa->ifa_link.tqe_next)
4708#elif defined(__NetBSD__) || defined (__OpenBSD__)
4709	for (ifa = ifp->if_addrlist.tqh_first;
4710	     ifa;
4711	     ifa = ifa->ifa_list.tqe_next)
4712#else
4713	for (ifa = ifp->if_addrlist; ifa; ifa = ifa->ifa_next)
4714#endif
4715	{
4716		if (ifa->ifa_addr->sa_family == AF_INET6)
4717		{
4718			sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
4719			if (sin6 && IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))
4720				break;
4721		}
4722	}
4723
4724	if (ifa && sin6)
4725	{
4726		int error;
4727		struct sockaddr_in6 new_sin6 = *sin6;
4728
4729		bcopy(src, &new_sin6.sin6_addr, sizeof(new_sin6.sin6_addr));
4730		error = in6_ifinit(ifp, ifatoia6(ifa), &new_sin6, 1);
4731		if (debug && error)
4732		{
4733			log(LOG_DEBUG, SPP_FMT "sppp_set_ip6_addr: in6_ifinit "
4734			    " failed, error=%d\n", SPP_ARGS(ifp), error);
4735		}
4736	}
4737}
4738#endif
4739
4740/*
4741 * Suggest a candidate address to be used by peer.
4742 */
4743static void
4744sppp_suggest_ip6_addr(struct sppp *sp, struct in6_addr *suggest)
4745{
4746	struct in6_addr myaddr;
4747	struct timeval tv;
4748
4749	sppp_get_ip6_addrs(sp, &myaddr, 0, 0);
4750
4751	myaddr.s6_addr[8] &= ~0x02;	/* u bit to "local" */
4752	microtime(&tv);
4753	if ((tv.tv_usec & 0xff) == 0 && (tv.tv_sec & 0xff) == 0) {
4754		myaddr.s6_addr[14] ^= 0xff;
4755		myaddr.s6_addr[15] ^= 0xff;
4756	} else {
4757		myaddr.s6_addr[14] ^= (tv.tv_usec & 0xff);
4758		myaddr.s6_addr[15] ^= (tv.tv_sec & 0xff);
4759	}
4760	if (suggest)
4761		bcopy(&myaddr, suggest, sizeof(myaddr));
4762}
4763#endif /*INET6*/
4764
4765static int
4766sppp_params(struct sppp *sp, u_long cmd, void *data)
4767{
4768	u_long subcmd;
4769	struct ifreq *ifr = (struct ifreq *)data;
4770	struct spppreq spr;
4771
4772	/*
4773	 * ifr->ifr_data is supposed to point to a struct spppreq.
4774	 * Check the cmd word first before attempting to fetch all the
4775	 * data.
4776	 */
4777	if ((subcmd = fuword(ifr->ifr_data)) == -1)
4778		return EFAULT;
4779
4780	if (copyin((caddr_t)ifr->ifr_data, &spr, sizeof spr) != 0)
4781		return EFAULT;
4782
4783	switch (subcmd) {
4784	case SPPPIOGDEFS:
4785		if (cmd != SIOCGIFGENERIC)
4786			return EINVAL;
4787		/*
4788		 * We copy over the entire current state, but clean
4789		 * out some of the stuff we don't wanna pass up.
4790		 * Remember, SIOCGIFGENERIC is unprotected, and can be
4791		 * called by any user.  No need to ever get PAP or
4792		 * CHAP secrets back to userland anyway.
4793		 */
4794		bcopy(sp, &spr.defs, sizeof(struct sppp));
4795		bzero(spr.defs.myauth.secret, AUTHKEYLEN);
4796		bzero(spr.defs.myauth.challenge, AUTHKEYLEN);
4797		bzero(spr.defs.hisauth.secret, AUTHKEYLEN);
4798		bzero(spr.defs.hisauth.challenge, AUTHKEYLEN);
4799		return copyout(&spr, (caddr_t)ifr->ifr_data, sizeof spr);
4800
4801	case SPPPIOSDEFS:
4802		if (cmd != SIOCSIFGENERIC)
4803			return EINVAL;
4804		/*
4805		 * We have a very specific idea of which fields we allow
4806		 * being passed back from userland, so to not clobber our
4807		 * current state.  For one, we only allow setting
4808		 * anything if LCP is in dead phase.  Once the LCP
4809		 * negotiations started, the authentication settings must
4810		 * not be changed again.  (The administrator can force an
4811		 * ifconfig down in order to get LCP back into dead
4812		 * phase.)
4813		 *
4814		 * Also, we only allow for authentication parameters to be
4815		 * specified.
4816		 *
4817		 * XXX Should allow to set or clear pp_flags.
4818		 *
4819		 * Finally, if the respective authentication protocol to
4820		 * be used is set differently than 0, but the secret is
4821		 * passed as all zeros, we don't trash the existing secret.
4822		 * This allows an administrator to change the system name
4823		 * only without clobbering the secret (which he didn't get
4824		 * back in a previous SPPPIOGDEFS call).  However, the
4825		 * secrets are cleared if the authentication protocol is
4826		 * reset to 0.
4827		 */
4828		if (sp->pp_phase != PHASE_DEAD)
4829			return EBUSY;
4830
4831		if ((spr.defs.myauth.proto != 0 && spr.defs.myauth.proto != PPP_PAP &&
4832		     spr.defs.myauth.proto != PPP_CHAP) ||
4833		    (spr.defs.hisauth.proto != 0 && spr.defs.hisauth.proto != PPP_PAP &&
4834		     spr.defs.hisauth.proto != PPP_CHAP))
4835			return EINVAL;
4836
4837		if (spr.defs.myauth.proto == 0)
4838			/* resetting myauth */
4839			bzero(&sp->myauth, sizeof sp->myauth);
4840		else {
4841			/* setting/changing myauth */
4842			sp->myauth.proto = spr.defs.myauth.proto;
4843			bcopy(spr.defs.myauth.name, sp->myauth.name, AUTHNAMELEN);
4844			if (spr.defs.myauth.secret[0] != '\0')
4845				bcopy(spr.defs.myauth.secret, sp->myauth.secret,
4846				      AUTHKEYLEN);
4847		}
4848		if (spr.defs.hisauth.proto == 0)
4849			/* resetting hisauth */
4850			bzero(&sp->hisauth, sizeof sp->hisauth);
4851		else {
4852			/* setting/changing hisauth */
4853			sp->hisauth.proto = spr.defs.hisauth.proto;
4854			sp->hisauth.flags = spr.defs.hisauth.flags;
4855			bcopy(spr.defs.hisauth.name, sp->hisauth.name, AUTHNAMELEN);
4856			if (spr.defs.hisauth.secret[0] != '\0')
4857				bcopy(spr.defs.hisauth.secret, sp->hisauth.secret,
4858				      AUTHKEYLEN);
4859		}
4860		break;
4861
4862	default:
4863		return EINVAL;
4864	}
4865
4866	return 0;
4867}
4868
4869static void
4870sppp_phase_network(struct sppp *sp)
4871{
4872	STDDCL;
4873	int i;
4874	u_long mask;
4875
4876	sp->pp_phase = PHASE_NETWORK;
4877
4878	if (debug)
4879		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
4880		    sppp_phase_name(sp->pp_phase));
4881
4882	/* Notify NCPs now. */
4883	for (i = 0; i < IDX_COUNT; i++)
4884		if ((cps[i])->flags & CP_NCP)
4885			(cps[i])->Open(sp);
4886
4887	/* Send Up events to all NCPs. */
4888	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
4889		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_NCP))
4890			(cps[i])->Up(sp);
4891
4892	/* if no NCP is starting, all this was in vain, close down */
4893	sppp_lcp_check_and_close(sp);
4894}
4895
4896
4897static const char *
4898sppp_cp_type_name(u_char type)
4899{
4900	static char buf[12];
4901	switch (type) {
4902	case CONF_REQ:   return "conf-req";
4903	case CONF_ACK:   return "conf-ack";
4904	case CONF_NAK:   return "conf-nak";
4905	case CONF_REJ:   return "conf-rej";
4906	case TERM_REQ:   return "term-req";
4907	case TERM_ACK:   return "term-ack";
4908	case CODE_REJ:   return "code-rej";
4909	case PROTO_REJ:  return "proto-rej";
4910	case ECHO_REQ:   return "echo-req";
4911	case ECHO_REPLY: return "echo-reply";
4912	case DISC_REQ:   return "discard-req";
4913	}
4914	snprintf (buf, sizeof(buf), "cp/0x%x", type);
4915	return buf;
4916}
4917
4918static const char *
4919sppp_auth_type_name(u_short proto, u_char type)
4920{
4921	static char buf[12];
4922	switch (proto) {
4923	case PPP_CHAP:
4924		switch (type) {
4925		case CHAP_CHALLENGE:	return "challenge";
4926		case CHAP_RESPONSE:	return "response";
4927		case CHAP_SUCCESS:	return "success";
4928		case CHAP_FAILURE:	return "failure";
4929		}
4930	case PPP_PAP:
4931		switch (type) {
4932		case PAP_REQ:		return "req";
4933		case PAP_ACK:		return "ack";
4934		case PAP_NAK:		return "nak";
4935		}
4936	}
4937	snprintf (buf, sizeof(buf), "auth/0x%x", type);
4938	return buf;
4939}
4940
4941static const char *
4942sppp_lcp_opt_name(u_char opt)
4943{
4944	static char buf[12];
4945	switch (opt) {
4946	case LCP_OPT_MRU:		return "mru";
4947	case LCP_OPT_ASYNC_MAP:		return "async-map";
4948	case LCP_OPT_AUTH_PROTO:	return "auth-proto";
4949	case LCP_OPT_QUAL_PROTO:	return "qual-proto";
4950	case LCP_OPT_MAGIC:		return "magic";
4951	case LCP_OPT_PROTO_COMP:	return "proto-comp";
4952	case LCP_OPT_ADDR_COMP:		return "addr-comp";
4953	}
4954	snprintf (buf, sizeof(buf), "lcp/0x%x", opt);
4955	return buf;
4956}
4957
4958static const char *
4959sppp_ipcp_opt_name(u_char opt)
4960{
4961	static char buf[12];
4962	switch (opt) {
4963	case IPCP_OPT_ADDRESSES:	return "addresses";
4964	case IPCP_OPT_COMPRESSION:	return "compression";
4965	case IPCP_OPT_ADDRESS:		return "address";
4966	}
4967	snprintf (buf, sizeof(buf), "ipcp/0x%x", opt);
4968	return buf;
4969}
4970
4971#ifdef INET6
4972static const char *
4973sppp_ipv6cp_opt_name(u_char opt)
4974{
4975	static char buf[12];
4976	switch (opt) {
4977	case IPV6CP_OPT_IFID:		return "ifid";
4978	case IPV6CP_OPT_COMPRESSION:	return "compression";
4979	}
4980	sprintf (buf, "0x%x", opt);
4981	return buf;
4982}
4983#endif
4984
4985static const char *
4986sppp_state_name(int state)
4987{
4988	switch (state) {
4989	case STATE_INITIAL:	return "initial";
4990	case STATE_STARTING:	return "starting";
4991	case STATE_CLOSED:	return "closed";
4992	case STATE_STOPPED:	return "stopped";
4993	case STATE_CLOSING:	return "closing";
4994	case STATE_STOPPING:	return "stopping";
4995	case STATE_REQ_SENT:	return "req-sent";
4996	case STATE_ACK_RCVD:	return "ack-rcvd";
4997	case STATE_ACK_SENT:	return "ack-sent";
4998	case STATE_OPENED:	return "opened";
4999	}
5000	return "illegal";
5001}
5002
5003static const char *
5004sppp_phase_name(enum ppp_phase phase)
5005{
5006	switch (phase) {
5007	case PHASE_DEAD:	return "dead";
5008	case PHASE_ESTABLISH:	return "establish";
5009	case PHASE_TERMINATE:	return "terminate";
5010	case PHASE_AUTHENTICATE: return "authenticate";
5011	case PHASE_NETWORK:	return "network";
5012	}
5013	return "illegal";
5014}
5015
5016static const char *
5017sppp_proto_name(u_short proto)
5018{
5019	static char buf[12];
5020	switch (proto) {
5021	case PPP_LCP:	return "lcp";
5022	case PPP_IPCP:	return "ipcp";
5023	case PPP_PAP:	return "pap";
5024	case PPP_CHAP:	return "chap";
5025	case PPP_IPV6CP: return "ipv6cp";
5026	}
5027	snprintf(buf, sizeof(buf), "proto/0x%x", (unsigned)proto);
5028	return buf;
5029}
5030
5031static void
5032sppp_print_bytes(const u_char *p, u_short len)
5033{
5034	if (len)
5035		log(-1, " %*D", len, p, "-");
5036}
5037
5038static void
5039sppp_print_string(const char *p, u_short len)
5040{
5041	u_char c;
5042
5043	while (len-- > 0) {
5044		c = *p++;
5045		/*
5046		 * Print only ASCII chars directly.  RFC 1994 recommends
5047		 * using only them, but we don't rely on it.  */
5048		if (c < ' ' || c > '~')
5049			log(-1, "\\x%x", c);
5050		else
5051			log(-1, "%c", c);
5052	}
5053}
5054
5055static const char *
5056sppp_dotted_quad(u_long addr)
5057{
5058	static char s[16];
5059	sprintf(s, "%d.%d.%d.%d",
5060		(int)((addr >> 24) & 0xff),
5061		(int)((addr >> 16) & 0xff),
5062		(int)((addr >> 8) & 0xff),
5063		(int)(addr & 0xff));
5064	return s;
5065}
5066
5067static int
5068sppp_strnlen(u_char *p, int max)
5069{
5070	int len;
5071
5072	for (len = 0; len < max && *p; ++p)
5073		++len;
5074	return len;
5075}
5076
5077/* a dummy, used to drop uninteresting events */
5078static void
5079sppp_null(struct sppp *unused)
5080{
5081	/* do just nothing */
5082}
5083