if_spppsubr.c revision 88716
166458Sdfr/*
266458Sdfr * Synchronous PPP/Cisco link level subroutines.
366458Sdfr * Keepalive protocol implemented in both Cisco and PPP modes.
4139790Simp *
566458Sdfr * Copyright (C) 1994-1996 Cronyx Engineering Ltd.
666458Sdfr * Author: Serge Vakulenko, <vak@cronyx.ru>
766458Sdfr *
866458Sdfr * Heavily revamped to conform to RFC 1661.
966458Sdfr * Copyright (C) 1997, 2001 Joerg Wunsch.
1066458Sdfr *
1166458Sdfr * This software is distributed with NO WARRANTIES, not even the implied
1266458Sdfr * warranties for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
1366458Sdfr *
1466458Sdfr * Authors grant any other persons or organisations permission to use
1566458Sdfr * or modify this software as long as this message is kept with the software,
1666458Sdfr * all derivative works or modified versions.
1766458Sdfr *
1866458Sdfr * From: Version 2.4, Thu Apr 30 17:17:21 MSD 1997
1966458Sdfr *
2066458Sdfr * $FreeBSD: head/sys/net/if_spppsubr.c 88716 2001-12-30 19:02:27Z joerg $
2166458Sdfr */
2266458Sdfr
2366458Sdfr#include <sys/param.h>
2466458Sdfr
2566458Sdfr#if defined(__FreeBSD__) && __FreeBSD__ >= 3
2666458Sdfr#include "opt_inet.h"
2766458Sdfr#include "opt_inet6.h"
2866458Sdfr#include "opt_ipx.h"
2966458Sdfr#endif
3066458Sdfr
3166458Sdfr#ifdef NetBSD1_3
3266458Sdfr#  if NetBSD1_3 > 6
3366458Sdfr#      include "opt_inet.h"
3466458Sdfr#      include "opt_inet6.h"
3566458Sdfr#      include "opt_iso.h"
3666458Sdfr#  endif
3766458Sdfr#endif
3866458Sdfr
3966458Sdfr#include <sys/systm.h>
4066458Sdfr#include <sys/kernel.h>
4166458Sdfr#include <sys/module.h>
4266458Sdfr#include <sys/sockio.h>
4366458Sdfr#include <sys/socket.h>
4466458Sdfr#include <sys/syslog.h>
4566458Sdfr#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4666458Sdfr#include <sys/random.h>
4766458Sdfr#endif
4866458Sdfr#include <sys/malloc.h>
4966458Sdfr#include <sys/mbuf.h>
5066458Sdfr
5166458Sdfr#if defined (__OpenBSD__)
5266458Sdfr#include <sys/md5k.h>
5366458Sdfr#else
5466458Sdfr#include <sys/md5.h>
5566458Sdfr#endif
5666458Sdfr
5766458Sdfr#include <net/if.h>
5866458Sdfr#include <net/netisr.h>
5966458Sdfr#include <net/if_types.h>
6066458Sdfr#include <net/route.h>
6166458Sdfr#include <netinet/in.h>
6266458Sdfr#include <netinet/in_systm.h>
6366458Sdfr#include <netinet/ip.h>
6466458Sdfr#include <net/slcompress.h>
6566458Sdfr
6666458Sdfr#if defined (__NetBSD__) || defined (__OpenBSD__)
6766458Sdfr#include <machine/cpu.h> /* XXX for softnet */
6866458Sdfr#endif
6966458Sdfr
7066458Sdfr#include <machine/stdarg.h>
7166458Sdfr
7266458Sdfr#include <netinet/in.h>
7366458Sdfr#include <netinet/in_systm.h>
7466458Sdfr#include <netinet/in_var.h>
7566458Sdfr
7666458Sdfr#ifdef INET
7766458Sdfr#include <netinet/ip.h>
7866458Sdfr#include <netinet/tcp.h>
7966458Sdfr#endif
8066458Sdfr
8166458Sdfr#if defined (__FreeBSD__) || defined (__OpenBSD__)
8266458Sdfr# include <netinet/if_ether.h>
8366458Sdfr#else
8466458Sdfr# include <net/ethertypes.h>
8566458Sdfr#endif
8666458Sdfr
8766458Sdfr#ifdef IPX
8866458Sdfr#include <netipx/ipx.h>
8966458Sdfr#include <netipx/ipx_if.h>
9066458Sdfr#endif
9166458Sdfr
9266458Sdfr#ifdef NS
9366458Sdfr#include <netns/ns.h>
9466458Sdfr#include <netns/ns_if.h>
9566458Sdfr#endif
9666458Sdfr
9766458Sdfr#include <net/if_sppp.h>
9866458Sdfr
9966458Sdfr#if defined(__FreeBSD__) && __FreeBSD__ >= 3
10066458Sdfr# define UNTIMEOUT(fun, arg, handle) untimeout(fun, arg, handle)
10166458Sdfr# define TIMEOUT(fun, arg1, arg2, handle) handle = timeout(fun, arg1, arg2)
10266458Sdfr# define IOCTL_CMD_T	u_long
10366458Sdfr#else
10466458Sdfr# define UNTIMEOUT(fun, arg, handle) untimeout(fun, arg)
10566458Sdfr# define TIMEOUT(fun, arg1, arg2, handle) timeout(fun, arg1, arg2)
10666458Sdfr# define IOCTL_CMD_T	int
10766458Sdfr#endif
10866458Sdfr
10966458Sdfr#define MAXALIVECNT     3               /* max. alive packets */
11066458Sdfr
11166458Sdfr/*
11266458Sdfr * Interface flags that can be set in an ifconfig command.
11366458Sdfr *
11466458Sdfr * Setting link0 will make the link passive, i.e. it will be marked
11566458Sdfr * as being administrative openable, but won't be opened to begin
116 * with.  Incoming calls will be answered, or subsequent calls with
117 * -link1 will cause the administrative open of the LCP layer.
118 *
119 * Setting link1 will cause the link to auto-dial only as packets
120 * arrive to be sent.
121 *
122 * Setting IFF_DEBUG will syslog the option negotiation and state
123 * transitions at level kern.debug.  Note: all logs consistently look
124 * like
125 *
126 *   <if-name><unit>: <proto-name> <additional info...>
127 *
128 * with <if-name><unit> being something like "bppp0", and <proto-name>
129 * being one of "lcp", "ipcp", "cisco", "chap", "pap", etc.
130 */
131
132#define IFF_PASSIVE	IFF_LINK0	/* wait passively for connection */
133#define IFF_AUTO	IFF_LINK1	/* auto-dial on output */
134#define IFF_CISCO	IFF_LINK2	/* auto-dial on output */
135
136#define PPP_ALLSTATIONS 0xff		/* All-Stations broadcast address */
137#define PPP_UI		0x03		/* Unnumbered Information */
138#define PPP_IP		0x0021		/* Internet Protocol */
139#define PPP_ISO		0x0023		/* ISO OSI Protocol */
140#define PPP_XNS		0x0025		/* Xerox NS Protocol */
141#define PPP_IPX		0x002b		/* Novell IPX Protocol */
142#define PPP_VJ_COMP	0x002d		/* VJ compressed TCP/IP */
143#define PPP_VJ_UCOMP	0x002f		/* VJ uncompressed TCP/IP */
144#define PPP_IPV6	0x0057		/* Internet Protocol Version 6 */
145#define PPP_LCP		0xc021		/* Link Control Protocol */
146#define PPP_PAP		0xc023		/* Password Authentication Protocol */
147#define PPP_CHAP	0xc223		/* Challenge-Handshake Auth Protocol */
148#define PPP_IPCP	0x8021		/* Internet Protocol Control Protocol */
149#define PPP_IPV6CP	0x8057		/* IPv6 Control Protocol */
150
151#define CONF_REQ	1		/* PPP configure request */
152#define CONF_ACK	2		/* PPP configure acknowledge */
153#define CONF_NAK	3		/* PPP configure negative ack */
154#define CONF_REJ	4		/* PPP configure reject */
155#define TERM_REQ	5		/* PPP terminate request */
156#define TERM_ACK	6		/* PPP terminate acknowledge */
157#define CODE_REJ	7		/* PPP code reject */
158#define PROTO_REJ	8		/* PPP protocol reject */
159#define ECHO_REQ	9		/* PPP echo request */
160#define ECHO_REPLY	10		/* PPP echo reply */
161#define DISC_REQ	11		/* PPP discard request */
162
163#define LCP_OPT_MRU		1	/* maximum receive unit */
164#define LCP_OPT_ASYNC_MAP	2	/* async control character map */
165#define LCP_OPT_AUTH_PROTO	3	/* authentication protocol */
166#define LCP_OPT_QUAL_PROTO	4	/* quality protocol */
167#define LCP_OPT_MAGIC		5	/* magic number */
168#define LCP_OPT_RESERVED	6	/* reserved */
169#define LCP_OPT_PROTO_COMP	7	/* protocol field compression */
170#define LCP_OPT_ADDR_COMP	8	/* address/control field compression */
171
172#define IPCP_OPT_ADDRESSES	1	/* both IP addresses; deprecated */
173#define IPCP_OPT_COMPRESSION	2	/* IP compression protocol (VJ) */
174#define IPCP_OPT_ADDRESS	3	/* local IP address */
175
176#define IPV6CP_OPT_IFID	1	/* interface identifier */
177#define IPV6CP_OPT_COMPRESSION	2	/* IPv6 compression protocol */
178
179#define IPCP_COMP_VJ		0x2d	/* Code for VJ compression */
180
181#define PAP_REQ			1	/* PAP name/password request */
182#define PAP_ACK			2	/* PAP acknowledge */
183#define PAP_NAK			3	/* PAP fail */
184
185#define CHAP_CHALLENGE		1	/* CHAP challenge request */
186#define CHAP_RESPONSE		2	/* CHAP challenge response */
187#define CHAP_SUCCESS		3	/* CHAP response ok */
188#define CHAP_FAILURE		4	/* CHAP response failed */
189
190#define CHAP_MD5		5	/* hash algorithm - MD5 */
191
192#define CISCO_MULTICAST		0x8f	/* Cisco multicast address */
193#define CISCO_UNICAST		0x0f	/* Cisco unicast address */
194#define CISCO_KEEPALIVE		0x8035	/* Cisco keepalive protocol */
195#define CISCO_ADDR_REQ		0	/* Cisco address request */
196#define CISCO_ADDR_REPLY	1	/* Cisco address reply */
197#define CISCO_KEEPALIVE_REQ	2	/* Cisco keepalive request */
198
199/* states are named and numbered according to RFC 1661 */
200#define STATE_INITIAL	0
201#define STATE_STARTING	1
202#define STATE_CLOSED	2
203#define STATE_STOPPED	3
204#define STATE_CLOSING	4
205#define STATE_STOPPING	5
206#define STATE_REQ_SENT	6
207#define STATE_ACK_RCVD	7
208#define STATE_ACK_SENT	8
209#define STATE_OPENED	9
210
211struct ppp_header {
212	u_char address;
213	u_char control;
214	u_short protocol;
215} __attribute__((__packed__));
216#define PPP_HEADER_LEN          sizeof (struct ppp_header)
217
218struct lcp_header {
219	u_char type;
220	u_char ident;
221	u_short len;
222} __attribute__((__packed__));
223#define LCP_HEADER_LEN          sizeof (struct lcp_header)
224
225struct cisco_packet {
226	u_long type;
227	u_long par1;
228	u_long par2;
229	u_short rel;
230	u_short time0;
231	u_short time1;
232} __attribute__((__packed__));
233#define CISCO_PACKET_LEN	sizeof (struct cisco_packet)
234
235/*
236 * We follow the spelling and capitalization of RFC 1661 here, to make
237 * it easier comparing with the standard.  Please refer to this RFC in
238 * case you can't make sense out of these abbreviation; it will also
239 * explain the semantics related to the various events and actions.
240 */
241struct cp {
242	u_short	proto;		/* PPP control protocol number */
243	u_char protoidx;	/* index into state table in struct sppp */
244	u_char flags;
245#define CP_LCP		0x01	/* this is the LCP */
246#define CP_AUTH		0x02	/* this is an authentication protocol */
247#define CP_NCP		0x04	/* this is a NCP */
248#define CP_QUAL		0x08	/* this is a quality reporting protocol */
249	const char *name;	/* name of this control protocol */
250	/* event handlers */
251	void	(*Up)(struct sppp *sp);
252	void	(*Down)(struct sppp *sp);
253	void	(*Open)(struct sppp *sp);
254	void	(*Close)(struct sppp *sp);
255	void	(*TO)(void *sp);
256	int	(*RCR)(struct sppp *sp, struct lcp_header *h, int len);
257	void	(*RCN_rej)(struct sppp *sp, struct lcp_header *h, int len);
258	void	(*RCN_nak)(struct sppp *sp, struct lcp_header *h, int len);
259	/* actions */
260	void	(*tlu)(struct sppp *sp);
261	void	(*tld)(struct sppp *sp);
262	void	(*tls)(struct sppp *sp);
263	void	(*tlf)(struct sppp *sp);
264	void	(*scr)(struct sppp *sp);
265};
266
267static struct sppp *spppq;
268#if defined(__FreeBSD__) && __FreeBSD__ >= 3
269static struct callout_handle keepalive_ch;
270#endif
271
272#if defined(__FreeBSD__) && __FreeBSD__ >= 3
273#define	SPP_FMT		"%s%d: "
274#define	SPP_ARGS(ifp)	(ifp)->if_name, (ifp)->if_unit
275#else
276#define	SPP_FMT		"%s: "
277#define	SPP_ARGS(ifp)	(ifp)->if_xname
278#endif
279
280#ifdef INET
281/*
282 * The following disgusting hack gets around the problem that IP TOS
283 * can't be set yet.  We want to put "interactive" traffic on a high
284 * priority queue.  To decide if traffic is interactive, we check that
285 * a) it is TCP and b) one of its ports is telnet, rlogin or ftp control.
286 *
287 * XXX is this really still necessary?  - joerg -
288 */
289static u_short interactive_ports[8] = {
290	0,	513,	0,	0,
291	0,	21,	0,	23,
292};
293#define INTERACTIVE(p) (interactive_ports[(p) & 7] == (p))
294#endif
295
296/* almost every function needs these */
297#define STDDCL							\
298	struct ifnet *ifp = &sp->pp_if;				\
299	int debug = ifp->if_flags & IFF_DEBUG
300
301static int sppp_output(struct ifnet *ifp, struct mbuf *m,
302		       struct sockaddr *dst, struct rtentry *rt);
303
304static void sppp_cisco_send(struct sppp *sp, int type, long par1, long par2);
305static void sppp_cisco_input(struct sppp *sp, struct mbuf *m);
306
307static void sppp_cp_input(const struct cp *cp, struct sppp *sp,
308			  struct mbuf *m);
309static void sppp_cp_send(struct sppp *sp, u_short proto, u_char type,
310			 u_char ident, u_short len, void *data);
311/* static void sppp_cp_timeout(void *arg); */
312static void sppp_cp_change_state(const struct cp *cp, struct sppp *sp,
313				 int newstate);
314static void sppp_auth_send(const struct cp *cp,
315			   struct sppp *sp, unsigned int type, unsigned int id,
316			   ...);
317
318static void sppp_up_event(const struct cp *cp, struct sppp *sp);
319static void sppp_down_event(const struct cp *cp, struct sppp *sp);
320static void sppp_open_event(const struct cp *cp, struct sppp *sp);
321static void sppp_close_event(const struct cp *cp, struct sppp *sp);
322static void sppp_to_event(const struct cp *cp, struct sppp *sp);
323
324static void sppp_null(struct sppp *sp);
325
326static void sppp_lcp_init(struct sppp *sp);
327static void sppp_lcp_up(struct sppp *sp);
328static void sppp_lcp_down(struct sppp *sp);
329static void sppp_lcp_open(struct sppp *sp);
330static void sppp_lcp_close(struct sppp *sp);
331static void sppp_lcp_TO(void *sp);
332static int sppp_lcp_RCR(struct sppp *sp, struct lcp_header *h, int len);
333static void sppp_lcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len);
334static void sppp_lcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len);
335static void sppp_lcp_tlu(struct sppp *sp);
336static void sppp_lcp_tld(struct sppp *sp);
337static void sppp_lcp_tls(struct sppp *sp);
338static void sppp_lcp_tlf(struct sppp *sp);
339static void sppp_lcp_scr(struct sppp *sp);
340static void sppp_lcp_check_and_close(struct sppp *sp);
341static int sppp_ncp_check(struct sppp *sp);
342
343static void sppp_ipcp_init(struct sppp *sp);
344static void sppp_ipcp_up(struct sppp *sp);
345static void sppp_ipcp_down(struct sppp *sp);
346static void sppp_ipcp_open(struct sppp *sp);
347static void sppp_ipcp_close(struct sppp *sp);
348static void sppp_ipcp_TO(void *sp);
349static int sppp_ipcp_RCR(struct sppp *sp, struct lcp_header *h, int len);
350static void sppp_ipcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len);
351static void sppp_ipcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len);
352static void sppp_ipcp_tlu(struct sppp *sp);
353static void sppp_ipcp_tld(struct sppp *sp);
354static void sppp_ipcp_tls(struct sppp *sp);
355static void sppp_ipcp_tlf(struct sppp *sp);
356static void sppp_ipcp_scr(struct sppp *sp);
357
358static void sppp_ipv6cp_init(struct sppp *sp);
359static void sppp_ipv6cp_up(struct sppp *sp);
360static void sppp_ipv6cp_down(struct sppp *sp);
361static void sppp_ipv6cp_open(struct sppp *sp);
362static void sppp_ipv6cp_close(struct sppp *sp);
363static void sppp_ipv6cp_TO(void *sp);
364static int sppp_ipv6cp_RCR(struct sppp *sp, struct lcp_header *h, int len);
365static void sppp_ipv6cp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len);
366static void sppp_ipv6cp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len);
367static void sppp_ipv6cp_tlu(struct sppp *sp);
368static void sppp_ipv6cp_tld(struct sppp *sp);
369static void sppp_ipv6cp_tls(struct sppp *sp);
370static void sppp_ipv6cp_tlf(struct sppp *sp);
371static void sppp_ipv6cp_scr(struct sppp *sp);
372
373static void sppp_pap_input(struct sppp *sp, struct mbuf *m);
374static void sppp_pap_init(struct sppp *sp);
375static void sppp_pap_open(struct sppp *sp);
376static void sppp_pap_close(struct sppp *sp);
377static void sppp_pap_TO(void *sp);
378static void sppp_pap_my_TO(void *sp);
379static void sppp_pap_tlu(struct sppp *sp);
380static void sppp_pap_tld(struct sppp *sp);
381static void sppp_pap_scr(struct sppp *sp);
382
383static void sppp_chap_input(struct sppp *sp, struct mbuf *m);
384static void sppp_chap_init(struct sppp *sp);
385static void sppp_chap_open(struct sppp *sp);
386static void sppp_chap_close(struct sppp *sp);
387static void sppp_chap_TO(void *sp);
388static void sppp_chap_tlu(struct sppp *sp);
389static void sppp_chap_tld(struct sppp *sp);
390static void sppp_chap_scr(struct sppp *sp);
391
392static const char *sppp_auth_type_name(u_short proto, u_char type);
393static const char *sppp_cp_type_name(u_char type);
394static const char *sppp_dotted_quad(u_long addr);
395static const char *sppp_ipcp_opt_name(u_char opt);
396#ifdef INET6
397static const char *sppp_ipv6cp_opt_name(u_char opt);
398#endif
399static const char *sppp_lcp_opt_name(u_char opt);
400static const char *sppp_phase_name(enum ppp_phase phase);
401static const char *sppp_proto_name(u_short proto);
402static const char *sppp_state_name(int state);
403static int sppp_params(struct sppp *sp, u_long cmd, void *data);
404static int sppp_strnlen(u_char *p, int max);
405static void sppp_get_ip_addrs(struct sppp *sp, u_long *src, u_long *dst,
406			      u_long *srcmask);
407static void sppp_keepalive(void *dummy);
408static void sppp_phase_network(struct sppp *sp);
409static void sppp_print_bytes(const u_char *p, u_short len);
410static void sppp_print_string(const char *p, u_short len);
411static void sppp_qflush(struct ifqueue *ifq);
412static void sppp_set_ip_addr(struct sppp *sp, u_long src);
413#ifdef INET6
414static void sppp_get_ip6_addrs(struct sppp *sp, struct in6_addr *src,
415			       struct in6_addr *dst, struct in6_addr *srcmask);
416#ifdef IPV6CP_MYIFID_DYN
417static void sppp_set_ip6_addr(struct sppp *sp, const struct in6_addr *src);
418static void sppp_gen_ip6_addr(struct sppp *sp, const struct in6_addr *src);
419#endif
420static void sppp_suggest_ip6_addr(struct sppp *sp, struct in6_addr *src);
421#endif
422
423/* our control protocol descriptors */
424static const struct cp lcp = {
425	PPP_LCP, IDX_LCP, CP_LCP, "lcp",
426	sppp_lcp_up, sppp_lcp_down, sppp_lcp_open, sppp_lcp_close,
427	sppp_lcp_TO, sppp_lcp_RCR, sppp_lcp_RCN_rej, sppp_lcp_RCN_nak,
428	sppp_lcp_tlu, sppp_lcp_tld, sppp_lcp_tls, sppp_lcp_tlf,
429	sppp_lcp_scr
430};
431
432static const struct cp ipcp = {
433	PPP_IPCP, IDX_IPCP,
434#ifdef INET	/* don't run IPCP if there's no IPv4 support */
435	CP_NCP,
436#else
437	0,
438#endif
439	"ipcp",
440	sppp_ipcp_up, sppp_ipcp_down, sppp_ipcp_open, sppp_ipcp_close,
441	sppp_ipcp_TO, sppp_ipcp_RCR, sppp_ipcp_RCN_rej, sppp_ipcp_RCN_nak,
442	sppp_ipcp_tlu, sppp_ipcp_tld, sppp_ipcp_tls, sppp_ipcp_tlf,
443	sppp_ipcp_scr
444};
445
446static const struct cp ipv6cp = {
447	PPP_IPV6CP, IDX_IPV6CP,
448#ifdef INET6	/*don't run IPv6CP if there's no IPv6 support*/
449	CP_NCP,
450#else
451	0,
452#endif
453	"ipv6cp",
454	sppp_ipv6cp_up, sppp_ipv6cp_down, sppp_ipv6cp_open, sppp_ipv6cp_close,
455	sppp_ipv6cp_TO, sppp_ipv6cp_RCR, sppp_ipv6cp_RCN_rej, sppp_ipv6cp_RCN_nak,
456	sppp_ipv6cp_tlu, sppp_ipv6cp_tld, sppp_ipv6cp_tls, sppp_ipv6cp_tlf,
457	sppp_ipv6cp_scr
458};
459
460static const struct cp pap = {
461	PPP_PAP, IDX_PAP, CP_AUTH, "pap",
462	sppp_null, sppp_null, sppp_pap_open, sppp_pap_close,
463	sppp_pap_TO, 0, 0, 0,
464	sppp_pap_tlu, sppp_pap_tld, sppp_null, sppp_null,
465	sppp_pap_scr
466};
467
468static const struct cp chap = {
469	PPP_CHAP, IDX_CHAP, CP_AUTH, "chap",
470	sppp_null, sppp_null, sppp_chap_open, sppp_chap_close,
471	sppp_chap_TO, 0, 0, 0,
472	sppp_chap_tlu, sppp_chap_tld, sppp_null, sppp_null,
473	sppp_chap_scr
474};
475
476static const struct cp *cps[IDX_COUNT] = {
477	&lcp,			/* IDX_LCP */
478	&ipcp,			/* IDX_IPCP */
479	&ipv6cp,		/* IDX_IPV6CP */
480	&pap,			/* IDX_PAP */
481	&chap,			/* IDX_CHAP */
482};
483
484static int
485sppp_modevent(module_t mod, int type, void *unused)
486{
487	switch (type) {
488	case MOD_LOAD:
489		break;
490	case MOD_UNLOAD:
491		return EACCES;
492		break;
493	default:
494		break;
495	}
496	return 0;
497}
498static moduledata_t spppmod = {
499	"sppp",
500	sppp_modevent,
501	0
502};
503MODULE_VERSION(sppp, 1);
504DECLARE_MODULE(sppp, spppmod, SI_SUB_DRIVERS, SI_ORDER_ANY);
505
506/*
507 * Exported functions, comprising our interface to the lower layer.
508 */
509
510/*
511 * Process the received packet.
512 */
513void
514sppp_input(struct ifnet *ifp, struct mbuf *m)
515{
516	struct ppp_header *h;
517	struct ifqueue *inq = 0;
518	struct sppp *sp = (struct sppp *)ifp;
519	u_char *iphdr;
520	int hlen, vjlen, do_account = 0;
521	int debug = ifp->if_flags & IFF_DEBUG;
522
523	if (ifp->if_flags & IFF_UP)
524		/* Count received bytes, add FCS and one flag */
525		ifp->if_ibytes += m->m_pkthdr.len + 3;
526
527	if (m->m_pkthdr.len <= PPP_HEADER_LEN) {
528		/* Too small packet, drop it. */
529		if (debug)
530			log(LOG_DEBUG,
531			    SPP_FMT "input packet is too small, %d bytes\n",
532			    SPP_ARGS(ifp), m->m_pkthdr.len);
533	  drop:
534		m_freem (m);
535	  drop2:
536		++ifp->if_ierrors;
537		++ifp->if_iqdrops;
538		return;
539	}
540
541	/* Get PPP header. */
542	h = mtod (m, struct ppp_header*);
543	m_adj (m, PPP_HEADER_LEN);
544
545	switch (h->address) {
546	case PPP_ALLSTATIONS:
547		if (h->control != PPP_UI)
548			goto invalid;
549		if (sp->pp_mode == IFF_CISCO) {
550			if (debug)
551				log(LOG_DEBUG,
552				    SPP_FMT "PPP packet in Cisco mode "
553				    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
554				    SPP_ARGS(ifp),
555				    h->address, h->control, ntohs(h->protocol));
556			goto drop;
557		}
558		switch (ntohs (h->protocol)) {
559		default:
560			if (debug)
561				log(LOG_DEBUG,
562				    SPP_FMT "rejecting protocol "
563				    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
564				    SPP_ARGS(ifp),
565				    h->address, h->control, ntohs(h->protocol));
566			if (sp->state[IDX_LCP] == STATE_OPENED)
567				sppp_cp_send (sp, PPP_LCP, PROTO_REJ,
568					++sp->pp_seq[IDX_LCP], m->m_pkthdr.len + 2,
569					&h->protocol);
570			++ifp->if_noproto;
571			goto drop;
572		case PPP_LCP:
573			sppp_cp_input(&lcp, sp, m);
574			m_freem (m);
575			return;
576		case PPP_PAP:
577			if (sp->pp_phase >= PHASE_AUTHENTICATE)
578				sppp_pap_input(sp, m);
579			m_freem (m);
580			return;
581		case PPP_CHAP:
582			if (sp->pp_phase >= PHASE_AUTHENTICATE)
583				sppp_chap_input(sp, m);
584			m_freem (m);
585			return;
586#ifdef INET
587		case PPP_IPCP:
588			if (sp->pp_phase == PHASE_NETWORK)
589				sppp_cp_input(&ipcp, sp, m);
590			m_freem (m);
591			return;
592		case PPP_IP:
593			if (sp->state[IDX_IPCP] == STATE_OPENED) {
594				schednetisr (NETISR_IP);
595				inq = &ipintrq;
596			}
597			do_account++;
598			break;
599		case PPP_VJ_COMP:
600			if (sp->state[IDX_IPCP] == STATE_OPENED) {
601				if ((vjlen =
602				     sl_uncompress_tcp_core(mtod(m, u_char *),
603							    m->m_len, m->m_len,
604							    TYPE_COMPRESSED_TCP,
605							    sp->pp_comp,
606							    &iphdr, &hlen)) <= 0) {
607					if (debug)
608						log(LOG_INFO,
609			    SPP_FMT "VJ uncompress failed on compressed packet\n",
610						    SPP_ARGS(ifp));
611					goto drop;
612				}
613
614				/*
615				 * Trim the VJ header off the packet, and prepend
616				 * the uncompressed IP header (which will usually
617				 * end up in two chained mbufs since there's not
618				 * enough leading space in the existing mbuf).
619				 */
620				m_adj(m, vjlen);
621				M_PREPEND(m, hlen, M_DONTWAIT);
622				if (m == NULL)
623					goto drop2;
624				bcopy(iphdr, mtod(m, u_char *), hlen);
625
626				schednetisr (NETISR_IP);
627				inq = &ipintrq;
628			}
629			do_account++;
630			break;
631		case PPP_VJ_UCOMP:
632			if (sp->state[IDX_IPCP] == STATE_OPENED) {
633				if (sl_uncompress_tcp_core(mtod(m, u_char *),
634							   m->m_len, m->m_len,
635							   TYPE_UNCOMPRESSED_TCP,
636							   sp->pp_comp,
637							   &iphdr, &hlen) != 0) {
638					if (debug)
639						log(LOG_INFO,
640			    SPP_FMT "VJ uncompress failed on uncompressed packet\n",
641						    SPP_ARGS(ifp));
642					goto drop;
643				}
644				schednetisr (NETISR_IP);
645				inq = &ipintrq;
646			}
647			do_account++;
648			break;
649#endif
650#ifdef INET6
651		case PPP_IPV6CP:
652			if (sp->pp_phase == PHASE_NETWORK)
653			    sppp_cp_input(&ipv6cp, sp, m);
654			m_freem (m);
655			return;
656
657		case PPP_IPV6:
658			if (sp->state[IDX_IPV6CP] == STATE_OPENED) {
659				schednetisr (NETISR_IPV6);
660				inq = &ip6intrq;
661			}
662			do_account++;
663			break;
664#endif
665#ifdef IPX
666		case PPP_IPX:
667			/* IPX IPXCP not implemented yet */
668			if (sp->pp_phase == PHASE_NETWORK) {
669				schednetisr (NETISR_IPX);
670				inq = &ipxintrq;
671			}
672			do_account++;
673			break;
674#endif
675#ifdef NS
676		case PPP_XNS:
677			/* XNS IDPCP not implemented yet */
678			if (sp->pp_phase == PHASE_NETWORK) {
679				schednetisr (NETISR_NS);
680				inq = &nsintrq;
681			}
682			do_account++;
683			break;
684#endif
685		}
686		break;
687	case CISCO_MULTICAST:
688	case CISCO_UNICAST:
689		/* Don't check the control field here (RFC 1547). */
690		if (sp->pp_mode != IFF_CISCO) {
691			if (debug)
692				log(LOG_DEBUG,
693				    SPP_FMT "Cisco packet in PPP mode "
694				    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
695				    SPP_ARGS(ifp),
696				    h->address, h->control, ntohs(h->protocol));
697			goto drop;
698		}
699		switch (ntohs (h->protocol)) {
700		default:
701			++ifp->if_noproto;
702			goto invalid;
703		case CISCO_KEEPALIVE:
704			sppp_cisco_input ((struct sppp*) ifp, m);
705			m_freem (m);
706			return;
707#ifdef INET
708		case ETHERTYPE_IP:
709			schednetisr (NETISR_IP);
710			inq = &ipintrq;
711			do_account++;
712			break;
713#endif
714#ifdef INET6
715		case ETHERTYPE_IPV6:
716			schednetisr (NETISR_IPV6);
717			inq = &ip6intrq;
718			do_account++;
719			break;
720#endif
721#ifdef IPX
722		case ETHERTYPE_IPX:
723			schednetisr (NETISR_IPX);
724			inq = &ipxintrq;
725			do_account++;
726			break;
727#endif
728#ifdef NS
729		case ETHERTYPE_NS:
730			schednetisr (NETISR_NS);
731			inq = &nsintrq;
732			do_account++;
733			break;
734#endif
735		}
736		break;
737	default:        /* Invalid PPP packet. */
738	  invalid:
739		if (debug)
740			log(LOG_DEBUG,
741			    SPP_FMT "invalid input packet "
742			    "<addr=0x%x ctrl=0x%x proto=0x%x>\n",
743			    SPP_ARGS(ifp),
744			    h->address, h->control, ntohs(h->protocol));
745		goto drop;
746	}
747
748	if (! (ifp->if_flags & IFF_UP) || ! inq)
749		goto drop;
750
751	/* Check queue. */
752	if (! IF_HANDOFF(inq, m, NULL)) {
753		if (debug)
754			log(LOG_DEBUG, SPP_FMT "protocol queue overflow\n",
755				SPP_ARGS(ifp));
756		goto drop;
757	}
758	if (do_account)
759		/*
760		 * Do only account for network packets, not for control
761		 * packets.  This is used by some subsystems to detect
762		 * idle lines.
763		 */
764		sp->pp_last_recv = time_second;
765}
766
767/*
768 * Enqueue transmit packet.
769 */
770static int
771sppp_output(struct ifnet *ifp, struct mbuf *m,
772	    struct sockaddr *dst, struct rtentry *rt)
773{
774	struct sppp *sp = (struct sppp*) ifp;
775	struct ppp_header *h;
776	struct ifqueue *ifq = NULL;
777	int s, rv = 0;
778	int ipproto = PPP_IP;
779	int debug = ifp->if_flags & IFF_DEBUG;
780
781	s = splimp();
782
783	if ((ifp->if_flags & IFF_UP) == 0 ||
784	    (ifp->if_flags & (IFF_RUNNING | IFF_AUTO)) == 0) {
785		m_freem (m);
786		splx (s);
787		return (ENETDOWN);
788	}
789
790	if ((ifp->if_flags & (IFF_RUNNING | IFF_AUTO)) == IFF_AUTO) {
791		/*
792		 * Interface is not yet running, but auto-dial.  Need
793		 * to start LCP for it.
794		 */
795		ifp->if_flags |= IFF_RUNNING;
796		splx(s);
797		lcp.Open(sp);
798		s = splimp();
799	}
800
801	ifq = &ifp->if_snd;
802#ifdef INET
803	if (dst->sa_family == AF_INET) {
804		/* XXX Check mbuf length here? */
805		struct ip *ip = mtod (m, struct ip*);
806		struct tcphdr *tcp = (struct tcphdr*) ((long*)ip + ip->ip_hl);
807
808		/*
809		 * When using dynamic local IP address assignment by using
810		 * 0.0.0.0 as a local address, the first TCP session will
811		 * not connect because the local TCP checksum is computed
812		 * using 0.0.0.0 which will later become our real IP address
813		 * so the TCP checksum computed at the remote end will
814		 * become invalid. So we
815		 * - don't let packets with src ip addr 0 thru
816		 * - we flag TCP packets with src ip 0 as an error
817		 */
818
819		if(ip->ip_src.s_addr == INADDR_ANY)	/* -hm */
820		{
821			m_freem(m);
822			splx(s);
823			if(ip->ip_p == IPPROTO_TCP)
824				return(EADDRNOTAVAIL);
825			else
826				return(0);
827		}
828
829		/*
830		 * Put low delay, telnet, rlogin and ftp control packets
831		 * in front of the queue.
832		 */
833		if (_IF_QFULL(&sp->pp_fastq))
834			;
835		else if (ip->ip_tos & IPTOS_LOWDELAY)
836			ifq = &sp->pp_fastq;
837		else if (m->m_len < sizeof *ip + sizeof *tcp)
838			;
839		else if (ip->ip_p != IPPROTO_TCP)
840			;
841		else if (INTERACTIVE (ntohs (tcp->th_sport)))
842			ifq = &sp->pp_fastq;
843		else if (INTERACTIVE (ntohs (tcp->th_dport)))
844			ifq = &sp->pp_fastq;
845
846		/*
847		 * Do IP Header compression
848		 */
849		if (sp->pp_mode != IFF_CISCO && (sp->ipcp.flags & IPCP_VJ) &&
850		    ip->ip_p == IPPROTO_TCP)
851			switch (sl_compress_tcp(m, ip, sp->pp_comp,
852						sp->ipcp.compress_cid)) {
853			case TYPE_COMPRESSED_TCP:
854				ipproto = PPP_VJ_COMP;
855				break;
856			case TYPE_UNCOMPRESSED_TCP:
857				ipproto = PPP_VJ_UCOMP;
858				break;
859			case TYPE_IP:
860				ipproto = PPP_IP;
861				break;
862			default:
863				m_freem(m);
864				splx(s);
865				return (EINVAL);
866			}
867	}
868#endif
869
870#ifdef INET6
871	if (dst->sa_family == AF_INET6) {
872		/* XXX do something tricky here? */
873	}
874#endif
875
876	/*
877	 * Prepend general data packet PPP header. For now, IP only.
878	 */
879	M_PREPEND (m, PPP_HEADER_LEN, M_DONTWAIT);
880	if (! m) {
881		if (debug)
882			log(LOG_DEBUG, SPP_FMT "no memory for transmit header\n",
883				SPP_ARGS(ifp));
884		++ifp->if_oerrors;
885		splx (s);
886		return (ENOBUFS);
887	}
888	/*
889	 * May want to check size of packet
890	 * (albeit due to the implementation it's always enough)
891	 */
892	h = mtod (m, struct ppp_header*);
893	if (sp->pp_mode == IFF_CISCO) {
894		h->address = CISCO_UNICAST;        /* unicast address */
895		h->control = 0;
896	} else {
897		h->address = PPP_ALLSTATIONS;        /* broadcast address */
898		h->control = PPP_UI;                 /* Unnumbered Info */
899	}
900
901	switch (dst->sa_family) {
902#ifdef INET
903	case AF_INET:   /* Internet Protocol */
904		if (sp->pp_mode == IFF_CISCO)
905			h->protocol = htons (ETHERTYPE_IP);
906		else {
907			/*
908			 * Don't choke with an ENETDOWN early.  It's
909			 * possible that we just started dialing out,
910			 * so don't drop the packet immediately.  If
911			 * we notice that we run out of buffer space
912			 * below, we will however remember that we are
913			 * not ready to carry IP packets, and return
914			 * ENETDOWN, as opposed to ENOBUFS.
915			 */
916			h->protocol = htons(ipproto);
917			if (sp->state[IDX_IPCP] != STATE_OPENED)
918				rv = ENETDOWN;
919		}
920		break;
921#endif
922#ifdef INET6
923	case AF_INET6:   /* Internet Protocol */
924		if (sp->pp_mode == IFF_CISCO)
925			h->protocol = htons (ETHERTYPE_IPV6);
926		else {
927			/*
928			 * Don't choke with an ENETDOWN early.  It's
929			 * possible that we just started dialing out,
930			 * so don't drop the packet immediately.  If
931			 * we notice that we run out of buffer space
932			 * below, we will however remember that we are
933			 * not ready to carry IP packets, and return
934			 * ENETDOWN, as opposed to ENOBUFS.
935			 */
936			h->protocol = htons(PPP_IPV6);
937			if (sp->state[IDX_IPV6CP] != STATE_OPENED)
938				rv = ENETDOWN;
939		}
940		break;
941#endif
942#ifdef NS
943	case AF_NS:     /* Xerox NS Protocol */
944		h->protocol = htons (sp->pp_mode == IFF_CISCO ?
945			ETHERTYPE_NS : PPP_XNS);
946		break;
947#endif
948#ifdef IPX
949	case AF_IPX:     /* Novell IPX Protocol */
950		h->protocol = htons (sp->pp_mode == IFF_CISCO ?
951			ETHERTYPE_IPX : PPP_IPX);
952		break;
953#endif
954	default:
955		m_freem (m);
956		++ifp->if_oerrors;
957		splx (s);
958		return (EAFNOSUPPORT);
959	}
960
961	/*
962	 * Queue message on interface, and start output if interface
963	 * not yet active.
964	 */
965	if (! IF_HANDOFF_ADJ(ifq, m, ifp, 3)) {
966		++ifp->if_oerrors;
967		return (rv? rv: ENOBUFS);
968	}
969	/*
970	 * Unlike in sppp_input(), we can always bump the timestamp
971	 * here since sppp_output() is only called on behalf of
972	 * network-layer traffic; control-layer traffic is handled
973	 * by sppp_cp_send().
974	 */
975	sp->pp_last_sent = time_second;
976	return (0);
977}
978
979void
980sppp_attach(struct ifnet *ifp)
981{
982	struct sppp *sp = (struct sppp*) ifp;
983
984	/* Initialize keepalive handler. */
985	if (! spppq)
986		TIMEOUT(sppp_keepalive, 0, hz * 10, keepalive_ch);
987
988	/* Insert new entry into the keepalive list. */
989	sp->pp_next = spppq;
990	spppq = sp;
991
992	sp->pp_if.if_mtu = PP_MTU;
993	sp->pp_if.if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
994	sp->pp_if.if_type = IFT_PPP;
995	sp->pp_if.if_output = sppp_output;
996#if 0
997	sp->pp_flags = PP_KEEPALIVE;
998#endif
999 	sp->pp_if.if_snd.ifq_maxlen = 32;
1000 	sp->pp_fastq.ifq_maxlen = 32;
1001 	sp->pp_cpq.ifq_maxlen = 20;
1002	sp->pp_loopcnt = 0;
1003	sp->pp_alivecnt = 0;
1004	bzero(&sp->pp_seq[0], sizeof(sp->pp_seq));
1005	bzero(&sp->pp_rseq[0], sizeof(sp->pp_rseq));
1006	sp->pp_phase = PHASE_DEAD;
1007	sp->pp_up = lcp.Up;
1008	sp->pp_down = lcp.Down;
1009	if(!mtx_initialized(&sp->pp_cpq.ifq_mtx))
1010		mtx_init(&sp->pp_cpq.ifq_mtx, "sppp_cpq", MTX_DEF);
1011	if(!mtx_initialized(&sp->pp_fastq.ifq_mtx))
1012		mtx_init(&sp->pp_fastq.ifq_mtx, "sppp_fastq", MTX_DEF);
1013	sp->pp_last_recv = sp->pp_last_sent = time_second;
1014	sp->enable_vj = 1;
1015	sp->pp_comp = malloc(sizeof(struct slcompress), M_TEMP, M_WAIT);
1016	sl_compress_init(sp->pp_comp, -1);
1017	sppp_lcp_init(sp);
1018	sppp_ipcp_init(sp);
1019	sppp_ipv6cp_init(sp);
1020	sppp_pap_init(sp);
1021	sppp_chap_init(sp);
1022}
1023
1024void
1025sppp_detach(struct ifnet *ifp)
1026{
1027	struct sppp **q, *p, *sp = (struct sppp*) ifp;
1028	int i;
1029
1030	/* Remove the entry from the keepalive list. */
1031	for (q = &spppq; (p = *q); q = &p->pp_next)
1032		if (p == sp) {
1033			*q = p->pp_next;
1034			break;
1035		}
1036
1037	/* Stop keepalive handler. */
1038	if (! spppq)
1039		UNTIMEOUT(sppp_keepalive, 0, keepalive_ch);
1040
1041	for (i = 0; i < IDX_COUNT; i++)
1042		UNTIMEOUT((cps[i])->TO, (void *)sp, sp->ch[i]);
1043	UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
1044	mtx_destroy(&sp->pp_cpq.ifq_mtx);
1045	mtx_destroy(&sp->pp_fastq.ifq_mtx);
1046}
1047
1048/*
1049 * Flush the interface output queue.
1050 */
1051void
1052sppp_flush(struct ifnet *ifp)
1053{
1054	struct sppp *sp = (struct sppp*) ifp;
1055
1056	sppp_qflush (&sp->pp_if.if_snd);
1057	sppp_qflush (&sp->pp_fastq);
1058	sppp_qflush (&sp->pp_cpq);
1059}
1060
1061/*
1062 * Check if the output queue is empty.
1063 */
1064int
1065sppp_isempty(struct ifnet *ifp)
1066{
1067	struct sppp *sp = (struct sppp*) ifp;
1068	int empty, s;
1069
1070	s = splimp();
1071	empty = !sp->pp_fastq.ifq_head && !sp->pp_cpq.ifq_head &&
1072		!sp->pp_if.if_snd.ifq_head;
1073	splx(s);
1074	return (empty);
1075}
1076
1077/*
1078 * Get next packet to send.
1079 */
1080struct mbuf *
1081sppp_dequeue(struct ifnet *ifp)
1082{
1083	struct sppp *sp = (struct sppp*) ifp;
1084	struct mbuf *m;
1085	int s;
1086
1087	s = splimp();
1088	/*
1089	 * Process only the control protocol queue until we have at
1090	 * least one NCP open.
1091	 *
1092	 * Do always serve all three queues in Cisco mode.
1093	 */
1094	IF_DEQUEUE(&sp->pp_cpq, m);
1095	if (m == NULL &&
1096	    (sppp_ncp_check(sp) || sp->pp_mode == IFF_CISCO)) {
1097		IF_DEQUEUE(&sp->pp_fastq, m);
1098		if (m == NULL)
1099			IF_DEQUEUE (&sp->pp_if.if_snd, m);
1100	}
1101	splx(s);
1102	return m;
1103}
1104
1105/*
1106 * Pick the next packet, do not remove it from the queue.
1107 */
1108struct mbuf *
1109sppp_pick(struct ifnet *ifp)
1110{
1111	struct sppp *sp = (struct sppp*)ifp;
1112	struct mbuf *m;
1113	int s;
1114
1115	s= splimp ();
1116
1117	m = sp->pp_cpq.ifq_head;
1118	if (m == NULL &&
1119	    (sp->pp_phase == PHASE_NETWORK || sp->pp_mode == IFF_CISCO))
1120		if ((m = sp->pp_fastq.ifq_head) == NULL)
1121			m = sp->pp_if.if_snd.ifq_head;
1122	splx (s);
1123	return (m);
1124}
1125
1126/*
1127 * Process an ioctl request.  Called on low priority level.
1128 */
1129int
1130sppp_ioctl(struct ifnet *ifp, IOCTL_CMD_T cmd, void *data)
1131{
1132	struct ifreq *ifr = (struct ifreq*) data;
1133	struct sppp *sp = (struct sppp*) ifp;
1134	int s, rv, going_up, going_down, newmode;
1135
1136	s = splimp();
1137	rv = 0;
1138	switch (cmd) {
1139	case SIOCAIFADDR:
1140	case SIOCSIFDSTADDR:
1141		break;
1142
1143	case SIOCSIFADDR:
1144		/* set the interface "up" when assigning an IP address */
1145		ifp->if_flags |= IFF_UP;
1146		/* fall through... */
1147
1148	case SIOCSIFFLAGS:
1149		going_up = ifp->if_flags & IFF_UP &&
1150			(ifp->if_flags & IFF_RUNNING) == 0;
1151		going_down = (ifp->if_flags & IFF_UP) == 0 &&
1152			ifp->if_flags & IFF_RUNNING;
1153
1154		newmode = ifp->if_flags & IFF_PASSIVE;
1155		if (!newmode)
1156			newmode = ifp->if_flags & IFF_AUTO;
1157		if (!newmode)
1158			newmode = ifp->if_flags & IFF_CISCO;
1159		ifp->if_flags &= ~(IFF_PASSIVE | IFF_AUTO | IFF_CISCO);
1160		ifp->if_flags |= newmode;
1161
1162		if (newmode != sp->pp_mode) {
1163			going_down = 1;
1164			if (!going_up)
1165				going_up = ifp->if_flags & IFF_RUNNING;
1166		}
1167
1168		if (going_down) {
1169			if (sp->pp_mode != IFF_CISCO)
1170				lcp.Close(sp);
1171			else if (sp->pp_tlf)
1172				(sp->pp_tlf)(sp);
1173			sppp_flush(ifp);
1174			ifp->if_flags &= ~IFF_RUNNING;
1175			sp->pp_mode = newmode;
1176		}
1177
1178		if (going_up) {
1179			if (sp->pp_mode != IFF_CISCO)
1180				lcp.Close(sp);
1181			sp->pp_mode = newmode;
1182			if (sp->pp_mode == 0) {
1183				ifp->if_flags |= IFF_RUNNING;
1184				lcp.Open(sp);
1185			}
1186			if (sp->pp_mode == IFF_CISCO) {
1187				if (sp->pp_tls)
1188					(sp->pp_tls)(sp);
1189				ifp->if_flags |= IFF_RUNNING;
1190			}
1191		}
1192
1193		break;
1194
1195#ifdef SIOCSIFMTU
1196#ifndef ifr_mtu
1197#define ifr_mtu ifr_metric
1198#endif
1199	case SIOCSIFMTU:
1200		if (ifr->ifr_mtu < 128 || ifr->ifr_mtu > sp->lcp.their_mru)
1201			return (EINVAL);
1202		ifp->if_mtu = ifr->ifr_mtu;
1203		break;
1204#endif
1205#ifdef SLIOCSETMTU
1206	case SLIOCSETMTU:
1207		if (*(short*)data < 128 || *(short*)data > sp->lcp.their_mru)
1208			return (EINVAL);
1209		ifp->if_mtu = *(short*)data;
1210		break;
1211#endif
1212#ifdef SIOCGIFMTU
1213	case SIOCGIFMTU:
1214		ifr->ifr_mtu = ifp->if_mtu;
1215		break;
1216#endif
1217#ifdef SLIOCGETMTU
1218	case SLIOCGETMTU:
1219		*(short*)data = ifp->if_mtu;
1220		break;
1221#endif
1222	case SIOCADDMULTI:
1223	case SIOCDELMULTI:
1224		break;
1225
1226	case SIOCGIFGENERIC:
1227	case SIOCSIFGENERIC:
1228		rv = sppp_params(sp, cmd, data);
1229		break;
1230
1231	default:
1232		rv = ENOTTY;
1233	}
1234	splx(s);
1235	return rv;
1236}
1237
1238/*
1239 * Cisco framing implementation.
1240 */
1241
1242/*
1243 * Handle incoming Cisco keepalive protocol packets.
1244 */
1245static void
1246sppp_cisco_input(struct sppp *sp, struct mbuf *m)
1247{
1248	STDDCL;
1249	struct cisco_packet *h;
1250	u_long me, mymask;
1251
1252	if (m->m_pkthdr.len < CISCO_PACKET_LEN) {
1253		if (debug)
1254			log(LOG_DEBUG,
1255			    SPP_FMT "cisco invalid packet length: %d bytes\n",
1256			    SPP_ARGS(ifp), m->m_pkthdr.len);
1257		return;
1258	}
1259	h = mtod (m, struct cisco_packet*);
1260	if (debug)
1261		log(LOG_DEBUG,
1262		    SPP_FMT "cisco input: %d bytes "
1263		    "<0x%lx 0x%lx 0x%lx 0x%x 0x%x-0x%x>\n",
1264		    SPP_ARGS(ifp), m->m_pkthdr.len,
1265		    (u_long)ntohl (h->type), (u_long)h->par1, (u_long)h->par2, (u_int)h->rel,
1266		    (u_int)h->time0, (u_int)h->time1);
1267	switch (ntohl (h->type)) {
1268	default:
1269		if (debug)
1270			log(-1, SPP_FMT "cisco unknown packet type: 0x%lx\n",
1271			       SPP_ARGS(ifp), (u_long)ntohl (h->type));
1272		break;
1273	case CISCO_ADDR_REPLY:
1274		/* Reply on address request, ignore */
1275		break;
1276	case CISCO_KEEPALIVE_REQ:
1277		sp->pp_alivecnt = 0;
1278		sp->pp_rseq[IDX_LCP] = ntohl (h->par1);
1279		if (sp->pp_seq[IDX_LCP] == sp->pp_rseq[IDX_LCP]) {
1280			/* Local and remote sequence numbers are equal.
1281			 * Probably, the line is in loopback mode. */
1282			if (sp->pp_loopcnt >= MAXALIVECNT) {
1283				printf (SPP_FMT "loopback\n",
1284					SPP_ARGS(ifp));
1285				sp->pp_loopcnt = 0;
1286				if (ifp->if_flags & IFF_UP) {
1287					if_down (ifp);
1288					sppp_qflush (&sp->pp_cpq);
1289				}
1290			}
1291			++sp->pp_loopcnt;
1292
1293			/* Generate new local sequence number */
1294#if defined(__FreeBSD__) && __FreeBSD__ >= 3
1295			sp->pp_seq[IDX_LCP] = random();
1296#else
1297			sp->pp_seq[IDX_LCP] ^= time.tv_sec ^ time.tv_usec;
1298#endif
1299			break;
1300		}
1301		sp->pp_loopcnt = 0;
1302		if (! (ifp->if_flags & IFF_UP) &&
1303		    (ifp->if_flags & IFF_RUNNING)) {
1304			if_up(ifp);
1305			printf (SPP_FMT "up\n", SPP_ARGS(ifp));
1306		}
1307		break;
1308	case CISCO_ADDR_REQ:
1309		sppp_get_ip_addrs(sp, &me, 0, &mymask);
1310		if (me != 0L)
1311			sppp_cisco_send(sp, CISCO_ADDR_REPLY, me, mymask);
1312		break;
1313	}
1314}
1315
1316/*
1317 * Send Cisco keepalive packet.
1318 */
1319static void
1320sppp_cisco_send(struct sppp *sp, int type, long par1, long par2)
1321{
1322	STDDCL;
1323	struct ppp_header *h;
1324	struct cisco_packet *ch;
1325	struct mbuf *m;
1326#if defined(__FreeBSD__) && __FreeBSD__ >= 3
1327	struct timeval tv;
1328#else
1329	u_long t = (time.tv_sec - boottime.tv_sec) * 1000;
1330#endif
1331
1332#if defined(__FreeBSD__) && __FreeBSD__ >= 3
1333	getmicrouptime(&tv);
1334#endif
1335
1336	MGETHDR (m, M_DONTWAIT, MT_DATA);
1337	if (! m)
1338		return;
1339	m->m_pkthdr.len = m->m_len = PPP_HEADER_LEN + CISCO_PACKET_LEN;
1340	m->m_pkthdr.rcvif = 0;
1341
1342	h = mtod (m, struct ppp_header*);
1343	h->address = CISCO_MULTICAST;
1344	h->control = 0;
1345	h->protocol = htons (CISCO_KEEPALIVE);
1346
1347	ch = (struct cisco_packet*) (h + 1);
1348	ch->type = htonl (type);
1349	ch->par1 = htonl (par1);
1350	ch->par2 = htonl (par2);
1351	ch->rel = -1;
1352
1353#if defined(__FreeBSD__) && __FreeBSD__ >= 3
1354	ch->time0 = htons ((u_short) (tv.tv_sec >> 16));
1355	ch->time1 = htons ((u_short) tv.tv_sec);
1356#else
1357	ch->time0 = htons ((u_short) (t >> 16));
1358	ch->time1 = htons ((u_short) t);
1359#endif
1360
1361	if (debug)
1362		log(LOG_DEBUG,
1363		    SPP_FMT "cisco output: <0x%lx 0x%lx 0x%lx 0x%x 0x%x-0x%x>\n",
1364			SPP_ARGS(ifp), (u_long)ntohl (ch->type), (u_long)ch->par1,
1365			(u_long)ch->par2, (u_int)ch->rel, (u_int)ch->time0, (u_int)ch->time1);
1366
1367	if (! IF_HANDOFF_ADJ(&sp->pp_cpq, m, ifp, 3))
1368		ifp->if_oerrors++;
1369}
1370
1371/*
1372 * PPP protocol implementation.
1373 */
1374
1375/*
1376 * Send PPP control protocol packet.
1377 */
1378static void
1379sppp_cp_send(struct sppp *sp, u_short proto, u_char type,
1380	     u_char ident, u_short len, void *data)
1381{
1382	STDDCL;
1383	struct ppp_header *h;
1384	struct lcp_header *lh;
1385	struct mbuf *m;
1386
1387	if (len > MHLEN - PPP_HEADER_LEN - LCP_HEADER_LEN)
1388		len = MHLEN - PPP_HEADER_LEN - LCP_HEADER_LEN;
1389	MGETHDR (m, M_DONTWAIT, MT_DATA);
1390	if (! m)
1391		return;
1392	m->m_pkthdr.len = m->m_len = PPP_HEADER_LEN + LCP_HEADER_LEN + len;
1393	m->m_pkthdr.rcvif = 0;
1394
1395	h = mtod (m, struct ppp_header*);
1396	h->address = PPP_ALLSTATIONS;        /* broadcast address */
1397	h->control = PPP_UI;                 /* Unnumbered Info */
1398	h->protocol = htons (proto);         /* Link Control Protocol */
1399
1400	lh = (struct lcp_header*) (h + 1);
1401	lh->type = type;
1402	lh->ident = ident;
1403	lh->len = htons (LCP_HEADER_LEN + len);
1404	if (len)
1405		bcopy (data, lh+1, len);
1406
1407	if (debug) {
1408		log(LOG_DEBUG, SPP_FMT "%s output <%s id=0x%x len=%d",
1409		    SPP_ARGS(ifp),
1410		    sppp_proto_name(proto),
1411		    sppp_cp_type_name (lh->type), lh->ident,
1412		    ntohs (lh->len));
1413		sppp_print_bytes ((u_char*) (lh+1), len);
1414		log(-1, ">\n");
1415	}
1416	if (! IF_HANDOFF_ADJ(&sp->pp_cpq, m, ifp, 3))
1417		ifp->if_oerrors++;
1418}
1419
1420/*
1421 * Handle incoming PPP control protocol packets.
1422 */
1423static void
1424sppp_cp_input(const struct cp *cp, struct sppp *sp, struct mbuf *m)
1425{
1426	STDDCL;
1427	struct lcp_header *h;
1428	int len = m->m_pkthdr.len;
1429	int rv;
1430	u_char *p;
1431
1432	if (len < 4) {
1433		if (debug)
1434			log(LOG_DEBUG,
1435			    SPP_FMT "%s invalid packet length: %d bytes\n",
1436			    SPP_ARGS(ifp), cp->name, len);
1437		return;
1438	}
1439	h = mtod (m, struct lcp_header*);
1440	if (debug) {
1441		log(LOG_DEBUG,
1442		    SPP_FMT "%s input(%s): <%s id=0x%x len=%d",
1443		    SPP_ARGS(ifp), cp->name,
1444		    sppp_state_name(sp->state[cp->protoidx]),
1445		    sppp_cp_type_name (h->type), h->ident, ntohs (h->len));
1446		sppp_print_bytes ((u_char*) (h+1), len-4);
1447		log(-1, ">\n");
1448	}
1449	if (len > ntohs (h->len))
1450		len = ntohs (h->len);
1451	p = (u_char *)(h + 1);
1452	switch (h->type) {
1453	case CONF_REQ:
1454		if (len < 4) {
1455			if (debug)
1456				log(-1, SPP_FMT "%s invalid conf-req length %d\n",
1457				       SPP_ARGS(ifp), cp->name,
1458				       len);
1459			++ifp->if_ierrors;
1460			break;
1461		}
1462		/* handle states where RCR doesn't get a SCA/SCN */
1463		switch (sp->state[cp->protoidx]) {
1464		case STATE_CLOSING:
1465		case STATE_STOPPING:
1466			return;
1467		case STATE_CLOSED:
1468			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident,
1469				     0, 0);
1470			return;
1471		}
1472		rv = (cp->RCR)(sp, h, len);
1473		switch (sp->state[cp->protoidx]) {
1474		case STATE_OPENED:
1475			(cp->tld)(sp);
1476			(cp->scr)(sp);
1477			/* fall through... */
1478		case STATE_ACK_SENT:
1479		case STATE_REQ_SENT:
1480			/*
1481			 * sppp_cp_change_state() have the side effect of
1482			 * restarting the timeouts. We want to avoid that
1483			 * if the state don't change, otherwise we won't
1484			 * ever timeout and resend a configuration request
1485			 * that got lost.
1486			 */
1487			if (sp->state[cp->protoidx] == (rv ? STATE_ACK_SENT:
1488			    STATE_REQ_SENT))
1489				break;
1490			sppp_cp_change_state(cp, sp, rv?
1491					     STATE_ACK_SENT: STATE_REQ_SENT);
1492			break;
1493		case STATE_STOPPED:
1494			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1495			(cp->scr)(sp);
1496			sppp_cp_change_state(cp, sp, rv?
1497					     STATE_ACK_SENT: STATE_REQ_SENT);
1498			break;
1499		case STATE_ACK_RCVD:
1500			if (rv) {
1501				sppp_cp_change_state(cp, sp, STATE_OPENED);
1502				if (debug)
1503					log(LOG_DEBUG, SPP_FMT "%s tlu\n",
1504					    SPP_ARGS(ifp),
1505					    cp->name);
1506				(cp->tlu)(sp);
1507			} else
1508				sppp_cp_change_state(cp, sp, STATE_ACK_RCVD);
1509			break;
1510		default:
1511			printf(SPP_FMT "%s illegal %s in state %s\n",
1512			       SPP_ARGS(ifp), cp->name,
1513			       sppp_cp_type_name(h->type),
1514			       sppp_state_name(sp->state[cp->protoidx]));
1515			++ifp->if_ierrors;
1516		}
1517		break;
1518	case CONF_ACK:
1519		if (h->ident != sp->confid[cp->protoidx]) {
1520			if (debug)
1521				log(-1, SPP_FMT "%s id mismatch 0x%x != 0x%x\n",
1522				       SPP_ARGS(ifp), cp->name,
1523				       h->ident, sp->confid[cp->protoidx]);
1524			++ifp->if_ierrors;
1525			break;
1526		}
1527		switch (sp->state[cp->protoidx]) {
1528		case STATE_CLOSED:
1529		case STATE_STOPPED:
1530			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident, 0, 0);
1531			break;
1532		case STATE_CLOSING:
1533		case STATE_STOPPING:
1534			break;
1535		case STATE_REQ_SENT:
1536			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1537			sppp_cp_change_state(cp, sp, STATE_ACK_RCVD);
1538			break;
1539		case STATE_OPENED:
1540			(cp->tld)(sp);
1541			/* fall through */
1542		case STATE_ACK_RCVD:
1543			(cp->scr)(sp);
1544			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1545			break;
1546		case STATE_ACK_SENT:
1547			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1548			sppp_cp_change_state(cp, sp, STATE_OPENED);
1549			if (debug)
1550				log(LOG_DEBUG, SPP_FMT "%s tlu\n",
1551				       SPP_ARGS(ifp), cp->name);
1552			(cp->tlu)(sp);
1553			break;
1554		default:
1555			printf(SPP_FMT "%s illegal %s in state %s\n",
1556			       SPP_ARGS(ifp), cp->name,
1557			       sppp_cp_type_name(h->type),
1558			       sppp_state_name(sp->state[cp->protoidx]));
1559			++ifp->if_ierrors;
1560		}
1561		break;
1562	case CONF_NAK:
1563	case CONF_REJ:
1564		if (h->ident != sp->confid[cp->protoidx]) {
1565			if (debug)
1566				log(-1, SPP_FMT "%s id mismatch 0x%x != 0x%x\n",
1567				       SPP_ARGS(ifp), cp->name,
1568				       h->ident, sp->confid[cp->protoidx]);
1569			++ifp->if_ierrors;
1570			break;
1571		}
1572		if (h->type == CONF_NAK)
1573			(cp->RCN_nak)(sp, h, len);
1574		else /* CONF_REJ */
1575			(cp->RCN_rej)(sp, h, len);
1576
1577		switch (sp->state[cp->protoidx]) {
1578		case STATE_CLOSED:
1579		case STATE_STOPPED:
1580			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident, 0, 0);
1581			break;
1582		case STATE_REQ_SENT:
1583		case STATE_ACK_SENT:
1584			sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1585			/*
1586			 * Slow things down a bit if we think we might be
1587			 * in loopback. Depend on the timeout to send the
1588			 * next configuration request.
1589			 */
1590			if (sp->pp_loopcnt)
1591				break;
1592			(cp->scr)(sp);
1593			break;
1594		case STATE_OPENED:
1595			(cp->tld)(sp);
1596			/* fall through */
1597		case STATE_ACK_RCVD:
1598			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1599			(cp->scr)(sp);
1600			break;
1601		case STATE_CLOSING:
1602		case STATE_STOPPING:
1603			break;
1604		default:
1605			printf(SPP_FMT "%s illegal %s in state %s\n",
1606			       SPP_ARGS(ifp), cp->name,
1607			       sppp_cp_type_name(h->type),
1608			       sppp_state_name(sp->state[cp->protoidx]));
1609			++ifp->if_ierrors;
1610		}
1611		break;
1612
1613	case TERM_REQ:
1614		switch (sp->state[cp->protoidx]) {
1615		case STATE_ACK_RCVD:
1616		case STATE_ACK_SENT:
1617			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1618			/* fall through */
1619		case STATE_CLOSED:
1620		case STATE_STOPPED:
1621		case STATE_CLOSING:
1622		case STATE_STOPPING:
1623		case STATE_REQ_SENT:
1624		  sta:
1625			/* Send Terminate-Ack packet. */
1626			if (debug)
1627				log(LOG_DEBUG, SPP_FMT "%s send terminate-ack\n",
1628				    SPP_ARGS(ifp), cp->name);
1629			sppp_cp_send(sp, cp->proto, TERM_ACK, h->ident, 0, 0);
1630			break;
1631		case STATE_OPENED:
1632			(cp->tld)(sp);
1633			sp->rst_counter[cp->protoidx] = 0;
1634			sppp_cp_change_state(cp, sp, STATE_STOPPING);
1635			goto sta;
1636			break;
1637		default:
1638			printf(SPP_FMT "%s illegal %s in state %s\n",
1639			       SPP_ARGS(ifp), cp->name,
1640			       sppp_cp_type_name(h->type),
1641			       sppp_state_name(sp->state[cp->protoidx]));
1642			++ifp->if_ierrors;
1643		}
1644		break;
1645	case TERM_ACK:
1646		switch (sp->state[cp->protoidx]) {
1647		case STATE_CLOSED:
1648		case STATE_STOPPED:
1649		case STATE_REQ_SENT:
1650		case STATE_ACK_SENT:
1651			break;
1652		case STATE_CLOSING:
1653			sppp_cp_change_state(cp, sp, STATE_CLOSED);
1654			(cp->tlf)(sp);
1655			break;
1656		case STATE_STOPPING:
1657			sppp_cp_change_state(cp, sp, STATE_STOPPED);
1658			(cp->tlf)(sp);
1659			break;
1660		case STATE_ACK_RCVD:
1661			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1662			break;
1663		case STATE_OPENED:
1664			(cp->tld)(sp);
1665			(cp->scr)(sp);
1666			sppp_cp_change_state(cp, sp, STATE_ACK_RCVD);
1667			break;
1668		default:
1669			printf(SPP_FMT "%s illegal %s in state %s\n",
1670			       SPP_ARGS(ifp), cp->name,
1671			       sppp_cp_type_name(h->type),
1672			       sppp_state_name(sp->state[cp->protoidx]));
1673			++ifp->if_ierrors;
1674		}
1675		break;
1676	case CODE_REJ:
1677		/* XXX catastrophic rejects (RXJ-) aren't handled yet. */
1678		log(LOG_INFO,
1679		    SPP_FMT "%s: ignoring RXJ (%s) for proto 0x%x, "
1680		    "danger will robinson\n",
1681		    SPP_ARGS(ifp), cp->name,
1682		    sppp_cp_type_name(h->type), ntohs(*((u_short *)p)));
1683		switch (sp->state[cp->protoidx]) {
1684		case STATE_CLOSED:
1685		case STATE_STOPPED:
1686		case STATE_REQ_SENT:
1687		case STATE_ACK_SENT:
1688		case STATE_CLOSING:
1689		case STATE_STOPPING:
1690		case STATE_OPENED:
1691			break;
1692		case STATE_ACK_RCVD:
1693			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1694			break;
1695		default:
1696			printf(SPP_FMT "%s illegal %s in state %s\n",
1697			       SPP_ARGS(ifp), cp->name,
1698			       sppp_cp_type_name(h->type),
1699			       sppp_state_name(sp->state[cp->protoidx]));
1700			++ifp->if_ierrors;
1701		}
1702		break;
1703	case PROTO_REJ:
1704	    {
1705		int catastrophic;
1706		const struct cp *upper;
1707		int i;
1708		u_int16_t proto;
1709
1710		catastrophic = 0;
1711		upper = NULL;
1712		proto = ntohs(*((u_int16_t *)p));
1713		for (i = 0; i < IDX_COUNT; i++) {
1714			if (cps[i]->proto == proto) {
1715				upper = cps[i];
1716				break;
1717			}
1718		}
1719		if (upper == NULL)
1720			catastrophic++;
1721
1722		if (catastrophic || debug)
1723			log(catastrophic? LOG_INFO: LOG_DEBUG,
1724			    SPP_FMT "%s: RXJ%c (%s) for proto 0x%x (%s/%s)\n",
1725			    SPP_ARGS(ifp), cp->name, catastrophic ? '-' : '+',
1726			    sppp_cp_type_name(h->type), proto,
1727			    upper ? upper->name : "unknown",
1728			    upper ? sppp_state_name(sp->state[upper->protoidx]) : "?");
1729
1730		/*
1731		 * if we got RXJ+ against conf-req, the peer does not implement
1732		 * this particular protocol type.  terminate the protocol.
1733		 */
1734		if (upper && !catastrophic) {
1735			if (sp->state[upper->protoidx] == STATE_REQ_SENT) {
1736				upper->Close(sp);
1737				break;
1738			}
1739		}
1740
1741		/* XXX catastrophic rejects (RXJ-) aren't handled yet. */
1742		switch (sp->state[cp->protoidx]) {
1743		case STATE_CLOSED:
1744		case STATE_STOPPED:
1745		case STATE_REQ_SENT:
1746		case STATE_ACK_SENT:
1747		case STATE_CLOSING:
1748		case STATE_STOPPING:
1749		case STATE_OPENED:
1750			break;
1751		case STATE_ACK_RCVD:
1752			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1753			break;
1754		default:
1755			printf(SPP_FMT "%s illegal %s in state %s\n",
1756			       SPP_ARGS(ifp), cp->name,
1757			       sppp_cp_type_name(h->type),
1758			       sppp_state_name(sp->state[cp->protoidx]));
1759			++ifp->if_ierrors;
1760		}
1761		break;
1762	    }
1763	case DISC_REQ:
1764		if (cp->proto != PPP_LCP)
1765			goto illegal;
1766		/* Discard the packet. */
1767		break;
1768	case ECHO_REQ:
1769		if (cp->proto != PPP_LCP)
1770			goto illegal;
1771		if (sp->state[cp->protoidx] != STATE_OPENED) {
1772			if (debug)
1773				log(-1, SPP_FMT "lcp echo req but lcp closed\n",
1774				       SPP_ARGS(ifp));
1775			++ifp->if_ierrors;
1776			break;
1777		}
1778		if (len < 8) {
1779			if (debug)
1780				log(-1, SPP_FMT "invalid lcp echo request "
1781				       "packet length: %d bytes\n",
1782				       SPP_ARGS(ifp), len);
1783			break;
1784		}
1785		if ((sp->lcp.opts & (1 << LCP_OPT_MAGIC)) &&
1786		    ntohl (*(long*)(h+1)) == sp->lcp.magic) {
1787			/* Line loopback mode detected. */
1788			printf(SPP_FMT "loopback\n", SPP_ARGS(ifp));
1789			sp->pp_loopcnt = MAXALIVECNT * 5;
1790			if_down (ifp);
1791			sppp_qflush (&sp->pp_cpq);
1792
1793			/* Shut down the PPP link. */
1794			/* XXX */
1795			lcp.Down(sp);
1796			lcp.Up(sp);
1797			break;
1798		}
1799		*(long*)(h+1) = htonl (sp->lcp.magic);
1800		if (debug)
1801			log(-1, SPP_FMT "got lcp echo req, sending echo rep\n",
1802			       SPP_ARGS(ifp));
1803		sppp_cp_send (sp, PPP_LCP, ECHO_REPLY, h->ident, len-4, h+1);
1804		break;
1805	case ECHO_REPLY:
1806		if (cp->proto != PPP_LCP)
1807			goto illegal;
1808		if (h->ident != sp->lcp.echoid) {
1809			++ifp->if_ierrors;
1810			break;
1811		}
1812		if (len < 8) {
1813			if (debug)
1814				log(-1, SPP_FMT "lcp invalid echo reply "
1815				       "packet length: %d bytes\n",
1816				       SPP_ARGS(ifp), len);
1817			break;
1818		}
1819		if (debug)
1820			log(-1, SPP_FMT "lcp got echo rep\n",
1821			       SPP_ARGS(ifp));
1822		if (!(sp->lcp.opts & (1 << LCP_OPT_MAGIC)) ||
1823		    ntohl (*(long*)(h+1)) != sp->lcp.magic)
1824			sp->pp_alivecnt = 0;
1825		break;
1826	default:
1827		/* Unknown packet type -- send Code-Reject packet. */
1828	  illegal:
1829		if (debug)
1830			log(-1, SPP_FMT "%s send code-rej for 0x%x\n",
1831			       SPP_ARGS(ifp), cp->name, h->type);
1832		sppp_cp_send(sp, cp->proto, CODE_REJ,
1833			     ++sp->pp_seq[cp->protoidx], m->m_pkthdr.len, h);
1834		++ifp->if_ierrors;
1835	}
1836}
1837
1838
1839/*
1840 * The generic part of all Up/Down/Open/Close/TO event handlers.
1841 * Basically, the state transition handling in the automaton.
1842 */
1843static void
1844sppp_up_event(const struct cp *cp, struct sppp *sp)
1845{
1846	STDDCL;
1847
1848	if (debug)
1849		log(LOG_DEBUG, SPP_FMT "%s up(%s)\n",
1850		    SPP_ARGS(ifp), cp->name,
1851		    sppp_state_name(sp->state[cp->protoidx]));
1852
1853	switch (sp->state[cp->protoidx]) {
1854	case STATE_INITIAL:
1855		sppp_cp_change_state(cp, sp, STATE_CLOSED);
1856		break;
1857	case STATE_STARTING:
1858		sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1859		(cp->scr)(sp);
1860		sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1861		break;
1862	default:
1863		printf(SPP_FMT "%s illegal up in state %s\n",
1864		       SPP_ARGS(ifp), cp->name,
1865		       sppp_state_name(sp->state[cp->protoidx]));
1866	}
1867}
1868
1869static void
1870sppp_down_event(const struct cp *cp, struct sppp *sp)
1871{
1872	STDDCL;
1873
1874	if (debug)
1875		log(LOG_DEBUG, SPP_FMT "%s down(%s)\n",
1876		    SPP_ARGS(ifp), cp->name,
1877		    sppp_state_name(sp->state[cp->protoidx]));
1878
1879	switch (sp->state[cp->protoidx]) {
1880	case STATE_CLOSED:
1881	case STATE_CLOSING:
1882		sppp_cp_change_state(cp, sp, STATE_INITIAL);
1883		break;
1884	case STATE_STOPPED:
1885		sppp_cp_change_state(cp, sp, STATE_STARTING);
1886		(cp->tls)(sp);
1887		break;
1888	case STATE_STOPPING:
1889	case STATE_REQ_SENT:
1890	case STATE_ACK_RCVD:
1891	case STATE_ACK_SENT:
1892		sppp_cp_change_state(cp, sp, STATE_STARTING);
1893		break;
1894	case STATE_OPENED:
1895		(cp->tld)(sp);
1896		sppp_cp_change_state(cp, sp, STATE_STARTING);
1897		break;
1898	default:
1899		printf(SPP_FMT "%s illegal down in state %s\n",
1900		       SPP_ARGS(ifp), cp->name,
1901		       sppp_state_name(sp->state[cp->protoidx]));
1902	}
1903}
1904
1905
1906static void
1907sppp_open_event(const struct cp *cp, struct sppp *sp)
1908{
1909	STDDCL;
1910
1911	if (debug)
1912		log(LOG_DEBUG, SPP_FMT "%s open(%s)\n",
1913		    SPP_ARGS(ifp), cp->name,
1914		    sppp_state_name(sp->state[cp->protoidx]));
1915
1916	switch (sp->state[cp->protoidx]) {
1917	case STATE_INITIAL:
1918		sppp_cp_change_state(cp, sp, STATE_STARTING);
1919		(cp->tls)(sp);
1920		break;
1921	case STATE_STARTING:
1922		break;
1923	case STATE_CLOSED:
1924		sp->rst_counter[cp->protoidx] = sp->lcp.max_configure;
1925		(cp->scr)(sp);
1926		sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
1927		break;
1928	case STATE_STOPPED:
1929		/*
1930		 * Try escaping stopped state.  This seems to bite
1931		 * people occasionally, in particular for IPCP,
1932		 * presumably following previous IPCP negotiation
1933		 * aborts.  Somehow, we must have missed a Down event
1934		 * which would have caused a transition into starting
1935		 * state, so as a bandaid we force the Down event now.
1936		 * This effectively implements (something like the)
1937		 * `restart' option mentioned in the state transition
1938		 * table of RFC 1661.
1939		 */
1940		sppp_cp_change_state(cp, sp, STATE_STARTING);
1941		(cp->tls)(sp);
1942		break;
1943	case STATE_STOPPING:
1944	case STATE_REQ_SENT:
1945	case STATE_ACK_RCVD:
1946	case STATE_ACK_SENT:
1947	case STATE_OPENED:
1948		break;
1949	case STATE_CLOSING:
1950		sppp_cp_change_state(cp, sp, STATE_STOPPING);
1951		break;
1952	}
1953}
1954
1955
1956static void
1957sppp_close_event(const struct cp *cp, struct sppp *sp)
1958{
1959	STDDCL;
1960
1961	if (debug)
1962		log(LOG_DEBUG, SPP_FMT "%s close(%s)\n",
1963		    SPP_ARGS(ifp), cp->name,
1964		    sppp_state_name(sp->state[cp->protoidx]));
1965
1966	switch (sp->state[cp->protoidx]) {
1967	case STATE_INITIAL:
1968	case STATE_CLOSED:
1969	case STATE_CLOSING:
1970		break;
1971	case STATE_STARTING:
1972		sppp_cp_change_state(cp, sp, STATE_INITIAL);
1973		(cp->tlf)(sp);
1974		break;
1975	case STATE_STOPPED:
1976		sppp_cp_change_state(cp, sp, STATE_CLOSED);
1977		break;
1978	case STATE_STOPPING:
1979		sppp_cp_change_state(cp, sp, STATE_CLOSING);
1980		break;
1981	case STATE_OPENED:
1982		(cp->tld)(sp);
1983		/* fall through */
1984	case STATE_REQ_SENT:
1985	case STATE_ACK_RCVD:
1986	case STATE_ACK_SENT:
1987		sp->rst_counter[cp->protoidx] = sp->lcp.max_terminate;
1988		sppp_cp_send(sp, cp->proto, TERM_REQ,
1989			     ++sp->pp_seq[cp->protoidx], 0, 0);
1990		sppp_cp_change_state(cp, sp, STATE_CLOSING);
1991		break;
1992	}
1993}
1994
1995static void
1996sppp_to_event(const struct cp *cp, struct sppp *sp)
1997{
1998	STDDCL;
1999	int s;
2000
2001	s = splimp();
2002	if (debug)
2003		log(LOG_DEBUG, SPP_FMT "%s TO(%s) rst_counter = %d\n",
2004		    SPP_ARGS(ifp), cp->name,
2005		    sppp_state_name(sp->state[cp->protoidx]),
2006		    sp->rst_counter[cp->protoidx]);
2007
2008	if (--sp->rst_counter[cp->protoidx] < 0)
2009		/* TO- event */
2010		switch (sp->state[cp->protoidx]) {
2011		case STATE_CLOSING:
2012			sppp_cp_change_state(cp, sp, STATE_CLOSED);
2013			(cp->tlf)(sp);
2014			break;
2015		case STATE_STOPPING:
2016			sppp_cp_change_state(cp, sp, STATE_STOPPED);
2017			(cp->tlf)(sp);
2018			break;
2019		case STATE_REQ_SENT:
2020		case STATE_ACK_RCVD:
2021		case STATE_ACK_SENT:
2022			sppp_cp_change_state(cp, sp, STATE_STOPPED);
2023			(cp->tlf)(sp);
2024			break;
2025		}
2026	else
2027		/* TO+ event */
2028		switch (sp->state[cp->protoidx]) {
2029		case STATE_CLOSING:
2030		case STATE_STOPPING:
2031			sppp_cp_send(sp, cp->proto, TERM_REQ,
2032				     ++sp->pp_seq[cp->protoidx], 0, 0);
2033			TIMEOUT(cp->TO, (void *)sp, sp->lcp.timeout,
2034			    sp->ch[cp->protoidx]);
2035			break;
2036		case STATE_REQ_SENT:
2037		case STATE_ACK_RCVD:
2038			(cp->scr)(sp);
2039			/* sppp_cp_change_state() will restart the timer */
2040			sppp_cp_change_state(cp, sp, STATE_REQ_SENT);
2041			break;
2042		case STATE_ACK_SENT:
2043			(cp->scr)(sp);
2044			TIMEOUT(cp->TO, (void *)sp, sp->lcp.timeout,
2045			    sp->ch[cp->protoidx]);
2046			break;
2047		}
2048
2049	splx(s);
2050}
2051
2052/*
2053 * Change the state of a control protocol in the state automaton.
2054 * Takes care of starting/stopping the restart timer.
2055 */
2056void
2057sppp_cp_change_state(const struct cp *cp, struct sppp *sp, int newstate)
2058{
2059	sp->state[cp->protoidx] = newstate;
2060
2061	UNTIMEOUT(cp->TO, (void *)sp, sp->ch[cp->protoidx]);
2062	switch (newstate) {
2063	case STATE_INITIAL:
2064	case STATE_STARTING:
2065	case STATE_CLOSED:
2066	case STATE_STOPPED:
2067	case STATE_OPENED:
2068		break;
2069	case STATE_CLOSING:
2070	case STATE_STOPPING:
2071	case STATE_REQ_SENT:
2072	case STATE_ACK_RCVD:
2073	case STATE_ACK_SENT:
2074		TIMEOUT(cp->TO, (void *)sp, sp->lcp.timeout,
2075		    sp->ch[cp->protoidx]);
2076		break;
2077	}
2078}
2079
2080/*
2081 *--------------------------------------------------------------------------*
2082 *                                                                          *
2083 *                         The LCP implementation.                          *
2084 *                                                                          *
2085 *--------------------------------------------------------------------------*
2086 */
2087static void
2088sppp_lcp_init(struct sppp *sp)
2089{
2090	sp->lcp.opts = (1 << LCP_OPT_MAGIC);
2091	sp->lcp.magic = 0;
2092	sp->state[IDX_LCP] = STATE_INITIAL;
2093	sp->fail_counter[IDX_LCP] = 0;
2094	sp->pp_seq[IDX_LCP] = 0;
2095	sp->pp_rseq[IDX_LCP] = 0;
2096	sp->lcp.protos = 0;
2097	sp->lcp.mru = sp->lcp.their_mru = PP_MTU;
2098
2099	/* Note that these values are  relevant for all control protocols */
2100	sp->lcp.timeout = 3 * hz;
2101	sp->lcp.max_terminate = 2;
2102	sp->lcp.max_configure = 10;
2103	sp->lcp.max_failure = 10;
2104#if defined(__FreeBSD__) && __FreeBSD__ >= 3
2105	callout_handle_init(&sp->ch[IDX_LCP]);
2106#endif
2107}
2108
2109static void
2110sppp_lcp_up(struct sppp *sp)
2111{
2112	STDDCL;
2113
2114	sp->pp_alivecnt = 0;
2115	sp->lcp.opts = (1 << LCP_OPT_MAGIC);
2116	sp->lcp.magic = 0;
2117	sp->lcp.protos = 0;
2118	sp->lcp.mru = sp->lcp.their_mru = PP_MTU;
2119	/*
2120	 * If we are authenticator, negotiate LCP_AUTH
2121	 */
2122	if (sp->hisauth.proto != 0)
2123		sp->lcp.opts |= (1 << LCP_OPT_AUTH_PROTO);
2124	else
2125		sp->lcp.opts &= ~(1 << LCP_OPT_AUTH_PROTO);
2126	sp->pp_flags &= ~PP_NEEDAUTH;
2127	/*
2128	 * If this interface is passive or dial-on-demand, and we are
2129	 * still in Initial state, it means we've got an incoming
2130	 * call.  Activate the interface.
2131	 */
2132	if ((ifp->if_flags & (IFF_AUTO | IFF_PASSIVE)) != 0) {
2133		if (debug)
2134			log(LOG_DEBUG,
2135			    SPP_FMT "Up event", SPP_ARGS(ifp));
2136		ifp->if_flags |= IFF_RUNNING;
2137		if (sp->state[IDX_LCP] == STATE_INITIAL) {
2138			if (debug)
2139				log(-1, "(incoming call)\n");
2140			sp->pp_flags |= PP_CALLIN;
2141			lcp.Open(sp);
2142		} else if (debug)
2143			log(-1, "\n");
2144	} else if ((ifp->if_flags & (IFF_AUTO | IFF_PASSIVE)) == 0 &&
2145		   (sp->state[IDX_LCP] == STATE_INITIAL)) {
2146		ifp->if_flags |= IFF_RUNNING;
2147		lcp.Open(sp);
2148	}
2149
2150	sppp_up_event(&lcp, sp);
2151}
2152
2153static void
2154sppp_lcp_down(struct sppp *sp)
2155{
2156	STDDCL;
2157
2158	sppp_down_event(&lcp, sp);
2159
2160	/*
2161	 * If this is neither a dial-on-demand nor a passive
2162	 * interface, simulate an ``ifconfig down'' action, so the
2163	 * administrator can force a redial by another ``ifconfig
2164	 * up''.  XXX For leased line operation, should we immediately
2165	 * try to reopen the connection here?
2166	 */
2167	if ((ifp->if_flags & (IFF_AUTO | IFF_PASSIVE)) == 0) {
2168		log(LOG_INFO,
2169		    SPP_FMT "Down event, taking interface down.\n",
2170		    SPP_ARGS(ifp));
2171		if_down(ifp);
2172	} else {
2173		if (debug)
2174			log(LOG_DEBUG,
2175			    SPP_FMT "Down event (carrier loss)\n",
2176			    SPP_ARGS(ifp));
2177		sp->pp_flags &= ~PP_CALLIN;
2178		if (sp->state[IDX_LCP] != STATE_INITIAL)
2179			lcp.Close(sp);
2180		ifp->if_flags &= ~IFF_RUNNING;
2181	}
2182}
2183
2184static void
2185sppp_lcp_open(struct sppp *sp)
2186{
2187	sppp_open_event(&lcp, sp);
2188}
2189
2190static void
2191sppp_lcp_close(struct sppp *sp)
2192{
2193	sppp_close_event(&lcp, sp);
2194}
2195
2196static void
2197sppp_lcp_TO(void *cookie)
2198{
2199	sppp_to_event(&lcp, (struct sppp *)cookie);
2200}
2201
2202/*
2203 * Analyze a configure request.  Return true if it was agreeable, and
2204 * caused action sca, false if it has been rejected or nak'ed, and
2205 * caused action scn.  (The return value is used to make the state
2206 * transition decision in the state automaton.)
2207 */
2208static int
2209sppp_lcp_RCR(struct sppp *sp, struct lcp_header *h, int len)
2210{
2211	STDDCL;
2212	u_char *buf, *r, *p;
2213	int origlen, rlen;
2214	u_long nmagic;
2215	u_short authproto;
2216
2217	len -= 4;
2218	origlen = len;
2219	buf = r = malloc (len, M_TEMP, M_NOWAIT);
2220	if (! buf)
2221		return (0);
2222
2223	if (debug)
2224		log(LOG_DEBUG, SPP_FMT "lcp parse opts: ",
2225		    SPP_ARGS(ifp));
2226
2227	/* pass 1: check for things that need to be rejected */
2228	p = (void*) (h+1);
2229	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2230		if (debug)
2231			log(-1, " %s ", sppp_lcp_opt_name(*p));
2232		switch (*p) {
2233		case LCP_OPT_MAGIC:
2234			/* Magic number. */
2235			if (len >= 6 && p[1] == 6)
2236				continue;
2237			if (debug)
2238				log(-1, "[invalid] ");
2239			break;
2240		case LCP_OPT_ASYNC_MAP:
2241			/* Async control character map. */
2242			if (len >= 6 && p[1] == 6)
2243				continue;
2244			if (debug)
2245				log(-1, "[invalid] ");
2246			break;
2247		case LCP_OPT_MRU:
2248			/* Maximum receive unit. */
2249			if (len >= 4 && p[1] == 4)
2250				continue;
2251			if (debug)
2252				log(-1, "[invalid] ");
2253			break;
2254		case LCP_OPT_AUTH_PROTO:
2255			if (len < 4) {
2256				if (debug)
2257					log(-1, "[invalid] ");
2258				break;
2259			}
2260			authproto = (p[2] << 8) + p[3];
2261			if (authproto == PPP_CHAP && p[1] != 5) {
2262				if (debug)
2263					log(-1, "[invalid chap len] ");
2264				break;
2265			}
2266			if (sp->myauth.proto == 0) {
2267				/* we are not configured to do auth */
2268				if (debug)
2269					log(-1, "[not configured] ");
2270				break;
2271			}
2272			/*
2273			 * Remote want us to authenticate, remember this,
2274			 * so we stay in PHASE_AUTHENTICATE after LCP got
2275			 * up.
2276			 */
2277			sp->pp_flags |= PP_NEEDAUTH;
2278			continue;
2279		default:
2280			/* Others not supported. */
2281			if (debug)
2282				log(-1, "[rej] ");
2283			break;
2284		}
2285		/* Add the option to rejected list. */
2286		bcopy (p, r, p[1]);
2287		r += p[1];
2288		rlen += p[1];
2289	}
2290	if (rlen) {
2291		if (debug)
2292			log(-1, " send conf-rej\n");
2293		sppp_cp_send (sp, PPP_LCP, CONF_REJ, h->ident, rlen, buf);
2294		return 0;
2295	} else if (debug)
2296		log(-1, "\n");
2297
2298	/*
2299	 * pass 2: check for option values that are unacceptable and
2300	 * thus require to be nak'ed.
2301	 */
2302	if (debug)
2303		log(LOG_DEBUG, SPP_FMT "lcp parse opt values: ",
2304		    SPP_ARGS(ifp));
2305
2306	p = (void*) (h+1);
2307	len = origlen;
2308	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2309		if (debug)
2310			log(-1, " %s ", sppp_lcp_opt_name(*p));
2311		switch (*p) {
2312		case LCP_OPT_MAGIC:
2313			/* Magic number -- extract. */
2314			nmagic = (u_long)p[2] << 24 |
2315				(u_long)p[3] << 16 | p[4] << 8 | p[5];
2316			if (nmagic != sp->lcp.magic) {
2317				sp->pp_loopcnt = 0;
2318				if (debug)
2319					log(-1, "0x%lx ", nmagic);
2320				continue;
2321			}
2322			if (debug && sp->pp_loopcnt < MAXALIVECNT*5)
2323				log(-1, "[glitch] ");
2324			++sp->pp_loopcnt;
2325			/*
2326			 * We negate our magic here, and NAK it.  If
2327			 * we see it later in an NAK packet, we
2328			 * suggest a new one.
2329			 */
2330			nmagic = ~sp->lcp.magic;
2331			/* Gonna NAK it. */
2332			p[2] = nmagic >> 24;
2333			p[3] = nmagic >> 16;
2334			p[4] = nmagic >> 8;
2335			p[5] = nmagic;
2336			break;
2337
2338		case LCP_OPT_ASYNC_MAP:
2339			/*
2340			 * Async control character map -- just ignore it.
2341			 *
2342			 * Quote from RFC 1662, chapter 6:
2343			 * To enable this functionality, synchronous PPP
2344			 * implementations MUST always respond to the
2345			 * Async-Control-Character-Map Configuration
2346			 * Option with the LCP Configure-Ack.  However,
2347			 * acceptance of the Configuration Option does
2348			 * not imply that the synchronous implementation
2349			 * will do any ACCM mapping.  Instead, all such
2350			 * octet mapping will be performed by the
2351			 * asynchronous-to-synchronous converter.
2352			 */
2353			continue;
2354
2355		case LCP_OPT_MRU:
2356			/*
2357			 * Maximum receive unit.  Always agreeable,
2358			 * but ignored by now.
2359			 */
2360			sp->lcp.their_mru = p[2] * 256 + p[3];
2361			if (debug)
2362				log(-1, "%lu ", sp->lcp.their_mru);
2363			continue;
2364
2365		case LCP_OPT_AUTH_PROTO:
2366			authproto = (p[2] << 8) + p[3];
2367			if (sp->myauth.proto != authproto) {
2368				/* not agreed, nak */
2369				if (debug)
2370					log(-1, "[mine %s != his %s] ",
2371					       sppp_proto_name(sp->hisauth.proto),
2372					       sppp_proto_name(authproto));
2373				p[2] = sp->myauth.proto >> 8;
2374				p[3] = sp->myauth.proto;
2375				break;
2376			}
2377			if (authproto == PPP_CHAP && p[4] != CHAP_MD5) {
2378				if (debug)
2379					log(-1, "[chap not MD5] ");
2380				p[4] = CHAP_MD5;
2381				break;
2382			}
2383			continue;
2384		}
2385		/* Add the option to nak'ed list. */
2386		bcopy (p, r, p[1]);
2387		r += p[1];
2388		rlen += p[1];
2389	}
2390	if (rlen) {
2391		/*
2392		 * Local and remote magics equal -- loopback?
2393		 */
2394		if (sp->pp_loopcnt >= MAXALIVECNT*5) {
2395			if (sp->pp_loopcnt == MAXALIVECNT*5)
2396				printf (SPP_FMT "loopback\n",
2397					SPP_ARGS(ifp));
2398			if (ifp->if_flags & IFF_UP) {
2399				if_down(ifp);
2400				sppp_qflush(&sp->pp_cpq);
2401				/* XXX ? */
2402				lcp.Down(sp);
2403				lcp.Up(sp);
2404			}
2405		} else if (++sp->fail_counter[IDX_LCP] >= sp->lcp.max_failure) {
2406			if (debug)
2407				log(-1, " max_failure (%d) exceeded, "
2408				       "send conf-rej\n",
2409				       sp->lcp.max_failure);
2410			sppp_cp_send(sp, PPP_LCP, CONF_REJ, h->ident, rlen, buf);
2411		} else {
2412			if (debug)
2413				log(-1, " send conf-nak\n");
2414			sppp_cp_send (sp, PPP_LCP, CONF_NAK, h->ident, rlen, buf);
2415		}
2416	} else {
2417		if (debug)
2418			log(-1, " send conf-ack\n");
2419		sp->fail_counter[IDX_LCP] = 0;
2420		sp->pp_loopcnt = 0;
2421		sppp_cp_send (sp, PPP_LCP, CONF_ACK,
2422			      h->ident, origlen, h+1);
2423	}
2424
2425	free (buf, M_TEMP);
2426	return (rlen == 0);
2427}
2428
2429/*
2430 * Analyze the LCP Configure-Reject option list, and adjust our
2431 * negotiation.
2432 */
2433static void
2434sppp_lcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
2435{
2436	STDDCL;
2437	u_char *buf, *p;
2438
2439	len -= 4;
2440	buf = malloc (len, M_TEMP, M_NOWAIT);
2441	if (!buf)
2442		return;
2443
2444	if (debug)
2445		log(LOG_DEBUG, SPP_FMT "lcp rej opts: ",
2446		    SPP_ARGS(ifp));
2447
2448	p = (void*) (h+1);
2449	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2450		if (debug)
2451			log(-1, " %s ", sppp_lcp_opt_name(*p));
2452		switch (*p) {
2453		case LCP_OPT_MAGIC:
2454			/* Magic number -- can't use it, use 0 */
2455			sp->lcp.opts &= ~(1 << LCP_OPT_MAGIC);
2456			sp->lcp.magic = 0;
2457			break;
2458		case LCP_OPT_MRU:
2459			/*
2460			 * Should not be rejected anyway, since we only
2461			 * negotiate a MRU if explicitly requested by
2462			 * peer.
2463			 */
2464			sp->lcp.opts &= ~(1 << LCP_OPT_MRU);
2465			break;
2466		case LCP_OPT_AUTH_PROTO:
2467			/*
2468			 * Peer doesn't want to authenticate himself,
2469			 * deny unless this is a dialout call, and
2470			 * AUTHFLAG_NOCALLOUT is set.
2471			 */
2472			if ((sp->pp_flags & PP_CALLIN) == 0 &&
2473			    (sp->hisauth.flags & AUTHFLAG_NOCALLOUT) != 0) {
2474				if (debug)
2475					log(-1, "[don't insist on auth "
2476					       "for callout]");
2477				sp->lcp.opts &= ~(1 << LCP_OPT_AUTH_PROTO);
2478				break;
2479			}
2480			if (debug)
2481				log(-1, "[access denied]\n");
2482			lcp.Close(sp);
2483			break;
2484		}
2485	}
2486	if (debug)
2487		log(-1, "\n");
2488	free (buf, M_TEMP);
2489	return;
2490}
2491
2492/*
2493 * Analyze the LCP Configure-NAK option list, and adjust our
2494 * negotiation.
2495 */
2496static void
2497sppp_lcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
2498{
2499	STDDCL;
2500	u_char *buf, *p;
2501	u_long magic;
2502
2503	len -= 4;
2504	buf = malloc (len, M_TEMP, M_NOWAIT);
2505	if (!buf)
2506		return;
2507
2508	if (debug)
2509		log(LOG_DEBUG, SPP_FMT "lcp nak opts: ",
2510		    SPP_ARGS(ifp));
2511
2512	p = (void*) (h+1);
2513	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
2514		if (debug)
2515			log(-1, " %s ", sppp_lcp_opt_name(*p));
2516		switch (*p) {
2517		case LCP_OPT_MAGIC:
2518			/* Magic number -- renegotiate */
2519			if ((sp->lcp.opts & (1 << LCP_OPT_MAGIC)) &&
2520			    len >= 6 && p[1] == 6) {
2521				magic = (u_long)p[2] << 24 |
2522					(u_long)p[3] << 16 | p[4] << 8 | p[5];
2523				/*
2524				 * If the remote magic is our negated one,
2525				 * this looks like a loopback problem.
2526				 * Suggest a new magic to make sure.
2527				 */
2528				if (magic == ~sp->lcp.magic) {
2529					if (debug)
2530						log(-1, "magic glitch ");
2531#if defined(__FreeBSD__) && __FreeBSD__ >= 3
2532					sp->lcp.magic = random();
2533#else
2534					sp->lcp.magic = time.tv_sec + time.tv_usec;
2535#endif
2536				} else {
2537					sp->lcp.magic = magic;
2538					if (debug)
2539						log(-1, "%lu ", magic);
2540				}
2541			}
2542			break;
2543		case LCP_OPT_MRU:
2544			/*
2545			 * Peer wants to advise us to negotiate an MRU.
2546			 * Agree on it if it's reasonable, or use
2547			 * default otherwise.
2548			 */
2549			if (len >= 4 && p[1] == 4) {
2550				u_int mru = p[2] * 256 + p[3];
2551				if (debug)
2552					log(-1, "%d ", mru);
2553				if (mru < PP_MTU || mru > PP_MAX_MRU)
2554					mru = PP_MTU;
2555				sp->lcp.mru = mru;
2556				sp->lcp.opts |= (1 << LCP_OPT_MRU);
2557			}
2558			break;
2559		case LCP_OPT_AUTH_PROTO:
2560			/*
2561			 * Peer doesn't like our authentication method,
2562			 * deny.
2563			 */
2564			if (debug)
2565				log(-1, "[access denied]\n");
2566			lcp.Close(sp);
2567			break;
2568		}
2569	}
2570	if (debug)
2571		log(-1, "\n");
2572	free (buf, M_TEMP);
2573	return;
2574}
2575
2576static void
2577sppp_lcp_tlu(struct sppp *sp)
2578{
2579	STDDCL;
2580	int i;
2581	u_long mask;
2582
2583	/* XXX ? */
2584	if (! (ifp->if_flags & IFF_UP) &&
2585	    (ifp->if_flags & IFF_RUNNING)) {
2586		/* Coming out of loopback mode. */
2587		if_up(ifp);
2588		printf (SPP_FMT "up\n", SPP_ARGS(ifp));
2589	}
2590
2591	for (i = 0; i < IDX_COUNT; i++)
2592		if ((cps[i])->flags & CP_QUAL)
2593			(cps[i])->Open(sp);
2594
2595	if ((sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0 ||
2596	    (sp->pp_flags & PP_NEEDAUTH) != 0)
2597		sp->pp_phase = PHASE_AUTHENTICATE;
2598	else
2599		sp->pp_phase = PHASE_NETWORK;
2600
2601	if (debug)
2602		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2603		    sppp_phase_name(sp->pp_phase));
2604
2605	/*
2606	 * Open all authentication protocols.  This is even required
2607	 * if we already proceeded to network phase, since it might be
2608	 * that remote wants us to authenticate, so we might have to
2609	 * send a PAP request.  Undesired authentication protocols
2610	 * don't do anything when they get an Open event.
2611	 */
2612	for (i = 0; i < IDX_COUNT; i++)
2613		if ((cps[i])->flags & CP_AUTH)
2614			(cps[i])->Open(sp);
2615
2616	if (sp->pp_phase == PHASE_NETWORK) {
2617		/* Notify all NCPs. */
2618		for (i = 0; i < IDX_COUNT; i++)
2619			if ((cps[i])->flags & CP_NCP)
2620				(cps[i])->Open(sp);
2621	}
2622
2623	/* Send Up events to all started protos. */
2624	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2625		if ((sp->lcp.protos & mask) && ((cps[i])->flags & CP_LCP) == 0)
2626			(cps[i])->Up(sp);
2627
2628	/* notify low-level driver of state change */
2629	if (sp->pp_chg)
2630		sp->pp_chg(sp, (int)sp->pp_phase);
2631
2632	if (sp->pp_phase == PHASE_NETWORK)
2633		/* if no NCP is starting, close down */
2634		sppp_lcp_check_and_close(sp);
2635}
2636
2637static void
2638sppp_lcp_tld(struct sppp *sp)
2639{
2640	STDDCL;
2641	int i;
2642	u_long mask;
2643
2644	sp->pp_phase = PHASE_TERMINATE;
2645
2646	if (debug)
2647		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2648		    sppp_phase_name(sp->pp_phase));
2649
2650	/*
2651	 * Take upper layers down.  We send the Down event first and
2652	 * the Close second to prevent the upper layers from sending
2653	 * ``a flurry of terminate-request packets'', as the RFC
2654	 * describes it.
2655	 */
2656	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2657		if ((sp->lcp.protos & mask) && ((cps[i])->flags & CP_LCP) == 0) {
2658			(cps[i])->Down(sp);
2659			(cps[i])->Close(sp);
2660		}
2661}
2662
2663static void
2664sppp_lcp_tls(struct sppp *sp)
2665{
2666	STDDCL;
2667
2668	sp->pp_phase = PHASE_ESTABLISH;
2669
2670	if (debug)
2671		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2672		    sppp_phase_name(sp->pp_phase));
2673
2674	/* Notify lower layer if desired. */
2675	if (sp->pp_tls)
2676		(sp->pp_tls)(sp);
2677	else
2678		(sp->pp_up)(sp);
2679}
2680
2681static void
2682sppp_lcp_tlf(struct sppp *sp)
2683{
2684	STDDCL;
2685
2686	sp->pp_phase = PHASE_DEAD;
2687	if (debug)
2688		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
2689		    sppp_phase_name(sp->pp_phase));
2690
2691	/* Notify lower layer if desired. */
2692	if (sp->pp_tlf)
2693		(sp->pp_tlf)(sp);
2694	else
2695		(sp->pp_down)(sp);
2696}
2697
2698static void
2699sppp_lcp_scr(struct sppp *sp)
2700{
2701	char opt[6 /* magicnum */ + 4 /* mru */ + 5 /* chap */];
2702	int i = 0;
2703	u_short authproto;
2704
2705	if (sp->lcp.opts & (1 << LCP_OPT_MAGIC)) {
2706		if (! sp->lcp.magic)
2707#if defined(__FreeBSD__) && __FreeBSD__ >= 3
2708			sp->lcp.magic = random();
2709#else
2710			sp->lcp.magic = time.tv_sec + time.tv_usec;
2711#endif
2712		opt[i++] = LCP_OPT_MAGIC;
2713		opt[i++] = 6;
2714		opt[i++] = sp->lcp.magic >> 24;
2715		opt[i++] = sp->lcp.magic >> 16;
2716		opt[i++] = sp->lcp.magic >> 8;
2717		opt[i++] = sp->lcp.magic;
2718	}
2719
2720	if (sp->lcp.opts & (1 << LCP_OPT_MRU)) {
2721		opt[i++] = LCP_OPT_MRU;
2722		opt[i++] = 4;
2723		opt[i++] = sp->lcp.mru >> 8;
2724		opt[i++] = sp->lcp.mru;
2725	}
2726
2727	if (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) {
2728		authproto = sp->hisauth.proto;
2729		opt[i++] = LCP_OPT_AUTH_PROTO;
2730		opt[i++] = authproto == PPP_CHAP? 5: 4;
2731		opt[i++] = authproto >> 8;
2732		opt[i++] = authproto;
2733		if (authproto == PPP_CHAP)
2734			opt[i++] = CHAP_MD5;
2735	}
2736
2737	sp->confid[IDX_LCP] = ++sp->pp_seq[IDX_LCP];
2738	sppp_cp_send (sp, PPP_LCP, CONF_REQ, sp->confid[IDX_LCP], i, &opt);
2739}
2740
2741/*
2742 * Check the open NCPs, return true if at least one NCP is open.
2743 */
2744static int
2745sppp_ncp_check(struct sppp *sp)
2746{
2747	int i, mask;
2748
2749	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
2750		if ((sp->lcp.protos & mask) && (cps[i])->flags & CP_NCP)
2751			return 1;
2752	return 0;
2753}
2754
2755/*
2756 * Re-check the open NCPs and see if we should terminate the link.
2757 * Called by the NCPs during their tlf action handling.
2758 */
2759static void
2760sppp_lcp_check_and_close(struct sppp *sp)
2761{
2762
2763	if (sp->pp_phase < PHASE_NETWORK)
2764		/* don't bother, we are already going down */
2765		return;
2766
2767	if (sppp_ncp_check(sp))
2768		return;
2769
2770	lcp.Close(sp);
2771}
2772
2773/*
2774 *--------------------------------------------------------------------------*
2775 *                                                                          *
2776 *                        The IPCP implementation.                          *
2777 *                                                                          *
2778 *--------------------------------------------------------------------------*
2779 */
2780
2781static void
2782sppp_ipcp_init(struct sppp *sp)
2783{
2784	sp->ipcp.opts = 0;
2785	sp->ipcp.flags = 0;
2786	sp->state[IDX_IPCP] = STATE_INITIAL;
2787	sp->fail_counter[IDX_IPCP] = 0;
2788	sp->pp_seq[IDX_IPCP] = 0;
2789	sp->pp_rseq[IDX_IPCP] = 0;
2790#if defined(__FreeBSD__) && __FreeBSD__ >= 3
2791	callout_handle_init(&sp->ch[IDX_IPCP]);
2792#endif
2793}
2794
2795static void
2796sppp_ipcp_up(struct sppp *sp)
2797{
2798	sppp_up_event(&ipcp, sp);
2799}
2800
2801static void
2802sppp_ipcp_down(struct sppp *sp)
2803{
2804	sppp_down_event(&ipcp, sp);
2805}
2806
2807static void
2808sppp_ipcp_open(struct sppp *sp)
2809{
2810	STDDCL;
2811	u_long myaddr, hisaddr;
2812
2813	sp->ipcp.flags &= ~(IPCP_HISADDR_SEEN | IPCP_MYADDR_SEEN |
2814			    IPCP_MYADDR_DYN | IPCP_VJ);
2815	sp->ipcp.opts = 0;
2816
2817	sppp_get_ip_addrs(sp, &myaddr, &hisaddr, 0);
2818	/*
2819	 * If we don't have his address, this probably means our
2820	 * interface doesn't want to talk IP at all.  (This could
2821	 * be the case if somebody wants to speak only IPX, for
2822	 * example.)  Don't open IPCP in this case.
2823	 */
2824	if (hisaddr == 0L) {
2825		/* XXX this message should go away */
2826		if (debug)
2827			log(LOG_DEBUG, SPP_FMT "ipcp_open(): no IP interface\n",
2828			    SPP_ARGS(ifp));
2829		return;
2830	}
2831	if (myaddr == 0L) {
2832		/*
2833		 * I don't have an assigned address, so i need to
2834		 * negotiate my address.
2835		 */
2836		sp->ipcp.flags |= IPCP_MYADDR_DYN;
2837		sp->ipcp.opts |= (1 << IPCP_OPT_ADDRESS);
2838	} else
2839		sp->ipcp.flags |= IPCP_MYADDR_SEEN;
2840	if (sp->enable_vj) {
2841		sp->ipcp.opts |= (1 << IPCP_OPT_COMPRESSION);
2842		sp->ipcp.max_state = MAX_STATES - 1;
2843		sp->ipcp.compress_cid = 1;
2844	}
2845	sppp_open_event(&ipcp, sp);
2846}
2847
2848static void
2849sppp_ipcp_close(struct sppp *sp)
2850{
2851	sppp_close_event(&ipcp, sp);
2852	if (sp->ipcp.flags & IPCP_MYADDR_DYN)
2853		/*
2854		 * My address was dynamic, clear it again.
2855		 */
2856		sppp_set_ip_addr(sp, 0L);
2857}
2858
2859static void
2860sppp_ipcp_TO(void *cookie)
2861{
2862	sppp_to_event(&ipcp, (struct sppp *)cookie);
2863}
2864
2865/*
2866 * Analyze a configure request.  Return true if it was agreeable, and
2867 * caused action sca, false if it has been rejected or nak'ed, and
2868 * caused action scn.  (The return value is used to make the state
2869 * transition decision in the state automaton.)
2870 */
2871static int
2872sppp_ipcp_RCR(struct sppp *sp, struct lcp_header *h, int len)
2873{
2874	u_char *buf, *r, *p;
2875	struct ifnet *ifp = &sp->pp_if;
2876	int rlen, origlen, debug = ifp->if_flags & IFF_DEBUG;
2877	u_long hisaddr, desiredaddr;
2878	int gotmyaddr = 0;
2879	int desiredcomp;
2880
2881	len -= 4;
2882	origlen = len;
2883	/*
2884	 * Make sure to allocate a buf that can at least hold a
2885	 * conf-nak with an `address' option.  We might need it below.
2886	 */
2887	buf = r = malloc ((len < 6? 6: len), M_TEMP, M_NOWAIT);
2888	if (! buf)
2889		return (0);
2890
2891	/* pass 1: see if we can recognize them */
2892	if (debug)
2893		log(LOG_DEBUG, SPP_FMT "ipcp parse opts: ",
2894		    SPP_ARGS(ifp));
2895	p = (void*) (h+1);
2896	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2897		if (debug)
2898			log(-1, " %s ", sppp_ipcp_opt_name(*p));
2899		switch (*p) {
2900		case IPCP_OPT_COMPRESSION:
2901			if (!sp->enable_vj) {
2902				/* VJ compression administratively disabled */
2903				if (debug)
2904					log(-1, "[locally disabled] ");
2905				break;
2906			}
2907			/*
2908			 * In theory, we should only conf-rej an
2909			 * option that is shorter than RFC 1618
2910			 * requires (i.e. < 4), and should conf-nak
2911			 * anything else that is not VJ.  However,
2912			 * since our algorithm always uses the
2913			 * original option to NAK it with new values,
2914			 * things would become more complicated.  In
2915			 * pratice, the only commonly implemented IP
2916			 * compression option is VJ anyway, so the
2917			 * difference is negligible.
2918			 */
2919			if (len >= 6 && p[1] == 6) {
2920				/*
2921				 * correctly formed compression option
2922				 * that could be VJ compression
2923				 */
2924				continue;
2925			}
2926			if (debug)
2927				log(-1,
2928				    "optlen %d [invalid/unsupported] ",
2929				    p[1]);
2930			break;
2931		case IPCP_OPT_ADDRESS:
2932			if (len >= 6 && p[1] == 6) {
2933				/* correctly formed address option */
2934				continue;
2935			}
2936			if (debug)
2937				log(-1, "[invalid] ");
2938			break;
2939		default:
2940			/* Others not supported. */
2941			if (debug)
2942				log(-1, "[rej] ");
2943			break;
2944		}
2945		/* Add the option to rejected list. */
2946		bcopy (p, r, p[1]);
2947		r += p[1];
2948		rlen += p[1];
2949	}
2950	if (rlen) {
2951		if (debug)
2952			log(-1, " send conf-rej\n");
2953		sppp_cp_send (sp, PPP_IPCP, CONF_REJ, h->ident, rlen, buf);
2954		return 0;
2955	} else if (debug)
2956		log(-1, "\n");
2957
2958	/* pass 2: parse option values */
2959	sppp_get_ip_addrs(sp, 0, &hisaddr, 0);
2960	if (debug)
2961		log(LOG_DEBUG, SPP_FMT "ipcp parse opt values: ",
2962		       SPP_ARGS(ifp));
2963	p = (void*) (h+1);
2964	len = origlen;
2965	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
2966		if (debug)
2967			log(-1, " %s ", sppp_ipcp_opt_name(*p));
2968		switch (*p) {
2969		case IPCP_OPT_COMPRESSION:
2970			desiredcomp = p[2] << 8 | p[3];
2971			/* We only support VJ */
2972			if (desiredcomp == IPCP_COMP_VJ) {
2973				if (debug)
2974					log(-1, "VJ [ack] ");
2975				sp->ipcp.flags |= IPCP_VJ;
2976				sl_compress_init(sp->pp_comp, p[4]);
2977				sp->ipcp.max_state = p[4];
2978				sp->ipcp.compress_cid = p[5];
2979				continue;
2980			}
2981			if (debug)
2982				log(-1,
2983				    "compproto %#04x [not supported] ",
2984				    desiredcomp);
2985			p[2] = IPCP_COMP_VJ >> 8;
2986			p[3] = IPCP_COMP_VJ;
2987			p[4] = sp->ipcp.max_state;
2988			p[5] = sp->ipcp.compress_cid;
2989			break;
2990		case IPCP_OPT_ADDRESS:
2991			/* This is the address he wants in his end */
2992			desiredaddr = p[2] << 24 | p[3] << 16 |
2993				p[4] << 8 | p[5];
2994			if (desiredaddr == hisaddr ||
2995			    (hisaddr >= 1 && hisaddr <= 254 && desiredaddr != 0)) {
2996				/*
2997				 * Peer's address is same as our value,
2998				 * or we have set it to 0.0.0.* to
2999				 * indicate that we do not really care,
3000				 * this is agreeable.  Gonna conf-ack
3001				 * it.
3002				 */
3003				if (debug)
3004					log(-1, "%s [ack] ",
3005						sppp_dotted_quad(hisaddr));
3006				/* record that we've seen it already */
3007				sp->ipcp.flags |= IPCP_HISADDR_SEEN;
3008				continue;
3009			}
3010			/*
3011			 * The address wasn't agreeable.  This is either
3012			 * he sent us 0.0.0.0, asking to assign him an
3013			 * address, or he send us another address not
3014			 * matching our value.  Either case, we gonna
3015			 * conf-nak it with our value.
3016			 * XXX: we should "rej" if hisaddr == 0
3017			 */
3018			if (debug) {
3019				if (desiredaddr == 0)
3020					log(-1, "[addr requested] ");
3021				else
3022					log(-1, "%s [not agreed] ",
3023						sppp_dotted_quad(desiredaddr));
3024
3025			}
3026			p[2] = hisaddr >> 24;
3027			p[3] = hisaddr >> 16;
3028			p[4] = hisaddr >> 8;
3029			p[5] = hisaddr;
3030			break;
3031		}
3032		/* Add the option to nak'ed list. */
3033		bcopy (p, r, p[1]);
3034		r += p[1];
3035		rlen += p[1];
3036	}
3037
3038	/*
3039	 * If we are about to conf-ack the request, but haven't seen
3040	 * his address so far, gonna conf-nak it instead, with the
3041	 * `address' option present and our idea of his address being
3042	 * filled in there, to request negotiation of both addresses.
3043	 *
3044	 * XXX This can result in an endless req - nak loop if peer
3045	 * doesn't want to send us his address.  Q: What should we do
3046	 * about it?  XXX  A: implement the max-failure counter.
3047	 */
3048	if (rlen == 0 && !(sp->ipcp.flags & IPCP_HISADDR_SEEN) && !gotmyaddr) {
3049		buf[0] = IPCP_OPT_ADDRESS;
3050		buf[1] = 6;
3051		buf[2] = hisaddr >> 24;
3052		buf[3] = hisaddr >> 16;
3053		buf[4] = hisaddr >> 8;
3054		buf[5] = hisaddr;
3055		rlen = 6;
3056		if (debug)
3057			log(-1, "still need hisaddr ");
3058	}
3059
3060	if (rlen) {
3061		if (debug)
3062			log(-1, " send conf-nak\n");
3063		sppp_cp_send (sp, PPP_IPCP, CONF_NAK, h->ident, rlen, buf);
3064	} else {
3065		if (debug)
3066			log(-1, " send conf-ack\n");
3067		sppp_cp_send (sp, PPP_IPCP, CONF_ACK,
3068			      h->ident, origlen, h+1);
3069	}
3070
3071	free (buf, M_TEMP);
3072	return (rlen == 0);
3073}
3074
3075/*
3076 * Analyze the IPCP Configure-Reject option list, and adjust our
3077 * negotiation.
3078 */
3079static void
3080sppp_ipcp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
3081{
3082	u_char *buf, *p;
3083	struct ifnet *ifp = &sp->pp_if;
3084	int debug = ifp->if_flags & IFF_DEBUG;
3085
3086	len -= 4;
3087	buf = malloc (len, M_TEMP, M_NOWAIT);
3088	if (!buf)
3089		return;
3090
3091	if (debug)
3092		log(LOG_DEBUG, SPP_FMT "ipcp rej opts: ",
3093		    SPP_ARGS(ifp));
3094
3095	p = (void*) (h+1);
3096	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
3097		if (debug)
3098			log(-1, " %s ", sppp_ipcp_opt_name(*p));
3099		switch (*p) {
3100		case IPCP_OPT_COMPRESSION:
3101			sp->ipcp.opts &= ~(1 << IPCP_OPT_COMPRESSION);
3102			break;
3103		case IPCP_OPT_ADDRESS:
3104			/*
3105			 * Peer doesn't grok address option.  This is
3106			 * bad.  XXX  Should we better give up here?
3107			 * XXX We could try old "addresses" option...
3108			 */
3109			sp->ipcp.opts &= ~(1 << IPCP_OPT_ADDRESS);
3110			break;
3111		}
3112	}
3113	if (debug)
3114		log(-1, "\n");
3115	free (buf, M_TEMP);
3116	return;
3117}
3118
3119/*
3120 * Analyze the IPCP Configure-NAK option list, and adjust our
3121 * negotiation.
3122 */
3123static void
3124sppp_ipcp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
3125{
3126	u_char *buf, *p;
3127	struct ifnet *ifp = &sp->pp_if;
3128	int debug = ifp->if_flags & IFF_DEBUG;
3129	int desiredcomp;
3130	u_long wantaddr;
3131
3132	len -= 4;
3133	buf = malloc (len, M_TEMP, M_NOWAIT);
3134	if (!buf)
3135		return;
3136
3137	if (debug)
3138		log(LOG_DEBUG, SPP_FMT "ipcp nak opts: ",
3139		    SPP_ARGS(ifp));
3140
3141	p = (void*) (h+1);
3142	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
3143		if (debug)
3144			log(-1, " %s ", sppp_ipcp_opt_name(*p));
3145		switch (*p) {
3146		case IPCP_OPT_COMPRESSION:
3147			if (len >= 6 && p[1] == 6) {
3148				desiredcomp = p[2] << 8 | p[3];
3149				if (debug)
3150					log(-1, "[wantcomp %#04x] ",
3151						desiredcomp);
3152				if (desiredcomp == IPCP_COMP_VJ) {
3153					sl_compress_init(sp->pp_comp, p[4]);
3154					sp->ipcp.max_state = p[4];
3155					sp->ipcp.compress_cid = p[5];
3156					if (debug)
3157						log(-1, "[agree] ");
3158				} else
3159					sp->ipcp.opts &=
3160						~(1 << IPCP_OPT_COMPRESSION);
3161			}
3162			break;
3163		case IPCP_OPT_ADDRESS:
3164			/*
3165			 * Peer doesn't like our local IP address.  See
3166			 * if we can do something for him.  We'll drop
3167			 * him our address then.
3168			 */
3169			if (len >= 6 && p[1] == 6) {
3170				wantaddr = p[2] << 24 | p[3] << 16 |
3171					p[4] << 8 | p[5];
3172				sp->ipcp.opts |= (1 << IPCP_OPT_ADDRESS);
3173				if (debug)
3174					log(-1, "[wantaddr %s] ",
3175					       sppp_dotted_quad(wantaddr));
3176				/*
3177				 * When doing dynamic address assignment,
3178				 * we accept his offer.  Otherwise, we
3179				 * ignore it and thus continue to negotiate
3180				 * our already existing value.
3181			 	 * XXX: Bogus, if he said no once, he'll
3182				 * just say no again, might as well die.
3183				 */
3184				if (sp->ipcp.flags & IPCP_MYADDR_DYN) {
3185					sppp_set_ip_addr(sp, wantaddr);
3186					if (debug)
3187						log(-1, "[agree] ");
3188					sp->ipcp.flags |= IPCP_MYADDR_SEEN;
3189				}
3190			}
3191			break;
3192		}
3193	}
3194	if (debug)
3195		log(-1, "\n");
3196	free (buf, M_TEMP);
3197	return;
3198}
3199
3200static void
3201sppp_ipcp_tlu(struct sppp *sp)
3202{
3203	/* we are up - notify isdn daemon */
3204	if (sp->pp_con)
3205		sp->pp_con(sp);
3206}
3207
3208static void
3209sppp_ipcp_tld(struct sppp *sp)
3210{
3211}
3212
3213static void
3214sppp_ipcp_tls(struct sppp *sp)
3215{
3216	/* indicate to LCP that it must stay alive */
3217	sp->lcp.protos |= (1 << IDX_IPCP);
3218}
3219
3220static void
3221sppp_ipcp_tlf(struct sppp *sp)
3222{
3223	/* we no longer need LCP */
3224	sp->lcp.protos &= ~(1 << IDX_IPCP);
3225	sppp_lcp_check_and_close(sp);
3226}
3227
3228static void
3229sppp_ipcp_scr(struct sppp *sp)
3230{
3231	char opt[6 /* compression */ + 6 /* address */];
3232	u_long ouraddr;
3233	int i = 0;
3234
3235	if (sp->ipcp.opts & (1 << IPCP_OPT_COMPRESSION)) {
3236		opt[i++] = IPCP_OPT_COMPRESSION;
3237		opt[i++] = 6;
3238		opt[i++] = IPCP_COMP_VJ >> 8;
3239		opt[i++] = IPCP_COMP_VJ;
3240		opt[i++] = sp->ipcp.max_state;
3241		opt[i++] = sp->ipcp.compress_cid;
3242	}
3243	if (sp->ipcp.opts & (1 << IPCP_OPT_ADDRESS)) {
3244		sppp_get_ip_addrs(sp, &ouraddr, 0, 0);
3245		opt[i++] = IPCP_OPT_ADDRESS;
3246		opt[i++] = 6;
3247		opt[i++] = ouraddr >> 24;
3248		opt[i++] = ouraddr >> 16;
3249		opt[i++] = ouraddr >> 8;
3250		opt[i++] = ouraddr;
3251	}
3252
3253	sp->confid[IDX_IPCP] = ++sp->pp_seq[IDX_IPCP];
3254	sppp_cp_send(sp, PPP_IPCP, CONF_REQ, sp->confid[IDX_IPCP], i, &opt);
3255}
3256
3257/*
3258 *--------------------------------------------------------------------------*
3259 *                                                                          *
3260 *                      The IPv6CP implementation.                          *
3261 *                                                                          *
3262 *--------------------------------------------------------------------------*
3263 */
3264
3265#ifdef INET6
3266static void
3267sppp_ipv6cp_init(struct sppp *sp)
3268{
3269	sp->ipv6cp.opts = 0;
3270	sp->ipv6cp.flags = 0;
3271	sp->state[IDX_IPV6CP] = STATE_INITIAL;
3272	sp->fail_counter[IDX_IPV6CP] = 0;
3273	sp->pp_seq[IDX_IPV6CP] = 0;
3274	sp->pp_rseq[IDX_IPV6CP] = 0;
3275#if defined(__NetBSD__)
3276	callout_init(&sp->ch[IDX_IPV6CP]);
3277#endif
3278#if defined(__FreeBSD__) && __FreeBSD__ >= 3
3279	callout_handle_init(&sp->ch[IDX_IPV6CP]);
3280#endif
3281}
3282
3283static void
3284sppp_ipv6cp_up(struct sppp *sp)
3285{
3286	sppp_up_event(&ipv6cp, sp);
3287}
3288
3289static void
3290sppp_ipv6cp_down(struct sppp *sp)
3291{
3292	sppp_down_event(&ipv6cp, sp);
3293}
3294
3295static void
3296sppp_ipv6cp_open(struct sppp *sp)
3297{
3298	STDDCL;
3299	struct in6_addr myaddr, hisaddr;
3300
3301#ifdef IPV6CP_MYIFID_DYN
3302	sp->ipv6cp.flags &= ~(IPV6CP_MYIFID_SEEN|IPV6CP_MYIFID_DYN);
3303#else
3304	sp->ipv6cp.flags &= ~IPV6CP_MYIFID_SEEN;
3305#endif
3306
3307	sppp_get_ip6_addrs(sp, &myaddr, &hisaddr, 0);
3308	/*
3309	 * If we don't have our address, this probably means our
3310	 * interface doesn't want to talk IPv6 at all.  (This could
3311	 * be the case if somebody wants to speak only IPX, for
3312	 * example.)  Don't open IPv6CP in this case.
3313	 */
3314	if (IN6_IS_ADDR_UNSPECIFIED(&myaddr)) {
3315		/* XXX this message should go away */
3316		if (debug)
3317			log(LOG_DEBUG, SPP_FMT "ipv6cp_open(): no IPv6 interface\n",
3318			    SPP_ARGS(ifp));
3319		return;
3320	}
3321
3322	sp->ipv6cp.flags |= IPV6CP_MYIFID_SEEN;
3323	sp->ipv6cp.opts |= (1 << IPV6CP_OPT_IFID);
3324	sppp_open_event(&ipv6cp, sp);
3325}
3326
3327static void
3328sppp_ipv6cp_close(struct sppp *sp)
3329{
3330	sppp_close_event(&ipv6cp, sp);
3331}
3332
3333static void
3334sppp_ipv6cp_TO(void *cookie)
3335{
3336	sppp_to_event(&ipv6cp, (struct sppp *)cookie);
3337}
3338
3339/*
3340 * Analyze a configure request.  Return true if it was agreeable, and
3341 * caused action sca, false if it has been rejected or nak'ed, and
3342 * caused action scn.  (The return value is used to make the state
3343 * transition decision in the state automaton.)
3344 */
3345static int
3346sppp_ipv6cp_RCR(struct sppp *sp, struct lcp_header *h, int len)
3347{
3348	u_char *buf, *r, *p;
3349	struct ifnet *ifp = &sp->pp_if;
3350	int rlen, origlen, debug = ifp->if_flags & IFF_DEBUG;
3351	struct in6_addr myaddr, desiredaddr, suggestaddr;
3352	int ifidcount;
3353	int type;
3354	int collision, nohisaddr;
3355
3356	len -= 4;
3357	origlen = len;
3358	/*
3359	 * Make sure to allocate a buf that can at least hold a
3360	 * conf-nak with an `address' option.  We might need it below.
3361	 */
3362	buf = r = malloc ((len < 6? 6: len), M_TEMP, M_NOWAIT);
3363	if (! buf)
3364		return (0);
3365
3366	/* pass 1: see if we can recognize them */
3367	if (debug)
3368		log(LOG_DEBUG, SPP_FMT "ipv6cp parse opts:",
3369		    SPP_ARGS(ifp));
3370	p = (void*) (h+1);
3371	ifidcount = 0;
3372	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
3373		if (debug)
3374			log(-1, " %s", sppp_ipv6cp_opt_name(*p));
3375		switch (*p) {
3376		case IPV6CP_OPT_IFID:
3377			if (len >= 10 && p[1] == 10 && ifidcount == 0) {
3378				/* correctly formed address option */
3379				ifidcount++;
3380				continue;
3381			}
3382			if (debug)
3383				log(-1, " [invalid]");
3384			break;
3385#ifdef notyet
3386		case IPV6CP_OPT_COMPRESSION:
3387			if (len >= 4 && p[1] >= 4) {
3388				/* correctly formed compress option */
3389				continue;
3390			}
3391			if (debug)
3392				log(-1, " [invalid]");
3393			break;
3394#endif
3395		default:
3396			/* Others not supported. */
3397			if (debug)
3398				log(-1, " [rej]");
3399			break;
3400		}
3401		/* Add the option to rejected list. */
3402		bcopy (p, r, p[1]);
3403		r += p[1];
3404		rlen += p[1];
3405	}
3406	if (rlen) {
3407		if (debug)
3408			log(-1, " send conf-rej\n");
3409		sppp_cp_send (sp, PPP_IPV6CP, CONF_REJ, h->ident, rlen, buf);
3410		goto end;
3411	} else if (debug)
3412		log(-1, "\n");
3413
3414	/* pass 2: parse option values */
3415	sppp_get_ip6_addrs(sp, &myaddr, 0, 0);
3416	if (debug)
3417		log(LOG_DEBUG, SPP_FMT "ipv6cp parse opt values: ",
3418		    SPP_ARGS(ifp));
3419	p = (void*) (h+1);
3420	len = origlen;
3421	type = CONF_ACK;
3422	for (rlen=0; len>1 && p[1]; len-=p[1], p+=p[1]) {
3423		if (debug)
3424			log(-1, " %s", sppp_ipv6cp_opt_name(*p));
3425		switch (*p) {
3426#ifdef notyet
3427		case IPV6CP_OPT_COMPRESSION:
3428			continue;
3429#endif
3430		case IPV6CP_OPT_IFID:
3431			bzero(&desiredaddr, sizeof(desiredaddr));
3432			bcopy(&p[2], &desiredaddr.s6_addr[8], 8);
3433			collision = (bcmp(&desiredaddr.s6_addr[8],
3434					  &myaddr.s6_addr[8], 8) == 0);
3435			nohisaddr = IN6_IS_ADDR_UNSPECIFIED(&desiredaddr);
3436
3437			desiredaddr.s6_addr16[0] = htons(0xfe80);
3438			desiredaddr.s6_addr16[1] = htons(sp->pp_if.if_index);
3439
3440			if (!collision && !nohisaddr) {
3441				/* no collision, hisaddr known - Conf-Ack */
3442				type = CONF_ACK;
3443
3444				if (debug) {
3445					log(-1, " %s [%s]",
3446					       ip6_sprintf(&desiredaddr),
3447					       sppp_cp_type_name(type));
3448				}
3449				continue;
3450			}
3451
3452			bzero(&suggestaddr, sizeof(&suggestaddr));
3453			if (collision && nohisaddr) {
3454				/* collision, hisaddr unknown - Conf-Rej */
3455				type = CONF_REJ;
3456				bzero(&p[2], 8);
3457			} else {
3458				/*
3459				 * - no collision, hisaddr unknown, or
3460				 * - collision, hisaddr known
3461				 * Conf-Nak, suggest hisaddr
3462				 */
3463				type = CONF_NAK;
3464				sppp_suggest_ip6_addr(sp, &suggestaddr);
3465				bcopy(&suggestaddr.s6_addr[8], &p[2], 8);
3466			}
3467			if (debug)
3468				log(-1, " %s [%s]", ip6_sprintf(&desiredaddr),
3469				       sppp_cp_type_name(type));
3470			break;
3471		}
3472		/* Add the option to nak'ed list. */
3473		bcopy (p, r, p[1]);
3474		r += p[1];
3475		rlen += p[1];
3476	}
3477
3478	if (rlen == 0 && type == CONF_ACK) {
3479		if (debug)
3480			log(-1, " send %s\n", sppp_cp_type_name(type));
3481		sppp_cp_send (sp, PPP_IPV6CP, type, h->ident, origlen, h+1);
3482	} else {
3483#ifdef DIAGNOSTIC
3484		if (type == CONF_ACK)
3485			panic("IPv6CP RCR: CONF_ACK with non-zero rlen");
3486#endif
3487
3488		if (debug) {
3489			log(-1, " send %s suggest %s\n",
3490			       sppp_cp_type_name(type), ip6_sprintf(&suggestaddr));
3491		}
3492		sppp_cp_send (sp, PPP_IPV6CP, type, h->ident, rlen, buf);
3493	}
3494
3495 end:
3496	free (buf, M_TEMP);
3497	return (rlen == 0);
3498}
3499
3500/*
3501 * Analyze the IPv6CP Configure-Reject option list, and adjust our
3502 * negotiation.
3503 */
3504static void
3505sppp_ipv6cp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
3506{
3507	u_char *buf, *p;
3508	struct ifnet *ifp = &sp->pp_if;
3509	int debug = ifp->if_flags & IFF_DEBUG;
3510
3511	len -= 4;
3512	buf = malloc (len, M_TEMP, M_NOWAIT);
3513	if (!buf)
3514		return;
3515
3516	if (debug)
3517		log(LOG_DEBUG, SPP_FMT "ipv6cp rej opts:",
3518		    SPP_ARGS(ifp));
3519
3520	p = (void*) (h+1);
3521	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
3522		if (debug)
3523			log(-1, " %s", sppp_ipv6cp_opt_name(*p));
3524		switch (*p) {
3525		case IPV6CP_OPT_IFID:
3526			/*
3527			 * Peer doesn't grok address option.  This is
3528			 * bad.  XXX  Should we better give up here?
3529			 */
3530			sp->ipv6cp.opts &= ~(1 << IPV6CP_OPT_IFID);
3531			break;
3532#ifdef notyet
3533		case IPV6CP_OPT_COMPRESS:
3534			sp->ipv6cp.opts &= ~(1 << IPV6CP_OPT_COMPRESS);
3535			break;
3536#endif
3537		}
3538	}
3539	if (debug)
3540		log(-1, "\n");
3541	free (buf, M_TEMP);
3542	return;
3543}
3544
3545/*
3546 * Analyze the IPv6CP Configure-NAK option list, and adjust our
3547 * negotiation.
3548 */
3549static void
3550sppp_ipv6cp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
3551{
3552	u_char *buf, *p;
3553	struct ifnet *ifp = &sp->pp_if;
3554	int debug = ifp->if_flags & IFF_DEBUG;
3555	struct in6_addr suggestaddr;
3556
3557	len -= 4;
3558	buf = malloc (len, M_TEMP, M_NOWAIT);
3559	if (!buf)
3560		return;
3561
3562	if (debug)
3563		log(LOG_DEBUG, SPP_FMT "ipv6cp nak opts:",
3564		    SPP_ARGS(ifp));
3565
3566	p = (void*) (h+1);
3567	for (; len > 1 && p[1]; len -= p[1], p += p[1]) {
3568		if (debug)
3569			log(-1, " %s", sppp_ipv6cp_opt_name(*p));
3570		switch (*p) {
3571		case IPV6CP_OPT_IFID:
3572			/*
3573			 * Peer doesn't like our local ifid.  See
3574			 * if we can do something for him.  We'll drop
3575			 * him our address then.
3576			 */
3577			if (len < 10 || p[1] != 10)
3578				break;
3579			bzero(&suggestaddr, sizeof(suggestaddr));
3580			suggestaddr.s6_addr16[0] = htons(0xfe80);
3581			suggestaddr.s6_addr16[1] = htons(sp->pp_if.if_index);
3582			bcopy(&p[2], &suggestaddr.s6_addr[8], 8);
3583
3584			sp->ipv6cp.opts |= (1 << IPV6CP_OPT_IFID);
3585			if (debug)
3586				log(-1, " [suggestaddr %s]",
3587				       ip6_sprintf(&suggestaddr));
3588#ifdef IPV6CP_MYIFID_DYN
3589			/*
3590			 * When doing dynamic address assignment,
3591			 * we accept his offer.
3592			 */
3593			if (sp->ipv6cp.flags & IPV6CP_MYIFID_DYN) {
3594				struct in6_addr lastsuggest;
3595				/*
3596				 * If <suggested myaddr from peer> equals to
3597				 * <hisaddr we have suggested last time>,
3598				 * we have a collision.  generate new random
3599				 * ifid.
3600				 */
3601				sppp_suggest_ip6_addr(&lastsuggest);
3602				if (IN6_ARE_ADDR_EQUAL(&suggestaddr,
3603						       lastsuggest)) {
3604					if (debug)
3605						log(-1, " [random]");
3606					sppp_gen_ip6_addr(sp, &suggestaddr);
3607				}
3608				sppp_set_ip6_addr(sp, &suggestaddr, 0);
3609				if (debug)
3610					log(-1, " [agree]");
3611				sp->ipv6cp.flags |= IPV6CP_MYIFID_SEEN;
3612			}
3613#else
3614			/*
3615			 * Since we do not do dynamic address assignment,
3616			 * we ignore it and thus continue to negotiate
3617			 * our already existing value.  This can possibly
3618			 * go into infinite request-reject loop.
3619			 *
3620			 * This is not likely because we normally use
3621			 * ifid based on MAC-address.
3622			 * If you have no ethernet card on the node, too bad.
3623			 * XXX should we use fail_counter?
3624			 */
3625#endif
3626			break;
3627#ifdef notyet
3628		case IPV6CP_OPT_COMPRESS:
3629			/*
3630			 * Peer wants different compression parameters.
3631			 */
3632			break;
3633#endif
3634		}
3635	}
3636	if (debug)
3637		log(-1, "\n");
3638	free (buf, M_TEMP);
3639	return;
3640}
3641static void
3642sppp_ipv6cp_tlu(struct sppp *sp)
3643{
3644	/* we are up - notify isdn daemon */
3645	if (sp->pp_con)
3646		sp->pp_con(sp);
3647}
3648
3649static void
3650sppp_ipv6cp_tld(struct sppp *sp)
3651{
3652}
3653
3654static void
3655sppp_ipv6cp_tls(struct sppp *sp)
3656{
3657	/* indicate to LCP that it must stay alive */
3658	sp->lcp.protos |= (1 << IDX_IPV6CP);
3659}
3660
3661static void
3662sppp_ipv6cp_tlf(struct sppp *sp)
3663{
3664
3665#if 0	/* need #if 0 to close IPv6CP properly */
3666	/* we no longer need LCP */
3667	sp->lcp.protos &= ~(1 << IDX_IPV6CP);
3668	sppp_lcp_check_and_close(sp);
3669#endif
3670}
3671
3672static void
3673sppp_ipv6cp_scr(struct sppp *sp)
3674{
3675	char opt[10 /* ifid */ + 4 /* compression, minimum */];
3676	struct in6_addr ouraddr;
3677	int i = 0;
3678
3679	if (sp->ipv6cp.opts & (1 << IPV6CP_OPT_IFID)) {
3680		sppp_get_ip6_addrs(sp, &ouraddr, 0, 0);
3681		opt[i++] = IPV6CP_OPT_IFID;
3682		opt[i++] = 10;
3683		bcopy(&ouraddr.s6_addr[8], &opt[i], 8);
3684		i += 8;
3685	}
3686
3687#ifdef notyet
3688	if (sp->ipv6cp.opts & (1 << IPV6CP_OPT_COMPRESSION)) {
3689		opt[i++] = IPV6CP_OPT_COMPRESSION;
3690		opt[i++] = 4;
3691		opt[i++] = 0;   /* TBD */
3692		opt[i++] = 0;   /* TBD */
3693		/* variable length data may follow */
3694	}
3695#endif
3696
3697	sp->confid[IDX_IPV6CP] = ++sp->pp_seq[IDX_IPV6CP];
3698	sppp_cp_send(sp, PPP_IPV6CP, CONF_REQ, sp->confid[IDX_IPV6CP], i, &opt);
3699}
3700#else /*INET6*/
3701static void sppp_ipv6cp_init(struct sppp *sp)
3702{
3703}
3704
3705static void sppp_ipv6cp_up(struct sppp *sp)
3706{
3707}
3708
3709static void sppp_ipv6cp_down(struct sppp *sp)
3710{
3711}
3712
3713
3714static void sppp_ipv6cp_open(struct sppp *sp)
3715{
3716}
3717
3718static void sppp_ipv6cp_close(struct sppp *sp)
3719{
3720}
3721
3722static void sppp_ipv6cp_TO(void *sp)
3723{
3724}
3725
3726static int sppp_ipv6cp_RCR(struct sppp *sp, struct lcp_header *h, int len)
3727{
3728	return 0;
3729}
3730
3731static void sppp_ipv6cp_RCN_rej(struct sppp *sp, struct lcp_header *h, int len)
3732{
3733}
3734
3735static void sppp_ipv6cp_RCN_nak(struct sppp *sp, struct lcp_header *h, int len)
3736{
3737}
3738
3739static void sppp_ipv6cp_tlu(struct sppp *sp)
3740{
3741}
3742
3743static void sppp_ipv6cp_tld(struct sppp *sp)
3744{
3745}
3746
3747static void sppp_ipv6cp_tls(struct sppp *sp)
3748{
3749}
3750
3751static void sppp_ipv6cp_tlf(struct sppp *sp)
3752{
3753}
3754
3755static void sppp_ipv6cp_scr(struct sppp *sp)
3756{
3757}
3758#endif /*INET6*/
3759
3760/*
3761 *--------------------------------------------------------------------------*
3762 *                                                                          *
3763 *                        The CHAP implementation.                          *
3764 *                                                                          *
3765 *--------------------------------------------------------------------------*
3766 */
3767
3768/*
3769 * The authentication protocols don't employ a full-fledged state machine as
3770 * the control protocols do, since they do have Open and Close events, but
3771 * not Up and Down, nor are they explicitly terminated.  Also, use of the
3772 * authentication protocols may be different in both directions (this makes
3773 * sense, think of a machine that never accepts incoming calls but only
3774 * calls out, it doesn't require the called party to authenticate itself).
3775 *
3776 * Our state machine for the local authentication protocol (we are requesting
3777 * the peer to authenticate) looks like:
3778 *
3779 *						    RCA-
3780 *	      +--------------------------------------------+
3781 *	      V					    scn,tld|
3782 *	  +--------+			       Close   +---------+ RCA+
3783 *	  |	   |<----------------------------------|	 |------+
3784 *   +--->| Closed |				TO*    | Opened	 | sca	|
3785 *   |	  |	   |-----+		       +-------|	 |<-----+
3786 *   |	  +--------+ irc |		       |       +---------+
3787 *   |	    ^		 |		       |	   ^
3788 *   |	    |		 |		       |	   |
3789 *   |	    |		 |		       |	   |
3790 *   |	 TO-|		 |		       |	   |
3791 *   |	    |tld  TO+	 V		       |	   |
3792 *   |	    |	+------->+		       |	   |
3793 *   |	    |	|	 |		       |	   |
3794 *   |	  +--------+	 V		       |	   |
3795 *   |	  |	   |<----+<--------------------+	   |
3796 *   |	  | Req-   | scr				   |
3797 *   |	  | Sent   |					   |
3798 *   |	  |	   |					   |
3799 *   |	  +--------+					   |
3800 *   | RCA- |	| RCA+					   |
3801 *   +------+	+------------------------------------------+
3802 *   scn,tld	  sca,irc,ict,tlu
3803 *
3804 *
3805 *   with:
3806 *
3807 *	Open:	LCP reached authentication phase
3808 *	Close:	LCP reached terminate phase
3809 *
3810 *	RCA+:	received reply (pap-req, chap-response), acceptable
3811 *	RCN:	received reply (pap-req, chap-response), not acceptable
3812 *	TO+:	timeout with restart counter >= 0
3813 *	TO-:	timeout with restart counter < 0
3814 *	TO*:	reschedule timeout for CHAP
3815 *
3816 *	scr:	send request packet (none for PAP, chap-challenge)
3817 *	sca:	send ack packet (pap-ack, chap-success)
3818 *	scn:	send nak packet (pap-nak, chap-failure)
3819 *	ict:	initialize re-challenge timer (CHAP only)
3820 *
3821 *	tlu:	this-layer-up, LCP reaches network phase
3822 *	tld:	this-layer-down, LCP enters terminate phase
3823 *
3824 * Note that in CHAP mode, after sending a new challenge, while the state
3825 * automaton falls back into Req-Sent state, it doesn't signal a tld
3826 * event to LCP, so LCP remains in network phase.  Only after not getting
3827 * any response (or after getting an unacceptable response), CHAP closes,
3828 * causing LCP to enter terminate phase.
3829 *
3830 * With PAP, there is no initial request that can be sent.  The peer is
3831 * expected to send one based on the successful negotiation of PAP as
3832 * the authentication protocol during the LCP option negotiation.
3833 *
3834 * Incoming authentication protocol requests (remote requests
3835 * authentication, we are peer) don't employ a state machine at all,
3836 * they are simply answered.  Some peers [Ascend P50 firmware rev
3837 * 4.50] react allergically when sending IPCP requests while they are
3838 * still in authentication phase (thereby violating the standard that
3839 * demands that these NCP packets are to be discarded), so we keep
3840 * track of the peer demanding us to authenticate, and only proceed to
3841 * phase network once we've seen a positive acknowledge for the
3842 * authentication.
3843 */
3844
3845/*
3846 * Handle incoming CHAP packets.
3847 */
3848void
3849sppp_chap_input(struct sppp *sp, struct mbuf *m)
3850{
3851	STDDCL;
3852	struct lcp_header *h;
3853	int len, x;
3854	u_char *value, *name, digest[AUTHKEYLEN], dsize;
3855	int value_len, name_len;
3856	MD5_CTX ctx;
3857
3858	len = m->m_pkthdr.len;
3859	if (len < 4) {
3860		if (debug)
3861			log(LOG_DEBUG,
3862			    SPP_FMT "chap invalid packet length: %d bytes\n",
3863			    SPP_ARGS(ifp), len);
3864		return;
3865	}
3866	h = mtod (m, struct lcp_header*);
3867	if (len > ntohs (h->len))
3868		len = ntohs (h->len);
3869
3870	switch (h->type) {
3871	/* challenge, failure and success are his authproto */
3872	case CHAP_CHALLENGE:
3873		value = 1 + (u_char*)(h+1);
3874		value_len = value[-1];
3875		name = value + value_len;
3876		name_len = len - value_len - 5;
3877		if (name_len < 0) {
3878			if (debug) {
3879				log(LOG_DEBUG,
3880				    SPP_FMT "chap corrupted challenge "
3881				    "<%s id=0x%x len=%d",
3882				    SPP_ARGS(ifp),
3883				    sppp_auth_type_name(PPP_CHAP, h->type),
3884				    h->ident, ntohs(h->len));
3885				sppp_print_bytes((u_char*) (h+1), len-4);
3886				log(-1, ">\n");
3887			}
3888			break;
3889		}
3890
3891		if (debug) {
3892			log(LOG_DEBUG,
3893			    SPP_FMT "chap input <%s id=0x%x len=%d name=",
3894			    SPP_ARGS(ifp),
3895			    sppp_auth_type_name(PPP_CHAP, h->type), h->ident,
3896			    ntohs(h->len));
3897			sppp_print_string((char*) name, name_len);
3898			log(-1, " value-size=%d value=", value_len);
3899			sppp_print_bytes(value, value_len);
3900			log(-1, ">\n");
3901		}
3902
3903		/* Compute reply value. */
3904		MD5Init(&ctx);
3905		MD5Update(&ctx, &h->ident, 1);
3906		MD5Update(&ctx, sp->myauth.secret,
3907			  sppp_strnlen(sp->myauth.secret, AUTHKEYLEN));
3908		MD5Update(&ctx, value, value_len);
3909		MD5Final(digest, &ctx);
3910		dsize = sizeof digest;
3911
3912		sppp_auth_send(&chap, sp, CHAP_RESPONSE, h->ident,
3913			       sizeof dsize, (const char *)&dsize,
3914			       sizeof digest, digest,
3915			       (size_t)sppp_strnlen(sp->myauth.name, AUTHNAMELEN),
3916			       sp->myauth.name,
3917			       0);
3918		break;
3919
3920	case CHAP_SUCCESS:
3921		if (debug) {
3922			log(LOG_DEBUG, SPP_FMT "chap success",
3923			    SPP_ARGS(ifp));
3924			if (len > 4) {
3925				log(-1, ": ");
3926				sppp_print_string((char*)(h + 1), len - 4);
3927			}
3928			log(-1, "\n");
3929		}
3930		x = splimp();
3931		sp->pp_flags &= ~PP_NEEDAUTH;
3932		if (sp->myauth.proto == PPP_CHAP &&
3933		    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) &&
3934		    (sp->lcp.protos & (1 << IDX_CHAP)) == 0) {
3935			/*
3936			 * We are authenticator for CHAP but didn't
3937			 * complete yet.  Leave it to tlu to proceed
3938			 * to network phase.
3939			 */
3940			splx(x);
3941			break;
3942		}
3943		splx(x);
3944		sppp_phase_network(sp);
3945		break;
3946
3947	case CHAP_FAILURE:
3948		if (debug) {
3949			log(LOG_INFO, SPP_FMT "chap failure",
3950			    SPP_ARGS(ifp));
3951			if (len > 4) {
3952				log(-1, ": ");
3953				sppp_print_string((char*)(h + 1), len - 4);
3954			}
3955			log(-1, "\n");
3956		} else
3957			log(LOG_INFO, SPP_FMT "chap failure\n",
3958			    SPP_ARGS(ifp));
3959		/* await LCP shutdown by authenticator */
3960		break;
3961
3962	/* response is my authproto */
3963	case CHAP_RESPONSE:
3964		value = 1 + (u_char*)(h+1);
3965		value_len = value[-1];
3966		name = value + value_len;
3967		name_len = len - value_len - 5;
3968		if (name_len < 0) {
3969			if (debug) {
3970				log(LOG_DEBUG,
3971				    SPP_FMT "chap corrupted response "
3972				    "<%s id=0x%x len=%d",
3973				    SPP_ARGS(ifp),
3974				    sppp_auth_type_name(PPP_CHAP, h->type),
3975				    h->ident, ntohs(h->len));
3976				sppp_print_bytes((u_char*)(h+1), len-4);
3977				log(-1, ">\n");
3978			}
3979			break;
3980		}
3981		if (h->ident != sp->confid[IDX_CHAP]) {
3982			if (debug)
3983				log(LOG_DEBUG,
3984				    SPP_FMT "chap dropping response for old ID "
3985				    "(got %d, expected %d)\n",
3986				    SPP_ARGS(ifp),
3987				    h->ident, sp->confid[IDX_CHAP]);
3988			break;
3989		}
3990		if (name_len != sppp_strnlen(sp->hisauth.name, AUTHNAMELEN)
3991		    || bcmp(name, sp->hisauth.name, name_len) != 0) {
3992			log(LOG_INFO, SPP_FMT "chap response, his name ",
3993			    SPP_ARGS(ifp));
3994			sppp_print_string(name, name_len);
3995			log(-1, " != expected ");
3996			sppp_print_string(sp->hisauth.name,
3997					  sppp_strnlen(sp->hisauth.name, AUTHNAMELEN));
3998			log(-1, "\n");
3999		}
4000		if (debug) {
4001			log(LOG_DEBUG, SPP_FMT "chap input(%s) "
4002			    "<%s id=0x%x len=%d name=",
4003			    SPP_ARGS(ifp),
4004			    sppp_state_name(sp->state[IDX_CHAP]),
4005			    sppp_auth_type_name(PPP_CHAP, h->type),
4006			    h->ident, ntohs (h->len));
4007			sppp_print_string((char*)name, name_len);
4008			log(-1, " value-size=%d value=", value_len);
4009			sppp_print_bytes(value, value_len);
4010			log(-1, ">\n");
4011		}
4012		if (value_len != AUTHKEYLEN) {
4013			if (debug)
4014				log(LOG_DEBUG,
4015				    SPP_FMT "chap bad hash value length: "
4016				    "%d bytes, should be %d\n",
4017				    SPP_ARGS(ifp), value_len,
4018				    AUTHKEYLEN);
4019			break;
4020		}
4021
4022		MD5Init(&ctx);
4023		MD5Update(&ctx, &h->ident, 1);
4024		MD5Update(&ctx, sp->hisauth.secret,
4025			  sppp_strnlen(sp->hisauth.secret, AUTHKEYLEN));
4026		MD5Update(&ctx, sp->myauth.challenge, AUTHKEYLEN);
4027		MD5Final(digest, &ctx);
4028
4029#define FAILMSG "Failed..."
4030#define SUCCMSG "Welcome!"
4031
4032		if (value_len != sizeof digest ||
4033		    bcmp(digest, value, value_len) != 0) {
4034			/* action scn, tld */
4035			sppp_auth_send(&chap, sp, CHAP_FAILURE, h->ident,
4036				       sizeof(FAILMSG) - 1, (u_char *)FAILMSG,
4037				       0);
4038			chap.tld(sp);
4039			break;
4040		}
4041		/* action sca, perhaps tlu */
4042		if (sp->state[IDX_CHAP] == STATE_REQ_SENT ||
4043		    sp->state[IDX_CHAP] == STATE_OPENED)
4044			sppp_auth_send(&chap, sp, CHAP_SUCCESS, h->ident,
4045				       sizeof(SUCCMSG) - 1, (u_char *)SUCCMSG,
4046				       0);
4047		if (sp->state[IDX_CHAP] == STATE_REQ_SENT) {
4048			sppp_cp_change_state(&chap, sp, STATE_OPENED);
4049			chap.tlu(sp);
4050		}
4051		break;
4052
4053	default:
4054		/* Unknown CHAP packet type -- ignore. */
4055		if (debug) {
4056			log(LOG_DEBUG, SPP_FMT "chap unknown input(%s) "
4057			    "<0x%x id=0x%xh len=%d",
4058			    SPP_ARGS(ifp),
4059			    sppp_state_name(sp->state[IDX_CHAP]),
4060			    h->type, h->ident, ntohs(h->len));
4061			sppp_print_bytes((u_char*)(h+1), len-4);
4062			log(-1, ">\n");
4063		}
4064		break;
4065
4066	}
4067}
4068
4069static void
4070sppp_chap_init(struct sppp *sp)
4071{
4072	/* Chap doesn't have STATE_INITIAL at all. */
4073	sp->state[IDX_CHAP] = STATE_CLOSED;
4074	sp->fail_counter[IDX_CHAP] = 0;
4075	sp->pp_seq[IDX_CHAP] = 0;
4076	sp->pp_rseq[IDX_CHAP] = 0;
4077#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4078	callout_handle_init(&sp->ch[IDX_CHAP]);
4079#endif
4080}
4081
4082static void
4083sppp_chap_open(struct sppp *sp)
4084{
4085	if (sp->myauth.proto == PPP_CHAP &&
4086	    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0) {
4087		/* we are authenticator for CHAP, start it */
4088		chap.scr(sp);
4089		sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
4090		sppp_cp_change_state(&chap, sp, STATE_REQ_SENT);
4091	}
4092	/* nothing to be done if we are peer, await a challenge */
4093}
4094
4095static void
4096sppp_chap_close(struct sppp *sp)
4097{
4098	if (sp->state[IDX_CHAP] != STATE_CLOSED)
4099		sppp_cp_change_state(&chap, sp, STATE_CLOSED);
4100}
4101
4102static void
4103sppp_chap_TO(void *cookie)
4104{
4105	struct sppp *sp = (struct sppp *)cookie;
4106	STDDCL;
4107	int s;
4108
4109	s = splimp();
4110	if (debug)
4111		log(LOG_DEBUG, SPP_FMT "chap TO(%s) rst_counter = %d\n",
4112		    SPP_ARGS(ifp),
4113		    sppp_state_name(sp->state[IDX_CHAP]),
4114		    sp->rst_counter[IDX_CHAP]);
4115
4116	if (--sp->rst_counter[IDX_CHAP] < 0)
4117		/* TO- event */
4118		switch (sp->state[IDX_CHAP]) {
4119		case STATE_REQ_SENT:
4120			chap.tld(sp);
4121			sppp_cp_change_state(&chap, sp, STATE_CLOSED);
4122			break;
4123		}
4124	else
4125		/* TO+ (or TO*) event */
4126		switch (sp->state[IDX_CHAP]) {
4127		case STATE_OPENED:
4128			/* TO* event */
4129			sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
4130			/* fall through */
4131		case STATE_REQ_SENT:
4132			chap.scr(sp);
4133			/* sppp_cp_change_state() will restart the timer */
4134			sppp_cp_change_state(&chap, sp, STATE_REQ_SENT);
4135			break;
4136		}
4137
4138	splx(s);
4139}
4140
4141static void
4142sppp_chap_tlu(struct sppp *sp)
4143{
4144	STDDCL;
4145	int i, x;
4146
4147	i = 0;
4148	sp->rst_counter[IDX_CHAP] = sp->lcp.max_configure;
4149
4150	/*
4151	 * Some broken CHAP implementations (Conware CoNet, firmware
4152	 * 4.0.?) don't want to re-authenticate their CHAP once the
4153	 * initial challenge-response exchange has taken place.
4154	 * Provide for an option to avoid rechallenges.
4155	 */
4156	if ((sp->hisauth.flags & AUTHFLAG_NORECHALLENGE) == 0) {
4157		/*
4158		 * Compute the re-challenge timeout.  This will yield
4159		 * a number between 300 and 810 seconds.
4160		 */
4161		i = 300 + ((unsigned)(random() & 0xff00) >> 7);
4162		TIMEOUT(chap.TO, (void *)sp, i * hz, sp->ch[IDX_CHAP]);
4163	}
4164
4165	if (debug) {
4166		log(LOG_DEBUG,
4167		    SPP_FMT "chap %s, ",
4168		    SPP_ARGS(ifp),
4169		    sp->pp_phase == PHASE_NETWORK? "reconfirmed": "tlu");
4170		if ((sp->hisauth.flags & AUTHFLAG_NORECHALLENGE) == 0)
4171			log(-1, "next re-challenge in %d seconds\n", i);
4172		else
4173			log(-1, "re-challenging supressed\n");
4174	}
4175
4176	x = splimp();
4177	/* indicate to LCP that we need to be closed down */
4178	sp->lcp.protos |= (1 << IDX_CHAP);
4179
4180	if (sp->pp_flags & PP_NEEDAUTH) {
4181		/*
4182		 * Remote is authenticator, but his auth proto didn't
4183		 * complete yet.  Defer the transition to network
4184		 * phase.
4185		 */
4186		splx(x);
4187		return;
4188	}
4189	splx(x);
4190
4191	/*
4192	 * If we are already in phase network, we are done here.  This
4193	 * is the case if this is a dummy tlu event after a re-challenge.
4194	 */
4195	if (sp->pp_phase != PHASE_NETWORK)
4196		sppp_phase_network(sp);
4197}
4198
4199static void
4200sppp_chap_tld(struct sppp *sp)
4201{
4202	STDDCL;
4203
4204	if (debug)
4205		log(LOG_DEBUG, SPP_FMT "chap tld\n", SPP_ARGS(ifp));
4206	UNTIMEOUT(chap.TO, (void *)sp, sp->ch[IDX_CHAP]);
4207	sp->lcp.protos &= ~(1 << IDX_CHAP);
4208
4209	lcp.Close(sp);
4210}
4211
4212static void
4213sppp_chap_scr(struct sppp *sp)
4214{
4215	u_long *ch, seed;
4216	u_char clen;
4217
4218	/* Compute random challenge. */
4219	ch = (u_long *)sp->myauth.challenge;
4220#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4221	read_random(&seed, sizeof seed);
4222#else
4223	{
4224	struct timeval tv;
4225	microtime(&tv);
4226	seed = tv.tv_sec ^ tv.tv_usec;
4227	}
4228#endif
4229	ch[0] = seed ^ random();
4230	ch[1] = seed ^ random();
4231	ch[2] = seed ^ random();
4232	ch[3] = seed ^ random();
4233	clen = AUTHKEYLEN;
4234
4235	sp->confid[IDX_CHAP] = ++sp->pp_seq[IDX_CHAP];
4236
4237	sppp_auth_send(&chap, sp, CHAP_CHALLENGE, sp->confid[IDX_CHAP],
4238		       sizeof clen, (const char *)&clen,
4239		       (size_t)AUTHKEYLEN, sp->myauth.challenge,
4240		       (size_t)sppp_strnlen(sp->myauth.name, AUTHNAMELEN),
4241		       sp->myauth.name,
4242		       0);
4243}
4244
4245/*
4246 *--------------------------------------------------------------------------*
4247 *                                                                          *
4248 *                        The PAP implementation.                           *
4249 *                                                                          *
4250 *--------------------------------------------------------------------------*
4251 */
4252/*
4253 * For PAP, we need to keep a little state also if we are the peer, not the
4254 * authenticator.  This is since we don't get a request to authenticate, but
4255 * have to repeatedly authenticate ourself until we got a response (or the
4256 * retry counter is expired).
4257 */
4258
4259/*
4260 * Handle incoming PAP packets.  */
4261static void
4262sppp_pap_input(struct sppp *sp, struct mbuf *m)
4263{
4264	STDDCL;
4265	struct lcp_header *h;
4266	int len, x;
4267	u_char *name, *passwd, mlen;
4268	int name_len, passwd_len;
4269
4270	len = m->m_pkthdr.len;
4271	if (len < 5) {
4272		if (debug)
4273			log(LOG_DEBUG,
4274			    SPP_FMT "pap invalid packet length: %d bytes\n",
4275			    SPP_ARGS(ifp), len);
4276		return;
4277	}
4278	h = mtod (m, struct lcp_header*);
4279	if (len > ntohs (h->len))
4280		len = ntohs (h->len);
4281	switch (h->type) {
4282	/* PAP request is my authproto */
4283	case PAP_REQ:
4284		name = 1 + (u_char*)(h+1);
4285		name_len = name[-1];
4286		passwd = name + name_len + 1;
4287		if (name_len > len - 6 ||
4288		    (passwd_len = passwd[-1]) > len - 6 - name_len) {
4289			if (debug) {
4290				log(LOG_DEBUG, SPP_FMT "pap corrupted input "
4291				    "<%s id=0x%x len=%d",
4292				    SPP_ARGS(ifp),
4293				    sppp_auth_type_name(PPP_PAP, h->type),
4294				    h->ident, ntohs(h->len));
4295				sppp_print_bytes((u_char*)(h+1), len-4);
4296				log(-1, ">\n");
4297			}
4298			break;
4299		}
4300		if (debug) {
4301			log(LOG_DEBUG, SPP_FMT "pap input(%s) "
4302			    "<%s id=0x%x len=%d name=",
4303			    SPP_ARGS(ifp),
4304			    sppp_state_name(sp->state[IDX_PAP]),
4305			    sppp_auth_type_name(PPP_PAP, h->type),
4306			    h->ident, ntohs(h->len));
4307			sppp_print_string((char*)name, name_len);
4308			log(-1, " passwd=");
4309			sppp_print_string((char*)passwd, passwd_len);
4310			log(-1, ">\n");
4311		}
4312		if (name_len != sppp_strnlen(sp->hisauth.name, AUTHNAMELEN) ||
4313		    passwd_len != sppp_strnlen(sp->hisauth.secret, AUTHKEYLEN) ||
4314		    bcmp(name, sp->hisauth.name, name_len) != 0 ||
4315		    bcmp(passwd, sp->hisauth.secret, passwd_len) != 0) {
4316			/* action scn, tld */
4317			mlen = sizeof(FAILMSG) - 1;
4318			sppp_auth_send(&pap, sp, PAP_NAK, h->ident,
4319				       sizeof mlen, (const char *)&mlen,
4320				       sizeof(FAILMSG) - 1, (u_char *)FAILMSG,
4321				       0);
4322			pap.tld(sp);
4323			break;
4324		}
4325		/* action sca, perhaps tlu */
4326		if (sp->state[IDX_PAP] == STATE_REQ_SENT ||
4327		    sp->state[IDX_PAP] == STATE_OPENED) {
4328			mlen = sizeof(SUCCMSG) - 1;
4329			sppp_auth_send(&pap, sp, PAP_ACK, h->ident,
4330				       sizeof mlen, (const char *)&mlen,
4331				       sizeof(SUCCMSG) - 1, (u_char *)SUCCMSG,
4332				       0);
4333		}
4334		if (sp->state[IDX_PAP] == STATE_REQ_SENT) {
4335			sppp_cp_change_state(&pap, sp, STATE_OPENED);
4336			pap.tlu(sp);
4337		}
4338		break;
4339
4340	/* ack and nak are his authproto */
4341	case PAP_ACK:
4342		UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
4343		if (debug) {
4344			log(LOG_DEBUG, SPP_FMT "pap success",
4345			    SPP_ARGS(ifp));
4346			name_len = *((char *)h);
4347			if (len > 5 && name_len) {
4348				log(-1, ": ");
4349				sppp_print_string((char*)(h+1), name_len);
4350			}
4351			log(-1, "\n");
4352		}
4353		x = splimp();
4354		sp->pp_flags &= ~PP_NEEDAUTH;
4355		if (sp->myauth.proto == PPP_PAP &&
4356		    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) &&
4357		    (sp->lcp.protos & (1 << IDX_PAP)) == 0) {
4358			/*
4359			 * We are authenticator for PAP but didn't
4360			 * complete yet.  Leave it to tlu to proceed
4361			 * to network phase.
4362			 */
4363			splx(x);
4364			break;
4365		}
4366		splx(x);
4367		sppp_phase_network(sp);
4368		break;
4369
4370	case PAP_NAK:
4371		UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
4372		if (debug) {
4373			log(LOG_INFO, SPP_FMT "pap failure",
4374			    SPP_ARGS(ifp));
4375			name_len = *((char *)h);
4376			if (len > 5 && name_len) {
4377				log(-1, ": ");
4378				sppp_print_string((char*)(h+1), name_len);
4379			}
4380			log(-1, "\n");
4381		} else
4382			log(LOG_INFO, SPP_FMT "pap failure\n",
4383			    SPP_ARGS(ifp));
4384		/* await LCP shutdown by authenticator */
4385		break;
4386
4387	default:
4388		/* Unknown PAP packet type -- ignore. */
4389		if (debug) {
4390			log(LOG_DEBUG, SPP_FMT "pap corrupted input "
4391			    "<0x%x id=0x%x len=%d",
4392			    SPP_ARGS(ifp),
4393			    h->type, h->ident, ntohs(h->len));
4394			sppp_print_bytes((u_char*)(h+1), len-4);
4395			log(-1, ">\n");
4396		}
4397		break;
4398
4399	}
4400}
4401
4402static void
4403sppp_pap_init(struct sppp *sp)
4404{
4405	/* PAP doesn't have STATE_INITIAL at all. */
4406	sp->state[IDX_PAP] = STATE_CLOSED;
4407	sp->fail_counter[IDX_PAP] = 0;
4408	sp->pp_seq[IDX_PAP] = 0;
4409	sp->pp_rseq[IDX_PAP] = 0;
4410#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4411	callout_handle_init(&sp->ch[IDX_PAP]);
4412	callout_handle_init(&sp->pap_my_to_ch);
4413#endif
4414}
4415
4416static void
4417sppp_pap_open(struct sppp *sp)
4418{
4419	if (sp->hisauth.proto == PPP_PAP &&
4420	    (sp->lcp.opts & (1 << LCP_OPT_AUTH_PROTO)) != 0) {
4421		/* we are authenticator for PAP, start our timer */
4422		sp->rst_counter[IDX_PAP] = sp->lcp.max_configure;
4423		sppp_cp_change_state(&pap, sp, STATE_REQ_SENT);
4424	}
4425	if (sp->myauth.proto == PPP_PAP) {
4426		/* we are peer, send a request, and start a timer */
4427		pap.scr(sp);
4428		TIMEOUT(sppp_pap_my_TO, (void *)sp, sp->lcp.timeout,
4429		    sp->pap_my_to_ch);
4430	}
4431}
4432
4433static void
4434sppp_pap_close(struct sppp *sp)
4435{
4436	if (sp->state[IDX_PAP] != STATE_CLOSED)
4437		sppp_cp_change_state(&pap, sp, STATE_CLOSED);
4438}
4439
4440/*
4441 * That's the timeout routine if we are authenticator.  Since the
4442 * authenticator is basically passive in PAP, we can't do much here.
4443 */
4444static void
4445sppp_pap_TO(void *cookie)
4446{
4447	struct sppp *sp = (struct sppp *)cookie;
4448	STDDCL;
4449	int s;
4450
4451	s = splimp();
4452	if (debug)
4453		log(LOG_DEBUG, SPP_FMT "pap TO(%s) rst_counter = %d\n",
4454		    SPP_ARGS(ifp),
4455		    sppp_state_name(sp->state[IDX_PAP]),
4456		    sp->rst_counter[IDX_PAP]);
4457
4458	if (--sp->rst_counter[IDX_PAP] < 0)
4459		/* TO- event */
4460		switch (sp->state[IDX_PAP]) {
4461		case STATE_REQ_SENT:
4462			pap.tld(sp);
4463			sppp_cp_change_state(&pap, sp, STATE_CLOSED);
4464			break;
4465		}
4466	else
4467		/* TO+ event, not very much we could do */
4468		switch (sp->state[IDX_PAP]) {
4469		case STATE_REQ_SENT:
4470			/* sppp_cp_change_state() will restart the timer */
4471			sppp_cp_change_state(&pap, sp, STATE_REQ_SENT);
4472			break;
4473		}
4474
4475	splx(s);
4476}
4477
4478/*
4479 * That's the timeout handler if we are peer.  Since the peer is active,
4480 * we need to retransmit our PAP request since it is apparently lost.
4481 * XXX We should impose a max counter.
4482 */
4483static void
4484sppp_pap_my_TO(void *cookie)
4485{
4486	struct sppp *sp = (struct sppp *)cookie;
4487	STDDCL;
4488
4489	if (debug)
4490		log(LOG_DEBUG, SPP_FMT "pap peer TO\n",
4491		    SPP_ARGS(ifp));
4492
4493	pap.scr(sp);
4494}
4495
4496static void
4497sppp_pap_tlu(struct sppp *sp)
4498{
4499	STDDCL;
4500	int x;
4501
4502	sp->rst_counter[IDX_PAP] = sp->lcp.max_configure;
4503
4504	if (debug)
4505		log(LOG_DEBUG, SPP_FMT "%s tlu\n",
4506		    SPP_ARGS(ifp), pap.name);
4507
4508	x = splimp();
4509	/* indicate to LCP that we need to be closed down */
4510	sp->lcp.protos |= (1 << IDX_PAP);
4511
4512	if (sp->pp_flags & PP_NEEDAUTH) {
4513		/*
4514		 * Remote is authenticator, but his auth proto didn't
4515		 * complete yet.  Defer the transition to network
4516		 * phase.
4517		 */
4518		splx(x);
4519		return;
4520	}
4521	splx(x);
4522	sppp_phase_network(sp);
4523}
4524
4525static void
4526sppp_pap_tld(struct sppp *sp)
4527{
4528	STDDCL;
4529
4530	if (debug)
4531		log(LOG_DEBUG, SPP_FMT "pap tld\n", SPP_ARGS(ifp));
4532	UNTIMEOUT(pap.TO, (void *)sp, sp->ch[IDX_PAP]);
4533	UNTIMEOUT(sppp_pap_my_TO, (void *)sp, sp->pap_my_to_ch);
4534	sp->lcp.protos &= ~(1 << IDX_PAP);
4535
4536	lcp.Close(sp);
4537}
4538
4539static void
4540sppp_pap_scr(struct sppp *sp)
4541{
4542	u_char idlen, pwdlen;
4543
4544	sp->confid[IDX_PAP] = ++sp->pp_seq[IDX_PAP];
4545	pwdlen = sppp_strnlen(sp->myauth.secret, AUTHKEYLEN);
4546	idlen = sppp_strnlen(sp->myauth.name, AUTHNAMELEN);
4547
4548	sppp_auth_send(&pap, sp, PAP_REQ, sp->confid[IDX_PAP],
4549		       sizeof idlen, (const char *)&idlen,
4550		       (size_t)idlen, sp->myauth.name,
4551		       sizeof pwdlen, (const char *)&pwdlen,
4552		       (size_t)pwdlen, sp->myauth.secret,
4553		       0);
4554}
4555
4556/*
4557 * Random miscellaneous functions.
4558 */
4559
4560/*
4561 * Send a PAP or CHAP proto packet.
4562 *
4563 * Varadic function, each of the elements for the ellipsis is of type
4564 * ``size_t mlen, const u_char *msg''.  Processing will stop iff
4565 * mlen == 0.
4566 * NOTE: never declare variadic functions with types subject to type
4567 * promotion (i.e. u_char). This is asking for big trouble depending
4568 * on the architecture you are on...
4569 */
4570
4571static void
4572sppp_auth_send(const struct cp *cp, struct sppp *sp,
4573               unsigned int type, unsigned int id,
4574	       ...)
4575{
4576	STDDCL;
4577	struct ppp_header *h;
4578	struct lcp_header *lh;
4579	struct mbuf *m;
4580	u_char *p;
4581	int len;
4582	unsigned int mlen;
4583	const char *msg;
4584	va_list ap;
4585
4586	MGETHDR (m, M_DONTWAIT, MT_DATA);
4587	if (! m)
4588		return;
4589	m->m_pkthdr.rcvif = 0;
4590
4591	h = mtod (m, struct ppp_header*);
4592	h->address = PPP_ALLSTATIONS;		/* broadcast address */
4593	h->control = PPP_UI;			/* Unnumbered Info */
4594	h->protocol = htons(cp->proto);
4595
4596	lh = (struct lcp_header*)(h + 1);
4597	lh->type = type;
4598	lh->ident = id;
4599	p = (u_char*) (lh+1);
4600
4601	va_start(ap, id);
4602	len = 0;
4603
4604	while ((mlen = (unsigned int)va_arg(ap, size_t)) != 0) {
4605		msg = va_arg(ap, const char *);
4606		len += mlen;
4607		if (len > MHLEN - PPP_HEADER_LEN - LCP_HEADER_LEN) {
4608			va_end(ap);
4609			m_freem(m);
4610			return;
4611		}
4612
4613		bcopy(msg, p, mlen);
4614		p += mlen;
4615	}
4616	va_end(ap);
4617
4618	m->m_pkthdr.len = m->m_len = PPP_HEADER_LEN + LCP_HEADER_LEN + len;
4619	lh->len = htons (LCP_HEADER_LEN + len);
4620
4621	if (debug) {
4622		log(LOG_DEBUG, SPP_FMT "%s output <%s id=0x%x len=%d",
4623		    SPP_ARGS(ifp), cp->name,
4624		    sppp_auth_type_name(cp->proto, lh->type),
4625		    lh->ident, ntohs(lh->len));
4626		sppp_print_bytes((u_char*) (lh+1), len);
4627		log(-1, ">\n");
4628	}
4629	if (! IF_HANDOFF_ADJ(&sp->pp_cpq, m, ifp, 3))
4630		ifp->if_oerrors++;
4631}
4632
4633/*
4634 * Flush interface queue.
4635 */
4636static void
4637sppp_qflush(struct ifqueue *ifq)
4638{
4639	struct mbuf *m, *n;
4640
4641	n = ifq->ifq_head;
4642	while ((m = n)) {
4643		n = m->m_act;
4644		m_freem (m);
4645	}
4646	ifq->ifq_head = 0;
4647	ifq->ifq_tail = 0;
4648	ifq->ifq_len = 0;
4649}
4650
4651/*
4652 * Send keepalive packets, every 10 seconds.
4653 */
4654static void
4655sppp_keepalive(void *dummy)
4656{
4657	struct sppp *sp;
4658	int s;
4659
4660	s = splimp();
4661	for (sp=spppq; sp; sp=sp->pp_next) {
4662		struct ifnet *ifp = &sp->pp_if;
4663
4664		/* Keepalive mode disabled or channel down? */
4665		if (! (sp->pp_flags & PP_KEEPALIVE) ||
4666		    ! (ifp->if_flags & IFF_RUNNING))
4667			continue;
4668
4669		/* No keepalive in PPP mode if LCP not opened yet. */
4670		if (sp->pp_mode != IFF_CISCO &&
4671		    sp->pp_phase < PHASE_AUTHENTICATE)
4672			continue;
4673
4674		if (sp->pp_alivecnt == MAXALIVECNT) {
4675			/* No keepalive packets got.  Stop the interface. */
4676			printf (SPP_FMT "down\n", SPP_ARGS(ifp));
4677			if_down (ifp);
4678			sppp_qflush (&sp->pp_cpq);
4679			if (sp->pp_mode != IFF_CISCO) {
4680				/* XXX */
4681				/* Shut down the PPP link. */
4682				lcp.Down(sp);
4683				/* Initiate negotiation. XXX */
4684				lcp.Up(sp);
4685			}
4686		}
4687		if (sp->pp_alivecnt <= MAXALIVECNT)
4688			++sp->pp_alivecnt;
4689		if (sp->pp_mode == IFF_CISCO)
4690			sppp_cisco_send (sp, CISCO_KEEPALIVE_REQ,
4691				 ++sp->pp_seq[IDX_LCP],	sp->pp_rseq[IDX_LCP]);
4692		else if (sp->pp_phase >= PHASE_AUTHENTICATE) {
4693			long nmagic = htonl (sp->lcp.magic);
4694			sp->lcp.echoid = ++sp->pp_seq[IDX_LCP];
4695			sppp_cp_send (sp, PPP_LCP, ECHO_REQ,
4696				sp->lcp.echoid, 4, &nmagic);
4697		}
4698	}
4699	splx(s);
4700	TIMEOUT(sppp_keepalive, 0, hz * 10, keepalive_ch);
4701}
4702
4703/*
4704 * Get both IP addresses.
4705 */
4706static void
4707sppp_get_ip_addrs(struct sppp *sp, u_long *src, u_long *dst, u_long *srcmask)
4708{
4709	struct ifnet *ifp = &sp->pp_if;
4710	struct ifaddr *ifa;
4711	struct sockaddr_in *si, *sm;
4712	u_long ssrc, ddst;
4713
4714	sm = NULL;
4715	ssrc = ddst = 0L;
4716	/*
4717	 * Pick the first AF_INET address from the list,
4718	 * aliases don't make any sense on a p2p link anyway.
4719	 */
4720	si = 0;
4721#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4722	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
4723#elif defined(__NetBSD__) || defined (__OpenBSD__)
4724	for (ifa = TAILQ_FIRST(&ifp->if_addrlist);
4725	     ifa;
4726	     ifa = TAILQ_NEXT(ifa, ifa_list))
4727#else
4728	for (ifa = ifp->if_addrlist;
4729	     ifa;
4730	     ifa = ifa->ifa_next)
4731#endif
4732		if (ifa->ifa_addr->sa_family == AF_INET) {
4733			si = (struct sockaddr_in *)ifa->ifa_addr;
4734			sm = (struct sockaddr_in *)ifa->ifa_netmask;
4735			if (si)
4736				break;
4737		}
4738	if (ifa) {
4739		if (si && si->sin_addr.s_addr) {
4740			ssrc = si->sin_addr.s_addr;
4741			if (srcmask)
4742				*srcmask = ntohl(sm->sin_addr.s_addr);
4743		}
4744
4745		si = (struct sockaddr_in *)ifa->ifa_dstaddr;
4746		if (si && si->sin_addr.s_addr)
4747			ddst = si->sin_addr.s_addr;
4748	}
4749
4750	if (dst) *dst = ntohl(ddst);
4751	if (src) *src = ntohl(ssrc);
4752}
4753
4754/*
4755 * Set my IP address.  Must be called at splimp.
4756 */
4757static void
4758sppp_set_ip_addr(struct sppp *sp, u_long src)
4759{
4760	STDDCL;
4761	struct ifaddr *ifa;
4762	struct sockaddr_in *si;
4763	struct in_ifaddr *ia;
4764
4765	/*
4766	 * Pick the first AF_INET address from the list,
4767	 * aliases don't make any sense on a p2p link anyway.
4768	 */
4769	si = 0;
4770#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4771	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
4772#elif defined(__NetBSD__) || defined (__OpenBSD__)
4773	for (ifa = TAILQ_FIRST(&ifp->if_addrlist);
4774	     ifa;
4775	     ifa = TAILQ_NEXT(ifa, ifa_list))
4776#else
4777	for (ifa = ifp->if_addrlist;
4778	     ifa;
4779	     ifa = ifa->ifa_next)
4780#endif
4781	{
4782		if (ifa->ifa_addr->sa_family == AF_INET)
4783		{
4784			si = (struct sockaddr_in *)ifa->ifa_addr;
4785			if (si)
4786				break;
4787		}
4788	}
4789
4790	if (ifa && si)
4791	{
4792		int error;
4793#if __NetBSD_Version__ >= 103080000
4794		struct sockaddr_in new_sin = *si;
4795
4796		new_sin.sin_addr.s_addr = htonl(src);
4797		error = in_ifinit(ifp, ifatoia(ifa), &new_sin, 1);
4798		if(debug && error)
4799		{
4800			log(LOG_DEBUG, SPP_FMT "sppp_set_ip_addr: in_ifinit "
4801			" failed, error=%d\n", SPP_ARGS(ifp), error);
4802		}
4803#else
4804		/* delete old route */
4805		error = rtinit(ifa, (int)RTM_DELETE, RTF_HOST);
4806		if(debug && error)
4807		{
4808			log(LOG_DEBUG, SPP_FMT "sppp_set_ip_addr: rtinit DEL failed, error=%d\n",
4809		    		SPP_ARGS(ifp), error);
4810		}
4811
4812		/* set new address */
4813		si->sin_addr.s_addr = htonl(src);
4814		ia = ifatoia(ifa);
4815		LIST_REMOVE(ia, ia_hash);
4816		LIST_INSERT_HEAD(INADDR_HASH(si->sin_addr.s_addr), ia, ia_hash);
4817
4818		/* add new route */
4819		error = rtinit(ifa, (int)RTM_ADD, RTF_HOST);
4820		if (debug && error)
4821		{
4822			log(LOG_DEBUG, SPP_FMT "sppp_set_ip_addr: rtinit ADD failed, error=%d",
4823		    		SPP_ARGS(ifp), error);
4824		}
4825#endif
4826	}
4827}
4828
4829#ifdef INET6
4830/*
4831 * Get both IPv6 addresses.
4832 */
4833static void
4834sppp_get_ip6_addrs(struct sppp *sp, struct in6_addr *src, struct in6_addr *dst,
4835		   struct in6_addr *srcmask)
4836{
4837	struct ifnet *ifp = &sp->pp_if;
4838	struct ifaddr *ifa;
4839	struct sockaddr_in6 *si, *sm;
4840	struct in6_addr ssrc, ddst;
4841
4842	sm = NULL;
4843	bzero(&ssrc, sizeof(ssrc));
4844	bzero(&ddst, sizeof(ddst));
4845	/*
4846	 * Pick the first link-local AF_INET6 address from the list,
4847	 * aliases don't make any sense on a p2p link anyway.
4848	 */
4849#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4850	for (ifa = ifp->if_addrhead.tqh_first, si = 0;
4851	     ifa;
4852	     ifa = ifa->ifa_link.tqe_next)
4853#elif defined(__NetBSD__) || defined (__OpenBSD__)
4854	for (ifa = ifp->if_addrlist.tqh_first, si = 0;
4855	     ifa;
4856	     ifa = ifa->ifa_list.tqe_next)
4857#else
4858	for (ifa = ifp->if_addrlist, si = 0;
4859	     ifa;
4860	     ifa = ifa->ifa_next)
4861#endif
4862		if (ifa->ifa_addr->sa_family == AF_INET6) {
4863			si = (struct sockaddr_in6 *)ifa->ifa_addr;
4864			sm = (struct sockaddr_in6 *)ifa->ifa_netmask;
4865			if (si && IN6_IS_ADDR_LINKLOCAL(&si->sin6_addr))
4866				break;
4867		}
4868	if (ifa) {
4869		if (si && !IN6_IS_ADDR_UNSPECIFIED(&si->sin6_addr)) {
4870			bcopy(&si->sin6_addr, &ssrc, sizeof(ssrc));
4871			if (srcmask) {
4872				bcopy(&sm->sin6_addr, srcmask,
4873				      sizeof(*srcmask));
4874			}
4875		}
4876
4877		si = (struct sockaddr_in6 *)ifa->ifa_dstaddr;
4878		if (si && !IN6_IS_ADDR_UNSPECIFIED(&si->sin6_addr))
4879			bcopy(&si->sin6_addr, &ddst, sizeof(ddst));
4880	}
4881
4882	if (dst)
4883		bcopy(&ddst, dst, sizeof(*dst));
4884	if (src)
4885		bcopy(&ssrc, src, sizeof(*src));
4886}
4887
4888#ifdef IPV6CP_MYIFID_DYN
4889/*
4890 * Generate random ifid.
4891 */
4892static void
4893sppp_gen_ip6_addr(struct sppp *sp, struct in6_addr *addr)
4894{
4895	/* TBD */
4896}
4897
4898/*
4899 * Set my IPv6 address.  Must be called at splimp.
4900 */
4901static void
4902sppp_set_ip6_addr(struct sppp *sp, const struct in6_addr *src)
4903{
4904	STDDCL;
4905	struct ifaddr *ifa;
4906	struct sockaddr_in6 *sin6;
4907
4908	/*
4909	 * Pick the first link-local AF_INET6 address from the list,
4910	 * aliases don't make any sense on a p2p link anyway.
4911	 */
4912
4913	sin6 = NULL;
4914#if defined(__FreeBSD__) && __FreeBSD__ >= 3
4915	for (ifa = ifp->if_addrhead.tqh_first;
4916	     ifa;
4917	     ifa = ifa->ifa_link.tqe_next)
4918#elif defined(__NetBSD__) || defined (__OpenBSD__)
4919	for (ifa = ifp->if_addrlist.tqh_first;
4920	     ifa;
4921	     ifa = ifa->ifa_list.tqe_next)
4922#else
4923	for (ifa = ifp->if_addrlist; ifa; ifa = ifa->ifa_next)
4924#endif
4925	{
4926		if (ifa->ifa_addr->sa_family == AF_INET6)
4927		{
4928			sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
4929			if (sin6 && IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))
4930				break;
4931		}
4932	}
4933
4934	if (ifa && sin6)
4935	{
4936		int error;
4937		struct sockaddr_in6 new_sin6 = *sin6;
4938
4939		bcopy(src, &new_sin6.sin6_addr, sizeof(new_sin6.sin6_addr));
4940		error = in6_ifinit(ifp, ifatoia6(ifa), &new_sin6, 1);
4941		if (debug && error)
4942		{
4943			log(LOG_DEBUG, SPP_FMT "sppp_set_ip6_addr: in6_ifinit "
4944			    " failed, error=%d\n", SPP_ARGS(ifp), error);
4945		}
4946	}
4947}
4948#endif
4949
4950/*
4951 * Suggest a candidate address to be used by peer.
4952 */
4953static void
4954sppp_suggest_ip6_addr(struct sppp *sp, struct in6_addr *suggest)
4955{
4956	struct in6_addr myaddr;
4957	struct timeval tv;
4958
4959	sppp_get_ip6_addrs(sp, &myaddr, 0, 0);
4960
4961	myaddr.s6_addr[8] &= ~0x02;	/* u bit to "local" */
4962	microtime(&tv);
4963	if ((tv.tv_usec & 0xff) == 0 && (tv.tv_sec & 0xff) == 0) {
4964		myaddr.s6_addr[14] ^= 0xff;
4965		myaddr.s6_addr[15] ^= 0xff;
4966	} else {
4967		myaddr.s6_addr[14] ^= (tv.tv_usec & 0xff);
4968		myaddr.s6_addr[15] ^= (tv.tv_sec & 0xff);
4969	}
4970	if (suggest)
4971		bcopy(&myaddr, suggest, sizeof(myaddr));
4972}
4973#endif /*INET6*/
4974
4975static int
4976sppp_params(struct sppp *sp, u_long cmd, void *data)
4977{
4978	u_long subcmd;
4979	struct ifreq *ifr = (struct ifreq *)data;
4980	struct spppreq *spr;
4981	int rv = 0;
4982
4983	if ((spr = malloc(sizeof(struct spppreq), M_TEMP, M_NOWAIT)) == 0)
4984		return (EAGAIN);
4985	/*
4986	 * ifr->ifr_data is supposed to point to a struct spppreq.
4987	 * Check the cmd word first before attempting to fetch all the
4988	 * data.
4989	 */
4990	if ((subcmd = fuword(ifr->ifr_data)) == -1) {
4991		rv = EFAULT;
4992		goto quit;
4993	}
4994
4995	if (copyin((caddr_t)ifr->ifr_data, spr, sizeof(struct spppreq)) != 0) {
4996		rv = EFAULT;
4997		goto quit;
4998	}
4999
5000	switch (subcmd) {
5001	case SPPPIOGDEFS:
5002		if (cmd != SIOCGIFGENERIC) {
5003			rv = EINVAL;
5004			break;
5005		}
5006		/*
5007		 * We copy over the entire current state, but clean
5008		 * out some of the stuff we don't wanna pass up.
5009		 * Remember, SIOCGIFGENERIC is unprotected, and can be
5010		 * called by any user.  No need to ever get PAP or
5011		 * CHAP secrets back to userland anyway.
5012		 */
5013		spr->defs.pp_phase = sp->pp_phase;
5014		spr->defs.enable_vj = sp->enable_vj;
5015		spr->defs.lcp = sp->lcp;
5016		spr->defs.ipcp = sp->ipcp;
5017		spr->defs.ipv6cp = sp->ipv6cp;
5018		spr->defs.myauth = sp->myauth;
5019		spr->defs.hisauth = sp->hisauth;
5020		bzero(spr->defs.myauth.secret, AUTHKEYLEN);
5021		bzero(spr->defs.myauth.challenge, AUTHKEYLEN);
5022		bzero(spr->defs.hisauth.secret, AUTHKEYLEN);
5023		bzero(spr->defs.hisauth.challenge, AUTHKEYLEN);
5024		/*
5025		 * Fixup the LCP timeout value to milliseconds so
5026		 * spppcontrol doesn't need to bother about the value
5027		 * of "hz".  We do the reverse calculation below when
5028		 * setting it.
5029		 */
5030		spr->defs.lcp.timeout = sp->lcp.timeout * 1000 / hz;
5031		rv = copyout(spr, (caddr_t)ifr->ifr_data,
5032			     sizeof(struct spppreq));
5033		break;
5034
5035	case SPPPIOSDEFS:
5036		if (cmd != SIOCSIFGENERIC) {
5037			rv = EINVAL;
5038			break;
5039		}
5040		/*
5041		 * We have a very specific idea of which fields we
5042		 * allow being passed back from userland, so to not
5043		 * clobber our current state.  For one, we only allow
5044		 * setting anything if LCP is in dead or establish
5045		 * phase.  Once the authentication negotiations
5046		 * started, the authentication settings must not be
5047		 * changed again.  (The administrator can force an
5048		 * ifconfig down in order to get LCP back into dead
5049		 * phase.)
5050		 *
5051		 * Also, we only allow for authentication parameters to be
5052		 * specified.
5053		 *
5054		 * XXX Should allow to set or clear pp_flags.
5055		 *
5056		 * Finally, if the respective authentication protocol to
5057		 * be used is set differently than 0, but the secret is
5058		 * passed as all zeros, we don't trash the existing secret.
5059		 * This allows an administrator to change the system name
5060		 * only without clobbering the secret (which he didn't get
5061		 * back in a previous SPPPIOGDEFS call).  However, the
5062		 * secrets are cleared if the authentication protocol is
5063		 * reset to 0.  */
5064		if (sp->pp_phase != PHASE_DEAD &&
5065		    sp->pp_phase != PHASE_ESTABLISH) {
5066			rv = EBUSY;
5067			break;
5068		}
5069
5070		if ((spr->defs.myauth.proto != 0 && spr->defs.myauth.proto != PPP_PAP &&
5071		     spr->defs.myauth.proto != PPP_CHAP) ||
5072		    (spr->defs.hisauth.proto != 0 && spr->defs.hisauth.proto != PPP_PAP &&
5073		     spr->defs.hisauth.proto != PPP_CHAP)) {
5074			rv = EINVAL;
5075			break;
5076		}
5077
5078		if (spr->defs.myauth.proto == 0)
5079			/* resetting myauth */
5080			bzero(&sp->myauth, sizeof sp->myauth);
5081		else {
5082			/* setting/changing myauth */
5083			sp->myauth.proto = spr->defs.myauth.proto;
5084			bcopy(spr->defs.myauth.name, sp->myauth.name, AUTHNAMELEN);
5085			if (spr->defs.myauth.secret[0] != '\0')
5086				bcopy(spr->defs.myauth.secret, sp->myauth.secret,
5087				      AUTHKEYLEN);
5088		}
5089		if (spr->defs.hisauth.proto == 0)
5090			/* resetting hisauth */
5091			bzero(&sp->hisauth, sizeof sp->hisauth);
5092		else {
5093			/* setting/changing hisauth */
5094			sp->hisauth.proto = spr->defs.hisauth.proto;
5095			sp->hisauth.flags = spr->defs.hisauth.flags;
5096			bcopy(spr->defs.hisauth.name, sp->hisauth.name, AUTHNAMELEN);
5097			if (spr->defs.hisauth.secret[0] != '\0')
5098				bcopy(spr->defs.hisauth.secret, sp->hisauth.secret,
5099				      AUTHKEYLEN);
5100		}
5101		/* set LCP restart timer timeout */
5102		if (spr->defs.lcp.timeout != 0)
5103			sp->lcp.timeout = spr->defs.lcp.timeout * hz / 1000;
5104		/* set VJ enable flag */
5105		sp->enable_vj = spr->defs.enable_vj;
5106		break;
5107
5108	default:
5109		rv = EINVAL;
5110	}
5111
5112 quit:
5113	free(spr, M_TEMP);
5114
5115	return (rv);
5116}
5117
5118static void
5119sppp_phase_network(struct sppp *sp)
5120{
5121	STDDCL;
5122	int i;
5123	u_long mask;
5124
5125	sp->pp_phase = PHASE_NETWORK;
5126
5127	if (debug)
5128		log(LOG_DEBUG, SPP_FMT "phase %s\n", SPP_ARGS(ifp),
5129		    sppp_phase_name(sp->pp_phase));
5130
5131	/* Notify NCPs now. */
5132	for (i = 0; i < IDX_COUNT; i++)
5133		if ((cps[i])->flags & CP_NCP)
5134			(cps[i])->Open(sp);
5135
5136	/* Send Up events to all NCPs. */
5137	for (i = 0, mask = 1; i < IDX_COUNT; i++, mask <<= 1)
5138		if ((sp->lcp.protos & mask) && ((cps[i])->flags & CP_NCP))
5139			(cps[i])->Up(sp);
5140
5141	/* if no NCP is starting, all this was in vain, close down */
5142	sppp_lcp_check_and_close(sp);
5143}
5144
5145
5146static const char *
5147sppp_cp_type_name(u_char type)
5148{
5149	static char buf[12];
5150	switch (type) {
5151	case CONF_REQ:   return "conf-req";
5152	case CONF_ACK:   return "conf-ack";
5153	case CONF_NAK:   return "conf-nak";
5154	case CONF_REJ:   return "conf-rej";
5155	case TERM_REQ:   return "term-req";
5156	case TERM_ACK:   return "term-ack";
5157	case CODE_REJ:   return "code-rej";
5158	case PROTO_REJ:  return "proto-rej";
5159	case ECHO_REQ:   return "echo-req";
5160	case ECHO_REPLY: return "echo-reply";
5161	case DISC_REQ:   return "discard-req";
5162	}
5163	snprintf (buf, sizeof(buf), "cp/0x%x", type);
5164	return buf;
5165}
5166
5167static const char *
5168sppp_auth_type_name(u_short proto, u_char type)
5169{
5170	static char buf[12];
5171	switch (proto) {
5172	case PPP_CHAP:
5173		switch (type) {
5174		case CHAP_CHALLENGE:	return "challenge";
5175		case CHAP_RESPONSE:	return "response";
5176		case CHAP_SUCCESS:	return "success";
5177		case CHAP_FAILURE:	return "failure";
5178		}
5179	case PPP_PAP:
5180		switch (type) {
5181		case PAP_REQ:		return "req";
5182		case PAP_ACK:		return "ack";
5183		case PAP_NAK:		return "nak";
5184		}
5185	}
5186	snprintf (buf, sizeof(buf), "auth/0x%x", type);
5187	return buf;
5188}
5189
5190static const char *
5191sppp_lcp_opt_name(u_char opt)
5192{
5193	static char buf[12];
5194	switch (opt) {
5195	case LCP_OPT_MRU:		return "mru";
5196	case LCP_OPT_ASYNC_MAP:		return "async-map";
5197	case LCP_OPT_AUTH_PROTO:	return "auth-proto";
5198	case LCP_OPT_QUAL_PROTO:	return "qual-proto";
5199	case LCP_OPT_MAGIC:		return "magic";
5200	case LCP_OPT_PROTO_COMP:	return "proto-comp";
5201	case LCP_OPT_ADDR_COMP:		return "addr-comp";
5202	}
5203	snprintf (buf, sizeof(buf), "lcp/0x%x", opt);
5204	return buf;
5205}
5206
5207static const char *
5208sppp_ipcp_opt_name(u_char opt)
5209{
5210	static char buf[12];
5211	switch (opt) {
5212	case IPCP_OPT_ADDRESSES:	return "addresses";
5213	case IPCP_OPT_COMPRESSION:	return "compression";
5214	case IPCP_OPT_ADDRESS:		return "address";
5215	}
5216	snprintf (buf, sizeof(buf), "ipcp/0x%x", opt);
5217	return buf;
5218}
5219
5220#ifdef INET6
5221static const char *
5222sppp_ipv6cp_opt_name(u_char opt)
5223{
5224	static char buf[12];
5225	switch (opt) {
5226	case IPV6CP_OPT_IFID:		return "ifid";
5227	case IPV6CP_OPT_COMPRESSION:	return "compression";
5228	}
5229	sprintf (buf, "0x%x", opt);
5230	return buf;
5231}
5232#endif
5233
5234static const char *
5235sppp_state_name(int state)
5236{
5237	switch (state) {
5238	case STATE_INITIAL:	return "initial";
5239	case STATE_STARTING:	return "starting";
5240	case STATE_CLOSED:	return "closed";
5241	case STATE_STOPPED:	return "stopped";
5242	case STATE_CLOSING:	return "closing";
5243	case STATE_STOPPING:	return "stopping";
5244	case STATE_REQ_SENT:	return "req-sent";
5245	case STATE_ACK_RCVD:	return "ack-rcvd";
5246	case STATE_ACK_SENT:	return "ack-sent";
5247	case STATE_OPENED:	return "opened";
5248	}
5249	return "illegal";
5250}
5251
5252static const char *
5253sppp_phase_name(enum ppp_phase phase)
5254{
5255	switch (phase) {
5256	case PHASE_DEAD:	return "dead";
5257	case PHASE_ESTABLISH:	return "establish";
5258	case PHASE_TERMINATE:	return "terminate";
5259	case PHASE_AUTHENTICATE: return "authenticate";
5260	case PHASE_NETWORK:	return "network";
5261	}
5262	return "illegal";
5263}
5264
5265static const char *
5266sppp_proto_name(u_short proto)
5267{
5268	static char buf[12];
5269	switch (proto) {
5270	case PPP_LCP:	return "lcp";
5271	case PPP_IPCP:	return "ipcp";
5272	case PPP_PAP:	return "pap";
5273	case PPP_CHAP:	return "chap";
5274	case PPP_IPV6CP: return "ipv6cp";
5275	}
5276	snprintf(buf, sizeof(buf), "proto/0x%x", (unsigned)proto);
5277	return buf;
5278}
5279
5280static void
5281sppp_print_bytes(const u_char *p, u_short len)
5282{
5283	if (len)
5284		log(-1, " %*D", len, p, "-");
5285}
5286
5287static void
5288sppp_print_string(const char *p, u_short len)
5289{
5290	u_char c;
5291
5292	while (len-- > 0) {
5293		c = *p++;
5294		/*
5295		 * Print only ASCII chars directly.  RFC 1994 recommends
5296		 * using only them, but we don't rely on it.  */
5297		if (c < ' ' || c > '~')
5298			log(-1, "\\x%x", c);
5299		else
5300			log(-1, "%c", c);
5301	}
5302}
5303
5304static const char *
5305sppp_dotted_quad(u_long addr)
5306{
5307	static char s[16];
5308	sprintf(s, "%d.%d.%d.%d",
5309		(int)((addr >> 24) & 0xff),
5310		(int)((addr >> 16) & 0xff),
5311		(int)((addr >> 8) & 0xff),
5312		(int)(addr & 0xff));
5313	return s;
5314}
5315
5316static int
5317sppp_strnlen(u_char *p, int max)
5318{
5319	int len;
5320
5321	for (len = 0; len < max && *p; ++p)
5322		++len;
5323	return len;
5324}
5325
5326/* a dummy, used to drop uninteresting events */
5327static void
5328sppp_null(struct sppp *unused)
5329{
5330	/* do just nothing */
5331}
5332