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