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