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