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