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