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