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