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