xref: /freebsd/sys/netgraph/ng_pppoe.c (revision b3512b30dbec579da28028e29d8b33ec7242af68)
1 /*
2  * ng_pppoe.c
3  */
4 
5 /*-
6  * Copyright (c) 1996-1999 Whistle Communications, Inc.
7  * All rights reserved.
8  *
9  * Subject to the following obligations and disclaimer of warranty, use and
10  * redistribution of this software, in source or object code forms, with or
11  * without modifications are expressly permitted by Whistle Communications;
12  * provided, however, that:
13  * 1. Any and all reproductions of the source or object code must include the
14  *    copyright notice above and the following disclaimer of warranties; and
15  * 2. No rights are granted, in any manner or form, to use Whistle
16  *    Communications, Inc. trademarks, including the mark "WHISTLE
17  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
18  *    such appears in the above copyright notice or in the software.
19  *
20  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
21  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
22  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
23  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
25  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
26  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
27  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
28  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
29  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
30  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
31  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
32  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
36  * OF SUCH DAMAGE.
37  *
38  * Author: Julian Elischer <julian@freebsd.org>
39  *
40  * $FreeBSD$
41  * $Whistle: ng_pppoe.c,v 1.10 1999/11/01 09:24:52 julian Exp $
42  */
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/ktr.h>
48 #include <sys/mbuf.h>
49 #include <sys/malloc.h>
50 #include <sys/errno.h>
51 #include <sys/syslog.h>
52 #include <net/ethernet.h>
53 
54 #include <netgraph/ng_message.h>
55 #include <netgraph/netgraph.h>
56 #include <netgraph/ng_parse.h>
57 #include <netgraph/ng_pppoe.h>
58 #include <netgraph/ng_ether.h>
59 
60 #ifdef NG_SEPARATE_MALLOC
61 static MALLOC_DEFINE(M_NETGRAPH_PPPOE, "netgraph_pppoe", "netgraph pppoe node");
62 #else
63 #define M_NETGRAPH_PPPOE M_NETGRAPH
64 #endif
65 
66 #define SIGNOFF "session closed"
67 
68 /*
69  * This section contains the netgraph method declarations for the
70  * pppoe node. These methods define the netgraph pppoe 'type'.
71  */
72 
73 static ng_constructor_t	ng_pppoe_constructor;
74 static ng_rcvmsg_t	ng_pppoe_rcvmsg;
75 static ng_shutdown_t	ng_pppoe_shutdown;
76 static ng_newhook_t	ng_pppoe_newhook;
77 static ng_connect_t	ng_pppoe_connect;
78 static ng_rcvdata_t	ng_pppoe_rcvdata;
79 static ng_rcvdata_t	ng_pppoe_rcvdata_ether;
80 static ng_rcvdata_t	ng_pppoe_rcvdata_debug;
81 static ng_disconnect_t	ng_pppoe_disconnect;
82 
83 /* Parse type for struct ngpppoe_init_data */
84 static const struct ng_parse_struct_field ngpppoe_init_data_type_fields[]
85 	= NG_PPPOE_INIT_DATA_TYPE_INFO;
86 static const struct ng_parse_type ngpppoe_init_data_state_type = {
87 	&ng_parse_struct_type,
88 	&ngpppoe_init_data_type_fields
89 };
90 
91 /* Parse type for struct ngpppoe_sts */
92 static const struct ng_parse_struct_field ng_pppoe_sts_type_fields[]
93 	= NG_PPPOE_STS_TYPE_INFO;
94 static const struct ng_parse_type ng_pppoe_sts_state_type = {
95 	&ng_parse_struct_type,
96 	&ng_pppoe_sts_type_fields
97 };
98 
99 /* List of commands and how to convert arguments to/from ASCII */
100 static const struct ng_cmdlist ng_pppoe_cmds[] = {
101 	{
102 	  NGM_PPPOE_COOKIE,
103 	  NGM_PPPOE_CONNECT,
104 	  "pppoe_connect",
105 	  &ngpppoe_init_data_state_type,
106 	  NULL
107 	},
108 	{
109 	  NGM_PPPOE_COOKIE,
110 	  NGM_PPPOE_LISTEN,
111 	  "pppoe_listen",
112 	  &ngpppoe_init_data_state_type,
113 	  NULL
114 	},
115 	{
116 	  NGM_PPPOE_COOKIE,
117 	  NGM_PPPOE_OFFER,
118 	  "pppoe_offer",
119 	  &ngpppoe_init_data_state_type,
120 	  NULL
121 	},
122 	{
123 	  NGM_PPPOE_COOKIE,
124 	  NGM_PPPOE_SERVICE,
125 	  "pppoe_service",
126 	  &ngpppoe_init_data_state_type,
127 	  NULL
128 	},
129 	{
130 	  NGM_PPPOE_COOKIE,
131 	  NGM_PPPOE_SUCCESS,
132 	  "pppoe_success",
133 	  &ng_pppoe_sts_state_type,
134 	  NULL
135 	},
136 	{
137 	  NGM_PPPOE_COOKIE,
138 	  NGM_PPPOE_FAIL,
139 	  "pppoe_fail",
140 	  &ng_pppoe_sts_state_type,
141 	  NULL
142 	},
143 	{
144 	  NGM_PPPOE_COOKIE,
145 	  NGM_PPPOE_CLOSE,
146 	  "pppoe_close",
147 	  &ng_pppoe_sts_state_type,
148 	  NULL
149 	},
150 	{
151 	  NGM_PPPOE_COOKIE,
152 	  NGM_PPPOE_SETMODE,
153 	  "pppoe_setmode",
154 	  &ng_parse_string_type,
155 	  NULL
156 	},
157 	{
158 	  NGM_PPPOE_COOKIE,
159 	  NGM_PPPOE_GETMODE,
160 	  "pppoe_getmode",
161 	  NULL,
162 	  &ng_parse_string_type
163 	},
164 	{
165 	  NGM_PPPOE_COOKIE,
166 	  NGM_PPPOE_SETENADDR,
167 	  "setenaddr",
168 	  &ng_parse_enaddr_type,
169 	  NULL
170 	},
171 	{
172 	  NGM_PPPOE_COOKIE,
173 	  NGM_PPPOE_SETMAXP,
174 	  "setmaxp",
175 	  &ng_parse_uint16_type,
176 	  NULL
177 	},
178         {
179 	  NGM_PPPOE_COOKIE,
180 	  NGM_PPPOE_SEND_HURL,
181 	  "send_hurl",
182 	  &ngpppoe_init_data_state_type,
183 	  NULL
184         },
185         {
186 	  NGM_PPPOE_COOKIE,
187 	  NGM_PPPOE_SEND_MOTM,
188 	  "send_motm",
189 	  &ngpppoe_init_data_state_type,
190 	  NULL
191         },
192 	{ 0 }
193 };
194 
195 /* Netgraph node type descriptor */
196 static struct ng_type typestruct = {
197 	.version =	NG_ABI_VERSION,
198 	.name =		NG_PPPOE_NODE_TYPE,
199 	.constructor =	ng_pppoe_constructor,
200 	.rcvmsg =	ng_pppoe_rcvmsg,
201 	.shutdown =	ng_pppoe_shutdown,
202 	.newhook =	ng_pppoe_newhook,
203 	.connect =	ng_pppoe_connect,
204 	.rcvdata =	ng_pppoe_rcvdata,
205 	.disconnect =	ng_pppoe_disconnect,
206 	.cmdlist =	ng_pppoe_cmds,
207 };
208 NETGRAPH_INIT(pppoe, &typestruct);
209 
210 /*
211  * States for the session state machine.
212  * These have no meaning if there is no hook attached yet.
213  */
214 enum state {
215     PPPOE_SNONE=0,	/* [both] Initial state */
216     PPPOE_LISTENING,	/* [Daemon] Listening for discover initiation pkt */
217     PPPOE_SINIT,	/* [Client] Sent discovery initiation */
218     PPPOE_PRIMED,	/* [Server] Awaiting PADI from daemon */
219     PPPOE_SOFFER,	/* [Server] Sent offer message  (got PADI)*/
220     PPPOE_SREQ,		/* [Client] Sent a Request */
221     PPPOE_NEWCONNECTED,	/* [Server] Connection established, No data received */
222     PPPOE_CONNECTED,	/* [Both] Connection established, Data received */
223     PPPOE_DEAD		/* [Both] */
224 };
225 
226 #define NUMTAGS 20 /* number of tags we are set up to work with */
227 
228 /*
229  * Information we store for each hook on each node for negotiating the
230  * session. The mbuf and cluster are freed once negotiation has completed.
231  * The whole negotiation block is then discarded.
232  */
233 
234 struct sess_neg {
235 	struct mbuf 		*m; /* holds cluster with last sent packet */
236 	union	packet		*pkt; /* points within the above cluster */
237 	struct callout		handle;   /* see timeout(9) */
238 	u_int			timeout; /* 0,1,2,4,8,16 etc. seconds */
239 	u_int			numtags;
240 	const struct pppoe_tag	*tags[NUMTAGS];
241 	u_int			service_len;
242 	u_int			ac_name_len;
243 	u_int			host_uniq_len;
244 
245 	struct datatag		service;
246 	struct datatag		ac_name;
247 	struct datatag		host_uniq;
248 };
249 typedef struct sess_neg *negp;
250 
251 /*
252  * Session information that is needed after connection.
253  */
254 struct sess_con {
255 	hook_p  		hook;
256 	uint16_t		Session_ID;
257 	enum state		state;
258 	ng_ID_t			creator;	/* who to notify */
259 	struct pppoe_full_hdr	pkt_hdr;	/* used when connected */
260 	negp			neg;		/* used when negotiating */
261 	LIST_ENTRY(sess_con)	sessions;
262 };
263 typedef struct sess_con *sessp;
264 
265 #define SESSHASHSIZE	0x0100
266 #define SESSHASH(x)	(((x) ^ ((x) >> 8)) & (SESSHASHSIZE - 1))
267 
268 struct sess_hash_entry {
269 	struct mtx	mtx;
270 	LIST_HEAD(hhead, sess_con) head;
271 };
272 
273 /*
274  * Information we store for each node
275  */
276 struct PPPoE {
277 	node_p		node;		/* back pointer to node */
278 	hook_p  	ethernet_hook;
279 	hook_p  	debug_hook;
280 	u_int   	packets_in;	/* packets in from ethernet */
281 	u_int   	packets_out;	/* packets out towards ethernet */
282 	uint32_t	flags;
283 #define	COMPAT_3COM	0x00000001
284 #define	COMPAT_DLINK	0x00000002
285 	struct ether_header	eh;
286 	LIST_HEAD(, sess_con) listeners;
287 	struct sess_hash_entry	sesshash[SESSHASHSIZE];
288 	struct maxptag	max_payload;	/* PPP-Max-Payload (RFC4638) */
289 };
290 typedef struct PPPoE *priv_p;
291 
292 union uniq {
293 	char bytes[sizeof(void *)];
294 	void *pointer;
295 };
296 
297 #define	LEAVE(x) do { error = x; goto quit; } while(0)
298 static void	pppoe_start(sessp sp);
299 static void	pppoe_ticker(node_p node, hook_p hook, void *arg1, int arg2);
300 static const	struct pppoe_tag *scan_tags(sessp sp,
301 			const struct pppoe_hdr* ph);
302 static	int	pppoe_send_event(sessp sp, enum cmd cmdid);
303 
304 /*************************************************************************
305  * Some basic utilities  from the Linux version with author's permission.*
306  * Author:	Michal Ostrowski <mostrows@styx.uwaterloo.ca>		 *
307  ************************************************************************/
308 
309 /*
310  * Return the location where the next tag can be put
311  */
312 static __inline const struct pppoe_tag*
313 next_tag(const struct pppoe_hdr* ph)
314 {
315 	return (const struct pppoe_tag*)(((const char*)(ph + 1))
316 	    + ntohs(ph->length));
317 }
318 
319 /*
320  * Look for a tag of a specific type.
321  * Don't trust any length the other end says,
322  * but assume we already sanity checked ph->length.
323  */
324 static const struct pppoe_tag*
325 get_tag(const struct pppoe_hdr* ph, uint16_t idx)
326 {
327 	const char *const end = (const char *)next_tag(ph);
328 	const struct pppoe_tag *pt = (const void *)(ph + 1);
329 	const char *ptn;
330 
331 	/*
332 	 * Keep processing tags while a tag header will still fit.
333 	 */
334 	while((const char*)(pt + 1) <= end) {
335 		/*
336 		 * If the tag data would go past the end of the packet, abort.
337 		 */
338 		ptn = (((const char *)(pt + 1)) + ntohs(pt->tag_len));
339 		if (ptn > end) {
340 			CTR2(KTR_NET, "%20s: invalid length for tag %d",
341 			    __func__, idx);
342 			return (NULL);
343 		}
344 		if (pt->tag_type == idx) {
345 			CTR2(KTR_NET, "%20s: found tag %d", __func__, idx);
346 			return (pt);
347 		}
348 
349 		pt = (const struct pppoe_tag*)ptn;
350 	}
351 
352 	CTR2(KTR_NET, "%20s: not found tag %d", __func__, idx);
353 	return (NULL);
354 }
355 
356 /**************************************************************************
357  * Inlines to initialise or add tags to a session's tag list.
358  **************************************************************************/
359 /*
360  * Initialise the session's tag list.
361  */
362 static void
363 init_tags(sessp sp)
364 {
365 	KASSERT(sp->neg != NULL, ("%s: no neg", __func__));
366 	sp->neg->numtags = 0;
367 }
368 
369 static void
370 insert_tag(sessp sp, const struct pppoe_tag *tp)
371 {
372 	negp neg = sp->neg;
373 	int i;
374 
375 	KASSERT(neg != NULL, ("%s: no neg", __func__));
376 	if ((i = neg->numtags++) < NUMTAGS) {
377 		neg->tags[i] = tp;
378 	} else {
379 		log(LOG_NOTICE, "ng_pppoe: asked to add too many tags to "
380 		    "packet\n");
381 		neg->numtags--;
382 	}
383 }
384 
385 /*
386  * Make up a packet, using the tags filled out for the session.
387  *
388  * Assume that the actual pppoe header and ethernet header
389  * are filled out externally to this routine.
390  * Also assume that neg->wh points to the correct
391  * location at the front of the buffer space.
392  */
393 static void
394 make_packet(sessp sp) {
395 	struct pppoe_full_hdr *wh = &sp->neg->pkt->pkt_header;
396 	const struct pppoe_tag **tag;
397 	char *dp;
398 	int count;
399 	int tlen;
400 	uint16_t length = 0;
401 
402 	KASSERT((sp->neg != NULL) && (sp->neg->m != NULL),
403 	    ("%s: called from wrong state", __func__));
404 	CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
405 
406 	dp = (char *)(&wh->ph + 1);
407 	for (count = 0, tag = sp->neg->tags;
408 	    ((count < sp->neg->numtags) && (count < NUMTAGS));
409 	    tag++, count++) {
410 		tlen = ntohs((*tag)->tag_len) + sizeof(**tag);
411 		if ((length + tlen) > (ETHER_MAX_LEN - 4 - sizeof(*wh))) {
412 			log(LOG_NOTICE, "ng_pppoe: tags too long\n");
413 			sp->neg->numtags = count;
414 			break;	/* XXX chop off what's too long */
415 		}
416 		bcopy(*tag, (char *)dp, tlen);
417 		length += tlen;
418 		dp += tlen;
419 	}
420  	wh->ph.length = htons(length);
421 	sp->neg->m->m_len = length + sizeof(*wh);
422 	sp->neg->m->m_pkthdr.len = length + sizeof(*wh);
423 }
424 
425 /**************************************************************************
426  * Routines to match a service.						  *
427  **************************************************************************/
428 
429 /*
430  * Find a hook that has a service string that matches that
431  * we are seeking. For now use a simple string.
432  * In the future we may need something like regexp().
433  *
434  * Null string is a wildcard (ANY service), according to RFC2516.
435  * And historical FreeBSD wildcard is also "*".
436  */
437 
438 static hook_p
439 pppoe_match_svc(node_p node, const struct pppoe_tag *tag)
440 {
441 	const priv_p privp = NG_NODE_PRIVATE(node);
442 	sessp sp;
443 
444 	LIST_FOREACH(sp, &privp->listeners, sessions) {
445 		negp neg = sp->neg;
446 
447 		/* Empty Service-Name matches any service. */
448 		if (neg->service_len == 0)
449 			break;
450 
451 		/* Special case for a blank or "*" service name (wildcard). */
452 		if (neg->service_len == 1 && neg->service.data[0] == '*')
453 			break;
454 
455 		/* If the lengths don't match, that aint it. */
456 		if (neg->service_len != ntohs(tag->tag_len))
457 			continue;
458 
459 		if (strncmp((const char *)(tag + 1), neg->service.data,
460 		    ntohs(tag->tag_len)) == 0)
461 			break;
462 	}
463 	CTR3(KTR_NET, "%20s: matched %p for %s", __func__,
464 	    sp?sp->hook:NULL, (const char *)(tag + 1));
465 
466 	return (sp?sp->hook:NULL);
467 }
468 
469 /*
470  * Broadcast the PADI packet in m0 to all listening hooks.
471  * This routine is called when a PADI with empty Service-Name
472  * tag is received. Client should receive PADOs with all
473  * available services.
474  */
475 static int
476 pppoe_broadcast_padi(node_p node, struct mbuf *m0)
477 {
478 	const priv_p privp = NG_NODE_PRIVATE(node);
479 	sessp sp;
480 	int error = 0;
481 
482 	LIST_FOREACH(sp, &privp->listeners, sessions) {
483 		struct mbuf *m;
484 
485 		m = m_dup(m0, M_NOWAIT);
486 		if (m == NULL)
487 			return (ENOMEM);
488 		NG_SEND_DATA_ONLY(error, sp->hook, m);
489 		if (error)
490 			return (error);
491 	}
492 
493 	return (0);
494 }
495 
496 /*
497  * Find a hook, which name equals to given service.
498  */
499 static hook_p
500 pppoe_find_svc(node_p node, const char *svc_name, int svc_len)
501 {
502 	const priv_p privp = NG_NODE_PRIVATE(node);
503 	sessp sp;
504 
505 	LIST_FOREACH(sp, &privp->listeners, sessions) {
506 		negp neg = sp->neg;
507 
508 		if (neg->service_len == svc_len &&
509 		    strncmp(svc_name, neg->service.data, svc_len) == 0)
510 			return (sp->hook);
511 	}
512 
513 	return (NULL);
514 }
515 
516 /**************************************************************************
517  * Routines to find a particular session that matches an incoming packet. *
518  **************************************************************************/
519 /* Find free session and add to hash. */
520 static uint16_t
521 pppoe_getnewsession(sessp sp)
522 {
523 	const priv_p privp = NG_NODE_PRIVATE(NG_HOOK_NODE(sp->hook));
524 	static uint16_t pppoe_sid = 1;
525 	sessp	tsp;
526 	uint16_t val, hash;
527 
528 restart:
529 	/* Atomicity is not needed here as value will be checked. */
530 	val = pppoe_sid++;
531 	/* Spec says 0xFFFF is reserved, also don't use 0x0000. */
532 	if (val == 0xffff || val == 0x0000)
533 		val = pppoe_sid = 1;
534 
535 	/* Check it isn't already in use. */
536 	hash = SESSHASH(val);
537 	mtx_lock(&privp->sesshash[hash].mtx);
538 	LIST_FOREACH(tsp, &privp->sesshash[hash].head, sessions) {
539 		if (tsp->Session_ID == val)
540 			break;
541 	}
542 	if (!tsp) {
543 		sp->Session_ID = val;
544 		LIST_INSERT_HEAD(&privp->sesshash[hash].head, sp, sessions);
545 	}
546 	mtx_unlock(&privp->sesshash[hash].mtx);
547 	if (tsp)
548 		goto restart;
549 
550 	CTR2(KTR_NET, "%20s: new sid %d", __func__, val);
551 
552 	return (val);
553 }
554 
555 /* Add specified session to hash. */
556 static void
557 pppoe_addsession(sessp sp)
558 {
559 	const priv_p	privp = NG_NODE_PRIVATE(NG_HOOK_NODE(sp->hook));
560 	uint16_t	hash = SESSHASH(sp->Session_ID);
561 
562 	mtx_lock(&privp->sesshash[hash].mtx);
563 	LIST_INSERT_HEAD(&privp->sesshash[hash].head, sp, sessions);
564 	mtx_unlock(&privp->sesshash[hash].mtx);
565 }
566 
567 /* Delete specified session from hash. */
568 static void
569 pppoe_delsession(sessp sp)
570 {
571 	const priv_p	privp = NG_NODE_PRIVATE(NG_HOOK_NODE(sp->hook));
572 	uint16_t	hash = SESSHASH(sp->Session_ID);
573 
574 	mtx_lock(&privp->sesshash[hash].mtx);
575 	LIST_REMOVE(sp, sessions);
576 	mtx_unlock(&privp->sesshash[hash].mtx);
577 }
578 
579 /* Find matching peer/session combination. */
580 static sessp
581 pppoe_findsession(priv_p privp, const struct pppoe_full_hdr *wh)
582 {
583 	uint16_t 	session = ntohs(wh->ph.sid);
584 	uint16_t	hash = SESSHASH(session);
585 	sessp		sp = NULL;
586 
587 	mtx_lock(&privp->sesshash[hash].mtx);
588 	LIST_FOREACH(sp, &privp->sesshash[hash].head, sessions) {
589 		if (sp->Session_ID == session &&
590 		    bcmp(sp->pkt_hdr.eh.ether_dhost,
591 		     wh->eh.ether_shost, ETHER_ADDR_LEN) == 0) {
592 			break;
593 		}
594 	}
595 	mtx_unlock(&privp->sesshash[hash].mtx);
596 	CTR3(KTR_NET, "%20s: matched %p for %d", __func__, sp?sp->hook:NULL,
597 	    session);
598 
599 	return (sp);
600 }
601 
602 static hook_p
603 pppoe_finduniq(node_p node, const struct pppoe_tag *tag)
604 {
605 	hook_p	hook = NULL;
606 	sessp	sp;
607 
608 	/* Cycle through all known hooks. */
609 	LIST_FOREACH(hook, &node->nd_hooks, hk_hooks) {
610 		/* Skip any nonsession hook. */
611 		if (NG_HOOK_PRIVATE(hook) == NULL)
612 			continue;
613 		sp = NG_HOOK_PRIVATE(hook);
614 		/* Skip already connected sessions. */
615 		if (sp->neg == NULL)
616 			continue;
617 		if (sp->neg->host_uniq_len == ntohs(tag->tag_len) &&
618 		    bcmp(sp->neg->host_uniq.data, (const char *)(tag + 1),
619 		     sp->neg->host_uniq_len) == 0)
620 			break;
621 	}
622 	CTR3(KTR_NET, "%20s: matched %p for %p", __func__, hook, sp);
623 
624 	return (hook);
625 }
626 
627 static hook_p
628 pppoe_findcookie(node_p node, const struct pppoe_tag *tag)
629 {
630 	hook_p	hook = NULL;
631 	union uniq cookie;
632 
633 	bcopy(tag + 1, cookie.bytes, sizeof(void *));
634 	/* Cycle through all known hooks. */
635 	LIST_FOREACH(hook, &node->nd_hooks, hk_hooks) {
636 		/* Skip any nonsession hook. */
637 		if (NG_HOOK_PRIVATE(hook) == NULL)
638 			continue;
639 		if (cookie.pointer == NG_HOOK_PRIVATE(hook))
640 			break;
641 	}
642 	CTR3(KTR_NET, "%20s: matched %p for %p", __func__, hook, cookie.pointer);
643 
644 	return (hook);
645 }
646 
647 /**************************************************************************
648  * Start of Netgraph entrypoints.					  *
649  **************************************************************************/
650 
651 /*
652  * Allocate the private data structure and link it with node.
653  */
654 static int
655 ng_pppoe_constructor(node_p node)
656 {
657 	priv_p	privp;
658 	int	i;
659 
660 	/* Initialize private descriptor. */
661 	privp = malloc(sizeof(*privp), M_NETGRAPH_PPPOE, M_WAITOK | M_ZERO);
662 
663 	/* Link structs together; this counts as our one reference to *node. */
664 	NG_NODE_SET_PRIVATE(node, privp);
665 	privp->node = node;
666 
667 	/* Initialize to standard mode. */
668 	memset(&privp->eh.ether_dhost, 0xff, ETHER_ADDR_LEN);
669 	privp->eh.ether_type = ETHERTYPE_PPPOE_DISC;
670 
671 	LIST_INIT(&privp->listeners);
672 	for (i = 0; i < SESSHASHSIZE; i++) {
673 	    mtx_init(&privp->sesshash[i].mtx, "PPPoE hash mutex", NULL, MTX_DEF);
674 	    LIST_INIT(&privp->sesshash[i].head);
675 	}
676 
677 	CTR3(KTR_NET, "%20s: created node [%x] (%p)",
678 	    __func__, node->nd_ID, node);
679 
680 	return (0);
681 }
682 
683 /*
684  * Give our ok for a hook to be added...
685  * point the hook's private info to the hook structure.
686  *
687  * The following hook names are special:
688  *  "ethernet":  the hook that should be connected to a NIC.
689  *  "debug":	copies of data sent out here  (when I write the code).
690  * All other hook names need only be unique. (the framework checks this).
691  */
692 static int
693 ng_pppoe_newhook(node_p node, hook_p hook, const char *name)
694 {
695 	const priv_p privp = NG_NODE_PRIVATE(node);
696 	sessp sp;
697 
698 	if (strcmp(name, NG_PPPOE_HOOK_ETHERNET) == 0) {
699 		privp->ethernet_hook = hook;
700 		NG_HOOK_SET_RCVDATA(hook, ng_pppoe_rcvdata_ether);
701 	} else if (strcmp(name, NG_PPPOE_HOOK_DEBUG) == 0) {
702 		privp->debug_hook = hook;
703 		NG_HOOK_SET_RCVDATA(hook, ng_pppoe_rcvdata_debug);
704 	} else {
705 		/*
706 		 * Any other unique name is OK.
707 		 * The infrastructure has already checked that it's unique,
708 		 * so just allocate it and hook it in.
709 		 */
710 		sp = malloc(sizeof(*sp), M_NETGRAPH_PPPOE, M_NOWAIT | M_ZERO);
711 		if (sp == NULL)
712 			return (ENOMEM);
713 
714 		NG_HOOK_SET_PRIVATE(hook, sp);
715 		sp->hook = hook;
716 	}
717 	CTR5(KTR_NET, "%20s: node [%x] (%p) connected hook %s (%p)",
718 	    __func__, node->nd_ID, node, name, hook);
719 
720 	return(0);
721 }
722 
723 /*
724  * Hook has been added successfully. Request the MAC address of
725  * the underlying Ethernet node.
726  */
727 static int
728 ng_pppoe_connect(hook_p hook)
729 {
730 	const priv_p privp = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
731 	struct ng_mesg *msg;
732 	int error;
733 
734 	if (hook != privp->ethernet_hook)
735 		return (0);
736 
737 	/*
738 	 * If this is Ethernet hook, then request MAC address
739 	 * from our downstream.
740 	 */
741 	NG_MKMESSAGE(msg, NGM_ETHER_COOKIE, NGM_ETHER_GET_ENADDR, 0, M_NOWAIT);
742 	if (msg == NULL)
743 		return (ENOBUFS);
744 
745 	/*
746 	 * Our hook and peer hook have HK_INVALID flag set,
747 	 * so we can't use NG_SEND_MSG_HOOK() macro here.
748 	 */
749 	NG_SEND_MSG_ID(error, privp->node, msg,
750 	    NG_NODE_ID(NG_PEER_NODE(privp->ethernet_hook)),
751 	    NG_NODE_ID(privp->node));
752 
753 	return (error);
754 }
755 /*
756  * Get a netgraph control message.
757  * Check it is one we understand. If needed, send a response.
758  * We sometimes save the address for an async action later.
759  * Always free the message.
760  */
761 static int
762 ng_pppoe_rcvmsg(node_p node, item_p item, hook_p lasthook)
763 {
764 	priv_p privp = NG_NODE_PRIVATE(node);
765 	struct ngpppoe_init_data *ourmsg = NULL;
766 	struct ng_mesg *resp = NULL;
767 	int error = 0;
768 	hook_p hook = NULL;
769 	sessp sp = NULL;
770 	negp neg = NULL;
771 	struct ng_mesg *msg;
772 
773 	NGI_GET_MSG(item, msg);
774 	CTR5(KTR_NET, "%20s: node [%x] (%p) got message %d with cookie %d",
775 	    __func__, node->nd_ID, node, msg->header.cmd,
776 	    msg->header.typecookie);
777 
778 	/* Deal with message according to cookie and command. */
779 	switch (msg->header.typecookie) {
780 	case NGM_PPPOE_COOKIE:
781 		switch (msg->header.cmd) {
782 		case NGM_PPPOE_CONNECT:
783 		case NGM_PPPOE_LISTEN:
784 		case NGM_PPPOE_OFFER:
785 		case NGM_PPPOE_SERVICE:
786 		case NGM_PPPOE_SEND_HURL:
787 		case NGM_PPPOE_SEND_MOTM:
788 			ourmsg = (struct ngpppoe_init_data *)msg->data;
789 			if (msg->header.arglen < sizeof(*ourmsg)) {
790 				log(LOG_ERR, "ng_pppoe[%x]: init data too "
791 				    "small\n", node->nd_ID);
792 				LEAVE(EMSGSIZE);
793 			}
794 			if (msg->header.cmd == NGM_PPPOE_SEND_HURL ||
795 			    msg->header.cmd == NGM_PPPOE_SEND_MOTM) {
796 				if (msg->header.arglen - sizeof(*ourmsg) >
797 				    PPPOE_PADM_VALUE_SIZE) {
798 					log(LOG_ERR, "ng_pppoe[%x]: message "
799 					    "too big\n", node->nd_ID);
800 					LEAVE(EMSGSIZE);
801 				}
802 			} else {
803 				if (msg->header.arglen - sizeof(*ourmsg) >
804 				    PPPOE_SERVICE_NAME_SIZE) {
805 					log(LOG_ERR, "ng_pppoe[%x]: service name "
806 					    "too big\n", node->nd_ID);
807 					LEAVE(EMSGSIZE);
808 				}
809 			}
810 			if (msg->header.arglen - sizeof(*ourmsg) <
811 			    ourmsg->data_len) {
812 				log(LOG_ERR, "ng_pppoe[%x]: init data has bad "
813 				    "length, %d should be %zd\n", node->nd_ID,
814 				    ourmsg->data_len,
815 				    msg->header.arglen - sizeof (*ourmsg));
816 				LEAVE(EMSGSIZE);
817 			}
818 
819 			/* Make sure strcmp will terminate safely. */
820 			ourmsg->hook[sizeof(ourmsg->hook) - 1] = '\0';
821 
822 			/* Find hook by name. */
823 			hook = ng_findhook(node, ourmsg->hook);
824 			if (hook == NULL)
825 				LEAVE(ENOENT);
826 
827 			sp = NG_HOOK_PRIVATE(hook);
828 			if (sp == NULL)
829 				LEAVE(EINVAL);
830 
831 			if (msg->header.cmd == NGM_PPPOE_LISTEN) {
832 				/*
833 				 * Ensure we aren't already listening for this
834 				 * service.
835 				 */
836 				if (pppoe_find_svc(node, ourmsg->data,
837 				    ourmsg->data_len) != NULL)
838 					LEAVE(EEXIST);
839 			}
840 
841 			/*
842 			 * PPPOE_SERVICE advertisements are set up
843 			 * on sessions that are in PRIMED state.
844 			 */
845 			if (msg->header.cmd == NGM_PPPOE_SERVICE)
846 				break;
847 
848 			/*
849 			 * PADM messages are set up on active sessions.
850 			 */
851 			if (msg->header.cmd == NGM_PPPOE_SEND_HURL ||
852 			    msg->header.cmd == NGM_PPPOE_SEND_MOTM) {
853 				if (sp->state != PPPOE_NEWCONNECTED &&
854 				    sp->state != PPPOE_CONNECTED) {
855 					log(LOG_NOTICE, "ng_pppoe[%x]: session is not "
856 					    "active\n", node->nd_ID);
857 					LEAVE(EISCONN);
858 				}
859 				break;
860 			}
861 
862 			if (sp->state != PPPOE_SNONE) {
863 				log(LOG_NOTICE, "ng_pppoe[%x]: Session already "
864 				    "active\n", node->nd_ID);
865 				LEAVE(EISCONN);
866 			}
867 
868 			/*
869 			 * Set up prototype header.
870 			 */
871 			neg = malloc(sizeof(*neg), M_NETGRAPH_PPPOE,
872 			    M_NOWAIT | M_ZERO);
873 
874 			if (neg == NULL)
875 				LEAVE(ENOMEM);
876 
877 			neg->m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
878 			if (neg->m == NULL) {
879 				free(neg, M_NETGRAPH_PPPOE);
880 				LEAVE(ENOBUFS);
881 			}
882 			neg->m->m_pkthdr.rcvif = NULL;
883 			sp->neg = neg;
884 			ng_callout_init(&neg->handle);
885 			neg->m->m_len = sizeof(struct pppoe_full_hdr);
886 			neg->pkt = mtod(neg->m, union packet*);
887 			memcpy((void *)&neg->pkt->pkt_header.eh,
888 			    &privp->eh, sizeof(struct ether_header));
889 			neg->pkt->pkt_header.ph.ver = 0x1;
890 			neg->pkt->pkt_header.ph.type = 0x1;
891 			neg->pkt->pkt_header.ph.sid = 0x0000;
892 			neg->timeout = 0;
893 
894 			sp->creator = NGI_RETADDR(item);
895 		}
896 		switch (msg->header.cmd) {
897 		case NGM_PPPOE_GET_STATUS:
898 		    {
899 			struct ngpppoestat *stats;
900 
901 			NG_MKRESPONSE(resp, msg, sizeof(*stats), M_NOWAIT);
902 			if (!resp)
903 				LEAVE(ENOMEM);
904 
905 			stats = (struct ngpppoestat *) resp->data;
906 			stats->packets_in = privp->packets_in;
907 			stats->packets_out = privp->packets_out;
908 			break;
909 		    }
910 		case NGM_PPPOE_CONNECT:
911 		    {
912 			/*
913 			 * Check the hook exists and is Uninitialised.
914 			 * Send a PADI request, and start the timeout logic.
915 			 * Store the originator of this message so we can send
916 			 * a success or fail message to them later.
917 			 * Move the session to SINIT.
918 			 * Set up the session to the correct state and
919 			 * start it.
920 			 */
921 			int	acnpos, acnlen = 0, acnsep = 0;
922 			int	hupos, hulen = 0, husep = 0;
923 			int	i, srvpos, srvlen;
924 			acnpos = 0;
925 			for (i = 0; i < ourmsg->data_len; i++) {
926 				if (ourmsg->data[i] == '\\') {
927 					acnlen = i;
928 					acnsep = 1;
929 					break;
930 				}
931 			}
932 			hupos = acnlen + acnsep;
933 			for (i = hupos; i < ourmsg->data_len; i++) {
934 				if (ourmsg->data[i] == '|') {
935 					hulen = i - hupos;
936 					husep = 1;
937 					break;
938 				}
939 			}
940 			srvpos = hupos + hulen + husep;
941 			srvlen = ourmsg->data_len - srvpos;
942 
943 			bcopy(ourmsg->data + acnpos, neg->ac_name.data, acnlen);
944 			neg->ac_name_len = acnlen;
945 
946 			neg->host_uniq.hdr.tag_type = PTT_HOST_UNIQ;
947 			if (hulen == 0) {
948 				/* Not provided, generate one */
949 				neg->host_uniq.hdr.tag_len = htons(sizeof(sp));
950 				bcopy(&sp, neg->host_uniq.data, sizeof(sp));
951 				neg->host_uniq_len = sizeof(sp);
952 			} else if (hulen > 2 && ourmsg->data[hupos] == '0' &&
953 			  ourmsg->data[hupos + 1] == 'x' && hulen % 2 == 0) {
954 				/* Hex encoded */
955 				static const char hexdig[16] = "0123456789abcdef";
956 				int j;
957 
958 				neg->host_uniq.hdr.tag_len = htons((uint16_t)(hulen / 2 - 1));
959 				for (i = 0; i < hulen - 2; i++) {
960 					for (j = 0;
961 					     j < 16 &&
962 					     ourmsg->data[hupos + 2 + i] != hexdig[j];
963 					     j++);
964 					if (j == 16)
965 						LEAVE(EINVAL);
966 					if (i % 2 == 0)
967 						neg->host_uniq.data[i / 2] = j << 4;
968 					else
969 						neg->host_uniq.data[i / 2] |= j;
970 				}
971 				neg->host_uniq_len = hulen / 2 - 1;
972 			} else {
973 				/* Plain string */
974 				neg->host_uniq.hdr.tag_len = htons((uint16_t)hulen);
975 				bcopy(ourmsg->data + hupos, neg->host_uniq.data, hulen);
976 				neg->host_uniq_len = hulen;
977 			}
978 
979 			neg->service.hdr.tag_type = PTT_SRV_NAME;
980 			neg->service.hdr.tag_len = htons((uint16_t)srvlen);
981 			bcopy(ourmsg->data + srvpos, neg->service.data, srvlen);
982 			neg->service_len = srvlen;
983 			pppoe_start(sp);
984 			break;
985 		    }
986 		case NGM_PPPOE_LISTEN:
987 			/*
988 			 * Check the hook exists and is Uninitialised.
989 			 * Install the service matching string.
990 			 * Store the originator of this message so we can send
991 			 * a success or fail message to them later.
992 			 * Move the hook to 'LISTENING'
993 			 */
994 			neg->service.hdr.tag_type = PTT_SRV_NAME;
995 			neg->service.hdr.tag_len =
996 			    htons((uint16_t)ourmsg->data_len);
997 
998 			if (ourmsg->data_len)
999 				bcopy(ourmsg->data, neg->service.data,
1000 				    ourmsg->data_len);
1001 			neg->service_len = ourmsg->data_len;
1002 			neg->pkt->pkt_header.ph.code = PADT_CODE;
1003 			/*
1004 			 * Wait for PADI packet coming from Ethernet.
1005 			 */
1006 			sp->state = PPPOE_LISTENING;
1007 			LIST_INSERT_HEAD(&privp->listeners, sp, sessions);
1008 			break;
1009 		case NGM_PPPOE_OFFER:
1010 			/*
1011 			 * Check the hook exists and is Uninitialised.
1012 			 * Store the originator of this message so we can send
1013 			 * a success of fail message to them later.
1014 			 * Store the AC-Name given and go to PRIMED.
1015 			 */
1016 			neg->ac_name.hdr.tag_type = PTT_AC_NAME;
1017 			neg->ac_name.hdr.tag_len =
1018 			    htons((uint16_t)ourmsg->data_len);
1019 			if (ourmsg->data_len)
1020 				bcopy(ourmsg->data, neg->ac_name.data,
1021 				    ourmsg->data_len);
1022 			neg->ac_name_len = ourmsg->data_len;
1023 			neg->pkt->pkt_header.ph.code = PADO_CODE;
1024 			/*
1025 			 * Wait for PADI packet coming from hook.
1026 			 */
1027 			sp->state = PPPOE_PRIMED;
1028 			break;
1029 		case NGM_PPPOE_SERVICE:
1030 			/*
1031 			 * Check the session is primed.
1032 			 * for now just allow ONE service to be advertised.
1033 			 * If you do it twice you just overwrite.
1034 			 */
1035 			if (sp->state != PPPOE_PRIMED) {
1036 				log(LOG_NOTICE, "ng_pppoe[%x]: session not "
1037 				    "primed\n", node->nd_ID);
1038 				LEAVE(EISCONN);
1039 			}
1040 			neg = sp->neg;
1041 			neg->service.hdr.tag_type = PTT_SRV_NAME;
1042 			neg->service.hdr.tag_len =
1043 			    htons((uint16_t)ourmsg->data_len);
1044 
1045 			if (ourmsg->data_len)
1046 				bcopy(ourmsg->data, neg->service.data,
1047 				    ourmsg->data_len);
1048 			neg->service_len = ourmsg->data_len;
1049 			break;
1050 		case NGM_PPPOE_SETMODE:
1051 		    {
1052 			char *s;
1053 			size_t len;
1054 
1055 			if (msg->header.arglen == 0)
1056 				LEAVE(EINVAL);
1057 
1058 			s = (char *)msg->data;
1059 			len = msg->header.arglen - 1;
1060 
1061 			/* Search for matching mode string. */
1062 			if (len == strlen(NG_PPPOE_STANDARD) &&
1063 			    (strncmp(NG_PPPOE_STANDARD, s, len) == 0)) {
1064 				privp->flags = 0;
1065 				privp->eh.ether_type = ETHERTYPE_PPPOE_DISC;
1066 				break;
1067 			}
1068 			if (len == strlen(NG_PPPOE_3COM) &&
1069 			    (strncmp(NG_PPPOE_3COM, s, len) == 0)) {
1070 				privp->flags |= COMPAT_3COM;
1071 				privp->eh.ether_type =
1072 				    ETHERTYPE_PPPOE_3COM_DISC;
1073 				break;
1074 			}
1075 			if (len == strlen(NG_PPPOE_DLINK) &&
1076 			    (strncmp(NG_PPPOE_DLINK, s, len) == 0)) {
1077 				privp->flags |= COMPAT_DLINK;
1078 				break;
1079 			}
1080 			error = EINVAL;
1081 			break;
1082 		    }
1083 		case NGM_PPPOE_GETMODE:
1084 		    {
1085 			char *s;
1086 			size_t len = 0;
1087 
1088 			if (privp->flags == 0)
1089 				len += strlen(NG_PPPOE_STANDARD) + 1;
1090 			if (privp->flags & COMPAT_3COM)
1091 				len += strlen(NG_PPPOE_3COM) + 1;
1092 			if (privp->flags & COMPAT_DLINK)
1093 				len += strlen(NG_PPPOE_DLINK) + 1;
1094 
1095 			NG_MKRESPONSE(resp, msg, len, M_NOWAIT);
1096 			if (resp == NULL)
1097 				LEAVE(ENOMEM);
1098 
1099 			s = (char *)resp->data;
1100 			if (privp->flags == 0) {
1101 				len = strlen(NG_PPPOE_STANDARD);
1102 				strlcpy(s, NG_PPPOE_STANDARD, len + 1);
1103 				break;
1104 			}
1105 			if (privp->flags & COMPAT_3COM) {
1106 				len = strlen(NG_PPPOE_3COM);
1107 				strlcpy(s, NG_PPPOE_3COM, len + 1);
1108 				s += len;
1109 			}
1110 			if (privp->flags & COMPAT_DLINK) {
1111 				if (s != resp->data)
1112 					*s++ = '|';
1113 				len = strlen(NG_PPPOE_DLINK);
1114 				strlcpy(s, NG_PPPOE_DLINK, len + 1);
1115 			}
1116 			break;
1117 		    }
1118 		case NGM_PPPOE_SETENADDR:
1119 			if (msg->header.arglen != ETHER_ADDR_LEN)
1120 				LEAVE(EINVAL);
1121 			bcopy(msg->data, &privp->eh.ether_shost,
1122 			    ETHER_ADDR_LEN);
1123 			break;
1124 		case NGM_PPPOE_SETMAXP:
1125 			if (msg->header.arglen != sizeof(uint16_t))
1126 				LEAVE(EINVAL);
1127 			privp->max_payload.hdr.tag_type = PTT_MAX_PAYL;
1128 			privp->max_payload.hdr.tag_len = htons(sizeof(uint16_t));
1129 			privp->max_payload.data = htons(*((uint16_t *)msg->data));
1130 			break;
1131 		case NGM_PPPOE_SEND_HURL:
1132 		    {
1133 			struct mbuf *m;
1134 
1135 			/* Generate a packet of that type. */
1136 			m = m_gethdr(M_NOWAIT, MT_DATA);
1137 			if (m == NULL)
1138 				log(LOG_NOTICE, "ng_pppoe[%x]: session out of "
1139 				    "mbufs\n", node->nd_ID);
1140 			else {
1141 				struct pppoe_full_hdr *wh;
1142 				struct pppoe_tag *tag;
1143 				int     error = 0;
1144 
1145 				wh = mtod(m, struct pppoe_full_hdr *);
1146 				bcopy(&sp->pkt_hdr, wh, sizeof(*wh));
1147 
1148 				/* Revert the stored header to DISC/PADM mode. */
1149 				wh->ph.code = PADM_CODE;
1150 				/*
1151 				 * Configure ethertype depending on what
1152 				 * was used during sessions stage.
1153 				 */
1154 				if (wh->eh.ether_type ==
1155 				    ETHERTYPE_PPPOE_3COM_SESS)
1156 					wh->eh.ether_type = ETHERTYPE_PPPOE_3COM_DISC;
1157 				else
1158 					wh->eh.ether_type = ETHERTYPE_PPPOE_DISC;
1159 				/*
1160 				 * Add PADM message and adjust sizes.
1161 				 */
1162 				tag = (void *)(&wh->ph + 1);
1163 				tag->tag_type = PTT_HURL;
1164 				tag->tag_len = htons(ourmsg->data_len);
1165 				strncpy((char *)(tag + 1), ourmsg->data, ourmsg->data_len);
1166 				m->m_pkthdr.len = m->m_len = sizeof(*wh) + sizeof(*tag) +
1167 				    ourmsg->data_len;
1168 				wh->ph.length = htons(sizeof(*tag) + ourmsg->data_len);
1169 				NG_SEND_DATA_ONLY(error,
1170 				    privp->ethernet_hook, m);
1171 			}
1172 			break;
1173 		    }
1174 		case NGM_PPPOE_SEND_MOTM:
1175 		    {
1176 			struct mbuf *m;
1177 
1178 			/* Generate a packet of that type. */
1179 			m = m_gethdr(M_NOWAIT, MT_DATA);
1180 			if (m == NULL)
1181 				log(LOG_NOTICE, "ng_pppoe[%x]: session out of "
1182 				    "mbufs\n", node->nd_ID);
1183 			else {
1184 				struct pppoe_full_hdr *wh;
1185 				struct pppoe_tag *tag;
1186 				int     error = 0;
1187 
1188 				wh = mtod(m, struct pppoe_full_hdr *);
1189 				bcopy(&sp->pkt_hdr, wh, sizeof(*wh));
1190 
1191 				/* Revert the stored header to DISC/PADM mode. */
1192 				wh->ph.code = PADM_CODE;
1193 				/*
1194 				 * Configure ethertype depending on what
1195 				 * was used during sessions stage.
1196 				 */
1197 				if (wh->eh.ether_type ==
1198 				    ETHERTYPE_PPPOE_3COM_SESS)
1199 					wh->eh.ether_type = ETHERTYPE_PPPOE_3COM_DISC;
1200 				else
1201 					wh->eh.ether_type = ETHERTYPE_PPPOE_DISC;
1202 				/*
1203 				 * Add PADM message and adjust sizes.
1204 				 */
1205 				tag = (void *)(&wh->ph + 1);
1206 				tag->tag_type = PTT_MOTM;
1207 				tag->tag_len = htons(ourmsg->data_len);
1208 				strncpy((char *)(tag + 1), ourmsg->data, ourmsg->data_len);
1209 				m->m_pkthdr.len = m->m_len = sizeof(*wh) + sizeof(*tag) +
1210 				    ourmsg->data_len;
1211 				wh->ph.length = htons(sizeof(*tag) + ourmsg->data_len);
1212 				NG_SEND_DATA_ONLY(error,
1213 				    privp->ethernet_hook, m);
1214 			}
1215 			break;
1216 		    }
1217 		default:
1218 			LEAVE(EINVAL);
1219 		}
1220 		break;
1221 	case NGM_ETHER_COOKIE:
1222 		if (!(msg->header.flags & NGF_RESP))
1223 			LEAVE(EINVAL);
1224 		switch (msg->header.cmd) {
1225 		case NGM_ETHER_GET_ENADDR:
1226 			if (msg->header.arglen != ETHER_ADDR_LEN)
1227 				LEAVE(EINVAL);
1228 			bcopy(msg->data, &privp->eh.ether_shost,
1229 			    ETHER_ADDR_LEN);
1230 			break;
1231 		default:
1232 			LEAVE(EINVAL);
1233 		}
1234 		break;
1235 	default:
1236 		LEAVE(EINVAL);
1237 	}
1238 
1239 	/* Take care of synchronous response, if any. */
1240 quit:
1241 	CTR2(KTR_NET, "%20s: returning %d", __func__, error);
1242 	NG_RESPOND_MSG(error, node, item, resp);
1243 	/* Free the message and return. */
1244 	NG_FREE_MSG(msg);
1245 	return(error);
1246 }
1247 
1248 /*
1249  * Start a client into the first state. A separate function because
1250  * it can be needed if the negotiation times out.
1251  */
1252 static void
1253 pppoe_start(sessp sp)
1254 {
1255 	hook_p	hook = sp->hook;
1256 	node_p	node = NG_HOOK_NODE(hook);
1257 	priv_p	privp = NG_NODE_PRIVATE(node);
1258 	negp	neg = sp->neg;
1259 	struct  mbuf *m0;
1260 	int	error;
1261 
1262 	/*
1263 	 * Kick the state machine into starting up.
1264 	 */
1265 	CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
1266 	sp->state = PPPOE_SINIT;
1267 	/*
1268 	 * Reset the packet header to broadcast. Since we are
1269 	 * in a client mode use configured ethertype.
1270 	 */
1271 	memcpy((void *)&neg->pkt->pkt_header.eh, &privp->eh,
1272 	    sizeof(struct ether_header));
1273 	neg->pkt->pkt_header.ph.code = PADI_CODE;
1274 	init_tags(sp);
1275 	insert_tag(sp, &neg->host_uniq.hdr);
1276 	insert_tag(sp, &neg->service.hdr);
1277 	if (privp->max_payload.data != 0)
1278 		insert_tag(sp, &privp->max_payload.hdr);
1279 	make_packet(sp);
1280 	/*
1281 	 * Send packet and prepare to retransmit it after timeout.
1282 	 */
1283 	ng_callout(&neg->handle, node, hook, PPPOE_INITIAL_TIMEOUT * hz,
1284 	    pppoe_ticker, NULL, 0);
1285 	neg->timeout = PPPOE_INITIAL_TIMEOUT * 2;
1286 	m0 = m_copypacket(neg->m, M_NOWAIT);
1287 	NG_SEND_DATA_ONLY(error, privp->ethernet_hook, m0);
1288 }
1289 
1290 static int
1291 send_acname(sessp sp, const struct pppoe_tag *tag)
1292 {
1293 	int error, tlen;
1294 	struct ng_mesg *msg;
1295 	struct ngpppoe_sts *sts;
1296 
1297 	CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
1298 
1299 	NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, NGM_PPPOE_ACNAME,
1300 	    sizeof(struct ngpppoe_sts), M_NOWAIT);
1301 	if (msg == NULL)
1302 		return (ENOMEM);
1303 
1304 	sts = (struct ngpppoe_sts *)msg->data;
1305 	tlen = min(NG_HOOKSIZ - 1, ntohs(tag->tag_len));
1306 	strncpy(sts->hook, (const char *)(tag + 1), tlen);
1307 	sts->hook[tlen] = '\0';
1308 	NG_SEND_MSG_ID(error, NG_HOOK_NODE(sp->hook), msg, sp->creator, 0);
1309 
1310 	return (error);
1311 }
1312 
1313 static int
1314 send_sessionid(sessp sp)
1315 {
1316 	int error;
1317 	struct ng_mesg *msg;
1318 
1319 	CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
1320 
1321 	NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, NGM_PPPOE_SESSIONID,
1322 	    sizeof(uint16_t), M_NOWAIT);
1323 	if (msg == NULL)
1324 		return (ENOMEM);
1325 
1326 	*(uint16_t *)msg->data = sp->Session_ID;
1327 	NG_SEND_MSG_ID(error, NG_HOOK_NODE(sp->hook), msg, sp->creator, 0);
1328 
1329 	return (error);
1330 }
1331 
1332 static int
1333 send_maxp(sessp sp, const struct pppoe_tag *tag)
1334 {
1335 	int error;
1336 	struct ng_mesg *msg;
1337 	struct ngpppoe_maxp *maxp;
1338 
1339 	CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
1340 
1341 	NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, NGM_PPPOE_SETMAXP,
1342 	    sizeof(struct ngpppoe_maxp), M_NOWAIT);
1343 	if (msg == NULL)
1344 		return (ENOMEM);
1345 
1346 	maxp = (struct ngpppoe_maxp *)msg->data;
1347 	strncpy(maxp->hook, NG_HOOK_NAME(sp->hook), NG_HOOKSIZ);
1348 	maxp->data = ntohs(((const struct maxptag *)tag)->data);
1349 	NG_SEND_MSG_ID(error, NG_HOOK_NODE(sp->hook), msg, sp->creator, 0);
1350 
1351 	return (error);
1352 }
1353 
1354 static int
1355 send_hurl(sessp sp, const struct pppoe_tag *tag)
1356 {
1357 	int error, tlen;
1358 	struct ng_mesg *msg;
1359 	struct ngpppoe_padm *padm;
1360 
1361 	CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
1362 
1363 	NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, NGM_PPPOE_HURL,
1364 	    sizeof(struct ngpppoe_padm), M_NOWAIT);
1365 	if (msg == NULL)
1366 		return (ENOMEM);
1367 
1368 	padm = (struct ngpppoe_padm *)msg->data;
1369 	tlen = min(PPPOE_PADM_VALUE_SIZE - 1, ntohs(tag->tag_len));
1370 	strncpy(padm->msg, (const char *)(tag + 1), tlen);
1371 	padm->msg[tlen] = '\0';
1372 	NG_SEND_MSG_ID(error, NG_HOOK_NODE(sp->hook), msg, sp->creator, 0);
1373 
1374 	return (error);
1375 }
1376 
1377 static int
1378 send_motm(sessp sp, const struct pppoe_tag *tag)
1379 {
1380 	int error, tlen;
1381 	struct ng_mesg *msg;
1382 	struct ngpppoe_padm *padm;
1383 
1384 	CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
1385 
1386 	NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, NGM_PPPOE_MOTM,
1387 	    sizeof(struct ngpppoe_padm), M_NOWAIT);
1388 	if (msg == NULL)
1389 		return (ENOMEM);
1390 
1391 	padm = (struct ngpppoe_padm *)msg->data;
1392 	tlen = min(PPPOE_PADM_VALUE_SIZE - 1, ntohs(tag->tag_len));
1393 	strncpy(padm->msg, (const char *)(tag + 1), tlen);
1394 	padm->msg[tlen] = '\0';
1395 	NG_SEND_MSG_ID(error, NG_HOOK_NODE(sp->hook), msg, sp->creator, 0);
1396 
1397 	return (error);
1398 }
1399 
1400 /*
1401  * Receive data from session hook and do something with it.
1402  */
1403 static int
1404 ng_pppoe_rcvdata(hook_p hook, item_p item)
1405 {
1406 	node_p			node = NG_HOOK_NODE(hook);
1407 	const priv_p		privp = NG_NODE_PRIVATE(node);
1408 	sessp			sp = NG_HOOK_PRIVATE(hook);
1409 	struct pppoe_full_hdr	*wh;
1410 	struct mbuf		*m;
1411 	int			error;
1412 
1413 	CTR6(KTR_NET, "%20s: node [%x] (%p) received %p on \"%s\" (%p)",
1414 	    __func__, node->nd_ID, node, item, hook->hk_name, hook);
1415 
1416 	NGI_GET_M(item, m);
1417 	switch (sp->state) {
1418 	case	PPPOE_NEWCONNECTED:
1419 	case	PPPOE_CONNECTED: {
1420 		/*
1421 		 * Remove PPP address and control fields, if any.
1422 		 * For example, ng_ppp(4) always sends LCP packets
1423 		 * with address and control fields as required by
1424 		 * generic PPP. PPPoE is an exception to the rule.
1425 		 */
1426 		if (m->m_pkthdr.len >= 2) {
1427 			if (m->m_len < 2 && !(m = m_pullup(m, 2)))
1428 				LEAVE(ENOBUFS);
1429 			if (mtod(m, u_char *)[0] == 0xff &&
1430 			    mtod(m, u_char *)[1] == 0x03)
1431 				m_adj(m, 2);
1432 		}
1433 		/*
1434 		 * Bang in a pre-made header, and set the length up
1435 		 * to be correct. Then send it to the ethernet driver.
1436 		 */
1437 		M_PREPEND(m, sizeof(*wh), M_NOWAIT);
1438 		if (m == NULL)
1439 			LEAVE(ENOBUFS);
1440 
1441 		wh = mtod(m, struct pppoe_full_hdr *);
1442 		bcopy(&sp->pkt_hdr, wh, sizeof(*wh));
1443 		wh->ph.length = htons(m->m_pkthdr.len - sizeof(*wh));
1444 		NG_FWD_NEW_DATA(error, item, privp->ethernet_hook, m);
1445 		privp->packets_out++;
1446 		break;
1447 		}
1448 	case	PPPOE_PRIMED: {
1449 		struct {
1450 			struct pppoe_tag hdr;
1451 			union	uniq	data;
1452 		} __packed 	uniqtag;
1453 		const struct pppoe_tag	*tag;
1454 		struct mbuf 	*m0;
1455 		const struct pppoe_hdr	*ph;
1456 		negp		neg = sp->neg;
1457 	        uint16_t	session;
1458 		uint16_t	length;
1459 		uint8_t		code;
1460 
1461 		/*
1462 		 * A PADI packet is being returned by the application
1463 		 * that has set up this hook. This indicates that it
1464 		 * wants us to offer service.
1465 		 */
1466 		if (m->m_len < sizeof(*wh)) {
1467 			m = m_pullup(m, sizeof(*wh));
1468 			if (m == NULL)
1469 				LEAVE(ENOBUFS);
1470 		}
1471 		wh = mtod(m, struct pppoe_full_hdr *);
1472 		ph = &wh->ph;
1473 		session = ntohs(wh->ph.sid);
1474 		length = ntohs(wh->ph.length);
1475 		code = wh->ph.code;
1476 		/* Use peers mode in session. */
1477 		neg->pkt->pkt_header.eh.ether_type = wh->eh.ether_type;
1478 		if (code != PADI_CODE)
1479 			LEAVE(EINVAL);
1480 		ng_uncallout(&neg->handle, node);
1481 
1482 		/*
1483 		 * This is the first time we hear
1484 		 * from the client, so note it's
1485 		 * unicast address, replacing the
1486 		 * broadcast address.
1487 		 */
1488 		bcopy(wh->eh.ether_shost,
1489 			neg->pkt->pkt_header.eh.ether_dhost,
1490 			ETHER_ADDR_LEN);
1491 		sp->state = PPPOE_SOFFER;
1492 		neg->timeout = 0;
1493 		neg->pkt->pkt_header.ph.code = PADO_CODE;
1494 
1495 		/*
1496 		 * Start working out the tags to respond with.
1497 		 */
1498 		uniqtag.hdr.tag_type = PTT_AC_COOKIE;
1499 		uniqtag.hdr.tag_len = htons((u_int16_t)sizeof(sp));
1500 		uniqtag.data.pointer = sp;
1501 		init_tags(sp);
1502 		insert_tag(sp, &neg->ac_name.hdr); /* AC_NAME */
1503 		if ((tag = get_tag(ph, PTT_SRV_NAME)))
1504 			insert_tag(sp, tag);	  /* return service */
1505 		/*
1506 		 * If we have a NULL service request
1507 		 * and have an extra service defined in this hook,
1508 		 * then also add a tag for the extra service.
1509 		 * XXX this is a hack. eventually we should be able
1510 		 * to support advertising many services, not just one
1511 		 */
1512 		if (((tag == NULL) || (tag->tag_len == 0)) &&
1513 		    (neg->service.hdr.tag_len != 0)) {
1514 			insert_tag(sp, &neg->service.hdr); /* SERVICE */
1515 		}
1516 		if ((tag = get_tag(ph, PTT_HOST_UNIQ)))
1517 			insert_tag(sp, tag); /* returned hostunique */
1518 		insert_tag(sp, &uniqtag.hdr);
1519 		scan_tags(sp, ph);
1520 		make_packet(sp);
1521 		/*
1522 		 * Send the offer but if they don't respond
1523 		 * in PPPOE_OFFER_TIMEOUT seconds, forget about it.
1524 		 */
1525 		ng_callout(&neg->handle, node, hook, PPPOE_OFFER_TIMEOUT * hz,
1526 		    pppoe_ticker, NULL, 0);
1527 		m0 = m_copypacket(sp->neg->m, M_NOWAIT);
1528 		NG_FWD_NEW_DATA(error, item, privp->ethernet_hook, m0);
1529 		privp->packets_out++;
1530 		break;
1531 		}
1532 
1533 	/*
1534 	 * Packets coming from the hook make no sense
1535 	 * to sessions in the rest of states. Throw them away.
1536 	 */
1537 	default:
1538 		LEAVE(ENETUNREACH);
1539 	}
1540 quit:
1541 	if (item)
1542 		NG_FREE_ITEM(item);
1543 	NG_FREE_M(m);
1544 	return (error);
1545 }
1546 
1547 /*
1548  * Receive data from ether and do something with it.
1549  */
1550 static int
1551 ng_pppoe_rcvdata_ether(hook_p hook, item_p item)
1552 {
1553 	node_p			node = NG_HOOK_NODE(hook);
1554 	const priv_p		privp = NG_NODE_PRIVATE(node);
1555 	sessp			sp;
1556 	const struct pppoe_tag	*utag = NULL, *tag = NULL;
1557 	const struct pppoe_tag	sntag = { PTT_SRV_NAME, 0 };
1558 	const struct pppoe_full_hdr *wh;
1559 	const struct pppoe_hdr	*ph;
1560 	negp			neg = NULL;
1561 	struct mbuf		*m;
1562 	hook_p 			sendhook;
1563 	int			error = 0;
1564 	uint16_t		session;
1565 	uint16_t		length;
1566 	uint8_t			code;
1567 	struct	mbuf 		*m0;
1568 
1569 	CTR6(KTR_NET, "%20s: node [%x] (%p) received %p on \"%s\" (%p)",
1570 	    __func__, node->nd_ID, node, item, hook->hk_name, hook);
1571 
1572 	NGI_GET_M(item, m);
1573 	/*
1574 	 * Dig out various fields from the packet.
1575 	 * Use them to decide where to send it.
1576 	 */
1577 	privp->packets_in++;
1578 	if( m->m_len < sizeof(*wh)) {
1579 		m = m_pullup(m, sizeof(*wh)); /* Checks length */
1580 		if (m == NULL) {
1581 			log(LOG_NOTICE, "ng_pppoe[%x]: couldn't "
1582 			    "m_pullup(wh)\n", node->nd_ID);
1583 			LEAVE(ENOBUFS);
1584 		}
1585 	}
1586 	wh = mtod(m, struct pppoe_full_hdr *);
1587 	length = ntohs(wh->ph.length);
1588 	switch(wh->eh.ether_type) {
1589 	case	ETHERTYPE_PPPOE_3COM_DISC: /* fall through */
1590 	case	ETHERTYPE_PPPOE_DISC:
1591 		/*
1592 		 * We need to try to make sure that the tag area
1593 		 * is contiguous, or we could wander off the end
1594 		 * of a buffer and make a mess.
1595 		 * (Linux wouldn't have this problem).
1596 		 */
1597 		if (m->m_pkthdr.len <= MHLEN) {
1598 			if( m->m_len < m->m_pkthdr.len) {
1599 				m = m_pullup(m, m->m_pkthdr.len);
1600 				if (m == NULL) {
1601 					log(LOG_NOTICE, "ng_pppoe[%x]: "
1602 					    "couldn't m_pullup(pkthdr)\n",
1603 					    node->nd_ID);
1604 					LEAVE(ENOBUFS);
1605 				}
1606 			}
1607 		}
1608 		if (m->m_len != m->m_pkthdr.len) {
1609 			/*
1610 			 * It's not all in one piece.
1611 			 * We need to do extra work.
1612 			 * Put it into a cluster.
1613 			 */
1614 			struct mbuf *n;
1615 			n = m_dup(m, M_NOWAIT);
1616 			m_freem(m);
1617 			m = n;
1618 			if (m) {
1619 				/* just check we got a cluster */
1620 				if (m->m_len != m->m_pkthdr.len) {
1621 					m_freem(m);
1622 					m = NULL;
1623 				}
1624 			}
1625 			if (m == NULL) {
1626 				log(LOG_NOTICE, "ng_pppoe[%x]: packet "
1627 				    "fragmented\n", node->nd_ID);
1628 				LEAVE(EMSGSIZE);
1629 			}
1630 		}
1631 		wh = mtod(m, struct pppoe_full_hdr *);
1632 		length = ntohs(wh->ph.length);
1633 		ph = &wh->ph;
1634 		session = ntohs(wh->ph.sid);
1635 		code = wh->ph.code;
1636 
1637 		switch(code) {
1638 		case	PADI_CODE:
1639 			/*
1640 			 * We are a server:
1641 			 * Look for a hook with the required service and send
1642 			 * the ENTIRE packet up there. It should come back to
1643 			 * a new hook in PRIMED state. Look there for further
1644 			 * processing.
1645 			 */
1646 			tag = get_tag(ph, PTT_SRV_NAME);
1647 			if (tag == NULL)
1648 				tag = &sntag;
1649 
1650 			/*
1651 			 * First, try to match Service-Name against our
1652 			 * listening hooks. If no success and we are in D-Link
1653 			 * compat mode and Service-Name is empty, then we
1654 			 * broadcast the PADI to all listening hooks.
1655 			 */
1656 			sendhook = pppoe_match_svc(node, tag);
1657 			if (sendhook != NULL)
1658 				NG_FWD_NEW_DATA(error, item, sendhook, m);
1659 			else if (privp->flags & COMPAT_DLINK &&
1660 				 ntohs(tag->tag_len) == 0)
1661 				error = pppoe_broadcast_padi(node, m);
1662 			else
1663 				error = ENETUNREACH;
1664 			break;
1665 		case	PADO_CODE:
1666 			/*
1667 			 * We are a client:
1668 			 * Use the host_uniq tag to find the hook this is in
1669 			 * response to. Received #2, now send #3
1670 			 * For now simply accept the first we receive.
1671 			 */
1672 			utag = get_tag(ph, PTT_HOST_UNIQ);
1673 			if (utag == NULL) {
1674 				log(LOG_NOTICE, "ng_pppoe[%x]: no host "
1675 				    "unique field\n", node->nd_ID);
1676 				LEAVE(ENETUNREACH);
1677 			}
1678 
1679 			sendhook = pppoe_finduniq(node, utag);
1680 			if (sendhook == NULL) {
1681 				log(LOG_NOTICE, "ng_pppoe[%x]: no "
1682 				    "matching session\n", node->nd_ID);
1683 				LEAVE(ENETUNREACH);
1684 			}
1685 
1686 			/*
1687 			 * Check the session is in the right state.
1688 			 * It needs to be in PPPOE_SINIT.
1689 			 */
1690 			sp = NG_HOOK_PRIVATE(sendhook);
1691 			if (sp->state == PPPOE_SREQ ||
1692 			    sp->state == PPPOE_CONNECTED) {
1693 				break;	/* Multiple PADO is OK. */
1694 			}
1695 			if (sp->state != PPPOE_SINIT) {
1696 				log(LOG_NOTICE, "ng_pppoe[%x]: session "
1697 				    "in wrong state\n", node->nd_ID);
1698 				LEAVE(ENETUNREACH);
1699 			}
1700 			neg = sp->neg;
1701 			/* If requested specific AC-name, check it. */
1702 			if (neg->ac_name_len) {
1703 				tag = get_tag(ph, PTT_AC_NAME);
1704 				if (!tag) {
1705 					/* No PTT_AC_NAME in PADO */
1706 					break;
1707 				}
1708 				if (neg->ac_name_len != htons(tag->tag_len) ||
1709 				    strncmp(neg->ac_name.data,
1710 				    (const char *)(tag + 1),
1711 				    neg->ac_name_len) != 0) {
1712 					break;
1713 				}
1714 			}
1715 			sp->state = PPPOE_SREQ;
1716 			ng_uncallout(&neg->handle, node);
1717 
1718 			/*
1719 			 * This is the first time we hear
1720 			 * from the server, so note it's
1721 			 * unicast address, replacing the
1722 			 * broadcast address .
1723 			 */
1724 			bcopy(wh->eh.ether_shost,
1725 				neg->pkt->pkt_header.eh.ether_dhost,
1726 				ETHER_ADDR_LEN);
1727 			neg->timeout = 0;
1728 			neg->pkt->pkt_header.ph.code = PADR_CODE;
1729 			init_tags(sp);
1730 			insert_tag(sp, utag);      	/* Host Unique */
1731 			if ((tag = get_tag(ph, PTT_AC_COOKIE)))
1732 				insert_tag(sp, tag); 	/* return cookie */
1733 			if ((tag = get_tag(ph, PTT_AC_NAME))) {
1734 				insert_tag(sp, tag); 	/* return it */
1735 				send_acname(sp, tag);
1736 			}
1737 			if ((tag = get_tag(ph, PTT_MAX_PAYL)) &&
1738 			    (privp->max_payload.data != 0))
1739 				insert_tag(sp, tag);	/* return it */
1740 			insert_tag(sp, &neg->service.hdr); /* Service */
1741 			scan_tags(sp, ph);
1742 			make_packet(sp);
1743 			sp->state = PPPOE_SREQ;
1744 			ng_callout(&neg->handle, node, sp->hook,
1745 			    PPPOE_INITIAL_TIMEOUT * hz,
1746 			    pppoe_ticker, NULL, 0);
1747 			neg->timeout = PPPOE_INITIAL_TIMEOUT * 2;
1748 			m0 = m_copypacket(neg->m, M_NOWAIT);
1749 			NG_FWD_NEW_DATA(error, item, privp->ethernet_hook, m0);
1750 			break;
1751 		case	PADR_CODE:
1752 			/*
1753 			 * We are a server:
1754 			 * Use the ac_cookie tag to find the
1755 			 * hook this is in response to.
1756 			 */
1757 			utag = get_tag(ph, PTT_AC_COOKIE);
1758 			if ((utag == NULL) ||
1759 			    (ntohs(utag->tag_len) != sizeof(sp))) {
1760 				LEAVE(ENETUNREACH);
1761 			}
1762 
1763 			sendhook = pppoe_findcookie(node, utag);
1764 			if (sendhook == NULL)
1765 				LEAVE(ENETUNREACH);
1766 
1767 			/*
1768 			 * Check the session is in the right state.
1769 			 * It needs to be in PPPOE_SOFFER or PPPOE_NEWCONNECTED.
1770 			 * If the latter, then this is a retry by the client,
1771 			 * so be nice, and resend.
1772 			 */
1773 			sp = NG_HOOK_PRIVATE(sendhook);
1774 			if (sp->state == PPPOE_NEWCONNECTED) {
1775 				/*
1776 				 * Whoa! drop back to resend that PADS packet.
1777 				 * We should still have a copy of it.
1778 				 */
1779 				sp->state = PPPOE_SOFFER;
1780 			} else if (sp->state != PPPOE_SOFFER)
1781 				LEAVE (ENETUNREACH);
1782 			neg = sp->neg;
1783 			ng_uncallout(&neg->handle, node);
1784 			neg->pkt->pkt_header.ph.code = PADS_CODE;
1785 			if (sp->Session_ID == 0) {
1786 				neg->pkt->pkt_header.ph.sid =
1787 				    htons(pppoe_getnewsession(sp));
1788 			}
1789 			send_sessionid(sp);
1790 			neg->timeout = 0;
1791 			/*
1792 			 * start working out the tags to respond with.
1793 			 */
1794 			init_tags(sp);
1795 			insert_tag(sp, &neg->ac_name.hdr); /* AC_NAME */
1796 			if ((tag = get_tag(ph, PTT_SRV_NAME)))
1797 				insert_tag(sp, tag);/* return service */
1798 			if ((tag = get_tag(ph, PTT_HOST_UNIQ)))
1799 				insert_tag(sp, tag); /* return it */
1800 			insert_tag(sp, utag);	/* ac_cookie */
1801 			scan_tags(sp, ph);
1802 			make_packet(sp);
1803 			sp->state = PPPOE_NEWCONNECTED;
1804 
1805 			/* Send the PADS without a timeout - we're now connected. */
1806 			m0 = m_copypacket(sp->neg->m, M_NOWAIT);
1807 			NG_FWD_NEW_DATA(error, item, privp->ethernet_hook, m0);
1808 
1809 			/*
1810 			 * Having sent the last Negotiation header,
1811 			 * Set up the stored packet header to be correct for
1812 			 * the actual session. But keep the negotialtion stuff
1813 			 * around in case we need to resend this last packet.
1814 			 * We'll discard it when we move from NEWCONNECTED
1815 			 * to CONNECTED
1816 			 */
1817 			sp->pkt_hdr = neg->pkt->pkt_header;
1818 			/* Configure ethertype depending on what
1819 			 * ethertype was used at discovery phase */
1820 			if (sp->pkt_hdr.eh.ether_type ==
1821 			    ETHERTYPE_PPPOE_3COM_DISC)
1822 				sp->pkt_hdr.eh.ether_type
1823 					= ETHERTYPE_PPPOE_3COM_SESS;
1824 			else
1825 				sp->pkt_hdr.eh.ether_type
1826 					= ETHERTYPE_PPPOE_SESS;
1827 			sp->pkt_hdr.ph.code = 0;
1828 			pppoe_send_event(sp, NGM_PPPOE_SUCCESS);
1829 			break;
1830 		case	PADS_CODE:
1831 			/*
1832 			 * We are a client:
1833 			 * Use the host_uniq tag to find the hook this is in
1834 			 * response to. Take the session ID and store it away.
1835 			 * Also make sure the pre-made header is correct and
1836 			 * set us into Session mode.
1837 			 */
1838 			utag = get_tag(ph, PTT_HOST_UNIQ);
1839 			if (utag == NULL) {
1840 				LEAVE (ENETUNREACH);
1841 			}
1842 			sendhook = pppoe_finduniq(node, utag);
1843 			if (sendhook == NULL)
1844 				LEAVE(ENETUNREACH);
1845 
1846 			/*
1847 			 * Check the session is in the right state.
1848 			 * It needs to be in PPPOE_SREQ.
1849 			 */
1850 			sp = NG_HOOK_PRIVATE(sendhook);
1851 			if (sp->state != PPPOE_SREQ)
1852 				LEAVE(ENETUNREACH);
1853 			neg = sp->neg;
1854 			ng_uncallout(&neg->handle, node);
1855 			neg->pkt->pkt_header.ph.sid = wh->ph.sid;
1856 			sp->Session_ID = ntohs(wh->ph.sid);
1857 			pppoe_addsession(sp);
1858 			send_sessionid(sp);
1859 			neg->timeout = 0;
1860 			sp->state = PPPOE_CONNECTED;
1861 			/*
1862 			 * Now we have gone to Connected mode,
1863 			 * Free all resources needed for negotiation.
1864 			 * Keep a copy of the header we will be using.
1865 			 */
1866 			sp->pkt_hdr = neg->pkt->pkt_header;
1867 			if (privp->flags & COMPAT_3COM)
1868 				sp->pkt_hdr.eh.ether_type
1869 					= ETHERTYPE_PPPOE_3COM_SESS;
1870 			else
1871 				sp->pkt_hdr.eh.ether_type
1872 					= ETHERTYPE_PPPOE_SESS;
1873 			sp->pkt_hdr.ph.code = 0;
1874 			m_freem(neg->m);
1875 			free(sp->neg, M_NETGRAPH_PPPOE);
1876 			sp->neg = NULL;
1877 			if ((tag = get_tag(ph, PTT_MAX_PAYL)) &&
1878 			    (privp->max_payload.data != 0))
1879 				send_maxp(sp, tag);
1880 			pppoe_send_event(sp, NGM_PPPOE_SUCCESS);
1881 			break;
1882 		case	PADT_CODE:
1883 			/*
1884 			 * Find matching peer/session combination.
1885 			 */
1886 			sp = pppoe_findsession(privp, wh);
1887 			if (sp == NULL)
1888 				LEAVE(ENETUNREACH);
1889 			/* Disconnect that hook. */
1890 			ng_rmhook_self(sp->hook);
1891 			break;
1892 		case	PADM_CODE:
1893 			/*
1894 			 * We are a client:
1895 			 * find matching peer/session combination.
1896 			 */
1897 			sp = pppoe_findsession(privp, wh);
1898 			if (sp == NULL)
1899 				LEAVE (ENETUNREACH);
1900 			if ((tag = get_tag(ph, PTT_HURL)))
1901 				send_hurl(sp, tag);
1902 			if ((tag = get_tag(ph, PTT_MOTM)))
1903 				send_motm(sp, tag);
1904 			break;
1905 		default:
1906 			LEAVE(EPFNOSUPPORT);
1907 		}
1908 		break;
1909 	case	ETHERTYPE_PPPOE_3COM_SESS:
1910 	case	ETHERTYPE_PPPOE_SESS:
1911 		/*
1912 		 * Find matching peer/session combination.
1913 		 */
1914 		sp = pppoe_findsession(privp, wh);
1915 		if (sp == NULL)
1916 			LEAVE (ENETUNREACH);
1917 		m_adj(m, sizeof(*wh));
1918 
1919 		/* If packet too short, dump it. */
1920 		if (m->m_pkthdr.len < length)
1921 			LEAVE(EMSGSIZE);
1922 		/* Also need to trim excess at the end */
1923 		if (m->m_pkthdr.len > length) {
1924 			m_adj(m, -((int)(m->m_pkthdr.len - length)));
1925 		}
1926 		if ( sp->state != PPPOE_CONNECTED) {
1927 			if (sp->state == PPPOE_NEWCONNECTED) {
1928 				sp->state = PPPOE_CONNECTED;
1929 				/*
1930 				 * Now we have gone to Connected mode,
1931 				 * Free all resources needed for negotiation.
1932 				 * Be paranoid about whether there may be
1933 				 * a timeout.
1934 				 */
1935 				m_freem(sp->neg->m);
1936 				ng_uncallout(&sp->neg->handle, node);
1937 				free(sp->neg, M_NETGRAPH_PPPOE);
1938 				sp->neg = NULL;
1939 			} else {
1940 				LEAVE (ENETUNREACH);
1941 			}
1942 		}
1943 		NG_FWD_NEW_DATA(error, item, sp->hook, m);
1944 		break;
1945 	default:
1946 		LEAVE(EPFNOSUPPORT);
1947 	}
1948 quit:
1949 	if (item)
1950 		NG_FREE_ITEM(item);
1951 	NG_FREE_M(m);
1952 	return (error);
1953 }
1954 
1955 /*
1956  * Receive data from debug hook and bypass it to ether.
1957  */
1958 static int
1959 ng_pppoe_rcvdata_debug(hook_p hook, item_p item)
1960 {
1961 	node_p		node = NG_HOOK_NODE(hook);
1962 	const priv_p	privp = NG_NODE_PRIVATE(node);
1963 	int		error;
1964 
1965 	CTR6(KTR_NET, "%20s: node [%x] (%p) received %p on \"%s\" (%p)",
1966 	    __func__, node->nd_ID, node, item, hook->hk_name, hook);
1967 
1968 	NG_FWD_ITEM_HOOK(error, item, privp->ethernet_hook);
1969 	privp->packets_out++;
1970 	return (error);
1971 }
1972 
1973 /*
1974  * Do local shutdown processing..
1975  * If we are a persistent device, we might refuse to go away, and
1976  * we'd only remove our links and reset ourself.
1977  */
1978 static int
1979 ng_pppoe_shutdown(node_p node)
1980 {
1981 	const priv_p privp = NG_NODE_PRIVATE(node);
1982 	int	i;
1983 
1984 	for (i = 0; i < SESSHASHSIZE; i++)
1985 	    mtx_destroy(&privp->sesshash[i].mtx);
1986 	NG_NODE_SET_PRIVATE(node, NULL);
1987 	NG_NODE_UNREF(privp->node);
1988 	free(privp, M_NETGRAPH_PPPOE);
1989 	return (0);
1990 }
1991 
1992 /*
1993  * Hook disconnection
1994  *
1995  * Clean up all dangling links and information about the session/hook.
1996  * For this type, removal of the last link destroys the node.
1997  */
1998 static int
1999 ng_pppoe_disconnect(hook_p hook)
2000 {
2001 	node_p node = NG_HOOK_NODE(hook);
2002 	priv_p privp = NG_NODE_PRIVATE(node);
2003 	sessp	sp;
2004 
2005 	if (hook == privp->debug_hook) {
2006 		privp->debug_hook = NULL;
2007 	} else if (hook == privp->ethernet_hook) {
2008 		privp->ethernet_hook = NULL;
2009 		if (NG_NODE_IS_VALID(node))
2010 			ng_rmnode_self(node);
2011 	} else {
2012 		sp = NG_HOOK_PRIVATE(hook);
2013 		if (sp->state != PPPOE_SNONE ) {
2014 			pppoe_send_event(sp, NGM_PPPOE_CLOSE);
2015 		}
2016 		/*
2017 		 * According to the spec, if we are connected,
2018 		 * we should send a DISC packet if we are shutting down
2019 		 * a session.
2020 		 */
2021 		if ((privp->ethernet_hook)
2022 		&& ((sp->state == PPPOE_CONNECTED)
2023 		 || (sp->state == PPPOE_NEWCONNECTED))) {
2024 			struct mbuf *m;
2025 
2026 			/* Generate a packet of that type. */
2027 			m = m_gethdr(M_NOWAIT, MT_DATA);
2028 			if (m == NULL)
2029 				log(LOG_NOTICE, "ng_pppoe[%x]: session out of "
2030 				    "mbufs\n", node->nd_ID);
2031 			else {
2032 				struct pppoe_full_hdr *wh;
2033 				struct pppoe_tag *tag;
2034 				int	msglen = strlen(SIGNOFF);
2035 				int	error = 0;
2036 
2037 				wh = mtod(m, struct pppoe_full_hdr *);
2038 				bcopy(&sp->pkt_hdr, wh, sizeof(*wh));
2039 
2040 				/* Revert the stored header to DISC/PADT mode. */
2041 				wh->ph.code = PADT_CODE;
2042 				/*
2043 				 * Configure ethertype depending on what
2044 				 * was used during sessions stage.
2045 				 */
2046 				if (wh->eh.ether_type ==
2047 				    ETHERTYPE_PPPOE_3COM_SESS)
2048 					wh->eh.ether_type = ETHERTYPE_PPPOE_3COM_DISC;
2049 				else
2050 					wh->eh.ether_type = ETHERTYPE_PPPOE_DISC;
2051 				/*
2052 				 * Add a General error message and adjust
2053 				 * sizes.
2054 				 */
2055 				tag = (void *)(&wh->ph + 1);
2056 				tag->tag_type = PTT_GEN_ERR;
2057 				tag->tag_len = htons((u_int16_t)msglen);
2058 				strncpy((char *)(tag + 1), SIGNOFF, msglen);
2059 				m->m_pkthdr.len = m->m_len = sizeof(*wh) + sizeof(*tag) +
2060 				    msglen;
2061 				wh->ph.length = htons(sizeof(*tag) + msglen);
2062 				NG_SEND_DATA_ONLY(error,
2063 					privp->ethernet_hook, m);
2064 			}
2065 		}
2066 		if (sp->state == PPPOE_LISTENING)
2067 			LIST_REMOVE(sp, sessions);
2068 		else if (sp->Session_ID)
2069 			pppoe_delsession(sp);
2070 		/*
2071 		 * As long as we have somewhere to store the timeout handle,
2072 		 * we may have a timeout pending.. get rid of it.
2073 		 */
2074 		if (sp->neg) {
2075 			ng_uncallout(&sp->neg->handle, node);
2076 			if (sp->neg->m)
2077 				m_freem(sp->neg->m);
2078 			free(sp->neg, M_NETGRAPH_PPPOE);
2079 		}
2080 		free(sp, M_NETGRAPH_PPPOE);
2081 		NG_HOOK_SET_PRIVATE(hook, NULL);
2082 	}
2083 	if ((NG_NODE_NUMHOOKS(node) == 0) &&
2084 	    (NG_NODE_IS_VALID(node)))
2085 		ng_rmnode_self(node);
2086 	return (0);
2087 }
2088 
2089 /*
2090  * Timeouts come here.
2091  */
2092 static void
2093 pppoe_ticker(node_p node, hook_p hook, void *arg1, int arg2)
2094 {
2095 	priv_p privp = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
2096 	sessp	sp = NG_HOOK_PRIVATE(hook);
2097 	negp	neg = sp->neg;
2098 	struct mbuf *m0 = NULL;
2099 	int	error = 0;
2100 
2101 	CTR6(KTR_NET, "%20s: node [%x] (%p) hook \"%s\" (%p) session %d",
2102 	    __func__, node->nd_ID, node, hook->hk_name, hook, sp->Session_ID);
2103 	switch(sp->state) {
2104 		/*
2105 		 * Resend the last packet, using an exponential backoff.
2106 		 * After a period of time, stop growing the backoff,
2107 		 * And either leave it, or revert to the start.
2108 		 */
2109 	case	PPPOE_SINIT:
2110 	case	PPPOE_SREQ:
2111 		/* Timeouts on these produce resends. */
2112 		m0 = m_copypacket(sp->neg->m, M_NOWAIT);
2113 		NG_SEND_DATA_ONLY( error, privp->ethernet_hook, m0);
2114 		ng_callout(&neg->handle, node, hook, neg->timeout * hz,
2115 		    pppoe_ticker, NULL, 0);
2116 		if ((neg->timeout <<= 1) > PPPOE_TIMEOUT_LIMIT) {
2117 			if (sp->state == PPPOE_SREQ) {
2118 				/* Revert to SINIT mode. */
2119 				pppoe_start(sp);
2120 			} else {
2121 				neg->timeout = PPPOE_TIMEOUT_LIMIT;
2122 			}
2123 		}
2124 		break;
2125 	case	PPPOE_PRIMED:
2126 	case	PPPOE_SOFFER:
2127 		/* A timeout on these says "give up" */
2128 		ng_rmhook_self(hook);
2129 		break;
2130 	default:
2131 		/* Timeouts have no meaning in other states. */
2132 		log(LOG_NOTICE, "ng_pppoe[%x]: unexpected timeout\n",
2133 		    node->nd_ID);
2134 	}
2135 }
2136 
2137 /*
2138  * Parse an incoming packet to see if any tags should be copied to the
2139  * output packet. Don't do any tags that have been handled in the main
2140  * state machine.
2141  */
2142 static const struct pppoe_tag*
2143 scan_tags(sessp	sp, const struct pppoe_hdr* ph)
2144 {
2145 	const char *const end = (const char *)next_tag(ph);
2146 	const char *ptn;
2147 	const struct pppoe_tag *pt = (const void *)(ph + 1);
2148 
2149 	/*
2150 	 * Keep processing tags while a tag header will still fit.
2151 	 */
2152 	CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
2153 
2154 	while((const char*)(pt + 1) <= end) {
2155 		/*
2156 		 * If the tag data would go past the end of the packet, abort.
2157 		 */
2158 		ptn = (((const char *)(pt + 1)) + ntohs(pt->tag_len));
2159 		if(ptn > end)
2160 			return NULL;
2161 
2162 		switch (pt->tag_type) {
2163 		case	PTT_RELAY_SID:
2164 			insert_tag(sp, pt);
2165 			break;
2166 		case	PTT_EOL:
2167 			return NULL;
2168 		case	PTT_SRV_NAME:
2169 		case	PTT_AC_NAME:
2170 		case	PTT_HOST_UNIQ:
2171 		case	PTT_AC_COOKIE:
2172 		case	PTT_VENDOR:
2173 		case	PTT_SRV_ERR:
2174 		case	PTT_SYS_ERR:
2175 		case	PTT_GEN_ERR:
2176 		case	PTT_MAX_PAYL:
2177 		case	PTT_HURL:
2178 		case	PTT_MOTM:
2179 			break;
2180 		}
2181 		pt = (const struct pppoe_tag*)ptn;
2182 	}
2183 	return NULL;
2184 }
2185 
2186 static	int
2187 pppoe_send_event(sessp sp, enum cmd cmdid)
2188 {
2189 	int error;
2190 	struct ng_mesg *msg;
2191 	struct ngpppoe_sts *sts;
2192 
2193 	CTR2(KTR_NET, "%20s: called %d", __func__, sp->Session_ID);
2194 
2195 	NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, cmdid,
2196 			sizeof(struct ngpppoe_sts), M_NOWAIT);
2197 	if (msg == NULL)
2198 		return (ENOMEM);
2199 	sts = (struct ngpppoe_sts *)msg->data;
2200 	strncpy(sts->hook, NG_HOOK_NAME(sp->hook), NG_HOOKSIZ);
2201 	NG_SEND_MSG_ID(error, NG_HOOK_NODE(sp->hook), msg, sp->creator, 0);
2202 	return (error);
2203 }
2204