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