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