Merge from vendor branch OPENSSL:
[dragonfly.git] / sys / netgraph / pppoe / ng_pppoe.c
1
2 /*
3  * ng_pppoe.c
4  *
5  * Copyright (c) 1996-1999 Whistle Communications, Inc.
6  * All rights reserved.
7  * 
8  * Subject to the following obligations and disclaimer of warranty, use and
9  * redistribution of this software, in source or object code forms, with or
10  * without modifications are expressly permitted by Whistle Communications;
11  * provided, however, that:
12  * 1. Any and all reproductions of the source or object code must include the
13  *    copyright notice above and the following disclaimer of warranties; and
14  * 2. No rights are granted, in any manner or form, to use Whistle
15  *    Communications, Inc. trademarks, including the mark "WHISTLE
16  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17  *    such appears in the above copyright notice or in the software.
18  * 
19  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35  * OF SUCH DAMAGE.
36  *
37  * Author: Julian Elischer <julian@freebsd.org>
38  *
39  * $FreeBSD: src/sys/netgraph/ng_pppoe.c,v 1.23.2.17 2002/07/02 22:17:18 archie Exp $
40  * $DragonFly: src/sys/netgraph/pppoe/ng_pppoe.c,v 1.8 2005/06/02 22:11:46 swildner Exp $
41  * $Whistle: ng_pppoe.c,v 1.10 1999/11/01 09:24:52 julian Exp $
42  */
43 #if 0
44 #define AAA printf("pppoe: %s\n", __func__ );
45 #define BBB printf("-%d-", __LINE__ );
46 #else
47 #define AAA
48 #define BBB
49 #endif
50
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/kernel.h>
54 #include <sys/mbuf.h>
55 #include <sys/malloc.h>
56 #include <sys/errno.h>
57 #include <sys/sysctl.h>
58 #include <sys/syslog.h>
59 #include <sys/thread2.h>
60 #include <net/ethernet.h>
61
62 #include <netgraph/ng_message.h>
63 #include <netgraph/netgraph.h>
64 #include "ng_pppoe.h"
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_rmnode;
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_disconnect_t  ng_pppoe_disconnect;
80
81 /* Netgraph node type descriptor */
82 static struct ng_type typestruct = {
83         NG_VERSION,
84         NG_PPPOE_NODE_TYPE,
85         NULL,
86         ng_pppoe_constructor,
87         ng_pppoe_rcvmsg,
88         ng_pppoe_rmnode,
89         ng_pppoe_newhook,
90         NULL,
91         ng_pppoe_connect,
92         ng_pppoe_rcvdata,
93         ng_pppoe_rcvdata,
94         ng_pppoe_disconnect,
95         NULL
96 };
97 NETGRAPH_INIT(pppoe, &typestruct);
98
99 /*
100  * States for the session state machine.
101  * These have no meaning if there is no hook attached yet.
102  */
103 enum state {
104     PPPOE_SNONE=0,      /* [both] Initial state */
105     PPPOE_LISTENING,    /* [Daemon] Listening for discover initiation pkt */
106     PPPOE_SINIT,        /* [Client] Sent discovery initiation */
107     PPPOE_PRIMED,       /* [Server] Awaiting PADI from daemon */
108     PPPOE_SOFFER,       /* [Server] Sent offer message  (got PADI)*/
109     PPPOE_SREQ,         /* [Client] Sent a Request */
110     PPPOE_NEWCONNECTED, /* [Server] Connection established, No data received */
111     PPPOE_CONNECTED,    /* [Both] Connection established, Data received */
112     PPPOE_DEAD          /* [Both] */
113 };
114
115 #define NUMTAGS 20 /* number of tags we are set up to work with */
116
117 /*
118  * Information we store for each hook on each node for negotiating the 
119  * session. The mbuf and cluster are freed once negotiation has completed.
120  * The whole negotiation block is then discarded.
121  */
122
123 struct sess_neg {
124         struct mbuf             *m; /* holds cluster with last sent packet */
125         union   packet          *pkt; /* points within the above cluster */
126         struct callout          timeout_ch;
127         u_int                   timeout; /* 0,1,2,4,8,16 etc. seconds */
128         u_int                   numtags;
129         const struct pppoe_tag  *tags[NUMTAGS];
130         u_int                   service_len;
131         u_int                   ac_name_len;
132
133         struct datatag          service;
134         struct datatag          ac_name;
135 };
136 typedef struct sess_neg *negp;
137
138 /*
139  * Session information that is needed after connection.
140  */
141 struct sess_con {
142         hook_p                  hook;
143         u_int16_t               Session_ID;
144         enum state              state;
145         char                    creator[NG_NODELEN + 1]; /* who to notify */
146         struct pppoe_full_hdr   pkt_hdr;        /* used when connected */
147         negp                    neg;            /* used when negotiating */
148         /*struct sess_con       *hash_next;*/   /* not yet used */
149 };
150 typedef struct sess_con *sessp;
151
152 /*
153  * Information we store for each node
154  */
155 struct PPPOE {
156         node_p          node;           /* back pointer to node */
157         hook_p          ethernet_hook;
158         hook_p          debug_hook;
159         u_int           packets_in;     /* packets in from ethernet */
160         u_int           packets_out;    /* packets out towards ethernet */
161         u_int32_t       flags;
162         /*struct sess_con *buckets[HASH_SIZE];*/        /* not yet used */
163 };
164 typedef struct PPPOE *priv_p;
165
166 struct ether_header eh_prototype =
167         {{0xff,0xff,0xff,0xff,0xff,0xff},
168          {0x00,0x00,0x00,0x00,0x00,0x00},
169          ETHERTYPE_PPPOE_DISC};
170
171 #define PPPOE_KEEPSTANDARD      -1      /* never switch to nonstandard mode */
172 #define PPPOE_STANDARD          0       /* try standard mode (dangerous!) */
173 #define PPPOE_NONSTANDARD       1       /* just be in nonstandard mode */
174 static int pppoe_mode = PPPOE_KEEPSTANDARD;
175
176 static int
177 ngpppoe_set_ethertype(SYSCTL_HANDLER_ARGS)
178 {
179         int error;
180         int val;
181
182         val = pppoe_mode;
183         error = sysctl_handle_int(oidp, &val, sizeof(int), req);
184         if (error != 0 || req->newptr == NULL)
185                 return (error);
186         switch (val) {
187         case PPPOE_NONSTANDARD:
188                 pppoe_mode = PPPOE_NONSTANDARD;
189                 eh_prototype.ether_type = ETHERTYPE_PPPOE_STUPID_DISC;
190                 break;
191         case PPPOE_STANDARD:
192                 pppoe_mode = PPPOE_STANDARD;
193                 eh_prototype.ether_type = ETHERTYPE_PPPOE_DISC;
194                 break;
195         case PPPOE_KEEPSTANDARD:
196                 pppoe_mode = PPPOE_KEEPSTANDARD;
197                 eh_prototype.ether_type = ETHERTYPE_PPPOE_DISC;
198                 break;
199         default:
200                 return (EINVAL);
201         }
202         return (0);
203 }
204
205 SYSCTL_PROC(_net_graph, OID_AUTO, nonstandard_pppoe, CTLTYPE_INT | CTLFLAG_RW,
206     0, sizeof(int), ngpppoe_set_ethertype, "I", "nonstandard ethertype");
207
208 union uniq {
209         char bytes[sizeof(void *)];
210         void * pointer;
211         };
212
213 #define LEAVE(x) do { error = x; goto quit; } while(0)
214 static void     pppoe_start(sessp sp);
215 static void     sendpacket(sessp sp);
216 static void     pppoe_ticker(void *arg);
217 static const    struct pppoe_tag *scan_tags(sessp sp,
218                         const struct pppoe_hdr* ph);
219 static  int     pppoe_send_event(sessp sp, enum cmd cmdid);
220
221 /*************************************************************************
222  * Some basic utilities  from the Linux version with author's permission.*
223  * Author:      Michal Ostrowski <mostrows@styx.uwaterloo.ca>            *
224  ************************************************************************/
225
226 /*
227  * Generate a new session id
228  * XXX find out the FreeBSD locking scheme.
229  */
230 static u_int16_t
231 get_new_sid(node_p node)
232 {
233         static int pppoe_sid = 10;
234         sessp sp;
235         hook_p  hook;
236         u_int16_t val; 
237         priv_p privp = node->private;
238
239 AAA
240 restart:
241         val = pppoe_sid++;
242         /*
243          * Spec says 0xFFFF is reserved.
244          * Also don't use 0x0000
245          */
246         if (val == 0xffff) {
247                 pppoe_sid = 20;
248                 goto restart;
249         }
250
251         /* Check it isn't already in use */
252         LIST_FOREACH(hook, &node->hooks, hooks) {
253                 /* don't check special hooks */
254                 if ((hook->private == &privp->debug_hook)
255                 ||  (hook->private == &privp->ethernet_hook)) 
256                         continue;
257                 sp = hook->private;
258                 if (sp->Session_ID == val)
259                         goto restart;
260         }
261
262         return val;
263 }
264
265
266 /*
267  * Return the location where the next tag can be put 
268  */
269 static __inline const struct pppoe_tag*
270 next_tag(const struct pppoe_hdr* ph)
271 {
272         return (const struct pppoe_tag*)(((const char*)&ph->tag[0])
273             + ntohs(ph->length));
274 }
275
276 /*
277  * Look for a tag of a specific type
278  * Don't trust any length the other end says.
279  * but assume we already sanity checked ph->length.
280  */
281 static const struct pppoe_tag*
282 get_tag(const struct pppoe_hdr* ph, u_int16_t idx)
283 {
284         const char *const end = (const char *)next_tag(ph);
285         const char *ptn;
286         const struct pppoe_tag *pt = &ph->tag[0];
287         /*
288          * Keep processing tags while a tag header will still fit.
289          */
290 AAA
291         while((const char*)(pt + 1) <= end) {
292             /*
293              * If the tag data would go past the end of the packet, abort.
294              */
295             ptn = (((const char *)(pt + 1)) + ntohs(pt->tag_len));
296             if(ptn > end)
297                 return NULL;
298
299             if(pt->tag_type == idx)
300                 return pt;
301
302             pt = (const struct pppoe_tag*)ptn;
303         }
304         return NULL;
305 }
306
307 /**************************************************************************
308  * inlines to initialise or add tags to a session's tag list,
309  **************************************************************************/
310 /*
311  * Initialise the session's tag list
312  */
313 static void
314 init_tags(sessp sp)
315 {
316 AAA
317         if(sp->neg == NULL) {
318                 printf("pppoe: asked to init NULL neg pointer\n");
319                 return;
320         }
321         sp->neg->numtags = 0;
322 }
323
324 static void
325 insert_tag(sessp sp, const struct pppoe_tag *tp)
326 {
327         int     i;
328         negp neg;
329
330 AAA
331         if((neg = sp->neg) == NULL) {
332                 printf("pppoe: asked to use NULL neg pointer\n");
333                 return;
334         }
335         if ((i = neg->numtags++) < NUMTAGS) {
336                 neg->tags[i] = tp;
337         } else {
338                 printf("pppoe: asked to add too many tags to packet\n");
339                 neg->numtags--;
340         }
341 }
342
343 /*
344  * Make up a packet, using the tags filled out for the session.
345  *
346  * Assume that the actual pppoe header and ethernet header 
347  * are filled out externally to this routine.
348  * Also assume that neg->wh points to the correct 
349  * location at the front of the buffer space.
350  */
351 static void
352 make_packet(sessp sp) {
353         struct pppoe_full_hdr *wh = &sp->neg->pkt->pkt_header;
354         const struct pppoe_tag **tag;
355         char *dp;
356         int count;
357         int tlen;
358         u_int16_t length = 0;
359
360 AAA
361         if ((sp->neg == NULL) || (sp->neg->m == NULL)) {
362                 printf("pppoe: make_packet called from wrong state\n");
363         }
364         dp = (char *)wh->ph.tag;
365         for (count = 0, tag = sp->neg->tags;
366             ((count < sp->neg->numtags) && (count < NUMTAGS)); 
367             tag++, count++) {
368                 tlen = ntohs((*tag)->tag_len) + sizeof(**tag);
369                 if ((length + tlen) > (ETHER_MAX_LEN - 4 - sizeof(*wh))) {
370                         printf("pppoe: tags too long\n");
371                         sp->neg->numtags = count;
372                         break;  /* XXX chop off what's too long */
373                 }
374                 bcopy(*tag, (char *)dp, tlen);
375                 length += tlen;
376                 dp += tlen;
377         }
378         wh->ph.length = htons(length);
379         sp->neg->m->m_len = length + sizeof(*wh);
380         sp->neg->m->m_pkthdr.len = length + sizeof(*wh);
381 }
382
383 /**************************************************************************
384  * Routine to match a service offered                                     *
385  **************************************************************************/
386 /* 
387  * Find a hook that has a service string that matches that
388  * we are seeking. for now use a simple string.
389  * In the future we may need something like regexp().
390  * for testing allow a null string to match 1st found and a null service
391  * to match all requests. Also make '*' do the same.
392  */
393
394 #define NG_MATCH_EXACT  1
395 #define NG_MATCH_ANY    2
396
397 static hook_p
398 pppoe_match_svc(node_p node, const char *svc_name, int svc_len, int match)
399 {
400         sessp   sp      = NULL;
401         negp    neg     = NULL;
402         priv_p  privp   = node->private;
403         hook_p  allhook = NULL;
404         hook_p  hook;
405
406 AAA
407         LIST_FOREACH(hook, &node->hooks, hooks) {
408
409                 /* skip any hook that is debug or ethernet */
410                 if ((hook->private == &privp->debug_hook)
411                 ||  (hook->private == &privp->ethernet_hook))
412                         continue;
413                 sp = hook->private;
414
415                 /* Skip any sessions which are not in LISTEN mode. */
416                 if ( sp->state != PPPOE_LISTENING)
417                         continue;
418
419                 neg = sp->neg;
420
421                 /* Special case for a blank or "*" service name (wildcard) */
422                 if (match == NG_MATCH_ANY && neg->service_len == 1 &&
423                     neg->service.data[0] == '*') {
424                         allhook = hook;
425                         continue;
426                 }
427
428                 /* If the lengths don't match, that aint it. */
429                 if (neg->service_len != svc_len)
430                         continue;
431
432                 /* An exact match? */
433                 if (svc_len == 0)
434                         break;
435
436                 if (strncmp(svc_name, neg->service.data, svc_len) == 0)
437                         break;
438         }
439         return (hook ? hook : allhook);
440 }
441 /**************************************************************************
442  * Routine to find a particular session that matches an incoming packet   *
443  **************************************************************************/
444 static hook_p
445 pppoe_findsession(node_p node, const struct pppoe_full_hdr *wh)
446 {
447         sessp   sp = NULL;
448         hook_p hook = NULL;
449         priv_p  privp = node->private;
450         u_int16_t       session = ntohs(wh->ph.sid);
451
452         /*
453          * find matching peer/session combination.
454          */
455 AAA
456         LIST_FOREACH(hook, &node->hooks, hooks) {
457                 /* don't check special hooks */
458                 if ((hook->private == &privp->debug_hook)
459                 ||  (hook->private == &privp->ethernet_hook)) {
460                         continue;
461                 }
462                 sp = hook->private;
463                 if ( ( (sp->state == PPPOE_CONNECTED)
464                     || (sp->state == PPPOE_NEWCONNECTED) )
465                 && (sp->Session_ID == session)
466                 && (bcmp(sp->pkt_hdr.eh.ether_dhost,
467                     wh->eh.ether_shost,
468                     ETHER_ADDR_LEN)) == 0) {
469                         break;
470                 }
471         }
472         return (hook);
473 }
474
475 static hook_p
476 pppoe_finduniq(node_p node, const struct pppoe_tag *tag)
477 {
478         hook_p hook = NULL;
479         priv_p  privp = node->private;
480         union uniq              uniq;
481
482 AAA
483         bcopy(tag->tag_data, uniq.bytes, sizeof(void *));
484         /* cycle through all known hooks */
485         LIST_FOREACH(hook, &node->hooks, hooks) {
486                 /* don't check special hooks */
487                 if ((hook->private == &privp->debug_hook)
488                 ||  (hook->private == &privp->ethernet_hook)) 
489                         continue;
490                 if (uniq.pointer == hook->private)
491                         break;
492         }
493         return (hook);
494 }
495
496 /**************************************************************************
497  * start of Netgraph entrypoints                                          *
498  **************************************************************************/
499
500 /*
501  * Allocate the private data structure and the generic node
502  * and link them together.
503  *
504  * ng_make_node_common() returns with a generic node struct
505  * with a single reference for us.. we transfer it to the
506  * private structure.. when we free the private struct we must
507  * unref the node so it gets freed too.
508  */
509 static int
510 ng_pppoe_constructor(node_p *nodep)
511 {
512         priv_p privdata;
513         int error;
514
515 AAA
516         /* Initialize private descriptor */
517         MALLOC(privdata, priv_p, sizeof(*privdata), M_NETGRAPH, M_NOWAIT);
518         if (privdata == NULL)
519                 return (ENOMEM);
520         bzero(privdata, sizeof(*privdata));
521
522         /* Call the 'generic' (ie, superclass) node constructor */
523         if ((error = ng_make_node_common(&typestruct, nodep))) {
524                 FREE(privdata, M_NETGRAPH);
525                 return (error);
526         }
527
528         /* Link structs together; this counts as our one reference to *nodep */
529         (*nodep)->private = privdata;
530         privdata->node = *nodep;
531         return (0);
532 }
533
534 /*
535  * Give our ok for a hook to be added...
536  * point the hook's private info to the hook structure.
537  *
538  * The following hook names are special:
539  *  Ethernet:  the hook that should be connected to a NIC.
540  *  debug:      copies of data sent out here  (when I write the code).
541  * All other hook names need only be unique. (the framework checks this).
542  */
543 static int
544 ng_pppoe_newhook(node_p node, hook_p hook, const char *name)
545 {
546         const priv_p privp = node->private;
547         sessp sp;
548
549 AAA
550         if (strcmp(name, NG_PPPOE_HOOK_ETHERNET) == 0) {
551                 privp->ethernet_hook = hook;
552                 hook->private = &privp->ethernet_hook;
553         } else if (strcmp(name, NG_PPPOE_HOOK_DEBUG) == 0) {
554                 privp->debug_hook = hook;
555                 hook->private = &privp->debug_hook;
556         } else {
557                 /*
558                  * Any other unique name is OK.
559                  * The infrastructure has already checked that it's unique,
560                  * so just allocate it and hook it in.
561                  */
562                 MALLOC(sp, sessp, sizeof(*sp), M_NETGRAPH, M_NOWAIT);
563                 if (sp == NULL) {
564                                 return (ENOMEM);
565                 }
566                 bzero(sp, sizeof(*sp));
567
568                 hook->private = sp;
569                 sp->hook = hook;
570         }
571         return(0);
572 }
573
574 /*
575  * Get a netgraph control message.
576  * Check it is one we understand. If needed, send a response.
577  * We sometimes save the address for an async action later.
578  * Always free the message.
579  */
580 static int
581 ng_pppoe_rcvmsg(node_p node,
582            struct ng_mesg *msg, const char *retaddr, struct ng_mesg **rptr)
583 {
584         priv_p privp = node->private;
585         struct ngpppoe_init_data *ourmsg = NULL;
586         struct ng_mesg *resp = NULL;
587         int error = 0;
588         hook_p hook = NULL;
589         sessp sp = NULL;
590         negp neg = NULL;
591
592 AAA
593         /* Deal with message according to cookie and command */
594         switch (msg->header.typecookie) {
595         case NGM_PPPOE_COOKIE: 
596                 switch (msg->header.cmd) {
597                 case NGM_PPPOE_CONNECT:
598                 case NGM_PPPOE_LISTEN: 
599                 case NGM_PPPOE_OFFER: 
600                 case NGM_PPPOE_SERVICE: 
601                         ourmsg = (struct ngpppoe_init_data *)msg->data;
602                         if (( sizeof(*ourmsg) > msg->header.arglen)
603                         || ((sizeof(*ourmsg) + ourmsg->data_len)
604                             > msg->header.arglen)) {
605                                 printf("pppoe_rcvmsg: bad arg size");
606                                 LEAVE(EMSGSIZE);
607                         }
608                         if (ourmsg->data_len > PPPOE_SERVICE_NAME_SIZE) {
609                                 printf("pppoe: init data too long (%d)\n",
610                                                         ourmsg->data_len);
611                                 LEAVE(EMSGSIZE);
612                         }
613                         /* make sure strcmp will terminate safely */
614                         ourmsg->hook[sizeof(ourmsg->hook) - 1] = '\0';
615
616                         /* cycle through all known hooks */
617                         LIST_FOREACH(hook, &node->hooks, hooks) {
618                                 if (hook->name
619                                 && strcmp(hook->name, ourmsg->hook) == 0)
620                                         break;
621                         }
622                         if (hook == NULL) {
623                                 LEAVE(ENOENT);
624                         }
625                         if ((hook->private == &privp->debug_hook)
626                         ||  (hook->private == &privp->ethernet_hook)) {
627                                 LEAVE(EINVAL);
628                         }
629                         sp = hook->private;
630
631                         if (msg->header.cmd == NGM_PPPOE_LISTEN) {
632                                 /*
633                                  * Ensure we aren't already listening for this
634                                  * service.
635                                  */
636                                 if (pppoe_match_svc(node, ourmsg->data,
637                                     ourmsg->data_len, NG_MATCH_EXACT) != NULL) {
638                                         LEAVE(EEXIST);
639                                 }
640                         }
641
642                         /*
643                          * PPPOE_SERVICE advertisments are set up
644                          * on sessions that are in PRIMED state.
645                          */
646                         if (msg->header.cmd == NGM_PPPOE_SERVICE) {
647                                 break;
648                         }
649                         if (sp->state |= PPPOE_SNONE) {
650                                 printf("pppoe: Session already active\n");
651                                 LEAVE(EISCONN);
652                         }
653
654                         /*
655                          * set up prototype header
656                          */
657                         MALLOC(neg, negp, sizeof(*neg), M_NETGRAPH, M_NOWAIT);
658
659                         if (neg == NULL) {
660                                 printf("pppoe: Session out of memory\n");
661                                 LEAVE(ENOMEM);
662                         }
663                         bzero(neg, sizeof(*neg));
664                         MGETHDR(neg->m, MB_DONTWAIT, MT_DATA);
665                         if(neg->m == NULL) {
666                                 printf("pppoe: Session out of mbufs\n");
667                                 FREE(neg, M_NETGRAPH);
668                                 LEAVE(ENOBUFS);
669                         }
670                         neg->m->m_pkthdr.rcvif = NULL;
671                         MCLGET(neg->m, MB_DONTWAIT);
672                         if ((neg->m->m_flags & M_EXT) == 0) {
673                                 printf("pppoe: Session out of mcls\n");
674                                 m_freem(neg->m);
675                                 FREE(neg, M_NETGRAPH);
676                                 LEAVE(ENOBUFS);
677                         }
678                         sp->neg = neg;
679                         callout_init(&neg->timeout_ch);
680                         neg->m->m_len = sizeof(struct pppoe_full_hdr);
681                         neg->pkt = mtod(neg->m, union packet*);
682                         neg->pkt->pkt_header.eh = eh_prototype;
683                         neg->pkt->pkt_header.ph.ver = 0x1;
684                         neg->pkt->pkt_header.ph.type = 0x1;
685                         neg->pkt->pkt_header.ph.sid = 0x0000;
686                         neg->timeout = 0;
687
688                         strncpy(sp->creator, retaddr, NG_NODELEN);
689                         sp->creator[NG_NODELEN] = '\0';
690                 }
691                 switch (msg->header.cmd) {
692                 case NGM_PPPOE_GET_STATUS:
693                     {
694                         struct ngpppoestat *stats;
695
696                         NG_MKRESPONSE(resp, msg, sizeof(*stats), M_NOWAIT);
697                         if (!resp) {
698                                 LEAVE(ENOMEM);
699                         }
700                         stats = (struct ngpppoestat *) resp->data;
701                         stats->packets_in = privp->packets_in;
702                         stats->packets_out = privp->packets_out;
703                         break;
704                     }
705                 case NGM_PPPOE_CONNECT:
706                         /*
707                          * Check the hook exists and is Uninitialised.
708                          * Send a PADI request, and start the timeout logic.
709                          * Store the originator of this message so we can send
710                          * a success of fail message to them later.
711                          * Move the session to SINIT
712                          * Set up the session to the correct state and
713                          * start it.
714                          */
715                         neg->service.hdr.tag_type = PTT_SRV_NAME;
716                         neg->service.hdr.tag_len =
717                                         htons((u_int16_t)ourmsg->data_len);
718                         if (ourmsg->data_len) {
719                                 bcopy(ourmsg->data,
720                                         neg->service.data, ourmsg->data_len);
721                         }
722                         neg->service_len = ourmsg->data_len;
723                         pppoe_start(sp);
724                         break;
725                 case NGM_PPPOE_LISTEN:
726                         /*
727                          * Check the hook exists and is Uninitialised.
728                          * Install the service matching string.
729                          * Store the originator of this message so we can send
730                          * a success of fail message to them later.
731                          * Move the hook to 'LISTENING'
732                          */
733                         neg->service.hdr.tag_type = PTT_SRV_NAME;
734                         neg->service.hdr.tag_len =
735                                         htons((u_int16_t)ourmsg->data_len);
736
737                         if (ourmsg->data_len) {
738                                 bcopy(ourmsg->data,
739                                         neg->service.data, ourmsg->data_len);
740                         }
741                         neg->service_len = ourmsg->data_len;
742                         neg->pkt->pkt_header.ph.code = PADT_CODE;
743                         /*
744                          * wait for PADI packet coming from ethernet
745                          */
746                         sp->state = PPPOE_LISTENING;
747                         break;
748                 case NGM_PPPOE_OFFER:
749                         /*
750                          * Check the hook exists and is Uninitialised.
751                          * Store the originator of this message so we can send
752                          * a success of fail message to them later.
753                          * Store the AC-Name given and go to PRIMED.
754                          */
755                         neg->ac_name.hdr.tag_type = PTT_AC_NAME;
756                         neg->ac_name.hdr.tag_len =
757                                         htons((u_int16_t)ourmsg->data_len);
758                         if (ourmsg->data_len) {
759                                 bcopy(ourmsg->data,
760                                         neg->ac_name.data, ourmsg->data_len);
761                         }
762                         neg->ac_name_len = ourmsg->data_len;
763                         neg->pkt->pkt_header.ph.code = PADO_CODE;
764                         /*
765                          * Wait for PADI packet coming from hook
766                          */
767                         sp->state = PPPOE_PRIMED;
768                         break;
769                 case NGM_PPPOE_SERVICE: 
770                         /* 
771                          * Check the session is primed.
772                          * for now just allow ONE service to be advertised.
773                          * If you do it twice you just overwrite.
774                          */
775                         if (sp->state != PPPOE_PRIMED) {
776                                 printf("pppoe: Session not primed\n");
777                                 LEAVE(EISCONN);
778                         }
779                         neg = sp->neg;
780                         neg->service.hdr.tag_type = PTT_SRV_NAME;
781                         neg->service.hdr.tag_len =
782                             htons((u_int16_t)ourmsg->data_len);
783
784                         if (ourmsg->data_len)
785                                 bcopy(ourmsg->data, neg->service.data,
786                                     ourmsg->data_len);
787                         neg->service_len = ourmsg->data_len;
788                         break;
789                 default:
790                         LEAVE(EINVAL);
791                 }
792                 break;
793         default:
794                 LEAVE(EINVAL);
795         }
796
797         /* Take care of synchronous response, if any */
798         if (rptr)
799                 *rptr = resp;
800         else if (resp)
801                 FREE(resp, M_NETGRAPH);
802
803         /* Free the message and return */
804 quit:
805         FREE(msg, M_NETGRAPH);
806         return(error);
807 }
808
809 /*
810  * Start a client into the first state. A separate function because
811  * it can be needed if the negotiation times out.
812  */
813 static void
814 pppoe_start(sessp sp)
815 {
816         struct {
817                 struct pppoe_tag hdr;
818                 union   uniq    data;
819         } __attribute ((packed)) uniqtag;
820
821         /* 
822          * kick the state machine into starting up
823          */
824 AAA
825         sp->state = PPPOE_SINIT;
826         /* reset the packet header to broadcast */
827         sp->neg->pkt->pkt_header.eh = eh_prototype;
828         sp->neg->pkt->pkt_header.ph.code = PADI_CODE;
829         uniqtag.hdr.tag_type = PTT_HOST_UNIQ;
830         uniqtag.hdr.tag_len = htons((u_int16_t)sizeof(uniqtag.data));
831         uniqtag.data.pointer = sp;
832         init_tags(sp);
833         insert_tag(sp, &uniqtag.hdr);
834         insert_tag(sp, &sp->neg->service.hdr);
835         make_packet(sp);
836         sendpacket(sp);
837 }
838
839 static int
840 send_acname(sessp sp, const struct pppoe_tag *tag)
841 {
842         int error, tlen;
843         struct ng_mesg *msg;
844         struct ngpppoe_sts *sts;
845
846         NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, NGM_PPPOE_ACNAME,
847             sizeof(struct ngpppoe_sts), M_NOWAIT);
848         if (msg == NULL)
849                 return (ENOMEM);
850
851         sts = (struct ngpppoe_sts *)msg->data;
852         tlen = min(NG_HOOKLEN, ntohs(tag->tag_len));
853         strncpy(sts->hook, tag->tag_data, tlen);
854         sts->hook[tlen] = '\0';
855         error = ng_send_msg(sp->hook->node, msg, sp->creator, NULL);
856
857         return (error);
858 }
859
860 static int
861 send_sessionid(sessp sp)
862 {
863         int error;
864         struct ng_mesg *msg;
865
866         NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, NGM_PPPOE_SESSIONID,
867             sizeof(u_int16_t), M_NOWAIT);
868         if (msg == NULL)
869                 return (ENOMEM);
870
871         *(u_int16_t *)msg->data = sp->Session_ID;
872         error = ng_send_msg(sp->hook->node, msg, sp->creator, NULL);
873
874         return (error);
875 }
876
877 /*
878  * Receive data, and do something with it.
879  * The caller will never free m or meta, so
880  * if we use up this data or abort we must free BOTH of these.
881  */
882 static int
883 ng_pppoe_rcvdata(hook_p hook, struct mbuf *m, meta_p meta)
884 {
885         node_p                  node = hook->node;
886         const priv_p            privp = node->private;
887         sessp                   sp = hook->private;
888         const struct pppoe_full_hdr *wh;
889         const struct pppoe_hdr  *ph;
890         int                     error = 0;
891         u_int16_t               session;
892         u_int16_t               length;
893         u_int8_t                code;
894         const struct pppoe_tag  *utag = NULL, *tag = NULL;
895         hook_p                  sendhook;
896         struct {
897                 struct pppoe_tag hdr;
898                 union   uniq    data;
899         } __attribute ((packed)) uniqtag;
900         negp                    neg = NULL;
901
902 AAA
903         if (hook->private == &privp->debug_hook) {
904                 /*
905                  * Data from the debug hook gets sent without modification
906                  * straight to the ethernet. 
907                  */
908                 NG_SEND_DATA( error, privp->ethernet_hook, m, meta);
909                 privp->packets_out++;
910         } else if (hook->private == &privp->ethernet_hook) {
911                 /*
912                  * Incoming data. 
913                  * Dig out various fields from the packet.
914                  * use them to decide where to send it.
915                  */
916                 
917                 privp->packets_in++;
918                 if( m->m_len < sizeof(*wh)) {
919                         m = m_pullup(m, sizeof(*wh)); /* Checks length */
920                         if (m == NULL) {
921                                 printf("couldn't m_pullup\n");
922                                 LEAVE(ENOBUFS);
923                         }
924                 }
925                 wh = mtod(m, struct pppoe_full_hdr *);
926                 ph = &wh->ph;
927                 session = ntohs(wh->ph.sid);
928                 length = ntohs(wh->ph.length);
929                 code = wh->ph.code; 
930                 switch(wh->eh.ether_type) {
931                 case    ETHERTYPE_PPPOE_STUPID_DISC:
932                         if (pppoe_mode == PPPOE_STANDARD) {
933                                 pppoe_mode = PPPOE_NONSTANDARD;
934                                 eh_prototype.ether_type =
935                                     ETHERTYPE_PPPOE_STUPID_DISC;
936                                 log(LOG_NOTICE,
937                                     "Switched to nonstandard PPPoE mode due to "
938                                     "packet from %*D\n",
939                                     ETHER_ADDR_LEN,
940                                     wh->eh.ether_shost, ":");
941                         } else if (pppoe_mode == PPPOE_KEEPSTANDARD)
942                                 log(LOG_NOTICE,
943                                     "Ignored nonstandard PPPoE packet "
944                                     "from %*D\n",
945                                     ETHER_ADDR_LEN,
946                                     wh->eh.ether_shost, ":");
947                         /* fall through */
948                 case    ETHERTYPE_PPPOE_DISC:
949                         /*
950                          * We need to try to make sure that the tag area
951                          * is contiguous, or we could wander off the end
952                          * of a buffer and make a mess. 
953                          * (Linux wouldn't have this problem).
954                          */
955 /*XXX fix this mess */
956                         
957                         if (m->m_pkthdr.len <= MHLEN) {
958                                 if( m->m_len < m->m_pkthdr.len) {
959                                         m = m_pullup(m, m->m_pkthdr.len);
960                                         if (m == NULL) {
961                                                 printf("couldn't m_pullup\n");
962                                                 LEAVE(ENOBUFS);
963                                         }
964                                 }
965                         }
966                         if (m->m_len != m->m_pkthdr.len) {
967                                 /*
968                                  * It's not all in one piece.
969                                  * We need to do extra work.
970                                  */
971                                 printf("packet fragmented\n");
972                                 LEAVE(EMSGSIZE);
973                         }
974
975                         switch(code) {
976                         case    PADI_CODE:
977                                 /*
978                                  * We are a server:
979                                  * Look for a hook with the required service
980                                  * and send the ENTIRE packet up there.
981                                  * It should come back to a new hook in 
982                                  * PRIMED state. Look there for further
983                                  * processing.
984                                  */
985                                 tag = get_tag(ph, PTT_SRV_NAME);
986                                 if (tag == NULL) {
987                                         printf("no service tag\n");
988                                         LEAVE(ENETUNREACH);
989                                 }
990                                 sendhook = pppoe_match_svc(hook->node,
991                                         tag->tag_data, ntohs(tag->tag_len),
992                                         NG_MATCH_ANY);
993                                 if (sendhook) {
994                                         NG_SEND_DATA(error, sendhook, m, meta);
995                                 } else {
996                                         LEAVE(ENETUNREACH);
997                                 }
998                                 break;
999                         case    PADO_CODE:
1000                                 /*
1001                                  * We are a client:
1002                                  * Use the host_uniq tag to find the 
1003                                  * hook this is in response to.
1004                                  * Received #2, now send #3
1005                                  * For now simply accept the first we receive.
1006                                  */
1007                                 utag = get_tag(ph, PTT_HOST_UNIQ);
1008                                 if ((utag == NULL)
1009                                 || (ntohs(utag->tag_len) != sizeof(sp))) {
1010                                         printf("no host unique field\n");
1011                                         LEAVE(ENETUNREACH);
1012                                 }
1013
1014                                 sendhook = pppoe_finduniq(node, utag);
1015                                 if (sendhook == NULL) {
1016                                         printf("no matching session\n");
1017                                         LEAVE(ENETUNREACH);
1018                                 }
1019
1020                                 /*
1021                                  * Check the session is in the right state.
1022                                  * It needs to be in PPPOE_SINIT.
1023                                  */
1024                                 sp = sendhook->private;
1025                                 if (sp->state != PPPOE_SINIT) {
1026                                         printf("session in wrong state\n");
1027                                         LEAVE(ENETUNREACH);
1028                                 }
1029                                 neg = sp->neg;
1030                                 callout_stop(&neg->timeout_ch);
1031
1032                                 /*
1033                                  * This is the first time we hear
1034                                  * from the server, so note it's
1035                                  * unicast address, replacing the
1036                                  * broadcast address .
1037                                  */
1038                                 bcopy(wh->eh.ether_shost,
1039                                         neg->pkt->pkt_header.eh.ether_dhost,
1040                                         ETHER_ADDR_LEN);
1041                                 neg->timeout = 0;
1042                                 neg->pkt->pkt_header.ph.code = PADR_CODE;
1043                                 init_tags(sp);
1044                                 insert_tag(sp, utag);      /* Host Unique */
1045                                 if ((tag = get_tag(ph, PTT_AC_COOKIE)))
1046                                         insert_tag(sp, tag); /* return cookie */
1047                                 if ((tag = get_tag(ph, PTT_AC_NAME))) { 
1048                                         insert_tag(sp, tag); /* return it */
1049                                         send_acname(sp, tag);
1050                                 }
1051                                 insert_tag(sp, &neg->service.hdr); /* Service */
1052                                 scan_tags(sp, ph);
1053                                 make_packet(sp);
1054                                 sp->state = PPPOE_SREQ;
1055                                 sendpacket(sp);
1056                                 break;
1057                         case    PADR_CODE:
1058
1059                                 /*
1060                                  * We are a server:
1061                                  * Use the ac_cookie tag to find the 
1062                                  * hook this is in response to.
1063                                  */
1064                                 utag = get_tag(ph, PTT_AC_COOKIE);
1065                                 if ((utag == NULL)
1066                                 || (ntohs(utag->tag_len) != sizeof(sp))) {
1067                                         LEAVE(ENETUNREACH);
1068                                 }
1069
1070                                 sendhook = pppoe_finduniq(node, utag);
1071                                 if (sendhook == NULL) {
1072                                         LEAVE(ENETUNREACH);
1073                                 }
1074
1075                                 /*
1076                                  * Check the session is in the right state.
1077                                  * It needs to be in PPPOE_SOFFER
1078                                  * or PPPOE_NEWCONNECTED. If the latter,
1079                                  * then this is a retry by the client.
1080                                  * so be nice, and resend.
1081                                  */
1082                                 sp = sendhook->private;
1083                                 if (sp->state == PPPOE_NEWCONNECTED) {
1084                                         /*
1085                                          * Whoa! drop back to resend that 
1086                                          * PADS packet.
1087                                          * We should still have a copy of it.
1088                                          */
1089                                         sp->state = PPPOE_SOFFER;
1090                                 }
1091                                 if (sp->state != PPPOE_SOFFER) {
1092                                         LEAVE (ENETUNREACH);
1093                                         break;
1094                                 }
1095                                 neg = sp->neg;
1096                                 callout_stop(&neg->timeout_ch);
1097                                 neg->pkt->pkt_header.ph.code = PADS_CODE;
1098                                 if (sp->Session_ID == 0)
1099                                         neg->pkt->pkt_header.ph.sid =
1100                                             htons(sp->Session_ID
1101                                                 = get_new_sid(node));
1102                                 send_sessionid(sp);
1103                                 neg->timeout = 0;
1104                                 /*
1105                                  * start working out the tags to respond with.
1106                                  */
1107                                 init_tags(sp);
1108                                 insert_tag(sp, &neg->ac_name.hdr); /* AC_NAME */
1109                                 if ((tag = get_tag(ph, PTT_SRV_NAME)))
1110                                         insert_tag(sp, tag);/* return service */
1111                                 if ((tag = get_tag(ph, PTT_HOST_UNIQ)))
1112                                         insert_tag(sp, tag); /* return it */
1113                                 insert_tag(sp, utag);   /* ac_cookie */
1114                                 scan_tags(sp, ph);
1115                                 make_packet(sp);
1116                                 sp->state = PPPOE_NEWCONNECTED;
1117                                 sendpacket(sp);
1118                                 /*
1119                                  * Having sent the last Negotiation header,
1120                                  * Set up the stored packet header to 
1121                                  * be correct for the actual session.
1122                                  * But keep the negotialtion stuff
1123                                  * around in case we need to resend this last 
1124                                  * packet. We'll discard it when we move
1125                                  * from NEWCONNECTED to CONNECTED
1126                                  */
1127                                 sp->pkt_hdr = neg->pkt->pkt_header;
1128                                 if (pppoe_mode == PPPOE_NONSTANDARD)
1129                                         sp->pkt_hdr.eh.ether_type
1130                                                 = ETHERTYPE_PPPOE_STUPID_SESS;
1131                                 else
1132                                         sp->pkt_hdr.eh.ether_type
1133                                                 = ETHERTYPE_PPPOE_SESS;
1134                                 sp->pkt_hdr.ph.code = 0;
1135                                 pppoe_send_event(sp, NGM_PPPOE_SUCCESS);
1136                                 break;
1137                         case    PADS_CODE:
1138                                 /*
1139                                  * We are a client:
1140                                  * Use the host_uniq tag to find the 
1141                                  * hook this is in response to.
1142                                  * take the session ID and store it away.
1143                                  * Also make sure the pre-made header is
1144                                  * correct and set us into Session mode.
1145                                  */
1146                                 utag = get_tag(ph, PTT_HOST_UNIQ);
1147                                 if ((utag == NULL)
1148                                 || (ntohs(utag->tag_len) != sizeof(sp))) {
1149                                         LEAVE (ENETUNREACH);
1150                                         break;
1151                                 }
1152                                 sendhook = pppoe_finduniq(node, utag);
1153                                 if (sendhook == NULL) {
1154                                         LEAVE(ENETUNREACH);
1155                                 }
1156
1157                                 /*
1158                                  * Check the session is in the right state.
1159                                  * It needs to be in PPPOE_SREQ.
1160                                  */
1161                                 sp = sendhook->private;
1162                                 if (sp->state != PPPOE_SREQ) {
1163                                         LEAVE(ENETUNREACH);
1164                                 }
1165                                 neg = sp->neg;
1166                                 callout_stop(&neg->timeout_ch);
1167                                 neg->pkt->pkt_header.ph.sid = wh->ph.sid;
1168                                 sp->Session_ID = ntohs(wh->ph.sid);
1169                                 send_sessionid(sp);
1170                                 neg->timeout = 0;
1171                                 sp->state = PPPOE_CONNECTED;
1172                                 /*
1173                                  * Now we have gone to Connected mode, 
1174                                  * Free all resources needed for 
1175                                  * negotiation.
1176                                  * Keep a copy of the header we will be using.
1177                                  */
1178                                 sp->pkt_hdr = neg->pkt->pkt_header;
1179                                 if (pppoe_mode == PPPOE_NONSTANDARD)
1180                                         sp->pkt_hdr.eh.ether_type
1181                                                 = ETHERTYPE_PPPOE_STUPID_SESS;
1182                                 else
1183                                         sp->pkt_hdr.eh.ether_type
1184                                                 = ETHERTYPE_PPPOE_SESS;
1185                                 sp->pkt_hdr.ph.code = 0;
1186                                 m_freem(neg->m);
1187                                 FREE(sp->neg, M_NETGRAPH);
1188                                 sp->neg = NULL;
1189                                 pppoe_send_event(sp, NGM_PPPOE_SUCCESS);
1190                                 break;
1191                         case    PADT_CODE:
1192                                 /*
1193                                  * Send a 'close' message to the controlling
1194                                  * process (the one that set us up);
1195                                  * And then tear everything down.
1196                                  *
1197                                  * Find matching peer/session combination.
1198                                  */
1199                                 sendhook = pppoe_findsession(node, wh);
1200                                 NG_FREE_DATA(m, meta); /* no longer needed */
1201                                 if (sendhook == NULL) {
1202                                         LEAVE(ENETUNREACH);
1203                                 }
1204                                 /* send message to creator */
1205                                 /* close hook */
1206                                 if (sendhook) {
1207                                         ng_destroy_hook(sendhook);
1208                                 }
1209                                 break;
1210                         default:
1211                                 LEAVE(EPFNOSUPPORT);
1212                         }
1213                         break;
1214                 case    ETHERTYPE_PPPOE_STUPID_SESS:
1215                 case    ETHERTYPE_PPPOE_SESS:
1216                         /*
1217                          * find matching peer/session combination.
1218                          */
1219                         sendhook = pppoe_findsession(node, wh);
1220                         if (sendhook == NULL) {
1221                                 LEAVE (ENETUNREACH);
1222                                 break;
1223                         }
1224                         sp = sendhook->private;
1225                         m_adj(m, sizeof(*wh));
1226                         if (m->m_pkthdr.len < length) {
1227                                 /* Packet too short, dump it */
1228                                 LEAVE(EMSGSIZE);
1229                         }
1230
1231                         /* Also need to trim excess at the end */
1232                         if (m->m_pkthdr.len > length) {
1233                                 m_adj(m, -((int)(m->m_pkthdr.len - length)));
1234                         }
1235                         if ( sp->state != PPPOE_CONNECTED) {
1236                                 if (sp->state == PPPOE_NEWCONNECTED) {
1237                                         sp->state = PPPOE_CONNECTED;
1238                                         /*
1239                                          * Now we have gone to Connected mode, 
1240                                          * Free all resources needed for 
1241                                          * negotiation. Be paranoid about
1242                                          * whether there may be a timeout.
1243                                          */
1244                                         m_freem(sp->neg->m);
1245                                         callout_stop(&sp->neg->timeout_ch);
1246                                         FREE(sp->neg, M_NETGRAPH);
1247                                         sp->neg = NULL;
1248                                 } else {
1249                                         LEAVE (ENETUNREACH);
1250                                         break;
1251                                 }
1252                         }
1253                         NG_SEND_DATA( error, sendhook, m, meta);
1254                         break;
1255                 default:
1256                         LEAVE(EPFNOSUPPORT);
1257                 }
1258         } else {
1259                 /*
1260                  *      Not ethernet or debug hook..
1261                  *
1262                  * The packet has come in on a normal hook.
1263                  * We need to find out what kind of hook,
1264                  * So we can decide how to handle it.
1265                  * Check the hook's state.
1266                  */
1267                 sp = hook->private;
1268                 switch (sp->state) {
1269                 case    PPPOE_NEWCONNECTED:
1270                 case    PPPOE_CONNECTED: {
1271                         static const u_char addrctrl[] = { 0xff, 0x03 };
1272                         struct pppoe_full_hdr *wh;
1273
1274                         /*
1275                          * Remove PPP address and control fields, if any.
1276                          * For example, ng_ppp(4) always sends LCP packets
1277                          * with address and control fields as required by
1278                          * generic PPP. PPPoE is an exception to the rule.
1279                          */
1280                         if (m->m_pkthdr.len >= 2) {
1281                                 if (m->m_len < 2 && !(m = m_pullup(m, 2)))
1282                                         LEAVE(ENOBUFS);
1283                                 if (bcmp(mtod(m, u_char *), addrctrl, 2) == 0)
1284                                         m_adj(m, 2);
1285                         }
1286                         /*
1287                          * Bang in a pre-made header, and set the length up
1288                          * to be correct. Then send it to the ethernet driver.
1289                          * But first correct the length.
1290                          */
1291                         sp->pkt_hdr.ph.length = htons((short)(m->m_pkthdr.len));
1292                         M_PREPEND(m, sizeof(*wh), MB_DONTWAIT);
1293                         if (m == NULL) {
1294                                 LEAVE(ENOBUFS);
1295                         }
1296                         wh = mtod(m, struct pppoe_full_hdr *);
1297                         bcopy(&sp->pkt_hdr, wh, sizeof(*wh));
1298                         NG_SEND_DATA( error, privp->ethernet_hook, m, meta);
1299                         privp->packets_out++;
1300                         break;
1301                         }
1302                 case    PPPOE_PRIMED:
1303                         /*
1304                          * A PADI packet is being returned by the application
1305                          * that has set up this hook. This indicates that it 
1306                          * wants us to offer service.
1307                          */
1308                         neg = sp->neg;
1309                         if (m->m_len < sizeof(*wh)) {
1310                                 m = m_pullup(m, sizeof(*wh));
1311                                 if (m == NULL) {
1312                                         LEAVE(ENOBUFS);
1313                                 }
1314                         }
1315                         wh = mtod(m, struct pppoe_full_hdr *);
1316                         ph = &wh->ph;
1317                         session = ntohs(wh->ph.sid);
1318                         length = ntohs(wh->ph.length);
1319                         code = wh->ph.code; 
1320                         if ( code != PADI_CODE) {
1321                                 LEAVE(EINVAL);
1322                         };
1323                         callout_stop(&neg->timeout_ch);
1324
1325                         /*
1326                          * This is the first time we hear
1327                          * from the client, so note it's
1328                          * unicast address, replacing the
1329                          * broadcast address.
1330                          */
1331                         bcopy(wh->eh.ether_shost,
1332                                 neg->pkt->pkt_header.eh.ether_dhost,
1333                                 ETHER_ADDR_LEN);
1334                         sp->state = PPPOE_SOFFER;
1335                         neg->timeout = 0;
1336                         neg->pkt->pkt_header.ph.code = PADO_CODE;
1337
1338                         /*
1339                          * start working out the tags to respond with.
1340                          */
1341                         uniqtag.hdr.tag_type = PTT_AC_COOKIE;
1342                         uniqtag.hdr.tag_len = htons((u_int16_t)sizeof(sp));
1343                         uniqtag.data.pointer = sp;
1344                         init_tags(sp);
1345                         insert_tag(sp, &neg->ac_name.hdr); /* AC_NAME */
1346                         if ((tag = get_tag(ph, PTT_SRV_NAME)))
1347                                 insert_tag(sp, tag);      /* return service */
1348                         /*
1349                          * If we have a NULL service request
1350                          * and have an extra service defined in this hook,
1351                          * then also add a tag for the extra service.
1352                          * XXX this is a hack. eventually we should be able
1353                          * to support advertising many services, not just one 
1354                          */
1355                         if (((tag == NULL) || (tag->tag_len == 0))
1356                         && (neg->service.hdr.tag_len != 0)) {
1357                                 insert_tag(sp, &neg->service.hdr); /* SERVICE */
1358                         }
1359                         if ((tag = get_tag(ph, PTT_HOST_UNIQ)))
1360                                 insert_tag(sp, tag); /* returned hostunique */
1361                         insert_tag(sp, &uniqtag.hdr);
1362                         scan_tags(sp, ph);
1363                         make_packet(sp);
1364                         sendpacket(sp);
1365                         break;
1366
1367                 /*
1368                  * Packets coming from the hook make no sense
1369                  * to sessions in these states. Throw them away.
1370                  */
1371                 case    PPPOE_SINIT:
1372                 case    PPPOE_SREQ:
1373                 case    PPPOE_SOFFER:
1374                 case    PPPOE_SNONE:
1375                 case    PPPOE_LISTENING:
1376                 case    PPPOE_DEAD:
1377                 default:
1378                         LEAVE(ENETUNREACH);
1379                 }
1380         }
1381 quit:
1382         NG_FREE_DATA(m, meta);
1383         return error;
1384 }
1385
1386 /*
1387  * Do local shutdown processing..
1388  * If we are a persistant device, we might refuse to go away, and
1389  * we'd only remove our links and reset ourself.
1390  */
1391 static int
1392 ng_pppoe_rmnode(node_p node)
1393 {
1394         const priv_p privdata = node->private;
1395
1396 AAA
1397         node->flags |= NG_INVALID;
1398         ng_cutlinks(node);
1399         ng_unname(node);
1400         node->private = NULL;
1401         ng_unref(privdata->node);
1402         FREE(privdata, M_NETGRAPH);
1403         return (0);
1404 }
1405
1406 /*
1407  * This is called once we've already connected a new hook to the other node.
1408  * It gives us a chance to balk at the last minute.
1409  */
1410 static int
1411 ng_pppoe_connect(hook_p hook)
1412 {
1413         /* be really amiable and just say "YUP that's OK by me! " */
1414         return (0);
1415 }
1416
1417 /*
1418  * Hook disconnection
1419  *
1420  * Clean up all dangling links and information about the session/hook.
1421  * For this type, removal of the last link destroys the node
1422  */
1423 static int
1424 ng_pppoe_disconnect(hook_p hook)
1425 {
1426         node_p node = hook->node;
1427         priv_p privp = node->private;
1428         sessp   sp;
1429         int     hooks;
1430
1431 AAA
1432         hooks = node->numhooks; /* this one already not counted */
1433         if (hook->private == &privp->debug_hook) {
1434                 privp->debug_hook = NULL;
1435         } else if (hook->private == &privp->ethernet_hook) {
1436                 privp->ethernet_hook = NULL;
1437                 ng_rmnode(node);
1438         } else {
1439                 sp = hook->private;
1440                 if (sp->state != PPPOE_SNONE ) {
1441                         pppoe_send_event(sp, NGM_PPPOE_CLOSE);
1442                 }
1443                 /*
1444                  * According to the spec, if we are connected,
1445                  * we should send a DISC packet if we are shutting down
1446                  * a session.
1447                  */
1448                 if ((privp->ethernet_hook)
1449                 && ((sp->state == PPPOE_CONNECTED)
1450                  || (sp->state == PPPOE_NEWCONNECTED))) {
1451                         struct mbuf *m;
1452                         struct pppoe_full_hdr *wh;
1453                         struct pppoe_tag *tag;
1454                         int     msglen = strlen(SIGNOFF);
1455                         void *dummy = NULL;
1456                         int error = 0;
1457
1458                         /* revert the stored header to DISC/PADT mode */
1459                         wh = &sp->pkt_hdr;
1460                         wh->ph.code = PADT_CODE;
1461                         if (pppoe_mode == PPPOE_NONSTANDARD)
1462                                 wh->eh.ether_type = ETHERTYPE_PPPOE_STUPID_DISC;
1463                         else
1464                                 wh->eh.ether_type = ETHERTYPE_PPPOE_DISC;
1465
1466                         /* generate a packet of that type */
1467                         MGETHDR(m, MB_DONTWAIT, MT_DATA);
1468                         if(m == NULL)
1469                                 printf("pppoe: Session out of mbufs\n");
1470                         else {
1471                                 m->m_pkthdr.rcvif = NULL;
1472                                 m->m_pkthdr.len = m->m_len = sizeof(*wh);
1473                                 bcopy((caddr_t)wh, mtod(m, caddr_t),
1474                                     sizeof(*wh));
1475                                 /*
1476                                  * Add a General error message and adjust
1477                                  * sizes
1478                                  */
1479                                 wh = mtod(m, struct pppoe_full_hdr *);
1480                                 tag = wh->ph.tag;
1481                                 tag->tag_type = PTT_GEN_ERR;
1482                                 tag->tag_len = htons((u_int16_t)msglen);
1483                                 strncpy(tag->tag_data, SIGNOFF, msglen);
1484                                 m->m_pkthdr.len = (m->m_len += sizeof(*tag) +
1485                                     msglen);
1486                                 wh->ph.length = htons(sizeof(*tag) + msglen);
1487                                 NG_SEND_DATA(error, privp->ethernet_hook, m,
1488                                     dummy);
1489                         }
1490                 }
1491                 /*
1492                  * As long as we have somewhere to store the timeout handle,
1493                  * we may have a timeout pending.. get rid of it.
1494                  */
1495                 if (sp->neg) {
1496                         callout_stop(&sp->neg->timeout_ch);
1497                         if (sp->neg->m)
1498                                 m_freem(sp->neg->m);
1499                         FREE(sp->neg, M_NETGRAPH);
1500                 }
1501                 FREE(sp, M_NETGRAPH);
1502                 hook->private = NULL;
1503                 /* work out how many session hooks there are */
1504                 /* Node goes away on last session hook removal */
1505                 if (privp->ethernet_hook) hooks -= 1;
1506                 if (privp->debug_hook) hooks -= 1;
1507         }
1508         if (node->numhooks == 0)
1509                 ng_rmnode(node);
1510         return (0);
1511 }
1512
1513 /*
1514  * timeouts come here.
1515  */
1516 static void
1517 pppoe_ticker(void *arg)
1518 {
1519         hook_p hook = arg;
1520         sessp   sp = hook->private;
1521         negp    neg = sp->neg;
1522         int     error = 0;
1523         struct mbuf *m0 = NULL;
1524         priv_p privp = hook->node->private;
1525         meta_p dummy = NULL;
1526
1527         crit_enter();
1528 AAA
1529         switch(sp->state) {
1530                 /*
1531                  * resend the last packet, using an exponential backoff.
1532                  * After a period of time, stop growing the backoff,
1533                  * and either leave it, or revert to the start.
1534                  */
1535         case    PPPOE_SINIT:
1536         case    PPPOE_SREQ:
1537                 /* timeouts on these produce resends */
1538                 m0 = m_copypacket(sp->neg->m, MB_DONTWAIT);
1539                 NG_SEND_DATA( error, privp->ethernet_hook, m0, dummy);
1540                 callout_reset(&neg->timeout_ch, neg->timeout * hz,
1541                                 pppoe_ticker, hook);
1542                 if ((neg->timeout <<= 1) > PPPOE_TIMEOUT_LIMIT) {
1543                         if (sp->state == PPPOE_SREQ) {
1544                                 /* revert to SINIT mode */
1545                                 pppoe_start(sp);
1546                         } else {
1547                                 neg->timeout = PPPOE_TIMEOUT_LIMIT;
1548                         }
1549                 }
1550                 break;
1551         case    PPPOE_PRIMED:
1552         case    PPPOE_SOFFER:
1553                 /* a timeout on these says "give up" */
1554                 ng_destroy_hook(hook);
1555                 break;
1556         default:
1557                 /* timeouts have no meaning in other states */
1558                 printf("pppoe: unexpected timeout\n");
1559         }
1560         crit_exit();
1561 }
1562
1563
1564 static void
1565 sendpacket(sessp sp)
1566 {
1567         int     error = 0;
1568         struct mbuf *m0 = NULL;
1569         hook_p hook = sp->hook;
1570         negp    neg = sp->neg;
1571         priv_p  privp = hook->node->private;
1572         meta_p dummy = NULL;
1573
1574 AAA
1575         switch(sp->state) {
1576         case    PPPOE_LISTENING:
1577         case    PPPOE_DEAD:
1578         case    PPPOE_SNONE:
1579         case    PPPOE_CONNECTED:
1580                 printf("pppoe: sendpacket: unexpected state\n");
1581                 break;
1582
1583         case    PPPOE_NEWCONNECTED:
1584                 /* send the PADS without a timeout - we're now connected */
1585                 m0 = m_copypacket(sp->neg->m, MB_DONTWAIT);
1586                 NG_SEND_DATA( error, privp->ethernet_hook, m0, dummy);
1587                 break;
1588
1589         case    PPPOE_PRIMED:
1590                 /* No packet to send, but set up the timeout */
1591                 callout_reset(&neg->timeout_ch, PPPOE_OFFER_TIMEOUT * hz,
1592                                 pppoe_ticker, hook);
1593                 break;
1594
1595         case    PPPOE_SOFFER:
1596                 /*
1597                  * send the offer but if they don't respond
1598                  * in PPPOE_OFFER_TIMEOUT seconds, forget about it.
1599                  */
1600                 m0 = m_copypacket(sp->neg->m, MB_DONTWAIT);
1601                 NG_SEND_DATA( error, privp->ethernet_hook, m0, dummy);
1602                 callout_reset(&neg->timeout_ch, PPPOE_OFFER_TIMEOUT * hz,
1603                                 pppoe_ticker, hook);
1604                 break;
1605
1606         case    PPPOE_SINIT:
1607         case    PPPOE_SREQ:
1608                 m0 = m_copypacket(sp->neg->m, MB_DONTWAIT);
1609                 NG_SEND_DATA( error, privp->ethernet_hook, m0, dummy);
1610                 callout_reset(&neg->timeout_ch, PPPOE_INITIAL_TIMEOUT * hz,
1611                                 pppoe_ticker, hook);
1612                 neg->timeout = PPPOE_INITIAL_TIMEOUT * 2;
1613                 break;
1614
1615         default:
1616                 error = EINVAL;
1617                 printf("pppoe: timeout: bad state\n");
1618         }
1619         /* return (error); */
1620 }
1621
1622 /*
1623  * Parse an incoming packet to see if any tags should be copied to the
1624  * output packet. Don't do any tags that have been handled in the main
1625  * state machine.
1626  */
1627 static const struct pppoe_tag* 
1628 scan_tags(sessp sp, const struct pppoe_hdr* ph)
1629 {
1630         const char *const end = (const char *)next_tag(ph);
1631         const char *ptn;
1632         const struct pppoe_tag *pt = &ph->tag[0];
1633         /*
1634          * Keep processing tags while a tag header will still fit.
1635          */
1636 AAA
1637         while((const char*)(pt + 1) <= end) {
1638                 /*
1639                  * If the tag data would go past the end of the packet, abort.
1640                  */
1641                 ptn = (((const char *)(pt + 1)) + ntohs(pt->tag_len));
1642                 if(ptn > end)
1643                         return NULL;
1644
1645                 switch (pt->tag_type) {
1646                 case    PTT_RELAY_SID:
1647                         insert_tag(sp, pt);
1648                         break;
1649                 case    PTT_EOL:
1650                         return NULL;
1651                 case    PTT_SRV_NAME:
1652                 case    PTT_AC_NAME:
1653                 case    PTT_HOST_UNIQ:
1654                 case    PTT_AC_COOKIE:
1655                 case    PTT_VENDOR:
1656                 case    PTT_SRV_ERR:
1657                 case    PTT_SYS_ERR:
1658                 case    PTT_GEN_ERR:
1659                         break;
1660                 }
1661                 pt = (const struct pppoe_tag*)ptn;
1662         }
1663         return NULL;
1664 }
1665         
1666 static  int
1667 pppoe_send_event(sessp sp, enum cmd cmdid)
1668 {
1669         int error;
1670         struct ng_mesg *msg;
1671         struct ngpppoe_sts *sts;
1672
1673 AAA
1674         NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, cmdid,
1675                         sizeof(struct ngpppoe_sts), M_NOWAIT);
1676         if (msg == NULL)
1677                 return (ENOMEM);
1678         sts = (struct ngpppoe_sts *)msg->data;
1679         strncpy(sts->hook, sp->hook->name, NG_HOOKLEN + 1);
1680         error = ng_send_msg(sp->hook->node, msg, sp->creator, NULL);
1681         return (error);
1682 }