]> CyberLeo.Net >> Repos - FreeBSD/releng/10.3.git/blob - sys/netgraph/ng_pppoe.c
- Copy stable/10@296371 to releng/10.3 in preparation for 10.3-RC1
[FreeBSD/releng/10.3.git] / sys / netgraph / ng_pppoe.c
1 /*
2  * ng_pppoe.c
3  */
4
5 /*-
6  * Copyright (c) 1996-1999 Whistle Communications, Inc.
7  * All rights reserved.
8  * 
9  * Subject to the following obligations and disclaimer of warranty, use and
10  * redistribution of this software, in source or object code forms, with or
11  * without modifications are expressly permitted by Whistle Communications;
12  * provided, however, that:
13  * 1. Any and all reproductions of the source or object code must include the
14  *    copyright notice above and the following disclaimer of warranties; and
15  * 2. No rights are granted, in any manner or form, to use Whistle
16  *    Communications, Inc. trademarks, including the mark "WHISTLE
17  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
18  *    such appears in the above copyright notice or in the software.
19  * 
20  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
21  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
22  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
23  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
25  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
26  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
27  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
28  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
29  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
30  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
31  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
32  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
36  * OF SUCH DAMAGE.
37  *
38  * Author: Julian Elischer <julian@freebsd.org>
39  *
40  * $FreeBSD$
41  * $Whistle: ng_pppoe.c,v 1.10 1999/11/01 09:24:52 julian Exp $
42  */
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/ktr.h>
48 #include <sys/mbuf.h>
49 #include <sys/malloc.h>
50 #include <sys/errno.h>
51 #include <sys/syslog.h>
52 #include <net/ethernet.h>
53
54 #include <netgraph/ng_message.h>
55 #include <netgraph/netgraph.h>
56 #include <netgraph/ng_parse.h>
57 #include <netgraph/ng_pppoe.h>
58 #include <netgraph/ng_ether.h>
59
60 #ifdef NG_SEPARATE_MALLOC
61 static MALLOC_DEFINE(M_NETGRAPH_PPPOE, "netgraph_pppoe", "netgraph pppoe node");
62 #else
63 #define M_NETGRAPH_PPPOE M_NETGRAPH
64 #endif
65
66 #define SIGNOFF "session closed"
67
68 /*
69  * This section contains the netgraph method declarations for the
70  * pppoe node. These methods define the netgraph pppoe 'type'.
71  */
72
73 static ng_constructor_t ng_pppoe_constructor;
74 static ng_rcvmsg_t      ng_pppoe_rcvmsg;
75 static ng_shutdown_t    ng_pppoe_shutdown;
76 static ng_newhook_t     ng_pppoe_newhook;
77 static ng_connect_t     ng_pppoe_connect;
78 static ng_rcvdata_t     ng_pppoe_rcvdata;
79 static ng_rcvdata_t     ng_pppoe_rcvdata_ether;
80 static ng_rcvdata_t     ng_pppoe_rcvdata_debug;
81 static ng_disconnect_t  ng_pppoe_disconnect;
82
83 /* Parse type for struct ngpppoe_init_data */
84 static const struct ng_parse_struct_field ngpppoe_init_data_type_fields[]
85         = NG_PPPOE_INIT_DATA_TYPE_INFO;
86 static const struct ng_parse_type ngpppoe_init_data_state_type = {
87         &ng_parse_struct_type,
88         &ngpppoe_init_data_type_fields
89 };
90
91 /* Parse type for struct ngpppoe_sts */
92 static const struct ng_parse_struct_field ng_pppoe_sts_type_fields[]
93         = NG_PPPOE_STS_TYPE_INFO;
94 static const struct ng_parse_type ng_pppoe_sts_state_type = {
95         &ng_parse_struct_type,
96         &ng_pppoe_sts_type_fields
97 };
98
99 /* List of commands and how to convert arguments to/from ASCII */
100 static const struct ng_cmdlist ng_pppoe_cmds[] = {
101         {
102           NGM_PPPOE_COOKIE,
103           NGM_PPPOE_CONNECT,
104           "pppoe_connect",
105           &ngpppoe_init_data_state_type,
106           NULL
107         },
108         {
109           NGM_PPPOE_COOKIE,
110           NGM_PPPOE_LISTEN,
111           "pppoe_listen",
112           &ngpppoe_init_data_state_type,
113           NULL
114         },
115         {
116           NGM_PPPOE_COOKIE,
117           NGM_PPPOE_OFFER,
118           "pppoe_offer",
119           &ngpppoe_init_data_state_type,
120           NULL
121         },
122         {
123           NGM_PPPOE_COOKIE,
124           NGM_PPPOE_SERVICE,
125           "pppoe_service",
126           &ngpppoe_init_data_state_type,
127           NULL
128         },
129         {
130           NGM_PPPOE_COOKIE,
131           NGM_PPPOE_SUCCESS,
132           "pppoe_success",
133           &ng_pppoe_sts_state_type,
134           NULL
135         },
136         {
137           NGM_PPPOE_COOKIE,
138           NGM_PPPOE_FAIL,
139           "pppoe_fail",
140           &ng_pppoe_sts_state_type,
141           NULL
142         },
143         {
144           NGM_PPPOE_COOKIE,
145           NGM_PPPOE_CLOSE,
146           "pppoe_close",
147           &ng_pppoe_sts_state_type,
148           NULL
149         },
150         {
151           NGM_PPPOE_COOKIE,
152           NGM_PPPOE_SETMODE,
153           "pppoe_setmode",
154           &ng_parse_string_type,
155           NULL
156         },
157         {
158           NGM_PPPOE_COOKIE,
159           NGM_PPPOE_GETMODE,
160           "pppoe_getmode",
161           NULL,
162           &ng_parse_string_type
163         },
164         {
165           NGM_PPPOE_COOKIE,
166           NGM_PPPOE_SETENADDR,
167           "setenaddr",
168           &ng_parse_enaddr_type,
169           NULL
170         },
171         {
172           NGM_PPPOE_COOKIE,
173           NGM_PPPOE_SETMAXP,
174           "setmaxp",
175           &ng_parse_uint16_type,
176           NULL
177         },
178         { 0 }
179 };
180
181 /* Netgraph node type descriptor */
182 static struct ng_type typestruct = {
183         .version =      NG_ABI_VERSION,
184         .name =         NG_PPPOE_NODE_TYPE,
185         .constructor =  ng_pppoe_constructor,
186         .rcvmsg =       ng_pppoe_rcvmsg,
187         .shutdown =     ng_pppoe_shutdown,
188         .newhook =      ng_pppoe_newhook,
189         .connect =      ng_pppoe_connect,
190         .rcvdata =      ng_pppoe_rcvdata,
191         .disconnect =   ng_pppoe_disconnect,
192         .cmdlist =      ng_pppoe_cmds,
193 };
194 NETGRAPH_INIT(pppoe, &typestruct);
195
196 /*
197  * States for the session state machine.
198  * These have no meaning if there is no hook attached yet.
199  */
200 enum state {
201     PPPOE_SNONE=0,      /* [both] Initial state */
202     PPPOE_LISTENING,    /* [Daemon] Listening for discover initiation pkt */
203     PPPOE_SINIT,        /* [Client] Sent discovery initiation */
204     PPPOE_PRIMED,       /* [Server] Awaiting PADI from daemon */
205     PPPOE_SOFFER,       /* [Server] Sent offer message  (got PADI)*/
206     PPPOE_SREQ,         /* [Client] Sent a Request */
207     PPPOE_NEWCONNECTED, /* [Server] Connection established, No data received */
208     PPPOE_CONNECTED,    /* [Both] Connection established, Data received */
209     PPPOE_DEAD          /* [Both] */
210 };
211
212 #define NUMTAGS 20 /* number of tags we are set up to work with */
213
214 /*
215  * Information we store for each hook on each node for negotiating the
216  * session. The mbuf and cluster are freed once negotiation has completed.
217  * The whole negotiation block is then discarded.
218  */
219
220 struct sess_neg {
221         struct mbuf             *m; /* holds cluster with last sent packet */
222         union   packet          *pkt; /* points within the above cluster */
223         struct callout          handle;   /* see timeout(9) */
224         u_int                   timeout; /* 0,1,2,4,8,16 etc. seconds */
225         u_int                   numtags;
226         const struct pppoe_tag  *tags[NUMTAGS];
227         u_int                   service_len;
228         u_int                   ac_name_len;
229
230         struct datatag          service;
231         struct datatag          ac_name;
232 };
233 typedef struct sess_neg *negp;
234
235 /*
236  * Session information that is needed after connection.
237  */
238 struct sess_con {
239         hook_p                  hook;
240         uint16_t                Session_ID;
241         enum state              state;
242         ng_ID_t                 creator;        /* who to notify */
243         struct pppoe_full_hdr   pkt_hdr;        /* used when connected */
244         negp                    neg;            /* used when negotiating */
245         LIST_ENTRY(sess_con)    sessions;
246 };
247 typedef struct sess_con *sessp;
248
249 #define SESSHASHSIZE    0x0100
250 #define SESSHASH(x)     (((x) ^ ((x) >> 8)) & (SESSHASHSIZE - 1))
251
252 struct sess_hash_entry {
253         struct mtx      mtx;
254         LIST_HEAD(hhead, sess_con) head;
255 };
256
257 /*
258  * Information we store for each node
259  */
260 struct PPPoE {
261         node_p          node;           /* back pointer to node */
262         hook_p          ethernet_hook;
263         hook_p          debug_hook;
264         u_int           packets_in;     /* packets in from ethernet */
265         u_int           packets_out;    /* packets out towards ethernet */
266         uint32_t        flags;
267 #define COMPAT_3COM     0x00000001
268 #define COMPAT_DLINK    0x00000002
269         struct ether_header     eh;
270         LIST_HEAD(, sess_con) listeners;
271         struct sess_hash_entry  sesshash[SESSHASHSIZE];
272         struct maxptag  max_payload;    /* PPP-Max-Payload (RFC4638) */
273 };
274 typedef struct PPPoE *priv_p;
275
276 union uniq {
277         char bytes[sizeof(void *)];
278         void *pointer;
279 };
280
281 #define LEAVE(x) do { error = x; goto quit; } while(0)
282 static void     pppoe_start(sessp sp);
283 static void     pppoe_ticker(node_p node, hook_p hook, void *arg1, int arg2);
284 static const    struct pppoe_tag *scan_tags(sessp sp,
285                         const struct pppoe_hdr* ph);
286 static  int     pppoe_send_event(sessp sp, enum cmd cmdid);
287
288 /*************************************************************************
289  * Some basic utilities  from the Linux version with author's permission.*
290  * Author:      Michal Ostrowski <mostrows@styx.uwaterloo.ca>            *
291  ************************************************************************/
292
293
294
295 /*
296  * Return the location where the next tag can be put
297  */
298 static __inline const struct pppoe_tag*
299 next_tag(const struct pppoe_hdr* ph)
300 {
301         return (const struct pppoe_tag*)(((const char*)(ph + 1))
302             + ntohs(ph->length));
303 }
304
305 /*
306  * Look for a tag of a specific type.
307  * Don't trust any length the other end says,
308  * but assume we already sanity checked ph->length.
309  */
310 static const struct pppoe_tag*
311 get_tag(const struct pppoe_hdr* ph, uint16_t idx)
312 {
313         const char *const end = (const char *)next_tag(ph);
314         const struct pppoe_tag *pt = (const void *)(ph + 1);
315         const char *ptn;
316
317         /*
318          * Keep processing tags while a tag header will still fit.
319          */
320         while((const char*)(pt + 1) <= end) {
321                 /*
322                  * If the tag data would go past the end of the packet, abort.
323                  */
324                 ptn = (((const char *)(pt + 1)) + ntohs(pt->tag_len));
325                 if (ptn > end) {
326                         CTR2(KTR_NET, "%20s: invalid length for tag %d",
327                             __func__, idx);
328                         return (NULL);
329                 }
330                 if (pt->tag_type == idx) {
331                         CTR2(KTR_NET, "%20s: found tag %d", __func__, idx);
332                         return (pt);
333                 }
334
335                 pt = (const struct pppoe_tag*)ptn;
336         }
337
338         CTR2(KTR_NET, "%20s: not found tag %d", __func__, idx);
339         return (NULL);
340 }
341
342 /**************************************************************************
343  * Inlines to initialise or add tags to a session's tag list.
344  **************************************************************************/
345 /*
346  * Initialise the session's tag list.
347  */
348 static void
349 init_tags(sessp sp)
350 {
351         KASSERT(sp->neg != NULL, ("%s: no neg", __func__));
352         sp->neg->numtags = 0;
353 }
354
355 static void
356 insert_tag(sessp sp, const struct pppoe_tag *tp)
357 {
358         negp neg = sp->neg;
359         int i;
360
361         KASSERT(neg != NULL, ("%s: no neg", __func__));
362         if ((i = neg->numtags++) < NUMTAGS) {
363                 neg->tags[i] = tp;
364         } else {
365                 log(LOG_NOTICE, "ng_pppoe: asked to add too many tags to "
366                     "packet\n");
367                 neg->numtags--;
368         }
369 }
370
371 /*
372  * Make up a packet, using the tags filled out for the session.
373  *
374  * Assume that the actual pppoe header and ethernet header
375  * are filled out externally to this routine.
376  * Also assume that neg->wh points to the correct
377  * location at the front of the buffer space.
378  */
379 static void
380 make_packet(sessp sp) {
381         struct pppoe_full_hdr *wh = &sp->neg->pkt->pkt_header;
382         const struct pppoe_tag **tag;
383         char *dp;
384         int count;
385         int tlen;
386         uint16_t length = 0;
387
388         KASSERT((sp->neg != NULL) && (sp->neg->m != NULL),
389             ("%s: called from wrong state", __func__));
390         CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
391
392         dp = (char *)(&wh->ph + 1);
393         for (count = 0, tag = sp->neg->tags;
394             ((count < sp->neg->numtags) && (count < NUMTAGS));
395             tag++, count++) {
396                 tlen = ntohs((*tag)->tag_len) + sizeof(**tag);
397                 if ((length + tlen) > (ETHER_MAX_LEN - 4 - sizeof(*wh))) {
398                         log(LOG_NOTICE, "ng_pppoe: tags too long\n");
399                         sp->neg->numtags = count;
400                         break;  /* XXX chop off what's too long */
401                 }
402                 bcopy(*tag, (char *)dp, tlen);
403                 length += tlen;
404                 dp += tlen;
405         }
406         wh->ph.length = htons(length);
407         sp->neg->m->m_len = length + sizeof(*wh);
408         sp->neg->m->m_pkthdr.len = length + sizeof(*wh);
409 }
410
411 /**************************************************************************
412  * Routines to match a service.                                           *
413  **************************************************************************/
414
415 /*
416  * Find a hook that has a service string that matches that
417  * we are seeking. For now use a simple string.
418  * In the future we may need something like regexp().
419  *
420  * Null string is a wildcard (ANY service), according to RFC2516.
421  * And historical FreeBSD wildcard is also "*".
422  */
423
424 static hook_p
425 pppoe_match_svc(node_p node, const struct pppoe_tag *tag)
426 {
427         const priv_p privp = NG_NODE_PRIVATE(node);
428         sessp sp;
429
430         LIST_FOREACH(sp, &privp->listeners, sessions) {
431                 negp neg = sp->neg;
432
433                 /* Empty Service-Name matches any service. */
434                 if (neg->service_len == 0)
435                         break;
436
437                 /* Special case for a blank or "*" service name (wildcard). */
438                 if (neg->service_len == 1 && neg->service.data[0] == '*')
439                         break;
440
441                 /* If the lengths don't match, that aint it. */
442                 if (neg->service_len != ntohs(tag->tag_len))
443                         continue;
444
445                 if (strncmp((const char *)(tag + 1), neg->service.data,
446                     ntohs(tag->tag_len)) == 0)
447                         break;
448         }
449         CTR3(KTR_NET, "%20s: matched %p for %s", __func__,
450             sp?sp->hook:NULL, (const char *)(tag + 1));
451
452         return (sp?sp->hook:NULL);
453 }
454
455 /*
456  * Broadcast the PADI packet in m0 to all listening hooks.
457  * This routine is called when a PADI with empty Service-Name
458  * tag is received. Client should receive PADOs with all
459  * available services.
460  */
461 static int
462 pppoe_broadcast_padi(node_p node, struct mbuf *m0)
463 {
464         const priv_p privp = NG_NODE_PRIVATE(node);
465         sessp sp;
466         int error = 0;
467
468         LIST_FOREACH(sp, &privp->listeners, sessions) {
469                 struct mbuf *m;
470
471                 m = m_dup(m0, M_NOWAIT);
472                 if (m == NULL)
473                         return (ENOMEM);
474                 NG_SEND_DATA_ONLY(error, sp->hook, m);
475                 if (error)
476                         return (error);
477         }
478
479         return (0);
480 }
481
482 /*
483  * Find a hook, which name equals to given service.
484  */
485 static hook_p
486 pppoe_find_svc(node_p node, const char *svc_name, int svc_len)
487 {
488         const priv_p privp = NG_NODE_PRIVATE(node);
489         sessp sp;
490
491         LIST_FOREACH(sp, &privp->listeners, sessions) {
492                 negp neg = sp->neg;
493
494                 if (neg->service_len == svc_len &&
495                     strncmp(svc_name, neg->service.data, svc_len) == 0)
496                         return (sp->hook);
497         }
498
499         return (NULL);
500 }
501
502 /**************************************************************************
503  * Routines to find a particular session that matches an incoming packet. *
504  **************************************************************************/
505 /* Find free session and add to hash. */
506 static uint16_t
507 pppoe_getnewsession(sessp sp)
508 {
509         const priv_p privp = NG_NODE_PRIVATE(NG_HOOK_NODE(sp->hook));
510         static uint16_t pppoe_sid = 1;
511         sessp   tsp;
512         uint16_t val, hash;
513
514 restart:
515         /* Atomicity is not needed here as value will be checked. */
516         val = pppoe_sid++;
517         /* Spec says 0xFFFF is reserved, also don't use 0x0000. */
518         if (val == 0xffff || val == 0x0000)
519                 val = pppoe_sid = 1;
520
521         /* Check it isn't already in use. */
522         hash = SESSHASH(val);
523         mtx_lock(&privp->sesshash[hash].mtx);
524         LIST_FOREACH(tsp, &privp->sesshash[hash].head, sessions) {
525                 if (tsp->Session_ID == val)
526                         break;
527         }
528         if (!tsp) {
529                 sp->Session_ID = val;
530                 LIST_INSERT_HEAD(&privp->sesshash[hash].head, sp, sessions);
531         }
532         mtx_unlock(&privp->sesshash[hash].mtx);
533         if (tsp)
534                 goto restart;
535
536         CTR2(KTR_NET, "%20s: new sid %d", __func__, val);
537
538         return (val);
539 }
540
541 /* Add specified session to hash. */
542 static void
543 pppoe_addsession(sessp sp)
544 {
545         const priv_p    privp = NG_NODE_PRIVATE(NG_HOOK_NODE(sp->hook));
546         uint16_t        hash = SESSHASH(sp->Session_ID);
547
548         mtx_lock(&privp->sesshash[hash].mtx);
549         LIST_INSERT_HEAD(&privp->sesshash[hash].head, sp, sessions);
550         mtx_unlock(&privp->sesshash[hash].mtx);
551 }
552
553 /* Delete specified session from hash. */
554 static void
555 pppoe_delsession(sessp sp)
556 {
557         const priv_p    privp = NG_NODE_PRIVATE(NG_HOOK_NODE(sp->hook));
558         uint16_t        hash = SESSHASH(sp->Session_ID);
559
560         mtx_lock(&privp->sesshash[hash].mtx);
561         LIST_REMOVE(sp, sessions);
562         mtx_unlock(&privp->sesshash[hash].mtx);
563 }
564
565 /* Find matching peer/session combination. */
566 static sessp
567 pppoe_findsession(priv_p privp, const struct pppoe_full_hdr *wh)
568 {
569         uint16_t        session = ntohs(wh->ph.sid);
570         uint16_t        hash = SESSHASH(session);
571         sessp           sp = NULL;
572
573         mtx_lock(&privp->sesshash[hash].mtx);
574         LIST_FOREACH(sp, &privp->sesshash[hash].head, sessions) {
575                 if (sp->Session_ID == session &&
576                     bcmp(sp->pkt_hdr.eh.ether_dhost,
577                      wh->eh.ether_shost, ETHER_ADDR_LEN) == 0) {
578                         break;
579                 }
580         }
581         mtx_unlock(&privp->sesshash[hash].mtx);
582         CTR3(KTR_NET, "%20s: matched %p for %d", __func__, sp?sp->hook:NULL,
583             session);
584
585         return (sp);
586 }
587
588 static hook_p
589 pppoe_finduniq(node_p node, const struct pppoe_tag *tag)
590 {
591         hook_p  hook = NULL;
592         union uniq uniq;
593
594         bcopy(tag + 1, uniq.bytes, sizeof(void *));
595         /* Cycle through all known hooks. */
596         LIST_FOREACH(hook, &node->nd_hooks, hk_hooks) {
597                 /* Skip any nonsession hook. */
598                 if (NG_HOOK_PRIVATE(hook) == NULL)
599                         continue;
600                 if (uniq.pointer == NG_HOOK_PRIVATE(hook))
601                         break;
602         }
603         CTR3(KTR_NET, "%20s: matched %p for %p", __func__, hook, uniq.pointer);
604
605         return (hook);
606 }
607
608 /**************************************************************************
609  * Start of Netgraph entrypoints.                                         *
610  **************************************************************************/
611
612 /*
613  * Allocate the private data structure and link it with node.
614  */
615 static int
616 ng_pppoe_constructor(node_p node)
617 {
618         priv_p  privp;
619         int     i;
620
621         /* Initialize private descriptor. */
622         privp = malloc(sizeof(*privp), M_NETGRAPH_PPPOE, M_WAITOK | M_ZERO);
623
624         /* Link structs together; this counts as our one reference to *node. */
625         NG_NODE_SET_PRIVATE(node, privp);
626         privp->node = node;
627
628         /* Initialize to standard mode. */
629         memset(&privp->eh.ether_dhost, 0xff, ETHER_ADDR_LEN);
630         privp->eh.ether_type = ETHERTYPE_PPPOE_DISC;
631
632         LIST_INIT(&privp->listeners);
633         for (i = 0; i < SESSHASHSIZE; i++) {
634             mtx_init(&privp->sesshash[i].mtx, "PPPoE hash mutex", NULL, MTX_DEF);
635             LIST_INIT(&privp->sesshash[i].head);
636         }
637
638         CTR3(KTR_NET, "%20s: created node [%x] (%p)",
639             __func__, node->nd_ID, node);
640
641         return (0);
642 }
643
644 /*
645  * Give our ok for a hook to be added...
646  * point the hook's private info to the hook structure.
647  *
648  * The following hook names are special:
649  *  "ethernet":  the hook that should be connected to a NIC.
650  *  "debug":    copies of data sent out here  (when I write the code).
651  * All other hook names need only be unique. (the framework checks this).
652  */
653 static int
654 ng_pppoe_newhook(node_p node, hook_p hook, const char *name)
655 {
656         const priv_p privp = NG_NODE_PRIVATE(node);
657         sessp sp;
658
659         if (strcmp(name, NG_PPPOE_HOOK_ETHERNET) == 0) {
660                 privp->ethernet_hook = hook;
661                 NG_HOOK_SET_RCVDATA(hook, ng_pppoe_rcvdata_ether);
662         } else if (strcmp(name, NG_PPPOE_HOOK_DEBUG) == 0) {
663                 privp->debug_hook = hook;
664                 NG_HOOK_SET_RCVDATA(hook, ng_pppoe_rcvdata_debug);
665         } else {
666                 /*
667                  * Any other unique name is OK.
668                  * The infrastructure has already checked that it's unique,
669                  * so just allocate it and hook it in.
670                  */
671                 sp = malloc(sizeof(*sp), M_NETGRAPH_PPPOE, M_NOWAIT | M_ZERO);
672                 if (sp == NULL)
673                         return (ENOMEM);
674
675                 NG_HOOK_SET_PRIVATE(hook, sp);
676                 sp->hook = hook;
677         }
678         CTR5(KTR_NET, "%20s: node [%x] (%p) connected hook %s (%p)",
679             __func__, node->nd_ID, node, name, hook);
680
681         return(0);
682 }
683
684 /*
685  * Hook has been added successfully. Request the MAC address of
686  * the underlying Ethernet node.
687  */
688 static int
689 ng_pppoe_connect(hook_p hook)
690 {
691         const priv_p privp = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
692         struct ng_mesg *msg;
693         int error;
694
695         if (hook != privp->ethernet_hook)
696                 return (0);
697
698         /*
699          * If this is Ethernet hook, then request MAC address
700          * from our downstream.
701          */
702         NG_MKMESSAGE(msg, NGM_ETHER_COOKIE, NGM_ETHER_GET_ENADDR, 0, M_NOWAIT);
703         if (msg == NULL)
704                 return (ENOBUFS);
705
706         /*
707          * Our hook and peer hook have HK_INVALID flag set,
708          * so we can't use NG_SEND_MSG_HOOK() macro here.
709          */
710         NG_SEND_MSG_ID(error, privp->node, msg,
711             NG_NODE_ID(NG_PEER_NODE(privp->ethernet_hook)),
712             NG_NODE_ID(privp->node));
713
714         return (error);
715 }
716 /*
717  * Get a netgraph control message.
718  * Check it is one we understand. If needed, send a response.
719  * We sometimes save the address for an async action later.
720  * Always free the message.
721  */
722 static int
723 ng_pppoe_rcvmsg(node_p node, item_p item, hook_p lasthook)
724 {
725         priv_p privp = NG_NODE_PRIVATE(node);
726         struct ngpppoe_init_data *ourmsg = NULL;
727         struct ng_mesg *resp = NULL;
728         int error = 0;
729         hook_p hook = NULL;
730         sessp sp = NULL;
731         negp neg = NULL;
732         struct ng_mesg *msg;
733
734         NGI_GET_MSG(item, msg);
735         CTR5(KTR_NET, "%20s: node [%x] (%p) got message %d with cookie %d",
736             __func__, node->nd_ID, node, msg->header.cmd,
737             msg->header.typecookie);
738
739         /* Deal with message according to cookie and command. */
740         switch (msg->header.typecookie) {
741         case NGM_PPPOE_COOKIE:
742                 switch (msg->header.cmd) {
743                 case NGM_PPPOE_CONNECT:
744                 case NGM_PPPOE_LISTEN:
745                 case NGM_PPPOE_OFFER:
746                 case NGM_PPPOE_SERVICE:
747                         ourmsg = (struct ngpppoe_init_data *)msg->data;
748                         if (msg->header.arglen < sizeof(*ourmsg)) {
749                                 log(LOG_ERR, "ng_pppoe[%x]: init data too "
750                                     "small\n", node->nd_ID);
751                                 LEAVE(EMSGSIZE);
752                         }
753                         if (msg->header.arglen - sizeof(*ourmsg) >
754                             PPPOE_SERVICE_NAME_SIZE) {
755                                 log(LOG_ERR, "ng_pppoe[%x]: service name "
756                                     "too big\n", node->nd_ID);
757                                 LEAVE(EMSGSIZE);
758                         }
759                         if (msg->header.arglen - sizeof(*ourmsg) <
760                             ourmsg->data_len) {
761                                 log(LOG_ERR, "ng_pppoe[%x]: init data has bad "
762                                     "length, %d should be %zd\n", node->nd_ID,
763                                     ourmsg->data_len,
764                                     msg->header.arglen - sizeof (*ourmsg));
765                                 LEAVE(EMSGSIZE);
766                         }
767
768                         /* Make sure strcmp will terminate safely. */
769                         ourmsg->hook[sizeof(ourmsg->hook) - 1] = '\0';
770
771                         /* Find hook by name. */
772                         hook = ng_findhook(node, ourmsg->hook);
773                         if (hook == NULL)
774                                 LEAVE(ENOENT);
775
776                         sp = NG_HOOK_PRIVATE(hook);
777                         if (sp == NULL)
778                                 LEAVE(EINVAL);
779
780                         if (msg->header.cmd == NGM_PPPOE_LISTEN) {
781                                 /*
782                                  * Ensure we aren't already listening for this
783                                  * service.
784                                  */
785                                 if (pppoe_find_svc(node, ourmsg->data,
786                                     ourmsg->data_len) != NULL)
787                                         LEAVE(EEXIST);
788                         }
789
790                         /*
791                          * PPPOE_SERVICE advertisments are set up
792                          * on sessions that are in PRIMED state.
793                          */
794                         if (msg->header.cmd == NGM_PPPOE_SERVICE)
795                                 break;
796
797                         if (sp->state != PPPOE_SNONE) {
798                                 log(LOG_NOTICE, "ng_pppoe[%x]: Session already "
799                                     "active\n", node->nd_ID);
800                                 LEAVE(EISCONN);
801                         }
802
803                         /*
804                          * Set up prototype header.
805                          */
806                         neg = malloc(sizeof(*neg), M_NETGRAPH_PPPOE,
807                             M_NOWAIT | M_ZERO);
808
809                         if (neg == NULL)
810                                 LEAVE(ENOMEM);
811
812                         neg->m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
813                         if (neg->m == NULL) {
814                                 free(neg, M_NETGRAPH_PPPOE);
815                                 LEAVE(ENOBUFS);
816                         }
817                         neg->m->m_pkthdr.rcvif = NULL;
818                         sp->neg = neg;
819                         ng_callout_init(&neg->handle);
820                         neg->m->m_len = sizeof(struct pppoe_full_hdr);
821                         neg->pkt = mtod(neg->m, union packet*);
822                         memcpy((void *)&neg->pkt->pkt_header.eh,
823                             &privp->eh, sizeof(struct ether_header));
824                         neg->pkt->pkt_header.ph.ver = 0x1;
825                         neg->pkt->pkt_header.ph.type = 0x1;
826                         neg->pkt->pkt_header.ph.sid = 0x0000;
827                         neg->timeout = 0;
828
829                         sp->creator = NGI_RETADDR(item);
830                 }
831                 switch (msg->header.cmd) {
832                 case NGM_PPPOE_GET_STATUS:
833                     {
834                         struct ngpppoestat *stats;
835
836                         NG_MKRESPONSE(resp, msg, sizeof(*stats), M_NOWAIT);
837                         if (!resp)
838                                 LEAVE(ENOMEM);
839
840                         stats = (struct ngpppoestat *) resp->data;
841                         stats->packets_in = privp->packets_in;
842                         stats->packets_out = privp->packets_out;
843                         break;
844                     }
845                 case NGM_PPPOE_CONNECT:
846                     {
847                         /*
848                          * Check the hook exists and is Uninitialised.
849                          * Send a PADI request, and start the timeout logic.
850                          * Store the originator of this message so we can send
851                          * a success of fail message to them later.
852                          * Move the session to SINIT.
853                          * Set up the session to the correct state and
854                          * start it.
855                          */
856                         int     i, acnlen = 0, acnsep = 0, srvlen;
857                         for (i = 0; i < ourmsg->data_len; i++) {
858                                 if (ourmsg->data[i] == '\\') {
859                                         acnlen = i;
860                                         acnsep = 1;
861                                         break;
862                                 }
863                         }
864                         srvlen = ourmsg->data_len - acnlen - acnsep;
865
866                         bcopy(ourmsg->data, neg->ac_name.data, acnlen);
867                         neg->ac_name_len = acnlen;
868
869                         neg->service.hdr.tag_type = PTT_SRV_NAME;
870                         neg->service.hdr.tag_len = htons((uint16_t)srvlen);
871                         bcopy(ourmsg->data + acnlen + acnsep,
872                             neg->service.data, srvlen);
873                         neg->service_len = srvlen;
874                         pppoe_start(sp);
875                         break;
876                     }
877                 case NGM_PPPOE_LISTEN:
878                         /*
879                          * Check the hook exists and is Uninitialised.
880                          * Install the service matching string.
881                          * Store the originator of this message so we can send
882                          * a success of fail message to them later.
883                          * Move the hook to 'LISTENING'
884                          */
885                         neg->service.hdr.tag_type = PTT_SRV_NAME;
886                         neg->service.hdr.tag_len =
887                             htons((uint16_t)ourmsg->data_len);
888
889                         if (ourmsg->data_len)
890                                 bcopy(ourmsg->data, neg->service.data,
891                                     ourmsg->data_len);
892                         neg->service_len = ourmsg->data_len;
893                         neg->pkt->pkt_header.ph.code = PADT_CODE;
894                         /*
895                          * Wait for PADI packet coming from Ethernet.
896                          */
897                         sp->state = PPPOE_LISTENING;
898                         LIST_INSERT_HEAD(&privp->listeners, sp, sessions);
899                         break;
900                 case NGM_PPPOE_OFFER:
901                         /*
902                          * Check the hook exists and is Uninitialised.
903                          * Store the originator of this message so we can send
904                          * a success of fail message to them later.
905                          * Store the AC-Name given and go to PRIMED.
906                          */
907                         neg->ac_name.hdr.tag_type = PTT_AC_NAME;
908                         neg->ac_name.hdr.tag_len =
909                             htons((uint16_t)ourmsg->data_len);
910                         if (ourmsg->data_len)
911                                 bcopy(ourmsg->data, neg->ac_name.data,
912                                     ourmsg->data_len);
913                         neg->ac_name_len = ourmsg->data_len;
914                         neg->pkt->pkt_header.ph.code = PADO_CODE;
915                         /*
916                          * Wait for PADI packet coming from hook.
917                          */
918                         sp->state = PPPOE_PRIMED;
919                         break;
920                 case NGM_PPPOE_SERVICE:
921                         /*
922                          * Check the session is primed.
923                          * for now just allow ONE service to be advertised.
924                          * If you do it twice you just overwrite.
925                          */
926                         if (sp->state != PPPOE_PRIMED) {
927                                 log(LOG_NOTICE, "ng_pppoe[%x]: session not "
928                                     "primed\n", node->nd_ID);
929                                 LEAVE(EISCONN);
930                         }
931                         neg = sp->neg;
932                         neg->service.hdr.tag_type = PTT_SRV_NAME;
933                         neg->service.hdr.tag_len =
934                             htons((uint16_t)ourmsg->data_len);
935
936                         if (ourmsg->data_len)
937                                 bcopy(ourmsg->data, neg->service.data,
938                                     ourmsg->data_len);
939                         neg->service_len = ourmsg->data_len;
940                         break;
941                 case NGM_PPPOE_SETMODE:
942                     {
943                         char *s;
944                         size_t len;
945
946                         if (msg->header.arglen == 0)
947                                 LEAVE(EINVAL);
948
949                         s = (char *)msg->data;
950                         len = msg->header.arglen - 1;
951
952                         /* Search for matching mode string. */
953                         if (len == strlen(NG_PPPOE_STANDARD) &&
954                             (strncmp(NG_PPPOE_STANDARD, s, len) == 0)) {
955                                 privp->flags = 0;
956                                 privp->eh.ether_type = ETHERTYPE_PPPOE_DISC;
957                                 break;
958                         }
959                         if (len == strlen(NG_PPPOE_3COM) &&
960                             (strncmp(NG_PPPOE_3COM, s, len) == 0)) {
961                                 privp->flags |= COMPAT_3COM;
962                                 privp->eh.ether_type =
963                                     ETHERTYPE_PPPOE_3COM_DISC;
964                                 break;
965                         }
966                         if (len == strlen(NG_PPPOE_DLINK) &&
967                             (strncmp(NG_PPPOE_DLINK, s, len) == 0)) {
968                                 privp->flags |= COMPAT_DLINK;
969                                 break;
970                         }
971                         error = EINVAL;
972                         break;
973                     }
974                 case NGM_PPPOE_GETMODE:
975                     {
976                         char *s;
977                         size_t len = 0;
978
979                         if (privp->flags == 0)
980                                 len += strlen(NG_PPPOE_STANDARD) + 1;
981                         if (privp->flags & COMPAT_3COM)
982                                 len += strlen(NG_PPPOE_3COM) + 1;
983                         if (privp->flags & COMPAT_DLINK)
984                                 len += strlen(NG_PPPOE_DLINK) + 1;
985
986                         NG_MKRESPONSE(resp, msg, len, M_NOWAIT);
987                         if (resp == NULL)
988                                 LEAVE(ENOMEM);
989
990                         s = (char *)resp->data;
991                         if (privp->flags == 0) {
992                                 len = strlen(NG_PPPOE_STANDARD);
993                                 strlcpy(s, NG_PPPOE_STANDARD, len + 1);
994                                 break;
995                         }
996                         if (privp->flags & COMPAT_3COM) {
997                                 len = strlen(NG_PPPOE_3COM);
998                                 strlcpy(s, NG_PPPOE_3COM, len + 1);
999                                 s += len;
1000                         }
1001                         if (privp->flags & COMPAT_DLINK) {
1002                                 if (s != resp->data)
1003                                         *s++ = '|';
1004                                 len = strlen(NG_PPPOE_DLINK);
1005                                 strlcpy(s, NG_PPPOE_DLINK, len + 1);
1006                         }
1007                         break;
1008                     }
1009                 case NGM_PPPOE_SETENADDR:
1010                         if (msg->header.arglen != ETHER_ADDR_LEN)
1011                                 LEAVE(EINVAL);
1012                         bcopy(msg->data, &privp->eh.ether_shost,
1013                             ETHER_ADDR_LEN);
1014                         break;
1015                 case NGM_PPPOE_SETMAXP:
1016                         if (msg->header.arglen != sizeof(uint16_t))
1017                                 LEAVE(EINVAL);
1018                         privp->max_payload.hdr.tag_type = PTT_MAX_PAYL;
1019                         privp->max_payload.hdr.tag_len = htons(sizeof(uint16_t));
1020                         privp->max_payload.data = htons(*((uint16_t *)msg->data));
1021                         break;
1022                 default:
1023                         LEAVE(EINVAL);
1024                 }
1025                 break;
1026         case NGM_ETHER_COOKIE:
1027                 if (!(msg->header.flags & NGF_RESP))
1028                         LEAVE(EINVAL);
1029                 switch (msg->header.cmd) {
1030                 case NGM_ETHER_GET_ENADDR:
1031                         if (msg->header.arglen != ETHER_ADDR_LEN)
1032                                 LEAVE(EINVAL);
1033                         bcopy(msg->data, &privp->eh.ether_shost,
1034                             ETHER_ADDR_LEN);
1035                         break;
1036                 default:
1037                         LEAVE(EINVAL);
1038                 }
1039                 break;
1040         default:
1041                 LEAVE(EINVAL);
1042         }
1043
1044         /* Take care of synchronous response, if any. */
1045 quit:
1046         CTR2(KTR_NET, "%20s: returning %d", __func__, error);
1047         NG_RESPOND_MSG(error, node, item, resp);
1048         /* Free the message and return. */
1049         NG_FREE_MSG(msg);
1050         return(error);
1051 }
1052
1053 /*
1054  * Start a client into the first state. A separate function because
1055  * it can be needed if the negotiation times out.
1056  */
1057 static void
1058 pppoe_start(sessp sp)
1059 {
1060         hook_p  hook = sp->hook;
1061         node_p  node = NG_HOOK_NODE(hook);
1062         priv_p  privp = NG_NODE_PRIVATE(node);
1063         negp    neg = sp->neg;
1064         struct {
1065                 struct pppoe_tag hdr;
1066                 union   uniq    data;
1067         } __packed uniqtag;
1068         struct  mbuf *m0;
1069         int     error;
1070
1071         /*
1072          * Kick the state machine into starting up.
1073          */
1074         CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
1075         sp->state = PPPOE_SINIT;
1076         /*
1077          * Reset the packet header to broadcast. Since we are
1078          * in a client mode use configured ethertype.
1079          */
1080         memcpy((void *)&neg->pkt->pkt_header.eh, &privp->eh,
1081             sizeof(struct ether_header));
1082         neg->pkt->pkt_header.ph.code = PADI_CODE;
1083         uniqtag.hdr.tag_type = PTT_HOST_UNIQ;
1084         uniqtag.hdr.tag_len = htons((u_int16_t)sizeof(uniqtag.data));
1085         uniqtag.data.pointer = sp;
1086         init_tags(sp);
1087         insert_tag(sp, &uniqtag.hdr);
1088         insert_tag(sp, &neg->service.hdr);
1089         if (privp->max_payload.data != 0)
1090                 insert_tag(sp, &privp->max_payload.hdr);
1091         make_packet(sp);
1092         /*
1093          * Send packet and prepare to retransmit it after timeout.
1094          */
1095         ng_callout(&neg->handle, node, hook, PPPOE_INITIAL_TIMEOUT * hz,
1096             pppoe_ticker, NULL, 0);
1097         neg->timeout = PPPOE_INITIAL_TIMEOUT * 2;
1098         m0 = m_copypacket(neg->m, M_NOWAIT);
1099         NG_SEND_DATA_ONLY(error, privp->ethernet_hook, m0);
1100 }
1101
1102 static int
1103 send_acname(sessp sp, const struct pppoe_tag *tag)
1104 {
1105         int error, tlen;
1106         struct ng_mesg *msg;
1107         struct ngpppoe_sts *sts;
1108
1109         CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
1110
1111         NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, NGM_PPPOE_ACNAME,
1112             sizeof(struct ngpppoe_sts), M_NOWAIT);
1113         if (msg == NULL)
1114                 return (ENOMEM);
1115
1116         sts = (struct ngpppoe_sts *)msg->data;
1117         tlen = min(NG_HOOKSIZ - 1, ntohs(tag->tag_len));
1118         strncpy(sts->hook, (const char *)(tag + 1), tlen);
1119         sts->hook[tlen] = '\0';
1120         NG_SEND_MSG_ID(error, NG_HOOK_NODE(sp->hook), msg, sp->creator, 0);
1121
1122         return (error);
1123 }
1124
1125 static int
1126 send_sessionid(sessp sp)
1127 {
1128         int error;
1129         struct ng_mesg *msg;
1130
1131         CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
1132
1133         NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, NGM_PPPOE_SESSIONID,
1134             sizeof(uint16_t), M_NOWAIT);
1135         if (msg == NULL)
1136                 return (ENOMEM);
1137
1138         *(uint16_t *)msg->data = sp->Session_ID;
1139         NG_SEND_MSG_ID(error, NG_HOOK_NODE(sp->hook), msg, sp->creator, 0);
1140
1141         return (error);
1142 }
1143
1144 static int
1145 send_maxp(sessp sp, const struct pppoe_tag *tag)
1146 {
1147         int error;
1148         struct ng_mesg *msg;
1149         struct ngpppoe_maxp *maxp;
1150
1151         CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
1152
1153         NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, NGM_PPPOE_SETMAXP,
1154             sizeof(struct ngpppoe_maxp), M_NOWAIT);
1155         if (msg == NULL)
1156                 return (ENOMEM);
1157
1158         maxp = (struct ngpppoe_maxp *)msg->data;
1159         strncpy(maxp->hook, NG_HOOK_NAME(sp->hook), NG_HOOKSIZ);
1160         maxp->data = ntohs(((const struct maxptag *)tag)->data);
1161         NG_SEND_MSG_ID(error, NG_HOOK_NODE(sp->hook), msg, sp->creator, 0);
1162
1163         return (error);
1164 }
1165
1166 /*
1167  * Receive data from session hook and do something with it.
1168  */
1169 static int
1170 ng_pppoe_rcvdata(hook_p hook, item_p item)
1171 {
1172         node_p                  node = NG_HOOK_NODE(hook);
1173         const priv_p            privp = NG_NODE_PRIVATE(node);
1174         sessp                   sp = NG_HOOK_PRIVATE(hook);
1175         struct pppoe_full_hdr   *wh;
1176         struct mbuf             *m;
1177         int                     error;
1178
1179         CTR6(KTR_NET, "%20s: node [%x] (%p) received %p on \"%s\" (%p)",
1180             __func__, node->nd_ID, node, item, hook->hk_name, hook);
1181
1182         NGI_GET_M(item, m);
1183         switch (sp->state) {
1184         case    PPPOE_NEWCONNECTED:
1185         case    PPPOE_CONNECTED: {
1186                 /*
1187                  * Remove PPP address and control fields, if any.
1188                  * For example, ng_ppp(4) always sends LCP packets
1189                  * with address and control fields as required by
1190                  * generic PPP. PPPoE is an exception to the rule.
1191                  */
1192                 if (m->m_pkthdr.len >= 2) {
1193                         if (m->m_len < 2 && !(m = m_pullup(m, 2)))
1194                                 LEAVE(ENOBUFS);
1195                         if (mtod(m, u_char *)[0] == 0xff &&
1196                             mtod(m, u_char *)[1] == 0x03)
1197                                 m_adj(m, 2);
1198                 }
1199                 /*
1200                  * Bang in a pre-made header, and set the length up
1201                  * to be correct. Then send it to the ethernet driver.
1202                  */
1203                 M_PREPEND(m, sizeof(*wh), M_NOWAIT);
1204                 if (m == NULL)
1205                         LEAVE(ENOBUFS);
1206
1207                 wh = mtod(m, struct pppoe_full_hdr *);
1208                 bcopy(&sp->pkt_hdr, wh, sizeof(*wh));
1209                 wh->ph.length = htons(m->m_pkthdr.len - sizeof(*wh));
1210                 NG_FWD_NEW_DATA(error, item, privp->ethernet_hook, m);
1211                 privp->packets_out++;
1212                 break;
1213                 }
1214         case    PPPOE_PRIMED: {
1215                 struct {
1216                         struct pppoe_tag hdr;
1217                         union   uniq    data;
1218                 } __packed      uniqtag;
1219                 const struct pppoe_tag  *tag;
1220                 struct mbuf     *m0;
1221                 const struct pppoe_hdr  *ph;
1222                 negp            neg = sp->neg;
1223                 uint16_t        session;
1224                 uint16_t        length;
1225                 uint8_t         code;
1226
1227                 /*
1228                  * A PADI packet is being returned by the application
1229                  * that has set up this hook. This indicates that it
1230                  * wants us to offer service.
1231                  */
1232                 if (m->m_len < sizeof(*wh)) {
1233                         m = m_pullup(m, sizeof(*wh));
1234                         if (m == NULL)
1235                                 LEAVE(ENOBUFS);
1236                 }
1237                 wh = mtod(m, struct pppoe_full_hdr *);
1238                 ph = &wh->ph;
1239                 session = ntohs(wh->ph.sid);
1240                 length = ntohs(wh->ph.length);
1241                 code = wh->ph.code;
1242                 /* Use peers mode in session. */
1243                 neg->pkt->pkt_header.eh.ether_type = wh->eh.ether_type;
1244                 if (code != PADI_CODE)
1245                         LEAVE(EINVAL);
1246                 ng_uncallout(&neg->handle, node);
1247
1248                 /*
1249                  * This is the first time we hear
1250                  * from the client, so note it's
1251                  * unicast address, replacing the
1252                  * broadcast address.
1253                  */
1254                 bcopy(wh->eh.ether_shost,
1255                         neg->pkt->pkt_header.eh.ether_dhost,
1256                         ETHER_ADDR_LEN);
1257                 sp->state = PPPOE_SOFFER;
1258                 neg->timeout = 0;
1259                 neg->pkt->pkt_header.ph.code = PADO_CODE;
1260
1261                 /*
1262                  * Start working out the tags to respond with.
1263                  */
1264                 uniqtag.hdr.tag_type = PTT_AC_COOKIE;
1265                 uniqtag.hdr.tag_len = htons((u_int16_t)sizeof(sp));
1266                 uniqtag.data.pointer = sp;
1267                 init_tags(sp);
1268                 insert_tag(sp, &neg->ac_name.hdr); /* AC_NAME */
1269                 if ((tag = get_tag(ph, PTT_SRV_NAME)))
1270                         insert_tag(sp, tag);      /* return service */
1271                 /*
1272                  * If we have a NULL service request
1273                  * and have an extra service defined in this hook,
1274                  * then also add a tag for the extra service.
1275                  * XXX this is a hack. eventually we should be able
1276                  * to support advertising many services, not just one
1277                  */
1278                 if (((tag == NULL) || (tag->tag_len == 0)) &&
1279                     (neg->service.hdr.tag_len != 0)) {
1280                         insert_tag(sp, &neg->service.hdr); /* SERVICE */
1281                 }
1282                 if ((tag = get_tag(ph, PTT_HOST_UNIQ)))
1283                         insert_tag(sp, tag); /* returned hostunique */
1284                 insert_tag(sp, &uniqtag.hdr);
1285                 scan_tags(sp, ph);
1286                 make_packet(sp);
1287                 /*
1288                  * Send the offer but if they don't respond
1289                  * in PPPOE_OFFER_TIMEOUT seconds, forget about it.
1290                  */
1291                 ng_callout(&neg->handle, node, hook, PPPOE_OFFER_TIMEOUT * hz,
1292                     pppoe_ticker, NULL, 0);
1293                 m0 = m_copypacket(sp->neg->m, M_NOWAIT);
1294                 NG_FWD_NEW_DATA(error, item, privp->ethernet_hook, m0);
1295                 privp->packets_out++;
1296                 break;
1297                 }
1298
1299         /*
1300          * Packets coming from the hook make no sense
1301          * to sessions in the rest of states. Throw them away.
1302          */
1303         default:
1304                 LEAVE(ENETUNREACH);
1305         }
1306 quit:
1307         if (item)
1308                 NG_FREE_ITEM(item);
1309         NG_FREE_M(m);
1310         return (error);
1311 }
1312
1313 /*
1314  * Receive data from ether and do something with it.
1315  */
1316 static int
1317 ng_pppoe_rcvdata_ether(hook_p hook, item_p item)
1318 {
1319         node_p                  node = NG_HOOK_NODE(hook);
1320         const priv_p            privp = NG_NODE_PRIVATE(node);
1321         sessp                   sp;
1322         const struct pppoe_tag  *utag = NULL, *tag = NULL;
1323         const struct pppoe_full_hdr *wh;
1324         const struct pppoe_hdr  *ph;
1325         negp                    neg = NULL;
1326         struct mbuf             *m;
1327         hook_p                  sendhook;
1328         int                     error = 0;
1329         uint16_t                session;
1330         uint16_t                length;
1331         uint8_t                 code;
1332         struct  mbuf            *m0;
1333
1334         CTR6(KTR_NET, "%20s: node [%x] (%p) received %p on \"%s\" (%p)",
1335             __func__, node->nd_ID, node, item, hook->hk_name, hook);
1336
1337         NGI_GET_M(item, m);
1338         /*
1339          * Dig out various fields from the packet.
1340          * Use them to decide where to send it.
1341          */
1342         privp->packets_in++;
1343         if( m->m_len < sizeof(*wh)) {
1344                 m = m_pullup(m, sizeof(*wh)); /* Checks length */
1345                 if (m == NULL) {
1346                         log(LOG_NOTICE, "ng_pppoe[%x]: couldn't "
1347                             "m_pullup(wh)\n", node->nd_ID);
1348                         LEAVE(ENOBUFS);
1349                 }
1350         }
1351         wh = mtod(m, struct pppoe_full_hdr *);
1352         length = ntohs(wh->ph.length);
1353         switch(wh->eh.ether_type) {
1354         case    ETHERTYPE_PPPOE_3COM_DISC: /* fall through */
1355         case    ETHERTYPE_PPPOE_DISC:
1356                 /*
1357                  * We need to try to make sure that the tag area
1358                  * is contiguous, or we could wander off the end
1359                  * of a buffer and make a mess.
1360                  * (Linux wouldn't have this problem).
1361                  */
1362                 if (m->m_pkthdr.len <= MHLEN) {
1363                         if( m->m_len < m->m_pkthdr.len) {
1364                                 m = m_pullup(m, m->m_pkthdr.len);
1365                                 if (m == NULL) {
1366                                         log(LOG_NOTICE, "ng_pppoe[%x]: "
1367                                             "couldn't m_pullup(pkthdr)\n",
1368                                             node->nd_ID);
1369                                         LEAVE(ENOBUFS);
1370                                 }
1371                         }
1372                 }
1373                 if (m->m_len != m->m_pkthdr.len) {
1374                         /*
1375                          * It's not all in one piece.
1376                          * We need to do extra work.
1377                          * Put it into a cluster.
1378                          */
1379                         struct mbuf *n;
1380                         n = m_dup(m, M_NOWAIT);
1381                         m_freem(m);
1382                         m = n;
1383                         if (m) {
1384                                 /* just check we got a cluster */
1385                                 if (m->m_len != m->m_pkthdr.len) {
1386                                         m_freem(m);
1387                                         m = NULL;
1388                                 }
1389                         }
1390                         if (m == NULL) {
1391                                 log(LOG_NOTICE, "ng_pppoe[%x]: packet "
1392                                     "fragmented\n", node->nd_ID);
1393                                 LEAVE(EMSGSIZE);
1394                         }
1395                 }
1396                 wh = mtod(m, struct pppoe_full_hdr *);
1397                 length = ntohs(wh->ph.length);
1398                 ph = &wh->ph;
1399                 session = ntohs(wh->ph.sid);
1400                 code = wh->ph.code;
1401
1402                 switch(code) {
1403                 case    PADI_CODE:
1404                         /*
1405                          * We are a server:
1406                          * Look for a hook with the required service and send
1407                          * the ENTIRE packet up there. It should come back to
1408                          * a new hook in PRIMED state. Look there for further
1409                          * processing.
1410                          */
1411                         tag = get_tag(ph, PTT_SRV_NAME);
1412                         if (tag == NULL) {
1413                                 CTR1(KTR_NET, "%20s: PADI w/o Service-Name",
1414                                     __func__);
1415                                 LEAVE(ENETUNREACH);
1416                         }
1417
1418                         /*
1419                          * First, try to match Service-Name against our 
1420                          * listening hooks. If no success and we are in D-Link
1421                          * compat mode and Service-Name is empty, then we 
1422                          * broadcast the PADI to all listening hooks.
1423                          */
1424                         sendhook = pppoe_match_svc(node, tag);
1425                         if (sendhook != NULL)
1426                                 NG_FWD_NEW_DATA(error, item, sendhook, m);
1427                         else if (privp->flags & COMPAT_DLINK &&
1428                                  ntohs(tag->tag_len) == 0)
1429                                 error = pppoe_broadcast_padi(node, m);
1430                         else
1431                                 error = ENETUNREACH;
1432                         break;
1433                 case    PADO_CODE:
1434                         /*
1435                          * We are a client:
1436                          * Use the host_uniq tag to find the hook this is in
1437                          * response to. Received #2, now send #3
1438                          * For now simply accept the first we receive.
1439                          */
1440                         utag = get_tag(ph, PTT_HOST_UNIQ);
1441                         if ((utag == NULL) ||
1442                             (ntohs(utag->tag_len) != sizeof(sp))) {
1443                                 log(LOG_NOTICE, "ng_pppoe[%x]: no host "
1444                                     "unique field\n", node->nd_ID);
1445                                 LEAVE(ENETUNREACH);
1446                         }
1447
1448                         sendhook = pppoe_finduniq(node, utag);
1449                         if (sendhook == NULL) {
1450                                 log(LOG_NOTICE, "ng_pppoe[%x]: no "
1451                                     "matching session\n", node->nd_ID);
1452                                 LEAVE(ENETUNREACH);
1453                         }
1454
1455                         /*
1456                          * Check the session is in the right state.
1457                          * It needs to be in PPPOE_SINIT.
1458                          */
1459                         sp = NG_HOOK_PRIVATE(sendhook);
1460                         if (sp->state == PPPOE_SREQ ||
1461                             sp->state == PPPOE_CONNECTED) {
1462                                 break;  /* Multiple PADO is OK. */
1463                         }
1464                         if (sp->state != PPPOE_SINIT) {
1465                                 log(LOG_NOTICE, "ng_pppoe[%x]: session "
1466                                     "in wrong state\n", node->nd_ID);
1467                                 LEAVE(ENETUNREACH);
1468                         }
1469                         neg = sp->neg;
1470                         /* If requested specific AC-name, check it. */
1471                         if (neg->ac_name_len) {
1472                                 tag = get_tag(ph, PTT_AC_NAME);
1473                                 if (!tag) {
1474                                         /* No PTT_AC_NAME in PADO */
1475                                         break;
1476                                 }
1477                                 if (neg->ac_name_len != htons(tag->tag_len) ||
1478                                     strncmp(neg->ac_name.data,
1479                                     (const char *)(tag + 1),
1480                                     neg->ac_name_len) != 0) {
1481                                         break;
1482                                 }
1483                         }
1484                         sp->state = PPPOE_SREQ;
1485                         ng_uncallout(&neg->handle, node);
1486
1487                         /*
1488                          * This is the first time we hear
1489                          * from the server, so note it's
1490                          * unicast address, replacing the
1491                          * broadcast address .
1492                          */
1493                         bcopy(wh->eh.ether_shost,
1494                                 neg->pkt->pkt_header.eh.ether_dhost,
1495                                 ETHER_ADDR_LEN);
1496                         neg->timeout = 0;
1497                         neg->pkt->pkt_header.ph.code = PADR_CODE;
1498                         init_tags(sp);
1499                         insert_tag(sp, utag);           /* Host Unique */
1500                         if ((tag = get_tag(ph, PTT_AC_COOKIE)))
1501                                 insert_tag(sp, tag);    /* return cookie */
1502                         if ((tag = get_tag(ph, PTT_AC_NAME))) { 
1503                                 insert_tag(sp, tag);    /* return it */
1504                                 send_acname(sp, tag);
1505                         }
1506                         if ((tag = get_tag(ph, PTT_MAX_PAYL)) &&
1507                             (privp->max_payload.data != 0))
1508                                 insert_tag(sp, tag);    /* return it */
1509                         insert_tag(sp, &neg->service.hdr); /* Service */
1510                         scan_tags(sp, ph);
1511                         make_packet(sp);
1512                         sp->state = PPPOE_SREQ;
1513                         ng_callout(&neg->handle, node, sp->hook,
1514                             PPPOE_INITIAL_TIMEOUT * hz,
1515                             pppoe_ticker, NULL, 0);
1516                         neg->timeout = PPPOE_INITIAL_TIMEOUT * 2;
1517                         m0 = m_copypacket(neg->m, M_NOWAIT);
1518                         NG_FWD_NEW_DATA(error, item, privp->ethernet_hook, m0);
1519                         break;
1520                 case    PADR_CODE:
1521                         /*
1522                          * We are a server:
1523                          * Use the ac_cookie tag to find the
1524                          * hook this is in response to.
1525                          */
1526                         utag = get_tag(ph, PTT_AC_COOKIE);
1527                         if ((utag == NULL) ||
1528                             (ntohs(utag->tag_len) != sizeof(sp))) {
1529                                 LEAVE(ENETUNREACH);
1530                         }
1531
1532                         sendhook = pppoe_finduniq(node, utag);
1533                         if (sendhook == NULL)
1534                                 LEAVE(ENETUNREACH);
1535
1536                         /*
1537                          * Check the session is in the right state.
1538                          * It needs to be in PPPOE_SOFFER or PPPOE_NEWCONNECTED.
1539                          * If the latter, then this is a retry by the client,
1540                          * so be nice, and resend.
1541                          */
1542                         sp = NG_HOOK_PRIVATE(sendhook);
1543                         if (sp->state == PPPOE_NEWCONNECTED) {
1544                                 /*
1545                                  * Whoa! drop back to resend that PADS packet.
1546                                  * We should still have a copy of it.
1547                                  */
1548                                 sp->state = PPPOE_SOFFER;
1549                         } else if (sp->state != PPPOE_SOFFER)
1550                                 LEAVE (ENETUNREACH);
1551                         neg = sp->neg;
1552                         ng_uncallout(&neg->handle, node);
1553                         neg->pkt->pkt_header.ph.code = PADS_CODE;
1554                         if (sp->Session_ID == 0) {
1555                                 neg->pkt->pkt_header.ph.sid =
1556                                     htons(pppoe_getnewsession(sp));
1557                         }
1558                         send_sessionid(sp);
1559                         neg->timeout = 0;
1560                         /*
1561                          * start working out the tags to respond with.
1562                          */
1563                         init_tags(sp);
1564                         insert_tag(sp, &neg->ac_name.hdr); /* AC_NAME */
1565                         if ((tag = get_tag(ph, PTT_SRV_NAME)))
1566                                 insert_tag(sp, tag);/* return service */
1567                         if ((tag = get_tag(ph, PTT_HOST_UNIQ)))
1568                                 insert_tag(sp, tag); /* return it */
1569                         insert_tag(sp, utag);   /* ac_cookie */
1570                         scan_tags(sp, ph);
1571                         make_packet(sp);
1572                         sp->state = PPPOE_NEWCONNECTED;
1573
1574                         /* Send the PADS without a timeout - we're now connected. */
1575                         m0 = m_copypacket(sp->neg->m, M_NOWAIT);
1576                         NG_FWD_NEW_DATA(error, item, privp->ethernet_hook, m0);
1577
1578                         /*
1579                          * Having sent the last Negotiation header,
1580                          * Set up the stored packet header to be correct for
1581                          * the actual session. But keep the negotialtion stuff
1582                          * around in case we need to resend this last packet.
1583                          * We'll discard it when we move from NEWCONNECTED
1584                          * to CONNECTED
1585                          */
1586                         sp->pkt_hdr = neg->pkt->pkt_header;
1587                         /* Configure ethertype depending on what
1588                          * ethertype was used at discovery phase */
1589                         if (sp->pkt_hdr.eh.ether_type ==
1590                             ETHERTYPE_PPPOE_3COM_DISC)
1591                                 sp->pkt_hdr.eh.ether_type
1592                                         = ETHERTYPE_PPPOE_3COM_SESS;
1593                         else
1594                                 sp->pkt_hdr.eh.ether_type
1595                                         = ETHERTYPE_PPPOE_SESS;
1596                         sp->pkt_hdr.ph.code = 0;
1597                         pppoe_send_event(sp, NGM_PPPOE_SUCCESS);
1598                         break;
1599                 case    PADS_CODE:
1600                         /*
1601                          * We are a client:
1602                          * Use the host_uniq tag to find the hook this is in
1603                          * response to. Take the session ID and store it away.
1604                          * Also make sure the pre-made header is correct and
1605                          * set us into Session mode.
1606                          */
1607                         utag = get_tag(ph, PTT_HOST_UNIQ);
1608                         if ((utag == NULL) ||
1609                             (ntohs(utag->tag_len) != sizeof(sp))) {
1610                                 LEAVE (ENETUNREACH);
1611                         }
1612                         sendhook = pppoe_finduniq(node, utag);
1613                         if (sendhook == NULL)
1614                                 LEAVE(ENETUNREACH);
1615
1616                         /*
1617                          * Check the session is in the right state.
1618                          * It needs to be in PPPOE_SREQ.
1619                          */
1620                         sp = NG_HOOK_PRIVATE(sendhook);
1621                         if (sp->state != PPPOE_SREQ)
1622                                 LEAVE(ENETUNREACH);
1623                         neg = sp->neg;
1624                         ng_uncallout(&neg->handle, node);
1625                         neg->pkt->pkt_header.ph.sid = wh->ph.sid;
1626                         sp->Session_ID = ntohs(wh->ph.sid);
1627                         pppoe_addsession(sp);
1628                         send_sessionid(sp);
1629                         neg->timeout = 0;
1630                         sp->state = PPPOE_CONNECTED;
1631                         /*
1632                          * Now we have gone to Connected mode,
1633                          * Free all resources needed for negotiation.
1634                          * Keep a copy of the header we will be using.
1635                          */
1636                         sp->pkt_hdr = neg->pkt->pkt_header;
1637                         if (privp->flags & COMPAT_3COM)
1638                                 sp->pkt_hdr.eh.ether_type
1639                                         = ETHERTYPE_PPPOE_3COM_SESS;
1640                         else
1641                                 sp->pkt_hdr.eh.ether_type
1642                                         = ETHERTYPE_PPPOE_SESS;
1643                         sp->pkt_hdr.ph.code = 0;
1644                         m_freem(neg->m);
1645                         free(sp->neg, M_NETGRAPH_PPPOE);
1646                         sp->neg = NULL;
1647                         if ((tag = get_tag(ph, PTT_MAX_PAYL)) &&
1648                             (privp->max_payload.data != 0))
1649                                 send_maxp(sp, tag);
1650                         pppoe_send_event(sp, NGM_PPPOE_SUCCESS);
1651                         break;
1652                 case    PADT_CODE:
1653                         /*
1654                          * Find matching peer/session combination.
1655                          */
1656                         sp = pppoe_findsession(privp, wh);
1657                         if (sp == NULL)
1658                                 LEAVE(ENETUNREACH);
1659                         /* Disconnect that hook. */
1660                         ng_rmhook_self(sp->hook);
1661                         break;
1662                 default:
1663                         LEAVE(EPFNOSUPPORT);
1664                 }
1665                 break;
1666         case    ETHERTYPE_PPPOE_3COM_SESS:
1667         case    ETHERTYPE_PPPOE_SESS:
1668                 /*
1669                  * Find matching peer/session combination.
1670                  */
1671                 sp = pppoe_findsession(privp, wh);
1672                 if (sp == NULL)
1673                         LEAVE (ENETUNREACH);
1674                 m_adj(m, sizeof(*wh));
1675
1676                 /* If packet too short, dump it. */
1677                 if (m->m_pkthdr.len < length)
1678                         LEAVE(EMSGSIZE);
1679                 /* Also need to trim excess at the end */
1680                 if (m->m_pkthdr.len > length) {
1681                         m_adj(m, -((int)(m->m_pkthdr.len - length)));
1682                 }
1683                 if ( sp->state != PPPOE_CONNECTED) {
1684                         if (sp->state == PPPOE_NEWCONNECTED) {
1685                                 sp->state = PPPOE_CONNECTED;
1686                                 /*
1687                                  * Now we have gone to Connected mode,
1688                                  * Free all resources needed for negotiation.
1689                                  * Be paranoid about whether there may be
1690                                  * a timeout.
1691                                  */
1692                                 m_freem(sp->neg->m);
1693                                 ng_uncallout(&sp->neg->handle, node);
1694                                 free(sp->neg, M_NETGRAPH_PPPOE);
1695                                 sp->neg = NULL;
1696                         } else {
1697                                 LEAVE (ENETUNREACH);
1698                         }
1699                 }
1700                 NG_FWD_NEW_DATA(error, item, sp->hook, m);
1701                 break;
1702         default:
1703                 LEAVE(EPFNOSUPPORT);
1704         }
1705 quit:
1706         if (item)
1707                 NG_FREE_ITEM(item);
1708         NG_FREE_M(m);
1709         return (error);
1710 }
1711
1712 /*
1713  * Receive data from debug hook and bypass it to ether.
1714  */
1715 static int
1716 ng_pppoe_rcvdata_debug(hook_p hook, item_p item)
1717 {
1718         node_p          node = NG_HOOK_NODE(hook);
1719         const priv_p    privp = NG_NODE_PRIVATE(node);
1720         int             error;
1721
1722         CTR6(KTR_NET, "%20s: node [%x] (%p) received %p on \"%s\" (%p)",
1723             __func__, node->nd_ID, node, item, hook->hk_name, hook);
1724
1725         NG_FWD_ITEM_HOOK(error, item, privp->ethernet_hook);
1726         privp->packets_out++;
1727         return (error);
1728 }
1729
1730 /*
1731  * Do local shutdown processing..
1732  * If we are a persistant device, we might refuse to go away, and
1733  * we'd only remove our links and reset ourself.
1734  */
1735 static int
1736 ng_pppoe_shutdown(node_p node)
1737 {
1738         const priv_p privp = NG_NODE_PRIVATE(node);
1739         int     i;
1740
1741         for (i = 0; i < SESSHASHSIZE; i++)
1742             mtx_destroy(&privp->sesshash[i].mtx);
1743         NG_NODE_SET_PRIVATE(node, NULL);
1744         NG_NODE_UNREF(privp->node);
1745         free(privp, M_NETGRAPH_PPPOE);
1746         return (0);
1747 }
1748
1749 /*
1750  * Hook disconnection
1751  *
1752  * Clean up all dangling links and information about the session/hook.
1753  * For this type, removal of the last link destroys the node.
1754  */
1755 static int
1756 ng_pppoe_disconnect(hook_p hook)
1757 {
1758         node_p node = NG_HOOK_NODE(hook);
1759         priv_p privp = NG_NODE_PRIVATE(node);
1760         sessp   sp;
1761
1762         if (hook == privp->debug_hook) {
1763                 privp->debug_hook = NULL;
1764         } else if (hook == privp->ethernet_hook) {
1765                 privp->ethernet_hook = NULL;
1766                 if (NG_NODE_IS_VALID(node))
1767                         ng_rmnode_self(node);
1768         } else {
1769                 sp = NG_HOOK_PRIVATE(hook);
1770                 if (sp->state != PPPOE_SNONE ) {
1771                         pppoe_send_event(sp, NGM_PPPOE_CLOSE);
1772                 }
1773                 /*
1774                  * According to the spec, if we are connected,
1775                  * we should send a DISC packet if we are shutting down
1776                  * a session.
1777                  */
1778                 if ((privp->ethernet_hook)
1779                 && ((sp->state == PPPOE_CONNECTED)
1780                  || (sp->state == PPPOE_NEWCONNECTED))) {
1781                         struct mbuf *m;
1782
1783                         /* Generate a packet of that type. */
1784                         MGETHDR(m, M_NOWAIT, MT_DATA);
1785                         if (m == NULL)
1786                                 log(LOG_NOTICE, "ng_pppoe[%x]: session out of "
1787                                     "mbufs\n", node->nd_ID);
1788                         else {
1789                                 struct pppoe_full_hdr *wh;
1790                                 struct pppoe_tag *tag;
1791                                 int     msglen = strlen(SIGNOFF);
1792                                 int     error = 0;
1793
1794                                 m->m_pkthdr.rcvif = NULL;
1795                                 m->m_pkthdr.len = m->m_len = sizeof(*wh);
1796                                 wh = mtod(m, struct pppoe_full_hdr *);
1797                                 bcopy(&sp->pkt_hdr, wh, sizeof(*wh));
1798
1799                                 /* Revert the stored header to DISC/PADT mode. */
1800                                 wh->ph.code = PADT_CODE;
1801                                 /*
1802                                  * Configure ethertype depending on what
1803                                  * was used during sessions stage.
1804                                  */
1805                                 if (wh->eh.ether_type == 
1806                                     ETHERTYPE_PPPOE_3COM_SESS)
1807                                         wh->eh.ether_type = ETHERTYPE_PPPOE_3COM_DISC;
1808                                 else
1809                                         wh->eh.ether_type = ETHERTYPE_PPPOE_DISC;
1810                                 /*
1811                                  * Add a General error message and adjust
1812                                  * sizes.
1813                                  */
1814                                 tag = (void *)(&wh->ph + 1);
1815                                 tag->tag_type = PTT_GEN_ERR;
1816                                 tag->tag_len = htons((u_int16_t)msglen);
1817                                 strncpy((char *)(tag + 1), SIGNOFF, msglen);
1818                                 m->m_pkthdr.len = (m->m_len += sizeof(*tag) +
1819                                     msglen);
1820                                 wh->ph.length = htons(sizeof(*tag) + msglen);
1821                                 NG_SEND_DATA_ONLY(error,
1822                                         privp->ethernet_hook, m);
1823                         }
1824                 }
1825                 if (sp->state == PPPOE_LISTENING)
1826                         LIST_REMOVE(sp, sessions);
1827                 else if (sp->Session_ID)
1828                         pppoe_delsession(sp);
1829                 /*
1830                  * As long as we have somewhere to store the timeout handle,
1831                  * we may have a timeout pending.. get rid of it.
1832                  */
1833                 if (sp->neg) {
1834                         ng_uncallout(&sp->neg->handle, node);
1835                         if (sp->neg->m)
1836                                 m_freem(sp->neg->m);
1837                         free(sp->neg, M_NETGRAPH_PPPOE);
1838                 }
1839                 free(sp, M_NETGRAPH_PPPOE);
1840                 NG_HOOK_SET_PRIVATE(hook, NULL);
1841         }
1842         if ((NG_NODE_NUMHOOKS(node) == 0) &&
1843             (NG_NODE_IS_VALID(node)))
1844                 ng_rmnode_self(node);
1845         return (0);
1846 }
1847
1848 /*
1849  * Timeouts come here.
1850  */
1851 static void
1852 pppoe_ticker(node_p node, hook_p hook, void *arg1, int arg2)
1853 {
1854         priv_p privp = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1855         sessp   sp = NG_HOOK_PRIVATE(hook);
1856         negp    neg = sp->neg;
1857         struct mbuf *m0 = NULL;
1858         int     error = 0;
1859
1860         CTR6(KTR_NET, "%20s: node [%x] (%p) hook \"%s\" (%p) session %d",
1861             __func__, node->nd_ID, node, hook->hk_name, hook, sp->Session_ID);
1862         switch(sp->state) {
1863                 /*
1864                  * Resend the last packet, using an exponential backoff.
1865                  * After a period of time, stop growing the backoff,
1866                  * And either leave it, or revert to the start.
1867                  */
1868         case    PPPOE_SINIT:
1869         case    PPPOE_SREQ:
1870                 /* Timeouts on these produce resends. */
1871                 m0 = m_copypacket(sp->neg->m, M_NOWAIT);
1872                 NG_SEND_DATA_ONLY( error, privp->ethernet_hook, m0);
1873                 ng_callout(&neg->handle, node, hook, neg->timeout * hz,
1874                     pppoe_ticker, NULL, 0);
1875                 if ((neg->timeout <<= 1) > PPPOE_TIMEOUT_LIMIT) {
1876                         if (sp->state == PPPOE_SREQ) {
1877                                 /* Revert to SINIT mode. */
1878                                 pppoe_start(sp);
1879                         } else {
1880                                 neg->timeout = PPPOE_TIMEOUT_LIMIT;
1881                         }
1882                 }
1883                 break;
1884         case    PPPOE_PRIMED:
1885         case    PPPOE_SOFFER:
1886                 /* A timeout on these says "give up" */
1887                 ng_rmhook_self(hook);
1888                 break;
1889         default:
1890                 /* Timeouts have no meaning in other states. */
1891                 log(LOG_NOTICE, "ng_pppoe[%x]: unexpected timeout\n",
1892                     node->nd_ID);
1893         }
1894 }
1895
1896 /*
1897  * Parse an incoming packet to see if any tags should be copied to the
1898  * output packet. Don't do any tags that have been handled in the main
1899  * state machine.
1900  */
1901 static const struct pppoe_tag*
1902 scan_tags(sessp sp, const struct pppoe_hdr* ph)
1903 {
1904         const char *const end = (const char *)next_tag(ph);
1905         const char *ptn;
1906         const struct pppoe_tag *pt = (const void *)(ph + 1);
1907
1908         /*
1909          * Keep processing tags while a tag header will still fit.
1910          */
1911         CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
1912
1913         while((const char*)(pt + 1) <= end) {
1914                 /*
1915                  * If the tag data would go past the end of the packet, abort.
1916                  */
1917                 ptn = (((const char *)(pt + 1)) + ntohs(pt->tag_len));
1918                 if(ptn > end)
1919                         return NULL;
1920
1921                 switch (pt->tag_type) {
1922                 case    PTT_RELAY_SID:
1923                         insert_tag(sp, pt);
1924                         break;
1925                 case    PTT_EOL:
1926                         return NULL;
1927                 case    PTT_SRV_NAME:
1928                 case    PTT_AC_NAME:
1929                 case    PTT_HOST_UNIQ:
1930                 case    PTT_AC_COOKIE:
1931                 case    PTT_VENDOR:
1932                 case    PTT_SRV_ERR:
1933                 case    PTT_SYS_ERR:
1934                 case    PTT_GEN_ERR:
1935                 case    PTT_MAX_PAYL:
1936                         break;
1937                 }
1938                 pt = (const struct pppoe_tag*)ptn;
1939         }
1940         return NULL;
1941 }
1942         
1943 static  int
1944 pppoe_send_event(sessp sp, enum cmd cmdid)
1945 {
1946         int error;
1947         struct ng_mesg *msg;
1948         struct ngpppoe_sts *sts;
1949
1950         CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
1951
1952         NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, cmdid,
1953                         sizeof(struct ngpppoe_sts), M_NOWAIT);
1954         if (msg == NULL)
1955                 return (ENOMEM);
1956         sts = (struct ngpppoe_sts *)msg->data;
1957         strncpy(sts->hook, NG_HOOK_NAME(sp->hook), NG_HOOKSIZ);
1958         NG_SEND_MSG_ID(error, NG_HOOK_NODE(sp->hook), msg, sp->creator, 0);
1959         return (error);
1960 }