if_spppsubr.c revision 42066
1/*
2 * Synchronous PPP/Cisco link level subroutines.
3 * Keepalive protocol implemented in both Cisco and PPP modes.
4 *
5 * Copyright (C) 1994-1996 Cronyx Engineering Ltd.
6 * Author: Serge Vakulenko, <vak@cronyx.ru>
7 *
8 * Heavily revamped to conform to RFC 1661.
9 * Copyright (C) 1997, Joerg Wunsch.
10 *
11 * This software is distributed with NO WARRANTIES, not even the implied
12 * warranties for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 *
14 * Authors grant any other persons or organisations permission to use
15 * or modify this software as long as this message is kept with the software,
16 * all derivative works or modified versions.
17 *
18 * From: Version 2.4, Thu Apr 30 17:17:21 MSD 1997
19 *
20 * $Id: if_spppsubr.c,v 1.50 1998/12/26 12:43:26 phk Exp $
21 */
22
23#include <sys/param.h>
24
25#if defined(__FreeBSD__) && __FreeBSD__ >= 3
26#include "opt_inet.h"
27#include "opt_ipx.h"
28#endif
29
30#ifdef NetBSD1_3
31#  if NetBSD1_3 > 6
32#      include "opt_inet.h"
33#      include "opt_iso.h"
34#  endif
35#endif
36
37#include <sys/systm.h>
38#include <sys/kernel.h>
39#include <sys/sockio.h>
40#include <sys/socket.h>
41#include <sys/syslog.h>
42#include <sys/malloc.h>
43#include <sys/mbuf.h>
44
45#if defined (__OpenBSD__)
46#include <sys/md5k.h>
47#else
48#include <sys/md5.h>
49#endif
50
51#include <net/if.h>
52#include <net/netisr.h>
53#include <net/if_types.h>
54
55#if defined(__FreeBSD__) && __FreeBSD__ >= 3
56#include <machine/random.h>
57#endif
58#if defined (__NetBSD__) || defined (__OpenBSD__)
59#include <machine/cpu.h> /* XXX for softnet */
60#endif
61#include <machine/stdarg.h>
62
63#ifdef INET
64#include <netinet/in.h>
65#include <netinet/in_systm.h>
66#include <netinet/in_var.h>
67#include <netinet/ip.h>
68#include <netinet/tcp.h>
69# if defined (__FreeBSD__) || defined (__OpenBSD__)
70#  include <netinet/if_ether.h>
71# else
72#  include <net/ethertypes.h>
73# endif
74#else
75# error Huh? sppp without INET?
76#endif
77
78#ifdef IPX
79#include <netipx/ipx.h>
80#include <netipx/ipx_if.h>
81#endif
82
83#ifdef NS
84#include <netns/ns.h>
85#include <netns/ns_if.h>
86#endif
87
88#ifdef ISO
89#include <netiso/argo_debug.h>
90#include <netiso/iso.h>
91#include <netiso/iso_var.h>
92#include <netiso/iso_snpac.h>
93#endif
94
95#include <net/if_sppp.h>
96
97#if defined(__FreeBSD__) && __FreeBSD__ >= 3
98# define UNTIMEOUT(fun, arg, handle) untimeout(fun, arg, handle)
99# define TIMEOUT(fun, arg1, arg2, handle) handle = timeout(fun, arg1, arg2)
100#else
101# define UNTIMEOUT(fun, arg, handle) untimeout(fun, arg)
102# define TIMEOUT(fun, arg1, arg2, handle) timeout(fun, arg1, arg2)
103#endif
104#define MAXALIVECNT     3               /* max. alive packets */
105
106/*
107 * Interface flags that can be set in an ifconfig command.
108 *
109 * Setting link0 will make the link passive, i.e. it will be marked
110 * as being administrative openable, but won't be opened to begin
111 * with.  Incoming calls will be answered, or subsequent calls with
112 * -link1 will cause the administrative open of the LCP layer.
113 *
114 * Setting link1 will cause the link to auto-dial only as packets
115 * arrive to be sent.
116 *
117 * Setting IFF_DEBUG will syslog the option negotiation and state
118 * transitions at level kern.debug.  Note: all logs consistently look
119 * like
120 *
121 *   <if-name><unit>: <proto-name> <additional info...>
122 *
123 * with <if-name><unit> being something like "bppp0", and <proto-name>
124 * being one of "lcp", "ipcp", "cisco", "chap", "pap", etc.
125 */
126
127#define IFF_PASSIVE	IFF_LINK0	/* wait passively for connection */
128#define IFF_AUTO	IFF_LINK1	/* auto-dial on output */
129
130#define PPP_ALLSTATIONS 0xff		/* All-Stations broadcast address */
131#define PPP_UI		0x03		/* Unnumbered Information */
132#define PPP_IP		0x0021		/* Internet Protocol */
133#define PPP_ISO		0x0023		/* ISO OSI Protocol */
134#define PPP_XNS		0x0025		/* Xerox NS Protocol */
135#define PPP_IPX		0x002b		/* Novell IPX Protocol */
136#define PPP_LCP		0xc021		/* Link Control Protocol */
137#define PPP_PAP		0xc023		/* Password Authentication Protocol */
138#define PPP_CHAP	0xc223		/* Challenge-Handshake Auth Protocol */
139#define PPP_IPCP	0x8021		/* Internet Protocol Control Protocol */
140
141#define CONF_REQ	1		/* PPP configure request */
142#define CONF_ACK	2		/* PPP configure acknowledge */
143#define CONF_NAK	3		/* PPP configure negative ack */
144#define CONF_REJ	4		/* PPP configure reject */
145#define TERM_REQ	5		/* PPP terminate request */
146#define TERM_ACK	6		/* PPP terminate acknowledge */
147#define CODE_REJ	7		/* PPP code reject */
148#define PROTO_REJ	8		/* PPP protocol reject */
149#define ECHO_REQ	9		/* PPP echo request */
150#define ECHO_REPLY	10		/* PPP echo reply */
151#define DISC_REQ	11		/* PPP discard request */
152
153#define LCP_OPT_MRU		1	/* maximum receive unit */
154#define LCP_OPT_ASYNC_MAP	2	/* async control character map */
155#define LCP_OPT_AUTH_PROTO	3	/* authentication protocol */
156#define LCP_OPT_QUAL_PROTO	4	/* quality protocol */
157#define LCP_OPT_MAGIC		5	/* magic number */
158#define LCP_OPT_RESERVED	6	/* reserved */
159#define LCP_OPT_PROTO_COMP	7	/* protocol field compression */
160#define LCP_OPT_ADDR_COMP	8	/* address/control field compression */
161
162#define IPCP_OPT_ADDRESSES	1	/* both IP addresses; deprecated */
163#define IPCP_OPT_COMPRESSION	2	/* IP compression protocol (VJ) */
164#define IPCP_OPT_ADDRESS	3	/* local IP address */
165
166#define PAP_REQ			1	/* PAP name/password request */
167#define PAP_ACK			2	/* PAP acknowledge */
168#define PAP_NAK			3	/* PAP fail */
169
170#define CHAP_CHALLENGE		1	/* CHAP challenge request */
171#define CHAP_RESPONSE		2	/* CHAP challenge response */
172#define CHAP_SUCCESS		3	/* CHAP response ok */
173#define CHAP_FAILURE		4	/* CHAP response failed */
174
175#define CHAP_MD5		5	/* hash algorithm - MD5 */
176
177#define CISCO_MULTICAST		0x8f	/* Cisco multicast address */
178#define CISCO_UNICAST		0x0f	/* Cisco unicast address */
179#define CISCO_KEEPALIVE		0x8035	/* Cisco keepalive protocol */
180#define CISCO_ADDR_REQ		0	/* Cisco address request */
181#define CISCO_ADDR_REPLY	1	/* Cisco address reply */
182#define CISCO_KEEPALIVE_REQ	2	/* Cisco keepalive request */
183
184/* states are named and numbered according to RFC 1661 */
185#define STATE_INITIAL	0
186#define STATE_STARTING	1
187#define STATE_CLOSED	2
188#define STATE_STOPPED	3
189#define STATE_CLOSING	4
190#define STATE_STOPPING	5
191#define STATE_REQ_SENT	6
192#define STATE_ACK_RCVD	7
193#define STATE_ACK_SENT	8
194#define STATE_OPENED	9
195
196struct ppp_header {
197	u_char address;
198	u_char control;
199	u_short protocol;
200};
201#define PPP_HEADER_LEN          sizeof (struct ppp_header)
202
203struct lcp_header {
204	u_char type;
205	u_char ident;
206	u_short len;
207};
208#define LCP_HEADER_LEN          sizeof (struct lcp_header)
209
210struct cisco_packet {
211	u_long type;
212	u_long par1;
213	u_long par2;
214	u_short rel;
215	u_short time0;
216	u_short time1;
217};
218#define CISCO_PACKET_LEN 18
219
220/*
221 * We follow the spelling and capitalization of RFC 1661 here, to make
222 * it easier comparing with the standard.  Please refer to this RFC in
223 * case you can't make sense out of these abbreviation; it will also
224 * explain the semantics related to the various events and actions.
225 */
226struct cp {
227	u_short	proto;		/* PPP control protocol number */
228	u_char protoidx;	/* index into state table in struct sppp */
229	u_char flags;
230#define CP_LCP		0x01	/* this is the LCP */
231#define CP_AUTH		0x02	/* this is an authentication protocol */
232#define CP_NCP		0x04	/* this is a NCP */
233#define CP_QUAL		0x08	/* this is a quality reporting protocol */
234	const char *name;	/* name of this control protocol */
235	/* event handlers */
236	void	(*Up)(struct sppp *sp);
237	void	(*Down)(struct sppp *sp);
238	void	(*Open)(struct sppp *sp);
239	void	(*Close)(struct sppp *sp);
240	void	(*TO)(void *sp);
241	int	(*RCR)(struct sppp *sp, struct lcp_header *h, int len);
242	void	(*RCN_rej)(struct sppp *sp, struct lcp_header *h, int len);
243	void	(*RCN_nak)(struct sppp *sp, struct lcp_header *h, int len);
244	/* actions */
245	void	(*tlu)(struct sppp *sp);
246	void	(*tld)(struct sppp *sp);
247	void	(*tls)(struct sppp *sp);
248	void	(*tlf)(struct sppp *sp);
249	void	(*scr)(struct sppp *sp);
250};
251
252static struct sppp *spppq;
253#if defined(__FreeBSD__) && __FreeBSD__ >= 3
254static struct callout_handle keepalive_ch;
255#endif
256
257#if defined(__FreeBSD__) && __FreeBSD__ >= 3
258#define	SPP_FMT		"%s%d: "
259#define	SPP_ARGS(ifp)	(ifp)->if_name, (ifp)->if_unit
260#else
261#define	SPP_FMT		"%s: "
262#define	SPP_ARGS(ifp)	(ifp)->if_xname
263#endif
264
265/*
266 * The following disgusting hack gets around the problem that IP TOS
267 * can't be set yet.  We want to put "interactive" traffic on a high
268 * priority queue.  To decide if traffic is interactive, we check that
269 * a) it is TCP and b) one of its ports is telnet, rlogin or ftp control.
270 *
271 * XXX is this really still necessary?  - joerg -
272 */
273static u_short interactive_ports[8] = {
274	0,	513,	0,	0,
275	0,	21,	0,	23,
276};
277#define INTERACTIVE(p) (interactive_ports[(p) & 7] == (p))
278
279/* almost every function needs these */
280#define STDDCL							\
281	struct ifnet *ifp = &sp->pp_if;				\
282	int debug = ifp->if_flags & IFF_DEBUG
283
284static int sppp_output(struct ifnet *ifp, struct mbuf *m,
285		       struct sockaddr *dst, struct rtentry *rt);
286
287static void sppp_cisco_send(struct sppp *sp, int type, long par1, long par2);
288static void sppp_cisco_input(struct sppp *sp, struct mbuf *m);
289
290static void sppp_cp_input(const struct cp *cp, struct sppp *sp,
291			  struct mbuf *m);
292static void sppp_cp_send(struct sppp *sp, u_short proto, u_char type,
293			 u_char ident, u_short len, void *data);
294#ifdef notyet
295static void sppp_cp_timeout(void *arg);
296#endif
297static void sppp_cp_change_state(const struct cp *cp, struct sppp *sp,
298				 int newstate);
299static void sppp_auth_send(const struct cp *cp,
300			   struct sppp *sp, u_char type, u_char id,
301			   ...);
302
303static void sppp_up_event(const struct cp *cp, struct sppp *sp);
304static void sppp_down_event(const struct cp *cp, struct sppp *sp);
305static void sppp_open_event(const struct cp *cp, struct sppp *sp);
306static void sppp_close_event(const struct cp *cp, struct sppp *sp);
307static void sppp_to_event(const struct cp *cp, struct sppp *sp);
308
309static void sppp_null(struct sppp *sp);
310
311static void sppp_lcp_init(struct sppp *sp);
312static void sppp_lcp_up(struct sppp *sp);
313static void sppp_lcp_down(struct sppp *sp);
314static void sppp_lcp_open(struct sppp *sp);
315static void sppp_lcp_close(struct sppp *sp);
316static void sppp_lcp_TO(void *sp);
317static int sppp_lcp_RCR(struct sppp *sp, struct lcp_header *h, int len);
318static void sppp_lcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len);
319static void sppp_lcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len);
320static void sppp_lcp_tlu(struct sppp *sp);
321static void sppp_lcp_tld(struct sppp *sp);
322static void sppp_lcp_tls(struct sppp *sp);
323static void sppp_lcp_tlf(struct sppp *sp);
324static void sppp_lcp_scr(struct sppp *sp);
325static void sppp_lcp_check_and_close(struct sppp *sp);
326static int sppp_ncp_check(struct sppp *sp);
327
328static void sppp_ipcp_init(struct sppp *sp);
329static void sppp_ipcp_up(struct sppp *sp);
330static void sppp_ipcp_down(struct sppp *sp);
331static void sppp_ipcp_open(struct sppp *sp);
332static void sppp_ipcp_close(struct sppp *sp);
333static void sppp_ipcp_TO(void *sp);
334static int sppp_ipcp_RCR(struct sppp *sp, struct lcp_header *h, int len);
335static void sppp_ipcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len);
336static void sppp_ipcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len);
337static void sppp_ipcp_tlu(struct sppp *sp);
338static void sppp_ipcp_tld(struct sppp *sp);
339static void sppp_ipcp_tls(struct sppp *sp);
340static void sppp_ipcp_tlf(struct sppp *sp);
341static void sppp_ipcp_scr(struct sppp *sp);
342
343static void sppp_pap_input(struct sppp *sp, struct mbuf *m);
344static void sppp_pap_init(struct sppp *sp);
345static void sppp_pap_open(struct sppp *sp);
346static void sppp_pap_close(struct sppp *sp);
347static void sppp_pap_TO(void *sp);
348static void sppp_pap_my_TO(void *sp);
349static void sppp_pap_tlu(struct sppp *sp);
350static void sppp_pap_tld(struct sppp *sp);
351static void sppp_pap_scr(struct sppp *sp);
352
353static void sppp_chap_input(struct sppp *sp, struct mbuf *m);
354static void sppp_chap_init(struct sppp *sp);
355static void sppp_chap_open(struct sppp *sp);
356static void sppp_chap_close(struct sppp *sp);
357static void sppp_chap_TO(void *sp);
358static void sppp_chap_tlu(struct sppp *sp);
359static void sppp_chap_tld(struct sppp *sp);
360static void sppp_chap_scr(struct sppp *sp);
361
362static const char *sppp_auth_type_name(u_short proto, u_char type);
363static const char *sppp_cp_type_name(u_char type);
364static const char *sppp_dotted_quad(u_long addr);
365static const char *sppp_ipcp_opt_name(u_char opt);
366static const char *sppp_lcp_opt_name(u_char opt);
367static const char *sppp_phase_name(enum ppp_phase phase);
368static const char *sppp_proto_name(u_short proto);
369static const char *sppp_state_name(int state);
370static int sppp_params(struct sppp *sp, u_long cmd, void *data);
371static int sppp_strnlen(u_char *p, int max);
372static void sppp_get_ip_addrs(struct sppp *sp, u_long *src, u_long *dst,
373			      u_long *srcmask);
374static void sppp_keepalive(void *dummy);
375static void sppp_phase_network(struct sppp *sp);
376static void sppp_print_bytes(const u_char *p, u_short len);
377static void sppp_print_string(const char *p, u_short len);
378static void sppp_qflush(struct ifqueue *ifq);
379static void sppp_set_ip_addr(struct sppp *sp, u_long src);
380
381/* our control protocol descriptors */
382static const struct cp lcp = {
383	PPP_LCP, IDX_LCP, CP_LCP, "lcp",
384	sppp_lcp_up, sppp_lcp_down, sppp_lcp_open, sppp_lcp_close,
385	sppp_lcp_TO, sppp_lcp_RCR, sppp_lcp_RCN_rej, sppp_lcp_RCN_nak,
386	sppp_lcp_tlu, sppp_lcp_tld, sppp_lcp_tls, sppp_lcp_tlf,
387	sppp_lcp_scr
388};
389
390static const struct cp ipcp = {
391	PPP_IPCP, IDX_IPCP, CP_NCP, "ipcp",
392	sppp_ipcp_up, sppp_ipcp_down, sppp_ipcp_open, sppp_ipcp_close,
393	sppp_ipcp_TO, sppp_ipcp_RCR, sppp_ipcp_RCN_rej, sppp_ipcp_RCN_nak,
394	sppp_ipcp_tlu, sppp_ipcp_tld, sppp_ipcp_tls, sppp_ipcp_tlf,
395	sppp_ipcp_scr
396};
397
398static const struct cp pap = {
399	PPP_PAP, IDX_PAP, CP_AUTH, "pap",
400	sppp_null, sppp_null, sppp_pap_open, sppp_pap_close,
401	sppp_pap_TO, 0, 0, 0,
402	sppp_pap_tlu, sppp_pap_tld, sppp_null, sppp_null,
403	sppp_pap_scr
404};
405
406static const struct cp chap = {
407	PPP_CHAP, IDX_CHAP, CP_AUTH, "chap",
408	sppp_null, sppp_null, sppp_chap_open, sppp_chap_close,
409	sppp_chap_TO, 0, 0, 0,
410	sppp_chap_tlu, sppp_chap_tld, sppp_null, sppp_null,
411	sppp_chap_scr
412};
413
414static const struct cp *cps[IDX_COUNT] = {
415	&lcp,			/* IDX_LCP */
416	&ipcp,			/* IDX_IPCP */
417	&pap,			/* IDX_PAP */
418	&chap,			/* IDX_CHAP */
419};
420
421
422/*
423 * Exported functions, comprising our interface to the lower layer.
424 */
425
426/*
427 * Process the received packet.
428 */
429void
430sppp_input(struct ifnet *ifp, struct mbuf *m)
431{
432	struct ppp_header *h;
433	struct ifqueue *inq = 0;
434	int s;
435	struct sppp *sp = (struct sppp *)ifp;
436	int debug = ifp->if_flags & IFF_DEBUG;
437
438	if (ifp->if_flags & IFF_UP)
439		/* Count received bytes, add FCS and one flag */
440		ifp->if_ibytes += m->m_pkthdr.len + 3;
441
442	if (m->m_pkthdr.len <= PPP_HEADER_LEN) {
443		/* Too small packet, drop it. */
444		if (debug)
445			log(LOG_DEBUG,
446			    SPP_FMT "input packet is too small, %d bytes\n",
447			    SPP_ARGS(ifp), m->m_pkthdr.len);
448	  drop:
449		++ifp->if_ierrors;
450		++ifp->if_iqdrops;
451		m_freem (m);
452		return;
453	}
454
455	/* Get PPP header. */
456	h = mtod (m, struct ppp_header*);
457	m_adj (m, PPP_HEADER_LEN);
458
459	switch (h->address) {
460	case PPP_ALLSTATIONS:
461		if (h->control != PPP_UI)
462			goto invalid;
463		if (sp->pp_flags & PP_CISCO) {
464			if (debug)
465				log(LOG_DEBUG,
466				    SPP_FMT "PPP packet in Cisco mode "
467				    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
468				    SPP_ARGS(ifp),
469				    h->address, h->control, ntohs(h->protocol));
470			goto drop;
471		}
472		switch (ntohs (h->protocol)) {
473		default:
474			if (sp->state[IDX_LCP] == STATE_OPENED)
475				sppp_cp_send (sp, PPP_LCP, PROTO_REJ,
476					++sp->pp_seq, m->m_pkthdr.len + 2,
477					&h->protocol);
478			if (debug)
479				log(LOG_DEBUG,
480				    SPP_FMT "invalid input protocol "
481				    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
482				    SPP_ARGS(ifp),
483				    h->address, h->control, ntohs(h->protocol));
484			++ifp->if_noproto;
485			goto drop;
486		case PPP_LCP:
487			sppp_cp_input(&lcp, sp, m);
488			m_freem (m);
489			return;
490		case PPP_PAP:
491			if (sp->pp_phase >= PHASE_AUTHENTICATE)
492				sppp_pap_input(sp, m);
493			m_freem (m);
494			return;
495		case PPP_CHAP:
496			if (sp->pp_phase >= PHASE_AUTHENTICATE)
497				sppp_chap_input(sp, m);
498			m_freem (m);
499			return;
500#ifdef INET
501		case PPP_IPCP:
502			if (sp->pp_phase == PHASE_NETWORK)
503				sppp_cp_input(&ipcp, sp, m);
504			m_freem (m);
505			return;
506		case PPP_IP:
507			if (sp->state[IDX_IPCP] == STATE_OPENED) {
508				schednetisr (NETISR_IP);
509				inq = &ipintrq;
510			}
511			break;
512#endif
513#ifdef IPX
514		case PPP_IPX:
515			/* IPX IPXCP not implemented yet */
516			if (sp->pp_phase == PHASE_NETWORK) {
517				schednetisr (NETISR_IPX);
518				inq = &ipxintrq;
519			}
520			break;
521#endif
522#ifdef NS
523		case PPP_XNS:
524			/* XNS IDPCP not implemented yet */
525			if (sp->pp_phase == PHASE_NETWORK) {
526				schednetisr (NETISR_NS);
527				inq = &nsintrq;
528			}
529			break;
530#endif
531#ifdef ISO
532		case PPP_ISO:
533			/* OSI NLCP not implemented yet */
534			if (sp->pp_phase == PHASE_NETWORK) {
535				schednetisr (NETISR_ISO);
536				inq = &clnlintrq;
537			}
538			break;
539#endif
540		}
541		break;
542	case CISCO_MULTICAST:
543	case CISCO_UNICAST:
544		/* Don't check the control field here (RFC 1547). */
545		if (! (sp->pp_flags & PP_CISCO)) {
546			if (debug)
547				log(LOG_DEBUG,
548				    SPP_FMT "Cisco packet in PPP mode "
549				    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
550				    SPP_ARGS(ifp),
551				    h->address, h->control, ntohs(h->protocol));
552			goto drop;
553		}
554		switch (ntohs (h->protocol)) {
555		default:
556			++ifp->if_noproto;
557			goto invalid;
558		case CISCO_KEEPALIVE:
559			sppp_cisco_input ((struct sppp*) ifp, m);
560			m_freem (m);
561			return;
562#ifdef INET
563		case ETHERTYPE_IP:
564			schednetisr (NETISR_IP);
565			inq = &ipintrq;
566			break;
567#endif
568#ifdef IPX
569		case ETHERTYPE_IPX:
570			schednetisr (NETISR_IPX);
571			inq = &ipxintrq;
572			break;
573#endif
574#ifdef NS
575		case ETHERTYPE_NS:
576			schednetisr (NETISR_NS);
577			inq = &nsintrq;
578			break;
579#endif
580		}
581		break;
582	default:        /* Invalid PPP packet. */
583	  invalid:
584		if (debug)
585			log(LOG_DEBUG,
586			    SPP_FMT "invalid input packet "
587			    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
588			    SPP_ARGS(ifp),
589			    h->address, h->control, ntohs(h->protocol));
590		goto drop;
591	}
592
593	if (! (ifp->if_flags & IFF_UP) || ! inq)
594		goto drop;
595
596	/* Check queue. */
597	s = splimp();
598	if (IF_QFULL (inq)) {
599		/* Queue overflow. */
600		IF_DROP(inq);
601		splx(s);
602		if (debug)
603			log(LOG_DEBUG, SPP_FMT "protocol queue overflow\n",
604				SPP_ARGS(ifp));
605		goto drop;
606	}
607	IF_ENQUEUE(inq, m);
608	splx(s);
609}
610
611/*
612 * Enqueue transmit packet.
613 */
614static int
615sppp_output(struct ifnet *ifp, struct mbuf *m,
616	    struct sockaddr *dst, struct rtentry *rt)
617{
618	struct sppp *sp = (struct sppp*) ifp;
619	struct ppp_header *h;
620	struct ifqueue *ifq;
621	int s, rv = 0;
622	int debug = ifp->if_flags & IFF_DEBUG;
623
624	s = splimp();
625
626	if ((ifp->if_flags & IFF_UP) == 0 ||
627	    (ifp->if_flags & (IFF_RUNNING | IFF_AUTO)) == 0) {
628		m_freem (m);
629		splx (s);
630		return (ENETDOWN);
631	}
632
633	if ((ifp->if_flags & (IFF_RUNNING | IFF_AUTO)) == IFF_AUTO) {
634		/*
635		 * Interface is not yet running, but auto-dial.  Need
636		 * to start LCP for it.
637		 */
638		ifp->if_flags |= IFF_RUNNING;
639		splx(s);
640		lcp.Open(sp);
641		s = splimp();
642	}
643
644	ifq = &ifp->if_snd;
645#ifdef INET
646	/*
647	 * Put low delay, telnet, rlogin and ftp control packets
648	 * in front of the queue.
649	 */
650	if (dst->sa_family == AF_INET) {
651		/* XXX Check mbuf length here? */
652		struct ip *ip = mtod (m, struct ip*);
653		struct tcphdr *tcp = (struct tcphdr*) ((long*)ip + ip->ip_hl);
654
655		if (IF_QFULL (&sp->pp_fastq))
656			;
657		else if (ip->ip_tos & IPTOS_LOWDELAY)
658			ifq = &sp->pp_fastq;
659		else if (m->m_len < sizeof *ip + sizeof *tcp)
660			;
661		else if (ip->ip_p != IPPROTO_TCP)
662			;
663		else if (INTERACTIVE (ntohs (tcp->th_sport)))
664			ifq = &sp->pp_fastq;
665		else if (INTERACTIVE (ntohs (tcp->th_dport)))
666			ifq = &sp->pp_fastq;
667	}
668#endif
669
670	/*
671	 * Prepend general data packet PPP header. For now, IP only.
672	 */
673	M_PREPEND (m, PPP_HEADER_LEN, M_DONTWAIT);
674	if (! m) {
675		if (debug)
676			log(LOG_DEBUG, SPP_FMT "no memory for transmit header\n",
677				SPP_ARGS(ifp));
678		++ifp->if_oerrors;
679		splx (s);
680		return (ENOBUFS);
681	}
682	/*
683	 * May want to check size of packet
684	 * (albeit due to the implementation it's always enough)
685	 */
686	h = mtod (m, struct ppp_header*);
687	if (sp->pp_flags & PP_CISCO) {
688		h->address = CISCO_UNICAST;        /* unicast address */
689		h->control = 0;
690	} else {
691		h->address = PPP_ALLSTATIONS;        /* broadcast address */
692		h->control = PPP_UI;                 /* Unnumbered Info */
693	}
694
695	switch (dst->sa_family) {
696#ifdef INET
697	case AF_INET:   /* Internet Protocol */
698		if (sp->pp_flags & PP_CISCO)
699			h->protocol = htons (ETHERTYPE_IP);
700		else {
701			/*
702			 * Don't choke with an ENETDOWN early.  It's
703			 * possible that we just started dialing out,
704			 * so don't drop the packet immediately.  If
705			 * we notice that we run out of buffer space
706			 * below, we will however remember that we are
707			 * not ready to carry IP packets, and return
708			 * ENETDOWN, as opposed to ENOBUFS.
709			 */
710			h->protocol = htons(PPP_IP);
711			if (sp->state[IDX_IPCP] != STATE_OPENED)
712				rv = ENETDOWN;
713		}
714		break;
715#endif
716#ifdef NS
717	case AF_NS:     /* Xerox NS Protocol */
718		h->protocol = htons ((sp->pp_flags & PP_CISCO) ?
719			ETHERTYPE_NS : PPP_XNS);
720		break;
721#endif
722#ifdef IPX
723	case AF_IPX:     /* Novell IPX Protocol */
724		h->protocol = htons ((sp->pp_flags & PP_CISCO) ?
725			ETHERTYPE_IPX : PPP_IPX);
726		break;
727#endif
728#ifdef ISO
729	case AF_ISO:    /* ISO OSI Protocol */
730		if (sp->pp_flags & PP_CISCO)
731			goto nosupport;
732		h->protocol = htons (PPP_ISO);
733		break;
734nosupport:
735#endif
736	default:
737		m_freem (m);
738		++ifp->if_oerrors;
739		splx (s);
740		return (EAFNOSUPPORT);
741	}
742
743	/*
744	 * Queue message on interface, and start output if interface
745	 * not yet active.
746	 */
747	if (IF_QFULL (ifq)) {
748		IF_DROP (&ifp->if_snd);
749		m_freem (m);
750		++ifp->if_oerrors;
751		splx (s);
752		return (rv? rv: ENOBUFS);
753	}
754	IF_ENQUEUE (ifq, m);
755	if (! (ifp->if_flags & IFF_OACTIVE))
756		(*ifp->if_start) (ifp);
757
758	/*
759	 * Count output packets and bytes.
760	 * The packet length includes header, FCS and 1 flag,
761	 * according to RFC 1333.
762	 */
763	ifp->if_obytes += m->m_pkthdr.len + 3;
764	splx (s);
765	return (0);
766}
767
768void
769sppp_attach(struct ifnet *ifp)
770{
771	struct sppp *sp = (struct sppp*) ifp;
772
773	/* Initialize keepalive handler. */
774	if (! spppq)
775		TIMEOUT(sppp_keepalive, 0, hz * 10, keepalive_ch);
776
777	/* Insert new entry into the keepalive list. */
778	sp->pp_next = spppq;
779	spppq = sp;
780
781	sp->pp_if.if_mtu = PP_MTU;
782	sp->pp_if.if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
783	sp->pp_if.if_type = IFT_PPP;
784	sp->pp_if.if_output = sppp_output;
785	sp->pp_flags = PP_KEEPALIVE;
786	sp->pp_fastq.ifq_maxlen = 32;
787	sp->pp_cpq.ifq_maxlen = 20;
788	sp->pp_loopcnt = 0;
789	sp->pp_alivecnt = 0;
790	sp->pp_seq = 0;
791	sp->pp_rseq = 0;
792	sp->pp_phase = PHASE_DEAD;
793	sp->pp_up = lcp.Up;
794	sp->pp_down = lcp.Down;
795
796	sppp_lcp_init(sp);
797	sppp_ipcp_init(sp);
798	sppp_pap_init(sp);
799	sppp_chap_init(sp);
800}
801
802void
803sppp_detach(struct ifnet *ifp)
804{
805	struct sppp **q, *p, *sp = (struct sppp*) ifp;
806	int i;
807
808	/* Remove the entry from the keepalive list. */
809	for (q = &spppq; (p = *q); q = &p->pp_next)
810		if (p == sp) {
811			*q = p->pp_next;
812			break;
813		}
814
815	/* Stop keepalive handler. */
816	if (! spppq)
817		UNTIMEOUT(sppp_keepalive, 0, keepalive_ch);
818
819	for (i = 0; i < IDX_COUNT; i++)
820		UNTIMEOUT((cps[i])->TO, (void *)sp, sp->ch[i]);
821	UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
822}
823
824/*
825 * Flush the interface output queue.
826 */
827void
828sppp_flush(struct ifnet *ifp)
829{
830	struct sppp *sp = (struct sppp*) ifp;
831
832	sppp_qflush (&sp->pp_if.if_snd);
833	sppp_qflush (&sp->pp_fastq);
834	sppp_qflush (&sp->pp_cpq);
835}
836
837/*
838 * Check if the output queue is empty.
839 */
840int
841sppp_isempty(struct ifnet *ifp)
842{
843	struct sppp *sp = (struct sppp*) ifp;
844	int empty, s;
845
846	s = splimp();
847	empty = !sp->pp_fastq.ifq_head && !sp->pp_cpq.ifq_head &&
848		!sp->pp_if.if_snd.ifq_head;
849	splx(s);
850	return (empty);
851}
852
853/*
854 * Get next packet to send.
855 */
856struct mbuf *
857sppp_dequeue(struct ifnet *ifp)
858{
859	struct sppp *sp = (struct sppp*) ifp;
860	struct mbuf *m;
861	int s;
862
863	s = splimp();
864	/*
865	 * Process only the control protocol queue until we have at
866	 * least one NCP open.
867	 *
868	 * Do always serve all three queues in Cisco mode.
869	 */
870	IF_DEQUEUE(&sp->pp_cpq, m);
871	if (m == NULL &&
872	    (sppp_ncp_check(sp) || (sp->pp_flags & PP_CISCO) != 0)) {
873		IF_DEQUEUE(&sp->pp_fastq, m);
874		if (m == NULL)
875			IF_DEQUEUE (&sp->pp_if.if_snd, m);
876	}
877	splx(s);
878	return m;
879}
880
881/*
882 * Pick the next packet, do not remove it from the queue.
883 */
884struct mbuf *
885sppp_pick(struct ifnet *ifp)
886{
887	struct sppp *sp = (struct sppp*)ifp;
888	struct mbuf *m;
889	int s;
890
891	s= splimp ();
892
893	m = sp->pp_cpq.ifq_head;
894	if (m == NULL &&
895	    (sp->pp_phase == PHASE_NETWORK ||
896	     (sp->pp_flags & PP_CISCO) != 0))
897		if ((m = sp->pp_fastq.ifq_head) == NULL)
898			m = sp->pp_if.if_snd.ifq_head;
899	splx (s);
900	return (m);
901}
902
903/*
904 * Process an ioctl request.  Called on low priority level.
905 */
906int
907sppp_ioctl(struct ifnet *ifp, u_long cmd, void *data)
908{
909	struct ifreq *ifr = (struct ifreq*) data;
910	struct sppp *sp = (struct sppp*) ifp;
911	int s, rv, going_up, going_down, newmode;
912
913	s = splimp();
914	rv = 0;
915	switch (cmd) {
916	case SIOCAIFADDR:
917	case SIOCSIFDSTADDR:
918		break;
919
920	case SIOCSIFADDR:
921		if_up(ifp);
922		/* fall through... */
923
924	case SIOCSIFFLAGS:
925		going_up = ifp->if_flags & IFF_UP &&
926			(ifp->if_flags & IFF_RUNNING) == 0;
927		going_down = (ifp->if_flags & IFF_UP) == 0 &&
928			ifp->if_flags & IFF_RUNNING;
929		newmode = ifp->if_flags & (IFF_AUTO | IFF_PASSIVE);
930		if (newmode == (IFF_AUTO | IFF_PASSIVE)) {
931			/* sanity */
932			newmode = IFF_PASSIVE;
933			ifp->if_flags &= ~IFF_AUTO;
934		}
935
936		if (going_up || going_down)
937			lcp.Close(sp);
938		if (going_up && newmode == 0) {
939			/* neither auto-dial nor passive */
940			ifp->if_flags |= IFF_RUNNING;
941			if (!(sp->pp_flags & PP_CISCO))
942				lcp.Open(sp);
943		} else if (going_down) {
944			sppp_flush(ifp);
945			ifp->if_flags &= ~IFF_RUNNING;
946		}
947
948		break;
949
950#ifdef SIOCSIFMTU
951#ifndef ifr_mtu
952#define ifr_mtu ifr_metric
953#endif
954	case SIOCSIFMTU:
955		if (ifr->ifr_mtu < 128 || ifr->ifr_mtu > sp->lcp.their_mru)
956			return (EINVAL);
957		ifp->if_mtu = ifr->ifr_mtu;
958		break;
959#endif
960#ifdef SLIOCSETMTU
961	case SLIOCSETMTU:
962		if (*(short*)data < 128 || *(short*)data > sp->lcp.their_mru)
963			return (EINVAL);
964		ifp->if_mtu = *(short*)data;
965		break;
966#endif
967#ifdef SIOCGIFMTU
968	case SIOCGIFMTU:
969		ifr->ifr_mtu = ifp->if_mtu;
970		break;
971#endif
972#ifdef SLIOCGETMTU
973	case SLIOCGETMTU:
974		*(short*)data = ifp->if_mtu;
975		break;
976#endif
977	case SIOCADDMULTI:
978	case SIOCDELMULTI:
979		break;
980
981	case SIOCGIFGENERIC:
982	case SIOCSIFGENERIC:
983		rv = sppp_params(sp, cmd, data);
984		break;
985
986	default:
987		rv = ENOTTY;
988	}
989	splx(s);
990	return rv;
991}
992
993
994/*
995 * Cisco framing implementation.
996 */
997
998/*
999 * Handle incoming Cisco keepalive protocol packets.
1000 */
1001static void
1002sppp_cisco_input(struct sppp *sp, struct mbuf *m)
1003{
1004	STDDCL;
1005	struct cisco_packet *h;
1006	u_long me, mymask;
1007
1008	if (m->m_pkthdr.len < CISCO_PACKET_LEN) {
1009		if (debug)
1010			log(LOG_DEBUG,
1011			    SPP_FMT "cisco invalid packet length: %d bytes\n",
1012			    SPP_ARGS(ifp), m->m_pkthdr.len);
1013		return;
1014	}
1015	h = mtod (m, struct cisco_packet*);
1016	if (debug)
1017		log(LOG_DEBUG,
1018		    SPP_FMT "cisco input: %d bytes "
1019		    "<0x%lx 0x%lx 0x%lx 0x%x 0x%x-0x%x>\n",
1020		    SPP_ARGS(ifp), m->m_pkthdr.len,
1021		    (u_long)ntohl (h->type), (u_long)h->par1, (u_long)h->par2, (u_int)h->rel,
1022		    (u_int)h->time0, (u_int)h->time1);
1023	switch (ntohl (h->type)) {
1024	default:
1025		if (debug)
1026			addlog(SPP_FMT "cisco unknown packet type: 0x%lx\n",
1027			       SPP_ARGS(ifp), (u_long)ntohl (h->type));
1028		break;
1029	case CISCO_ADDR_REPLY:
1030		/* Reply on address request, ignore */
1031		break;
1032	case CISCO_KEEPALIVE_REQ:
1033		sp->pp_alivecnt = 0;
1034		sp->pp_rseq = ntohl (h->par1);
1035		if (sp->pp_seq == sp->pp_rseq) {
1036			/* Local and remote sequence numbers are equal.
1037			 * Probably, the line is in loopback mode. */
1038			if (sp->pp_loopcnt >= MAXALIVECNT) {
1039				printf (SPP_FMT "loopback\n",
1040					SPP_ARGS(ifp));
1041				sp->pp_loopcnt = 0;
1042				if (ifp->if_flags & IFF_UP) {
1043					if_down (ifp);
1044					sppp_qflush (&sp->pp_cpq);
1045				}
1046			}
1047			++sp->pp_loopcnt;
1048
1049			/* Generate new local sequence number */
1050#if defined(__FreeBSD__) && __FreeBSD__ >= 3
1051			sp->pp_seq = random();
1052#else
1053			sp->pp_seq ^= time.tv_sec ^ time.tv_usec;
1054#endif
1055			break;
1056		}
1057		sp->pp_loopcnt = 0;
1058		if (! (ifp->if_flags & IFF_UP) &&
1059		    (ifp->if_flags & IFF_RUNNING)) {
1060			if_up(ifp);
1061			printf (SPP_FMT "up\n", SPP_ARGS(ifp));
1062		}
1063		break;
1064	case CISCO_ADDR_REQ:
1065		sppp_get_ip_addrs(sp, &me, 0, &mymask);
1066		if (me != 0L)
1067			sppp_cisco_send(sp, CISCO_ADDR_REPLY, me, mymask);
1068		break;
1069	}
1070}
1071
1072/*
1073 * Send Cisco keepalive packet.
1074 */
1075static void
1076sppp_cisco_send(struct sppp *sp, int type, long par1, long par2)
1077{
1078	STDDCL;
1079	struct ppp_header *h;
1080	struct cisco_packet *ch;
1081	struct mbuf *m;
1082#if defined(__FreeBSD__) && __FreeBSD__ >= 3
1083	struct timeval tv;
1084#else
1085	u_long t = (time.tv_sec - boottime.tv_sec) * 1000;
1086#endif
1087
1088#if defined(__FreeBSD__) && __FreeBSD__ >= 3
1089	getmicrouptime(&tv);
1090#endif
1091
1092	MGETHDR (m, M_DONTWAIT, MT_DATA);
1093	if (! m)
1094		return;
1095	m->m_pkthdr.len = m->m_len = PPP_HEADER_LEN + CISCO_PACKET_LEN;
1096	m->m_pkthdr.rcvif = 0;
1097
1098	h = mtod (m, struct ppp_header*);
1099	h->address = CISCO_MULTICAST;
1100	h->control = 0;
1101	h->protocol = htons (CISCO_KEEPALIVE);
1102
1103	ch = (struct cisco_packet*) (h + 1);
1104	ch->type = htonl (type);
1105	ch->par1 = htonl (par1);
1106	ch->par2 = htonl (par2);
1107	ch->rel = -1;
1108
1109#if defined(__FreeBSD__) && __FreeBSD__ >= 3
1110	ch->time0 = htons ((u_short) (tv.tv_sec >> 16));
1111	ch->time1 = htons ((u_short) tv.tv_sec);
1112#else
1113	ch->time0 = htons ((u_short) (t >> 16));
1114	ch->time1 = htons ((u_short) t);
1115#endif
1116
1117	if (debug)
1118		log(LOG_DEBUG,
1119		    SPP_FMT "cisco output: <0x%lx 0x%lx 0x%lx 0x%x 0x%x-0x%x>\n",
1120			SPP_ARGS(ifp), (u_long)ntohl (ch->type), (u_long)ch->par1,
1121			(u_long)ch->par2, (u_int)ch->rel, (u_int)ch->time0, (u_int)ch->time1);
1122
1123	if (IF_QFULL (&sp->pp_cpq)) {
1124		IF_DROP (&sp->pp_fastq);
1125		IF_DROP (&ifp->if_snd);
1126		m_freem (m);
1127	} else
1128		IF_ENQUEUE (&sp->pp_cpq, m);
1129	if (! (ifp->if_flags & IFF_OACTIVE))
1130		(*ifp->if_start) (ifp);
1131	ifp->if_obytes += m->m_pkthdr.len + 3;
1132}
1133
1134/*
1135 * PPP protocol implementation.
1136 */
1137
1138/*
1139 * Send PPP control protocol packet.
1140 */
1141static void
1142sppp_cp_send(struct sppp *sp, u_short proto, u_char type,
1143	     u_char ident, u_short len, void *data)
1144{
1145	STDDCL;
1146	struct ppp_header *h;
1147	struct lcp_header *lh;
1148	struct mbuf *m;
1149
1150	if (len > MHLEN - PPP_HEADER_LEN - LCP_HEADER_LEN)
1151		len = MHLEN - PPP_HEADER_LEN - LCP_HEADER_LEN;
1152	MGETHDR (m, M_DONTWAIT, MT_DATA);
1153	if (! m)
1154		return;
1155	m->m_pkthdr.len = m->m_len = PPP_HEADER_LEN + LCP_HEADER_LEN + len;
1156	m->m_pkthdr.rcvif = 0;
1157
1158	h = mtod (m, struct ppp_header*);
1159	h->address = PPP_ALLSTATIONS;        /* broadcast address */
1160	h->control = PPP_UI;                 /* Unnumbered Info */
1161	h->protocol = htons (proto);         /* Link Control Protocol */
1162
1163	lh = (struct lcp_header*) (h + 1);
1164	lh->type = type;
1165	lh->ident = ident;
1166	lh->len = htons (LCP_HEADER_LEN + len);
1167	if (len)
1168		bcopy (data, lh+1, len);
1169
1170	if (debug) {
1171		log(LOG_DEBUG, SPP_FMT "%s output <%s id=0x%x len=%d",
1172		    SPP_ARGS(ifp),
1173		    sppp_proto_name(proto),
1174		    sppp_cp_type_name (lh->type), lh->ident,
1175		    ntohs (lh->len));
1176		if (len)
1177			sppp_print_bytes ((u_char*) (lh+1), len);
1178		addlog(">\n");
1179	}
1180	if (IF_QFULL (&sp->pp_cpq)) {
1181		IF_DROP (&sp->pp_fastq);
1182		IF_DROP (&ifp->if_snd);
1183		m_freem (m);
1184		++ifp->if_oerrors;
1185	} else
1186		IF_ENQUEUE (&sp->pp_cpq, m);
1187	if (! (ifp->if_flags & IFF_OACTIVE))
1188		(*ifp->if_start) (ifp);
1189	ifp->if_obytes += m->m_pkthdr.len + 3;
1190}
1191
1192/*
1193 * Handle incoming PPP control protocol packets.
1194 */
1195static void
1196sppp_cp_input(const struct cp *cp, struct sppp *sp, struct mbuf *m)
1197{
1198	STDDCL;
1199	struct lcp_header *h;
1200	int len = m->m_pkthdr.len;
1201	int rv;
1202	u_char *p;
1203
1204	if (len < 4) {
1205		if (debug)
1206			log(LOG_DEBUG,
1207			    SPP_FMT "%s invalid packet length: %d bytes\n",
1208			    SPP_ARGS(ifp), cp->name, len);
1209		return;
1210	}
1211	h = mtod (m, struct lcp_header*);
1212	if (debug) {
1213		log(LOG_DEBUG,
1214		    SPP_FMT "%s input(%s): <%s id=0x%x len=%d",
1215		    SPP_ARGS(ifp), cp->name,
1216		    sppp_state_name(sp->state[cp->protoidx]),
1217		    sppp_cp_type_name (h->type), h->ident, ntohs (h->len));
1218		if (len > 4)
1219			sppp_print_bytes ((u_char*) (h+1), len-4);
1220		addlog(">\n");
1221	}
1222	if (len > ntohs (h->len))
1223		len = ntohs (h->len);
1224	p = (u_char *)(h + 1);
1225	switch (h->type) {
1226	case CONF_REQ:
1227		if (len < 4) {
1228			if (debug)
1229				addlog(SPP_FMT "%s invalid conf-req length %d\n",
1230				       SPP_ARGS(ifp), cp->name,
1231				       len);
1232			++ifp->if_ierrors;
1233			break;
1234		}
1235		/* handle states where RCR doesn't get a SCA/SCN */
1236		switch (sp->state[cp->protoidx]) {
1237		case STATE_CLOSING:
1238		case STATE_STOPPING:
1239			return;
1240		case STATE_CLOSED:
1241			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident,
1242				     0, 0);
1243			return;
1244		}
1245		rv = (cp->RCR)(sp, h, len);
1246		switch (sp->state[cp->protoidx]) {
1247		case STATE_OPENED:
1248			(cp->tld)(sp);
1249			(cp->scr)(sp);
1250			/* fall through... */
1251		case STATE_ACK_SENT:
1252		case STATE_REQ_SENT:
1253			sppp_cp_change_state(cp, sp, rv?
1254					     STATE_ACK_SENT: STATE_REQ_SENT);
1255			break;
1256		case STATE_STOPPED:
1257			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1258			(cp->scr)(sp);
1259			sppp_cp_change_state(cp, sp, rv?
1260					     STATE_ACK_SENT: STATE_REQ_SENT);
1261			break;
1262		case STATE_ACK_RCVD:
1263			if (rv) {
1264				sppp_cp_change_state(cp, sp, STATE_OPENED);
1265				if (debug)
1266					log(LOG_DEBUG, SPP_FMT "%s tlu\n",
1267					    SPP_ARGS(ifp),
1268					    cp->name);
1269				(cp->tlu)(sp);
1270			} else
1271				sppp_cp_change_state(cp, sp, STATE_ACK_RCVD);
1272			break;
1273		default:
1274			printf(SPP_FMT "%s illegal %s in state %s\n",
1275			       SPP_ARGS(ifp), cp->name,
1276			       sppp_cp_type_name(h->type),
1277			       sppp_state_name(sp->state[cp->protoidx]));
1278			++ifp->if_ierrors;
1279		}
1280		break;
1281	case CONF_ACK:
1282		if (h->ident != sp->confid[cp->protoidx]) {
1283			if (debug)
1284				addlog(SPP_FMT "%s id mismatch 0x%x != 0x%x\n",
1285				       SPP_ARGS(ifp), cp->name,
1286				       h->ident, sp->confid[cp->protoidx]);
1287			++ifp->if_ierrors;
1288			break;
1289		}
1290		switch (sp->state[cp->protoidx]) {
1291		case STATE_CLOSED:
1292		case STATE_STOPPED:
1293			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident, 0, 0);
1294			break;
1295		case STATE_CLOSING:
1296		case STATE_STOPPING:
1297			break;
1298		case STATE_REQ_SENT:
1299			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1300			sppp_cp_change_state(cp, sp, STATE_ACK_RCVD);
1301			break;
1302		case STATE_OPENED:
1303			(cp->tld)(sp);
1304			/* fall through */
1305		case STATE_ACK_RCVD:
1306			(cp->scr)(sp);
1307			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1308			break;
1309		case STATE_ACK_SENT:
1310			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1311			sppp_cp_change_state(cp, sp, STATE_OPENED);
1312			if (debug)
1313				log(LOG_DEBUG, SPP_FMT "%s tlu\n",
1314				       SPP_ARGS(ifp), cp->name);
1315			(cp->tlu)(sp);
1316			break;
1317		default:
1318			printf(SPP_FMT "%s illegal %s in state %s\n",
1319			       SPP_ARGS(ifp), cp->name,
1320			       sppp_cp_type_name(h->type),
1321			       sppp_state_name(sp->state[cp->protoidx]));
1322			++ifp->if_ierrors;
1323		}
1324		break;
1325	case CONF_NAK:
1326	case CONF_REJ:
1327		if (h->ident != sp->confid[cp->protoidx]) {
1328			if (debug)
1329				addlog(SPP_FMT "%s id mismatch 0x%x != 0x%x\n",
1330				       SPP_ARGS(ifp), cp->name,
1331				       h->ident, sp->confid[cp->protoidx]);
1332			++ifp->if_ierrors;
1333			break;
1334		}
1335		if (h->type == CONF_NAK)
1336			(cp->RCN_nak)(sp, h, len);
1337		else /* CONF_REJ */
1338			(cp->RCN_rej)(sp, h, len);
1339
1340		switch (sp->state[cp->protoidx]) {
1341		case STATE_CLOSED:
1342		case STATE_STOPPED:
1343			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident, 0, 0);
1344			break;
1345		case STATE_REQ_SENT:
1346		case STATE_ACK_SENT:
1347			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1348			(cp->scr)(sp);
1349			break;
1350		case STATE_OPENED:
1351			(cp->tld)(sp);
1352			/* fall through */
1353		case STATE_ACK_RCVD:
1354			sppp_cp_change_state(cp, sp, STATE_ACK_SENT);
1355			(cp->scr)(sp);
1356			break;
1357		case STATE_CLOSING:
1358		case STATE_STOPPING:
1359			break;
1360		default:
1361			printf(SPP_FMT "%s illegal %s in state %s\n",
1362			       SPP_ARGS(ifp), cp->name,
1363			       sppp_cp_type_name(h->type),
1364			       sppp_state_name(sp->state[cp->protoidx]));
1365			++ifp->if_ierrors;
1366		}
1367		break;
1368
1369	case TERM_REQ:
1370		switch (sp->state[cp->protoidx]) {
1371		case STATE_ACK_RCVD:
1372		case STATE_ACK_SENT:
1373			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1374			/* fall through */
1375		case STATE_CLOSED:
1376		case STATE_STOPPED:
1377		case STATE_CLOSING:
1378		case STATE_STOPPING:
1379		case STATE_REQ_SENT:
1380		  sta:
1381			/* Send Terminate-Ack packet. */
1382			if (debug)
1383				log(LOG_DEBUG, SPP_FMT "%s send terminate-ack\n",
1384				    SPP_ARGS(ifp), cp->name);
1385			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident, 0, 0);
1386			break;
1387		case STATE_OPENED:
1388			(cp->tld)(sp);
1389			sp->rst_counter[cp->protoidx] = 0;
1390			sppp_cp_change_state(cp, sp, STATE_STOPPING);
1391			goto sta;
1392			break;
1393		default:
1394			printf(SPP_FMT "%s illegal %s in state %s\n",
1395			       SPP_ARGS(ifp), cp->name,
1396			       sppp_cp_type_name(h->type),
1397			       sppp_state_name(sp->state[cp->protoidx]));
1398			++ifp->if_ierrors;
1399		}
1400		break;
1401	case TERM_ACK:
1402		switch (sp->state[cp->protoidx]) {
1403		case STATE_CLOSED:
1404		case STATE_STOPPED:
1405		case STATE_REQ_SENT:
1406		case STATE_ACK_SENT:
1407			break;
1408		case STATE_CLOSING:
1409			sppp_cp_change_state(cp, sp, STATE_CLOSED);
1410			(cp->tlf)(sp);
1411			break;
1412		case STATE_STOPPING:
1413			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1414			(cp->tlf)(sp);
1415			break;
1416		case STATE_ACK_RCVD:
1417			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1418			break;
1419		case STATE_OPENED:
1420			(cp->tld)(sp);
1421			(cp->scr)(sp);
1422			sppp_cp_change_state(cp, sp, STATE_ACK_RCVD);
1423			break;
1424		default:
1425			printf(SPP_FMT "%s illegal %s in state %s\n",
1426			       SPP_ARGS(ifp), cp->name,
1427			       sppp_cp_type_name(h->type),
1428			       sppp_state_name(sp->state[cp->protoidx]));
1429			++ifp->if_ierrors;
1430		}
1431		break;
1432	case CODE_REJ:
1433	case PROTO_REJ:
1434		/* XXX catastrophic rejects (RXJ-) aren't handled yet. */
1435		log(LOG_INFO,
1436		    SPP_FMT "%s: ignoring RXJ (%s) for proto 0x%x, "
1437		    "danger will robinson\n",
1438		    SPP_ARGS(ifp), cp->name,
1439		    sppp_cp_type_name(h->type), ntohs(*((u_short *)p)));
1440		switch (sp->state[cp->protoidx]) {
1441		case STATE_CLOSED:
1442		case STATE_STOPPED:
1443		case STATE_REQ_SENT:
1444		case STATE_ACK_SENT:
1445		case STATE_CLOSING:
1446		case STATE_STOPPING:
1447		case STATE_OPENED:
1448			break;
1449		case STATE_ACK_RCVD:
1450			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1451			break;
1452		default:
1453			printf(SPP_FMT "%s illegal %s in state %s\n",
1454			       SPP_ARGS(ifp), cp->name,
1455			       sppp_cp_type_name(h->type),
1456			       sppp_state_name(sp->state[cp->protoidx]));
1457			++ifp->if_ierrors;
1458		}
1459		break;
1460	case DISC_REQ:
1461		if (cp->proto != PPP_LCP)
1462			goto illegal;
1463		/* Discard the packet. */
1464		break;
1465	case ECHO_REQ:
1466		if (cp->proto != PPP_LCP)
1467			goto illegal;
1468		if (sp->state[cp->protoidx] != STATE_OPENED) {
1469			if (debug)
1470				addlog(SPP_FMT "lcp echo req but lcp closed\n",
1471				       SPP_ARGS(ifp));
1472			++ifp->if_ierrors;
1473			break;
1474		}
1475		if (len < 8) {
1476			if (debug)
1477				addlog(SPP_FMT "invalid lcp echo request "
1478				       "packet length: %d bytes\n",
1479				       SPP_ARGS(ifp), len);
1480			break;
1481		}
1482		if (ntohl (*(long*)(h+1)) == sp->lcp.magic) {
1483			/* Line loopback mode detected. */
1484			printf(SPP_FMT "loopback\n", SPP_ARGS(ifp));
1485			if_down (ifp);
1486			sppp_qflush (&sp->pp_cpq);
1487
1488			/* Shut down the PPP link. */
1489			/* XXX */
1490			lcp.Down(sp);
1491			lcp.Up(sp);
1492			break;
1493		}
1494		*(long*)(h+1) = htonl (sp->lcp.magic);
1495		if (debug)
1496			addlog(SPP_FMT "got lcp echo req, sending echo rep\n",
1497			       SPP_ARGS(ifp));
1498		sppp_cp_send (sp, PPP_LCP, ECHO_REPLY, h->ident, len-4, h+1);
1499		break;
1500	case ECHO_REPLY:
1501		if (cp->proto != PPP_LCP)
1502			goto illegal;
1503		if (h->ident != sp->lcp.echoid) {
1504			++ifp->if_ierrors;
1505			break;
1506		}
1507		if (len < 8) {
1508			if (debug)
1509				addlog(SPP_FMT "lcp invalid echo reply "
1510				       "packet length: %d bytes\n",
1511				       SPP_ARGS(ifp), len);
1512			break;
1513		}
1514		if (debug)
1515			addlog(SPP_FMT "lcp got echo rep\n",
1516			       SPP_ARGS(ifp));
1517		if (ntohl (*(long*)(h+1)) != sp->lcp.magic)
1518			sp->pp_alivecnt = 0;
1519		break;
1520	default:
1521		/* Unknown packet type -- send Code-Reject packet. */
1522	  illegal:
1523		if (debug)
1524			addlog(SPP_FMT "%s send code-rej for 0x%x\n",
1525			       SPP_ARGS(ifp), cp->name, h->type);
1526		sppp_cp_send(sp, cp->proto, CODE_REJ, ++sp->pp_seq,
1527			     m->m_pkthdr.len, h);
1528		++ifp->if_ierrors;
1529	}
1530}
1531
1532
1533/*
1534 * The generic part of all Up/Down/Open/Close/TO event handlers.
1535 * Basically, the state transition handling in the automaton.
1536 */
1537static void
1538sppp_up_event(const struct cp *cp, struct sppp *sp)
1539{
1540	STDDCL;
1541
1542	if (debug)
1543		log(LOG_DEBUG, SPP_FMT "%s up(%s)\n",
1544		    SPP_ARGS(ifp), cp->name,
1545		    sppp_state_name(sp->state[cp->protoidx]));
1546
1547	switch (sp->state[cp->protoidx]) {
1548	case STATE_INITIAL:
1549		sppp_cp_change_state(cp, sp, STATE_CLOSED);
1550		break;
1551	case STATE_STARTING:
1552		sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1553		(cp->scr)(sp);
1554		sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1555		break;
1556	default:
1557		printf(SPP_FMT "%s illegal up in state %s\n",
1558		       SPP_ARGS(ifp), cp->name,
1559		       sppp_state_name(sp->state[cp->protoidx]));
1560	}
1561}
1562
1563static void
1564sppp_down_event(const struct cp *cp, struct sppp *sp)
1565{
1566	STDDCL;
1567
1568	if (debug)
1569		log(LOG_DEBUG, SPP_FMT "%s down(%s)\n",
1570		    SPP_ARGS(ifp), cp->name,
1571		    sppp_state_name(sp->state[cp->protoidx]));
1572
1573	switch (sp->state[cp->protoidx]) {
1574	case STATE_CLOSED:
1575	case STATE_CLOSING:
1576		sppp_cp_change_state(cp, sp, STATE_INITIAL);
1577		break;
1578	case STATE_STOPPED:
1579		sppp_cp_change_state(cp, sp, STATE_STARTING);
1580		(cp->tls)(sp);
1581		break;
1582	case STATE_STOPPING:
1583	case STATE_REQ_SENT:
1584	case STATE_ACK_RCVD:
1585	case STATE_ACK_SENT:
1586		sppp_cp_change_state(cp, sp, STATE_STARTING);
1587		break;
1588	case STATE_OPENED:
1589		(cp->tld)(sp);
1590		sppp_cp_change_state(cp, sp, STATE_STARTING);
1591		break;
1592	default:
1593		printf(SPP_FMT "%s illegal down in state %s\n",
1594		       SPP_ARGS(ifp), cp->name,
1595		       sppp_state_name(sp->state[cp->protoidx]));
1596	}
1597}
1598
1599
1600static void
1601sppp_open_event(const struct cp *cp, struct sppp *sp)
1602{
1603	STDDCL;
1604
1605	if (debug)
1606		log(LOG_DEBUG, SPP_FMT "%s open(%s)\n",
1607		    SPP_ARGS(ifp), cp->name,
1608		    sppp_state_name(sp->state[cp->protoidx]));
1609
1610	switch (sp->state[cp->protoidx]) {
1611	case STATE_INITIAL:
1612		sppp_cp_change_state(cp, sp, STATE_STARTING);
1613		(cp->tls)(sp);
1614		break;
1615	case STATE_STARTING:
1616		break;
1617	case STATE_CLOSED:
1618		sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1619		(cp->scr)(sp);
1620		sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1621		break;
1622	case STATE_STOPPED:
1623	case STATE_STOPPING:
1624	case STATE_REQ_SENT:
1625	case STATE_ACK_RCVD:
1626	case STATE_ACK_SENT:
1627	case STATE_OPENED:
1628		break;
1629	case STATE_CLOSING:
1630		sppp_cp_change_state(cp, sp, STATE_STOPPING);
1631		break;
1632	}
1633}
1634
1635
1636static void
1637sppp_close_event(const struct cp *cp, struct sppp *sp)
1638{
1639	STDDCL;
1640
1641	if (debug)
1642		log(LOG_DEBUG, SPP_FMT "%s close(%s)\n",
1643		    SPP_ARGS(ifp), cp->name,
1644		    sppp_state_name(sp->state[cp->protoidx]));
1645
1646	switch (sp->state[cp->protoidx]) {
1647	case STATE_INITIAL:
1648	case STATE_CLOSED:
1649	case STATE_CLOSING:
1650		break;
1651	case STATE_STARTING:
1652		sppp_cp_change_state(cp, sp, STATE_INITIAL);
1653		(cp->tlf)(sp);
1654		break;
1655	case STATE_STOPPED:
1656		sppp_cp_change_state(cp, sp, STATE_CLOSED);
1657		break;
1658	case STATE_STOPPING:
1659		sppp_cp_change_state(cp, sp, STATE_CLOSING);
1660		break;
1661	case STATE_OPENED:
1662		(cp->tld)(sp);
1663		/* fall through */
1664	case STATE_REQ_SENT:
1665	case STATE_ACK_RCVD:
1666	case STATE_ACK_SENT:
1667		sp->rst_counter[cp->protoidx] = sp->lcp.max_terminate;
1668		sppp_cp_send(sp, cp->proto, TERM_REQ, ++sp->pp_seq, 0, 0);
1669		sppp_cp_change_state(cp, sp, STATE_CLOSING);
1670		break;
1671	}
1672}
1673
1674static void
1675sppp_to_event(const struct cp *cp, struct sppp *sp)
1676{
1677	STDDCL;
1678	int s;
1679
1680	s = splimp();
1681	if (debug)
1682		log(LOG_DEBUG, SPP_FMT "%s TO(%s) rst_counter = %d\n",
1683		    SPP_ARGS(ifp), cp->name,
1684		    sppp_state_name(sp->state[cp->protoidx]),
1685		    sp->rst_counter[cp->protoidx]);
1686
1687	if (--sp->rst_counter[cp->protoidx] < 0)
1688		/* TO- event */
1689		switch (sp->state[cp->protoidx]) {
1690		case STATE_CLOSING:
1691			sppp_cp_change_state(cp, sp, STATE_CLOSED);
1692			(cp->tlf)(sp);
1693			break;
1694		case STATE_STOPPING:
1695			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1696			(cp->tlf)(sp);
1697			break;
1698		case STATE_REQ_SENT:
1699		case STATE_ACK_RCVD:
1700		case STATE_ACK_SENT:
1701			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1702			(cp->tlf)(sp);
1703			break;
1704		}
1705	else
1706		/* TO+ event */
1707		switch (sp->state[cp->protoidx]) {
1708		case STATE_CLOSING:
1709		case STATE_STOPPING:
1710			sppp_cp_send(sp, cp->proto, TERM_REQ, ++sp->pp_seq,
1711				     0, 0);
1712			TIMEOUT(cp->TO, (void *)sp, sp->lcp.timeout,
1713			    sp->ch[cp->protoidx]);
1714			break;
1715		case STATE_REQ_SENT:
1716		case STATE_ACK_RCVD:
1717			(cp->scr)(sp);
1718			/* sppp_cp_change_state() will restart the timer */
1719			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1720			break;
1721		case STATE_ACK_SENT:
1722			(cp->scr)(sp);
1723			TIMEOUT(cp->TO, (void *)sp, sp->lcp.timeout,
1724			    sp->ch[cp->protoidx]);
1725			break;
1726		}
1727
1728	splx(s);
1729}
1730
1731/*
1732 * Change the state of a control protocol in the state automaton.
1733 * Takes care of starting/stopping the restart timer.
1734 */
1735void
1736sppp_cp_change_state(const struct cp *cp, struct sppp *sp, int newstate)
1737{
1738	sp->state[cp->protoidx] = newstate;
1739
1740	UNTIMEOUT(cp->TO, (void *)sp, sp->ch[cp->protoidx]);
1741	switch (newstate) {
1742	case STATE_INITIAL:
1743	case STATE_STARTING:
1744	case STATE_CLOSED:
1745	case STATE_STOPPED:
1746	case STATE_OPENED:
1747		break;
1748	case STATE_CLOSING:
1749	case STATE_STOPPING:
1750	case STATE_REQ_SENT:
1751	case STATE_ACK_RCVD:
1752	case STATE_ACK_SENT:
1753		TIMEOUT(cp->TO, (void *)sp, sp->lcp.timeout,
1754		    sp->ch[cp->protoidx]);
1755		break;
1756	}
1757}
1758/*
1759 *--------------------------------------------------------------------------*
1760 *                                                                          *
1761 *                         The LCP implementation.                          *
1762 *                                                                          *
1763 *--------------------------------------------------------------------------*
1764 */
1765static void
1766sppp_lcp_init(struct sppp *sp)
1767{
1768	sp->lcp.opts = (1 << LCP_OPT_MAGIC);
1769	sp->lcp.magic = 0;
1770	sp->state[IDX_LCP] = STATE_INITIAL;
1771	sp->fail_counter[IDX_LCP] = 0;
1772	sp->lcp.protos = 0;
1773	sp->lcp.mru = sp->lcp.their_mru = PP_MTU;
1774
1775	/*
1776	 * Initialize counters and timeout values.  Note that we don't
1777	 * use the 3 seconds suggested in RFC 1661 since we are likely
1778	 * running on a fast link.  XXX We should probably implement
1779	 * the exponential backoff option.  Note that these values are
1780	 * relevant for all control protocols, not just LCP only.
1781	 */
1782	sp->lcp.timeout = 1 * hz;
1783	sp->lcp.max_terminate = 2;
1784	sp->lcp.max_configure = 10;
1785	sp->lcp.max_failure = 10;
1786#if defined(__FreeBSD__) && __FreeBSD__ >= 3
1787	callout_handle_init(&sp->ch[IDX_LCP]);
1788#endif
1789}
1790
1791static void
1792sppp_lcp_up(struct sppp *sp)
1793{
1794	STDDCL;
1795
1796	/*
1797	 * If this interface is passive or dial-on-demand, and we are
1798	 * still in Initial state, it means we've got an incoming
1799	 * call.  Activate the interface.
1800	 */
1801	if ((ifp->if_flags & (IFF_AUTO | IFF_PASSIVE)) != 0) {
1802		if (debug)
1803			log(LOG_DEBUG,
1804			    SPP_FMT "Up event", SPP_ARGS(ifp));
1805		ifp->if_flags |= IFF_RUNNING;
1806		if (sp->state[IDX_LCP] == STATE_INITIAL) {
1807			if (debug)
1808				addlog("(incoming call)\n");
1809			sp->pp_flags |= PP_CALLIN;
1810			lcp.Open(sp);
1811		} else if (debug)
1812			addlog("\n");
1813	}
1814
1815	sppp_up_event(&lcp, sp);
1816}
1817
1818static void
1819sppp_lcp_down(struct sppp *sp)
1820{
1821	STDDCL;
1822
1823	sppp_down_event(&lcp, sp);
1824
1825	/*
1826	 * If this is neither a dial-on-demand nor a passive
1827	 * interface, simulate an ``ifconfig down'' action, so the
1828	 * administrator can force a redial by another ``ifconfig
1829	 * up''.  XXX For leased line operation, should we immediately
1830	 * try to reopen the connection here?
1831	 */
1832	if ((ifp->if_flags & (IFF_AUTO | IFF_PASSIVE)) == 0) {
1833		log(LOG_INFO,
1834		    SPP_FMT "Down event, taking interface down.\n",
1835		    SPP_ARGS(ifp));
1836		if_down(ifp);
1837	} else {
1838		if (debug)
1839			log(LOG_DEBUG,
1840			    SPP_FMT "Down event (carrier loss)\n",
1841			    SPP_ARGS(ifp));
1842	}
1843	sp->pp_flags &= ~PP_CALLIN;
1844	if (sp->state[IDX_LCP] != STATE_INITIAL)
1845		lcp.Close(sp);
1846	ifp->if_flags &= ~IFF_RUNNING;
1847}
1848
1849static void
1850sppp_lcp_open(struct sppp *sp)
1851{
1852	/*
1853	 * If we are authenticator, negotiate LCP_AUTH
1854	 */
1855	if (sp->hisauth.proto != 0)
1856		sp->lcp.opts |= (1 << LCP_OPT_AUTH_PROTO);
1857	else
1858		sp->lcp.opts &= ~(1 << LCP_OPT_AUTH_PROTO);
1859	sp->pp_flags &= ~PP_NEEDAUTH;
1860	sppp_open_event(&lcp, sp);
1861}
1862
1863static void
1864sppp_lcp_close(struct sppp *sp)
1865{
1866	sppp_close_event(&lcp, sp);
1867}
1868
1869static void
1870sppp_lcp_TO(void *cookie)
1871{
1872	sppp_to_event(&lcp, (struct sppp *)cookie);
1873}
1874
1875/*
1876 * Analyze a configure request.  Return true if it was agreeable, and
1877 * caused action sca, false if it has been rejected or nak'ed, and
1878 * caused action scn.  (The return value is used to make the state
1879 * transition decision in the state automaton.)
1880 */
1881static int
1882sppp_lcp_RCR(struct sppp *sp, struct lcp_header *h, int len)
1883{
1884	STDDCL;
1885	u_char *buf, *r, *p;
1886	int origlen, rlen;
1887	u_long nmagic;
1888	u_short authproto;
1889
1890	len -= 4;
1891	origlen = len;
1892	buf = r = malloc (len, M_TEMP, M_NOWAIT);
1893	if (! buf)
1894		return (0);
1895
1896	if (debug)
1897		log(LOG_DEBUG, SPP_FMT "lcp parse opts: ",
1898		    SPP_ARGS(ifp));
1899
1900	/* pass 1: check for things that need to be rejected */
1901	p = (void*) (h+1);
1902	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
1903		if (debug)
1904			addlog(" %s ", sppp_lcp_opt_name(*p));
1905		switch (*p) {
1906		case LCP_OPT_MAGIC:
1907			/* Magic number. */
1908			/* fall through, both are same length */
1909		case LCP_OPT_ASYNC_MAP:
1910			/* Async control character map. */
1911			if (len >= 6 || p[1] == 6)
1912				continue;
1913			if (debug)
1914				addlog("[invalid] ");
1915			break;
1916		case LCP_OPT_MRU:
1917			/* Maximum receive unit. */
1918			if (len >= 4 && p[1] == 4)
1919				continue;
1920			if (debug)
1921				addlog("[invalid] ");
1922			break;
1923		case LCP_OPT_AUTH_PROTO:
1924			if (len < 4) {
1925				if (debug)
1926					addlog("[invalid] ");
1927				break;
1928			}
1929			authproto = (p[2] << 8) + p[3];
1930			if (authproto == PPP_CHAP && p[1] != 5) {
1931				if (debug)
1932					addlog("[invalid chap len] ");
1933				break;
1934			}
1935			if (sp->myauth.proto == 0) {
1936				/* we are not configured to do auth */
1937				if (debug)
1938					addlog("[not configured] ");
1939				break;
1940			}
1941			/*
1942			 * Remote want us to authenticate, remember this,
1943			 * so we stay in PHASE_AUTHENTICATE after LCP got
1944			 * up.
1945			 */
1946			sp->pp_flags |= PP_NEEDAUTH;
1947			continue;
1948		default:
1949			/* Others not supported. */
1950			if (debug)
1951				addlog("[rej] ");
1952			break;
1953		}
1954		/* Add the option to rejected list. */
1955		bcopy (p, r, p[1]);
1956		r += p[1];
1957		rlen += p[1];
1958	}
1959	if (rlen) {
1960		if (debug)
1961			addlog(" send conf-rej\n");
1962		sppp_cp_send (sp, PPP_LCP, CONF_REJ, h->ident, rlen, buf);
1963		return 0;
1964	} else if (debug)
1965		addlog("\n");
1966
1967	/*
1968	 * pass 2: check for option values that are unacceptable and
1969	 * thus require to be nak'ed.
1970	 */
1971	if (debug)
1972		log(LOG_DEBUG, SPP_FMT "lcp parse opt values: ",
1973		    SPP_ARGS(ifp));
1974
1975	p = (void*) (h+1);
1976	len = origlen;
1977	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
1978		if (debug)
1979			addlog(" %s ", sppp_lcp_opt_name(*p));
1980		switch (*p) {
1981		case LCP_OPT_MAGIC:
1982			/* Magic number -- extract. */
1983			nmagic = (u_long)p[2] << 24 |
1984				(u_long)p[3] << 16 | p[4] << 8 | p[5];
1985			if (nmagic != sp->lcp.magic) {
1986				if (debug)
1987					addlog("0x%lx ", nmagic);
1988				continue;
1989			}
1990			/*
1991			 * Local and remote magics equal -- loopback?
1992			 */
1993			if (sp->pp_loopcnt >= MAXALIVECNT*5) {
1994				printf (SPP_FMT "loopback\n",
1995					SPP_ARGS(ifp));
1996				sp->pp_loopcnt = 0;
1997				if (ifp->if_flags & IFF_UP) {
1998					if_down(ifp);
1999					sppp_qflush(&sp->pp_cpq);
2000					/* XXX ? */
2001					lcp.Down(sp);
2002					lcp.Up(sp);
2003				}
2004			} else if (debug)
2005				addlog("[glitch] ");
2006			++sp->pp_loopcnt;
2007			/*
2008			 * We negate our magic here, and NAK it.  If
2009			 * we see it later in an NAK packet, we
2010			 * suggest a new one.
2011			 */
2012			nmagic = ~sp->lcp.magic;
2013			/* Gonna NAK it. */
2014			p[2] = nmagic >> 24;
2015			p[3] = nmagic >> 16;
2016			p[4] = nmagic >> 8;
2017			p[5] = nmagic;
2018			break;
2019
2020		case LCP_OPT_ASYNC_MAP:
2021			/* Async control character map -- check to be zero. */
2022			if (! p[2] && ! p[3] && ! p[4] && ! p[5]) {
2023				if (debug)
2024					addlog("[empty] ");
2025				continue;
2026			}
2027			if (debug)
2028				addlog("[non-empty] ");
2029			/* suggest a zero one */
2030			p[2] = p[3] = p[4] = p[5] = 0;
2031			break;
2032
2033		case LCP_OPT_MRU:
2034			/*
2035			 * Maximum receive unit.  Always agreeable,
2036			 * but ignored by now.
2037			 */
2038			sp->lcp.their_mru = p[2] * 256 + p[3];
2039			if (debug)
2040				addlog("%lu ", sp->lcp.their_mru);
2041			continue;
2042
2043		case LCP_OPT_AUTH_PROTO:
2044			authproto = (p[2] << 8) + p[3];
2045			if (sp->myauth.proto != authproto) {
2046				/* not agreed, nak */
2047				if (debug)
2048					addlog("[mine %s != his %s] ",
2049					       sppp_proto_name(sp->hisauth.proto),
2050					       sppp_proto_name(authproto));
2051				p[2] = sp->myauth.proto >> 8;
2052				p[3] = sp->myauth.proto;
2053				break;
2054			}
2055			if (authproto == PPP_CHAP && p[4] != CHAP_MD5) {
2056				if (debug)
2057					addlog("[chap not MD5] ");
2058				p[4] = CHAP_MD5;
2059				break;
2060			}
2061			continue;
2062		}
2063		/* Add the option to nak'ed list. */
2064		bcopy (p, r, p[1]);
2065		r += p[1];
2066		rlen += p[1];
2067	}
2068	if (rlen) {
2069		if (++sp->fail_counter[IDX_LCP] >= sp->lcp.max_failure) {
2070			if (debug)
2071				addlog(" max_failure (%d) exceeded, "
2072				       "send conf-rej\n",
2073				       sp->lcp.max_failure);
2074			sppp_cp_send(sp, PPP_LCP, CONF_REJ, h->ident, rlen, buf);
2075		} else {
2076			if (debug)
2077				addlog(" send conf-nak\n");
2078			sppp_cp_send (sp, PPP_LCP, CONF_NAK, h->ident, rlen, buf);
2079		}
2080		return 0;
2081	} else {
2082		if (debug)
2083			addlog(" send conf-ack\n");
2084		sp->fail_counter[IDX_LCP] = 0;
2085		sp->pp_loopcnt = 0;
2086		sppp_cp_send (sp, PPP_LCP, CONF_ACK,
2087			      h->ident, origlen, h+1);
2088	}
2089
2090	free (buf, M_TEMP);
2091	return (rlen == 0);
2092}
2093
2094/*
2095 * Analyze the LCP Configure-Reject option list, and adjust our
2096 * negotiation.
2097 */
2098static void
2099sppp_lcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
2100{
2101	STDDCL;
2102	u_char *buf, *p;
2103
2104	len -= 4;
2105	buf = malloc (len, M_TEMP, M_NOWAIT);
2106	if (!buf)
2107		return;
2108
2109	if (debug)
2110		log(LOG_DEBUG, SPP_FMT "lcp rej opts: ",
2111		    SPP_ARGS(ifp));
2112
2113	p = (void*) (h+1);
2114	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2115		if (debug)
2116			addlog(" %s ", sppp_lcp_opt_name(*p));
2117		switch (*p) {
2118		case LCP_OPT_MAGIC:
2119			/* Magic number -- can't use it, use 0 */
2120			sp->lcp.opts &= ~(1 << LCP_OPT_MAGIC);
2121			sp->lcp.magic = 0;
2122			break;
2123		case LCP_OPT_MRU:
2124			/*
2125			 * Should not be rejected anyway, since we only
2126			 * negotiate a MRU if explicitly requested by
2127			 * peer.
2128			 */
2129			sp->lcp.opts &= ~(1 << LCP_OPT_MRU);
2130			break;
2131		case LCP_OPT_AUTH_PROTO:
2132			/*
2133			 * Peer doesn't want to authenticate himself,
2134			 * deny unless this is a dialout call, and
2135			 * AUTHFLAG_NOCALLOUT is set.
2136			 */
2137			if ((sp->pp_flags & PP_CALLIN) == 0 &&
2138			    (sp->hisauth.flags & AUTHFLAG_NOCALLOUT) != 0) {
2139				if (debug)
2140					addlog("[don't insist on auth "
2141					       "for callout]");
2142				sp->lcp.opts &= ~(1 << LCP_OPT_AUTH_PROTO);
2143				break;
2144			}
2145			if (debug)
2146				addlog("[access denied]\n");
2147			lcp.Close(sp);
2148			break;
2149		}
2150	}
2151	if (debug)
2152		addlog("\n");
2153	free (buf, M_TEMP);
2154	return;
2155}
2156
2157/*
2158 * Analyze the LCP Configure-NAK option list, and adjust our
2159 * negotiation.
2160 */
2161static void
2162sppp_lcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
2163{
2164	STDDCL;
2165	u_char *buf, *p;
2166	u_long magic;
2167
2168	len -= 4;
2169	buf = malloc (len, M_TEMP, M_NOWAIT);
2170	if (!buf)
2171		return;
2172
2173	if (debug)
2174		log(LOG_DEBUG, SPP_FMT "lcp nak opts: ",
2175		    SPP_ARGS(ifp));
2176
2177	p = (void*) (h+1);
2178	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2179		if (debug)
2180			addlog(" %s ", sppp_lcp_opt_name(*p));
2181		switch (*p) {
2182		case LCP_OPT_MAGIC:
2183			/* Magic number -- renegotiate */
2184			if ((sp->lcp.opts & (1 << LCP_OPT_MAGIC)) &&
2185			    len >= 6 && p[1] == 6) {
2186				magic = (u_long)p[2] << 24 |
2187					(u_long)p[3] << 16 | p[4] << 8 | p[5];
2188				/*
2189				 * If the remote magic is our negated one,
2190				 * this looks like a loopback problem.
2191				 * Suggest a new magic to make sure.
2192				 */
2193				if (magic == ~sp->lcp.magic) {
2194					if (debug)
2195						addlog("magic glitch ");
2196#if defined(__FreeBSD__) && __FreeBSD__ >= 3
2197					sp->lcp.magic = random();
2198#else
2199					sp->lcp.magic = time.tv_sec + time.tv_usec;
2200#endif
2201				} else {
2202					sp->lcp.magic = magic;
2203					if (debug)
2204						addlog("%lu ", magic);
2205				}
2206			}
2207			break;
2208		case LCP_OPT_MRU:
2209			/*
2210			 * Peer wants to advise us to negotiate an MRU.
2211			 * Agree on it if it's reasonable, or use
2212			 * default otherwise.
2213			 */
2214			if (len >= 4 && p[1] == 4) {
2215				u_int mru = p[2] * 256 + p[3];
2216				if (debug)
2217					addlog("%d ", mru);
2218				if (mru < PP_MTU || mru > PP_MAX_MRU)
2219					mru = PP_MTU;
2220				sp->lcp.mru = mru;
2221				sp->lcp.opts |= (1 << LCP_OPT_MRU);
2222			}
2223			break;
2224		case LCP_OPT_AUTH_PROTO:
2225			/*
2226			 * Peer doesn't like our authentication method,
2227			 * deny.
2228			 */
2229			if (debug)
2230				addlog("[access denied]\n");
2231			lcp.Close(sp);
2232			break;
2233		}
2234	}
2235	if (debug)
2236		addlog("\n");
2237	free (buf, M_TEMP);
2238	return;
2239}
2240
2241static void
2242sppp_lcp_tlu(struct sppp *sp)
2243{
2244	STDDCL;
2245	int i;
2246	u_long mask;
2247
2248	/* XXX ? */
2249	if (! (ifp->if_flags & IFF_UP) &&
2250	    (ifp->if_flags & IFF_RUNNING)) {
2251		/* Coming out of loopback mode. */
2252		if_up(ifp);
2253		printf (SPP_FMT "up\n", SPP_ARGS(ifp));
2254	}
2255
2256	for (i = 0; i < IDX_COUNT; i++)
2257		if ((cps[i])->flags & CP_QUAL)
2258			(cps[i])->Open(sp);
2259
2260	if ((sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0 ||
2261	    (sp->pp_flags & PP_NEEDAUTH) != 0)
2262		sp->pp_phase = PHASE_AUTHENTICATE;
2263	else
2264		sp->pp_phase = PHASE_NETWORK;
2265
2266	if (debug)
2267		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2268		    sppp_phase_name(sp->pp_phase));
2269
2270	/*
2271	 * Open all authentication protocols.  This is even required
2272	 * if we already proceeded to network phase, since it might be
2273	 * that remote wants us to authenticate, so we might have to
2274	 * send a PAP request.  Undesired authentication protocols
2275	 * don't do anything when they get an Open event.
2276	 */
2277	for (i = 0; i < IDX_COUNT; i++)
2278		if ((cps[i])->flags & CP_AUTH)
2279			(cps[i])->Open(sp);
2280
2281	if (sp->pp_phase == PHASE_NETWORK) {
2282		/* Notify all NCPs. */
2283		for (i = 0; i < IDX_COUNT; i++)
2284			if ((cps[i])->flags & CP_NCP)
2285				(cps[i])->Open(sp);
2286	}
2287
2288	/* Send Up events to all started protos. */
2289	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2290		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_LCP) == 0)
2291			(cps[i])->Up(sp);
2292
2293	if (sp->pp_phase == PHASE_NETWORK)
2294		/* if no NCP is starting, close down */
2295		sppp_lcp_check_and_close(sp);
2296}
2297
2298static void
2299sppp_lcp_tld(struct sppp *sp)
2300{
2301	STDDCL;
2302	int i;
2303	u_long mask;
2304
2305	sp->pp_phase = PHASE_TERMINATE;
2306
2307	if (debug)
2308		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2309		    sppp_phase_name(sp->pp_phase));
2310
2311	/*
2312	 * Take upper layers down.  We send the Down event first and
2313	 * the Close second to prevent the upper layers from sending
2314	 * ``a flurry of terminate-request packets'', as the RFC
2315	 * describes it.
2316	 */
2317	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2318		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_LCP) == 0) {
2319			(cps[i])->Down(sp);
2320			(cps[i])->Close(sp);
2321		}
2322}
2323
2324static void
2325sppp_lcp_tls(struct sppp *sp)
2326{
2327	STDDCL;
2328
2329	sp->pp_phase = PHASE_ESTABLISH;
2330
2331	if (debug)
2332		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2333		    sppp_phase_name(sp->pp_phase));
2334
2335	/* Notify lower layer if desired. */
2336	if (sp->pp_tls)
2337		(sp->pp_tls)(sp);
2338	else
2339		(sp->pp_up)(sp);
2340}
2341
2342static void
2343sppp_lcp_tlf(struct sppp *sp)
2344{
2345	STDDCL;
2346
2347	sp->pp_phase = PHASE_DEAD;
2348	if (debug)
2349		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2350		    sppp_phase_name(sp->pp_phase));
2351
2352	/* Notify lower layer if desired. */
2353	if (sp->pp_tlf)
2354		(sp->pp_tlf)(sp);
2355	else
2356		(sp->pp_down)(sp);
2357}
2358
2359static void
2360sppp_lcp_scr(struct sppp *sp)
2361{
2362	char opt[6 /* magicnum */ + 4 /* mru */ + 5 /* chap */];
2363	int i = 0;
2364	u_short authproto;
2365
2366	if (sp->lcp.opts & (1 << LCP_OPT_MAGIC)) {
2367		if (! sp->lcp.magic)
2368#if defined(__FreeBSD__) && __FreeBSD__ >= 3
2369			sp->lcp.magic = random();
2370#else
2371			sp->lcp.magic = time.tv_sec + time.tv_usec;
2372#endif
2373		opt[i++] = LCP_OPT_MAGIC;
2374		opt[i++] = 6;
2375		opt[i++] = sp->lcp.magic >> 24;
2376		opt[i++] = sp->lcp.magic >> 16;
2377		opt[i++] = sp->lcp.magic >> 8;
2378		opt[i++] = sp->lcp.magic;
2379	}
2380
2381	if (sp->lcp.opts & (1 << LCP_OPT_MRU)) {
2382		opt[i++] = LCP_OPT_MRU;
2383		opt[i++] = 4;
2384		opt[i++] = sp->lcp.mru >> 8;
2385		opt[i++] = sp->lcp.mru;
2386	}
2387
2388	if (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) {
2389		authproto = sp->hisauth.proto;
2390		opt[i++] = LCP_OPT_AUTH_PROTO;
2391		opt[i++] = authproto == PPP_CHAP? 5: 4;
2392		opt[i++] = authproto >> 8;
2393		opt[i++] = authproto;
2394		if (authproto == PPP_CHAP)
2395			opt[i++] = CHAP_MD5;
2396	}
2397
2398	sp->confid[IDX_LCP] = ++sp->pp_seq;
2399	sppp_cp_send (sp, PPP_LCP, CONF_REQ, sp->confid[IDX_LCP], i, &opt);
2400}
2401
2402/*
2403 * Check the open NCPs, return true if at least one NCP is open.
2404 */
2405static int
2406sppp_ncp_check(struct sppp *sp)
2407{
2408	int i, mask;
2409
2410	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2411		if (sp->lcp.protos & mask && (cps[i])->flags & CP_NCP)
2412			return 1;
2413	return 0;
2414}
2415
2416/*
2417 * Re-check the open NCPs and see if we should terminate the link.
2418 * Called by the NCPs during their tlf action handling.
2419 */
2420static void
2421sppp_lcp_check_and_close(struct sppp *sp)
2422{
2423
2424	if (sp->pp_phase < PHASE_NETWORK)
2425		/* don't bother, we are already going down */
2426		return;
2427
2428	if (sppp_ncp_check(sp))
2429		return;
2430
2431	lcp.Close(sp);
2432}
2433/*
2434 *--------------------------------------------------------------------------*
2435 *                                                                          *
2436 *                        The IPCP implementation.                          *
2437 *                                                                          *
2438 *--------------------------------------------------------------------------*
2439 */
2440
2441static void
2442sppp_ipcp_init(struct sppp *sp)
2443{
2444	sp->ipcp.opts = 0;
2445	sp->ipcp.flags = 0;
2446	sp->state[IDX_IPCP] = STATE_INITIAL;
2447	sp->fail_counter[IDX_IPCP] = 0;
2448#if defined(__FreeBSD__) && __FreeBSD__ >= 3
2449	callout_handle_init(&sp->ch[IDX_IPCP]);
2450#endif
2451}
2452
2453static void
2454sppp_ipcp_up(struct sppp *sp)
2455{
2456	sppp_up_event(&ipcp, sp);
2457}
2458
2459static void
2460sppp_ipcp_down(struct sppp *sp)
2461{
2462	sppp_down_event(&ipcp, sp);
2463}
2464
2465static void
2466sppp_ipcp_open(struct sppp *sp)
2467{
2468	STDDCL;
2469	u_long myaddr, hisaddr;
2470
2471	sppp_get_ip_addrs(sp, &myaddr, &hisaddr, 0);
2472	/*
2473	 * If we don't have his address, this probably means our
2474	 * interface doesn't want to talk IP at all.  (This could
2475	 * be the case if somebody wants to speak only IPX, for
2476	 * example.)  Don't open IPCP in this case.
2477	 */
2478	if (hisaddr == 0L) {
2479		/* XXX this message should go away */
2480		if (debug)
2481			log(LOG_DEBUG, SPP_FMT "ipcp_open(): no IP interface\n",
2482			    SPP_ARGS(ifp));
2483		return;
2484	}
2485
2486	if (myaddr == 0L) {
2487		/*
2488		 * I don't have an assigned address, so i need to
2489		 * negotiate my address.
2490		 */
2491		sp->ipcp.flags |= IPCP_MYADDR_DYN;
2492		sp->ipcp.opts |= (1 << IPCP_OPT_ADDRESS);
2493	}
2494	sppp_open_event(&ipcp, sp);
2495}
2496
2497static void
2498sppp_ipcp_close(struct sppp *sp)
2499{
2500	sppp_close_event(&ipcp, sp);
2501	if (sp->ipcp.flags & IPCP_MYADDR_DYN)
2502		/*
2503		 * My address was dynamic, clear it again.
2504		 */
2505		sppp_set_ip_addr(sp, 0L);
2506}
2507
2508static void
2509sppp_ipcp_TO(void *cookie)
2510{
2511	sppp_to_event(&ipcp, (struct sppp *)cookie);
2512}
2513
2514/*
2515 * Analyze a configure request.  Return true if it was agreeable, and
2516 * caused action sca, false if it has been rejected or nak'ed, and
2517 * caused action scn.  (The return value is used to make the state
2518 * transition decision in the state automaton.)
2519 */
2520static int
2521sppp_ipcp_RCR(struct sppp *sp, struct lcp_header *h, int len)
2522{
2523	u_char *buf, *r, *p;
2524	struct ifnet *ifp = &sp->pp_if;
2525	int rlen, origlen, debug = ifp->if_flags & IFF_DEBUG;
2526	u_long hisaddr, desiredaddr;
2527
2528	len -= 4;
2529	origlen = len;
2530	/*
2531	 * Make sure to allocate a buf that can at least hold a
2532	 * conf-nak with an `address' option.  We might need it below.
2533	 */
2534	buf = r = malloc ((len < 6? 6: len), M_TEMP, M_NOWAIT);
2535	if (! buf)
2536		return (0);
2537
2538	/* pass 1: see if we can recognize them */
2539	if (debug)
2540		log(LOG_DEBUG, SPP_FMT "ipcp parse opts: ",
2541		    SPP_ARGS(ifp));
2542	p = (void*) (h+1);
2543	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2544		if (debug)
2545			addlog(" %s ", sppp_ipcp_opt_name(*p));
2546		switch (*p) {
2547#ifdef notyet
2548		case IPCP_OPT_COMPRESSION:
2549			if (len >= 6 && p[1] >= 6) {
2550				/* correctly formed compress option */
2551				continue;
2552			}
2553			if (debug)
2554				addlog("[invalid] ");
2555			break;
2556#endif
2557		case IPCP_OPT_ADDRESS:
2558			if (len >= 6 && p[1] == 6) {
2559				/* correctly formed address option */
2560				continue;
2561			}
2562			if (debug)
2563				addlog("[invalid] ");
2564			break;
2565		default:
2566			/* Others not supported. */
2567			if (debug)
2568				addlog("[rej] ");
2569			break;
2570		}
2571		/* Add the option to rejected list. */
2572		bcopy (p, r, p[1]);
2573		r += p[1];
2574		rlen += p[1];
2575	}
2576	if (rlen) {
2577		if (debug)
2578			addlog(" send conf-rej\n");
2579		sppp_cp_send (sp, PPP_IPCP, CONF_REJ, h->ident, rlen, buf);
2580		return 0;
2581	} else if (debug)
2582		addlog("\n");
2583
2584	/* pass 2: parse option values */
2585	sppp_get_ip_addrs(sp, 0, &hisaddr, 0);
2586	if (debug)
2587		log(LOG_DEBUG, SPP_FMT "ipcp parse opt values: ",
2588		       SPP_ARGS(ifp));
2589	p = (void*) (h+1);
2590	len = origlen;
2591	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2592		if (debug)
2593			addlog(" %s ", sppp_ipcp_opt_name(*p));
2594		switch (*p) {
2595#ifdef notyet
2596		case IPCP_OPT_COMPRESSION:
2597			continue;
2598#endif
2599		case IPCP_OPT_ADDRESS:
2600			desiredaddr = p[2] << 24 | p[3] << 16 |
2601				p[4] << 8 | p[5];
2602			if (desiredaddr == hisaddr ||
2603			    hisaddr == 1 && desiredaddr != 0) {
2604				/*
2605				 * Peer's address is same as our value,
2606				 * or we have set it to 0.0.0.1 to
2607				 * indicate that we do not really care,
2608				 * this is agreeable.  Gonna conf-ack
2609				 * it.
2610				 */
2611				if (debug)
2612					addlog("%s [ack] ",
2613					       sppp_dotted_quad(desiredaddr));
2614				/* record that we've seen it already */
2615				sp->ipcp.flags |= IPCP_HISADDR_SEEN;
2616				continue;
2617			}
2618			/*
2619			 * The address wasn't agreeable.  This is either
2620			 * he sent us 0.0.0.0, asking to assign him an
2621			 * address, or he send us another address not
2622			 * matching our value.  Either case, we gonna
2623			 * conf-nak it with our value.
2624			 */
2625			if (debug) {
2626				if (desiredaddr == 0)
2627					addlog("[addr requested] ");
2628				else
2629					addlog("%s [not agreed] ",
2630					       sppp_dotted_quad(desiredaddr));
2631
2632				p[2] = hisaddr >> 24;
2633				p[3] = hisaddr >> 16;
2634				p[4] = hisaddr >> 8;
2635				p[5] = hisaddr;
2636			}
2637			break;
2638		}
2639		/* Add the option to nak'ed list. */
2640		bcopy (p, r, p[1]);
2641		r += p[1];
2642		rlen += p[1];
2643	}
2644
2645	/*
2646	 * If we are about to conf-ack the request, but haven't seen
2647	 * his address so far, gonna conf-nak it instead, with the
2648	 * `address' option present and our idea of his address being
2649	 * filled in there, to request negotiation of both addresses.
2650	 *
2651	 * XXX This can result in an endless req - nak loop if peer
2652	 * doesn't want to send us his address.  Q: What should we do
2653	 * about it?  XXX  A: implement the max-failure counter.
2654	 */
2655	if (rlen == 0 && !(sp->ipcp.flags & IPCP_HISADDR_SEEN)) {
2656		buf[0] = IPCP_OPT_ADDRESS;
2657		buf[1] = 6;
2658		buf[2] = hisaddr >> 24;
2659		buf[3] = hisaddr >> 16;
2660		buf[4] = hisaddr >> 8;
2661		buf[5] = hisaddr;
2662		rlen = 6;
2663		if (debug)
2664			addlog("still need hisaddr ");
2665	}
2666
2667	if (rlen) {
2668		if (debug)
2669			addlog(" send conf-nak\n");
2670		sppp_cp_send (sp, PPP_IPCP, CONF_NAK, h->ident, rlen, buf);
2671	} else {
2672		if (debug)
2673			addlog(" send conf-ack\n");
2674		sppp_cp_send (sp, PPP_IPCP, CONF_ACK,
2675			      h->ident, origlen, h+1);
2676	}
2677
2678	free (buf, M_TEMP);
2679	return (rlen == 0);
2680}
2681
2682/*
2683 * Analyze the IPCP Configure-Reject option list, and adjust our
2684 * negotiation.
2685 */
2686static void
2687sppp_ipcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
2688{
2689	u_char *buf, *p;
2690	struct ifnet *ifp = &sp->pp_if;
2691	int debug = ifp->if_flags & IFF_DEBUG;
2692
2693	len -= 4;
2694	buf = malloc (len, M_TEMP, M_NOWAIT);
2695	if (!buf)
2696		return;
2697
2698	if (debug)
2699		log(LOG_DEBUG, SPP_FMT "ipcp rej opts: ",
2700		    SPP_ARGS(ifp));
2701
2702	p = (void*) (h+1);
2703	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2704		if (debug)
2705			addlog(" %s ", sppp_ipcp_opt_name(*p));
2706		switch (*p) {
2707		case IPCP_OPT_ADDRESS:
2708			/*
2709			 * Peer doesn't grok address option.  This is
2710			 * bad.  XXX  Should we better give up here?
2711			 */
2712			sp->ipcp.opts &= ~(1 << IPCP_OPT_ADDRESS);
2713			break;
2714#ifdef notyet
2715		case IPCP_OPT_COMPRESS:
2716			sp->ipcp.opts &= ~(1 << IPCP_OPT_COMPRESS);
2717			break;
2718#endif
2719		}
2720	}
2721	if (debug)
2722		addlog("\n");
2723	free (buf, M_TEMP);
2724	return;
2725}
2726
2727/*
2728 * Analyze the IPCP Configure-NAK option list, and adjust our
2729 * negotiation.
2730 */
2731static void
2732sppp_ipcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
2733{
2734	u_char *buf, *p;
2735	struct ifnet *ifp = &sp->pp_if;
2736	int debug = ifp->if_flags & IFF_DEBUG;
2737	u_long wantaddr;
2738
2739	len -= 4;
2740	buf = malloc (len, M_TEMP, M_NOWAIT);
2741	if (!buf)
2742		return;
2743
2744	if (debug)
2745		log(LOG_DEBUG, SPP_FMT "ipcp nak opts: ",
2746		    SPP_ARGS(ifp));
2747
2748	p = (void*) (h+1);
2749	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2750		if (debug)
2751			addlog(" %s ", sppp_ipcp_opt_name(*p));
2752		switch (*p) {
2753		case IPCP_OPT_ADDRESS:
2754			/*
2755			 * Peer doesn't like our local IP address.  See
2756			 * if we can do something for him.  We'll drop
2757			 * him our address then.
2758			 */
2759			if (len >= 6 && p[1] == 6) {
2760				wantaddr = p[2] << 24 | p[3] << 16 |
2761					p[4] << 8 | p[5];
2762				sp->ipcp.opts |= (1 << IPCP_OPT_ADDRESS);
2763				if (debug)
2764					addlog("[wantaddr %s] ",
2765					       sppp_dotted_quad(wantaddr));
2766				/*
2767				 * When doing dynamic address assignment,
2768				 * we accept his offer.  Otherwise, we
2769				 * ignore it and thus continue to negotiate
2770				 * our already existing value.
2771				 */
2772				if (sp->ipcp.flags & IPCP_MYADDR_DYN) {
2773					sppp_set_ip_addr(sp, wantaddr);
2774					if (debug)
2775						addlog("[agree] ");
2776				}
2777			}
2778			break;
2779#ifdef notyet
2780		case IPCP_OPT_COMPRESS:
2781			/*
2782			 * Peer wants different compression parameters.
2783			 */
2784			break;
2785#endif
2786		}
2787	}
2788	if (debug)
2789		addlog("\n");
2790	free (buf, M_TEMP);
2791	return;
2792}
2793
2794static void
2795sppp_ipcp_tlu(struct sppp *sp)
2796{
2797}
2798
2799static void
2800sppp_ipcp_tld(struct sppp *sp)
2801{
2802}
2803
2804static void
2805sppp_ipcp_tls(struct sppp *sp)
2806{
2807	/* indicate to LCP that it must stay alive */
2808	sp->lcp.protos |= (1 << IDX_IPCP);
2809}
2810
2811static void
2812sppp_ipcp_tlf(struct sppp *sp)
2813{
2814	/* we no longer need LCP */
2815	sp->lcp.protos &= ~(1 << IDX_IPCP);
2816	sppp_lcp_check_and_close(sp);
2817}
2818
2819static void
2820sppp_ipcp_scr(struct sppp *sp)
2821{
2822	char opt[6 /* compression */ + 6 /* address */];
2823	u_long ouraddr;
2824	int i = 0;
2825
2826#ifdef notyet
2827	if (sp->ipcp.opts & (1 << IPCP_OPT_COMPRESSION)) {
2828		opt[i++] = IPCP_OPT_COMPRESSION;
2829		opt[i++] = 6;
2830		opt[i++] = 0;	/* VJ header compression */
2831		opt[i++] = 0x2d; /* VJ header compression */
2832		opt[i++] = max_slot_id;
2833		opt[i++] = comp_slot_id;
2834	}
2835#endif
2836
2837	if (sp->ipcp.opts & (1 << IPCP_OPT_ADDRESS)) {
2838		sppp_get_ip_addrs(sp, &ouraddr, 0, 0);
2839		opt[i++] = IPCP_OPT_ADDRESS;
2840		opt[i++] = 6;
2841		opt[i++] = ouraddr >> 24;
2842		opt[i++] = ouraddr >> 16;
2843		opt[i++] = ouraddr >> 8;
2844		opt[i++] = ouraddr;
2845	}
2846
2847	sp->confid[IDX_IPCP] = ++sp->pp_seq;
2848	sppp_cp_send(sp, PPP_IPCP, CONF_REQ, sp->confid[IDX_IPCP], i, &opt);
2849}
2850
2851
2852/*
2853 *--------------------------------------------------------------------------*
2854 *                                                                          *
2855 *                        The CHAP implementation.                          *
2856 *                                                                          *
2857 *--------------------------------------------------------------------------*
2858 */
2859
2860/*
2861 * The authentication protocols don't employ a full-fledged state machine as
2862 * the control protocols do, since they do have Open and Close events, but
2863 * not Up and Down, nor are they explicitly terminated.  Also, use of the
2864 * authentication protocols may be different in both directions (this makes
2865 * sense, think of a machine that never accepts incoming calls but only
2866 * calls out, it doesn't require the called party to authenticate itself).
2867 *
2868 * Our state machine for the local authentication protocol (we are requesting
2869 * the peer to authenticate) looks like:
2870 *
2871 *						    RCA-
2872 *	      +--------------------------------------------+
2873 *	      V					    scn,tld|
2874 *	  +--------+			       Close   +---------+ RCA+
2875 *	  |	   |<----------------------------------|	 |------+
2876 *   +--->| Closed |				TO*    | Opened	 | sca	|
2877 *   |	  |	   |-----+		       +-------|	 |<-----+
2878 *   |	  +--------+ irc |		       |       +---------+
2879 *   |	    ^		 |		       |	   ^
2880 *   |	    |		 |		       |	   |
2881 *   |	    |		 |		       |	   |
2882 *   |	 TO-|		 |		       |	   |
2883 *   |	    |tld  TO+	 V		       |	   |
2884 *   |	    |	+------->+		       |	   |
2885 *   |	    |	|	 |		       |	   |
2886 *   |	  +--------+	 V		       |	   |
2887 *   |	  |	   |<----+<--------------------+	   |
2888 *   |	  | Req-   | scr				   |
2889 *   |	  | Sent   |					   |
2890 *   |	  |	   |					   |
2891 *   |	  +--------+					   |
2892 *   | RCA- |	| RCA+					   |
2893 *   +------+	+------------------------------------------+
2894 *   scn,tld	  sca,irc,ict,tlu
2895 *
2896 *
2897 *   with:
2898 *
2899 *	Open:	LCP reached authentication phase
2900 *	Close:	LCP reached terminate phase
2901 *
2902 *	RCA+:	received reply (pap-req, chap-response), acceptable
2903 *	RCN:	received reply (pap-req, chap-response), not acceptable
2904 *	TO+:	timeout with restart counter >= 0
2905 *	TO-:	timeout with restart counter < 0
2906 *	TO*:	reschedule timeout for CHAP
2907 *
2908 *	scr:	send request packet (none for PAP, chap-challenge)
2909 *	sca:	send ack packet (pap-ack, chap-success)
2910 *	scn:	send nak packet (pap-nak, chap-failure)
2911 *	ict:	initialize re-challenge timer (CHAP only)
2912 *
2913 *	tlu:	this-layer-up, LCP reaches network phase
2914 *	tld:	this-layer-down, LCP enters terminate phase
2915 *
2916 * Note that in CHAP mode, after sending a new challenge, while the state
2917 * automaton falls back into Req-Sent state, it doesn't signal a tld
2918 * event to LCP, so LCP remains in network phase.  Only after not getting
2919 * any response (or after getting an unacceptable response), CHAP closes,
2920 * causing LCP to enter terminate phase.
2921 *
2922 * With PAP, there is no initial request that can be sent.  The peer is
2923 * expected to send one based on the successful negotiation of PAP as
2924 * the authentication protocol during the LCP option negotiation.
2925 *
2926 * Incoming authentication protocol requests (remote requests
2927 * authentication, we are peer) don't employ a state machine at all,
2928 * they are simply answered.  Some peers [Ascend P50 firmware rev
2929 * 4.50] react allergically when sending IPCP requests while they are
2930 * still in authentication phase (thereby violating the standard that
2931 * demands that these NCP packets are to be discarded), so we keep
2932 * track of the peer demanding us to authenticate, and only proceed to
2933 * phase network once we've seen a positive acknowledge for the
2934 * authentication.
2935 */
2936
2937/*
2938 * Handle incoming CHAP packets.
2939 */
2940void
2941sppp_chap_input(struct sppp *sp, struct mbuf *m)
2942{
2943	STDDCL;
2944	struct lcp_header *h;
2945	int len, x;
2946	u_char *value, *name, digest[AUTHKEYLEN], dsize;
2947	int value_len, name_len;
2948	MD5_CTX ctx;
2949
2950	len = m->m_pkthdr.len;
2951	if (len < 4) {
2952		if (debug)
2953			log(LOG_DEBUG,
2954			    SPP_FMT "chap invalid packet length: %d bytes\n",
2955			    SPP_ARGS(ifp), len);
2956		return;
2957	}
2958	h = mtod (m, struct lcp_header*);
2959	if (len > ntohs (h->len))
2960		len = ntohs (h->len);
2961
2962	switch (h->type) {
2963	/* challenge, failure and success are his authproto */
2964	case CHAP_CHALLENGE:
2965		value = 1 + (u_char*)(h+1);
2966		value_len = value[-1];
2967		name = value + value_len;
2968		name_len = len - value_len - 5;
2969		if (name_len < 0) {
2970			if (debug) {
2971				log(LOG_DEBUG,
2972				    SPP_FMT "chap corrupted challenge "
2973				    "<%s id=0x%x len=%d",
2974				    SPP_ARGS(ifp),
2975				    sppp_auth_type_name(PPP_CHAP, h->type),
2976				    h->ident, ntohs(h->len));
2977				if (len > 4)
2978					sppp_print_bytes((u_char*) (h+1), len-4);
2979				addlog(">\n");
2980			}
2981			break;
2982		}
2983
2984		if (debug) {
2985			log(LOG_DEBUG,
2986			    SPP_FMT "chap input <%s id=0x%x len=%d name=",
2987			    SPP_ARGS(ifp),
2988			    sppp_auth_type_name(PPP_CHAP, h->type), h->ident,
2989			    ntohs(h->len));
2990			sppp_print_string((char*) name, name_len);
2991			addlog(" value-size=%d value=", value_len);
2992			sppp_print_bytes(value, value_len);
2993			addlog(">\n");
2994		}
2995
2996		/* Compute reply value. */
2997		MD5Init(&ctx);
2998		MD5Update(&ctx, &h->ident, 1);
2999		MD5Update(&ctx, sp->myauth.secret,
3000			  sppp_strnlen(sp->myauth.secret, AUTHKEYLEN));
3001		MD5Update(&ctx, value, value_len);
3002		MD5Final(digest, &ctx);
3003		dsize = sizeof digest;
3004
3005		sppp_auth_send(&chap, sp, CHAP_RESPONSE, h->ident,
3006			       sizeof dsize, (const char *)&dsize,
3007			       sizeof digest, digest,
3008			       (size_t)sppp_strnlen(sp->myauth.name, AUTHNAMELEN),
3009			       sp->myauth.name,
3010			       0);
3011		break;
3012
3013	case CHAP_SUCCESS:
3014		if (debug) {
3015			log(LOG_DEBUG, SPP_FMT "chap success",
3016			    SPP_ARGS(ifp));
3017			if (len > 4) {
3018				addlog(": ");
3019				sppp_print_string((char*)(h + 1), len - 4);
3020			}
3021			addlog("\n");
3022		}
3023		x = splimp();
3024		sp->pp_flags &= ~PP_NEEDAUTH;
3025		if (sp->myauth.proto == PPP_CHAP &&
3026		    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) &&
3027		    (sp->lcp.protos & (1 << IDX_CHAP)) == 0) {
3028			/*
3029			 * We are authenticator for CHAP but didn't
3030			 * complete yet.  Leave it to tlu to proceed
3031			 * to network phase.
3032			 */
3033			splx(x);
3034			break;
3035		}
3036		splx(x);
3037		sppp_phase_network(sp);
3038		break;
3039
3040	case CHAP_FAILURE:
3041		if (debug) {
3042			log(LOG_INFO, SPP_FMT "chap failure",
3043			    SPP_ARGS(ifp));
3044			if (len > 4) {
3045				addlog(": ");
3046				sppp_print_string((char*)(h + 1), len - 4);
3047			}
3048			addlog("\n");
3049		} else
3050			log(LOG_INFO, SPP_FMT "chap failure\n",
3051			    SPP_ARGS(ifp));
3052		/* await LCP shutdown by authenticator */
3053		break;
3054
3055	/* response is my authproto */
3056	case CHAP_RESPONSE:
3057		value = 1 + (u_char*)(h+1);
3058		value_len = value[-1];
3059		name = value + value_len;
3060		name_len = len - value_len - 5;
3061		if (name_len < 0) {
3062			if (debug) {
3063				log(LOG_DEBUG,
3064				    SPP_FMT "chap corrupted response "
3065				    "<%s id=0x%x len=%d",
3066				    SPP_ARGS(ifp),
3067				    sppp_auth_type_name(PPP_CHAP, h->type),
3068				    h->ident, ntohs(h->len));
3069				if (len > 4)
3070					sppp_print_bytes((u_char*)(h+1), len-4);
3071				addlog(">\n");
3072			}
3073			break;
3074		}
3075		if (h->ident != sp->confid[IDX_CHAP]) {
3076			if (debug)
3077				log(LOG_DEBUG,
3078				    SPP_FMT "chap dropping response for old ID "
3079				    "(got %d, expected %d)\n",
3080				    SPP_ARGS(ifp),
3081				    h->ident, sp->confid[IDX_CHAP]);
3082			break;
3083		}
3084		if (name_len != sppp_strnlen(sp->hisauth.name, AUTHNAMELEN)
3085		    || bcmp(name, sp->hisauth.name, name_len) != 0) {
3086			log(LOG_INFO, SPP_FMT "chap response, his name ",
3087			    SPP_ARGS(ifp));
3088			sppp_print_string(name, name_len);
3089			addlog(" != expected ");
3090			sppp_print_string(sp->hisauth.name,
3091					  sppp_strnlen(sp->hisauth.name, AUTHNAMELEN));
3092			addlog("\n");
3093		}
3094		if (debug) {
3095			log(LOG_DEBUG, SPP_FMT "chap input(%s) "
3096			    "<%s id=0x%x len=%d name=",
3097			    SPP_ARGS(ifp),
3098			    sppp_state_name(sp->state[IDX_CHAP]),
3099			    sppp_auth_type_name(PPP_CHAP, h->type),
3100			    h->ident, ntohs (h->len));
3101			sppp_print_string((char*)name, name_len);
3102			addlog(" value-size=%d value=", value_len);
3103			sppp_print_bytes(value, value_len);
3104			addlog(">\n");
3105		}
3106		if (value_len != AUTHKEYLEN) {
3107			if (debug)
3108				log(LOG_DEBUG,
3109				    SPP_FMT "chap bad hash value length: "
3110				    "%d bytes, should be %d\n",
3111				    SPP_ARGS(ifp), value_len,
3112				    AUTHKEYLEN);
3113			break;
3114		}
3115
3116		MD5Init(&ctx);
3117		MD5Update(&ctx, &h->ident, 1);
3118		MD5Update(&ctx, sp->hisauth.secret,
3119			  sppp_strnlen(sp->hisauth.secret, AUTHKEYLEN));
3120		MD5Update(&ctx, sp->myauth.challenge, AUTHKEYLEN);
3121		MD5Final(digest, &ctx);
3122
3123#define FAILMSG "Failed..."
3124#define SUCCMSG "Welcome!"
3125
3126		if (value_len != sizeof digest ||
3127		    bcmp(digest, value, value_len) != 0) {
3128			/* action scn, tld */
3129			sppp_auth_send(&chap, sp, CHAP_FAILURE, h->ident,
3130				       sizeof(FAILMSG) - 1, (u_char *)FAILMSG,
3131				       0);
3132			chap.tld(sp);
3133			break;
3134		}
3135		/* action sca, perhaps tlu */
3136		if (sp->state[IDX_CHAP] == STATE_REQ_SENT ||
3137		    sp->state[IDX_CHAP] == STATE_OPENED)
3138			sppp_auth_send(&chap, sp, CHAP_SUCCESS, h->ident,
3139				       sizeof(SUCCMSG) - 1, (u_char *)SUCCMSG,
3140				       0);
3141		if (sp->state[IDX_CHAP] == STATE_REQ_SENT) {
3142			sppp_cp_change_state(&chap, sp, STATE_OPENED);
3143			chap.tlu(sp);
3144		}
3145		break;
3146
3147	default:
3148		/* Unknown CHAP packet type -- ignore. */
3149		if (debug) {
3150			log(LOG_DEBUG, SPP_FMT "chap unknown input(%s) "
3151			    "<0x%x id=0x%xh len=%d",
3152			    SPP_ARGS(ifp),
3153			    sppp_state_name(sp->state[IDX_CHAP]),
3154			    h->type, h->ident, ntohs(h->len));
3155			if (len > 4)
3156				sppp_print_bytes((u_char*)(h+1), len-4);
3157			addlog(">\n");
3158		}
3159		break;
3160
3161	}
3162}
3163
3164static void
3165sppp_chap_init(struct sppp *sp)
3166{
3167	/* Chap doesn't have STATE_INITIAL at all. */
3168	sp->state[IDX_CHAP] = STATE_CLOSED;
3169	sp->fail_counter[IDX_CHAP] = 0;
3170#if defined(__FreeBSD__) && __FreeBSD__ >= 3
3171	callout_handle_init(&sp->ch[IDX_CHAP]);
3172#endif
3173}
3174
3175static void
3176sppp_chap_open(struct sppp *sp)
3177{
3178	if (sp->myauth.proto == PPP_CHAP &&
3179	    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0) {
3180		/* we are authenticator for CHAP, start it */
3181		chap.scr(sp);
3182		sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3183		sppp_cp_change_state(&chap, sp, STATE_REQ_SENT);
3184	}
3185	/* nothing to be done if we are peer, await a challenge */
3186}
3187
3188static void
3189sppp_chap_close(struct sppp *sp)
3190{
3191	if (sp->state[IDX_CHAP] != STATE_CLOSED)
3192		sppp_cp_change_state(&chap, sp, STATE_CLOSED);
3193}
3194
3195static void
3196sppp_chap_TO(void *cookie)
3197{
3198	struct sppp *sp = (struct sppp *)cookie;
3199	STDDCL;
3200	int s;
3201
3202	s = splimp();
3203	if (debug)
3204		log(LOG_DEBUG, SPP_FMT "chap TO(%s) rst_counter = %d\n",
3205		    SPP_ARGS(ifp),
3206		    sppp_state_name(sp->state[IDX_CHAP]),
3207		    sp->rst_counter[IDX_CHAP]);
3208
3209	if (--sp->rst_counter[IDX_CHAP] < 0)
3210		/* TO- event */
3211		switch (sp->state[IDX_CHAP]) {
3212		case STATE_REQ_SENT:
3213			chap.tld(sp);
3214			sppp_cp_change_state(&chap, sp, STATE_CLOSED);
3215			break;
3216		}
3217	else
3218		/* TO+ (or TO*) event */
3219		switch (sp->state[IDX_CHAP]) {
3220		case STATE_OPENED:
3221			/* TO* event */
3222			sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3223			/* fall through */
3224		case STATE_REQ_SENT:
3225			chap.scr(sp);
3226			/* sppp_cp_change_state() will restart the timer */
3227			sppp_cp_change_state(&chap, sp, STATE_REQ_SENT);
3228			break;
3229		}
3230
3231	splx(s);
3232}
3233
3234static void
3235sppp_chap_tlu(struct sppp *sp)
3236{
3237	STDDCL;
3238	int i, x;
3239
3240	i = 0;
3241	sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3242
3243	/*
3244	 * Some broken CHAP implementations (Conware CoNet, firmware
3245	 * 4.0.?) don't want to re-authenticate their CHAP once the
3246	 * initial challenge-response exchange has taken place.
3247	 * Provide for an option to avoid rechallenges.
3248	 */
3249	if ((sp->hisauth.flags & AUTHFLAG_NORECHALLENGE) == 0) {
3250		/*
3251		 * Compute the re-challenge timeout.  This will yield
3252		 * a number between 300 and 810 seconds.
3253		 */
3254		i = 300 + ((unsigned)(random() & 0xff00) >> 7);
3255		TIMEOUT(chap.TO, (void *)sp, i * hz, sp->ch[IDX_CHAP]);
3256	}
3257
3258	if (debug) {
3259		log(LOG_DEBUG,
3260		    SPP_FMT "chap %s, ",
3261		    SPP_ARGS(ifp),
3262		    sp->pp_phase == PHASE_NETWORK? "reconfirmed": "tlu");
3263		if ((sp->hisauth.flags & AUTHFLAG_NORECHALLENGE) == 0)
3264			addlog("next re-challenge in %d seconds\n", i);
3265		else
3266			addlog("re-challenging supressed\n");
3267	}
3268
3269	x = splimp();
3270	/* indicate to LCP that we need to be closed down */
3271	sp->lcp.protos |= (1 << IDX_CHAP);
3272
3273	if (sp->pp_flags & PP_NEEDAUTH) {
3274		/*
3275		 * Remote is authenticator, but his auth proto didn't
3276		 * complete yet.  Defer the transition to network
3277		 * phase.
3278		 */
3279		splx(x);
3280		return;
3281	}
3282	splx(x);
3283
3284	/*
3285	 * If we are already in phase network, we are done here.  This
3286	 * is the case if this is a dummy tlu event after a re-challenge.
3287	 */
3288	if (sp->pp_phase != PHASE_NETWORK)
3289		sppp_phase_network(sp);
3290}
3291
3292static void
3293sppp_chap_tld(struct sppp *sp)
3294{
3295	STDDCL;
3296
3297	if (debug)
3298		log(LOG_DEBUG, SPP_FMT "chap tld\n", SPP_ARGS(ifp));
3299	UNTIMEOUT(chap.TO, (void *)sp, sp->ch[IDX_CHAP]);
3300	sp->lcp.protos &= ~(1 << IDX_CHAP);
3301
3302	lcp.Close(sp);
3303}
3304
3305static void
3306sppp_chap_scr(struct sppp *sp)
3307{
3308	u_long *ch, seed;
3309	u_char clen;
3310#if defined (__NetBSD__) || defined (__OpenBSD__)
3311	struct timeval tv;
3312#endif
3313
3314	/* Compute random challenge. */
3315	ch = (u_long *)sp->myauth.challenge;
3316#if defined(__FreeBSD__) && __FreeBSD__ >= 3
3317	read_random(&seed, sizeof seed);
3318#else
3319	microtime(&tv);
3320	seed = tv.tv_sec ^ tv.tv_usec;
3321#endif
3322	ch[0] = seed ^ random();
3323	ch[1] = seed ^ random();
3324	ch[2] = seed ^ random();
3325	ch[3] = seed ^ random();
3326	clen = AUTHKEYLEN;
3327
3328	sp->confid[IDX_CHAP] = ++sp->pp_seq;
3329
3330	sppp_auth_send(&chap, sp, CHAP_CHALLENGE, sp->confid[IDX_CHAP],
3331		       sizeof clen, (const char *)&clen,
3332		       (size_t)AUTHKEYLEN, sp->myauth.challenge,
3333		       (size_t)sppp_strnlen(sp->myauth.name, AUTHNAMELEN),
3334		       sp->myauth.name,
3335		       0);
3336}
3337/*
3338 *--------------------------------------------------------------------------*
3339 *                                                                          *
3340 *                        The PAP implementation.                           *
3341 *                                                                          *
3342 *--------------------------------------------------------------------------*
3343 */
3344/*
3345 * For PAP, we need to keep a little state also if we are the peer, not the
3346 * authenticator.  This is since we don't get a request to authenticate, but
3347 * have to repeatedly authenticate ourself until we got a response (or the
3348 * retry counter is expired).
3349 */
3350
3351/*
3352 * Handle incoming PAP packets.  */
3353static void
3354sppp_pap_input(struct sppp *sp, struct mbuf *m)
3355{
3356	STDDCL;
3357	struct lcp_header *h;
3358	int len, x;
3359	u_char *name, *passwd, mlen;
3360	int name_len, passwd_len;
3361
3362	len = m->m_pkthdr.len;
3363	if (len < 5) {
3364		if (debug)
3365			log(LOG_DEBUG,
3366			    SPP_FMT "pap invalid packet length: %d bytes\n",
3367			    SPP_ARGS(ifp), len);
3368		return;
3369	}
3370	h = mtod (m, struct lcp_header*);
3371	if (len > ntohs (h->len))
3372		len = ntohs (h->len);
3373	switch (h->type) {
3374	/* PAP request is my authproto */
3375	case PAP_REQ:
3376		name = 1 + (u_char*)(h+1);
3377		name_len = name[-1];
3378		passwd = name + name_len + 1;
3379		if (name_len > len - 6 ||
3380		    (passwd_len = passwd[-1]) > len - 6 - name_len) {
3381			if (debug) {
3382				log(LOG_DEBUG, SPP_FMT "pap corrupted input "
3383				    "<%s id=0x%x len=%d",
3384				    SPP_ARGS(ifp),
3385				    sppp_auth_type_name(PPP_PAP, h->type),
3386				    h->ident, ntohs(h->len));
3387				if (len > 4)
3388					sppp_print_bytes((u_char*)(h+1), len-4);
3389				addlog(">\n");
3390			}
3391			break;
3392		}
3393		if (debug) {
3394			log(LOG_DEBUG, SPP_FMT "pap input(%s) "
3395			    "<%s id=0x%x len=%d name=",
3396			    SPP_ARGS(ifp),
3397			    sppp_state_name(sp->state[IDX_PAP]),
3398			    sppp_auth_type_name(PPP_PAP, h->type),
3399			    h->ident, ntohs(h->len));
3400			sppp_print_string((char*)name, name_len);
3401			addlog(" passwd=");
3402			sppp_print_string((char*)passwd, passwd_len);
3403			addlog(">\n");
3404		}
3405		if (name_len > AUTHNAMELEN ||
3406		    passwd_len > AUTHKEYLEN ||
3407		    bcmp(name, sp->hisauth.name, name_len) != 0 ||
3408		    bcmp(passwd, sp->hisauth.secret, passwd_len) != 0) {
3409			/* action scn, tld */
3410			mlen = sizeof(FAILMSG) - 1;
3411			sppp_auth_send(&pap, sp, PAP_NAK, h->ident,
3412				       sizeof mlen, (const char *)&mlen,
3413				       sizeof(FAILMSG) - 1, (u_char *)FAILMSG,
3414				       0);
3415			pap.tld(sp);
3416			break;
3417		}
3418		/* action sca, perhaps tlu */
3419		if (sp->state[IDX_PAP] == STATE_REQ_SENT ||
3420		    sp->state[IDX_PAP] == STATE_OPENED) {
3421			mlen = sizeof(SUCCMSG) - 1;
3422			sppp_auth_send(&pap, sp, PAP_ACK, h->ident,
3423				       sizeof mlen, (const char *)&mlen,
3424				       sizeof(SUCCMSG) - 1, (u_char *)SUCCMSG,
3425				       0);
3426		}
3427		if (sp->state[IDX_PAP] == STATE_REQ_SENT) {
3428			sppp_cp_change_state(&pap, sp, STATE_OPENED);
3429			pap.tlu(sp);
3430		}
3431		break;
3432
3433	/* ack and nak are his authproto */
3434	case PAP_ACK:
3435		UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
3436		if (debug) {
3437			log(LOG_DEBUG, SPP_FMT "pap success",
3438			    SPP_ARGS(ifp));
3439			name_len = *((char *)h);
3440			if (len > 5 && name_len) {
3441				addlog(": ");
3442				sppp_print_string((char*)(h+1), name_len);
3443			}
3444			addlog("\n");
3445		}
3446		x = splimp();
3447		sp->pp_flags &= ~PP_NEEDAUTH;
3448		if (sp->myauth.proto == PPP_PAP &&
3449		    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) &&
3450		    (sp->lcp.protos & (1 << IDX_PAP)) == 0) {
3451			/*
3452			 * We are authenticator for PAP but didn't
3453			 * complete yet.  Leave it to tlu to proceed
3454			 * to network phase.
3455			 */
3456			splx(x);
3457			break;
3458		}
3459		splx(x);
3460		sppp_phase_network(sp);
3461		break;
3462
3463	case PAP_NAK:
3464		UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
3465		if (debug) {
3466			log(LOG_INFO, SPP_FMT "pap failure",
3467			    SPP_ARGS(ifp));
3468			name_len = *((char *)h);
3469			if (len > 5 && name_len) {
3470				addlog(": ");
3471				sppp_print_string((char*)(h+1), name_len);
3472			}
3473			addlog("\n");
3474		} else
3475			log(LOG_INFO, SPP_FMT "pap failure\n",
3476			    SPP_ARGS(ifp));
3477		/* await LCP shutdown by authenticator */
3478		break;
3479
3480	default:
3481		/* Unknown PAP packet type -- ignore. */
3482		if (debug) {
3483			log(LOG_DEBUG, SPP_FMT "pap corrupted input "
3484			    "<0x%x id=0x%x len=%d",
3485			    SPP_ARGS(ifp),
3486			    h->type, h->ident, ntohs(h->len));
3487			if (len > 4)
3488				sppp_print_bytes((u_char*)(h+1), len-4);
3489			addlog(">\n");
3490		}
3491		break;
3492
3493	}
3494}
3495
3496static void
3497sppp_pap_init(struct sppp *sp)
3498{
3499	/* PAP doesn't have STATE_INITIAL at all. */
3500	sp->state[IDX_PAP] = STATE_CLOSED;
3501	sp->fail_counter[IDX_PAP] = 0;
3502#if defined(__FreeBSD__) && __FreeBSD__ >= 3
3503	callout_handle_init(&sp->ch[IDX_PAP]);
3504	callout_handle_init(&sp->pap_my_to_ch);
3505#endif
3506}
3507
3508static void
3509sppp_pap_open(struct sppp *sp)
3510{
3511	if (sp->hisauth.proto == PPP_PAP &&
3512	    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0) {
3513		/* we are authenticator for PAP, start our timer */
3514		sp->rst_counter[IDX_PAP] = sp->lcp.max_configure;
3515		sppp_cp_change_state(&pap, sp, STATE_REQ_SENT);
3516	}
3517	if (sp->myauth.proto == PPP_PAP) {
3518		/* we are peer, send a request, and start a timer */
3519		pap.scr(sp);
3520		TIMEOUT(sppp_pap_my_TO, (void *)sp, sp->lcp.timeout,
3521		    sp->pap_my_to_ch);
3522	}
3523}
3524
3525static void
3526sppp_pap_close(struct sppp *sp)
3527{
3528	if (sp->state[IDX_PAP] != STATE_CLOSED)
3529		sppp_cp_change_state(&pap, sp, STATE_CLOSED);
3530}
3531
3532/*
3533 * That's the timeout routine if we are authenticator.  Since the
3534 * authenticator is basically passive in PAP, we can't do much here.
3535 */
3536static void
3537sppp_pap_TO(void *cookie)
3538{
3539	struct sppp *sp = (struct sppp *)cookie;
3540	STDDCL;
3541	int s;
3542
3543	s = splimp();
3544	if (debug)
3545		log(LOG_DEBUG, SPP_FMT "pap TO(%s) rst_counter = %d\n",
3546		    SPP_ARGS(ifp),
3547		    sppp_state_name(sp->state[IDX_PAP]),
3548		    sp->rst_counter[IDX_PAP]);
3549
3550	if (--sp->rst_counter[IDX_PAP] < 0)
3551		/* TO- event */
3552		switch (sp->state[IDX_PAP]) {
3553		case STATE_REQ_SENT:
3554			pap.tld(sp);
3555			sppp_cp_change_state(&pap, sp, STATE_CLOSED);
3556			break;
3557		}
3558	else
3559		/* TO+ event, not very much we could do */
3560		switch (sp->state[IDX_PAP]) {
3561		case STATE_REQ_SENT:
3562			/* sppp_cp_change_state() will restart the timer */
3563			sppp_cp_change_state(&pap, sp, STATE_REQ_SENT);
3564			break;
3565		}
3566
3567	splx(s);
3568}
3569
3570/*
3571 * That's the timeout handler if we are peer.  Since the peer is active,
3572 * we need to retransmit our PAP request since it is apparently lost.
3573 * XXX We should impose a max counter.
3574 */
3575static void
3576sppp_pap_my_TO(void *cookie)
3577{
3578	struct sppp *sp = (struct sppp *)cookie;
3579	STDDCL;
3580
3581	if (debug)
3582		log(LOG_DEBUG, SPP_FMT "pap peer TO\n",
3583		    SPP_ARGS(ifp));
3584
3585	pap.scr(sp);
3586}
3587
3588static void
3589sppp_pap_tlu(struct sppp *sp)
3590{
3591	STDDCL;
3592	int x;
3593
3594	sp->rst_counter[IDX_PAP] = sp->lcp.max_configure;
3595
3596	if (debug)
3597		log(LOG_DEBUG, SPP_FMT "%s tlu\n",
3598		    SPP_ARGS(ifp), pap.name);
3599
3600	x = splimp();
3601	/* indicate to LCP that we need to be closed down */
3602	sp->lcp.protos |= (1 << IDX_PAP);
3603
3604	if (sp->pp_flags & PP_NEEDAUTH) {
3605		/*
3606		 * Remote is authenticator, but his auth proto didn't
3607		 * complete yet.  Defer the transition to network
3608		 * phase.
3609		 */
3610		splx(x);
3611		return;
3612	}
3613	splx(x);
3614	sppp_phase_network(sp);
3615}
3616
3617static void
3618sppp_pap_tld(struct sppp *sp)
3619{
3620	STDDCL;
3621
3622	if (debug)
3623		log(LOG_DEBUG, SPP_FMT "pap tld\n", SPP_ARGS(ifp));
3624	UNTIMEOUT(pap.TO, (void *)sp, sp->ch[IDX_PAP]);
3625	UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
3626	sp->lcp.protos &= ~(1 << IDX_PAP);
3627
3628	lcp.Close(sp);
3629}
3630
3631static void
3632sppp_pap_scr(struct sppp *sp)
3633{
3634	u_char idlen, pwdlen;
3635
3636	sp->confid[IDX_PAP] = ++sp->pp_seq;
3637	pwdlen = sppp_strnlen(sp->myauth.secret, AUTHKEYLEN);
3638	idlen = sppp_strnlen(sp->myauth.name, AUTHNAMELEN);
3639
3640	sppp_auth_send(&pap, sp, PAP_REQ, sp->confid[IDX_PAP],
3641		       sizeof idlen, (const char *)&idlen,
3642		       (size_t)idlen, sp->myauth.name,
3643		       sizeof pwdlen, (const char *)&pwdlen,
3644		       (size_t)pwdlen, sp->myauth.secret,
3645		       0);
3646}
3647/*
3648 * Random miscellaneous functions.
3649 */
3650
3651/*
3652 * Send a PAP or CHAP proto packet.
3653 *
3654 * Varadic function, each of the elements for the ellipsis is of type
3655 * ``size_t mlen, const u_char *msg''.  Processing will stop iff
3656 * mlen == 0.
3657 */
3658
3659static void
3660sppp_auth_send(const struct cp *cp, struct sppp *sp, u_char type, u_char id,
3661	       ...)
3662{
3663	STDDCL;
3664	struct ppp_header *h;
3665	struct lcp_header *lh;
3666	struct mbuf *m;
3667	u_char *p;
3668	int len;
3669	size_t mlen;
3670	const char *msg;
3671	va_list ap;
3672
3673	MGETHDR (m, M_DONTWAIT, MT_DATA);
3674	if (! m)
3675		return;
3676	m->m_pkthdr.rcvif = 0;
3677
3678	h = mtod (m, struct ppp_header*);
3679	h->address = PPP_ALLSTATIONS;		/* broadcast address */
3680	h->control = PPP_UI;			/* Unnumbered Info */
3681	h->protocol = htons(cp->proto);
3682
3683	lh = (struct lcp_header*)(h + 1);
3684	lh->type = type;
3685	lh->ident = id;
3686	p = (u_char*) (lh+1);
3687
3688	va_start(ap, id);
3689	len = 0;
3690
3691	while ((mlen = va_arg(ap, size_t)) != 0) {
3692		msg = va_arg(ap, const char *);
3693		len += mlen;
3694		if (len > MHLEN - PPP_HEADER_LEN - LCP_HEADER_LEN) {
3695			va_end(ap);
3696			m_freem(m);
3697			return;
3698		}
3699
3700		bcopy(msg, p, mlen);
3701		p += mlen;
3702	}
3703	va_end(ap);
3704
3705	m->m_pkthdr.len = m->m_len = PPP_HEADER_LEN + LCP_HEADER_LEN + len;
3706	lh->len = htons (LCP_HEADER_LEN + len);
3707
3708	if (debug) {
3709		log(LOG_DEBUG, SPP_FMT "%s output <%s id=0x%x len=%d",
3710		    SPP_ARGS(ifp), cp->name,
3711		    sppp_auth_type_name(cp->proto, lh->type),
3712		    lh->ident, ntohs(lh->len));
3713		if (len)
3714			sppp_print_bytes((u_char*) (lh+1), len);
3715		addlog(">\n");
3716	}
3717	if (IF_QFULL (&sp->pp_cpq)) {
3718		IF_DROP (&sp->pp_fastq);
3719		IF_DROP (&ifp->if_snd);
3720		m_freem (m);
3721		++ifp->if_oerrors;
3722	} else
3723		IF_ENQUEUE (&sp->pp_cpq, m);
3724	if (! (ifp->if_flags & IFF_OACTIVE))
3725		(*ifp->if_start) (ifp);
3726	ifp->if_obytes += m->m_pkthdr.len + 3;
3727}
3728
3729/*
3730 * Flush interface queue.
3731 */
3732static void
3733sppp_qflush(struct ifqueue *ifq)
3734{
3735	struct mbuf *m, *n;
3736
3737	n = ifq->ifq_head;
3738	while ((m = n)) {
3739		n = m->m_act;
3740		m_freem (m);
3741	}
3742	ifq->ifq_head = 0;
3743	ifq->ifq_tail = 0;
3744	ifq->ifq_len = 0;
3745}
3746
3747/*
3748 * Send keepalive packets, every 10 seconds.
3749 */
3750static void
3751sppp_keepalive(void *dummy)
3752{
3753	struct sppp *sp;
3754	int s;
3755
3756	s = splimp();
3757	for (sp=spppq; sp; sp=sp->pp_next) {
3758		struct ifnet *ifp = &sp->pp_if;
3759
3760		/* Keepalive mode disabled or channel down? */
3761		if (! (sp->pp_flags & PP_KEEPALIVE) ||
3762		    ! (ifp->if_flags & IFF_RUNNING))
3763			continue;
3764
3765		/* No keepalive in PPP mode if LCP not opened yet. */
3766		if (! (sp->pp_flags & PP_CISCO) &&
3767		    sp->pp_phase < PHASE_AUTHENTICATE)
3768			continue;
3769
3770		if (sp->pp_alivecnt == MAXALIVECNT) {
3771			/* No keepalive packets got.  Stop the interface. */
3772			printf (SPP_FMT "down\n", SPP_ARGS(ifp));
3773			if_down (ifp);
3774			sppp_qflush (&sp->pp_cpq);
3775			if (! (sp->pp_flags & PP_CISCO)) {
3776				/* XXX */
3777				/* Shut down the PPP link. */
3778				lcp.Down(sp);
3779				/* Initiate negotiation. XXX */
3780				lcp.Up(sp);
3781			}
3782		}
3783		if (sp->pp_alivecnt <= MAXALIVECNT)
3784			++sp->pp_alivecnt;
3785		if (sp->pp_flags & PP_CISCO)
3786			sppp_cisco_send (sp, CISCO_KEEPALIVE_REQ, ++sp->pp_seq,
3787				sp->pp_rseq);
3788		else if (sp->pp_phase >= PHASE_AUTHENTICATE) {
3789			long nmagic = htonl (sp->lcp.magic);
3790			sp->lcp.echoid = ++sp->pp_seq;
3791			sppp_cp_send (sp, PPP_LCP, ECHO_REQ,
3792				sp->lcp.echoid, 4, &nmagic);
3793		}
3794	}
3795	splx(s);
3796	TIMEOUT(sppp_keepalive, 0, hz * 10, keepalive_ch);
3797}
3798
3799/*
3800 * Get both IP addresses.
3801 */
3802static void
3803sppp_get_ip_addrs(struct sppp *sp, u_long *src, u_long *dst, u_long *srcmask)
3804{
3805	struct ifnet *ifp = &sp->pp_if;
3806	struct ifaddr *ifa;
3807	struct sockaddr_in *si, *sm;
3808	u_long ssrc, ddst;
3809
3810	sm = NULL;
3811	ssrc = ddst = 0L;
3812	/*
3813	 * Pick the first AF_INET address from the list,
3814	 * aliases don't make any sense on a p2p link anyway.
3815	 */
3816	si = 0;
3817#if defined(__FreeBSD__) && __FreeBSD__ >= 3
3818	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
3819#else
3820	for (ifa = ifp->if_addrlist.tqh_first;
3821	     ifa;
3822	     ifa = ifa->ifa_list.tqe_next)
3823#endif
3824		if (ifa->ifa_addr->sa_family == AF_INET) {
3825			si = (struct sockaddr_in *)ifa->ifa_addr;
3826			sm = (struct sockaddr_in *)ifa->ifa_netmask;
3827			if (si)
3828				break;
3829		}
3830	if (ifa) {
3831		if (si && si->sin_addr.s_addr) {
3832			ssrc = si->sin_addr.s_addr;
3833			if (srcmask)
3834				*srcmask = ntohl(sm->sin_addr.s_addr);
3835		}
3836
3837		si = (struct sockaddr_in *)ifa->ifa_dstaddr;
3838		if (si && si->sin_addr.s_addr)
3839			ddst = si->sin_addr.s_addr;
3840	}
3841
3842	if (dst) *dst = ntohl(ddst);
3843	if (src) *src = ntohl(ssrc);
3844}
3845
3846/*
3847 * Set my IP address.  Must be called at splimp.
3848 */
3849static void
3850sppp_set_ip_addr(struct sppp *sp, u_long src)
3851{
3852	struct ifnet *ifp = &sp->pp_if;
3853	struct ifaddr *ifa;
3854	struct sockaddr_in *si;
3855
3856	/*
3857	 * Pick the first AF_INET address from the list,
3858	 * aliases don't make any sense on a p2p link anyway.
3859	 */
3860
3861	si = 0;
3862#if defined(__FreeBSD__) && __FreeBSD__ >= 3
3863	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
3864#else
3865	for (ifa = ifp->if_addrlist.tqh_first;
3866	     ifa;
3867	     ifa = ifa->ifa_list.tqe_next)
3868#endif
3869	{
3870		if (ifa->ifa_addr->sa_family == AF_INET)
3871		{
3872			si = (struct sockaddr_in *)ifa->ifa_addr;
3873			if (si)
3874				break;
3875		}
3876	}
3877
3878	if (ifa && si)
3879		si->sin_addr.s_addr = htonl(src);
3880}
3881
3882static int
3883sppp_params(struct sppp *sp, u_long cmd, void *data)
3884{
3885	u_long subcmd;
3886	struct ifreq *ifr = (struct ifreq *)data;
3887	struct spppreq spr;
3888
3889	/*
3890	 * ifr->ifr_data is supposed to point to a struct spppreq.
3891	 * Check the cmd word first before attempting to fetch all the
3892	 * data.
3893	 */
3894	if ((subcmd = fuword(ifr->ifr_data)) == -1)
3895		return EFAULT;
3896
3897	if (copyin((caddr_t)ifr->ifr_data, &spr, sizeof spr) != 0)
3898		return EFAULT;
3899
3900	switch (subcmd) {
3901	case SPPPIOGDEFS:
3902		if (cmd != SIOCGIFGENERIC)
3903			return EINVAL;
3904		/*
3905		 * We copy over the entire current state, but clean
3906		 * out some of the stuff we don't wanna pass up.
3907		 * Remember, SIOCGIFGENERIC is unprotected, and can be
3908		 * called by any user.  No need to ever get PAP or
3909		 * CHAP secrets back to userland anyway.
3910		 */
3911		bcopy(sp, &spr.defs, sizeof(struct sppp));
3912		bzero(spr.defs.myauth.secret, AUTHKEYLEN);
3913		bzero(spr.defs.myauth.challenge, AUTHKEYLEN);
3914		bzero(spr.defs.hisauth.secret, AUTHKEYLEN);
3915		bzero(spr.defs.hisauth.challenge, AUTHKEYLEN);
3916		return copyout(&spr, (caddr_t)ifr->ifr_data, sizeof spr);
3917
3918	case SPPPIOSDEFS:
3919		if (cmd != SIOCSIFGENERIC)
3920			return EINVAL;
3921		/*
3922		 * We have a very specific idea of which fields we allow
3923		 * being passed back from userland, so to not clobber our
3924		 * current state.  For one, we only allow setting
3925		 * anything if LCP is in dead phase.  Once the LCP
3926		 * negotiations started, the authentication settings must
3927		 * not be changed again.  (The administrator can force an
3928		 * ifconfig down in order to get LCP back into dead
3929		 * phase.)
3930		 *
3931		 * Also, we only allow for authentication parameters to be
3932		 * specified.
3933		 *
3934		 * XXX Should allow to set or clear pp_flags.
3935		 *
3936		 * Finally, if the respective authentication protocol to
3937		 * be used is set differently than 0, but the secret is
3938		 * passed as all zeros, we don't trash the existing secret.
3939		 * This allows an administrator to change the system name
3940		 * only without clobbering the secret (which he didn't get
3941		 * back in a previous SPPPIOGDEFS call).  However, the
3942		 * secrets are cleared if the authentication protocol is
3943		 * reset to 0.
3944		 */
3945		if (sp->pp_phase != PHASE_DEAD)
3946			return EBUSY;
3947
3948		if ((spr.defs.myauth.proto != 0 && spr.defs.myauth.proto != PPP_PAP &&
3949		     spr.defs.myauth.proto != PPP_CHAP) ||
3950		    (spr.defs.hisauth.proto != 0 && spr.defs.hisauth.proto != PPP_PAP &&
3951		     spr.defs.hisauth.proto != PPP_CHAP))
3952			return EINVAL;
3953
3954		if (spr.defs.myauth.proto == 0)
3955			/* resetting myauth */
3956			bzero(&sp->myauth, sizeof sp->myauth);
3957		else {
3958			/* setting/changing myauth */
3959			sp->myauth.proto = spr.defs.myauth.proto;
3960			bcopy(spr.defs.myauth.name, sp->myauth.name, AUTHNAMELEN);
3961			if (spr.defs.myauth.secret[0] != '\0')
3962				bcopy(spr.defs.myauth.secret, sp->myauth.secret,
3963				      AUTHKEYLEN);
3964		}
3965		if (spr.defs.hisauth.proto == 0)
3966			/* resetting hisauth */
3967			bzero(&sp->hisauth, sizeof sp->hisauth);
3968		else {
3969			/* setting/changing hisauth */
3970			sp->hisauth.proto = spr.defs.hisauth.proto;
3971			sp->hisauth.flags = spr.defs.hisauth.flags;
3972			bcopy(spr.defs.hisauth.name, sp->hisauth.name, AUTHNAMELEN);
3973			if (spr.defs.hisauth.secret[0] != '\0')
3974				bcopy(spr.defs.hisauth.secret, sp->hisauth.secret,
3975				      AUTHKEYLEN);
3976		}
3977		break;
3978
3979	default:
3980		return EINVAL;
3981	}
3982
3983	return 0;
3984}
3985
3986static void
3987sppp_phase_network(struct sppp *sp)
3988{
3989	STDDCL;
3990	int i;
3991	u_long mask;
3992
3993	sp->pp_phase = PHASE_NETWORK;
3994
3995	if (debug)
3996		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
3997		    sppp_phase_name(sp->pp_phase));
3998
3999	/* Notify NCPs now. */
4000	for (i = 0; i < IDX_COUNT; i++)
4001		if ((cps[i])->flags & CP_NCP)
4002			(cps[i])->Open(sp);
4003
4004	/* Send Up events to all NCPs. */
4005	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
4006		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_NCP))
4007			(cps[i])->Up(sp);
4008
4009	/* if no NCP is starting, all this was in vain, close down */
4010	sppp_lcp_check_and_close(sp);
4011}
4012
4013
4014static const char *
4015sppp_cp_type_name(u_char type)
4016{
4017	static char buf[12];
4018	switch (type) {
4019	case CONF_REQ:   return "conf-req";
4020	case CONF_ACK:   return "conf-ack";
4021	case CONF_NAK:   return "conf-nak";
4022	case CONF_REJ:   return "conf-rej";
4023	case TERM_REQ:   return "term-req";
4024	case TERM_ACK:   return "term-ack";
4025	case CODE_REJ:   return "code-rej";
4026	case PROTO_REJ:  return "proto-rej";
4027	case ECHO_REQ:   return "echo-req";
4028	case ECHO_REPLY: return "echo-reply";
4029	case DISC_REQ:   return "discard-req";
4030	}
4031	snprintf (buf, sizeof(buf), "0x%x", type);
4032	return buf;
4033}
4034
4035static const char *
4036sppp_auth_type_name(u_short proto, u_char type)
4037{
4038	static char buf[12];
4039	switch (proto) {
4040	case PPP_CHAP:
4041		switch (type) {
4042		case CHAP_CHALLENGE:	return "challenge";
4043		case CHAP_RESPONSE:	return "response";
4044		case CHAP_SUCCESS:	return "success";
4045		case CHAP_FAILURE:	return "failure";
4046		}
4047	case PPP_PAP:
4048		switch (type) {
4049		case PAP_REQ:		return "req";
4050		case PAP_ACK:		return "ack";
4051		case PAP_NAK:		return "nak";
4052		}
4053	}
4054	snprintf (buf, sizeof(buf), "0x%x", type);
4055	return buf;
4056}
4057
4058static const char *
4059sppp_lcp_opt_name(u_char opt)
4060{
4061	static char buf[12];
4062	switch (opt) {
4063	case LCP_OPT_MRU:		return "mru";
4064	case LCP_OPT_ASYNC_MAP:		return "async-map";
4065	case LCP_OPT_AUTH_PROTO:	return "auth-proto";
4066	case LCP_OPT_QUAL_PROTO:	return "qual-proto";
4067	case LCP_OPT_MAGIC:		return "magic";
4068	case LCP_OPT_PROTO_COMP:	return "proto-comp";
4069	case LCP_OPT_ADDR_COMP:		return "addr-comp";
4070	}
4071	snprintf (buf, sizeof(buf), "0x%x", opt);
4072	return buf;
4073}
4074
4075static const char *
4076sppp_ipcp_opt_name(u_char opt)
4077{
4078	static char buf[12];
4079	switch (opt) {
4080	case IPCP_OPT_ADDRESSES:	return "addresses";
4081	case IPCP_OPT_COMPRESSION:	return "compression";
4082	case IPCP_OPT_ADDRESS:		return "address";
4083	}
4084	snprintf (buf, sizeof(buf), "0x%x", opt);
4085	return buf;
4086}
4087
4088static const char *
4089sppp_state_name(int state)
4090{
4091	switch (state) {
4092	case STATE_INITIAL:	return "initial";
4093	case STATE_STARTING:	return "starting";
4094	case STATE_CLOSED:	return "closed";
4095	case STATE_STOPPED:	return "stopped";
4096	case STATE_CLOSING:	return "closing";
4097	case STATE_STOPPING:	return "stopping";
4098	case STATE_REQ_SENT:	return "req-sent";
4099	case STATE_ACK_RCVD:	return "ack-rcvd";
4100	case STATE_ACK_SENT:	return "ack-sent";
4101	case STATE_OPENED:	return "opened";
4102	}
4103	return "illegal";
4104}
4105
4106static const char *
4107sppp_phase_name(enum ppp_phase phase)
4108{
4109	switch (phase) {
4110	case PHASE_DEAD:	return "dead";
4111	case PHASE_ESTABLISH:	return "establish";
4112	case PHASE_TERMINATE:	return "terminate";
4113	case PHASE_AUTHENTICATE: return "authenticate";
4114	case PHASE_NETWORK:	return "network";
4115	}
4116	return "illegal";
4117}
4118
4119static const char *
4120sppp_proto_name(u_short proto)
4121{
4122	static char buf[12];
4123	switch (proto) {
4124	case PPP_LCP:	return "lcp";
4125	case PPP_IPCP:	return "ipcp";
4126	case PPP_PAP:	return "pap";
4127	case PPP_CHAP:	return "chap";
4128	}
4129	snprintf(buf, sizeof(buf), "0x%x", (unsigned)proto);
4130	return buf;
4131}
4132
4133static void
4134sppp_print_bytes(const u_char *p, u_short len)
4135{
4136	addlog(" %02x", *p++);
4137	while (--len > 0)
4138		addlog("-%02x", *p++);
4139}
4140
4141static void
4142sppp_print_string(const char *p, u_short len)
4143{
4144	u_char c;
4145
4146	while (len-- > 0) {
4147		c = *p++;
4148		/*
4149		 * Print only ASCII chars directly.  RFC 1994 recommends
4150		 * using only them, but we don't rely on it.  */
4151		if (c < ' ' || c > '~')
4152			addlog("\\x%x", c);
4153		else
4154			addlog("%c", c);
4155	}
4156}
4157
4158static const char *
4159sppp_dotted_quad(u_long addr)
4160{
4161	static char s[16];
4162	sprintf(s, "%d.%d.%d.%d",
4163		(int)((addr >> 24) & 0xff),
4164		(int)((addr >> 16) & 0xff),
4165		(int)((addr >> 8) & 0xff),
4166		(int)(addr & 0xff));
4167	return s;
4168}
4169
4170static int
4171sppp_strnlen(u_char *p, int max)
4172{
4173	int len;
4174
4175	for (len = 0; len < max && *p; ++p)
4176		++len;
4177	return len;
4178}
4179
4180/* a dummy, used to drop uninteresting events */
4181static void
4182sppp_null(struct sppp *unused)
4183{
4184	/* do just nothing */
4185}
4186/*
4187 * This file is large.  Tell emacs to highlight it nevertheless.
4188 *
4189 * Local Variables:
4190 * hilit-auto-highlight-maxout: 120000
4191 * End:
4192 */
4193