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