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