ng_pppoe.c revision 70700
1193323Sed
2193323Sed/*
3193323Sed * ng_pppoe.c
4193323Sed *
5193323Sed * Copyright (c) 1996-1999 Whistle Communications, Inc.
6193323Sed * All rights reserved.
7193323Sed *
8193323Sed * Subject to the following obligations and disclaimer of warranty, use and
9193323Sed * redistribution of this software, in source or object code forms, with or
10193323Sed * without modifications are expressly permitted by Whistle Communications;
11193323Sed * provided, however, that:
12193323Sed * 1. Any and all reproductions of the source or object code must include the
13193323Sed *    copyright notice above and the following disclaimer of warranties; and
14193323Sed * 2. No rights are granted, in any manner or form, to use Whistle
15193323Sed *    Communications, Inc. trademarks, including the mark "WHISTLE
16193323Sed *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17249423Sdim *    such appears in the above copyright notice or in the software.
18193323Sed *
19193323Sed * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20249423Sdim * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21249423Sdim * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22249423Sdim * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23249423Sdim * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24263508Sdim * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25193323Sed * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26193323Sed * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27193323Sed * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28193323Sed * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29193323Sed * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30195340Sed * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31249423Sdim * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32193323Sed * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33193323Sed * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34193323Sed * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35193323Sed * OF SUCH DAMAGE.
36193323Sed *
37193323Sed * Author: Julian Elischer <julian@freebsd.org>
38249423Sdim *
39193323Sed * $FreeBSD: head/sys/netgraph/ng_pppoe.c 70700 2001-01-06 00:46:47Z julian $
40193323Sed * $Whistle: ng_pppoe.c,v 1.10 1999/11/01 09:24:52 julian Exp $
41193323Sed */
42193323Sed#if 0
43193323Sed#define AAA printf("pppoe: %s\n", __FUNCTION__ );
44193323Sed#define BBB printf("-%d-", __LINE__ );
45193323Sed#else
46193323Sed#define AAA
47193323Sed#define BBB
48224145Sdim#endif
49193323Sed
50224145Sdim#include <sys/param.h>
51193323Sed#include <sys/systm.h>
52193323Sed#include <sys/kernel.h>
53193323Sed#include <sys/mbuf.h>
54193323Sed#include <sys/malloc.h>
55193323Sed#include <sys/errno.h>
56193323Sed#include <net/ethernet.h>
57193323Sed
58193323Sed#include <netgraph/ng_message.h>
59193323Sed#include <netgraph/netgraph.h>
60193323Sed#include <netgraph/ng_parse.h>
61249423Sdim#include <netgraph/ng_pppoe.h>
62193323Sed
63193323Sed#define SIGNOFF "session closed"
64193323Sed#define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
65193323Sed
66249423Sdim/*
67193323Sed * This section contains the netgraph method declarations for the
68193323Sed * sample node. These methods define the netgraph 'type'.
69193323Sed */
70193323Sed
71249423Sdimstatic ng_constructor_t	ng_pppoe_constructor;
72193323Sedstatic ng_rcvmsg_t	ng_pppoe_rcvmsg;
73193323Sedstatic ng_shutdown_t	ng_pppoe_shutdown;
74193323Sedstatic ng_newhook_t	ng_pppoe_newhook;
75193323Sedstatic ng_connect_t	ng_pppoe_connect;
76193323Sedstatic ng_rcvdata_t	ng_pppoe_rcvdata;
77193323Sedstatic ng_disconnect_t	ng_pppoe_disconnect;
78193323Sed
79249423Sdim/* Parse type for struct ngpppoe_init_data */
80226633Sdimstatic const struct ng_parse_struct_info ngpppoe_init_data_type_info
81226633Sdim	= NG_PPPOE_INIT_DATA_TYPE_INFO;
82249423Sdimstatic const struct ng_parse_type ngpppoe_init_data_state_type = {
83193323Sed	&ng_parse_struct_type,
84249423Sdim	&ngpppoe_init_data_type_info
85193323Sed};
86193323Sed
87193323Sed/* Parse type for struct ngpppoe_sts */
88193323Sedstatic const struct ng_parse_struct_info ng_pppoe_sts_type_info
89193323Sed	= NG_PPPOE_STS_TYPE_INFO;
90198090Srdivackystatic const struct ng_parse_type ng_pppoe_sts_state_type = {
91198090Srdivacky	&ng_parse_struct_type,
92198090Srdivacky	&ng_pppoe_sts_type_info
93198090Srdivacky};
94198090Srdivacky
95198090Srdivacky/* List of commands and how to convert arguments to/from ASCII */
96198090Srdivackystatic const struct ng_cmdlist ng_pppoe_cmds[] = {
97249423Sdim	{
98198892Srdivacky	  NGM_PPPOE_COOKIE,
99198090Srdivacky	  NGM_PPPOE_CONNECT,
100198090Srdivacky	  "pppoe_connect",
101198090Srdivacky	  &ngpppoe_init_data_state_type,
102198090Srdivacky	  NULL
103198090Srdivacky	},
104198090Srdivacky	{
105198090Srdivacky	  NGM_PPPOE_COOKIE,
106198090Srdivacky	  NGM_PPPOE_LISTEN,
107198090Srdivacky	  "pppoe_listen",
108198090Srdivacky	  &ngpppoe_init_data_state_type,
109198090Srdivacky	  NULL
110249423Sdim	},
111198090Srdivacky	{
112198090Srdivacky	  NGM_PPPOE_COOKIE,
113198090Srdivacky	  NGM_PPPOE_OFFER,
114198090Srdivacky	  "pppoe_offer",
115249423Sdim	  &ngpppoe_init_data_state_type,
116198090Srdivacky	  NULL
117198090Srdivacky	},
118198090Srdivacky	{
119198090Srdivacky	  NGM_PPPOE_COOKIE,
120198090Srdivacky	  NGM_PPPOE_SERVICE,
121198090Srdivacky	  "pppoe_service",
122198090Srdivacky	  &ngpppoe_init_data_state_type,
123198090Srdivacky	  NULL
124198090Srdivacky	},
125203954Srdivacky	{
126198892Srdivacky	  NGM_PPPOE_COOKIE,
127203954Srdivacky	  NGM_PPPOE_SUCCESS,
128193323Sed	  "pppoe_success",
129203954Srdivacky	  &ng_pppoe_sts_state_type,
130234353Sdim	  NULL
131193323Sed	},
132234353Sdim	{
133234353Sdim	  NGM_PPPOE_COOKIE,
134234353Sdim	  NGM_PPPOE_FAIL,
135249423Sdim	  "pppoe_fail",
136224145Sdim	  &ng_pppoe_sts_state_type,
137193323Sed	  NULL
138198090Srdivacky	},
139198090Srdivacky	{
140234353Sdim	  NGM_PPPOE_COOKIE,
141198090Srdivacky	  NGM_PPPOE_CLOSE,
142193323Sed	  "pppoe_close",
143193323Sed	  &ng_pppoe_sts_state_type,
144263508Sdim	  NULL
145249423Sdim	},
146263508Sdim	{ 0 }
147263508Sdim};
148193323Sed
149193323Sed/* Netgraph node type descriptor */
150193323Sedstatic struct ng_type typestruct = {
151249423Sdim	NG_ABI_VERSION,
152249423Sdim	NG_PPPOE_NODE_TYPE,
153249423Sdim	NULL,
154249423Sdim	ng_pppoe_constructor,
155249423Sdim	ng_pppoe_rcvmsg,
156193323Sed	ng_pppoe_shutdown,
157193323Sed	ng_pppoe_newhook,
158193323Sed	NULL,
159249423Sdim	ng_pppoe_connect,
160193323Sed	ng_pppoe_rcvdata,
161193323Sed	ng_pppoe_disconnect,
162193323Sed	ng_pppoe_cmds
163193323Sed};
164249423SdimNETGRAPH_INIT(pppoe, &typestruct);
165193323Sed
166193323Sed/*
167193323Sed * States for the session state machine.
168212904Sdim * These have no meaning if there is no hook attached yet.
169212904Sdim */
170212904Sdimenum state {
171249423Sdim    PPPOE_SNONE=0,	/* [both] Initial state */
172234353Sdim    PPPOE_LISTENING,	/* [Daemon] Listening for discover initiation pkt */
173234353Sdim    PPPOE_SINIT,	/* [Client] Sent discovery initiation */
174234353Sdim    PPPOE_PRIMED,	/* [Server] Awaiting PADI from daemon */
175234353Sdim    PPPOE_SOFFER,	/* [Server] Sent offer message  (got PADI)*/
176249423Sdim    PPPOE_SREQ,		/* [Client] Sent a Request */
177193323Sed    PPPOE_NEWCONNECTED,	/* [Server] Connection established, No data received */
178203954Srdivacky    PPPOE_CONNECTED,	/* [Both] Connection established, Data received */
179203954Srdivacky    PPPOE_DEAD		/* [Both] */
180203954Srdivacky};
181249423Sdim
182198892Srdivacky#define NUMTAGS 20 /* number of tags we are set up to work with */
183198892Srdivacky
184198892Srdivacky/*
185198892Srdivacky * Information we store for each hook on each node for negotiating the
186212904Sdim * session. The mbuf and cluster are freed once negotiation has completed.
187243830Sdim * The whole negotiation block is then discarded.
188243830Sdim */
189243830Sdim
190243830Sdimstruct sess_neg {
191243830Sdim	struct mbuf 		*m; /* holds cluster with last sent packet */
192243830Sdim	union	packet		*pkt; /* points within the above cluster */
193243830Sdim	struct callout_handle	timeout_handle;   /* see timeout(9) */
194243830Sdim	u_int			timeout; /* 0,1,2,4,8,16 etc. seconds */
195243830Sdim	u_int			numtags;
196263508Sdim	struct pppoe_tag	*tags[NUMTAGS];
197263508Sdim	u_int			service_len;
198193323Sed	u_int			ac_name_len;
199263508Sdim
200263508Sdim	struct datatag		service;
201263508Sdim	struct datatag		ac_name;
202263508Sdim};
203263508Sdimtypedef struct sess_neg *negp;
204263508Sdim
205263508Sdim/*
206263508Sdim * Session information that is needed after connection.
207263508Sdim */
208263508Sdimstruct sess_con {
209263508Sdim	hook_p  		hook;
210263508Sdim	u_int16_t		Session_ID;
211263508Sdim	enum state		state;
212263508Sdim	ng_ID_t			creator;		/* who to notify */
213263508Sdim	struct pppoe_full_hdr	pkt_hdr;	/* used when connected */
214263508Sdim	negp			neg;		/* used when negotiating */
215263508Sdim	/*struct sess_con	*hash_next;*/	/* not yet used */
216263508Sdim};
217263508Sdimtypedef struct sess_con *sessp;
218263508Sdim
219263508Sdim/*
220263508Sdim * Information we store for each node
221263508Sdim */
222263508Sdimstruct PPPOE {
223263508Sdim	node_p		node;		/* back pointer to node */
224263508Sdim	hook_p  	ethernet_hook;
225263508Sdim	hook_p  	debug_hook;
226201360Srdivacky	u_int   	packets_in;	/* packets in from ethernet */
227203954Srdivacky	u_int   	packets_out;	/* packets out towards ethernet */
228234353Sdim	u_int32_t	flags;
229263508Sdim	/*struct sess_con *buckets[HASH_SIZE];*/	/* not yet used */
230243830Sdim};
231193323Sedtypedef struct PPPOE *priv_p;
232234353Sdim
233234353Sdimconst struct ether_header eh_prototype =
234234353Sdim	{{0xff,0xff,0xff,0xff,0xff,0xff},
235263508Sdim	 {0x00,0x00,0x00,0x00,0x00,0x00},
236243830Sdim	 ETHERTYPE_PPPOE_DISC};
237234353Sdim
238193323Sedunion uniq {
239193323Sed	char bytes[sizeof(void *)];
240193323Sed	void * pointer;
241234353Sdim	};
242234353Sdim
243234353Sdim#define	LEAVE(x) do { error = x; goto quit; } while(0)
244193323Sedstatic void	pppoe_start(sessp sp);
245249423Sdimstatic void	sendpacket(sessp sp);
246203954Srdivackystatic void	pppoe_ticker(void *arg);
247203954Srdivackystatic struct pppoe_tag* scan_tags(sessp	sp, struct pppoe_hdr* ph);
248203954Srdivackystatic	int	pppoe_send_event(sessp sp, enum cmd cmdid);
249249423Sdim
250203954Srdivacky/*************************************************************************
251203954Srdivacky * Some basic utilities  from the Linux version with author's permission.*
252263508Sdim * Author:	Michal Ostrowski <mostrows@styx.uwaterloo.ca>		 *
253263508Sdim ************************************************************************/
254203954Srdivacky
255193323Sed/*
256193323Sed * Generate a new session id
257193323Sed * XXX find out the FreeBSD locking scheme.
258263508Sdim */
259218893Sdimstatic u_int16_t
260218893Sdimget_new_sid(node_p node)
261218893Sdim{
262263508Sdim	static int pppoe_sid = 10;
263243830Sdim	sessp sp;
264243830Sdim	hook_p	hook;
265243830Sdim	u_int16_t val;
266193323Sed	priv_p privp = node->private;
267224145Sdim
268226633SdimAAA
269224145Sdimrestart:
270198090Srdivacky	val = pppoe_sid++;
271224145Sdim	/*
272193323Sed	 * Spec says 0xFFFF is reserved.
273193323Sed	 * Also don't use 0x0000
274193323Sed	 */
275193323Sed	if (val == 0xffff) {
276193323Sed		pppoe_sid = 20;
277249423Sdim		goto restart;
278193323Sed	}
279193323Sed
280249423Sdim	/* Check it isn't already in use */
281193323Sed	LIST_FOREACH(hook, &node->hooks, hooks) {
282249423Sdim		/* don't check special hooks */
283193323Sed		if ((hook->private == &privp->debug_hook)
284193323Sed		||  (hook->private == &privp->ethernet_hook))
285193323Sed			continue;
286263508Sdim		sp = hook->private;
287193323Sed		if (sp->Session_ID == val)
288193323Sed			goto restart;
289193323Sed	}
290243830Sdim
291243830Sdim	return val;
292243830Sdim}
293193323Sed
294193323Sed
295193323Sed/*
296193323Sed * Return the location where the next tag can be put
297193323Sed */
298193323Sedstatic __inline struct pppoe_tag*
299193323Sednext_tag(struct pppoe_hdr* ph)
300193323Sed{
301243830Sdim	return (struct pppoe_tag*)(((char*)&ph->tag[0]) + ntohs(ph->length));
302193323Sed}
303193323Sed
304193323Sed/*
305193323Sed * Look for a tag of a specific type
306243830Sdim * Don't trust any length the other end says.
307243830Sdim * but assume we already sanity checked ph->length.
308243830Sdim */
309243830Sdimstatic struct pppoe_tag*
310263508Sdimget_tag(struct pppoe_hdr* ph, u_int16_t idx)
311243830Sdim{
312243830Sdim	char *end = (char *)next_tag(ph);
313243830Sdim	char *ptn;
314243830Sdim	struct pppoe_tag *pt = &ph->tag[0];
315243830Sdim	/*
316243830Sdim	 * Keep processing tags while a tag header will still fit.
317243830Sdim	 */
318243830SdimAAA
319243830Sdim	while((char*)(pt + 1) <= end) {
320263508Sdim	    /*
321243830Sdim	     * If the tag data would go past the end of the packet, abort.
322243830Sdim	     */
323193323Sed	    ptn = (((char *)(pt + 1)) + ntohs(pt->tag_len));
324193323Sed	    if(ptn > end)
325193323Sed		return NULL;
326243830Sdim
327243830Sdim	    if(pt->tag_type == idx)
328263508Sdim		return pt;
329243830Sdim
330243830Sdim	    pt = (struct pppoe_tag*)ptn;
331243830Sdim	}
332243830Sdim	return NULL;
333243830Sdim}
334243830Sdim
335243830Sdim/**************************************************************************
336243830Sdim * inlines to initialise or add tags to a session's tag list,
337243830Sdim **************************************************************************/
338243830Sdim/*
339263508Sdim * Initialise the session's tag list
340243830Sdim */
341243830Sdimstatic void
342243830Sdiminit_tags(sessp sp)
343243830Sdim{
344243830SdimAAA
345243830Sdim	if(sp->neg == NULL) {
346243830Sdim		printf("pppoe: asked to init NULL neg pointer\n");
347243830Sdim		return;
348243830Sdim	}
349263508Sdim	sp->neg->numtags = 0;
350263508Sdim}
351263508Sdim
352263508Sdimstatic void
353263508Sdiminsert_tag(sessp sp, struct pppoe_tag *tp)
354263508Sdim{
355224145Sdim	int	i;
356263508Sdim	negp neg;
357263508Sdim
358263508SdimAAA
359263508Sdim	if((neg = sp->neg) == NULL) {
360263508Sdim		printf("pppoe: asked to use NULL neg pointer\n");
361263508Sdim		return;
362263508Sdim	}
363263508Sdim	if ((i = neg->numtags++) < NUMTAGS) {
364263508Sdim		neg->tags[i] = tp;
365263508Sdim	} else {
366263508Sdim		printf("pppoe: asked to add too many tags to packet\n");
367263508Sdim		neg->numtags--;
368263508Sdim	}
369263508Sdim}
370234353Sdim
371193323Sed/*
372249423Sdim * Make up a packet, using the tags filled out for the session.
373193323Sed *
374193323Sed * Assume that the actual pppoe header and ethernet header
375193323Sed * are filled out externally to this routine.
376 * Also assume that neg->wh points to the correct
377 * location at the front of the buffer space.
378 */
379static void
380make_packet(sessp sp) {
381	struct pppoe_full_hdr *wh = &sp->neg->pkt->pkt_header;
382	struct pppoe_tag **tag;
383	char *dp;
384	int count;
385	int tlen;
386	u_int16_t length = 0;
387
388AAA
389	if ((sp->neg == NULL) || (sp->neg->m == NULL)) {
390		printf("pppoe: make_packet called from wrong state\n");
391	}
392	dp = (char *)wh->ph.tag;
393	for (count = 0, tag = sp->neg->tags;
394	    ((count < sp->neg->numtags) && (count < NUMTAGS));
395	    tag++, count++) {
396		tlen = ntohs((*tag)->tag_len) + sizeof(**tag);
397		if ((length + tlen) > (ETHER_MAX_LEN - 4 - sizeof(*wh))) {
398			printf("pppoe: tags too long\n");
399			sp->neg->numtags = count;
400			break;	/* XXX chop off what's too long */
401		}
402		bcopy((char *)*tag, (char *)dp, tlen);
403		length += tlen;
404		dp += tlen;
405	}
406 	wh->ph.length = htons(length);
407	sp->neg->m->m_len = length + sizeof(*wh);
408	sp->neg->m->m_pkthdr.len = length + sizeof(*wh);
409}
410
411/**************************************************************************
412 * Routine to match a service offered					  *
413 **************************************************************************/
414/*
415 * Find a hook that has a service string that matches that
416 * we are seeking. for now use a simple string.
417 * In the future we may need something like regexp().
418 * for testing allow a null string to match 1st found and a null service
419 * to match all requests. Also make '*' do the same.
420 */
421static hook_p
422pppoe_match_svc(node_p node, char *svc_name, int svc_len)
423{
424	sessp	sp	= NULL;
425	negp	neg	= NULL;
426	priv_p	privp	= node->private;
427	hook_p hook;
428
429AAA
430	LIST_FOREACH(hook, &node->hooks, hooks) {
431
432		/* skip any hook that is debug or ethernet */
433		if ((hook->private == &privp->debug_hook)
434		||  (hook->private == &privp->ethernet_hook))
435			continue;
436		sp = hook->private;
437
438		/* Skip any sessions which are not in LISTEN mode. */
439		if ( sp->state != PPPOE_LISTENING)
440			continue;
441
442		neg = sp->neg;
443		/* XXX check validity of this */
444		/* special case, NULL request. match 1st found. */
445		if (svc_len == 0)
446			break;
447
448		/* XXX check validity of this */
449		/* Special case for a blank or "*" service name (wildcard) */
450		if ((neg->service_len == 0)
451		||  ((neg->service_len == 1)
452		  && (neg->service.data[0] == '*'))) {
453			break;
454		}
455
456		/* If the lengths don't match, that aint it. */
457		if (neg->service_len != svc_len)
458			continue;
459
460		/* An exact match? */
461		if (strncmp(svc_name, neg->service.data, svc_len) == 0)
462			break;
463	}
464	return (hook);
465}
466/**************************************************************************
467 * Routine to find a particular session that matches an incoming packet	  *
468 **************************************************************************/
469static hook_p
470pppoe_findsession(node_p node, struct pppoe_full_hdr *wh)
471{
472	sessp	sp = NULL;
473	hook_p hook = NULL;
474	priv_p	privp = node->private;
475	u_int16_t	session = ntohs(wh->ph.sid);
476
477	/*
478	 * find matching peer/session combination.
479	 */
480AAA
481	LIST_FOREACH(hook, &node->hooks, hooks) {
482		/* don't check special hooks */
483		if ((hook->private == &privp->debug_hook)
484		||  (hook->private == &privp->ethernet_hook)) {
485			continue;
486		}
487		sp = hook->private;
488		if ( ( (sp->state == PPPOE_CONNECTED)
489		    || (sp->state == PPPOE_NEWCONNECTED) )
490		&& (sp->Session_ID == session)
491		&& (bcmp(sp->pkt_hdr.eh.ether_dhost,
492		    wh->eh.ether_shost,
493		    ETHER_ADDR_LEN)) == 0) {
494			break;
495		}
496	}
497	return (hook);
498}
499
500static hook_p
501pppoe_finduniq(node_p node, struct pppoe_tag *tag)
502{
503	hook_p hook = NULL;
504	priv_p	privp = node->private;
505	union uniq		uniq;
506
507AAA
508	bcopy(tag->tag_data, uniq.bytes, sizeof(void *));
509	/* cycle through all known hooks */
510	LIST_FOREACH(hook, &node->hooks, hooks) {
511		/* don't check special hooks */
512		if ((hook->private == &privp->debug_hook)
513		||  (hook->private == &privp->ethernet_hook))
514			continue;
515		if (uniq.pointer == hook->private)
516			break;
517	}
518	return (hook);
519}
520
521/**************************************************************************
522 * start of Netgraph entrypoints					  *
523 **************************************************************************/
524
525/*
526 * Allocate the private data structure and the generic node
527 * and link them together.
528 *
529 * ng_make_node_common() returns with a generic node struct
530 * with a single reference for us.. we transfer it to the
531 * private structure.. when we free the private struct we must
532 * unref the node so it gets freed too.
533 */
534static int
535ng_pppoe_constructor(node_p node)
536{
537	priv_p privdata;
538
539AAA
540	/* Initialize private descriptor */
541	MALLOC(privdata, priv_p, sizeof(*privdata), M_NETGRAPH,
542	    M_NOWAIT | M_ZERO);
543	if (privdata == NULL)
544		return (ENOMEM);
545
546	/* Link structs together; this counts as our one reference to *nodep */
547	node->private = privdata;
548	privdata->node = node;
549	return (0);
550}
551
552/*
553 * Give our ok for a hook to be added...
554 * point the hook's private info to the hook structure.
555 *
556 * The following hook names are special:
557 *  Ethernet:  the hook that should be connected to a NIC.
558 *  debug:	copies of data sent out here  (when I write the code).
559 * All other hook names need only be unique. (the framework checks this).
560 */
561static int
562ng_pppoe_newhook(node_p node, hook_p hook, const char *name)
563{
564	const priv_p privp = node->private;
565	sessp sp;
566
567AAA
568	if (strcmp(name, NG_PPPOE_HOOK_ETHERNET) == 0) {
569		privp->ethernet_hook = hook;
570		hook->private = &privp->ethernet_hook;
571	} else if (strcmp(name, NG_PPPOE_HOOK_DEBUG) == 0) {
572		privp->debug_hook = hook;
573		hook->private = &privp->debug_hook;
574	} else {
575		/*
576		 * Any other unique name is OK.
577		 * The infrastructure has already checked that it's unique,
578		 * so just allocate it and hook it in.
579		 */
580		MALLOC(sp, sessp, sizeof(*sp), M_NETGRAPH, M_NOWAIT | M_ZERO);
581		if (sp == NULL) {
582				return (ENOMEM);
583		}
584
585		hook->private = sp;
586		sp->hook = hook;
587	}
588	return(0);
589}
590
591/*
592 * Get a netgraph control message.
593 * Check it is one we understand. If needed, send a response.
594 * We sometimes save the address for an async action later.
595 * Always free the message.
596 */
597static int
598ng_pppoe_rcvmsg(node_p node, item_p item, hook_p lasthook)
599{
600	priv_p privp = node->private;
601	struct ngpppoe_init_data *ourmsg = NULL;
602	struct ng_mesg *resp = NULL;
603	int error = 0;
604	hook_p hook = NULL;
605	sessp sp = NULL;
606	negp neg = NULL;
607	struct ng_mesg *msg;
608
609AAA
610	NGI_GET_MSG(item, msg);
611	/* Deal with message according to cookie and command */
612	switch (msg->header.typecookie) {
613	case NGM_PPPOE_COOKIE:
614		switch (msg->header.cmd) {
615		case NGM_PPPOE_CONNECT:
616		case NGM_PPPOE_LISTEN:
617		case NGM_PPPOE_OFFER:
618		case NGM_PPPOE_SERVICE:
619			ourmsg = (struct ngpppoe_init_data *)msg->data;
620			if (msg->header.arglen < sizeof(*ourmsg)) {
621				printf("pppoe: init data too small\n");
622				LEAVE(EMSGSIZE);
623			}
624			if (msg->header.arglen - sizeof(*ourmsg) >
625			    PPPOE_SERVICE_NAME_SIZE) {
626				printf("pppoe_rcvmsg: service name too big");
627				LEAVE(EMSGSIZE);
628			}
629			if (msg->header.arglen - sizeof(*ourmsg) <
630			    ourmsg->data_len) {
631				printf("pppoe: init data has bad length,"
632				    " %d should be %d\n", ourmsg->data_len,
633				    msg->header.arglen - sizeof (*ourmsg));
634				LEAVE(EMSGSIZE);
635			}
636
637			/* make sure strcmp will terminate safely */
638			ourmsg->hook[sizeof(ourmsg->hook) - 1] = '\0';
639
640			/* cycle through all known hooks */
641			LIST_FOREACH(hook, &node->hooks, hooks) {
642				if (hook->name
643				&& strcmp(hook->name, ourmsg->hook) == 0)
644					break;
645			}
646			if (hook == NULL) {
647				LEAVE(ENOENT);
648			}
649			if ((hook->private == &privp->debug_hook)
650			||  (hook->private == &privp->ethernet_hook)) {
651				LEAVE(EINVAL);
652			}
653			sp = hook->private;
654
655			/*
656			 * PPPOE_SERVICE advertisments are set up
657			 * on sessions that are in PRIMED state.
658			 */
659			if (msg->header.cmd == NGM_PPPOE_SERVICE) {
660				break;
661			}
662			if (sp->state |= PPPOE_SNONE) {
663				printf("pppoe: Session already active\n");
664				LEAVE(EISCONN);
665			}
666
667			/*
668			 * set up prototype header
669			 */
670			MALLOC(neg, negp, sizeof(*neg), M_NETGRAPH,
671			    M_NOWAIT | M_ZERO);
672
673			if (neg == NULL) {
674				printf("pppoe: Session out of memory\n");
675				LEAVE(ENOMEM);
676			}
677			MGETHDR(neg->m, M_DONTWAIT, MT_DATA);
678			if(neg->m == NULL) {
679				printf("pppoe: Session out of mbufs\n");
680				FREE(neg, M_NETGRAPH);
681				LEAVE(ENOBUFS);
682			}
683			neg->m->m_pkthdr.rcvif = NULL;
684			MCLGET(neg->m, M_DONTWAIT);
685			if ((neg->m->m_flags & M_EXT) == 0) {
686				printf("pppoe: Session out of mcls\n");
687				m_freem(neg->m);
688				FREE(neg, M_NETGRAPH);
689				LEAVE(ENOBUFS);
690			}
691			sp->neg = neg;
692			callout_handle_init( &neg->timeout_handle);
693			neg->m->m_len = sizeof(struct pppoe_full_hdr);
694			neg->pkt = mtod(neg->m, union packet*);
695			neg->pkt->pkt_header.eh = eh_prototype;
696			neg->pkt->pkt_header.ph.ver = 0x1;
697			neg->pkt->pkt_header.ph.type = 0x1;
698			neg->pkt->pkt_header.ph.sid = 0x0000;
699			neg->timeout = 0;
700
701			sp->creator = NGI_RETADDR(item);
702		}
703		switch (msg->header.cmd) {
704		case NGM_PPPOE_GET_STATUS:
705		    {
706			struct ngpppoestat *stats;
707
708			NG_MKRESPONSE(resp, msg, sizeof(*stats), M_NOWAIT);
709			if (!resp) {
710				LEAVE(ENOMEM);
711			}
712			stats = (struct ngpppoestat *) resp->data;
713			stats->packets_in = privp->packets_in;
714			stats->packets_out = privp->packets_out;
715			break;
716		    }
717		case NGM_PPPOE_CONNECT:
718			/*
719			 * Check the hook exists and is Uninitialised.
720			 * Send a PADI request, and start the timeout logic.
721			 * Store the originator of this message so we can send
722			 * a success of fail message to them later.
723			 * Move the session to SINIT
724			 * Set up the session to the correct state and
725			 * start it.
726			 */
727			neg->service.hdr.tag_type = PTT_SRV_NAME;
728			neg->service.hdr.tag_len =
729			    htons((u_int16_t)ourmsg->data_len);
730			if (ourmsg->data_len)
731				bcopy(ourmsg->data, neg->service.data,
732				    ourmsg->data_len);
733			neg->service_len = ourmsg->data_len;
734			pppoe_start(sp);
735			break;
736		case NGM_PPPOE_LISTEN:
737			/*
738			 * Check the hook exists and is Uninitialised.
739			 * Install the service matching string.
740			 * Store the originator of this message so we can send
741			 * a success of fail message to them later.
742			 * Move the hook to 'LISTENING'
743			 */
744			neg->service.hdr.tag_type = PTT_SRV_NAME;
745			neg->service.hdr.tag_len =
746			    htons((u_int16_t)ourmsg->data_len);
747
748			if (ourmsg->data_len)
749				bcopy(ourmsg->data, neg->service.data,
750				    ourmsg->data_len);
751			neg->service_len = ourmsg->data_len;
752			neg->pkt->pkt_header.ph.code = PADT_CODE;
753			/*
754			 * wait for PADI packet coming from ethernet
755			 */
756			sp->state = PPPOE_LISTENING;
757			break;
758		case NGM_PPPOE_OFFER:
759			/*
760			 * Check the hook exists and is Uninitialised.
761			 * Store the originator of this message so we can send
762			 * a success of fail message to them later.
763			 * Store the AC-Name given and go to PRIMED.
764			 */
765			neg->ac_name.hdr.tag_type = PTT_AC_NAME;
766			neg->ac_name.hdr.tag_len =
767			    htons((u_int16_t)ourmsg->data_len);
768			if (ourmsg->data_len)
769				bcopy(ourmsg->data, neg->ac_name.data,
770				    ourmsg->data_len);
771			neg->ac_name_len = ourmsg->data_len;
772			neg->pkt->pkt_header.ph.code = PADO_CODE;
773			/*
774			 * Wait for PADI packet coming from hook
775			 */
776			sp->state = PPPOE_PRIMED;
777			break;
778		case NGM_PPPOE_SERVICE:
779			/*
780			 * Check the session is primed.
781			 * for now just allow ONE service to be advertised.
782			 * If you do it twice you just overwrite.
783			 */
784			if (sp->state != PPPOE_PRIMED) {
785				printf("pppoe: Session not primed\n");
786				LEAVE(EISCONN);
787			}
788			neg->service.hdr.tag_type = PTT_SRV_NAME;
789			neg->service.hdr.tag_len =
790			    htons((u_int16_t)ourmsg->data_len);
791
792			if (ourmsg->data_len)
793				bcopy(ourmsg->data, neg->service.data,
794				    ourmsg->data_len);
795			neg->service_len = ourmsg->data_len;
796			break;
797		default:
798			LEAVE(EINVAL);
799		}
800		break;
801	default:
802		LEAVE(EINVAL);
803	}
804
805	/* Take care of synchronous response, if any */
806quit:
807	NG_RESPOND_MSG(error, node, item, resp);
808	/* Free the message and return */
809	NG_FREE_MSG(msg);
810	return(error);
811}
812
813/*
814 * Start a client into the first state. A separate function because
815 * it can be needed if the negotiation times out.
816 */
817static void
818pppoe_start(sessp sp)
819{
820	struct {
821		struct pppoe_tag hdr;
822		union	uniq	data;
823	} uniqtag;
824
825	/*
826	 * kick the state machine into starting up
827	 */
828AAA
829	sp->state = PPPOE_SINIT;
830	/* reset the packet header to broadcast */
831	sp->neg->pkt->pkt_header.eh = eh_prototype;
832	sp->neg->pkt->pkt_header.ph.code = PADI_CODE;
833	uniqtag.hdr.tag_type = PTT_HOST_UNIQ;
834	uniqtag.hdr.tag_len = htons((u_int16_t)sizeof(uniqtag.data));
835	uniqtag.data.pointer = sp;
836	init_tags(sp);
837	insert_tag(sp, &uniqtag.hdr);
838	insert_tag(sp, &sp->neg->service.hdr);
839	make_packet(sp);
840	sendpacket(sp);
841}
842
843/*
844 * Receive data, and do something with it.
845 * The caller will never free m or meta, so
846 * if we use up this data or abort we must free BOTH of these.
847 */
848static int
849ng_pppoe_rcvdata(hook_p hook, item_p item)
850{
851	node_p			node = hook->node;
852	const priv_p		privp = node->private;
853	sessp			sp = hook->private;
854	struct pppoe_full_hdr	*wh;
855	struct pppoe_hdr	*ph;
856	int			error = 0;
857	u_int16_t		session;
858	u_int16_t		length;
859	u_int8_t		code;
860	struct pppoe_tag	*utag = NULL, *tag = NULL;
861	hook_p 			sendhook;
862	struct {
863		struct pppoe_tag hdr;
864		union	uniq	data;
865	} uniqtag;
866	negp			neg = NULL;
867	struct mbuf		*m;
868
869AAA
870	NGI_GET_M(item, m);
871	if (hook->private == &privp->debug_hook) {
872		/*
873		 * Data from the debug hook gets sent without modification
874		 * straight to the ethernet.
875		 */
876		NG_FWD_DATA( error, item, privp->ethernet_hook);
877	 	privp->packets_out++;
878	} else if (hook->private == &privp->ethernet_hook) {
879		/*
880		 * Incoming data.
881		 * Dig out various fields from the packet.
882		 * use them to decide where to send it.
883		 */
884
885 		privp->packets_in++;
886		if( m->m_len < sizeof(*wh)) {
887			m = m_pullup(m, sizeof(*wh)); /* Checks length */
888			if (m == NULL) {
889				printf("couldn't m_pullup\n");
890				LEAVE(ENOBUFS);
891			}
892		}
893		wh = mtod(m, struct pppoe_full_hdr *);
894		length = ntohs(wh->ph.length);
895		switch(wh->eh.ether_type) {
896		case	ETHERTYPE_PPPOE_DISC:
897			/*
898			 * We need to try to make sure that the tag area
899			 * is contiguous, or we could wander off the end
900			 * of a buffer and make a mess.
901			 * (Linux wouldn't have this problem).
902			 */
903			if (m->m_pkthdr.len <= MHLEN) {
904				if( m->m_len < m->m_pkthdr.len) {
905					m = m_pullup(m, m->m_pkthdr.len);
906					if (m == NULL) {
907						printf("couldn't m_pullup\n");
908						LEAVE(ENOBUFS);
909					}
910				}
911			}
912			if (m->m_len != m->m_pkthdr.len) {
913				/*
914				 * It's not all in one piece.
915				 * We need to do extra work.
916				 * Put it into a cluster.
917				 */
918				struct mbuf *n;
919				n = m_dup(m, M_DONTWAIT);
920				m_freem(m);
921				m = n;
922				if (m) {
923					/* just check we got a cluster */
924					if (m->m_len != m->m_pkthdr.len) {
925						m_freem(m);
926						m = NULL;
927					}
928				}
929				if (m == NULL) {
930					printf("packet fragmented\n");
931					LEAVE(EMSGSIZE);
932				}
933			}
934			wh = mtod(m, struct pppoe_full_hdr *);
935			length = ntohs(wh->ph.length);
936			ph = &wh->ph;
937			session = ntohs(wh->ph.sid);
938			code = wh->ph.code;
939
940			switch(code) {
941			case	PADI_CODE:
942				/*
943				 * We are a server:
944				 * Look for a hook with the required service
945				 * and send the ENTIRE packet up there.
946				 * It should come back to a new hook in
947				 * PRIMED state. Look there for further
948				 * processing.
949				 */
950				tag = get_tag(ph, PTT_SRV_NAME);
951				if (tag == NULL) {
952					printf("no service tag\n");
953					LEAVE(ENETUNREACH);
954				}
955				sendhook = pppoe_match_svc(hook->node,
956			    		tag->tag_data, ntohs(tag->tag_len));
957				if (sendhook) {
958					NG_FWD_NEW_DATA(error, item,
959								sendhook, m);
960				} else {
961					printf("no such service\n");
962					LEAVE(ENETUNREACH);
963				}
964				break;
965			case	PADO_CODE:
966				/*
967				 * We are a client:
968				 * Use the host_uniq tag to find the
969				 * hook this is in response to.
970				 * Received #2, now send #3
971				 * For now simply accept the first we receive.
972				 */
973				utag = get_tag(ph, PTT_HOST_UNIQ);
974				if ((utag == NULL)
975				|| (ntohs(utag->tag_len) != sizeof(sp))) {
976					printf("no host unique field\n");
977					LEAVE(ENETUNREACH);
978				}
979
980				sendhook = pppoe_finduniq(node, utag);
981				if (sendhook == NULL) {
982					printf("no matching session\n");
983					LEAVE(ENETUNREACH);
984				}
985
986				/*
987				 * Check the session is in the right state.
988				 * It needs to be in PPPOE_SINIT.
989				 */
990				sp = sendhook->private;
991				if (sp->state != PPPOE_SINIT) {
992					printf("session in wrong state\n");
993					LEAVE(ENETUNREACH);
994				}
995				neg = sp->neg;
996				untimeout(pppoe_ticker, sendhook,
997				    neg->timeout_handle);
998
999				/*
1000				 * This is the first time we hear
1001				 * from the server, so note it's
1002				 * unicast address, replacing the
1003				 * broadcast address .
1004				 */
1005				bcopy(wh->eh.ether_shost,
1006					neg->pkt->pkt_header.eh.ether_dhost,
1007					ETHER_ADDR_LEN);
1008				neg->timeout = 0;
1009				neg->pkt->pkt_header.ph.code = PADR_CODE;
1010				init_tags(sp);
1011				insert_tag(sp, utag);      /* Host Unique */
1012				if ((tag = get_tag(ph, PTT_AC_COOKIE)))
1013					insert_tag(sp, tag); /* return cookie */
1014				if ((tag = get_tag(ph, PTT_AC_NAME)))
1015					insert_tag(sp, tag); /* return it */
1016				insert_tag(sp, &neg->service.hdr); /* Service */
1017				scan_tags(sp, ph);
1018				make_packet(sp);
1019				sp->state = PPPOE_SREQ;
1020				sendpacket(sp);
1021				break;
1022			case	PADR_CODE:
1023
1024				/*
1025				 * We are a server:
1026				 * Use the ac_cookie tag to find the
1027				 * hook this is in response to.
1028				 */
1029				utag = get_tag(ph, PTT_AC_COOKIE);
1030				if ((utag == NULL)
1031				|| (ntohs(utag->tag_len) != sizeof(sp))) {
1032					LEAVE(ENETUNREACH);
1033				}
1034
1035				sendhook = pppoe_finduniq(node, utag);
1036				if (sendhook == NULL) {
1037					LEAVE(ENETUNREACH);
1038				}
1039
1040				/*
1041				 * Check the session is in the right state.
1042				 * It needs to be in PPPOE_SOFFER
1043				 * or PPPOE_NEWCONNECTED. If the latter,
1044				 * then this is a retry by the client.
1045				 * so be nice, and resend.
1046				 */
1047				sp = sendhook->private;
1048				if (sp->state == PPPOE_NEWCONNECTED) {
1049					/*
1050					 * Whoa! drop back to resend that
1051					 * PADS packet.
1052					 * We should still have a copy of it.
1053					 */
1054					sp->state = PPPOE_SOFFER;
1055				}
1056				if (sp->state != PPPOE_SOFFER) {
1057					LEAVE (ENETUNREACH);
1058					break;
1059				}
1060				neg = sp->neg;
1061				untimeout(pppoe_ticker, sendhook,
1062				    neg->timeout_handle);
1063				neg->pkt->pkt_header.ph.code = PADS_CODE;
1064				if (sp->Session_ID == 0)
1065					neg->pkt->pkt_header.ph.sid =
1066					    htons(sp->Session_ID
1067						= get_new_sid(node));
1068				neg->timeout = 0;
1069				/*
1070				 * start working out the tags to respond with.
1071				 */
1072				init_tags(sp);
1073				insert_tag(sp, &neg->ac_name.hdr); /* AC_NAME */
1074				if ((tag = get_tag(ph, PTT_SRV_NAME)))
1075					insert_tag(sp, tag);/* return service */
1076				if ((tag = get_tag(ph, PTT_HOST_UNIQ)))
1077					insert_tag(sp, tag); /* return it */
1078				insert_tag(sp, utag);	/* ac_cookie */
1079				scan_tags(sp, ph);
1080				make_packet(sp);
1081				sp->state = PPPOE_NEWCONNECTED;
1082				sendpacket(sp);
1083				/*
1084				 * Having sent the last Negotiation header,
1085				 * Set up the stored packet header to
1086				 * be correct for the actual session.
1087				 * But keep the negotialtion stuff
1088				 * around in case we need to resend this last
1089				 * packet. We'll discard it when we move
1090				 * from NEWCONNECTED to CONNECTED
1091				 */
1092				sp->pkt_hdr = neg->pkt->pkt_header;
1093				sp->pkt_hdr.eh.ether_type
1094						= ETHERTYPE_PPPOE_SESS;
1095				sp->pkt_hdr.ph.code = 0;
1096				pppoe_send_event(sp, NGM_PPPOE_SUCCESS);
1097				break;
1098			case	PADS_CODE:
1099				/*
1100				 * We are a client:
1101				 * Use the host_uniq tag to find the
1102				 * hook this is in response to.
1103				 * take the session ID and store it away.
1104				 * Also make sure the pre-made header is
1105				 * correct and set us into Session mode.
1106				 */
1107				utag = get_tag(ph, PTT_HOST_UNIQ);
1108				if ((utag == NULL)
1109				|| (ntohs(utag->tag_len) != sizeof(sp))) {
1110					LEAVE (ENETUNREACH);
1111					break;
1112				}
1113				sendhook = pppoe_finduniq(node, utag);
1114				if (sendhook == NULL) {
1115					LEAVE(ENETUNREACH);
1116				}
1117
1118				/*
1119				 * Check the session is in the right state.
1120				 * It needs to be in PPPOE_SREQ.
1121				 */
1122				sp = sendhook->private;
1123				if (sp->state != PPPOE_SREQ) {
1124					LEAVE(ENETUNREACH);
1125				}
1126				neg = sp->neg;
1127				untimeout(pppoe_ticker, sendhook,
1128				    neg->timeout_handle);
1129				neg->pkt->pkt_header.ph.sid = wh->ph.sid;
1130				sp->Session_ID = ntohs(wh->ph.sid);
1131				neg->timeout = 0;
1132				sp->state = PPPOE_CONNECTED;
1133				/*
1134				 * Now we have gone to Connected mode,
1135				 * Free all resources needed for
1136				 * negotiation.
1137				 * Keep a copy of the header we will be using.
1138				 */
1139				sp->pkt_hdr = neg->pkt->pkt_header;
1140				sp->pkt_hdr.eh.ether_type
1141						= ETHERTYPE_PPPOE_SESS;
1142				sp->pkt_hdr.ph.code = 0;
1143				m_freem(neg->m);
1144				FREE(sp->neg, M_NETGRAPH);
1145				sp->neg = NULL;
1146				pppoe_send_event(sp, NGM_PPPOE_SUCCESS);
1147				break;
1148			case	PADT_CODE:
1149				/*
1150				 * Send a 'close' message to the controlling
1151				 * process (the one that set us up);
1152				 * And then tear everything down.
1153				 *
1154				 * Find matching peer/session combination.
1155				 */
1156				sendhook = pppoe_findsession(node, wh);
1157				if (sendhook == NULL) {
1158					LEAVE(ENETUNREACH);
1159				}
1160				/* send message to creator */
1161				/* close hook */
1162				if (sendhook) {
1163					ng_destroy_hook(sendhook);
1164				}
1165				break;
1166			default:
1167				LEAVE(EPFNOSUPPORT);
1168			}
1169			break;
1170		case	ETHERTYPE_PPPOE_SESS:
1171			/*
1172			 * find matching peer/session combination.
1173			 */
1174			sendhook = pppoe_findsession(node, wh);
1175			if (sendhook == NULL) {
1176				LEAVE (ENETUNREACH);
1177				break;
1178			}
1179			sp = sendhook->private;
1180			m_adj(m, sizeof(*wh));
1181			if (m->m_pkthdr.len < length) {
1182				/* Packet too short, dump it */
1183				LEAVE(EMSGSIZE);
1184			}
1185
1186			/* Also need to trim excess at the end */
1187			if (m->m_pkthdr.len > length) {
1188				m_adj(m, -((int)(m->m_pkthdr.len - length)));
1189			}
1190			if ( sp->state != PPPOE_CONNECTED) {
1191				if (sp->state == PPPOE_NEWCONNECTED) {
1192					sp->state = PPPOE_CONNECTED;
1193					/*
1194					 * Now we have gone to Connected mode,
1195					 * Free all resources needed for
1196					 * negotiation. Be paranoid about
1197					 * whether there may be a timeout.
1198					 */
1199					m_freem(sp->neg->m);
1200					untimeout(pppoe_ticker, sendhook,
1201				    		sp->neg->timeout_handle);
1202					FREE(sp->neg, M_NETGRAPH);
1203					sp->neg = NULL;
1204				} else {
1205					LEAVE (ENETUNREACH);
1206					break;
1207				}
1208			}
1209			NG_FWD_NEW_DATA( error, item, sendhook, m);
1210			break;
1211		default:
1212			LEAVE(EPFNOSUPPORT);
1213		}
1214	} else {
1215		/*
1216		 * 	Not ethernet or debug hook..
1217		 *
1218		 * The packet has come in on a normal hook.
1219		 * We need to find out what kind of hook,
1220		 * So we can decide how to handle it.
1221		 * Check the hook's state.
1222		 */
1223		sp = hook->private;
1224		switch (sp->state) {
1225		case	PPPOE_NEWCONNECTED:
1226		case	PPPOE_CONNECTED: {
1227			static const u_char addrctrl[] = { 0xff, 0x03 };
1228			struct pppoe_full_hdr *wh;
1229
1230			/*
1231			 * Remove PPP address and control fields, if any.
1232			 * For example, ng_ppp(4) always sends LCP packets
1233			 * with address and control fields as required by
1234			 * generic PPP. PPPoE is an exception to the rule.
1235			 */
1236			if (m->m_pkthdr.len >= 2) {
1237				if (m->m_len < 2 && !(m = m_pullup(m, 2)))
1238					LEAVE(ENOBUFS);
1239				if (bcmp(mtod(m, u_char *), addrctrl, 2) == 0)
1240					m_adj(m, 2);
1241			}
1242			/*
1243			 * Bang in a pre-made header, and set the length up
1244			 * to be correct. Then send it to the ethernet driver.
1245			 * But first correct the length.
1246			 */
1247			sp->pkt_hdr.ph.length = htons((short)(m->m_pkthdr.len));
1248			M_PREPEND(m, sizeof(*wh), M_DONTWAIT);
1249			if (m == NULL) {
1250				LEAVE(ENOBUFS);
1251			}
1252			wh = mtod(m, struct pppoe_full_hdr *);
1253			bcopy(&sp->pkt_hdr, wh, sizeof(*wh));
1254			NG_FWD_NEW_DATA( error, item, privp->ethernet_hook, m);
1255			privp->packets_out++;
1256			break;
1257			}
1258		case	PPPOE_PRIMED:
1259			/*
1260			 * A PADI packet is being returned by the application
1261			 * that has set up this hook. This indicates that it
1262			 * wants us to offer service.
1263			 */
1264			neg = sp->neg;
1265			if (m->m_len < sizeof(*wh)) {
1266				m = m_pullup(m, sizeof(*wh));
1267				if (m == NULL) {
1268					LEAVE(ENOBUFS);
1269				}
1270			}
1271			wh = mtod(m, struct pppoe_full_hdr *);
1272			ph = &wh->ph;
1273			session = ntohs(wh->ph.sid);
1274			length = ntohs(wh->ph.length);
1275			code = wh->ph.code;
1276			if ( code != PADI_CODE) {
1277				LEAVE(EINVAL);
1278			};
1279			untimeout(pppoe_ticker, hook,
1280				    neg->timeout_handle);
1281
1282			/*
1283			 * This is the first time we hear
1284			 * from the client, so note it's
1285			 * unicast address, replacing the
1286			 * broadcast address.
1287			 */
1288			bcopy(wh->eh.ether_shost,
1289				neg->pkt->pkt_header.eh.ether_dhost,
1290				ETHER_ADDR_LEN);
1291			sp->state = PPPOE_SOFFER;
1292			neg->timeout = 0;
1293			neg->pkt->pkt_header.ph.code = PADO_CODE;
1294
1295			/*
1296			 * start working out the tags to respond with.
1297			 */
1298			uniqtag.hdr.tag_type = PTT_AC_COOKIE;
1299			uniqtag.hdr.tag_len = htons((u_int16_t)sizeof(sp));
1300			uniqtag.data.pointer = sp;
1301			init_tags(sp);
1302			insert_tag(sp, &neg->ac_name.hdr); /* AC_NAME */
1303			if ((tag = get_tag(ph, PTT_SRV_NAME)))
1304				insert_tag(sp, tag);	  /* return service */
1305			/*
1306			 * If we have a NULL service request
1307			 * and have an extra service defined in this hook,
1308			 * then also add a tag for the extra service.
1309			 * XXX this is a hack. eventually we should be able
1310			 * to support advertising many services, not just one
1311			 */
1312			if (((tag == NULL) || (tag->tag_len == 0))
1313			&& (neg->service.hdr.tag_len != 0)) {
1314				insert_tag(sp, &neg->service.hdr); /* SERVICE */
1315			}
1316			if ((tag = get_tag(ph, PTT_HOST_UNIQ)))
1317				insert_tag(sp, tag); /* returned hostunique */
1318			insert_tag(sp, &uniqtag.hdr);
1319			scan_tags(sp, ph);
1320			make_packet(sp);
1321			sendpacket(sp);
1322			break;
1323
1324		/*
1325		 * Packets coming from the hook make no sense
1326		 * to sessions in these states. Throw them away.
1327		 */
1328		case	PPPOE_SINIT:
1329		case	PPPOE_SREQ:
1330		case	PPPOE_SOFFER:
1331		case	PPPOE_SNONE:
1332		case	PPPOE_LISTENING:
1333		case	PPPOE_DEAD:
1334		default:
1335			LEAVE(ENETUNREACH);
1336		}
1337	}
1338quit:
1339	NG_FREE_ITEM(item);
1340	NG_FREE_M(m);
1341	return error;
1342}
1343
1344/*
1345 * Do local shutdown processing..
1346 * If we are a persistant device, we might refuse to go away, and
1347 * we'd only remove our links and reset ourself.
1348 */
1349static int
1350ng_pppoe_shutdown(node_p node)
1351{
1352	const priv_p privdata = node->private;
1353
1354AAA
1355	node->flags |= NG_INVALID;
1356	node->private = NULL;
1357	ng_unref(privdata->node);
1358	FREE(privdata, M_NETGRAPH);
1359	return (0);
1360}
1361
1362/*
1363 * This is called once we've already connected a new hook to the other node.
1364 * It gives us a chance to balk at the last minute.
1365 */
1366static int
1367ng_pppoe_connect(hook_p hook)
1368{
1369	/* be really amiable and just say "YUP that's OK by me! " */
1370	return (0);
1371}
1372
1373/*
1374 * Hook disconnection
1375 *
1376 * Clean up all dangling links and information about the session/hook.
1377 * For this type, removal of the last link destroys the node
1378 */
1379static int
1380ng_pppoe_disconnect(hook_p hook)
1381{
1382	node_p node = hook->node;
1383	priv_p privp = node->private;
1384	sessp	sp;
1385	int 	hooks;
1386
1387AAA
1388	hooks = node->numhooks; /* this one already not counted */
1389	if (hook->private == &privp->debug_hook) {
1390		privp->debug_hook = NULL;
1391	} else if (hook->private == &privp->ethernet_hook) {
1392		privp->ethernet_hook = NULL;
1393		if ((node->flags & NG_INVALID) == 0)
1394			ng_rmnode_self(node);
1395	} else {
1396		sp = hook->private;
1397		if (sp->state != PPPOE_SNONE ) {
1398			pppoe_send_event(sp, NGM_PPPOE_CLOSE);
1399		}
1400		/*
1401		 * According to the spec, if we are connected,
1402		 * we should send a DISC packet if we are shutting down
1403		 * a session.
1404		 */
1405		if ((privp->ethernet_hook)
1406		&& ((sp->state == PPPOE_CONNECTED)
1407		 || (sp->state == PPPOE_NEWCONNECTED))) {
1408			struct mbuf *m;
1409			struct pppoe_full_hdr *wh;
1410			struct pppoe_tag *tag;
1411			int	msglen = strlen(SIGNOFF);
1412			int error = 0;
1413
1414			/* revert the stored header to DISC/PADT mode */
1415		 	wh = &sp->pkt_hdr;
1416			wh->ph.code = PADT_CODE;
1417			wh->eh.ether_type = ETHERTYPE_PPPOE_DISC;
1418
1419			/* generate a packet of that type */
1420			MGETHDR(m, M_DONTWAIT, MT_DATA);
1421			if(m == NULL)
1422				printf("pppoe: Session out of mbufs\n");
1423			else {
1424				m->m_pkthdr.rcvif = NULL;
1425				m->m_pkthdr.len = m->m_len = sizeof(*wh);
1426				bcopy((caddr_t)wh, mtod(m, caddr_t),
1427				    sizeof(*wh));
1428				/*
1429				 * Add a General error message and adjust
1430				 * sizes
1431				 */
1432				wh = mtod(m, struct pppoe_full_hdr *);
1433				tag = wh->ph.tag;
1434				tag->tag_type = PTT_GEN_ERR;
1435				tag->tag_len = htons((u_int16_t)msglen);
1436				strncpy(tag->tag_data, SIGNOFF, msglen);
1437				m->m_pkthdr.len = (m->m_len += sizeof(*tag) +
1438				    msglen);
1439				wh->ph.length = htons(sizeof(*tag) + msglen);
1440				NG_SEND_DATA_ONLY(error,
1441					privp->ethernet_hook, m);
1442			}
1443		}
1444		/*
1445		 * As long as we have somewhere to store the timeout handle,
1446		 * we may have a timeout pending.. get rid of it.
1447		 */
1448		if (sp->neg) {
1449			untimeout(pppoe_ticker, hook, sp->neg->timeout_handle);
1450			if (sp->neg->m)
1451				m_freem(sp->neg->m);
1452			FREE(sp->neg, M_NETGRAPH);
1453		}
1454		FREE(sp, M_NETGRAPH);
1455		hook->private = NULL;
1456		/* work out how many session hooks there are */
1457		/* Node goes away on last session hook removal */
1458		if (privp->ethernet_hook) hooks -= 1;
1459		if (privp->debug_hook) hooks -= 1;
1460	}
1461	if ((node->numhooks == 0)
1462	&& ((node->flags & NG_INVALID) == 0))
1463		ng_rmnode_self(node);
1464	return (0);
1465}
1466
1467/*
1468 * timeouts come here.
1469 */
1470static void
1471pppoe_ticker(void *arg)
1472{
1473	int s = splnet();
1474	hook_p hook = arg;
1475	sessp	sp = hook->private;
1476	negp	neg = sp->neg;
1477	int	error = 0;
1478	struct mbuf *m0 = NULL;
1479	priv_p privp = hook->node->private;
1480
1481AAA
1482	switch(sp->state) {
1483		/*
1484		 * resend the last packet, using an exponential backoff.
1485		 * After a period of time, stop growing the backoff,
1486		 * and either leave it, or revert to the start.
1487		 */
1488	case	PPPOE_SINIT:
1489	case	PPPOE_SREQ:
1490		/* timeouts on these produce resends */
1491		m0 = m_copypacket(sp->neg->m, M_DONTWAIT);
1492		NG_SEND_DATA_ONLY( error, privp->ethernet_hook, m0);
1493		neg->timeout_handle = timeout(pppoe_ticker,
1494					hook, neg->timeout * hz);
1495		if ((neg->timeout <<= 1) > PPPOE_TIMEOUT_LIMIT) {
1496			if (sp->state == PPPOE_SREQ) {
1497				/* revert to SINIT mode */
1498				pppoe_start(sp);
1499			} else {
1500				neg->timeout = PPPOE_TIMEOUT_LIMIT;
1501			}
1502		}
1503		break;
1504	case	PPPOE_PRIMED:
1505	case	PPPOE_SOFFER:
1506		/* a timeout on these says "give up" */
1507		ng_destroy_hook(hook);
1508		break;
1509	default:
1510		/* timeouts have no meaning in other states */
1511		printf("pppoe: unexpected timeout\n");
1512	}
1513	splx(s);
1514}
1515
1516
1517static void
1518sendpacket(sessp sp)
1519{
1520	int	error = 0;
1521	struct mbuf *m0 = NULL;
1522	hook_p hook = sp->hook;
1523	negp	neg = sp->neg;
1524	priv_p	privp = hook->node->private;
1525
1526AAA
1527	switch(sp->state) {
1528	case	PPPOE_LISTENING:
1529	case	PPPOE_DEAD:
1530	case	PPPOE_SNONE:
1531	case	PPPOE_CONNECTED:
1532		printf("pppoe: sendpacket: unexpected state\n");
1533		break;
1534
1535	case	PPPOE_NEWCONNECTED:
1536		/* send the PADS without a timeout - we're now connected */
1537		m0 = m_copypacket(sp->neg->m, M_DONTWAIT);
1538		NG_SEND_DATA_ONLY( error, privp->ethernet_hook, m0);
1539		break;
1540
1541	case	PPPOE_PRIMED:
1542		/* No packet to send, but set up the timeout */
1543		neg->timeout_handle = timeout(pppoe_ticker,
1544					hook, PPPOE_OFFER_TIMEOUT * hz);
1545		break;
1546
1547	case	PPPOE_SOFFER:
1548		/*
1549		 * send the offer but if they don't respond
1550		 * in PPPOE_OFFER_TIMEOUT seconds, forget about it.
1551		 */
1552		m0 = m_copypacket(sp->neg->m, M_DONTWAIT);
1553		NG_SEND_DATA_ONLY( error, privp->ethernet_hook, m0);
1554		neg->timeout_handle = timeout(pppoe_ticker,
1555					hook, PPPOE_OFFER_TIMEOUT * hz);
1556		break;
1557
1558	case	PPPOE_SINIT:
1559	case	PPPOE_SREQ:
1560		m0 = m_copypacket(sp->neg->m, M_DONTWAIT);
1561		NG_SEND_DATA_ONLY( error, privp->ethernet_hook, m0);
1562		neg->timeout_handle = timeout(pppoe_ticker, hook,
1563					(hz * PPPOE_INITIAL_TIMEOUT));
1564		neg->timeout = PPPOE_INITIAL_TIMEOUT * 2;
1565		break;
1566
1567	default:
1568		error = EINVAL;
1569		printf("pppoe: timeout: bad state\n");
1570	}
1571	/* return (error); */
1572}
1573
1574/*
1575 * Parse an incoming packet to see if any tags should be copied to the
1576 * output packet. Don't do any tags that have been handled in the main
1577 * state machine.
1578 */
1579static struct pppoe_tag*
1580scan_tags(sessp	sp, struct pppoe_hdr* ph)
1581{
1582	char *end = (char *)next_tag(ph);
1583	char *ptn;
1584	struct pppoe_tag *pt = &ph->tag[0];
1585	/*
1586	 * Keep processing tags while a tag header will still fit.
1587	 */
1588AAA
1589	while((char*)(pt + 1) <= end) {
1590		/*
1591		 * If the tag data would go past the end of the packet, abort.
1592		 */
1593		ptn = (((char *)(pt + 1)) + ntohs(pt->tag_len));
1594		if(ptn > end)
1595			return NULL;
1596
1597		switch (pt->tag_type) {
1598		case	PTT_RELAY_SID:
1599			insert_tag(sp, pt);
1600			break;
1601		case	PTT_EOL:
1602			return NULL;
1603		case	PTT_SRV_NAME:
1604		case	PTT_AC_NAME:
1605		case	PTT_HOST_UNIQ:
1606		case	PTT_AC_COOKIE:
1607		case	PTT_VENDOR:
1608		case	PTT_SRV_ERR:
1609		case	PTT_SYS_ERR:
1610		case	PTT_GEN_ERR:
1611			break;
1612		}
1613		pt = (struct pppoe_tag*)ptn;
1614	}
1615	return NULL;
1616}
1617
1618static	int
1619pppoe_send_event(sessp sp, enum cmd cmdid)
1620{
1621	int error;
1622	struct ng_mesg *msg;
1623	struct ngpppoe_sts *sts;
1624
1625AAA
1626	NG_MKMESSAGE(msg, NGM_PPPOE_COOKIE, cmdid,
1627			sizeof(struct ngpppoe_sts), M_NOWAIT);
1628	if (msg == NULL)
1629		return (ENOMEM);
1630	sts = (struct ngpppoe_sts *)msg->data;
1631	strncpy(sts->hook, sp->hook->name, NG_HOOKLEN + 1);
1632	NG_SEND_MSG_ID(error, sp->hook->node, msg, sp->creator, NULL);
1633	return (error);
1634}
1635