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