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