ng_lmi.c revision 52539
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 52539 1999-10-26 22:33:54Z julian $
40 * $Whistle: ng_lmi.c,v 1.35 1999/01/28 23:54:53 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 int	nglmi_constructor(node_p *node);
93static int	nglmi_rcvmsg(node_p node, struct ng_mesg *msg,
94		    const char *retaddr, struct ng_mesg **resp);
95static int	nglmi_rmnode(node_p node);
96static int	nglmi_newhook(node_p node, hook_p hook, const char *name);
97static int	nglmi_rcvdata(hook_p hook, struct mbuf *m, meta_p meta);
98static int	nglmi_disconnect(hook_p hook);	/* notify on disconnect */
99static int	nglmi_checkdata(hook_p hook, struct mbuf *m, meta_p meta);
100
101static struct ng_type typestruct = {
102	NG_VERSION,
103	NG_LMI_NODE_TYPE,
104	NULL,
105	nglmi_constructor,
106	nglmi_rcvmsg,
107	nglmi_rmnode,
108	nglmi_newhook,
109	NULL,
110	NULL,
111	nglmi_rcvdata,
112	nglmi_rcvdata,
113	nglmi_disconnect
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	/* Allocate a meta struct (and leave some slop for options to be
338	 * added by other modules). */
339	/* MALLOC(meta, meta_p, sizeof( struct ng_meta) + META_PAD,
340	 * M_NETGRAPH, M_NOWAIT); */
341	MALLOC(meta, meta_p, sizeof(*meta) + META_PAD, M_NETGRAPH, M_NOWAIT);
342	if (meta != NULL) {	/* if it failed, well, it was optional anyhow */
343		meta->used_len = (u_short) sizeof(struct ng_meta);
344		meta->allocated_len
345		    = (u_short) sizeof(struct ng_meta) + META_PAD;
346		meta->flags = 0;
347		meta->priority = NG_LMI_LMI_PRIORITY;
348		meta->discardability = -1;
349	}
350	m->m_data += 4;		/* leave some room for a header */
351	cptr = start = mtod(m, char *);
352	/* add in the header for an LMI inquiry. */
353	*cptr++ = 0x03;		/* UI frame */
354	if (GROUP4(sc))
355		*cptr++ = 0x09;	/* proto discriminator */
356	else
357		*cptr++ = 0x08;	/* proto discriminator */
358	*cptr++ = 0x00;		/* call reference */
359	*cptr++ = 0x75;		/* inquiry */
360
361	/* If we are Annex-D, there is this extra thing.. */
362	if (ANNEXD(sc))
363		*cptr++ = 0x95;	/* ??? */
364	/* Add a request type */
365	if (ANNEXA(sc))
366		*cptr++ = 0x51;	/* report type */
367	else
368		*cptr++ = 0x01;	/* report type */
369	*cptr++ = 0x01;		/* size = 1 */
370	if (full)
371		*cptr++ = 0x00;	/* full */
372	else
373		*cptr++ = 0x01;	/* partial */
374
375	/* Add a link verification IE */
376	if (ANNEXA(sc))
377		*cptr++ = 0x53;	/* verification IE */
378	else
379		*cptr++ = 0x03;	/* verification IE */
380	*cptr++ = 0x02;		/* 2 extra bytes */
381	*cptr++ = sc->local_seq;
382	*cptr++ = sc->remote_seq;
383	sc->seq_retries++;
384
385	/* Send it */
386	m->m_len = m->m_pkthdr.len = cptr - start;
387	NG_SEND_DATA(error, sc->lmi_channel, m, meta);
388
389	/* If we've been sending requests for long enough, and there has
390	 * been no response, then mark as DOWN, any DLCIs that are UP. */
391	if (sc->seq_retries == LMI_PATIENCE) {
392		int     count;
393
394		for (count = 0; count < MAXDLCI; count++)
395			if (sc->dlci_state[count] == DLCI_UP)
396				sc->dlci_state[count] = DLCI_DOWN;
397	}
398}
399
400/*
401 * State machine for LMI auto-detect. The transitions are ordered
402 * to try the more likely possibilities first.
403 */
404static void
405ngauto_state_machine(sc_p sc)
406{
407	if ((sc->poll_count <= 0) || (sc->poll_count > LMIPOLLSIZE)) {
408		/* time to change states in the auto probe machine */
409		/* capture wild values of poll_count while we are at it */
410		sc->poll_count = LMIPOLLSIZE;
411		sc->poll_state++;
412	}
413	switch (sc->poll_state) {
414	case 7:
415		log(LOG_WARNING, "nglmi: no response from exchange\n");
416	default:		/* capture bad states */
417		sc->poll_state = 1;
418	case 1:
419		sc->lmi_channel = sc->lmi_channel0;
420		SETLMITYPE(sc, SCF_ANNEX_D);
421		break;
422	case 2:
423		sc->lmi_channel = sc->lmi_channel1023;
424		SETLMITYPE(sc, SCF_ANNEX_D);
425		break;
426	case 3:
427		sc->lmi_channel = sc->lmi_channel0;
428		SETLMITYPE(sc, SCF_ANNEX_A);
429		break;
430	case 4:
431		sc->lmi_channel = sc->lmi_channel1023;
432		SETLMITYPE(sc, SCF_GROUP4);
433		break;
434	case 5:
435		sc->lmi_channel = sc->lmi_channel1023;
436		SETLMITYPE(sc, SCF_ANNEX_A);
437		break;
438	case 6:
439		sc->lmi_channel = sc->lmi_channel0;
440		SETLMITYPE(sc, SCF_GROUP4);
441		break;
442	}
443
444	/* send an inquirey encoded appropriatly */
445	nglmi_inquire(sc, 0);
446	sc->poll_count--;
447}
448
449/*
450 * Receive a netgraph control message.
451 */
452static int
453nglmi_rcvmsg(node_p node, struct ng_mesg *msg, const char *retaddr,
454	     struct ng_mesg **resp)
455{
456	int     error = 0;
457	sc_p    sc = node->private;
458
459	switch (msg->header.typecookie) {
460	case NGM_GENERIC_COOKIE:
461		switch (msg->header.cmd) {
462		case NGM_TEXT_STATUS:
463		    {
464			char   *arg;
465			int     pos, count;
466
467			NG_MKRESPONSE(*resp, msg, NG_TEXTRESPONSE, M_NOWAIT);
468			if (*resp == NULL) {
469				error = ENOMEM;
470				break;
471			}
472			arg = (*resp)->data;
473			pos = sprintf(arg, "protocol %s ", sc->protoname);
474			if (sc->flags & SCF_FIXED)
475				pos += sprintf(arg + pos, "fixed\n");
476			else if (sc->flags & SCF_AUTO)
477				pos += sprintf(arg + pos, "auto-detecting\n");
478			else
479				pos += sprintf(arg + pos, "auto on dlci %d\n",
480				    (sc->lmi_channel == sc->lmi_channel0) ?
481				    0 : 1023);
482			pos += sprintf(arg + pos,
483			    "keepalive period: %d seconds\n", sc->liv_rate);
484			pos += sprintf(arg + pos,
485			    "unacknowledged keepalives: %ld\n",
486			    sc->seq_retries);
487			for (count = 0;
488			     ((count <= MAXDLCI)
489			      && (pos < (NG_TEXTRESPONSE - 20)));
490			     count++) {
491				if (sc->dlci_state[count]) {
492					pos += sprintf(arg + pos,
493					       "dlci %d %s\n", count,
494					       (sc->dlci_state[count]
495					== DLCI_UP) ? "up" : "down");
496				}
497			}
498			(*resp)->header.arglen = pos + 1;
499			break;
500		    }
501		default:
502			error = EINVAL;
503			break;
504		}
505		break;
506	case NGM_LMI_COOKIE:
507		switch (msg->header.cmd) {
508		case NGM_LMI_GET_STATUS:
509		    {
510			struct nglmistat *stat;
511			int k;
512
513			NG_MKRESPONSE(*resp, msg, sizeof(*stat), M_NOWAIT);
514			if (!*resp) {
515				error = ENOMEM;
516				break;
517			}
518			stat = (struct nglmistat *) (*resp)->data;
519			strncpy(stat->proto,
520			     sc->protoname, sizeof(stat->proto) - 1);
521			strncpy(stat->hook,
522			      sc->protoname, sizeof(stat->hook) - 1);
523			stat->autod = !!(sc->flags & SCF_AUTO);
524			stat->fixed = !!(sc->flags & SCF_FIXED);
525			for (k = 0; k <= MAXDLCI; k++) {
526				switch (sc->dlci_state[k]) {
527				case DLCI_UP:
528					stat->up[k / 8] |= (1 << (k % 8));
529					/* fall through */
530				case DLCI_DOWN:
531					stat->seen[k / 8] |= (1 << (k % 8));
532					break;
533				}
534			}
535			break;
536		    }
537		default:
538			error = EINVAL;
539			break;
540		}
541		break;
542	default:
543		error = EINVAL;
544		break;
545	}
546	FREE(msg, M_NETGRAPH);
547	return (error);
548}
549
550#define STEPBY(stepsize)			\
551	do {					\
552		packetlen -= (stepsize);	\
553		data += (stepsize);		\
554	} while (0)
555
556/*
557 * receive data, and use it to update our status.
558 * Anything coming in on the debug port is discarded.
559 */
560static int
561nglmi_rcvdata(hook_p hook, struct mbuf *m, meta_p meta)
562{
563	sc_p    sc = hook->node->private;
564	u_char *data;
565	unsigned short dlci;
566	u_short packetlen;
567	int     resptype_seen = 0;
568	int     seq_seen = 0;
569
570	if (hook->private == NULL) {
571		goto drop;
572	}
573	packetlen = m->m_hdr.mh_len;
574
575	/* XXX what if it's more than 1 mbuf? */
576	if ((packetlen > MHLEN) && !(m->m_flags & M_EXT)) {
577		log(LOG_WARNING, "nglmi: packetlen (%d) too big\n", packetlen);
578		goto drop;
579	}
580	if (m->m_len < packetlen && (m = m_pullup(m, packetlen)) == NULL) {
581		log(LOG_WARNING,
582		    "nglmi: m_pullup failed for %d bytes\n", packetlen);
583		NG_FREE_META(meta);
584		return (0);
585	}
586	if (nglmi_checkdata(hook, m, meta) == 0)
587		return (0);
588
589	/* pass the first 4 bytes (already checked in the nglmi_checkdata()) */
590	data = mtod(m, u_char *);
591	STEPBY(4);
592
593	/* Now check if there is a 'locking shift'. This is only seen in
594	 * Annex D frames. don't bother checking, we already did that. Don't
595	 * increment immediatly as it might not be there. */
596	if (ANNEXD(sc))
597		STEPBY(1);
598
599	/* If we get this far we should consider that it is a legitimate
600	 * frame and we know what it is. */
601	if (sc->flags & SCF_AUTO) {
602		/* note the hook that this valid channel came from and drop
603		 * out of auto probe mode. */
604		if (ANNEXA(sc))
605			sc->protoname = NAME_ANNEXA;
606		else if (ANNEXD(sc))
607			sc->protoname = NAME_ANNEXD;
608		else if (GROUP4(sc))
609			sc->protoname = NAME_GROUP4;
610		else {
611			log(LOG_ERR, "nglmi: No known type\n");
612			goto drop;
613		}
614		sc->lmi_channel = hook;
615		sc->flags &= ~SCF_AUTO;
616		log(LOG_INFO, "nglmi: auto-detected %s LMI on DLCI %d\n",
617		    sc->protoname, hook == sc->lmi_channel0 ? 0 : 1023);
618	}
619
620	/* While there is more data in the status packet, keep processing
621	 * status items. First make sure there is enough data for the
622	 * segment descriptor's length field. */
623	while (packetlen >= 2) {
624		u_int   segtype = data[0];
625		u_int   segsize = data[1];
626
627		/* Now that we know how long it claims to be, make sure
628		 * there is enough data for the next seg. */
629		if (packetlen < segsize + 2)
630			break;
631		switch (segtype) {
632		case 0x01:
633		case 0x51:
634			if (resptype_seen) {
635				log(LOG_WARNING, "nglmi: dup MSGTYPE\n");
636				goto nextIE;
637			}
638			resptype_seen++;
639			/* The remote end tells us what kind of response
640			 * this is. Only expect a type 0 or 1. if we are a
641			 * full status, invalidate a few DLCIs just to see
642			 * that they are still ok. */
643			if (segsize != 1)
644				goto nextIE;
645			switch (data[2]) {
646			case 1:
647				/* partial status, do no extra processing */
648				break;
649			case 0:
650			    {
651				int     count = 0;
652				int     idx = sc->invalidx;
653
654				for (count = 0; count < 10; count++) {
655					if (idx > MAXDLCI)
656						idx = 0;
657					if (sc->dlci_state[idx] == DLCI_UP)
658						sc->dlci_state[idx] = DLCI_DOWN;
659					idx++;
660				}
661				sc->invalidx = idx;
662				/* we got and we wanted one. relax
663				 * now.. but don't reset to 0 if it
664				 * was unrequested. */
665				if (sc->livs > sc->liv_per_full)
666					sc->livs = 0;
667				break;
668			    }
669			}
670			break;
671		case 0x03:
672		case 0x53:
673			/* The remote tells us what it thinks the sequence
674			 * numbers are. If it's not size 2, it must be a
675			 * duplicate to have gotten this far, skip it. */
676			if (seq_seen != 0)	/* already seen seq numbers */
677				goto nextIE;
678			if (segsize != 2)
679				goto nextIE;
680			sc->remote_seq = data[2];
681			if (sc->local_seq == data[3]) {
682				sc->local_seq++;
683				sc->seq_retries = 0;
684				/* Note that all 3 Frame protocols seem to
685				 * not like 0 as a sequence number. */
686				if (sc->local_seq == 0)
687					sc->local_seq = 1;
688			}
689			break;
690		case 0x07:
691		case 0x57:
692			/* The remote tells us about a DLCI that it knows
693			 * about. There may be many of these in a single
694			 * status response */
695			switch (segsize) {
696			case 6:/* only on 'group of 4' */
697				dlci = ((u_short) data[2] & 0xff) << 8;
698				dlci |= (data[3] & 0xff);
699				if ((dlci < 1024) && (dlci > 0)) {
700				  /* XXX */
701				}
702				break;
703			case 3:
704				dlci = ((u_short) data[2] & 0x3f) << 4;
705				dlci |= ((data[3] & 0x78) >> 3);
706				if ((dlci < 1024) && (dlci > 0)) {
707					/* set up the bottom half of the
708					 * support for that dlci if it's not
709					 * already been done */
710					/* store this information somewhere */
711				}
712				break;
713			default:
714				goto nextIE;
715			}
716			if (sc->dlci_state[dlci] != DLCI_UP) {
717				/* bring new DLCI to life */
718				/* may do more here some day */
719				if (sc->dlci_state[dlci] != DLCI_DOWN)
720					log(LOG_INFO,
721					    "nglmi: DLCI %d became active\n",
722					    dlci);
723				sc->dlci_state[dlci] = DLCI_UP;
724			}
725			break;
726		}
727nextIE:
728		STEPBY(segsize + 2);
729	}
730	NG_FREE_DATA(m, meta);
731	return (0);
732
733drop:
734	NG_FREE_DATA(m, meta);
735	return (EINVAL);
736}
737
738/*
739 * Check that a packet is entirely kosha.
740 * return 1 of ok, and 0 if not.
741 * All data is discarded if a 0 is returned.
742 */
743static int
744nglmi_checkdata(hook_p hook, struct mbuf *m, meta_p meta)
745{
746	sc_p    sc = hook->node->private;
747	u_char *data;
748	u_short packetlen;
749	unsigned short dlci;
750	u_char  type;
751	u_char  nextbyte;
752	int     seq_seen = 0;
753	int     resptype_seen = 0;	/* 0 , 1 (partial) or 2 (full) */
754	int     highest_dlci = 0;
755
756	packetlen = m->m_hdr.mh_len;
757	data = mtod(m, u_char *);
758	if (*data != 0x03) {
759		log(LOG_WARNING, "nglmi: unexpected value in LMI(%d)\n", 1);
760		goto reject;
761	}
762	STEPBY(1);
763
764	/* look at the protocol ID */
765	nextbyte = *data;
766	if (sc->flags & SCF_AUTO) {
767		SETLMITYPE(sc, SCF_NOLMI);	/* start with a clean slate */
768		switch (nextbyte) {
769		case 0x8:
770			sc->protoID = 8;
771			break;
772		case 0x9:
773			SETLMITYPE(sc, SCF_GROUP4);
774			sc->protoID = 9;
775			break;
776		default:
777			log(LOG_WARNING, "nglmi: bad Protocol ID(%d)\n",
778			    (int) nextbyte);
779			goto reject;
780		}
781	} else {
782		if (nextbyte != sc->protoID) {
783			log(LOG_WARNING, "nglmi: unexpected Protocol ID(%d)\n",
784			    (int) nextbyte);
785			goto reject;
786		}
787	}
788	STEPBY(1);
789
790	/* check call reference (always null in non ISDN frame relay) */
791	if (*data != 0x00) {
792		log(LOG_WARNING, "nglmi: unexpected Call Reference (0x%x)\n",
793		    data[-1]);
794		goto reject;
795	}
796	STEPBY(1);
797
798	/* check message type */
799	switch ((type = *data)) {
800	case 0x75:		/* Status enquiry */
801		log(LOG_WARNING, "nglmi: unexpected message type(0x%x)\n",
802		    data[-1]);
803		goto reject;
804	case 0x7D:		/* Status message */
805		break;
806	default:
807		log(LOG_WARNING,
808		    "nglmi: unexpected msg type(0x%x) \n", (int) type);
809		goto reject;
810	}
811	STEPBY(1);
812
813	/* Now check if there is a 'locking shift'. This is only seen in
814	 * Annex D frames. Don't increment immediately as it might not be
815	 * there. */
816	nextbyte = *data;
817	if (sc->flags & SCF_AUTO) {
818		if (!(GROUP4(sc))) {
819			if (nextbyte == 0x95) {
820				SETLMITYPE(sc, SCF_ANNEX_D);
821				STEPBY(1);
822			} else
823				SETLMITYPE(sc, SCF_ANNEX_A);
824		} else if (nextbyte == 0x95) {
825			log(LOG_WARNING, "nglmi: locking shift seen in G4\n");
826			goto reject;
827		}
828	} else {
829		if (ANNEXD(sc)) {
830			if (*data == 0x95)
831				STEPBY(1);
832			else {
833				log(LOG_WARNING,
834				    "nglmi: locking shift missing\n");
835				goto reject;
836			}
837		} else if (*data == 0x95) {
838			log(LOG_WARNING, "nglmi: locking shift seen\n");
839			goto reject;
840		}
841	}
842
843	/* While there is more data in the status packet, keep processing
844	 * status items. First make sure there is enough data for the
845	 * segment descriptor's length field. */
846	while (packetlen >= 2) {
847		u_int   segtype = data[0];
848		u_int   segsize = data[1];
849
850		/* Now that we know how long it claims to be, make sure
851		 * there is enough data for the next seg. */
852		if (packetlen < (segsize + 2)) {
853			log(LOG_WARNING, "nglmi: IE longer than packet\n");
854			break;
855		}
856		switch (segtype) {
857		case 0x01:
858		case 0x51:
859			/* According to MCI's HP analyser, we should just
860			 * ignore if there is mor ethan one of these (?). */
861			if (resptype_seen) {
862				log(LOG_WARNING, "nglmi: dup MSGTYPE\n");
863				goto nextIE;
864			}
865			if (segsize != 1) {
866				log(LOG_WARNING, "nglmi: MSGTYPE wrong size\n");
867				goto reject;
868			}
869			/* The remote end tells us what kind of response
870			 * this is. Only expect a type 0 or 1. if it was a
871			 * full (type 0) check we just asked for a type
872			 * full. */
873			switch (data[2]) {
874			case 1:/* partial */
875				if (sc->livs > sc->liv_per_full) {
876					log(LOG_WARNING,
877					  "nglmi: LIV when FULL expected\n");
878					goto reject;	/* need full */
879				}
880				resptype_seen = 1;
881				break;
882			case 0:/* full */
883				/* Full response is always acceptable */
884				resptype_seen = 2;
885				break;
886			default:
887				log(LOG_WARNING,
888				 "nglmi: Unknown report type %d\n", data[2]);
889				goto reject;
890			}
891			break;
892		case 0x03:
893		case 0x53:
894			/* The remote tells us what it thinks the sequence
895			 * numbers are. I would have thought that there
896			 * needs to be one and only one of these, but MCI
897			 * want us to just ignore extras. (?) */
898			if (resptype_seen == 0) {
899				log(LOG_WARNING, "nglmi: no TYPE before SEQ\n");
900				goto reject;
901			}
902			if (seq_seen != 0)	/* already seen seq numbers */
903				goto nextIE;
904			if (segsize != 2) {
905				log(LOG_WARNING, "nglmi: bad SEQ sts size\n");
906				goto reject;
907			}
908			if (sc->local_seq != data[3]) {
909				log(LOG_WARNING, "nglmi: unexpected SEQ\n");
910				goto reject;
911			}
912			seq_seen = 1;
913			break;
914		case 0x07:
915		case 0x57:
916			/* The remote tells us about a DLCI that it knows
917			 * about. There may be many of these in a single
918			 * status response */
919			if (seq_seen != 1) {	/* already seen seq numbers? */
920				log(LOG_WARNING,
921				    "nglmi: No sequence before DLCI\n");
922				goto reject;
923			}
924			if (resptype_seen != 2) {	/* must be full */
925				log(LOG_WARNING,
926				    "nglmi: No resp type before DLCI\n");
927				goto reject;
928			}
929			if (GROUP4(sc)) {
930				if (segsize != 6) {
931					log(LOG_WARNING,
932					    "nglmi: wrong IE segsize\n");
933					goto reject;
934				}
935				dlci = ((u_short) data[2] & 0xff) << 8;
936				dlci |= (data[3] & 0xff);
937			} else {
938				if (segsize != 3) {
939					log(LOG_WARNING,
940					    "nglmi: DLCI headersize of %d"
941					    " not supported\n", segsize - 1);
942					goto reject;
943				}
944				dlci = ((u_short) data[2] & 0x3f) << 4;
945				dlci |= ((data[3] & 0x78) >> 3);
946			}
947			/* async can only have one of these */
948#if 0				/* async not yet accepted */
949			if (async && highest_dlci) {
950				log(LOG_WARNING,
951				    "nglmi: Async with > 1 DLCI\n");
952				goto reject;
953			}
954#endif
955			/* Annex D says these will always be Ascending, but
956			 * the HP test for G4 says we should accept
957			 * duplicates, so for now allow that. ( <= vs. < ) */
958#if 0
959			/* MCI tests want us to accept out of order for AnxD */
960			if ((!GROUP4(sc)) && (dlci < highest_dlci)) {
961				/* duplicate or mis-ordered dlci */
962				/* (spec says they will increase in number) */
963				log(LOG_WARNING, "nglmi: DLCI out of order\n");
964				goto reject;
965			}
966#endif
967			if (dlci > 1023) {
968				log(LOG_WARNING, "nglmi: DLCI out of range\n");
969				goto reject;
970			}
971			highest_dlci = dlci;
972			break;
973		default:
974			log(LOG_WARNING,
975			    "nglmi: unknown LMI segment type %d\n", segtype);
976		}
977nextIE:
978		STEPBY(segsize + 2);
979	}
980	if (packetlen != 0) {	/* partial junk at end? */
981		log(LOG_WARNING,
982		    "nglmi: %d bytes extra at end of packet\n", packetlen);
983		goto print;
984	}
985	if (resptype_seen == 0) {
986		log(LOG_WARNING, "nglmi: No response type seen\n");
987		goto reject;	/* had no response type */
988	}
989	if (seq_seen == 0) {
990		log(LOG_WARNING, "nglmi: No sequence numbers seen\n");
991		goto reject;	/* had no sequence numbers */
992	}
993	return (1);
994
995print:
996	{
997		int     i, j, k, pos;
998		char    buf[100];
999		int     loc;
1000		u_char *bp = mtod(m, u_char *);
1001
1002		k = i = 0;
1003		loc = (m->m_hdr.mh_len - packetlen);
1004		log(LOG_WARNING, "nglmi: error at location %d\n", loc);
1005		while (k < m->m_hdr.mh_len) {
1006			pos = 0;
1007			j = 0;
1008			while ((j++ < 16) && k < m->m_hdr.mh_len) {
1009				pos += sprintf(buf + pos, "%c%02x",
1010					       ((loc == k) ? '>' : ' '),
1011					       bp[k]);
1012				k++;
1013			}
1014			if (i == 0)
1015				log(LOG_WARNING, "nglmi: packet data:%s\n", buf);
1016			else
1017				log(LOG_WARNING, "%04d              :%s\n", k, buf);
1018			i++;
1019		}
1020	}
1021	return (1);
1022reject:
1023	{
1024		int     i, j, k, pos;
1025		char    buf[100];
1026		int     loc;
1027		u_char *bp = mtod(m, u_char *);
1028
1029		k = i = 0;
1030		loc = (m->m_hdr.mh_len - packetlen);
1031		log(LOG_WARNING, "nglmi: error at location %d\n", loc);
1032		while (k < m->m_hdr.mh_len) {
1033			pos = 0;
1034			j = 0;
1035			while ((j++ < 16) && k < m->m_hdr.mh_len) {
1036				pos += sprintf(buf + pos, "%c%02x",
1037					       ((loc == k) ? '>' : ' '),
1038					       bp[k]);
1039				k++;
1040			}
1041			if (i == 0)
1042				log(LOG_WARNING, "nglmi: packet data:%s\n", buf);
1043			else
1044				log(LOG_WARNING, "%04d              :%s\n", k, buf);
1045			i++;
1046		}
1047	}
1048	NG_FREE_DATA(m, meta);
1049	return (0);
1050}
1051
1052/*
1053 * Do local shutdown processing..
1054 * Cut any remaining links and free our local resources.
1055 */
1056static int
1057nglmi_rmnode(node_p node)
1058{
1059	const sc_p sc = node->private;
1060
1061	node->flags |= NG_INVALID;
1062	ng_cutlinks(node);
1063	ng_unname(node);
1064	node->private = NULL;
1065	ng_unref(sc->node);
1066	FREE(sc, M_NETGRAPH);
1067	return (0);
1068}
1069
1070/*
1071 * Hook disconnection
1072 * For this type, removal of any link except "debug" destroys the node.
1073 */
1074static int
1075nglmi_disconnect(hook_p hook)
1076{
1077	const sc_p sc = hook->node->private;
1078
1079	/* OK to remove debug hook(s) */
1080	if (hook->private == NULL)
1081		return (0);
1082
1083	/* Stop timer if it's currently active */
1084	if (sc->flags & SCF_CONNECTED)
1085		untimeout(LMI_ticker, sc, sc->handle);
1086
1087	/* Self-destruct */
1088	ng_rmnode(hook->node);
1089	return (0);
1090}
1091
1092