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