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