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