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