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