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