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