if_spppsubr.c revision 41881
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.47 1998/12/11 21:40:13 phk 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			sppp_cp_change_state(cp, sp, STATE_CLOSED);
1409			(cp->tlf)(sp);
1410			break;
1411		case STATE_STOPPING:
1412			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1413			(cp->tlf)(sp);
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		sppp_cp_change_state(cp, sp, STATE_STARTING);
1579		(cp->tls)(sp);
1580		break;
1581	case STATE_STOPPING:
1582	case STATE_REQ_SENT:
1583	case STATE_ACK_RCVD:
1584	case STATE_ACK_SENT:
1585		sppp_cp_change_state(cp, sp, STATE_STARTING);
1586		break;
1587	case STATE_OPENED:
1588		(cp->tld)(sp);
1589		sppp_cp_change_state(cp, sp, STATE_STARTING);
1590		break;
1591	default:
1592		printf(SPP_FMT "%s illegal down in state %s\n",
1593		       SPP_ARGS(ifp), cp->name,
1594		       sppp_state_name(sp->state[cp->protoidx]));
1595	}
1596}
1597
1598
1599static void
1600sppp_open_event(const struct cp *cp, struct sppp *sp)
1601{
1602	STDDCL;
1603
1604	if (debug)
1605		log(LOG_DEBUG, SPP_FMT "%s open(%s)\n",
1606		    SPP_ARGS(ifp), cp->name,
1607		    sppp_state_name(sp->state[cp->protoidx]));
1608
1609	switch (sp->state[cp->protoidx]) {
1610	case STATE_INITIAL:
1611		sppp_cp_change_state(cp, sp, STATE_STARTING);
1612		(cp->tls)(sp);
1613		break;
1614	case STATE_STARTING:
1615		break;
1616	case STATE_CLOSED:
1617		sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1618		(cp->scr)(sp);
1619		sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1620		break;
1621	case STATE_STOPPED:
1622	case STATE_STOPPING:
1623	case STATE_REQ_SENT:
1624	case STATE_ACK_RCVD:
1625	case STATE_ACK_SENT:
1626	case STATE_OPENED:
1627		break;
1628	case STATE_CLOSING:
1629		sppp_cp_change_state(cp, sp, STATE_STOPPING);
1630		break;
1631	}
1632}
1633
1634
1635static void
1636sppp_close_event(const struct cp *cp, struct sppp *sp)
1637{
1638	STDDCL;
1639
1640	if (debug)
1641		log(LOG_DEBUG, SPP_FMT "%s close(%s)\n",
1642		    SPP_ARGS(ifp), cp->name,
1643		    sppp_state_name(sp->state[cp->protoidx]));
1644
1645	switch (sp->state[cp->protoidx]) {
1646	case STATE_INITIAL:
1647	case STATE_CLOSED:
1648	case STATE_CLOSING:
1649		break;
1650	case STATE_STARTING:
1651		sppp_cp_change_state(cp, sp, STATE_INITIAL);
1652		(cp->tlf)(sp);
1653		break;
1654	case STATE_STOPPED:
1655		sppp_cp_change_state(cp, sp, STATE_CLOSED);
1656		break;
1657	case STATE_STOPPING:
1658		sppp_cp_change_state(cp, sp, STATE_CLOSING);
1659		break;
1660	case STATE_OPENED:
1661		(cp->tld)(sp);
1662		/* fall through */
1663	case STATE_REQ_SENT:
1664	case STATE_ACK_RCVD:
1665	case STATE_ACK_SENT:
1666		sp->rst_counter[cp->protoidx] = sp->lcp.max_terminate;
1667		sppp_cp_send(sp, cp->proto, TERM_REQ, ++sp->pp_seq, 0, 0);
1668		sppp_cp_change_state(cp, sp, STATE_CLOSING);
1669		break;
1670	}
1671}
1672
1673static void
1674sppp_to_event(const struct cp *cp, struct sppp *sp)
1675{
1676	STDDCL;
1677	int s;
1678
1679	s = splimp();
1680	if (debug)
1681		log(LOG_DEBUG, SPP_FMT "%s TO(%s) rst_counter = %d\n",
1682		    SPP_ARGS(ifp), cp->name,
1683		    sppp_state_name(sp->state[cp->protoidx]),
1684		    sp->rst_counter[cp->protoidx]);
1685
1686	if (--sp->rst_counter[cp->protoidx] < 0)
1687		/* TO- event */
1688		switch (sp->state[cp->protoidx]) {
1689		case STATE_CLOSING:
1690			sppp_cp_change_state(cp, sp, STATE_CLOSED);
1691			(cp->tlf)(sp);
1692			break;
1693		case STATE_STOPPING:
1694			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1695			(cp->tlf)(sp);
1696			break;
1697		case STATE_REQ_SENT:
1698		case STATE_ACK_RCVD:
1699		case STATE_ACK_SENT:
1700			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1701			(cp->tlf)(sp);
1702			break;
1703		}
1704	else
1705		/* TO+ event */
1706		switch (sp->state[cp->protoidx]) {
1707		case STATE_CLOSING:
1708		case STATE_STOPPING:
1709			sppp_cp_send(sp, cp->proto, TERM_REQ, ++sp->pp_seq,
1710				     0, 0);
1711#if defined (__FreeBSD__)
1712			sp->ch[cp->protoidx] =
1713#endif
1714			timeout(cp->TO, (void *)sp, sp->lcp.timeout);
1715			break;
1716		case STATE_REQ_SENT:
1717		case STATE_ACK_RCVD:
1718			(cp->scr)(sp);
1719			/* sppp_cp_change_state() will restart the timer */
1720			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1721			break;
1722		case STATE_ACK_SENT:
1723			(cp->scr)(sp);
1724#if defined (__FreeBSD__)
1725			sp->ch[cp->protoidx] =
1726#endif
1727			timeout(cp->TO, (void *)sp, sp->lcp.timeout);
1728			break;
1729		}
1730
1731	splx(s);
1732}
1733
1734/*
1735 * Change the state of a control protocol in the state automaton.
1736 * Takes care of starting/stopping the restart timer.
1737 */
1738void
1739sppp_cp_change_state(const struct cp *cp, struct sppp *sp, int newstate)
1740{
1741	sp->state[cp->protoidx] = newstate;
1742
1743	UNTIMEOUT(cp->TO, (void *)sp, sp->ch[cp->protoidx]);
1744	switch (newstate) {
1745	case STATE_INITIAL:
1746	case STATE_STARTING:
1747	case STATE_CLOSED:
1748	case STATE_STOPPED:
1749	case STATE_OPENED:
1750		break;
1751	case STATE_CLOSING:
1752	case STATE_STOPPING:
1753	case STATE_REQ_SENT:
1754	case STATE_ACK_RCVD:
1755	case STATE_ACK_SENT:
1756#if defined (__FreeBSD__)
1757		sp->ch[cp->protoidx]  =
1758#endif
1759		timeout(cp->TO, (void *)sp, sp->lcp.timeout);
1760		break;
1761	}
1762}
1763/*
1764 *--------------------------------------------------------------------------*
1765 *                                                                          *
1766 *                         The LCP implementation.                          *
1767 *                                                                          *
1768 *--------------------------------------------------------------------------*
1769 */
1770static void
1771sppp_lcp_init(struct sppp *sp)
1772{
1773	sp->lcp.opts = (1 << LCP_OPT_MAGIC);
1774	sp->lcp.magic = 0;
1775	sp->state[IDX_LCP] = STATE_INITIAL;
1776	sp->fail_counter[IDX_LCP] = 0;
1777	sp->lcp.protos = 0;
1778	sp->lcp.mru = sp->lcp.their_mru = PP_MTU;
1779
1780	/*
1781	 * Initialize counters and timeout values.  Note that we don't
1782	 * use the 3 seconds suggested in RFC 1661 since we are likely
1783	 * running on a fast link.  XXX We should probably implement
1784	 * the exponential backoff option.  Note that these values are
1785	 * relevant for all control protocols, not just LCP only.
1786	 */
1787	sp->lcp.timeout = 1 * hz;
1788	sp->lcp.max_terminate = 2;
1789	sp->lcp.max_configure = 10;
1790	sp->lcp.max_failure = 10;
1791#if defined (__FreeBSD__)
1792	callout_handle_init(&sp->ch[IDX_LCP]);
1793#endif
1794}
1795
1796static void
1797sppp_lcp_up(struct sppp *sp)
1798{
1799	STDDCL;
1800
1801	/*
1802	 * If this interface is passive or dial-on-demand, and we are
1803	 * still in Initial state, it means we've got an incoming
1804	 * call.  Activate the interface.
1805	 */
1806	if ((ifp->if_flags & (IFF_AUTO | IFF_PASSIVE)) != 0) {
1807		if (debug)
1808			log(LOG_DEBUG,
1809			    SPP_FMT "Up event", SPP_ARGS(ifp));
1810		ifp->if_flags |= IFF_RUNNING;
1811		if (sp->state[IDX_LCP] == STATE_INITIAL) {
1812			if (debug)
1813				addlog("(incoming call)\n");
1814			sp->pp_flags |= PP_CALLIN;
1815			lcp.Open(sp);
1816		} else if (debug)
1817			addlog("\n");
1818	}
1819
1820	sppp_up_event(&lcp, sp);
1821}
1822
1823static void
1824sppp_lcp_down(struct sppp *sp)
1825{
1826	STDDCL;
1827
1828	sppp_down_event(&lcp, sp);
1829
1830	/*
1831	 * If this is neither a dial-on-demand nor a passive
1832	 * interface, simulate an ``ifconfig down'' action, so the
1833	 * administrator can force a redial by another ``ifconfig
1834	 * up''.  XXX For leased line operation, should we immediately
1835	 * try to reopen the connection here?
1836	 */
1837	if ((ifp->if_flags & (IFF_AUTO | IFF_PASSIVE)) == 0) {
1838		log(LOG_INFO,
1839		    SPP_FMT "Down event (carrier loss), taking interface down.\n",
1840		    SPP_ARGS(ifp));
1841		if_down(ifp);
1842	} else {
1843		if (debug)
1844			log(LOG_DEBUG,
1845			    SPP_FMT "Down event (carrier loss)\n",
1846			    SPP_ARGS(ifp));
1847	}
1848	sp->pp_flags &= ~PP_CALLIN;
1849	if (sp->state[IDX_LCP] != STATE_INITIAL)
1850		lcp.Close(sp);
1851	ifp->if_flags &= ~IFF_RUNNING;
1852}
1853
1854static void
1855sppp_lcp_open(struct sppp *sp)
1856{
1857	/*
1858	 * If we are authenticator, negotiate LCP_AUTH
1859	 */
1860	if (sp->hisauth.proto != 0)
1861		sp->lcp.opts |= (1 << LCP_OPT_AUTH_PROTO);
1862	else
1863		sp->lcp.opts &= ~(1 << LCP_OPT_AUTH_PROTO);
1864	sp->pp_flags &= ~PP_NEEDAUTH;
1865	sppp_open_event(&lcp, sp);
1866}
1867
1868static void
1869sppp_lcp_close(struct sppp *sp)
1870{
1871	sppp_close_event(&lcp, sp);
1872}
1873
1874static void
1875sppp_lcp_TO(void *cookie)
1876{
1877	sppp_to_event(&lcp, (struct sppp *)cookie);
1878}
1879
1880/*
1881 * Analyze a configure request.  Return true if it was agreeable, and
1882 * caused action sca, false if it has been rejected or nak'ed, and
1883 * caused action scn.  (The return value is used to make the state
1884 * transition decision in the state automaton.)
1885 */
1886static int
1887sppp_lcp_RCR(struct sppp *sp, struct lcp_header *h, int len)
1888{
1889	STDDCL;
1890	u_char *buf, *r, *p;
1891	int origlen, rlen;
1892	u_long nmagic;
1893	u_short authproto;
1894
1895	len -= 4;
1896	origlen = len;
1897	buf = r = malloc (len, M_TEMP, M_NOWAIT);
1898	if (! buf)
1899		return (0);
1900
1901	if (debug)
1902		log(LOG_DEBUG, SPP_FMT "lcp parse opts: ",
1903		    SPP_ARGS(ifp));
1904
1905	/* pass 1: check for things that need to be rejected */
1906	p = (void*) (h+1);
1907	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
1908		if (debug)
1909			addlog(" %s ", sppp_lcp_opt_name(*p));
1910		switch (*p) {
1911		case LCP_OPT_MAGIC:
1912			/* Magic number. */
1913			/* fall through, both are same length */
1914		case LCP_OPT_ASYNC_MAP:
1915			/* Async control character map. */
1916			if (len >= 6 || p[1] == 6)
1917				continue;
1918			if (debug)
1919				addlog("[invalid] ");
1920			break;
1921		case LCP_OPT_MRU:
1922			/* Maximum receive unit. */
1923			if (len >= 4 && p[1] == 4)
1924				continue;
1925			if (debug)
1926				addlog("[invalid] ");
1927			break;
1928		case LCP_OPT_AUTH_PROTO:
1929			if (len < 4) {
1930				if (debug)
1931					addlog("[invalid] ");
1932				break;
1933			}
1934			authproto = (p[2] << 8) + p[3];
1935			if (authproto == PPP_CHAP && p[1] != 5) {
1936				if (debug)
1937					addlog("[invalid chap len] ");
1938				break;
1939			}
1940			if (sp->myauth.proto == 0) {
1941				/* we are not configured to do auth */
1942				if (debug)
1943					addlog("[not configured] ");
1944				break;
1945			}
1946			/*
1947			 * Remote want us to authenticate, remember this,
1948			 * so we stay in PHASE_AUTHENTICATE after LCP got
1949			 * up.
1950			 */
1951			sp->pp_flags |= PP_NEEDAUTH;
1952			continue;
1953		default:
1954			/* Others not supported. */
1955			if (debug)
1956				addlog("[rej] ");
1957			break;
1958		}
1959		/* Add the option to rejected list. */
1960		bcopy (p, r, p[1]);
1961		r += p[1];
1962		rlen += p[1];
1963	}
1964	if (rlen) {
1965		if (debug)
1966			addlog(" send conf-rej\n");
1967		sppp_cp_send (sp, PPP_LCP, CONF_REJ, h->ident, rlen, buf);
1968		return 0;
1969	} else if (debug)
1970		addlog("\n");
1971
1972	/*
1973	 * pass 2: check for option values that are unacceptable and
1974	 * thus require to be nak'ed.
1975	 */
1976	if (debug)
1977		log(LOG_DEBUG, SPP_FMT "lcp parse opt values: ",
1978		    SPP_ARGS(ifp));
1979
1980	p = (void*) (h+1);
1981	len = origlen;
1982	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
1983		if (debug)
1984			addlog(" %s ", sppp_lcp_opt_name(*p));
1985		switch (*p) {
1986		case LCP_OPT_MAGIC:
1987			/* Magic number -- extract. */
1988			nmagic = (u_long)p[2] << 24 |
1989				(u_long)p[3] << 16 | p[4] << 8 | p[5];
1990			if (nmagic != sp->lcp.magic) {
1991				if (debug)
1992					addlog("0x%lx ", nmagic);
1993				continue;
1994			}
1995			/*
1996			 * Local and remote magics equal -- loopback?
1997			 */
1998			if (sp->pp_loopcnt >= MAXALIVECNT*5) {
1999				printf (SPP_FMT "loopback\n",
2000					SPP_ARGS(ifp));
2001				sp->pp_loopcnt = 0;
2002				if (ifp->if_flags & IFF_UP) {
2003					if_down(ifp);
2004					sppp_qflush(&sp->pp_cpq);
2005					/* XXX ? */
2006					lcp.Down(sp);
2007					lcp.Up(sp);
2008				}
2009			} else if (debug)
2010				addlog("[glitch] ");
2011			++sp->pp_loopcnt;
2012			/*
2013			 * We negate our magic here, and NAK it.  If
2014			 * we see it later in an NAK packet, we
2015			 * suggest a new one.
2016			 */
2017			nmagic = ~sp->lcp.magic;
2018			/* Gonna NAK it. */
2019			p[2] = nmagic >> 24;
2020			p[3] = nmagic >> 16;
2021			p[4] = nmagic >> 8;
2022			p[5] = nmagic;
2023			break;
2024
2025		case LCP_OPT_ASYNC_MAP:
2026			/* Async control character map -- check to be zero. */
2027			if (! p[2] && ! p[3] && ! p[4] && ! p[5]) {
2028				if (debug)
2029					addlog("[empty] ");
2030				continue;
2031			}
2032			if (debug)
2033				addlog("[non-empty] ");
2034			/* suggest a zero one */
2035			p[2] = p[3] = p[4] = p[5] = 0;
2036			break;
2037
2038		case LCP_OPT_MRU:
2039			/*
2040			 * Maximum receive unit.  Always agreeable,
2041			 * but ignored by now.
2042			 */
2043			sp->lcp.their_mru = p[2] * 256 + p[3];
2044			if (debug)
2045				addlog("%lu ", sp->lcp.their_mru);
2046			continue;
2047
2048		case LCP_OPT_AUTH_PROTO:
2049			authproto = (p[2] << 8) + p[3];
2050			if (sp->myauth.proto != authproto) {
2051				/* not agreed, nak */
2052				if (debug)
2053					addlog("[mine %s != his %s] ",
2054					       sppp_proto_name(sp->hisauth.proto),
2055					       sppp_proto_name(authproto));
2056				p[2] = sp->myauth.proto >> 8;
2057				p[3] = sp->myauth.proto;
2058				break;
2059			}
2060			if (authproto == PPP_CHAP && p[4] != CHAP_MD5) {
2061				if (debug)
2062					addlog("[chap not MD5] ");
2063				p[4] = CHAP_MD5;
2064				break;
2065			}
2066			continue;
2067		}
2068		/* Add the option to nak'ed list. */
2069		bcopy (p, r, p[1]);
2070		r += p[1];
2071		rlen += p[1];
2072	}
2073	if (rlen) {
2074		if (++sp->fail_counter[IDX_LCP] >= sp->lcp.max_failure) {
2075			if (debug)
2076				addlog(" max_failure (%d) exceeded, "
2077				       "send conf-rej\n",
2078				       sp->lcp.max_failure);
2079			sppp_cp_send(sp, PPP_LCP, CONF_REJ, h->ident, rlen, buf);
2080		} else {
2081			if (debug)
2082				addlog(" send conf-nak\n");
2083			sppp_cp_send (sp, PPP_LCP, CONF_NAK, h->ident, rlen, buf);
2084		}
2085		return 0;
2086	} else {
2087		if (debug)
2088			addlog(" send conf-ack\n");
2089		sp->fail_counter[IDX_LCP] = 0;
2090		sp->pp_loopcnt = 0;
2091		sppp_cp_send (sp, PPP_LCP, CONF_ACK,
2092			      h->ident, origlen, h+1);
2093	}
2094
2095	free (buf, M_TEMP);
2096	return (rlen == 0);
2097}
2098
2099/*
2100 * Analyze the LCP Configure-Reject option list, and adjust our
2101 * negotiation.
2102 */
2103static void
2104sppp_lcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
2105{
2106	STDDCL;
2107	u_char *buf, *p;
2108
2109	len -= 4;
2110	buf = malloc (len, M_TEMP, M_NOWAIT);
2111	if (!buf)
2112		return;
2113
2114	if (debug)
2115		log(LOG_DEBUG, SPP_FMT "lcp rej opts: ",
2116		    SPP_ARGS(ifp));
2117
2118	p = (void*) (h+1);
2119	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2120		if (debug)
2121			addlog(" %s ", sppp_lcp_opt_name(*p));
2122		switch (*p) {
2123		case LCP_OPT_MAGIC:
2124			/* Magic number -- can't use it, use 0 */
2125			sp->lcp.opts &= ~(1 << LCP_OPT_MAGIC);
2126			sp->lcp.magic = 0;
2127			break;
2128		case LCP_OPT_MRU:
2129			/*
2130			 * Should not be rejected anyway, since we only
2131			 * negotiate a MRU if explicitly requested by
2132			 * peer.
2133			 */
2134			sp->lcp.opts &= ~(1 << LCP_OPT_MRU);
2135			break;
2136		case LCP_OPT_AUTH_PROTO:
2137			/*
2138			 * Peer doesn't want to authenticate himself,
2139			 * deny unless this is a dialout call, and
2140			 * AUTHFLAG_NOCALLOUT is set.
2141			 */
2142			if ((sp->pp_flags & PP_CALLIN) == 0 &&
2143			    (sp->hisauth.flags & AUTHFLAG_NOCALLOUT) != 0) {
2144				if (debug)
2145					addlog("[don't insist on auth "
2146					       "for callout]");
2147				sp->lcp.opts &= ~(1 << LCP_OPT_AUTH_PROTO);
2148				break;
2149			}
2150			if (debug)
2151				addlog("[access denied]\n");
2152			lcp.Close(sp);
2153			break;
2154		}
2155	}
2156	if (debug)
2157		addlog("\n");
2158	free (buf, M_TEMP);
2159	return;
2160}
2161
2162/*
2163 * Analyze the LCP Configure-NAK option list, and adjust our
2164 * negotiation.
2165 */
2166static void
2167sppp_lcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
2168{
2169	STDDCL;
2170	u_char *buf, *p;
2171	u_long magic;
2172
2173	len -= 4;
2174	buf = malloc (len, M_TEMP, M_NOWAIT);
2175	if (!buf)
2176		return;
2177
2178	if (debug)
2179		log(LOG_DEBUG, SPP_FMT "lcp nak opts: ",
2180		    SPP_ARGS(ifp));
2181
2182	p = (void*) (h+1);
2183	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2184		if (debug)
2185			addlog(" %s ", sppp_lcp_opt_name(*p));
2186		switch (*p) {
2187		case LCP_OPT_MAGIC:
2188			/* Magic number -- renegotiate */
2189			if ((sp->lcp.opts & (1 << LCP_OPT_MAGIC)) &&
2190			    len >= 6 && p[1] == 6) {
2191				magic = (u_long)p[2] << 24 |
2192					(u_long)p[3] << 16 | p[4] << 8 | p[5];
2193				/*
2194				 * If the remote magic is our negated one,
2195				 * this looks like a loopback problem.
2196				 * Suggest a new magic to make sure.
2197				 */
2198				if (magic == ~sp->lcp.magic) {
2199					if (debug)
2200						addlog("magic glitch ");
2201#if defined (__FreeBSD__)
2202					sp->lcp.magic = random();
2203#else
2204					sp->lcp.magic = time.tv_sec + time.tv_usec;
2205#endif
2206				} else {
2207					sp->lcp.magic = magic;
2208					if (debug)
2209						addlog("%lu ", magic);
2210				}
2211			}
2212			break;
2213		case LCP_OPT_MRU:
2214			/*
2215			 * Peer wants to advise us to negotiate an MRU.
2216			 * Agree on it if it's reasonable, or use
2217			 * default otherwise.
2218			 */
2219			if (len >= 4 && p[1] == 4) {
2220				u_int mru = p[2] * 256 + p[3];
2221				if (debug)
2222					addlog("%d ", mru);
2223				if (mru < PP_MTU || mru > PP_MAX_MRU)
2224					mru = PP_MTU;
2225				sp->lcp.mru = mru;
2226				sp->lcp.opts |= (1 << LCP_OPT_MRU);
2227			}
2228			break;
2229		case LCP_OPT_AUTH_PROTO:
2230			/*
2231			 * Peer doesn't like our authentication method,
2232			 * deny.
2233			 */
2234			if (debug)
2235				addlog("[access denied]\n");
2236			lcp.Close(sp);
2237			break;
2238		}
2239	}
2240	if (debug)
2241		addlog("\n");
2242	free (buf, M_TEMP);
2243	return;
2244}
2245
2246static void
2247sppp_lcp_tlu(struct sppp *sp)
2248{
2249	struct ifnet *ifp = &sp->pp_if;
2250	int i;
2251	u_long mask;
2252
2253	/* XXX ? */
2254	if (! (ifp->if_flags & IFF_UP) &&
2255	    (ifp->if_flags & IFF_RUNNING)) {
2256		/* Coming out of loopback mode. */
2257		if_up(ifp);
2258		printf (SPP_FMT "up\n", SPP_ARGS(ifp));
2259	}
2260
2261	for (i = 0; i < IDX_COUNT; i++)
2262		if ((cps[i])->flags & CP_QUAL)
2263			(cps[i])->Open(sp);
2264
2265	if ((sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0 ||
2266	    (sp->pp_flags & PP_NEEDAUTH) != 0)
2267		sp->pp_phase = PHASE_AUTHENTICATE;
2268	else
2269		sp->pp_phase = PHASE_NETWORK;
2270
2271	log(LOG_INFO, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2272	    sppp_phase_name(sp->pp_phase));
2273
2274	/*
2275	 * Open all authentication protocols.  This is even required
2276	 * if we already proceeded to network phase, since it might be
2277	 * that remote wants us to authenticate, so we might have to
2278	 * send a PAP request.  Undesired authentication protocols
2279	 * don't do anything when they get an Open event.
2280	 */
2281	for (i = 0; i < IDX_COUNT; i++)
2282		if ((cps[i])->flags & CP_AUTH)
2283			(cps[i])->Open(sp);
2284
2285	if (sp->pp_phase == PHASE_NETWORK) {
2286		/* Notify all NCPs. */
2287		for (i = 0; i < IDX_COUNT; i++)
2288			if ((cps[i])->flags & CP_NCP)
2289				(cps[i])->Open(sp);
2290	}
2291
2292	/* Send Up events to all started protos. */
2293	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2294		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_LCP) == 0)
2295			(cps[i])->Up(sp);
2296
2297	if (sp->pp_phase == PHASE_NETWORK)
2298		/* if no NCP is starting, close down */
2299		sppp_lcp_check_and_close(sp);
2300}
2301
2302static void
2303sppp_lcp_tld(struct sppp *sp)
2304{
2305	struct ifnet *ifp = &sp->pp_if;
2306	int i;
2307	u_long mask;
2308
2309	sp->pp_phase = PHASE_TERMINATE;
2310
2311	log(LOG_INFO, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2312	    sppp_phase_name(sp->pp_phase));
2313
2314	/*
2315	 * Take upper layers down.  We send the Down event first and
2316	 * the Close second to prevent the upper layers from sending
2317	 * ``a flurry of terminate-request packets'', as the RFC
2318	 * describes it.
2319	 */
2320	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2321		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_LCP) == 0) {
2322			(cps[i])->Down(sp);
2323			(cps[i])->Close(sp);
2324		}
2325}
2326
2327static void
2328sppp_lcp_tls(struct sppp *sp)
2329{
2330	struct ifnet *ifp = &sp->pp_if;
2331
2332	sp->pp_phase = PHASE_ESTABLISH;
2333
2334	log(LOG_INFO, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2335	    sppp_phase_name(sp->pp_phase));
2336
2337	/* Notify lower layer if desired. */
2338	if (sp->pp_tls)
2339		(sp->pp_tls)(sp);
2340	else
2341		(sp->pp_up)(sp);
2342}
2343
2344static void
2345sppp_lcp_tlf(struct sppp *sp)
2346{
2347	struct ifnet *ifp = &sp->pp_if;
2348
2349	sp->pp_phase = PHASE_DEAD;
2350	log(LOG_INFO, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2351	    sppp_phase_name(sp->pp_phase));
2352
2353	/* Notify lower layer if desired. */
2354	if (sp->pp_tlf)
2355		(sp->pp_tlf)(sp);
2356	else
2357		(sp->pp_down)(sp);
2358}
2359
2360static void
2361sppp_lcp_scr(struct sppp *sp)
2362{
2363	char opt[6 /* magicnum */ + 4 /* mru */ + 5 /* chap */];
2364	int i = 0;
2365	u_short authproto;
2366
2367	if (sp->lcp.opts & (1 << LCP_OPT_MAGIC)) {
2368		if (! sp->lcp.magic)
2369#if defined (__FreeBSD__)
2370			sp->lcp.magic = random();
2371#else
2372			sp->lcp.magic = time.tv_sec + time.tv_usec;
2373#endif
2374		opt[i++] = LCP_OPT_MAGIC;
2375		opt[i++] = 6;
2376		opt[i++] = sp->lcp.magic >> 24;
2377		opt[i++] = sp->lcp.magic >> 16;
2378		opt[i++] = sp->lcp.magic >> 8;
2379		opt[i++] = sp->lcp.magic;
2380	}
2381
2382	if (sp->lcp.opts & (1 << LCP_OPT_MRU)) {
2383		opt[i++] = LCP_OPT_MRU;
2384		opt[i++] = 4;
2385		opt[i++] = sp->lcp.mru >> 8;
2386		opt[i++] = sp->lcp.mru;
2387	}
2388
2389	if (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) {
2390		authproto = sp->hisauth.proto;
2391		opt[i++] = LCP_OPT_AUTH_PROTO;
2392		opt[i++] = authproto == PPP_CHAP? 5: 4;
2393		opt[i++] = authproto >> 8;
2394		opt[i++] = authproto;
2395		if (authproto == PPP_CHAP)
2396			opt[i++] = CHAP_MD5;
2397	}
2398
2399	sp->confid[IDX_LCP] = ++sp->pp_seq;
2400	sppp_cp_send (sp, PPP_LCP, CONF_REQ, sp->confid[IDX_LCP], i, &opt);
2401}
2402
2403/*
2404 * Check the open NCPs, return true if at least one NCP is open.
2405 */
2406static int
2407sppp_ncp_check(struct sppp *sp)
2408{
2409	int i, mask;
2410
2411	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2412		if (sp->lcp.protos & mask && (cps[i])->flags & CP_NCP)
2413			return 1;
2414	return 0;
2415}
2416
2417/*
2418 * Re-check the open NCPs and see if we should terminate the link.
2419 * Called by the NCPs during their tlf action handling.
2420 */
2421static void
2422sppp_lcp_check_and_close(struct sppp *sp)
2423{
2424
2425	if (sp->pp_phase < PHASE_NETWORK)
2426		/* don't bother, we are already going down */
2427		return;
2428
2429	if (sppp_ncp_check(sp))
2430		return;
2431
2432	lcp.Close(sp);
2433}
2434/*
2435 *--------------------------------------------------------------------------*
2436 *                                                                          *
2437 *                        The IPCP implementation.                          *
2438 *                                                                          *
2439 *--------------------------------------------------------------------------*
2440 */
2441
2442static void
2443sppp_ipcp_init(struct sppp *sp)
2444{
2445	sp->ipcp.opts = 0;
2446	sp->ipcp.flags = 0;
2447	sp->state[IDX_IPCP] = STATE_INITIAL;
2448	sp->fail_counter[IDX_IPCP] = 0;
2449#if defined (__FreeBSD__)
2450	callout_handle_init(&sp->ch[IDX_IPCP]);
2451#endif
2452}
2453
2454static void
2455sppp_ipcp_up(struct sppp *sp)
2456{
2457	sppp_up_event(&ipcp, sp);
2458}
2459
2460static void
2461sppp_ipcp_down(struct sppp *sp)
2462{
2463	sppp_down_event(&ipcp, sp);
2464}
2465
2466static void
2467sppp_ipcp_open(struct sppp *sp)
2468{
2469	STDDCL;
2470	u_long myaddr, hisaddr;
2471
2472	sppp_get_ip_addrs(sp, &myaddr, &hisaddr, 0);
2473	/*
2474	 * If we don't have his address, this probably means our
2475	 * interface doesn't want to talk IP at all.  (This could
2476	 * be the case if somebody wants to speak only IPX, for
2477	 * example.)  Don't open IPCP in this case.
2478	 */
2479	if (hisaddr == 0L) {
2480		/* XXX this message should go away */
2481		if (debug)
2482			log(LOG_DEBUG, SPP_FMT "ipcp_open(): no IP interface\n",
2483			    SPP_ARGS(ifp));
2484		return;
2485	}
2486
2487	if (myaddr == 0L) {
2488		/*
2489		 * I don't have an assigned address, so i need to
2490		 * negotiate my address.
2491		 */
2492		sp->ipcp.flags |= IPCP_MYADDR_DYN;
2493		sp->ipcp.opts |= (1 << IPCP_OPT_ADDRESS);
2494	}
2495	sppp_open_event(&ipcp, sp);
2496}
2497
2498static void
2499sppp_ipcp_close(struct sppp *sp)
2500{
2501	sppp_close_event(&ipcp, sp);
2502	if (sp->ipcp.flags & IPCP_MYADDR_DYN)
2503		/*
2504		 * My address was dynamic, clear it again.
2505		 */
2506		sppp_set_ip_addr(sp, 0L);
2507}
2508
2509static void
2510sppp_ipcp_TO(void *cookie)
2511{
2512	sppp_to_event(&ipcp, (struct sppp *)cookie);
2513}
2514
2515/*
2516 * Analyze a configure request.  Return true if it was agreeable, and
2517 * caused action sca, false if it has been rejected or nak'ed, and
2518 * caused action scn.  (The return value is used to make the state
2519 * transition decision in the state automaton.)
2520 */
2521static int
2522sppp_ipcp_RCR(struct sppp *sp, struct lcp_header *h, int len)
2523{
2524	u_char *buf, *r, *p;
2525	struct ifnet *ifp = &sp->pp_if;
2526	int rlen, origlen, debug = ifp->if_flags & IFF_DEBUG;
2527	u_long hisaddr, desiredaddr;
2528
2529	len -= 4;
2530	origlen = len;
2531	/*
2532	 * Make sure to allocate a buf that can at least hold a
2533	 * conf-nak with an `address' option.  We might need it below.
2534	 */
2535	buf = r = malloc ((len < 6? 6: len), M_TEMP, M_NOWAIT);
2536	if (! buf)
2537		return (0);
2538
2539	/* pass 1: see if we can recognize them */
2540	if (debug)
2541		log(LOG_DEBUG, SPP_FMT "ipcp parse opts: ",
2542		    SPP_ARGS(ifp));
2543	p = (void*) (h+1);
2544	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2545		if (debug)
2546			addlog(" %s ", sppp_ipcp_opt_name(*p));
2547		switch (*p) {
2548#ifdef notyet
2549		case IPCP_OPT_COMPRESSION:
2550			if (len >= 6 && p[1] >= 6) {
2551				/* correctly formed compress option */
2552				continue;
2553			}
2554			if (debug)
2555				addlog("[invalid] ");
2556			break;
2557#endif
2558		case IPCP_OPT_ADDRESS:
2559			if (len >= 6 && p[1] == 6) {
2560				/* correctly formed address option */
2561				continue;
2562			}
2563			if (debug)
2564				addlog("[invalid] ");
2565			break;
2566		default:
2567			/* Others not supported. */
2568			if (debug)
2569				addlog("[rej] ");
2570			break;
2571		}
2572		/* Add the option to rejected list. */
2573		bcopy (p, r, p[1]);
2574		r += p[1];
2575		rlen += p[1];
2576	}
2577	if (rlen) {
2578		if (debug)
2579			addlog(" send conf-rej\n");
2580		sppp_cp_send (sp, PPP_IPCP, CONF_REJ, h->ident, rlen, buf);
2581		return 0;
2582	} else if (debug)
2583		addlog("\n");
2584
2585	/* pass 2: parse option values */
2586	sppp_get_ip_addrs(sp, 0, &hisaddr, 0);
2587	if (debug)
2588		log(LOG_DEBUG, SPP_FMT "ipcp parse opt values: ",
2589		       SPP_ARGS(ifp));
2590	p = (void*) (h+1);
2591	len = origlen;
2592	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2593		if (debug)
2594			addlog(" %s ", sppp_ipcp_opt_name(*p));
2595		switch (*p) {
2596#ifdef notyet
2597		case IPCP_OPT_COMPRESSION:
2598			continue;
2599#endif
2600		case IPCP_OPT_ADDRESS:
2601			desiredaddr = p[2] << 24 | p[3] << 16 |
2602				p[4] << 8 | p[5];
2603			if (desiredaddr == hisaddr ||
2604			    hisaddr == 1 && desiredaddr != 0) {
2605				/*
2606				 * Peer's address is same as our value,
2607				 * or we have set it to 0.0.0.1 to
2608				 * indicate that we do not really care,
2609				 * this is agreeable.  Gonna conf-ack
2610				 * it.
2611				 */
2612				if (debug)
2613					addlog("%s [ack] ",
2614					       sppp_dotted_quad(desiredaddr));
2615				/* record that we've seen it already */
2616				sp->ipcp.flags |= IPCP_HISADDR_SEEN;
2617				continue;
2618			}
2619			/*
2620			 * The address wasn't agreeable.  This is either
2621			 * he sent us 0.0.0.0, asking to assign him an
2622			 * address, or he send us another address not
2623			 * matching our value.  Either case, we gonna
2624			 * conf-nak it with our value.
2625			 */
2626			if (debug) {
2627				if (desiredaddr == 0)
2628					addlog("[addr requested] ");
2629				else
2630					addlog("%s [not agreed] ",
2631					       sppp_dotted_quad(desiredaddr));
2632
2633				p[2] = hisaddr >> 24;
2634				p[3] = hisaddr >> 16;
2635				p[4] = hisaddr >> 8;
2636				p[5] = hisaddr;
2637			}
2638			break;
2639		}
2640		/* Add the option to nak'ed list. */
2641		bcopy (p, r, p[1]);
2642		r += p[1];
2643		rlen += p[1];
2644	}
2645
2646	/*
2647	 * If we are about to conf-ack the request, but haven't seen
2648	 * his address so far, gonna conf-nak it instead, with the
2649	 * `address' option present and our idea of his address being
2650	 * filled in there, to request negotiation of both addresses.
2651	 *
2652	 * XXX This can result in an endless req - nak loop if peer
2653	 * doesn't want to send us his address.  Q: What should we do
2654	 * about it?  XXX  A: implement the max-failure counter.
2655	 */
2656	if (rlen == 0 && !(sp->ipcp.flags & IPCP_HISADDR_SEEN)) {
2657		buf[0] = IPCP_OPT_ADDRESS;
2658		buf[1] = 6;
2659		buf[2] = hisaddr >> 24;
2660		buf[3] = hisaddr >> 16;
2661		buf[4] = hisaddr >> 8;
2662		buf[5] = hisaddr;
2663		rlen = 6;
2664		if (debug)
2665			addlog("still need hisaddr ");
2666	}
2667
2668	if (rlen) {
2669		if (debug)
2670			addlog(" send conf-nak\n");
2671		sppp_cp_send (sp, PPP_IPCP, CONF_NAK, h->ident, rlen, buf);
2672	} else {
2673		if (debug)
2674			addlog(" send conf-ack\n");
2675		sppp_cp_send (sp, PPP_IPCP, CONF_ACK,
2676			      h->ident, origlen, h+1);
2677	}
2678
2679	free (buf, M_TEMP);
2680	return (rlen == 0);
2681}
2682
2683/*
2684 * Analyze the IPCP Configure-Reject option list, and adjust our
2685 * negotiation.
2686 */
2687static void
2688sppp_ipcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
2689{
2690	u_char *buf, *p;
2691	struct ifnet *ifp = &sp->pp_if;
2692	int debug = ifp->if_flags & IFF_DEBUG;
2693
2694	len -= 4;
2695	buf = malloc (len, M_TEMP, M_NOWAIT);
2696	if (!buf)
2697		return;
2698
2699	if (debug)
2700		log(LOG_DEBUG, SPP_FMT "ipcp rej opts: ",
2701		    SPP_ARGS(ifp));
2702
2703	p = (void*) (h+1);
2704	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2705		if (debug)
2706			addlog(" %s ", sppp_ipcp_opt_name(*p));
2707		switch (*p) {
2708		case IPCP_OPT_ADDRESS:
2709			/*
2710			 * Peer doesn't grok address option.  This is
2711			 * bad.  XXX  Should we better give up here?
2712			 */
2713			sp->ipcp.opts &= ~(1 << IPCP_OPT_ADDRESS);
2714			break;
2715#ifdef notyet
2716		case IPCP_OPT_COMPRESS:
2717			sp->ipcp.opts &= ~(1 << IPCP_OPT_COMPRESS);
2718			break;
2719#endif
2720		}
2721	}
2722	if (debug)
2723		addlog("\n");
2724	free (buf, M_TEMP);
2725	return;
2726}
2727
2728/*
2729 * Analyze the IPCP Configure-NAK option list, and adjust our
2730 * negotiation.
2731 */
2732static void
2733sppp_ipcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
2734{
2735	u_char *buf, *p;
2736	struct ifnet *ifp = &sp->pp_if;
2737	int debug = ifp->if_flags & IFF_DEBUG;
2738	u_long wantaddr;
2739
2740	len -= 4;
2741	buf = malloc (len, M_TEMP, M_NOWAIT);
2742	if (!buf)
2743		return;
2744
2745	if (debug)
2746		log(LOG_DEBUG, SPP_FMT "ipcp nak opts: ",
2747		    SPP_ARGS(ifp));
2748
2749	p = (void*) (h+1);
2750	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2751		if (debug)
2752			addlog(" %s ", sppp_ipcp_opt_name(*p));
2753		switch (*p) {
2754		case IPCP_OPT_ADDRESS:
2755			/*
2756			 * Peer doesn't like our local IP address.  See
2757			 * if we can do something for him.  We'll drop
2758			 * him our address then.
2759			 */
2760			if (len >= 6 && p[1] == 6) {
2761				wantaddr = p[2] << 24 | p[3] << 16 |
2762					p[4] << 8 | p[5];
2763				sp->ipcp.opts |= (1 << IPCP_OPT_ADDRESS);
2764				if (debug)
2765					addlog("[wantaddr %s] ",
2766					       sppp_dotted_quad(wantaddr));
2767				/*
2768				 * When doing dynamic address assignment,
2769				 * we accept his offer.  Otherwise, we
2770				 * ignore it and thus continue to negotiate
2771				 * our already existing value.
2772				 */
2773				if (sp->ipcp.flags & IPCP_MYADDR_DYN) {
2774					sppp_set_ip_addr(sp, wantaddr);
2775					if (debug)
2776						addlog("[agree] ");
2777				}
2778			}
2779			break;
2780#ifdef notyet
2781		case IPCP_OPT_COMPRESS:
2782			/*
2783			 * Peer wants different compression parameters.
2784			 */
2785			break;
2786#endif
2787		}
2788	}
2789	if (debug)
2790		addlog("\n");
2791	free (buf, M_TEMP);
2792	return;
2793}
2794
2795static void
2796sppp_ipcp_tlu(struct sppp *sp)
2797{
2798}
2799
2800static void
2801sppp_ipcp_tld(struct sppp *sp)
2802{
2803}
2804
2805static void
2806sppp_ipcp_tls(struct sppp *sp)
2807{
2808	/* indicate to LCP that it must stay alive */
2809	sp->lcp.protos |= (1 << IDX_IPCP);
2810}
2811
2812static void
2813sppp_ipcp_tlf(struct sppp *sp)
2814{
2815	/* we no longer need LCP */
2816	sp->lcp.protos &= ~(1 << IDX_IPCP);
2817	sppp_lcp_check_and_close(sp);
2818}
2819
2820static void
2821sppp_ipcp_scr(struct sppp *sp)
2822{
2823	char opt[6 /* compression */ + 6 /* address */];
2824	u_long ouraddr;
2825	int i = 0;
2826
2827#ifdef notyet
2828	if (sp->ipcp.opts & (1 << IPCP_OPT_COMPRESSION)) {
2829		opt[i++] = IPCP_OPT_COMPRESSION;
2830		opt[i++] = 6;
2831		opt[i++] = 0;	/* VJ header compression */
2832		opt[i++] = 0x2d; /* VJ header compression */
2833		opt[i++] = max_slot_id;
2834		opt[i++] = comp_slot_id;
2835	}
2836#endif
2837
2838	if (sp->ipcp.opts & (1 << IPCP_OPT_ADDRESS)) {
2839		sppp_get_ip_addrs(sp, &ouraddr, 0, 0);
2840		opt[i++] = IPCP_OPT_ADDRESS;
2841		opt[i++] = 6;
2842		opt[i++] = ouraddr >> 24;
2843		opt[i++] = ouraddr >> 16;
2844		opt[i++] = ouraddr >> 8;
2845		opt[i++] = ouraddr;
2846	}
2847
2848	sp->confid[IDX_IPCP] = ++sp->pp_seq;
2849	sppp_cp_send(sp, PPP_IPCP, CONF_REQ, sp->confid[IDX_IPCP], i, &opt);
2850}
2851
2852
2853/*
2854 *--------------------------------------------------------------------------*
2855 *                                                                          *
2856 *                        The CHAP implementation.                          *
2857 *                                                                          *
2858 *--------------------------------------------------------------------------*
2859 */
2860
2861/*
2862 * The authentication protocols don't employ a full-fledged state machine as
2863 * the control protocols do, since they do have Open and Close events, but
2864 * not Up and Down, nor are they explicitly terminated.  Also, use of the
2865 * authentication protocols may be different in both directions (this makes
2866 * sense, think of a machine that never accepts incoming calls but only
2867 * calls out, it doesn't require the called party to authenticate itself).
2868 *
2869 * Our state machine for the local authentication protocol (we are requesting
2870 * the peer to authenticate) looks like:
2871 *
2872 *						    RCA-
2873 *	      +--------------------------------------------+
2874 *	      V					    scn,tld|
2875 *	  +--------+			       Close   +---------+ RCA+
2876 *	  |	   |<----------------------------------|	 |------+
2877 *   +--->| Closed |				TO*    | Opened	 | sca	|
2878 *   |	  |	   |-----+		       +-------|	 |<-----+
2879 *   |	  +--------+ irc |		       |       +---------+
2880 *   |	    ^		 |		       |	   ^
2881 *   |	    |		 |		       |	   |
2882 *   |	    |		 |		       |	   |
2883 *   |	 TO-|		 |		       |	   |
2884 *   |	    |tld  TO+	 V		       |	   |
2885 *   |	    |	+------->+		       |	   |
2886 *   |	    |	|	 |		       |	   |
2887 *   |	  +--------+	 V		       |	   |
2888 *   |	  |	   |<----+<--------------------+	   |
2889 *   |	  | Req-   | scr				   |
2890 *   |	  | Sent   |					   |
2891 *   |	  |	   |					   |
2892 *   |	  +--------+					   |
2893 *   | RCA- |	| RCA+					   |
2894 *   +------+	+------------------------------------------+
2895 *   scn,tld	  sca,irc,ict,tlu
2896 *
2897 *
2898 *   with:
2899 *
2900 *	Open:	LCP reached authentication phase
2901 *	Close:	LCP reached terminate phase
2902 *
2903 *	RCA+:	received reply (pap-req, chap-response), acceptable
2904 *	RCN:	received reply (pap-req, chap-response), not acceptable
2905 *	TO+:	timeout with restart counter >= 0
2906 *	TO-:	timeout with restart counter < 0
2907 *	TO*:	reschedule timeout for CHAP
2908 *
2909 *	scr:	send request packet (none for PAP, chap-challenge)
2910 *	sca:	send ack packet (pap-ack, chap-success)
2911 *	scn:	send nak packet (pap-nak, chap-failure)
2912 *	ict:	initialize re-challenge timer (CHAP only)
2913 *
2914 *	tlu:	this-layer-up, LCP reaches network phase
2915 *	tld:	this-layer-down, LCP enters terminate phase
2916 *
2917 * Note that in CHAP mode, after sending a new challenge, while the state
2918 * automaton falls back into Req-Sent state, it doesn't signal a tld
2919 * event to LCP, so LCP remains in network phase.  Only after not getting
2920 * any response (or after getting an unacceptable response), CHAP closes,
2921 * causing LCP to enter terminate phase.
2922 *
2923 * With PAP, there is no initial request that can be sent.  The peer is
2924 * expected to send one based on the successful negotiation of PAP as
2925 * the authentication protocol during the LCP option negotiation.
2926 *
2927 * Incoming authentication protocol requests (remote requests
2928 * authentication, we are peer) don't employ a state machine at all,
2929 * they are simply answered.  Some peers [Ascend P50 firmware rev
2930 * 4.50] react allergically when sending IPCP requests while they are
2931 * still in authentication phase (thereby violating the standard that
2932 * demands that these NCP packets are to be discarded), so we keep
2933 * track of the peer demanding us to authenticate, and only proceed to
2934 * phase network once we've seen a positive acknowledge for the
2935 * authentication.
2936 */
2937
2938/*
2939 * Handle incoming CHAP packets.
2940 */
2941void
2942sppp_chap_input(struct sppp *sp, struct mbuf *m)
2943{
2944	STDDCL;
2945	struct lcp_header *h;
2946	int len, x;
2947	u_char *value, *name, digest[AUTHKEYLEN], dsize;
2948	int value_len, name_len;
2949	MD5_CTX ctx;
2950
2951	len = m->m_pkthdr.len;
2952	if (len < 4) {
2953		if (debug)
2954			log(LOG_DEBUG,
2955			    SPP_FMT "chap invalid packet length: %d bytes\n",
2956			    SPP_ARGS(ifp), len);
2957		return;
2958	}
2959	h = mtod (m, struct lcp_header*);
2960	if (len > ntohs (h->len))
2961		len = ntohs (h->len);
2962
2963	switch (h->type) {
2964	/* challenge, failure and success are his authproto */
2965	case CHAP_CHALLENGE:
2966		value = 1 + (u_char*)(h+1);
2967		value_len = value[-1];
2968		name = value + value_len;
2969		name_len = len - value_len - 5;
2970		if (name_len < 0) {
2971			if (debug) {
2972				log(LOG_DEBUG,
2973				    SPP_FMT "chap corrupted challenge "
2974				    "<%s id=0x%x len=%d",
2975				    SPP_ARGS(ifp),
2976				    sppp_auth_type_name(PPP_CHAP, h->type),
2977				    h->ident, ntohs(h->len));
2978				if (len > 4)
2979					sppp_print_bytes((u_char*) (h+1), len-4);
2980				addlog(">\n");
2981			}
2982			break;
2983		}
2984
2985		if (debug) {
2986			log(LOG_DEBUG,
2987			    SPP_FMT "chap input <%s id=0x%x len=%d name=",
2988			    SPP_ARGS(ifp),
2989			    sppp_auth_type_name(PPP_CHAP, h->type), h->ident,
2990			    ntohs(h->len));
2991			sppp_print_string((char*) name, name_len);
2992			addlog(" value-size=%d value=", value_len);
2993			sppp_print_bytes(value, value_len);
2994			addlog(">\n");
2995		}
2996
2997		/* Compute reply value. */
2998		MD5Init(&ctx);
2999		MD5Update(&ctx, &h->ident, 1);
3000		MD5Update(&ctx, sp->myauth.secret,
3001			  sppp_strnlen(sp->myauth.secret, AUTHKEYLEN));
3002		MD5Update(&ctx, value, value_len);
3003		MD5Final(digest, &ctx);
3004		dsize = sizeof digest;
3005
3006		sppp_auth_send(&chap, sp, CHAP_RESPONSE, h->ident,
3007			       sizeof dsize, (const char *)&dsize,
3008			       sizeof digest, digest,
3009			       (size_t)sppp_strnlen(sp->myauth.name, AUTHNAMELEN),
3010			       sp->myauth.name,
3011			       0);
3012		break;
3013
3014	case CHAP_SUCCESS:
3015		if (debug) {
3016			log(LOG_DEBUG, SPP_FMT "chap success",
3017			    SPP_ARGS(ifp));
3018			if (len > 4) {
3019				addlog(": ");
3020				sppp_print_string((char*)(h + 1), len - 4);
3021			}
3022			addlog("\n");
3023		}
3024		x = splimp();
3025		sp->pp_flags &= ~PP_NEEDAUTH;
3026		if (sp->myauth.proto == PPP_CHAP &&
3027		    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) &&
3028		    (sp->lcp.protos & (1 << IDX_CHAP)) == 0) {
3029			/*
3030			 * We are authenticator for CHAP but didn't
3031			 * complete yet.  Leave it to tlu to proceed
3032			 * to network phase.
3033			 */
3034			splx(x);
3035			break;
3036		}
3037		splx(x);
3038		sppp_phase_network(sp);
3039		break;
3040
3041	case CHAP_FAILURE:
3042		if (debug) {
3043			log(LOG_INFO, SPP_FMT "chap failure",
3044			    SPP_ARGS(ifp));
3045			if (len > 4) {
3046				addlog(": ");
3047				sppp_print_string((char*)(h + 1), len - 4);
3048			}
3049			addlog("\n");
3050		} else
3051			log(LOG_INFO, SPP_FMT "chap failure\n",
3052			    SPP_ARGS(ifp));
3053		/* await LCP shutdown by authenticator */
3054		break;
3055
3056	/* response is my authproto */
3057	case CHAP_RESPONSE:
3058		value = 1 + (u_char*)(h+1);
3059		value_len = value[-1];
3060		name = value + value_len;
3061		name_len = len - value_len - 5;
3062		if (name_len < 0) {
3063			if (debug) {
3064				log(LOG_DEBUG,
3065				    SPP_FMT "chap corrupted response "
3066				    "<%s id=0x%x len=%d",
3067				    SPP_ARGS(ifp),
3068				    sppp_auth_type_name(PPP_CHAP, h->type),
3069				    h->ident, ntohs(h->len));
3070				if (len > 4)
3071					sppp_print_bytes((u_char*)(h+1), len-4);
3072				addlog(">\n");
3073			}
3074			break;
3075		}
3076		if (h->ident != sp->confid[IDX_CHAP]) {
3077			if (debug)
3078				log(LOG_DEBUG,
3079				    SPP_FMT "chap dropping response for old ID "
3080				    "(got %d, expected %d)\n",
3081				    SPP_ARGS(ifp),
3082				    h->ident, sp->confid[IDX_CHAP]);
3083			break;
3084		}
3085		if (name_len != sppp_strnlen(sp->hisauth.name, AUTHNAMELEN)
3086		    || bcmp(name, sp->hisauth.name, name_len) != 0) {
3087			log(LOG_INFO, SPP_FMT "chap response, his name ",
3088			    SPP_ARGS(ifp));
3089			sppp_print_string(name, name_len);
3090			addlog(" != expected ");
3091			sppp_print_string(sp->hisauth.name,
3092					  sppp_strnlen(sp->hisauth.name, AUTHNAMELEN));
3093			addlog("\n");
3094		}
3095		if (debug) {
3096			log(LOG_DEBUG, SPP_FMT "chap input(%s) "
3097			    "<%s id=0x%x len=%d name=",
3098			    SPP_ARGS(ifp),
3099			    sppp_state_name(sp->state[IDX_CHAP]),
3100			    sppp_auth_type_name(PPP_CHAP, h->type),
3101			    h->ident, ntohs (h->len));
3102			sppp_print_string((char*)name, name_len);
3103			addlog(" value-size=%d value=", value_len);
3104			sppp_print_bytes(value, value_len);
3105			addlog(">\n");
3106		}
3107		if (value_len != AUTHKEYLEN) {
3108			if (debug)
3109				log(LOG_DEBUG,
3110				    SPP_FMT "chap bad hash value length: "
3111				    "%d bytes, should be %d\n",
3112				    SPP_ARGS(ifp), value_len,
3113				    AUTHKEYLEN);
3114			break;
3115		}
3116
3117		MD5Init(&ctx);
3118		MD5Update(&ctx, &h->ident, 1);
3119		MD5Update(&ctx, sp->hisauth.secret,
3120			  sppp_strnlen(sp->hisauth.secret, AUTHKEYLEN));
3121		MD5Update(&ctx, sp->myauth.challenge, AUTHKEYLEN);
3122		MD5Final(digest, &ctx);
3123
3124#define FAILMSG "Failed..."
3125#define SUCCMSG "Welcome!"
3126
3127		if (value_len != sizeof digest ||
3128		    bcmp(digest, value, value_len) != 0) {
3129			/* action scn, tld */
3130			sppp_auth_send(&chap, sp, CHAP_FAILURE, h->ident,
3131				       sizeof(FAILMSG) - 1, (u_char *)FAILMSG,
3132				       0);
3133			chap.tld(sp);
3134			break;
3135		}
3136		/* action sca, perhaps tlu */
3137		if (sp->state[IDX_CHAP] == STATE_REQ_SENT ||
3138		    sp->state[IDX_CHAP] == STATE_OPENED)
3139			sppp_auth_send(&chap, sp, CHAP_SUCCESS, h->ident,
3140				       sizeof(SUCCMSG) - 1, (u_char *)SUCCMSG,
3141				       0);
3142		if (sp->state[IDX_CHAP] == STATE_REQ_SENT) {
3143			sppp_cp_change_state(&chap, sp, STATE_OPENED);
3144			chap.tlu(sp);
3145		}
3146		break;
3147
3148	default:
3149		/* Unknown CHAP packet type -- ignore. */
3150		if (debug) {
3151			log(LOG_DEBUG, SPP_FMT "chap unknown input(%s) "
3152			    "<0x%x id=0x%xh len=%d",
3153			    SPP_ARGS(ifp),
3154			    sppp_state_name(sp->state[IDX_CHAP]),
3155			    h->type, h->ident, ntohs(h->len));
3156			if (len > 4)
3157				sppp_print_bytes((u_char*)(h+1), len-4);
3158			addlog(">\n");
3159		}
3160		break;
3161
3162	}
3163}
3164
3165static void
3166sppp_chap_init(struct sppp *sp)
3167{
3168	/* Chap doesn't have STATE_INITIAL at all. */
3169	sp->state[IDX_CHAP] = STATE_CLOSED;
3170	sp->fail_counter[IDX_CHAP] = 0;
3171#if defined (__FreeBSD__)
3172	callout_handle_init(&sp->ch[IDX_CHAP]);
3173#endif
3174}
3175
3176static void
3177sppp_chap_open(struct sppp *sp)
3178{
3179	if (sp->myauth.proto == PPP_CHAP &&
3180	    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0) {
3181		/* we are authenticator for CHAP, start it */
3182		chap.scr(sp);
3183		sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3184		sppp_cp_change_state(&chap, sp, STATE_REQ_SENT);
3185	}
3186	/* nothing to be done if we are peer, await a challenge */
3187}
3188
3189static void
3190sppp_chap_close(struct sppp *sp)
3191{
3192	if (sp->state[IDX_CHAP] != STATE_CLOSED)
3193		sppp_cp_change_state(&chap, sp, STATE_CLOSED);
3194}
3195
3196static void
3197sppp_chap_TO(void *cookie)
3198{
3199	struct sppp *sp = (struct sppp *)cookie;
3200	STDDCL;
3201	int s;
3202
3203	s = splimp();
3204	if (debug)
3205		log(LOG_DEBUG, SPP_FMT "chap TO(%s) rst_counter = %d\n",
3206		    SPP_ARGS(ifp),
3207		    sppp_state_name(sp->state[IDX_CHAP]),
3208		    sp->rst_counter[IDX_CHAP]);
3209
3210	if (--sp->rst_counter[IDX_CHAP] < 0)
3211		/* TO- event */
3212		switch (sp->state[IDX_CHAP]) {
3213		case STATE_REQ_SENT:
3214			chap.tld(sp);
3215			sppp_cp_change_state(&chap, sp, STATE_CLOSED);
3216			break;
3217		}
3218	else
3219		/* TO+ (or TO*) event */
3220		switch (sp->state[IDX_CHAP]) {
3221		case STATE_OPENED:
3222			/* TO* event */
3223			sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3224			/* fall through */
3225		case STATE_REQ_SENT:
3226			chap.scr(sp);
3227			/* sppp_cp_change_state() will restart the timer */
3228			sppp_cp_change_state(&chap, sp, STATE_REQ_SENT);
3229			break;
3230		}
3231
3232	splx(s);
3233}
3234
3235static void
3236sppp_chap_tlu(struct sppp *sp)
3237{
3238	STDDCL;
3239	int i, x;
3240
3241	i = 0;
3242	sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
3243
3244	/*
3245	 * Some broken CHAP implementations (Conware CoNet, firmware
3246	 * 4.0.?) don't want to re-authenticate their CHAP once the
3247	 * initial challenge-response exchange has taken place.
3248	 * Provide for an option to avoid rechallenges.
3249	 */
3250	if ((sp->hisauth.flags & AUTHFLAG_NORECHALLENGE) == 0) {
3251		/*
3252		 * Compute the re-challenge timeout.  This will yield
3253		 * a number between 300 and 810 seconds.
3254		 */
3255		i = 300 + ((unsigned)(random() & 0xff00) >> 7);
3256
3257#if defined (__FreeBSD__)
3258		sp->ch[IDX_CHAP] =
3259#endif
3260		timeout(chap.TO, (void *)sp, i * hz);
3261	}
3262
3263	if (debug) {
3264		log(LOG_DEBUG,
3265		    SPP_FMT "chap %s, ",
3266		    SPP_ARGS(ifp),
3267		    sp->pp_phase == PHASE_NETWORK? "reconfirmed": "tlu");
3268		if ((sp->hisauth.flags & AUTHFLAG_NORECHALLENGE) == 0)
3269			addlog("next re-challenge in %d seconds\n", i);
3270		else
3271			addlog("re-challenging supressed\n");
3272	}
3273
3274	x = splimp();
3275	/* indicate to LCP that we need to be closed down */
3276	sp->lcp.protos |= (1 << IDX_CHAP);
3277
3278	if (sp->pp_flags & PP_NEEDAUTH) {
3279		/*
3280		 * Remote is authenticator, but his auth proto didn't
3281		 * complete yet.  Defer the transition to network
3282		 * phase.
3283		 */
3284		splx(x);
3285		return;
3286	}
3287	splx(x);
3288
3289	/*
3290	 * If we are already in phase network, we are done here.  This
3291	 * is the case if this is a dummy tlu event after a re-challenge.
3292	 */
3293	if (sp->pp_phase != PHASE_NETWORK)
3294		sppp_phase_network(sp);
3295}
3296
3297static void
3298sppp_chap_tld(struct sppp *sp)
3299{
3300	STDDCL;
3301
3302	if (debug)
3303		log(LOG_DEBUG, SPP_FMT "chap tld\n", SPP_ARGS(ifp));
3304	UNTIMEOUT(chap.TO, (void *)sp, sp->ch[IDX_CHAP]);
3305	sp->lcp.protos &= ~(1 << IDX_CHAP);
3306
3307	lcp.Close(sp);
3308}
3309
3310static void
3311sppp_chap_scr(struct sppp *sp)
3312{
3313	u_long *ch, seed;
3314	u_char clen;
3315#if defined (__NetBSD__) || defined (__OpenBSD__)
3316	struct timeval tv;
3317#endif
3318
3319	/* Compute random challenge. */
3320	ch = (u_long *)sp->myauth.challenge;
3321#if defined (__FreeBSD__)
3322	read_random(&seed, sizeof seed);
3323#else
3324	microtime(&tv);
3325	seed = tv.tv_sec ^ tv.tv_usec;
3326#endif
3327	ch[0] = seed ^ random();
3328	ch[1] = seed ^ random();
3329	ch[2] = seed ^ random();
3330	ch[3] = seed ^ random();
3331	clen = AUTHKEYLEN;
3332
3333	sp->confid[IDX_CHAP] = ++sp->pp_seq;
3334
3335	sppp_auth_send(&chap, sp, CHAP_CHALLENGE, sp->confid[IDX_CHAP],
3336		       sizeof clen, (const char *)&clen,
3337		       (size_t)AUTHKEYLEN, sp->myauth.challenge,
3338		       (size_t)sppp_strnlen(sp->myauth.name, AUTHNAMELEN),
3339		       sp->myauth.name,
3340		       0);
3341}
3342/*
3343 *--------------------------------------------------------------------------*
3344 *                                                                          *
3345 *                        The PAP implementation.                           *
3346 *                                                                          *
3347 *--------------------------------------------------------------------------*
3348 */
3349/*
3350 * For PAP, we need to keep a little state also if we are the peer, not the
3351 * authenticator.  This is since we don't get a request to authenticate, but
3352 * have to repeatedly authenticate ourself until we got a response (or the
3353 * retry counter is expired).
3354 */
3355
3356/*
3357 * Handle incoming PAP packets.  */
3358static void
3359sppp_pap_input(struct sppp *sp, struct mbuf *m)
3360{
3361	STDDCL;
3362	struct lcp_header *h;
3363	int len, x;
3364	u_char *name, *passwd, mlen;
3365	int name_len, passwd_len;
3366
3367	len = m->m_pkthdr.len;
3368	if (len < 5) {
3369		if (debug)
3370			log(LOG_DEBUG,
3371			    SPP_FMT "pap invalid packet length: %d bytes\n",
3372			    SPP_ARGS(ifp), len);
3373		return;
3374	}
3375	h = mtod (m, struct lcp_header*);
3376	if (len > ntohs (h->len))
3377		len = ntohs (h->len);
3378	switch (h->type) {
3379	/* PAP request is my authproto */
3380	case PAP_REQ:
3381		name = 1 + (u_char*)(h+1);
3382		name_len = name[-1];
3383		passwd = name + name_len + 1;
3384		if (name_len > len - 6 ||
3385		    (passwd_len = passwd[-1]) > len - 6 - name_len) {
3386			if (debug) {
3387				log(LOG_DEBUG, SPP_FMT "pap corrupted input "
3388				    "<%s id=0x%x len=%d",
3389				    SPP_ARGS(ifp),
3390				    sppp_auth_type_name(PPP_PAP, h->type),
3391				    h->ident, ntohs(h->len));
3392				if (len > 4)
3393					sppp_print_bytes((u_char*)(h+1), len-4);
3394				addlog(">\n");
3395			}
3396			break;
3397		}
3398		if (debug) {
3399			log(LOG_DEBUG, SPP_FMT "pap input(%s) "
3400			    "<%s id=0x%x len=%d name=",
3401			    SPP_ARGS(ifp),
3402			    sppp_state_name(sp->state[IDX_PAP]),
3403			    sppp_auth_type_name(PPP_PAP, h->type),
3404			    h->ident, ntohs(h->len));
3405			sppp_print_string((char*)name, name_len);
3406			addlog(" passwd=");
3407			sppp_print_string((char*)passwd, passwd_len);
3408			addlog(">\n");
3409		}
3410		if (name_len > AUTHNAMELEN ||
3411		    passwd_len > AUTHKEYLEN ||
3412		    bcmp(name, sp->hisauth.name, name_len) != 0 ||
3413		    bcmp(passwd, sp->hisauth.secret, passwd_len) != 0) {
3414			/* action scn, tld */
3415			mlen = sizeof(FAILMSG) - 1;
3416			sppp_auth_send(&pap, sp, PAP_NAK, h->ident,
3417				       sizeof mlen, (const char *)&mlen,
3418				       sizeof(FAILMSG) - 1, (u_char *)FAILMSG,
3419				       0);
3420			pap.tld(sp);
3421			break;
3422		}
3423		/* action sca, perhaps tlu */
3424		if (sp->state[IDX_PAP] == STATE_REQ_SENT ||
3425		    sp->state[IDX_PAP] == STATE_OPENED) {
3426			mlen = sizeof(SUCCMSG) - 1;
3427			sppp_auth_send(&pap, sp, PAP_ACK, h->ident,
3428				       sizeof mlen, (const char *)&mlen,
3429				       sizeof(SUCCMSG) - 1, (u_char *)SUCCMSG,
3430				       0);
3431		}
3432		if (sp->state[IDX_PAP] == STATE_REQ_SENT) {
3433			sppp_cp_change_state(&pap, sp, STATE_OPENED);
3434			pap.tlu(sp);
3435		}
3436		break;
3437
3438	/* ack and nak are his authproto */
3439	case PAP_ACK:
3440		UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
3441		if (debug) {
3442			log(LOG_DEBUG, SPP_FMT "pap success",
3443			    SPP_ARGS(ifp));
3444			name_len = *((char *)h);
3445			if (len > 5 && name_len) {
3446				addlog(": ");
3447				sppp_print_string((char*)(h+1), name_len);
3448			}
3449			addlog("\n");
3450		}
3451		x = splimp();
3452		sp->pp_flags &= ~PP_NEEDAUTH;
3453		if (sp->myauth.proto == PPP_PAP &&
3454		    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) &&
3455		    (sp->lcp.protos & (1 << IDX_PAP)) == 0) {
3456			/*
3457			 * We are authenticator for PAP but didn't
3458			 * complete yet.  Leave it to tlu to proceed
3459			 * to network phase.
3460			 */
3461			splx(x);
3462			break;
3463		}
3464		splx(x);
3465		sppp_phase_network(sp);
3466		break;
3467
3468	case PAP_NAK:
3469		UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
3470		if (debug) {
3471			log(LOG_INFO, SPP_FMT "pap failure",
3472			    SPP_ARGS(ifp));
3473			name_len = *((char *)h);
3474			if (len > 5 && name_len) {
3475				addlog(": ");
3476				sppp_print_string((char*)(h+1), name_len);
3477			}
3478			addlog("\n");
3479		} else
3480			log(LOG_INFO, SPP_FMT "pap failure\n",
3481			    SPP_ARGS(ifp));
3482		/* await LCP shutdown by authenticator */
3483		break;
3484
3485	default:
3486		/* Unknown PAP packet type -- ignore. */
3487		if (debug) {
3488			log(LOG_DEBUG, SPP_FMT "pap corrupted input "
3489			    "<0x%x id=0x%x len=%d",
3490			    SPP_ARGS(ifp),
3491			    h->type, h->ident, ntohs(h->len));
3492			if (len > 4)
3493				sppp_print_bytes((u_char*)(h+1), len-4);
3494			addlog(">\n");
3495		}
3496		break;
3497
3498	}
3499}
3500
3501static void
3502sppp_pap_init(struct sppp *sp)
3503{
3504	/* PAP doesn't have STATE_INITIAL at all. */
3505	sp->state[IDX_PAP] = STATE_CLOSED;
3506	sp->fail_counter[IDX_PAP] = 0;
3507#if defined (__FreeBSD__)
3508	callout_handle_init(&sp->ch[IDX_PAP]);
3509	callout_handle_init(&sp->pap_my_to_ch);
3510#endif
3511}
3512
3513static void
3514sppp_pap_open(struct sppp *sp)
3515{
3516	if (sp->hisauth.proto == PPP_PAP &&
3517	    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0) {
3518		/* we are authenticator for PAP, start our timer */
3519		sp->rst_counter[IDX_PAP] = sp->lcp.max_configure;
3520		sppp_cp_change_state(&pap, sp, STATE_REQ_SENT);
3521	}
3522	if (sp->myauth.proto == PPP_PAP) {
3523		/* we are peer, send a request, and start a timer */
3524		pap.scr(sp);
3525#if defined (__FreeBSD__)
3526		sp->pap_my_to_ch =
3527#endif
3528		timeout(sppp_pap_my_TO, (void *)sp, sp->lcp.timeout);
3529	}
3530}
3531
3532static void
3533sppp_pap_close(struct sppp *sp)
3534{
3535	if (sp->state[IDX_PAP] != STATE_CLOSED)
3536		sppp_cp_change_state(&pap, sp, STATE_CLOSED);
3537}
3538
3539/*
3540 * That's the timeout routine if we are authenticator.  Since the
3541 * authenticator is basically passive in PAP, we can't do much here.
3542 */
3543static void
3544sppp_pap_TO(void *cookie)
3545{
3546	struct sppp *sp = (struct sppp *)cookie;
3547	STDDCL;
3548	int s;
3549
3550	s = splimp();
3551	if (debug)
3552		log(LOG_DEBUG, SPP_FMT "pap TO(%s) rst_counter = %d\n",
3553		    SPP_ARGS(ifp),
3554		    sppp_state_name(sp->state[IDX_PAP]),
3555		    sp->rst_counter[IDX_PAP]);
3556
3557	if (--sp->rst_counter[IDX_PAP] < 0)
3558		/* TO- event */
3559		switch (sp->state[IDX_PAP]) {
3560		case STATE_REQ_SENT:
3561			pap.tld(sp);
3562			sppp_cp_change_state(&pap, sp, STATE_CLOSED);
3563			break;
3564		}
3565	else
3566		/* TO+ event, not very much we could do */
3567		switch (sp->state[IDX_PAP]) {
3568		case STATE_REQ_SENT:
3569			/* sppp_cp_change_state() will restart the timer */
3570			sppp_cp_change_state(&pap, sp, STATE_REQ_SENT);
3571			break;
3572		}
3573
3574	splx(s);
3575}
3576
3577/*
3578 * That's the timeout handler if we are peer.  Since the peer is active,
3579 * we need to retransmit our PAP request since it is apparently lost.
3580 * XXX We should impose a max counter.
3581 */
3582static void
3583sppp_pap_my_TO(void *cookie)
3584{
3585	struct sppp *sp = (struct sppp *)cookie;
3586	STDDCL;
3587
3588	if (debug)
3589		log(LOG_DEBUG, SPP_FMT "pap peer TO\n",
3590		    SPP_ARGS(ifp));
3591
3592	pap.scr(sp);
3593}
3594
3595static void
3596sppp_pap_tlu(struct sppp *sp)
3597{
3598	STDDCL;
3599	int x;
3600
3601	sp->rst_counter[IDX_PAP] = sp->lcp.max_configure;
3602
3603	if (debug)
3604		log(LOG_DEBUG, SPP_FMT "%s tlu\n",
3605		    SPP_ARGS(ifp), pap.name);
3606
3607	x = splimp();
3608	/* indicate to LCP that we need to be closed down */
3609	sp->lcp.protos |= (1 << IDX_PAP);
3610
3611	if (sp->pp_flags & PP_NEEDAUTH) {
3612		/*
3613		 * Remote is authenticator, but his auth proto didn't
3614		 * complete yet.  Defer the transition to network
3615		 * phase.
3616		 */
3617		splx(x);
3618		return;
3619	}
3620	splx(x);
3621	sppp_phase_network(sp);
3622}
3623
3624static void
3625sppp_pap_tld(struct sppp *sp)
3626{
3627	STDDCL;
3628
3629	if (debug)
3630		log(LOG_DEBUG, SPP_FMT "pap tld\n", SPP_ARGS(ifp));
3631	UNTIMEOUT(pap.TO, (void *)sp, sp->ch[IDX_PAP]);
3632	UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
3633	sp->lcp.protos &= ~(1 << IDX_PAP);
3634
3635	lcp.Close(sp);
3636}
3637
3638static void
3639sppp_pap_scr(struct sppp *sp)
3640{
3641	u_char idlen, pwdlen;
3642
3643	sp->confid[IDX_PAP] = ++sp->pp_seq;
3644	pwdlen = sppp_strnlen(sp->myauth.secret, AUTHKEYLEN);
3645	idlen = sppp_strnlen(sp->myauth.name, AUTHNAMELEN);
3646
3647	sppp_auth_send(&pap, sp, PAP_REQ, sp->confid[IDX_PAP],
3648		       sizeof idlen, (const char *)&idlen,
3649		       (size_t)idlen, sp->myauth.name,
3650		       sizeof pwdlen, (const char *)&pwdlen,
3651		       (size_t)pwdlen, sp->myauth.secret,
3652		       0);
3653}
3654/*
3655 * Random miscellaneous functions.
3656 */
3657
3658/*
3659 * Send a PAP or CHAP proto packet.
3660 *
3661 * Varadic function, each of the elements for the ellipsis is of type
3662 * ``size_t mlen, const u_char *msg''.  Processing will stop iff
3663 * mlen == 0.
3664 */
3665
3666static void
3667sppp_auth_send(const struct cp *cp, struct sppp *sp, u_char type, u_char id,
3668	       ...)
3669{
3670	STDDCL;
3671	struct ppp_header *h;
3672	struct lcp_header *lh;
3673	struct mbuf *m;
3674	u_char *p;
3675	int len;
3676	size_t mlen;
3677	const char *msg;
3678	va_list ap;
3679
3680	MGETHDR (m, M_DONTWAIT, MT_DATA);
3681	if (! m)
3682		return;
3683	m->m_pkthdr.rcvif = 0;
3684
3685	h = mtod (m, struct ppp_header*);
3686	h->address = PPP_ALLSTATIONS;		/* broadcast address */
3687	h->control = PPP_UI;			/* Unnumbered Info */
3688	h->protocol = htons(cp->proto);
3689
3690	lh = (struct lcp_header*)(h + 1);
3691	lh->type = type;
3692	lh->ident = id;
3693	p = (u_char*) (lh+1);
3694
3695	va_start(ap, id);
3696	len = 0;
3697
3698	while ((mlen = va_arg(ap, size_t)) != 0) {
3699		msg = va_arg(ap, const char *);
3700		len += mlen;
3701		if (len > MHLEN - PPP_HEADER_LEN - LCP_HEADER_LEN) {
3702			va_end(ap);
3703			m_freem(m);
3704			return;
3705		}
3706
3707		bcopy(msg, p, mlen);
3708		p += mlen;
3709	}
3710	va_end(ap);
3711
3712	m->m_pkthdr.len = m->m_len = PPP_HEADER_LEN + LCP_HEADER_LEN + len;
3713	lh->len = htons (LCP_HEADER_LEN + len);
3714
3715	if (debug) {
3716		log(LOG_DEBUG, SPP_FMT "%s output <%s id=0x%x len=%d",
3717		    SPP_ARGS(ifp), cp->name,
3718		    sppp_auth_type_name(cp->proto, lh->type),
3719		    lh->ident, ntohs(lh->len));
3720		if (len)
3721			sppp_print_bytes((u_char*) (lh+1), len);
3722		addlog(">\n");
3723	}
3724	if (IF_QFULL (&sp->pp_cpq)) {
3725		IF_DROP (&sp->pp_fastq);
3726		IF_DROP (&ifp->if_snd);
3727		m_freem (m);
3728		++ifp->if_oerrors;
3729	} else
3730		IF_ENQUEUE (&sp->pp_cpq, m);
3731	if (! (ifp->if_flags & IFF_OACTIVE))
3732		(*ifp->if_start) (ifp);
3733	ifp->if_obytes += m->m_pkthdr.len + 3;
3734}
3735
3736/*
3737 * Flush interface queue.
3738 */
3739static void
3740sppp_qflush(struct ifqueue *ifq)
3741{
3742	struct mbuf *m, *n;
3743
3744	n = ifq->ifq_head;
3745	while ((m = n)) {
3746		n = m->m_act;
3747		m_freem (m);
3748	}
3749	ifq->ifq_head = 0;
3750	ifq->ifq_tail = 0;
3751	ifq->ifq_len = 0;
3752}
3753
3754/*
3755 * Send keepalive packets, every 10 seconds.
3756 */
3757static void
3758sppp_keepalive(void *dummy)
3759{
3760	struct sppp *sp;
3761	int s;
3762
3763	s = splimp();
3764	for (sp=spppq; sp; sp=sp->pp_next) {
3765		struct ifnet *ifp = &sp->pp_if;
3766
3767		/* Keepalive mode disabled or channel down? */
3768		if (! (sp->pp_flags & PP_KEEPALIVE) ||
3769		    ! (ifp->if_flags & IFF_RUNNING))
3770			continue;
3771
3772		/* No keepalive in PPP mode if LCP not opened yet. */
3773		if (! (sp->pp_flags & PP_CISCO) &&
3774		    sp->pp_phase < PHASE_AUTHENTICATE)
3775			continue;
3776
3777		if (sp->pp_alivecnt == MAXALIVECNT) {
3778			/* No keepalive packets got.  Stop the interface. */
3779			printf (SPP_FMT "down\n", SPP_ARGS(ifp));
3780			if_down (ifp);
3781			sppp_qflush (&sp->pp_cpq);
3782			if (! (sp->pp_flags & PP_CISCO)) {
3783				/* XXX */
3784				/* Shut down the PPP link. */
3785				lcp.Down(sp);
3786				/* Initiate negotiation. XXX */
3787				lcp.Up(sp);
3788			}
3789		}
3790		if (sp->pp_alivecnt <= MAXALIVECNT)
3791			++sp->pp_alivecnt;
3792		if (sp->pp_flags & PP_CISCO)
3793			sppp_cisco_send (sp, CISCO_KEEPALIVE_REQ, ++sp->pp_seq,
3794				sp->pp_rseq);
3795		else if (sp->pp_phase >= PHASE_AUTHENTICATE) {
3796			long nmagic = htonl (sp->lcp.magic);
3797			sp->lcp.echoid = ++sp->pp_seq;
3798			sppp_cp_send (sp, PPP_LCP, ECHO_REQ,
3799				sp->lcp.echoid, 4, &nmagic);
3800		}
3801	}
3802	splx(s);
3803#if defined (__FreeBSD__)
3804	keepalive_ch =
3805#endif
3806	timeout(sppp_keepalive, 0, hz * 10);
3807}
3808
3809/*
3810 * Get both IP addresses.
3811 */
3812static void
3813sppp_get_ip_addrs(struct sppp *sp, u_long *src, u_long *dst, u_long *srcmask)
3814{
3815	struct ifnet *ifp = &sp->pp_if;
3816	struct ifaddr *ifa;
3817	struct sockaddr_in *si, *sm;
3818	u_long ssrc, ddst;
3819
3820	sm = NULL;
3821	ssrc = ddst = 0L;
3822	/*
3823	 * Pick the first AF_INET address from the list,
3824	 * aliases don't make any sense on a p2p link anyway.
3825	 */
3826#if defined (__FreeBSD__)
3827	for (ifa = ifp->if_addrhead.tqh_first, si = 0;
3828	     ifa;
3829	     ifa = ifa->ifa_link.tqe_next)
3830#else
3831	for (ifa = ifp->if_addrlist.tqh_first, si = 0;
3832	     ifa;
3833	     ifa = ifa->ifa_list.tqe_next)
3834#endif
3835		if (ifa->ifa_addr->sa_family == AF_INET) {
3836			si = (struct sockaddr_in *)ifa->ifa_addr;
3837			sm = (struct sockaddr_in *)ifa->ifa_netmask;
3838			if (si)
3839				break;
3840		}
3841	if (ifa) {
3842		if (si && si->sin_addr.s_addr) {
3843			ssrc = si->sin_addr.s_addr;
3844			if (srcmask)
3845				*srcmask = ntohl(sm->sin_addr.s_addr);
3846		}
3847
3848		si = (struct sockaddr_in *)ifa->ifa_dstaddr;
3849		if (si && si->sin_addr.s_addr)
3850			ddst = si->sin_addr.s_addr;
3851	}
3852
3853	if (dst) *dst = ntohl(ddst);
3854	if (src) *src = ntohl(ssrc);
3855}
3856
3857/*
3858 * Set my IP address.  Must be called at splimp.
3859 */
3860static void
3861sppp_set_ip_addr(struct sppp *sp, u_long src)
3862{
3863	struct ifnet *ifp = &sp->pp_if;
3864	struct ifaddr *ifa;
3865	struct sockaddr_in *si;
3866
3867	/*
3868	 * Pick the first AF_INET address from the list,
3869	 * aliases don't make any sense on a p2p link anyway.
3870	 */
3871
3872#if defined (__FreeBSD__)
3873	for (ifa = ifp->if_addrhead.tqh_first, si = 0;
3874	     ifa;
3875	     ifa = ifa->ifa_link.tqe_next)
3876#else
3877	for (ifa = ifp->if_addrlist.tqh_first, si = 0;
3878	     ifa;
3879	     ifa = ifa->ifa_list.tqe_next)
3880#endif
3881	{
3882		if (ifa->ifa_addr->sa_family == AF_INET)
3883		{
3884			si = (struct sockaddr_in *)ifa->ifa_addr;
3885			if (si)
3886				break;
3887		}
3888	}
3889
3890	if (ifa && si)
3891		si->sin_addr.s_addr = htonl(src);
3892}
3893
3894static int
3895sppp_params(struct sppp *sp, u_long cmd, void *data)
3896{
3897	u_long subcmd;
3898	struct ifreq *ifr = (struct ifreq *)data;
3899	struct spppreq spr;
3900
3901	/*
3902	 * ifr->ifr_data is supposed to point to a struct spppreq.
3903	 * Check the cmd word first before attempting to fetch all the
3904	 * data.
3905	 */
3906	if ((subcmd = fuword(ifr->ifr_data)) == -1)
3907		return EFAULT;
3908
3909	if (copyin((caddr_t)ifr->ifr_data, &spr, sizeof spr) != 0)
3910		return EFAULT;
3911
3912	switch (subcmd) {
3913	case SPPPIOGDEFS:
3914		if (cmd != SIOCGIFGENERIC)
3915			return EINVAL;
3916		/*
3917		 * We copy over the entire current state, but clean
3918		 * out some of the stuff we don't wanna pass up.
3919		 * Remember, SIOCGIFGENERIC is unprotected, and can be
3920		 * called by any user.  No need to ever get PAP or
3921		 * CHAP secrets back to userland anyway.
3922		 */
3923		bcopy(sp, &spr.defs, sizeof(struct sppp));
3924		bzero(spr.defs.myauth.secret, AUTHKEYLEN);
3925		bzero(spr.defs.myauth.challenge, AUTHKEYLEN);
3926		bzero(spr.defs.hisauth.secret, AUTHKEYLEN);
3927		bzero(spr.defs.hisauth.challenge, AUTHKEYLEN);
3928		return copyout(&spr, (caddr_t)ifr->ifr_data, sizeof spr);
3929
3930	case SPPPIOSDEFS:
3931		if (cmd != SIOCSIFGENERIC)
3932			return EINVAL;
3933		/*
3934		 * We have a very specific idea of which fields we allow
3935		 * being passed back from userland, so to not clobber our
3936		 * current state.  For one, we only allow setting
3937		 * anything if LCP is in dead phase.  Once the LCP
3938		 * negotiations started, the authentication settings must
3939		 * not be changed again.  (The administrator can force an
3940		 * ifconfig down in order to get LCP back into dead
3941		 * phase.)
3942		 *
3943		 * Also, we only allow for authentication parameters to be
3944		 * specified.
3945		 *
3946		 * XXX Should allow to set or clear pp_flags.
3947		 *
3948		 * Finally, if the respective authentication protocol to
3949		 * be used is set differently than 0, but the secret is
3950		 * passed as all zeros, we don't trash the existing secret.
3951		 * This allows an administrator to change the system name
3952		 * only without clobbering the secret (which he didn't get
3953		 * back in a previous SPPPIOGDEFS call).  However, the
3954		 * secrets are cleared if the authentication protocol is
3955		 * reset to 0.
3956		 */
3957		if (sp->pp_phase != PHASE_DEAD)
3958			return EBUSY;
3959
3960		if ((spr.defs.myauth.proto != 0 && spr.defs.myauth.proto != PPP_PAP &&
3961		     spr.defs.myauth.proto != PPP_CHAP) ||
3962		    (spr.defs.hisauth.proto != 0 && spr.defs.hisauth.proto != PPP_PAP &&
3963		     spr.defs.hisauth.proto != PPP_CHAP))
3964			return EINVAL;
3965
3966		if (spr.defs.myauth.proto == 0)
3967			/* resetting myauth */
3968			bzero(&sp->myauth, sizeof sp->myauth);
3969		else {
3970			/* setting/changing myauth */
3971			sp->myauth.proto = spr.defs.myauth.proto;
3972			bcopy(spr.defs.myauth.name, sp->myauth.name, AUTHNAMELEN);
3973			if (spr.defs.myauth.secret[0] != '\0')
3974				bcopy(spr.defs.myauth.secret, sp->myauth.secret,
3975				      AUTHKEYLEN);
3976		}
3977		if (spr.defs.hisauth.proto == 0)
3978			/* resetting hisauth */
3979			bzero(&sp->hisauth, sizeof sp->hisauth);
3980		else {
3981			/* setting/changing hisauth */
3982			sp->hisauth.proto = spr.defs.hisauth.proto;
3983			sp->hisauth.flags = spr.defs.hisauth.flags;
3984			bcopy(spr.defs.hisauth.name, sp->hisauth.name, AUTHNAMELEN);
3985			if (spr.defs.hisauth.secret[0] != '\0')
3986				bcopy(spr.defs.hisauth.secret, sp->hisauth.secret,
3987				      AUTHKEYLEN);
3988		}
3989		break;
3990
3991	default:
3992		return EINVAL;
3993	}
3994
3995	return 0;
3996}
3997
3998static void
3999sppp_phase_network(struct sppp *sp)
4000{
4001	struct ifnet *ifp = &sp->pp_if;
4002	int i;
4003	u_long mask;
4004
4005	sp->pp_phase = PHASE_NETWORK;
4006
4007	log(LOG_INFO, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
4008	    sppp_phase_name(sp->pp_phase));
4009
4010	/* Notify NCPs now. */
4011	for (i = 0; i < IDX_COUNT; i++)
4012		if ((cps[i])->flags & CP_NCP)
4013			(cps[i])->Open(sp);
4014
4015	/* Send Up events to all NCPs. */
4016	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
4017		if (sp->lcp.protos & mask && ((cps[i])->flags & CP_NCP))
4018			(cps[i])->Up(sp);
4019
4020	/* if no NCP is starting, all this was in vain, close down */
4021	sppp_lcp_check_and_close(sp);
4022}
4023
4024
4025static const char *
4026sppp_cp_type_name(u_char type)
4027{
4028	static char buf[12];
4029	switch (type) {
4030	case CONF_REQ:   return "conf-req";
4031	case CONF_ACK:   return "conf-ack";
4032	case CONF_NAK:   return "conf-nak";
4033	case CONF_REJ:   return "conf-rej";
4034	case TERM_REQ:   return "term-req";
4035	case TERM_ACK:   return "term-ack";
4036	case CODE_REJ:   return "code-rej";
4037	case PROTO_REJ:  return "proto-rej";
4038	case ECHO_REQ:   return "echo-req";
4039	case ECHO_REPLY: return "echo-reply";
4040	case DISC_REQ:   return "discard-req";
4041	}
4042	snprintf (buf, sizeof(buf), "0x%x", type);
4043	return buf;
4044}
4045
4046static const char *
4047sppp_auth_type_name(u_short proto, u_char type)
4048{
4049	static char buf[12];
4050	switch (proto) {
4051	case PPP_CHAP:
4052		switch (type) {
4053		case CHAP_CHALLENGE:	return "challenge";
4054		case CHAP_RESPONSE:	return "response";
4055		case CHAP_SUCCESS:	return "success";
4056		case CHAP_FAILURE:	return "failure";
4057		}
4058	case PPP_PAP:
4059		switch (type) {
4060		case PAP_REQ:		return "req";
4061		case PAP_ACK:		return "ack";
4062		case PAP_NAK:		return "nak";
4063		}
4064	}
4065	snprintf (buf, sizeof(buf), "0x%x", type);
4066	return buf;
4067}
4068
4069static const char *
4070sppp_lcp_opt_name(u_char opt)
4071{
4072	static char buf[12];
4073	switch (opt) {
4074	case LCP_OPT_MRU:		return "mru";
4075	case LCP_OPT_ASYNC_MAP:		return "async-map";
4076	case LCP_OPT_AUTH_PROTO:	return "auth-proto";
4077	case LCP_OPT_QUAL_PROTO:	return "qual-proto";
4078	case LCP_OPT_MAGIC:		return "magic";
4079	case LCP_OPT_PROTO_COMP:	return "proto-comp";
4080	case LCP_OPT_ADDR_COMP:		return "addr-comp";
4081	}
4082	snprintf (buf, sizeof(buf), "0x%x", opt);
4083	return buf;
4084}
4085
4086static const char *
4087sppp_ipcp_opt_name(u_char opt)
4088{
4089	static char buf[12];
4090	switch (opt) {
4091	case IPCP_OPT_ADDRESSES:	return "addresses";
4092	case IPCP_OPT_COMPRESSION:	return "compression";
4093	case IPCP_OPT_ADDRESS:		return "address";
4094	}
4095	snprintf (buf, sizeof(buf), "0x%x", opt);
4096	return buf;
4097}
4098
4099static const char *
4100sppp_state_name(int state)
4101{
4102	switch (state) {
4103	case STATE_INITIAL:	return "initial";
4104	case STATE_STARTING:	return "starting";
4105	case STATE_CLOSED:	return "closed";
4106	case STATE_STOPPED:	return "stopped";
4107	case STATE_CLOSING:	return "closing";
4108	case STATE_STOPPING:	return "stopping";
4109	case STATE_REQ_SENT:	return "req-sent";
4110	case STATE_ACK_RCVD:	return "ack-rcvd";
4111	case STATE_ACK_SENT:	return "ack-sent";
4112	case STATE_OPENED:	return "opened";
4113	}
4114	return "illegal";
4115}
4116
4117static const char *
4118sppp_phase_name(enum ppp_phase phase)
4119{
4120	switch (phase) {
4121	case PHASE_DEAD:	return "dead";
4122	case PHASE_ESTABLISH:	return "establish";
4123	case PHASE_TERMINATE:	return "terminate";
4124	case PHASE_AUTHENTICATE: return "authenticate";
4125	case PHASE_NETWORK:	return "network";
4126	}
4127	return "illegal";
4128}
4129
4130static const char *
4131sppp_proto_name(u_short proto)
4132{
4133	static char buf[12];
4134	switch (proto) {
4135	case PPP_LCP:	return "lcp";
4136	case PPP_IPCP:	return "ipcp";
4137	case PPP_PAP:	return "pap";
4138	case PPP_CHAP:	return "chap";
4139	}
4140	snprintf(buf, sizeof(buf), "0x%x", (unsigned)proto);
4141	return buf;
4142}
4143
4144static void
4145sppp_print_bytes(const u_char *p, u_short len)
4146{
4147	addlog(" %02x", *p++);
4148	while (--len > 0)
4149		addlog("-%02x", *p++);
4150}
4151
4152static void
4153sppp_print_string(const char *p, u_short len)
4154{
4155	u_char c;
4156
4157	while (len-- > 0) {
4158		c = *p++;
4159		/*
4160		 * Print only ASCII chars directly.  RFC 1994 recommends
4161		 * using only them, but we don't rely on it.  */
4162		if (c < ' ' || c > '~')
4163			addlog("\\x%x", c);
4164		else
4165			addlog("%c", c);
4166	}
4167}
4168
4169static const char *
4170sppp_dotted_quad(u_long addr)
4171{
4172	static char s[16];
4173	sprintf(s, "%d.%d.%d.%d",
4174		(int)((addr >> 24) & 0xff),
4175		(int)((addr >> 16) & 0xff),
4176		(int)((addr >> 8) & 0xff),
4177		(int)(addr & 0xff));
4178	return s;
4179}
4180
4181static int
4182sppp_strnlen(u_char *p, int max)
4183{
4184	int len;
4185
4186	for (len = 0; len < max && *p; ++p)
4187		++len;
4188	return len;
4189}
4190
4191/* a dummy, used to drop uninteresting events */
4192static void
4193sppp_null(struct sppp *unused)
4194{
4195	/* do just nothing */
4196}
4197/*
4198 * This file is large.  Tell emacs to highlight it nevertheless.
4199 *
4200 * Local Variables:
4201 * hilit-auto-highlight-maxout: 120000
4202 * End:
4203 */
4204