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