ng_lmi.c revision 59728
1
2/*
3 * ng_lmi.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@whistle.com>
38 *
39 * $FreeBSD: head/sys/netgraph/ng_lmi.c 59728 2000-04-28 17:09:00Z julian $
40 * $Whistle: ng_lmi.c,v 1.38 1999/11/01 09:24:52 julian Exp $
41 */
42
43/*
44 * This node performs the frame relay LMI protocol. It knows how
45 * to do ITU Annex A, ANSI Annex D, and "Group-of-Four" variants
46 * of the protocol.
47 *
48 * A specific protocol can be forced by connecting the corresponding
49 * hook to DLCI 0 or 1023 (as appropriate) of a frame relay link.
50 *
51 * Alternately, this node can do auto-detection of the LMI protocol
52 * by connecting hook "auto0" to DLCI 0 and "auto1023" to DLCI 1023.
53 */
54
55#include <sys/param.h>
56#include <sys/systm.h>
57#include <sys/errno.h>
58#include <sys/kernel.h>
59#include <sys/malloc.h>
60#include <sys/mbuf.h>
61#include <sys/syslog.h>
62#include <netgraph/ng_message.h>
63#include <netgraph/netgraph.h>
64#include <netgraph/ng_lmi.h>
65
66/*
67 * Human readable names for LMI
68 */
69#define NAME_ANNEXA	NG_LMI_HOOK_ANNEXA
70#define NAME_ANNEXD	NG_LMI_HOOK_ANNEXD
71#define NAME_GROUP4	NG_LMI_HOOK_GROUPOF4
72#define NAME_NONE	"None"
73
74#define MAX_DLCIS	128
75#define MAXDLCI		1023
76
77/*
78 * DLCI states
79 */
80#define DLCI_NULL	0
81#define DLCI_UP		1
82#define DLCI_DOWN	2
83
84/*
85 * Any received LMI frame should be at least this long
86 */
87#define LMI_MIN_LENGTH	8	/* XXX verify */
88
89/*
90 * Netgraph node methods and type descriptor
91 */
92static ng_constructor_t	nglmi_constructor;
93static ng_rcvmsg_t	nglmi_rcvmsg;
94static ng_shutdown_t	nglmi_rmnode;
95static ng_newhook_t	nglmi_newhook;
96static ng_rcvdata_t	nglmi_rcvdata;
97static ng_disconnect_t	nglmi_disconnect;
98static int	nglmi_checkdata(hook_p hook, struct mbuf *m, meta_p meta);
99
100static struct ng_type typestruct = {
101	NG_VERSION,
102	NG_LMI_NODE_TYPE,
103	NULL,
104	nglmi_constructor,
105	nglmi_rcvmsg,
106	nglmi_rmnode,
107	nglmi_newhook,
108	NULL,
109	NULL,
110	nglmi_rcvdata,
111	nglmi_rcvdata,
112	nglmi_disconnect,
113	NULL
114};
115NETGRAPH_INIT(lmi, &typestruct);
116
117/*
118 * Info and status per node
119 */
120struct nglmi_softc {
121	node_p  node;		/* netgraph node */
122	int     flags;		/* state */
123	int     poll_count;	/* the count of times for autolmi */
124	int     poll_state;	/* state of auto detect machine */
125	u_char  remote_seq;	/* sequence number the remote sent */
126	u_char  local_seq;	/* last sequence number we sent */
127	u_char  protoID;	/* 9 for group of 4, 8 otherwise */
128	u_long  seq_retries;	/* sent this how many time so far */
129	struct callout_handle handle;	/* see timeout(9) */
130	int     liv_per_full;
131	int     liv_rate;
132	int     livs;
133	int     need_full;
134	hook_p  lmi_channel;	/* whatever we ended up using */
135	hook_p  lmi_annexA;
136	hook_p  lmi_annexD;
137	hook_p  lmi_group4;
138	hook_p  lmi_channel0;	/* auto-detect on DLCI 0 */
139	hook_p  lmi_channel1023;/* auto-detect on DLCI 1023 */
140	char   *protoname;	/* cache protocol name */
141	u_char  dlci_state[MAXDLCI + 1];
142	int     invalidx;	/* next dlci's to invalidate */
143};
144typedef struct nglmi_softc *sc_p;
145
146/*
147 * Other internal functions
148 */
149static void	LMI_ticker(void *arg);
150static void	nglmi_startup_fixed(sc_p sc, hook_p hook);
151static void	nglmi_startup_auto(sc_p sc);
152static void	nglmi_startup(sc_p sc);
153static void	nglmi_inquire(sc_p sc, int full);
154static void	ngauto_state_machine(sc_p sc);
155
156/*
157 * Values for 'flags' field
158 * NB: the SCF_CONNECTED flag is set if and only if the timer is running.
159 */
160#define	SCF_CONNECTED	0x01	/* connected to something */
161#define	SCF_AUTO	0x02	/* we are auto-detecting */
162#define	SCF_FIXED	0x04	/* we are fixed from the start */
163
164#define	SCF_LMITYPE	0x18	/* mask for determining Annex mode */
165#define	SCF_NOLMI	0x00	/* no LMI type selected yet */
166#define	SCF_ANNEX_A	0x08	/* running annex A mode */
167#define	SCF_ANNEX_D	0x10	/* running annex D mode */
168#define	SCF_GROUP4	0x18	/* running group of 4 */
169
170#define SETLMITYPE(sc, annex)						\
171do {									\
172	(sc)->flags &= ~SCF_LMITYPE;					\
173	(sc)->flags |= (annex);						\
174} while (0)
175
176#define NOPROTO(sc) (((sc)->flags & SCF_LMITYPE) == SCF_NOLMI)
177#define ANNEXA(sc) (((sc)->flags & SCF_LMITYPE) == SCF_ANNEX_A)
178#define ANNEXD(sc) (((sc)->flags & SCF_LMITYPE) == SCF_ANNEX_D)
179#define GROUP4(sc) (((sc)->flags & SCF_LMITYPE) == SCF_GROUP4)
180
181#define LMIPOLLSIZE	3
182#define LMI_PATIENCE	8	/* declare all DLCI DOWN after N LMI failures */
183
184/*
185 * Node constructor
186 */
187static int
188nglmi_constructor(node_p *nodep)
189{
190	sc_p sc;
191	int error = 0;
192
193	MALLOC(sc, sc_p, sizeof(*sc), M_NETGRAPH, M_WAITOK);
194	if (sc == NULL)
195		return (ENOMEM);
196	bzero(sc, sizeof(*sc));
197
198	callout_handle_init(&sc->handle);
199	if ((error = ng_make_node_common(&typestruct, nodep))) {
200		FREE(sc, M_NETGRAPH);
201		return (error);
202	}
203	(*nodep)->private = sc;
204	sc->protoname = NAME_NONE;
205	sc->node = *nodep;
206	sc->liv_per_full = NG_LMI_SEQ_PER_FULL;	/* make this dynamic */
207	sc->liv_rate = NG_LMI_KEEPALIVE_RATE;
208	return (0);
209}
210
211/*
212 * The LMI channel has a private pointer which is the same as the
213 * node private pointer. The debug channel has a NULL private pointer.
214 */
215static int
216nglmi_newhook(node_p node, hook_p hook, const char *name)
217{
218	sc_p sc = node->private;
219
220	if (strcmp(name, NG_LMI_HOOK_DEBUG) == 0) {
221		hook->private = NULL;
222		return (0);
223	}
224	if (sc->flags & SCF_CONNECTED) {
225		/* already connected, return an error */
226		return (EINVAL);
227	}
228	if (strcmp(name, NG_LMI_HOOK_ANNEXA) == 0) {
229		sc->lmi_annexA = hook;
230		hook->private = node->private;
231		sc->protoID = 8;
232		SETLMITYPE(sc, SCF_ANNEX_A);
233		sc->protoname = NAME_ANNEXA;
234		nglmi_startup_fixed(sc, hook);
235	} else if (strcmp(name, NG_LMI_HOOK_ANNEXD) == 0) {
236		sc->lmi_annexD = hook;
237		hook->private = node->private;
238		sc->protoID = 8;
239		SETLMITYPE(sc, SCF_ANNEX_D);
240		sc->protoname = NAME_ANNEXD;
241		nglmi_startup_fixed(sc, hook);
242	} else if (strcmp(name, NG_LMI_HOOK_GROUPOF4) == 0) {
243		sc->lmi_group4 = hook;
244		hook->private = node->private;
245		sc->protoID = 9;
246		SETLMITYPE(sc, SCF_GROUP4);
247		sc->protoname = NAME_GROUP4;
248		nglmi_startup_fixed(sc, hook);
249	} else if (strcmp(name, NG_LMI_HOOK_AUTO0) == 0) {
250		/* Note this, and if B is already installed, we're complete */
251		sc->lmi_channel0 = hook;
252		sc->protoname = NAME_NONE;
253		hook->private = node->private;
254		if (sc->lmi_channel1023)
255			nglmi_startup_auto(sc);
256	} else if (strcmp(name, NG_LMI_HOOK_AUTO1023) == 0) {
257		/* Note this, and if A is already installed, we're complete */
258		sc->lmi_channel1023 = hook;
259		sc->protoname = NAME_NONE;
260		hook->private = node->private;
261		if (sc->lmi_channel0)
262			nglmi_startup_auto(sc);
263	} else
264		return (EINVAL);		/* unknown hook */
265	return (0);
266}
267
268/*
269 * We have just attached to a live (we hope) node.
270 * Fire out a LMI inquiry, and then start up the timers.
271 */
272static void
273LMI_ticker(void *arg)
274{
275	sc_p sc = arg;
276	int s = splnet();
277
278	if (sc->flags & SCF_AUTO) {
279		ngauto_state_machine(sc);
280		sc->handle = timeout(LMI_ticker, sc, NG_LMI_POLL_RATE * hz);
281	} else {
282		if (sc->livs++ >= sc->liv_per_full) {
283			nglmi_inquire(sc, 1);
284			/* sc->livs = 0; *//* do this when we get the answer! */
285		} else {
286			nglmi_inquire(sc, 0);
287		}
288		sc->handle = timeout(LMI_ticker, sc, sc->liv_rate * hz);
289	}
290	splx(s);
291}
292
293static void
294nglmi_startup_fixed(sc_p sc, hook_p hook)
295{
296	sc->flags |= (SCF_FIXED | SCF_CONNECTED);
297	sc->lmi_channel = hook;
298	nglmi_startup(sc);
299}
300
301static void
302nglmi_startup_auto(sc_p sc)
303{
304	sc->flags |= (SCF_AUTO | SCF_CONNECTED);
305	sc->poll_state = 0;	/* reset state machine */
306	sc->poll_count = 0;
307	nglmi_startup(sc);
308}
309
310static void
311nglmi_startup(sc_p sc)
312{
313	sc->remote_seq = 0;
314	sc->local_seq = 1;
315	sc->seq_retries = 0;
316	sc->livs = sc->liv_per_full - 1;
317	/* start off the ticker in 1 sec */
318	sc->handle = timeout(LMI_ticker, sc, hz);
319}
320
321#define META_PAD 16
322static void
323nglmi_inquire(sc_p sc, int full)
324{
325	struct mbuf *m;
326	char   *cptr, *start;
327	int     error;
328	meta_p  meta = NULL;
329
330	if (sc->lmi_channel == NULL)
331		return;
332	MGETHDR(m, M_DONTWAIT, MT_DATA);
333	if (m == NULL) {
334		log(LOG_ERR, "nglmi: unable to start up LMI processing\n");
335		return;
336	}
337	m->m_pkthdr.rcvif = NULL;
338	/* Allocate a meta struct (and leave some slop for options to be
339	 * added by other modules). */
340	/* MALLOC(meta, meta_p, sizeof( struct ng_meta) + META_PAD,
341	 * M_NETGRAPH, M_NOWAIT); */
342	MALLOC(meta, meta_p, sizeof(*meta) + META_PAD, M_NETGRAPH, M_NOWAIT);
343	if (meta != NULL) {	/* if it failed, well, it was optional anyhow */
344		meta->used_len = (u_short) sizeof(struct ng_meta);
345		meta->allocated_len
346		    = (u_short) sizeof(struct ng_meta) + META_PAD;
347		meta->flags = 0;
348		meta->priority = NG_LMI_LMI_PRIORITY;
349		meta->discardability = -1;
350	}
351	m->m_data += 4;		/* leave some room for a header */
352	cptr = start = mtod(m, char *);
353	/* add in the header for an LMI inquiry. */
354	*cptr++ = 0x03;		/* UI frame */
355	if (GROUP4(sc))
356		*cptr++ = 0x09;	/* proto discriminator */
357	else
358		*cptr++ = 0x08;	/* proto discriminator */
359	*cptr++ = 0x00;		/* call reference */
360	*cptr++ = 0x75;		/* inquiry */
361
362	/* If we are Annex-D, there is this extra thing.. */
363	if (ANNEXD(sc))
364		*cptr++ = 0x95;	/* ??? */
365	/* Add a request type */
366	if (ANNEXA(sc))
367		*cptr++ = 0x51;	/* report type */
368	else
369		*cptr++ = 0x01;	/* report type */
370	*cptr++ = 0x01;		/* size = 1 */
371	if (full)
372		*cptr++ = 0x00;	/* full */
373	else
374		*cptr++ = 0x01;	/* partial */
375
376	/* Add a link verification IE */
377	if (ANNEXA(sc))
378		*cptr++ = 0x53;	/* verification IE */
379	else
380		*cptr++ = 0x03;	/* verification IE */
381	*cptr++ = 0x02;		/* 2 extra bytes */
382	*cptr++ = sc->local_seq;
383	*cptr++ = sc->remote_seq;
384	sc->seq_retries++;
385
386	/* Send it */
387	m->m_len = m->m_pkthdr.len = cptr - start;
388	NG_SEND_DATA(error, sc->lmi_channel, m, meta);
389
390	/* If we've been sending requests for long enough, and there has
391	 * been no response, then mark as DOWN, any DLCIs that are UP. */
392	if (sc->seq_retries == LMI_PATIENCE) {
393		int     count;
394
395		for (count = 0; count < MAXDLCI; count++)
396			if (sc->dlci_state[count] == DLCI_UP)
397				sc->dlci_state[count] = DLCI_DOWN;
398	}
399}
400
401/*
402 * State machine for LMI auto-detect. The transitions are ordered
403 * to try the more likely possibilities first.
404 */
405static void
406ngauto_state_machine(sc_p sc)
407{
408	if ((sc->poll_count <= 0) || (sc->poll_count > LMIPOLLSIZE)) {
409		/* time to change states in the auto probe machine */
410		/* capture wild values of poll_count while we are at it */
411		sc->poll_count = LMIPOLLSIZE;
412		sc->poll_state++;
413	}
414	switch (sc->poll_state) {
415	case 7:
416		log(LOG_WARNING, "nglmi: no response from exchange\n");
417	default:		/* capture bad states */
418		sc->poll_state = 1;
419	case 1:
420		sc->lmi_channel = sc->lmi_channel0;
421		SETLMITYPE(sc, SCF_ANNEX_D);
422		break;
423	case 2:
424		sc->lmi_channel = sc->lmi_channel1023;
425		SETLMITYPE(sc, SCF_ANNEX_D);
426		break;
427	case 3:
428		sc->lmi_channel = sc->lmi_channel0;
429		SETLMITYPE(sc, SCF_ANNEX_A);
430		break;
431	case 4:
432		sc->lmi_channel = sc->lmi_channel1023;
433		SETLMITYPE(sc, SCF_GROUP4);
434		break;
435	case 5:
436		sc->lmi_channel = sc->lmi_channel1023;
437		SETLMITYPE(sc, SCF_ANNEX_A);
438		break;
439	case 6:
440		sc->lmi_channel = sc->lmi_channel0;
441		SETLMITYPE(sc, SCF_GROUP4);
442		break;
443	}
444
445	/* send an inquirey encoded appropriatly */
446	nglmi_inquire(sc, 0);
447	sc->poll_count--;
448}
449
450/*
451 * Receive a netgraph control message.
452 */
453static int
454nglmi_rcvmsg(node_p node, struct ng_mesg *msg, const char *retaddr,
455	     struct ng_mesg **resp, hook_p lasthook)
456{
457	int     error = 0;
458	sc_p    sc = node->private;
459
460	switch (msg->header.typecookie) {
461	case NGM_GENERIC_COOKIE:
462		switch (msg->header.cmd) {
463		case NGM_TEXT_STATUS:
464		    {
465			char   *arg;
466			int     pos, count;
467
468			NG_MKRESPONSE(*resp, msg, NG_TEXTRESPONSE, M_NOWAIT);
469			if (*resp == NULL) {
470				error = ENOMEM;
471				break;
472			}
473			arg = (*resp)->data;
474			pos = sprintf(arg, "protocol %s ", sc->protoname);
475			if (sc->flags & SCF_FIXED)
476				pos += sprintf(arg + pos, "fixed\n");
477			else if (sc->flags & SCF_AUTO)
478				pos += sprintf(arg + pos, "auto-detecting\n");
479			else
480				pos += sprintf(arg + pos, "auto on dlci %d\n",
481				    (sc->lmi_channel == sc->lmi_channel0) ?
482				    0 : 1023);
483			pos += sprintf(arg + pos,
484			    "keepalive period: %d seconds\n", sc->liv_rate);
485			pos += sprintf(arg + pos,
486			    "unacknowledged keepalives: %ld\n",
487			    sc->seq_retries);
488			for (count = 0;
489			     ((count <= MAXDLCI)
490			      && (pos < (NG_TEXTRESPONSE - 20)));
491			     count++) {
492				if (sc->dlci_state[count]) {
493					pos += sprintf(arg + pos,
494					       "dlci %d %s\n", count,
495					       (sc->dlci_state[count]
496					== DLCI_UP) ? "up" : "down");
497				}
498			}
499			(*resp)->header.arglen = pos + 1;
500			break;
501		    }
502		default:
503			error = EINVAL;
504			break;
505		}
506		break;
507	case NGM_LMI_COOKIE:
508		switch (msg->header.cmd) {
509		case NGM_LMI_GET_STATUS:
510		    {
511			struct nglmistat *stat;
512			int k;
513
514			NG_MKRESPONSE(*resp, msg, sizeof(*stat), M_NOWAIT);
515			if (!*resp) {
516				error = ENOMEM;
517				break;
518			}
519			stat = (struct nglmistat *) (*resp)->data;
520			strncpy(stat->proto,
521			     sc->protoname, sizeof(stat->proto) - 1);
522			strncpy(stat->hook,
523			      sc->protoname, sizeof(stat->hook) - 1);
524			stat->autod = !!(sc->flags & SCF_AUTO);
525			stat->fixed = !!(sc->flags & SCF_FIXED);
526			for (k = 0; k <= MAXDLCI; k++) {
527				switch (sc->dlci_state[k]) {
528				case DLCI_UP:
529					stat->up[k / 8] |= (1 << (k % 8));
530					/* fall through */
531				case DLCI_DOWN:
532					stat->seen[k / 8] |= (1 << (k % 8));
533					break;
534				}
535			}
536			break;
537		    }
538		default:
539			error = EINVAL;
540			break;
541		}
542		break;
543	default:
544		error = EINVAL;
545		break;
546	}
547	FREE(msg, M_NETGRAPH);
548	return (error);
549}
550
551#define STEPBY(stepsize)			\
552	do {					\
553		packetlen -= (stepsize);	\
554		data += (stepsize);		\
555	} while (0)
556
557/*
558 * receive data, and use it to update our status.
559 * Anything coming in on the debug port is discarded.
560 */
561static int
562nglmi_rcvdata(hook_p hook, struct mbuf *m, meta_p meta,
563		struct mbuf **ret_m, meta_p *ret_meta)
564{
565	sc_p    sc = hook->node->private;
566	u_char *data;
567	unsigned short dlci;
568	u_short packetlen;
569	int     resptype_seen = 0;
570	int     seq_seen = 0;
571
572	if (hook->private == NULL) {
573		goto drop;
574	}
575	packetlen = m->m_hdr.mh_len;
576
577	/* XXX what if it's more than 1 mbuf? */
578	if ((packetlen > MHLEN) && !(m->m_flags & M_EXT)) {
579		log(LOG_WARNING, "nglmi: packetlen (%d) too big\n", packetlen);
580		goto drop;
581	}
582	if (m->m_len < packetlen && (m = m_pullup(m, packetlen)) == NULL) {
583		log(LOG_WARNING,
584		    "nglmi: m_pullup failed for %d bytes\n", packetlen);
585		NG_FREE_META(meta);
586		return (0);
587	}
588	if (nglmi_checkdata(hook, m, meta) == 0)
589		return (0);
590
591	/* pass the first 4 bytes (already checked in the nglmi_checkdata()) */
592	data = mtod(m, u_char *);
593	STEPBY(4);
594
595	/* Now check if there is a 'locking shift'. This is only seen in
596	 * Annex D frames. don't bother checking, we already did that. Don't
597	 * increment immediatly as it might not be there. */
598	if (ANNEXD(sc))
599		STEPBY(1);
600
601	/* If we get this far we should consider that it is a legitimate
602	 * frame and we know what it is. */
603	if (sc->flags & SCF_AUTO) {
604		/* note the hook that this valid channel came from and drop
605		 * out of auto probe mode. */
606		if (ANNEXA(sc))
607			sc->protoname = NAME_ANNEXA;
608		else if (ANNEXD(sc))
609			sc->protoname = NAME_ANNEXD;
610		else if (GROUP4(sc))
611			sc->protoname = NAME_GROUP4;
612		else {
613			log(LOG_ERR, "nglmi: No known type\n");
614			goto drop;
615		}
616		sc->lmi_channel = hook;
617		sc->flags &= ~SCF_AUTO;
618		log(LOG_INFO, "nglmi: auto-detected %s LMI on DLCI %d\n",
619		    sc->protoname, hook == sc->lmi_channel0 ? 0 : 1023);
620	}
621
622	/* While there is more data in the status packet, keep processing
623	 * status items. First make sure there is enough data for the
624	 * segment descriptor's length field. */
625	while (packetlen >= 2) {
626		u_int   segtype = data[0];
627		u_int   segsize = data[1];
628
629		/* Now that we know how long it claims to be, make sure
630		 * there is enough data for the next seg. */
631		if (packetlen < segsize + 2)
632			break;
633		switch (segtype) {
634		case 0x01:
635		case 0x51:
636			if (resptype_seen) {
637				log(LOG_WARNING, "nglmi: dup MSGTYPE\n");
638				goto nextIE;
639			}
640			resptype_seen++;
641			/* The remote end tells us what kind of response
642			 * this is. Only expect a type 0 or 1. if we are a
643			 * full status, invalidate a few DLCIs just to see
644			 * that they are still ok. */
645			if (segsize != 1)
646				goto nextIE;
647			switch (data[2]) {
648			case 1:
649				/* partial status, do no extra processing */
650				break;
651			case 0:
652			    {
653				int     count = 0;
654				int     idx = sc->invalidx;
655
656				for (count = 0; count < 10; count++) {
657					if (idx > MAXDLCI)
658						idx = 0;
659					if (sc->dlci_state[idx] == DLCI_UP)
660						sc->dlci_state[idx] = DLCI_DOWN;
661					idx++;
662				}
663				sc->invalidx = idx;
664				/* we got and we wanted one. relax
665				 * now.. but don't reset to 0 if it
666				 * was unrequested. */
667				if (sc->livs > sc->liv_per_full)
668					sc->livs = 0;
669				break;
670			    }
671			}
672			break;
673		case 0x03:
674		case 0x53:
675			/* The remote tells us what it thinks the sequence
676			 * numbers are. If it's not size 2, it must be a
677			 * duplicate to have gotten this far, skip it. */
678			if (seq_seen != 0)	/* already seen seq numbers */
679				goto nextIE;
680			if (segsize != 2)
681				goto nextIE;
682			sc->remote_seq = data[2];
683			if (sc->local_seq == data[3]) {
684				sc->local_seq++;
685				sc->seq_retries = 0;
686				/* Note that all 3 Frame protocols seem to
687				 * not like 0 as a sequence number. */
688				if (sc->local_seq == 0)
689					sc->local_seq = 1;
690			}
691			break;
692		case 0x07:
693		case 0x57:
694			/* The remote tells us about a DLCI that it knows
695			 * about. There may be many of these in a single
696			 * status response */
697			switch (segsize) {
698			case 6:/* only on 'group of 4' */
699				dlci = ((u_short) data[2] & 0xff) << 8;
700				dlci |= (data[3] & 0xff);
701				if ((dlci < 1024) && (dlci > 0)) {
702				  /* XXX */
703				}
704				break;
705			case 3:
706				dlci = ((u_short) data[2] & 0x3f) << 4;
707				dlci |= ((data[3] & 0x78) >> 3);
708				if ((dlci < 1024) && (dlci > 0)) {
709					/* set up the bottom half of the
710					 * support for that dlci if it's not
711					 * already been done */
712					/* store this information somewhere */
713				}
714				break;
715			default:
716				goto nextIE;
717			}
718			if (sc->dlci_state[dlci] != DLCI_UP) {
719				/* bring new DLCI to life */
720				/* may do more here some day */
721				if (sc->dlci_state[dlci] != DLCI_DOWN)
722					log(LOG_INFO,
723					    "nglmi: DLCI %d became active\n",
724					    dlci);
725				sc->dlci_state[dlci] = DLCI_UP;
726			}
727			break;
728		}
729nextIE:
730		STEPBY(segsize + 2);
731	}
732	NG_FREE_DATA(m, meta);
733	return (0);
734
735drop:
736	NG_FREE_DATA(m, meta);
737	return (EINVAL);
738}
739
740/*
741 * Check that a packet is entirely kosha.
742 * return 1 of ok, and 0 if not.
743 * All data is discarded if a 0 is returned.
744 */
745static int
746nglmi_checkdata(hook_p hook, struct mbuf *m, meta_p meta)
747{
748	sc_p    sc = hook->node->private;
749	u_char *data;
750	u_short packetlen;
751	unsigned short dlci;
752	u_char  type;
753	u_char  nextbyte;
754	int     seq_seen = 0;
755	int     resptype_seen = 0;	/* 0 , 1 (partial) or 2 (full) */
756	int     highest_dlci = 0;
757
758	packetlen = m->m_hdr.mh_len;
759	data = mtod(m, u_char *);
760	if (*data != 0x03) {
761		log(LOG_WARNING, "nglmi: unexpected value in LMI(%d)\n", 1);
762		goto reject;
763	}
764	STEPBY(1);
765
766	/* look at the protocol ID */
767	nextbyte = *data;
768	if (sc->flags & SCF_AUTO) {
769		SETLMITYPE(sc, SCF_NOLMI);	/* start with a clean slate */
770		switch (nextbyte) {
771		case 0x8:
772			sc->protoID = 8;
773			break;
774		case 0x9:
775			SETLMITYPE(sc, SCF_GROUP4);
776			sc->protoID = 9;
777			break;
778		default:
779			log(LOG_WARNING, "nglmi: bad Protocol ID(%d)\n",
780			    (int) nextbyte);
781			goto reject;
782		}
783	} else {
784		if (nextbyte != sc->protoID) {
785			log(LOG_WARNING, "nglmi: unexpected Protocol ID(%d)\n",
786			    (int) nextbyte);
787			goto reject;
788		}
789	}
790	STEPBY(1);
791
792	/* check call reference (always null in non ISDN frame relay) */
793	if (*data != 0x00) {
794		log(LOG_WARNING, "nglmi: unexpected Call Reference (0x%x)\n",
795		    data[-1]);
796		goto reject;
797	}
798	STEPBY(1);
799
800	/* check message type */
801	switch ((type = *data)) {
802	case 0x75:		/* Status enquiry */
803		log(LOG_WARNING, "nglmi: unexpected message type(0x%x)\n",
804		    data[-1]);
805		goto reject;
806	case 0x7D:		/* Status message */
807		break;
808	default:
809		log(LOG_WARNING,
810		    "nglmi: unexpected msg type(0x%x) \n", (int) type);
811		goto reject;
812	}
813	STEPBY(1);
814
815	/* Now check if there is a 'locking shift'. This is only seen in
816	 * Annex D frames. Don't increment immediately as it might not be
817	 * there. */
818	nextbyte = *data;
819	if (sc->flags & SCF_AUTO) {
820		if (!(GROUP4(sc))) {
821			if (nextbyte == 0x95) {
822				SETLMITYPE(sc, SCF_ANNEX_D);
823				STEPBY(1);
824			} else
825				SETLMITYPE(sc, SCF_ANNEX_A);
826		} else if (nextbyte == 0x95) {
827			log(LOG_WARNING, "nglmi: locking shift seen in G4\n");
828			goto reject;
829		}
830	} else {
831		if (ANNEXD(sc)) {
832			if (*data == 0x95)
833				STEPBY(1);
834			else {
835				log(LOG_WARNING,
836				    "nglmi: locking shift missing\n");
837				goto reject;
838			}
839		} else if (*data == 0x95) {
840			log(LOG_WARNING, "nglmi: locking shift seen\n");
841			goto reject;
842		}
843	}
844
845	/* While there is more data in the status packet, keep processing
846	 * status items. First make sure there is enough data for the
847	 * segment descriptor's length field. */
848	while (packetlen >= 2) {
849		u_int   segtype = data[0];
850		u_int   segsize = data[1];
851
852		/* Now that we know how long it claims to be, make sure
853		 * there is enough data for the next seg. */
854		if (packetlen < (segsize + 2)) {
855			log(LOG_WARNING, "nglmi: IE longer than packet\n");
856			break;
857		}
858		switch (segtype) {
859		case 0x01:
860		case 0x51:
861			/* According to MCI's HP analyser, we should just
862			 * ignore if there is mor ethan one of these (?). */
863			if (resptype_seen) {
864				log(LOG_WARNING, "nglmi: dup MSGTYPE\n");
865				goto nextIE;
866			}
867			if (segsize != 1) {
868				log(LOG_WARNING, "nglmi: MSGTYPE wrong size\n");
869				goto reject;
870			}
871			/* The remote end tells us what kind of response
872			 * this is. Only expect a type 0 or 1. if it was a
873			 * full (type 0) check we just asked for a type
874			 * full. */
875			switch (data[2]) {
876			case 1:/* partial */
877				if (sc->livs > sc->liv_per_full) {
878					log(LOG_WARNING,
879					  "nglmi: LIV when FULL expected\n");
880					goto reject;	/* need full */
881				}
882				resptype_seen = 1;
883				break;
884			case 0:/* full */
885				/* Full response is always acceptable */
886				resptype_seen = 2;
887				break;
888			default:
889				log(LOG_WARNING,
890				 "nglmi: Unknown report type %d\n", data[2]);
891				goto reject;
892			}
893			break;
894		case 0x03:
895		case 0x53:
896			/* The remote tells us what it thinks the sequence
897			 * numbers are. I would have thought that there
898			 * needs to be one and only one of these, but MCI
899			 * want us to just ignore extras. (?) */
900			if (resptype_seen == 0) {
901				log(LOG_WARNING, "nglmi: no TYPE before SEQ\n");
902				goto reject;
903			}
904			if (seq_seen != 0)	/* already seen seq numbers */
905				goto nextIE;
906			if (segsize != 2) {
907				log(LOG_WARNING, "nglmi: bad SEQ sts size\n");
908				goto reject;
909			}
910			if (sc->local_seq != data[3]) {
911				log(LOG_WARNING, "nglmi: unexpected SEQ\n");
912				goto reject;
913			}
914			seq_seen = 1;
915			break;
916		case 0x07:
917		case 0x57:
918			/* The remote tells us about a DLCI that it knows
919			 * about. There may be many of these in a single
920			 * status response */
921			if (seq_seen != 1) {	/* already seen seq numbers? */
922				log(LOG_WARNING,
923				    "nglmi: No sequence before DLCI\n");
924				goto reject;
925			}
926			if (resptype_seen != 2) {	/* must be full */
927				log(LOG_WARNING,
928				    "nglmi: No resp type before DLCI\n");
929				goto reject;
930			}
931			if (GROUP4(sc)) {
932				if (segsize != 6) {
933					log(LOG_WARNING,
934					    "nglmi: wrong IE segsize\n");
935					goto reject;
936				}
937				dlci = ((u_short) data[2] & 0xff) << 8;
938				dlci |= (data[3] & 0xff);
939			} else {
940				if (segsize != 3) {
941					log(LOG_WARNING,
942					    "nglmi: DLCI headersize of %d"
943					    " not supported\n", segsize - 1);
944					goto reject;
945				}
946				dlci = ((u_short) data[2] & 0x3f) << 4;
947				dlci |= ((data[3] & 0x78) >> 3);
948			}
949			/* async can only have one of these */
950#if 0				/* async not yet accepted */
951			if (async && highest_dlci) {
952				log(LOG_WARNING,
953				    "nglmi: Async with > 1 DLCI\n");
954				goto reject;
955			}
956#endif
957			/* Annex D says these will always be Ascending, but
958			 * the HP test for G4 says we should accept
959			 * duplicates, so for now allow that. ( <= vs. < ) */
960#if 0
961			/* MCI tests want us to accept out of order for AnxD */
962			if ((!GROUP4(sc)) && (dlci < highest_dlci)) {
963				/* duplicate or mis-ordered dlci */
964				/* (spec says they will increase in number) */
965				log(LOG_WARNING, "nglmi: DLCI out of order\n");
966				goto reject;
967			}
968#endif
969			if (dlci > 1023) {
970				log(LOG_WARNING, "nglmi: DLCI out of range\n");
971				goto reject;
972			}
973			highest_dlci = dlci;
974			break;
975		default:
976			log(LOG_WARNING,
977			    "nglmi: unknown LMI segment type %d\n", segtype);
978		}
979nextIE:
980		STEPBY(segsize + 2);
981	}
982	if (packetlen != 0) {	/* partial junk at end? */
983		log(LOG_WARNING,
984		    "nglmi: %d bytes extra at end of packet\n", packetlen);
985		goto print;
986	}
987	if (resptype_seen == 0) {
988		log(LOG_WARNING, "nglmi: No response type seen\n");
989		goto reject;	/* had no response type */
990	}
991	if (seq_seen == 0) {
992		log(LOG_WARNING, "nglmi: No sequence numbers seen\n");
993		goto reject;	/* had no sequence numbers */
994	}
995	return (1);
996
997print:
998	{
999		int     i, j, k, pos;
1000		char    buf[100];
1001		int     loc;
1002		u_char *bp = mtod(m, u_char *);
1003
1004		k = i = 0;
1005		loc = (m->m_hdr.mh_len - packetlen);
1006		log(LOG_WARNING, "nglmi: error at location %d\n", loc);
1007		while (k < m->m_hdr.mh_len) {
1008			pos = 0;
1009			j = 0;
1010			while ((j++ < 16) && k < m->m_hdr.mh_len) {
1011				pos += sprintf(buf + pos, "%c%02x",
1012					       ((loc == k) ? '>' : ' '),
1013					       bp[k]);
1014				k++;
1015			}
1016			if (i == 0)
1017				log(LOG_WARNING, "nglmi: packet data:%s\n", buf);
1018			else
1019				log(LOG_WARNING, "%04d              :%s\n", k, buf);
1020			i++;
1021		}
1022	}
1023	return (1);
1024reject:
1025	{
1026		int     i, j, k, pos;
1027		char    buf[100];
1028		int     loc;
1029		u_char *bp = mtod(m, u_char *);
1030
1031		k = i = 0;
1032		loc = (m->m_hdr.mh_len - packetlen);
1033		log(LOG_WARNING, "nglmi: error at location %d\n", loc);
1034		while (k < m->m_hdr.mh_len) {
1035			pos = 0;
1036			j = 0;
1037			while ((j++ < 16) && k < m->m_hdr.mh_len) {
1038				pos += sprintf(buf + pos, "%c%02x",
1039					       ((loc == k) ? '>' : ' '),
1040					       bp[k]);
1041				k++;
1042			}
1043			if (i == 0)
1044				log(LOG_WARNING, "nglmi: packet data:%s\n", buf);
1045			else
1046				log(LOG_WARNING, "%04d              :%s\n", k, buf);
1047			i++;
1048		}
1049	}
1050	NG_FREE_DATA(m, meta);
1051	return (0);
1052}
1053
1054/*
1055 * Do local shutdown processing..
1056 * Cut any remaining links and free our local resources.
1057 */
1058static int
1059nglmi_rmnode(node_p node)
1060{
1061	const sc_p sc = node->private;
1062
1063	node->flags |= NG_INVALID;
1064	ng_cutlinks(node);
1065	ng_unname(node);
1066	node->private = NULL;
1067	ng_unref(sc->node);
1068	FREE(sc, M_NETGRAPH);
1069	return (0);
1070}
1071
1072/*
1073 * Hook disconnection
1074 * For this type, removal of any link except "debug" destroys the node.
1075 */
1076static int
1077nglmi_disconnect(hook_p hook)
1078{
1079	const sc_p sc = hook->node->private;
1080
1081	/* OK to remove debug hook(s) */
1082	if (hook->private == NULL)
1083		return (0);
1084
1085	/* Stop timer if it's currently active */
1086	if (sc->flags & SCF_CONNECTED)
1087		untimeout(LMI_ticker, sc, sc->handle);
1088
1089	/* Self-destruct */
1090	ng_rmnode(hook->node);
1091	return (0);
1092}
1093
1094