xref: /freebsd/sys/netgraph/ng_pppoe.c (revision ee2ea5ceafed78a5bd9810beb9e3ca927180c226)
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 static int
892 send_acname(sessp sp, struct pppoe_tag *tag)
893 {
894 	int error;
895 	struct ng_mesg *msg;
896 	struct ngpppoe_sts *sts;
897 
898 	NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, NGM_PPPOE_ACNAME,
899 	    sizeof(struct ngpppoe_sts), M_NOWAIT);
900 	if (msg == NULL)
901 		return (ENOMEM);
902 
903 	sts = (struct ngpppoe_sts *)msg->data;
904 	strncpy(sts->hook, tag->tag_data,
905 	    min(NG_HOOKLEN + 1, ntohs(tag->tag_len)));
906 	NG_SEND_MSG_ID(error, NG_HOOK_NODE(sp->hook), msg, sp->creator, NULL);
907 
908 	return (error);
909 }
910 
911 /*
912  * Receive data, and do something with it.
913  * The caller will never free m or meta, so
914  * if we use up this data or abort we must free BOTH of these.
915  */
916 static int
917 ng_pppoe_rcvdata(hook_p hook, item_p item)
918 {
919 	node_p			node = NG_HOOK_NODE(hook);
920 	const priv_p		privp = NG_NODE_PRIVATE(node);
921 	sessp			sp = NG_HOOK_PRIVATE(hook);
922 	struct pppoe_full_hdr	*wh;
923 	struct pppoe_hdr	*ph;
924 	int			error = 0;
925 	u_int16_t		session;
926 	u_int16_t		length;
927 	u_int8_t		code;
928 	struct pppoe_tag	*utag = NULL, *tag = NULL;
929 	hook_p 			sendhook;
930 	struct {
931 		struct pppoe_tag hdr;
932 		union	uniq	data;
933 	} __attribute ((packed)) uniqtag;
934 	negp			neg = NULL;
935 	struct mbuf		*m;
936 
937 AAA
938 	NGI_GET_M(item, m);
939 	if (NG_HOOK_PRIVATE(hook) == &privp->debug_hook) {
940 		/*
941 		 * Data from the debug hook gets sent without modification
942 		 * straight to the ethernet.
943 		 */
944 		NG_FWD_ITEM_HOOK( error, item, privp->ethernet_hook);
945 	 	privp->packets_out++;
946 	} else if (NG_HOOK_PRIVATE(hook) == &privp->ethernet_hook) {
947 		/*
948 		 * Incoming data.
949 		 * Dig out various fields from the packet.
950 		 * use them to decide where to send it.
951 		 */
952 
953  		privp->packets_in++;
954 		if( m->m_len < sizeof(*wh)) {
955 			m = m_pullup(m, sizeof(*wh)); /* Checks length */
956 			if (m == NULL) {
957 				printf("couldn't m_pullup\n");
958 				LEAVE(ENOBUFS);
959 			}
960 		}
961 		wh = mtod(m, struct pppoe_full_hdr *);
962 		length = ntohs(wh->ph.length);
963 		switch(wh->eh.ether_type) {
964 		case	ETHERTYPE_PPPOE_STUPID_DISC:
965 			nonstandard = 1;
966 			eh_prototype.ether_type = ETHERTYPE_PPPOE_STUPID_DISC;
967 			/* fall through */
968 		case	ETHERTYPE_PPPOE_DISC:
969 			/*
970 			 * We need to try to make sure that the tag area
971 			 * is contiguous, or we could wander off the end
972 			 * of a buffer and make a mess.
973 			 * (Linux wouldn't have this problem).
974 			 */
975 			if (m->m_pkthdr.len <= MHLEN) {
976 				if( m->m_len < m->m_pkthdr.len) {
977 					m = m_pullup(m, m->m_pkthdr.len);
978 					if (m == NULL) {
979 						printf("couldn't m_pullup\n");
980 						LEAVE(ENOBUFS);
981 					}
982 				}
983 			}
984 			if (m->m_len != m->m_pkthdr.len) {
985 				/*
986 				 * It's not all in one piece.
987 				 * We need to do extra work.
988 				 * Put it into a cluster.
989 				 */
990 				struct mbuf *n;
991 				n = m_dup(m, M_DONTWAIT);
992 				m_freem(m);
993 				m = n;
994 				if (m) {
995 					/* just check we got a cluster */
996 					if (m->m_len != m->m_pkthdr.len) {
997 						m_freem(m);
998 						m = NULL;
999 					}
1000 				}
1001 				if (m == NULL) {
1002 					printf("packet fragmented\n");
1003 					LEAVE(EMSGSIZE);
1004 				}
1005 			}
1006 			wh = mtod(m, struct pppoe_full_hdr *);
1007 			length = ntohs(wh->ph.length);
1008 			ph = &wh->ph;
1009 			session = ntohs(wh->ph.sid);
1010 			code = wh->ph.code;
1011 
1012 			switch(code) {
1013 			case	PADI_CODE:
1014 				/*
1015 				 * We are a server:
1016 				 * Look for a hook with the required service
1017 				 * and send the ENTIRE packet up there.
1018 				 * It should come back to a new hook in
1019 				 * PRIMED state. Look there for further
1020 				 * processing.
1021 				 */
1022 				tag = get_tag(ph, PTT_SRV_NAME);
1023 				if (tag == NULL) {
1024 					printf("no service tag\n");
1025 					LEAVE(ENETUNREACH);
1026 				}
1027 				sendhook = pppoe_match_svc(NG_HOOK_NODE(hook),
1028 			    		tag->tag_data, ntohs(tag->tag_len),
1029 					NG_MATCH_ANY);
1030 				if (sendhook) {
1031 					NG_FWD_NEW_DATA(error, item,
1032 								sendhook, m);
1033 				} else {
1034 					LEAVE(ENETUNREACH);
1035 				}
1036 				break;
1037 			case	PADO_CODE:
1038 				/*
1039 				 * We are a client:
1040 				 * Use the host_uniq tag to find the
1041 				 * hook this is in response to.
1042 				 * Received #2, now send #3
1043 				 * For now simply accept the first we receive.
1044 				 */
1045 				utag = get_tag(ph, PTT_HOST_UNIQ);
1046 				if ((utag == NULL)
1047 				|| (ntohs(utag->tag_len) != sizeof(sp))) {
1048 					printf("no host unique field\n");
1049 					LEAVE(ENETUNREACH);
1050 				}
1051 
1052 				sendhook = pppoe_finduniq(node, utag);
1053 				if (sendhook == NULL) {
1054 					printf("no matching session\n");
1055 					LEAVE(ENETUNREACH);
1056 				}
1057 
1058 				/*
1059 				 * Check the session is in the right state.
1060 				 * It needs to be in PPPOE_SINIT.
1061 				 */
1062 				sp = NG_HOOK_PRIVATE(sendhook);
1063 				if (sp->state != PPPOE_SINIT) {
1064 					printf("session in wrong state\n");
1065 					LEAVE(ENETUNREACH);
1066 				}
1067 				neg = sp->neg;
1068 				untimeout(pppoe_ticker, sendhook,
1069 				    neg->timeout_handle);
1070 
1071 				/*
1072 				 * This is the first time we hear
1073 				 * from the server, so note it's
1074 				 * unicast address, replacing the
1075 				 * broadcast address .
1076 				 */
1077 				bcopy(wh->eh.ether_shost,
1078 					neg->pkt->pkt_header.eh.ether_dhost,
1079 					ETHER_ADDR_LEN);
1080 				neg->timeout = 0;
1081 				neg->pkt->pkt_header.ph.code = PADR_CODE;
1082 				init_tags(sp);
1083 				insert_tag(sp, utag);      /* Host Unique */
1084 				if ((tag = get_tag(ph, PTT_AC_COOKIE)))
1085 					insert_tag(sp, tag); /* return cookie */
1086 				if ((tag = get_tag(ph, PTT_AC_NAME))) {
1087 					insert_tag(sp, tag); /* return it */
1088 					send_acname(sp, tag);
1089 				}
1090 				insert_tag(sp, &neg->service.hdr); /* Service */
1091 				scan_tags(sp, ph);
1092 				make_packet(sp);
1093 				sp->state = PPPOE_SREQ;
1094 				sendpacket(sp);
1095 				break;
1096 			case	PADR_CODE:
1097 
1098 				/*
1099 				 * We are a server:
1100 				 * Use the ac_cookie tag to find the
1101 				 * hook this is in response to.
1102 				 */
1103 				utag = get_tag(ph, PTT_AC_COOKIE);
1104 				if ((utag == NULL)
1105 				|| (ntohs(utag->tag_len) != sizeof(sp))) {
1106 					LEAVE(ENETUNREACH);
1107 				}
1108 
1109 				sendhook = pppoe_finduniq(node, utag);
1110 				if (sendhook == NULL) {
1111 					LEAVE(ENETUNREACH);
1112 				}
1113 
1114 				/*
1115 				 * Check the session is in the right state.
1116 				 * It needs to be in PPPOE_SOFFER
1117 				 * or PPPOE_NEWCONNECTED. If the latter,
1118 				 * then this is a retry by the client.
1119 				 * so be nice, and resend.
1120 				 */
1121 				sp = NG_HOOK_PRIVATE(sendhook);
1122 				if (sp->state == PPPOE_NEWCONNECTED) {
1123 					/*
1124 					 * Whoa! drop back to resend that
1125 					 * PADS packet.
1126 					 * We should still have a copy of it.
1127 					 */
1128 					sp->state = PPPOE_SOFFER;
1129 				}
1130 				if (sp->state != PPPOE_SOFFER) {
1131 					LEAVE (ENETUNREACH);
1132 					break;
1133 				}
1134 				neg = sp->neg;
1135 				untimeout(pppoe_ticker, sendhook,
1136 				    neg->timeout_handle);
1137 				neg->pkt->pkt_header.ph.code = PADS_CODE;
1138 				if (sp->Session_ID == 0)
1139 					neg->pkt->pkt_header.ph.sid =
1140 					    htons(sp->Session_ID
1141 						= get_new_sid(node));
1142 				neg->timeout = 0;
1143 				/*
1144 				 * start working out the tags to respond with.
1145 				 */
1146 				init_tags(sp);
1147 				insert_tag(sp, &neg->ac_name.hdr); /* AC_NAME */
1148 				if ((tag = get_tag(ph, PTT_SRV_NAME)))
1149 					insert_tag(sp, tag);/* return service */
1150 				if ((tag = get_tag(ph, PTT_HOST_UNIQ)))
1151 					insert_tag(sp, tag); /* return it */
1152 				insert_tag(sp, utag);	/* ac_cookie */
1153 				scan_tags(sp, ph);
1154 				make_packet(sp);
1155 				sp->state = PPPOE_NEWCONNECTED;
1156 				sendpacket(sp);
1157 				/*
1158 				 * Having sent the last Negotiation header,
1159 				 * Set up the stored packet header to
1160 				 * be correct for the actual session.
1161 				 * But keep the negotialtion stuff
1162 				 * around in case we need to resend this last
1163 				 * packet. We'll discard it when we move
1164 				 * from NEWCONNECTED to CONNECTED
1165 				 */
1166 				sp->pkt_hdr = neg->pkt->pkt_header;
1167 				if (nonstandard)
1168 					sp->pkt_hdr.eh.ether_type
1169 						= ETHERTYPE_PPPOE_STUPID_SESS;
1170 				else
1171 					sp->pkt_hdr.eh.ether_type
1172 						= ETHERTYPE_PPPOE_SESS;
1173 				sp->pkt_hdr.ph.code = 0;
1174 				pppoe_send_event(sp, NGM_PPPOE_SUCCESS);
1175 				break;
1176 			case	PADS_CODE:
1177 				/*
1178 				 * We are a client:
1179 				 * Use the host_uniq tag to find the
1180 				 * hook this is in response to.
1181 				 * take the session ID and store it away.
1182 				 * Also make sure the pre-made header is
1183 				 * correct and set us into Session mode.
1184 				 */
1185 				utag = get_tag(ph, PTT_HOST_UNIQ);
1186 				if ((utag == NULL)
1187 				|| (ntohs(utag->tag_len) != sizeof(sp))) {
1188 					LEAVE (ENETUNREACH);
1189 					break;
1190 				}
1191 				sendhook = pppoe_finduniq(node, utag);
1192 				if (sendhook == NULL) {
1193 					LEAVE(ENETUNREACH);
1194 				}
1195 
1196 				/*
1197 				 * Check the session is in the right state.
1198 				 * It needs to be in PPPOE_SREQ.
1199 				 */
1200 				sp = NG_HOOK_PRIVATE(sendhook);
1201 				if (sp->state != PPPOE_SREQ) {
1202 					LEAVE(ENETUNREACH);
1203 				}
1204 				neg = sp->neg;
1205 				untimeout(pppoe_ticker, sendhook,
1206 				    neg->timeout_handle);
1207 				neg->pkt->pkt_header.ph.sid = wh->ph.sid;
1208 				sp->Session_ID = ntohs(wh->ph.sid);
1209 				neg->timeout = 0;
1210 				sp->state = PPPOE_CONNECTED;
1211 				/*
1212 				 * Now we have gone to Connected mode,
1213 				 * Free all resources needed for
1214 				 * negotiation.
1215 				 * Keep a copy of the header we will be using.
1216 				 */
1217 				sp->pkt_hdr = neg->pkt->pkt_header;
1218 				if (nonstandard)
1219 					sp->pkt_hdr.eh.ether_type
1220 						= ETHERTYPE_PPPOE_STUPID_SESS;
1221 				else
1222 					sp->pkt_hdr.eh.ether_type
1223 						= ETHERTYPE_PPPOE_SESS;
1224 				sp->pkt_hdr.ph.code = 0;
1225 				m_freem(neg->m);
1226 				FREE(sp->neg, M_NETGRAPH_PPPOE);
1227 				sp->neg = NULL;
1228 				pppoe_send_event(sp, NGM_PPPOE_SUCCESS);
1229 				break;
1230 			case	PADT_CODE:
1231 				/*
1232 				 * Send a 'close' message to the controlling
1233 				 * process (the one that set us up);
1234 				 * And then tear everything down.
1235 				 *
1236 				 * Find matching peer/session combination.
1237 				 */
1238 				sendhook = pppoe_findsession(node, wh);
1239 				if (sendhook == NULL) {
1240 					LEAVE(ENETUNREACH);
1241 				}
1242 				/* send message to creator */
1243 				/* close hook */
1244 				if (sendhook) {
1245 					ng_rmhook_self(sendhook);
1246 				}
1247 				break;
1248 			default:
1249 				LEAVE(EPFNOSUPPORT);
1250 			}
1251 			break;
1252 		case	ETHERTYPE_PPPOE_STUPID_SESS:
1253 		case	ETHERTYPE_PPPOE_SESS:
1254 			/*
1255 			 * find matching peer/session combination.
1256 			 */
1257 			sendhook = pppoe_findsession(node, wh);
1258 			if (sendhook == NULL) {
1259 				LEAVE (ENETUNREACH);
1260 				break;
1261 			}
1262 			sp = NG_HOOK_PRIVATE(sendhook);
1263 			m_adj(m, sizeof(*wh));
1264 			if (m->m_pkthdr.len < length) {
1265 				/* Packet too short, dump it */
1266 				LEAVE(EMSGSIZE);
1267 			}
1268 
1269 			/* Also need to trim excess at the end */
1270 			if (m->m_pkthdr.len > length) {
1271 				m_adj(m, -((int)(m->m_pkthdr.len - length)));
1272 			}
1273 			if ( sp->state != PPPOE_CONNECTED) {
1274 				if (sp->state == PPPOE_NEWCONNECTED) {
1275 					sp->state = PPPOE_CONNECTED;
1276 					/*
1277 					 * Now we have gone to Connected mode,
1278 					 * Free all resources needed for
1279 					 * negotiation. Be paranoid about
1280 					 * whether there may be a timeout.
1281 					 */
1282 					m_freem(sp->neg->m);
1283 					untimeout(pppoe_ticker, sendhook,
1284 				    		sp->neg->timeout_handle);
1285 					FREE(sp->neg, M_NETGRAPH_PPPOE);
1286 					sp->neg = NULL;
1287 				} else {
1288 					LEAVE (ENETUNREACH);
1289 					break;
1290 				}
1291 			}
1292 			NG_FWD_NEW_DATA( error, item, sendhook, m);
1293 			break;
1294 		default:
1295 			LEAVE(EPFNOSUPPORT);
1296 		}
1297 	} else {
1298 		/*
1299 		 * 	Not ethernet or debug hook..
1300 		 *
1301 		 * The packet has come in on a normal hook.
1302 		 * We need to find out what kind of hook,
1303 		 * So we can decide how to handle it.
1304 		 * Check the hook's state.
1305 		 */
1306 		sp = NG_HOOK_PRIVATE(hook);
1307 		switch (sp->state) {
1308 		case	PPPOE_NEWCONNECTED:
1309 		case	PPPOE_CONNECTED: {
1310 			static const u_char addrctrl[] = { 0xff, 0x03 };
1311 			struct pppoe_full_hdr *wh;
1312 
1313 			/*
1314 			 * Remove PPP address and control fields, if any.
1315 			 * For example, ng_ppp(4) always sends LCP packets
1316 			 * with address and control fields as required by
1317 			 * generic PPP. PPPoE is an exception to the rule.
1318 			 */
1319 			if (m->m_pkthdr.len >= 2) {
1320 				if (m->m_len < 2 && !(m = m_pullup(m, 2)))
1321 					LEAVE(ENOBUFS);
1322 				if (bcmp(mtod(m, u_char *), addrctrl, 2) == 0)
1323 					m_adj(m, 2);
1324 			}
1325 			/*
1326 			 * Bang in a pre-made header, and set the length up
1327 			 * to be correct. Then send it to the ethernet driver.
1328 			 * But first correct the length.
1329 			 */
1330 			sp->pkt_hdr.ph.length = htons((short)(m->m_pkthdr.len));
1331 			M_PREPEND(m, sizeof(*wh), M_DONTWAIT);
1332 			if (m == NULL) {
1333 				LEAVE(ENOBUFS);
1334 			}
1335 			wh = mtod(m, struct pppoe_full_hdr *);
1336 			bcopy(&sp->pkt_hdr, wh, sizeof(*wh));
1337 			NG_FWD_NEW_DATA( error, item, privp->ethernet_hook, m);
1338 			privp->packets_out++;
1339 			break;
1340 			}
1341 		case	PPPOE_PRIMED:
1342 			/*
1343 			 * A PADI packet is being returned by the application
1344 			 * that has set up this hook. This indicates that it
1345 			 * wants us to offer service.
1346 			 */
1347 			neg = sp->neg;
1348 			if (m->m_len < sizeof(*wh)) {
1349 				m = m_pullup(m, sizeof(*wh));
1350 				if (m == NULL) {
1351 					LEAVE(ENOBUFS);
1352 				}
1353 			}
1354 			wh = mtod(m, struct pppoe_full_hdr *);
1355 			ph = &wh->ph;
1356 			session = ntohs(wh->ph.sid);
1357 			length = ntohs(wh->ph.length);
1358 			code = wh->ph.code;
1359 			if ( code != PADI_CODE) {
1360 				LEAVE(EINVAL);
1361 			};
1362 			untimeout(pppoe_ticker, hook,
1363 				    neg->timeout_handle);
1364 
1365 			/*
1366 			 * This is the first time we hear
1367 			 * from the client, so note it's
1368 			 * unicast address, replacing the
1369 			 * broadcast address.
1370 			 */
1371 			bcopy(wh->eh.ether_shost,
1372 				neg->pkt->pkt_header.eh.ether_dhost,
1373 				ETHER_ADDR_LEN);
1374 			sp->state = PPPOE_SOFFER;
1375 			neg->timeout = 0;
1376 			neg->pkt->pkt_header.ph.code = PADO_CODE;
1377 
1378 			/*
1379 			 * start working out the tags to respond with.
1380 			 */
1381 			uniqtag.hdr.tag_type = PTT_AC_COOKIE;
1382 			uniqtag.hdr.tag_len = htons((u_int16_t)sizeof(sp));
1383 			uniqtag.data.pointer = sp;
1384 			init_tags(sp);
1385 			insert_tag(sp, &neg->ac_name.hdr); /* AC_NAME */
1386 			if ((tag = get_tag(ph, PTT_SRV_NAME)))
1387 				insert_tag(sp, tag);	  /* return service */
1388 			/*
1389 			 * If we have a NULL service request
1390 			 * and have an extra service defined in this hook,
1391 			 * then also add a tag for the extra service.
1392 			 * XXX this is a hack. eventually we should be able
1393 			 * to support advertising many services, not just one
1394 			 */
1395 			if (((tag == NULL) || (tag->tag_len == 0))
1396 			&& (neg->service.hdr.tag_len != 0)) {
1397 				insert_tag(sp, &neg->service.hdr); /* SERVICE */
1398 			}
1399 			if ((tag = get_tag(ph, PTT_HOST_UNIQ)))
1400 				insert_tag(sp, tag); /* returned hostunique */
1401 			insert_tag(sp, &uniqtag.hdr);
1402 			scan_tags(sp, ph);
1403 			make_packet(sp);
1404 			sendpacket(sp);
1405 			break;
1406 
1407 		/*
1408 		 * Packets coming from the hook make no sense
1409 		 * to sessions in these states. Throw them away.
1410 		 */
1411 		case	PPPOE_SINIT:
1412 		case	PPPOE_SREQ:
1413 		case	PPPOE_SOFFER:
1414 		case	PPPOE_SNONE:
1415 		case	PPPOE_LISTENING:
1416 		case	PPPOE_DEAD:
1417 		default:
1418 			LEAVE(ENETUNREACH);
1419 		}
1420 	}
1421 quit:
1422 	if (item)
1423 		NG_FREE_ITEM(item);
1424 	NG_FREE_M(m);
1425 	return error;
1426 }
1427 
1428 /*
1429  * Do local shutdown processing..
1430  * If we are a persistant device, we might refuse to go away, and
1431  * we'd only remove our links and reset ourself.
1432  */
1433 static int
1434 ng_pppoe_shutdown(node_p node)
1435 {
1436 	const priv_p privdata = NG_NODE_PRIVATE(node);
1437 
1438 AAA
1439 	NG_NODE_SET_PRIVATE(node, NULL);
1440 	NG_NODE_UNREF(privdata->node);
1441 	FREE(privdata, M_NETGRAPH_PPPOE);
1442 	return (0);
1443 }
1444 
1445 /*
1446  * This is called once we've already connected a new hook to the other node.
1447  * It gives us a chance to balk at the last minute.
1448  */
1449 static int
1450 ng_pppoe_connect(hook_p hook)
1451 {
1452 	/* be really amiable and just say "YUP that's OK by me! " */
1453 	return (0);
1454 }
1455 
1456 /*
1457  * Hook disconnection
1458  *
1459  * Clean up all dangling links and information about the session/hook.
1460  * For this type, removal of the last link destroys the node
1461  */
1462 static int
1463 ng_pppoe_disconnect(hook_p hook)
1464 {
1465 	node_p node = NG_HOOK_NODE(hook);
1466 	priv_p privp = NG_NODE_PRIVATE(node);
1467 	sessp	sp;
1468 	int 	hooks;
1469 
1470 AAA
1471 	hooks = NG_NODE_NUMHOOKS(node); /* this one already not counted */
1472 	if (NG_HOOK_PRIVATE(hook) == &privp->debug_hook) {
1473 		privp->debug_hook = NULL;
1474 	} else if (NG_HOOK_PRIVATE(hook) == &privp->ethernet_hook) {
1475 		privp->ethernet_hook = NULL;
1476 		if (NG_NODE_IS_VALID(node))
1477 			ng_rmnode_self(node);
1478 	} else {
1479 		sp = NG_HOOK_PRIVATE(hook);
1480 		if (sp->state != PPPOE_SNONE ) {
1481 			pppoe_send_event(sp, NGM_PPPOE_CLOSE);
1482 		}
1483 		/*
1484 		 * According to the spec, if we are connected,
1485 		 * we should send a DISC packet if we are shutting down
1486 		 * a session.
1487 		 */
1488 		if ((privp->ethernet_hook)
1489 		&& ((sp->state == PPPOE_CONNECTED)
1490 		 || (sp->state == PPPOE_NEWCONNECTED))) {
1491 			struct mbuf *m;
1492 			struct pppoe_full_hdr *wh;
1493 			struct pppoe_tag *tag;
1494 			int	msglen = strlen(SIGNOFF);
1495 			int error = 0;
1496 
1497 			/* revert the stored header to DISC/PADT mode */
1498 		 	wh = &sp->pkt_hdr;
1499 			wh->ph.code = PADT_CODE;
1500 			if (nonstandard)
1501 				wh->eh.ether_type = ETHERTYPE_PPPOE_STUPID_DISC;
1502 			else
1503 				wh->eh.ether_type = ETHERTYPE_PPPOE_DISC;
1504 
1505 			/* generate a packet of that type */
1506 			MGETHDR(m, M_DONTWAIT, MT_DATA);
1507 			if(m == NULL)
1508 				printf("pppoe: Session out of mbufs\n");
1509 			else {
1510 				m->m_pkthdr.rcvif = NULL;
1511 				m->m_pkthdr.len = m->m_len = sizeof(*wh);
1512 				bcopy((caddr_t)wh, mtod(m, caddr_t),
1513 				    sizeof(*wh));
1514 				/*
1515 				 * Add a General error message and adjust
1516 				 * sizes
1517 				 */
1518 				wh = mtod(m, struct pppoe_full_hdr *);
1519 				tag = wh->ph.tag;
1520 				tag->tag_type = PTT_GEN_ERR;
1521 				tag->tag_len = htons((u_int16_t)msglen);
1522 				strncpy(tag->tag_data, SIGNOFF, msglen);
1523 				m->m_pkthdr.len = (m->m_len += sizeof(*tag) +
1524 				    msglen);
1525 				wh->ph.length = htons(sizeof(*tag) + msglen);
1526 				NG_SEND_DATA_ONLY(error,
1527 					privp->ethernet_hook, m);
1528 			}
1529 		}
1530 		/*
1531 		 * As long as we have somewhere to store the timeout handle,
1532 		 * we may have a timeout pending.. get rid of it.
1533 		 */
1534 		if (sp->neg) {
1535 			untimeout(pppoe_ticker, hook, sp->neg->timeout_handle);
1536 			if (sp->neg->m)
1537 				m_freem(sp->neg->m);
1538 			FREE(sp->neg, M_NETGRAPH_PPPOE);
1539 		}
1540 		FREE(sp, M_NETGRAPH_PPPOE);
1541 		NG_HOOK_SET_PRIVATE(hook, NULL);
1542 		/* work out how many session hooks there are */
1543 		/* Node goes away on last session hook removal */
1544 		if (privp->ethernet_hook) hooks -= 1;
1545 		if (privp->debug_hook) hooks -= 1;
1546 	}
1547 	if ((NG_NODE_NUMHOOKS(node) == 0)
1548 	&& (NG_NODE_IS_VALID(node)))
1549 		ng_rmnode_self(node);
1550 	return (0);
1551 }
1552 
1553 /*
1554  * timeouts come here.
1555  */
1556 static void
1557 pppoe_ticker(void *arg)
1558 {
1559 	int s = splnet();
1560 	hook_p hook = arg;
1561 	sessp	sp = NG_HOOK_PRIVATE(hook);
1562 	negp	neg = sp->neg;
1563 	int	error = 0;
1564 	struct mbuf *m0 = NULL;
1565 	priv_p privp = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1566 
1567 AAA
1568 	switch(sp->state) {
1569 		/*
1570 		 * resend the last packet, using an exponential backoff.
1571 		 * After a period of time, stop growing the backoff,
1572 		 * and either leave it, or revert to the start.
1573 		 */
1574 	case	PPPOE_SINIT:
1575 	case	PPPOE_SREQ:
1576 		/* timeouts on these produce resends */
1577 		m0 = m_copypacket(sp->neg->m, M_DONTWAIT);
1578 		NG_SEND_DATA_ONLY( error, privp->ethernet_hook, m0);
1579 		neg->timeout_handle = timeout(pppoe_ticker,
1580 					hook, neg->timeout * hz);
1581 		if ((neg->timeout <<= 1) > PPPOE_TIMEOUT_LIMIT) {
1582 			if (sp->state == PPPOE_SREQ) {
1583 				/* revert to SINIT mode */
1584 				pppoe_start(sp);
1585 			} else {
1586 				neg->timeout = PPPOE_TIMEOUT_LIMIT;
1587 			}
1588 		}
1589 		break;
1590 	case	PPPOE_PRIMED:
1591 	case	PPPOE_SOFFER:
1592 		/* a timeout on these says "give up" */
1593 		ng_rmhook_self(hook);
1594 		break;
1595 	default:
1596 		/* timeouts have no meaning in other states */
1597 		printf("pppoe: unexpected timeout\n");
1598 	}
1599 	splx(s);
1600 }
1601 
1602 
1603 static void
1604 sendpacket(sessp sp)
1605 {
1606 	int	error = 0;
1607 	struct mbuf *m0 = NULL;
1608 	hook_p hook = sp->hook;
1609 	negp	neg = sp->neg;
1610 	priv_p	privp = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1611 
1612 AAA
1613 	switch(sp->state) {
1614 	case	PPPOE_LISTENING:
1615 	case	PPPOE_DEAD:
1616 	case	PPPOE_SNONE:
1617 	case	PPPOE_CONNECTED:
1618 		printf("pppoe: sendpacket: unexpected state\n");
1619 		break;
1620 
1621 	case	PPPOE_NEWCONNECTED:
1622 		/* send the PADS without a timeout - we're now connected */
1623 		m0 = m_copypacket(sp->neg->m, M_DONTWAIT);
1624 		NG_SEND_DATA_ONLY( error, privp->ethernet_hook, m0);
1625 		break;
1626 
1627 	case	PPPOE_PRIMED:
1628 		/* No packet to send, but set up the timeout */
1629 		neg->timeout_handle = timeout(pppoe_ticker,
1630 					hook, PPPOE_OFFER_TIMEOUT * hz);
1631 		break;
1632 
1633 	case	PPPOE_SOFFER:
1634 		/*
1635 		 * send the offer but if they don't respond
1636 		 * in PPPOE_OFFER_TIMEOUT seconds, forget about it.
1637 		 */
1638 		m0 = m_copypacket(sp->neg->m, M_DONTWAIT);
1639 		NG_SEND_DATA_ONLY( error, privp->ethernet_hook, m0);
1640 		neg->timeout_handle = timeout(pppoe_ticker,
1641 					hook, PPPOE_OFFER_TIMEOUT * hz);
1642 		break;
1643 
1644 	case	PPPOE_SINIT:
1645 	case	PPPOE_SREQ:
1646 		m0 = m_copypacket(sp->neg->m, M_DONTWAIT);
1647 		NG_SEND_DATA_ONLY( error, privp->ethernet_hook, m0);
1648 		neg->timeout_handle = timeout(pppoe_ticker, hook,
1649 					(hz * PPPOE_INITIAL_TIMEOUT));
1650 		neg->timeout = PPPOE_INITIAL_TIMEOUT * 2;
1651 		break;
1652 
1653 	default:
1654 		error = EINVAL;
1655 		printf("pppoe: timeout: bad state\n");
1656 	}
1657 	/* return (error); */
1658 }
1659 
1660 /*
1661  * Parse an incoming packet to see if any tags should be copied to the
1662  * output packet. Don't do any tags that have been handled in the main
1663  * state machine.
1664  */
1665 static struct pppoe_tag*
1666 scan_tags(sessp	sp, struct pppoe_hdr* ph)
1667 {
1668 	char *end = (char *)next_tag(ph);
1669 	char *ptn;
1670 	struct pppoe_tag *pt = &ph->tag[0];
1671 	/*
1672 	 * Keep processing tags while a tag header will still fit.
1673 	 */
1674 AAA
1675 	while((char*)(pt + 1) <= end) {
1676 		/*
1677 		 * If the tag data would go past the end of the packet, abort.
1678 		 */
1679 		ptn = (((char *)(pt + 1)) + ntohs(pt->tag_len));
1680 		if(ptn > end)
1681 			return NULL;
1682 
1683 		switch (pt->tag_type) {
1684 		case	PTT_RELAY_SID:
1685 			insert_tag(sp, pt);
1686 			break;
1687 		case	PTT_EOL:
1688 			return NULL;
1689 		case	PTT_SRV_NAME:
1690 		case	PTT_AC_NAME:
1691 		case	PTT_HOST_UNIQ:
1692 		case	PTT_AC_COOKIE:
1693 		case	PTT_VENDOR:
1694 		case	PTT_SRV_ERR:
1695 		case	PTT_SYS_ERR:
1696 		case	PTT_GEN_ERR:
1697 			break;
1698 		}
1699 		pt = (struct pppoe_tag*)ptn;
1700 	}
1701 	return NULL;
1702 }
1703 
1704 static	int
1705 pppoe_send_event(sessp sp, enum cmd cmdid)
1706 {
1707 	int error;
1708 	struct ng_mesg *msg;
1709 	struct ngpppoe_sts *sts;
1710 
1711 AAA
1712 	NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, cmdid,
1713 			sizeof(struct ngpppoe_sts), M_NOWAIT);
1714 	if (msg == NULL)
1715 		return (ENOMEM);
1716 	sts = (struct ngpppoe_sts *)msg->data;
1717 	strncpy(sts->hook, NG_HOOK_NAME(sp->hook), NG_HOOKLEN + 1);
1718 	NG_SEND_MSG_ID(error, NG_HOOK_NODE(sp->hook), msg, sp->creator, NULL);
1719 	return (error);
1720 }
1721