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