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