ng_lmi.c revision 68876
1135446Strhodes
2193149Sdougb/*
3135446Strhodes * ng_lmi.c
4135446Strhodes *
5193149Sdougb * Copyright (c) 1996-1999 Whistle Communications, Inc.
6135446Strhodes * All rights reserved.
7135446Strhodes *
8135446Strhodes * Subject to the following obligations and disclaimer of warranty, use and
9135446Strhodes * redistribution of this software, in source or object code forms, with or
10135446Strhodes * without modifications are expressly permitted by Whistle Communications;
11135446Strhodes * provided, however, that:
12135446Strhodes * 1. Any and all reproductions of the source or object code must include the
13135446Strhodes *    copyright notice above and the following disclaimer of warranties; and
14135446Strhodes * 2. No rights are granted, in any manner or form, to use Whistle
15135446Strhodes *    Communications, Inc. trademarks, including the mark "WHISTLE
16135446Strhodes *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17135446Strhodes *    such appears in the above copyright notice or in the software.
18234010Sdougb *
19135446Strhodes * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20170222Sdougb * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21170222Sdougb * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22135446Strhodes * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23135446Strhodes * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24135446Strhodes * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25135446Strhodes * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26135446Strhodes * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27135446Strhodes * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28135446Strhodes * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29135446Strhodes * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30135446Strhodes * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31135446Strhodes * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32135446Strhodes * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33135446Strhodes * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34135446Strhodes * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35135446Strhodes * OF SUCH DAMAGE.
36135446Strhodes *
37135446Strhodes * Author: Julian Elischer <julian@freebsd.org>
38135446Strhodes *
39135446Strhodes * $FreeBSD: head/sys/netgraph/ng_lmi.c 68876 2000-11-18 15:17:43Z dwmalone $
40135446Strhodes * $Whistle: ng_lmi.c,v 1.38 1999/11/01 09:24:52 julian Exp $
41135446Strhodes */
42135446Strhodes
43135446Strhodes/*
44135446Strhodes * This node performs the frame relay LMI protocol. It knows how
45135446Strhodes * to do ITU Annex A, ANSI Annex D, and "Group-of-Four" variants
46135446Strhodes * of the protocol.
47135446Strhodes *
48135446Strhodes * A specific protocol can be forced by connecting the corresponding
49135446Strhodes * hook to DLCI 0 or 1023 (as appropriate) of a frame relay link.
50135446Strhodes *
51135446Strhodes * Alternately, this node can do auto-detection of the LMI protocol
52135446Strhodes * by connecting hook "auto0" to DLCI 0 and "auto1023" to DLCI 1023.
53135446Strhodes */
54135446Strhodes
55135446Strhodes#include <sys/param.h>
56135446Strhodes#include <sys/systm.h>
57135446Strhodes#include <sys/errno.h>
58135446Strhodes#include <sys/kernel.h>
59135446Strhodes#include <sys/malloc.h>
60135446Strhodes#include <sys/mbuf.h>
61135446Strhodes#include <sys/syslog.h>
62135446Strhodes#include <netgraph/ng_message.h>
63135446Strhodes#include <netgraph/netgraph.h>
64135446Strhodes#include <netgraph/ng_lmi.h>
65135446Strhodes
66135446Strhodes/*
67135446Strhodes * Human readable names for LMI
68135446Strhodes */
69135446Strhodes#define NAME_ANNEXA	NG_LMI_HOOK_ANNEXA
70135446Strhodes#define NAME_ANNEXD	NG_LMI_HOOK_ANNEXD
71135446Strhodes#define NAME_GROUP4	NG_LMI_HOOK_GROUPOF4
72135446Strhodes#define NAME_NONE	"None"
73135446Strhodes
74135446Strhodes#define MAX_DLCIS	128
75135446Strhodes#define MAXDLCI		1023
76135446Strhodes
77135446Strhodes/*
78135446Strhodes * DLCI states
79135446Strhodes */
80135446Strhodes#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_NOWAIT | M_ZERO);
194	if (sc == NULL)
195		return (ENOMEM);
196
197	callout_handle_init(&sc->handle);
198	if ((error = ng_make_node_common(&typestruct, nodep))) {
199		FREE(sc, M_NETGRAPH);
200		return (error);
201	}
202	(*nodep)->private = sc;
203	sc->protoname = NAME_NONE;
204	sc->node = *nodep;
205	sc->liv_per_full = NG_LMI_SEQ_PER_FULL;	/* make this dynamic */
206	sc->liv_rate = NG_LMI_KEEPALIVE_RATE;
207	return (0);
208}
209
210/*
211 * The LMI channel has a private pointer which is the same as the
212 * node private pointer. The debug channel has a NULL private pointer.
213 */
214static int
215nglmi_newhook(node_p node, hook_p hook, const char *name)
216{
217	sc_p sc = node->private;
218
219	if (strcmp(name, NG_LMI_HOOK_DEBUG) == 0) {
220		hook->private = NULL;
221		return (0);
222	}
223	if (sc->flags & SCF_CONNECTED) {
224		/* already connected, return an error */
225		return (EINVAL);
226	}
227	if (strcmp(name, NG_LMI_HOOK_ANNEXA) == 0) {
228		sc->lmi_annexA = hook;
229		hook->private = node->private;
230		sc->protoID = 8;
231		SETLMITYPE(sc, SCF_ANNEX_A);
232		sc->protoname = NAME_ANNEXA;
233		nglmi_startup_fixed(sc, hook);
234	} else if (strcmp(name, NG_LMI_HOOK_ANNEXD) == 0) {
235		sc->lmi_annexD = hook;
236		hook->private = node->private;
237		sc->protoID = 8;
238		SETLMITYPE(sc, SCF_ANNEX_D);
239		sc->protoname = NAME_ANNEXD;
240		nglmi_startup_fixed(sc, hook);
241	} else if (strcmp(name, NG_LMI_HOOK_GROUPOF4) == 0) {
242		sc->lmi_group4 = hook;
243		hook->private = node->private;
244		sc->protoID = 9;
245		SETLMITYPE(sc, SCF_GROUP4);
246		sc->protoname = NAME_GROUP4;
247		nglmi_startup_fixed(sc, hook);
248	} else if (strcmp(name, NG_LMI_HOOK_AUTO0) == 0) {
249		/* Note this, and if B is already installed, we're complete */
250		sc->lmi_channel0 = hook;
251		sc->protoname = NAME_NONE;
252		hook->private = node->private;
253		if (sc->lmi_channel1023)
254			nglmi_startup_auto(sc);
255	} else if (strcmp(name, NG_LMI_HOOK_AUTO1023) == 0) {
256		/* Note this, and if A is already installed, we're complete */
257		sc->lmi_channel1023 = hook;
258		sc->protoname = NAME_NONE;
259		hook->private = node->private;
260		if (sc->lmi_channel0)
261			nglmi_startup_auto(sc);
262	} else
263		return (EINVAL);		/* unknown hook */
264	return (0);
265}
266
267/*
268 * We have just attached to a live (we hope) node.
269 * Fire out a LMI inquiry, and then start up the timers.
270 */
271static void
272LMI_ticker(void *arg)
273{
274	sc_p sc = arg;
275	int s = splnet();
276
277	if (sc->flags & SCF_AUTO) {
278		ngauto_state_machine(sc);
279		sc->handle = timeout(LMI_ticker, sc, NG_LMI_POLL_RATE * hz);
280	} else {
281		if (sc->livs++ >= sc->liv_per_full) {
282			nglmi_inquire(sc, 1);
283			/* sc->livs = 0; *//* do this when we get the answer! */
284		} else {
285			nglmi_inquire(sc, 0);
286		}
287		sc->handle = timeout(LMI_ticker, sc, sc->liv_rate * hz);
288	}
289	splx(s);
290}
291
292static void
293nglmi_startup_fixed(sc_p sc, hook_p hook)
294{
295	sc->flags |= (SCF_FIXED | SCF_CONNECTED);
296	sc->lmi_channel = hook;
297	nglmi_startup(sc);
298}
299
300static void
301nglmi_startup_auto(sc_p sc)
302{
303	sc->flags |= (SCF_AUTO | SCF_CONNECTED);
304	sc->poll_state = 0;	/* reset state machine */
305	sc->poll_count = 0;
306	nglmi_startup(sc);
307}
308
309static void
310nglmi_startup(sc_p sc)
311{
312	sc->remote_seq = 0;
313	sc->local_seq = 1;
314	sc->seq_retries = 0;
315	sc->livs = sc->liv_per_full - 1;
316	/* start off the ticker in 1 sec */
317	sc->handle = timeout(LMI_ticker, sc, hz);
318}
319
320#define META_PAD 16
321static void
322nglmi_inquire(sc_p sc, int full)
323{
324	struct mbuf *m;
325	char   *cptr, *start;
326	int     error;
327	meta_p  meta = NULL;
328
329	if (sc->lmi_channel == NULL)
330		return;
331	MGETHDR(m, M_DONTWAIT, MT_DATA);
332	if (m == NULL) {
333		log(LOG_ERR, "nglmi: unable to start up LMI processing\n");
334		return;
335	}
336	m->m_pkthdr.rcvif = NULL;
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, hook_p lasthook)
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		struct mbuf **ret_m, meta_p *ret_meta)
563{
564	sc_p    sc = hook->node->private;
565	u_char *data;
566	unsigned short dlci;
567	u_short packetlen;
568	int     resptype_seen = 0;
569	int     seq_seen = 0;
570
571	if (hook->private == NULL) {
572		goto drop;
573	}
574	packetlen = m->m_hdr.mh_len;
575
576	/* XXX what if it's more than 1 mbuf? */
577	if ((packetlen > MHLEN) && !(m->m_flags & M_EXT)) {
578		log(LOG_WARNING, "nglmi: packetlen (%d) too big\n", packetlen);
579		goto drop;
580	}
581	if (m->m_len < packetlen && (m = m_pullup(m, packetlen)) == NULL) {
582		log(LOG_WARNING,
583		    "nglmi: m_pullup failed for %d bytes\n", packetlen);
584		NG_FREE_META(meta);
585		return (0);
586	}
587	if (nglmi_checkdata(hook, m, meta) == 0)
588		return (0);
589
590	/* pass the first 4 bytes (already checked in the nglmi_checkdata()) */
591	data = mtod(m, u_char *);
592	STEPBY(4);
593
594	/* Now check if there is a 'locking shift'. This is only seen in
595	 * Annex D frames. don't bother checking, we already did that. Don't
596	 * increment immediatly as it might not be there. */
597	if (ANNEXD(sc))
598		STEPBY(1);
599
600	/* If we get this far we should consider that it is a legitimate
601	 * frame and we know what it is. */
602	if (sc->flags & SCF_AUTO) {
603		/* note the hook that this valid channel came from and drop
604		 * out of auto probe mode. */
605		if (ANNEXA(sc))
606			sc->protoname = NAME_ANNEXA;
607		else if (ANNEXD(sc))
608			sc->protoname = NAME_ANNEXD;
609		else if (GROUP4(sc))
610			sc->protoname = NAME_GROUP4;
611		else {
612			log(LOG_ERR, "nglmi: No known type\n");
613			goto drop;
614		}
615		sc->lmi_channel = hook;
616		sc->flags &= ~SCF_AUTO;
617		log(LOG_INFO, "nglmi: auto-detected %s LMI on DLCI %d\n",
618		    sc->protoname, hook == sc->lmi_channel0 ? 0 : 1023);
619	}
620
621	/* While there is more data in the status packet, keep processing
622	 * status items. First make sure there is enough data for the
623	 * segment descriptor's length field. */
624	while (packetlen >= 2) {
625		u_int   segtype = data[0];
626		u_int   segsize = data[1];
627
628		/* Now that we know how long it claims to be, make sure
629		 * there is enough data for the next seg. */
630		if (packetlen < segsize + 2)
631			break;
632		switch (segtype) {
633		case 0x01:
634		case 0x51:
635			if (resptype_seen) {
636				log(LOG_WARNING, "nglmi: dup MSGTYPE\n");
637				goto nextIE;
638			}
639			resptype_seen++;
640			/* The remote end tells us what kind of response
641			 * this is. Only expect a type 0 or 1. if we are a
642			 * full status, invalidate a few DLCIs just to see
643			 * that they are still ok. */
644			if (segsize != 1)
645				goto nextIE;
646			switch (data[2]) {
647			case 1:
648				/* partial status, do no extra processing */
649				break;
650			case 0:
651			    {
652				int     count = 0;
653				int     idx = sc->invalidx;
654
655				for (count = 0; count < 10; count++) {
656					if (idx > MAXDLCI)
657						idx = 0;
658					if (sc->dlci_state[idx] == DLCI_UP)
659						sc->dlci_state[idx] = DLCI_DOWN;
660					idx++;
661				}
662				sc->invalidx = idx;
663				/* we got and we wanted one. relax
664				 * now.. but don't reset to 0 if it
665				 * was unrequested. */
666				if (sc->livs > sc->liv_per_full)
667					sc->livs = 0;
668				break;
669			    }
670			}
671			break;
672		case 0x03:
673		case 0x53:
674			/* The remote tells us what it thinks the sequence
675			 * numbers are. If it's not size 2, it must be a
676			 * duplicate to have gotten this far, skip it. */
677			if (seq_seen != 0)	/* already seen seq numbers */
678				goto nextIE;
679			if (segsize != 2)
680				goto nextIE;
681			sc->remote_seq = data[2];
682			if (sc->local_seq == data[3]) {
683				sc->local_seq++;
684				sc->seq_retries = 0;
685				/* Note that all 3 Frame protocols seem to
686				 * not like 0 as a sequence number. */
687				if (sc->local_seq == 0)
688					sc->local_seq = 1;
689			}
690			break;
691		case 0x07:
692		case 0x57:
693			/* The remote tells us about a DLCI that it knows
694			 * about. There may be many of these in a single
695			 * status response */
696			switch (segsize) {
697			case 6:/* only on 'group of 4' */
698				dlci = ((u_short) data[2] & 0xff) << 8;
699				dlci |= (data[3] & 0xff);
700				if ((dlci < 1024) && (dlci > 0)) {
701				  /* XXX */
702				}
703				break;
704			case 3:
705				dlci = ((u_short) data[2] & 0x3f) << 4;
706				dlci |= ((data[3] & 0x78) >> 3);
707				if ((dlci < 1024) && (dlci > 0)) {
708					/* set up the bottom half of the
709					 * support for that dlci if it's not
710					 * already been done */
711					/* store this information somewhere */
712				}
713				break;
714			default:
715				goto nextIE;
716			}
717			if (sc->dlci_state[dlci] != DLCI_UP) {
718				/* bring new DLCI to life */
719				/* may do more here some day */
720				if (sc->dlci_state[dlci] != DLCI_DOWN)
721					log(LOG_INFO,
722					    "nglmi: DLCI %d became active\n",
723					    dlci);
724				sc->dlci_state[dlci] = DLCI_UP;
725			}
726			break;
727		}
728nextIE:
729		STEPBY(segsize + 2);
730	}
731	NG_FREE_DATA(m, meta);
732	return (0);
733
734drop:
735	NG_FREE_DATA(m, meta);
736	return (EINVAL);
737}
738
739/*
740 * Check that a packet is entirely kosha.
741 * return 1 of ok, and 0 if not.
742 * All data is discarded if a 0 is returned.
743 */
744static int
745nglmi_checkdata(hook_p hook, struct mbuf *m, meta_p meta)
746{
747	sc_p    sc = hook->node->private;
748	u_char *data;
749	u_short packetlen;
750	unsigned short dlci;
751	u_char  type;
752	u_char  nextbyte;
753	int     seq_seen = 0;
754	int     resptype_seen = 0;	/* 0 , 1 (partial) or 2 (full) */
755	int     highest_dlci = 0;
756
757	packetlen = m->m_hdr.mh_len;
758	data = mtod(m, u_char *);
759	if (*data != 0x03) {
760		log(LOG_WARNING, "nglmi: unexpected value in LMI(%d)\n", 1);
761		goto reject;
762	}
763	STEPBY(1);
764
765	/* look at the protocol ID */
766	nextbyte = *data;
767	if (sc->flags & SCF_AUTO) {
768		SETLMITYPE(sc, SCF_NOLMI);	/* start with a clean slate */
769		switch (nextbyte) {
770		case 0x8:
771			sc->protoID = 8;
772			break;
773		case 0x9:
774			SETLMITYPE(sc, SCF_GROUP4);
775			sc->protoID = 9;
776			break;
777		default:
778			log(LOG_WARNING, "nglmi: bad Protocol ID(%d)\n",
779			    (int) nextbyte);
780			goto reject;
781		}
782	} else {
783		if (nextbyte != sc->protoID) {
784			log(LOG_WARNING, "nglmi: unexpected Protocol ID(%d)\n",
785			    (int) nextbyte);
786			goto reject;
787		}
788	}
789	STEPBY(1);
790
791	/* check call reference (always null in non ISDN frame relay) */
792	if (*data != 0x00) {
793		log(LOG_WARNING, "nglmi: unexpected Call Reference (0x%x)\n",
794		    data[-1]);
795		goto reject;
796	}
797	STEPBY(1);
798
799	/* check message type */
800	switch ((type = *data)) {
801	case 0x75:		/* Status enquiry */
802		log(LOG_WARNING, "nglmi: unexpected message type(0x%x)\n",
803		    data[-1]);
804		goto reject;
805	case 0x7D:		/* Status message */
806		break;
807	default:
808		log(LOG_WARNING,
809		    "nglmi: unexpected msg type(0x%x) \n", (int) type);
810		goto reject;
811	}
812	STEPBY(1);
813
814	/* Now check if there is a 'locking shift'. This is only seen in
815	 * Annex D frames. Don't increment immediately as it might not be
816	 * there. */
817	nextbyte = *data;
818	if (sc->flags & SCF_AUTO) {
819		if (!(GROUP4(sc))) {
820			if (nextbyte == 0x95) {
821				SETLMITYPE(sc, SCF_ANNEX_D);
822				STEPBY(1);
823			} else
824				SETLMITYPE(sc, SCF_ANNEX_A);
825		} else if (nextbyte == 0x95) {
826			log(LOG_WARNING, "nglmi: locking shift seen in G4\n");
827			goto reject;
828		}
829	} else {
830		if (ANNEXD(sc)) {
831			if (*data == 0x95)
832				STEPBY(1);
833			else {
834				log(LOG_WARNING,
835				    "nglmi: locking shift missing\n");
836				goto reject;
837			}
838		} else if (*data == 0x95) {
839			log(LOG_WARNING, "nglmi: locking shift seen\n");
840			goto reject;
841		}
842	}
843
844	/* While there is more data in the status packet, keep processing
845	 * status items. First make sure there is enough data for the
846	 * segment descriptor's length field. */
847	while (packetlen >= 2) {
848		u_int   segtype = data[0];
849		u_int   segsize = data[1];
850
851		/* Now that we know how long it claims to be, make sure
852		 * there is enough data for the next seg. */
853		if (packetlen < (segsize + 2)) {
854			log(LOG_WARNING, "nglmi: IE longer than packet\n");
855			break;
856		}
857		switch (segtype) {
858		case 0x01:
859		case 0x51:
860			/* According to MCI's HP analyser, we should just
861			 * ignore if there is mor ethan one of these (?). */
862			if (resptype_seen) {
863				log(LOG_WARNING, "nglmi: dup MSGTYPE\n");
864				goto nextIE;
865			}
866			if (segsize != 1) {
867				log(LOG_WARNING, "nglmi: MSGTYPE wrong size\n");
868				goto reject;
869			}
870			/* The remote end tells us what kind of response
871			 * this is. Only expect a type 0 or 1. if it was a
872			 * full (type 0) check we just asked for a type
873			 * full. */
874			switch (data[2]) {
875			case 1:/* partial */
876				if (sc->livs > sc->liv_per_full) {
877					log(LOG_WARNING,
878					  "nglmi: LIV when FULL expected\n");
879					goto reject;	/* need full */
880				}
881				resptype_seen = 1;
882				break;
883			case 0:/* full */
884				/* Full response is always acceptable */
885				resptype_seen = 2;
886				break;
887			default:
888				log(LOG_WARNING,
889				 "nglmi: Unknown report type %d\n", data[2]);
890				goto reject;
891			}
892			break;
893		case 0x03:
894		case 0x53:
895			/* The remote tells us what it thinks the sequence
896			 * numbers are. I would have thought that there
897			 * needs to be one and only one of these, but MCI
898			 * want us to just ignore extras. (?) */
899			if (resptype_seen == 0) {
900				log(LOG_WARNING, "nglmi: no TYPE before SEQ\n");
901				goto reject;
902			}
903			if (seq_seen != 0)	/* already seen seq numbers */
904				goto nextIE;
905			if (segsize != 2) {
906				log(LOG_WARNING, "nglmi: bad SEQ sts size\n");
907				goto reject;
908			}
909			if (sc->local_seq != data[3]) {
910				log(LOG_WARNING, "nglmi: unexpected SEQ\n");
911				goto reject;
912			}
913			seq_seen = 1;
914			break;
915		case 0x07:
916		case 0x57:
917			/* The remote tells us about a DLCI that it knows
918			 * about. There may be many of these in a single
919			 * status response */
920			if (seq_seen != 1) {	/* already seen seq numbers? */
921				log(LOG_WARNING,
922				    "nglmi: No sequence before DLCI\n");
923				goto reject;
924			}
925			if (resptype_seen != 2) {	/* must be full */
926				log(LOG_WARNING,
927				    "nglmi: No resp type before DLCI\n");
928				goto reject;
929			}
930			if (GROUP4(sc)) {
931				if (segsize != 6) {
932					log(LOG_WARNING,
933					    "nglmi: wrong IE segsize\n");
934					goto reject;
935				}
936				dlci = ((u_short) data[2] & 0xff) << 8;
937				dlci |= (data[3] & 0xff);
938			} else {
939				if (segsize != 3) {
940					log(LOG_WARNING,
941					    "nglmi: DLCI headersize of %d"
942					    " not supported\n", segsize - 1);
943					goto reject;
944				}
945				dlci = ((u_short) data[2] & 0x3f) << 4;
946				dlci |= ((data[3] & 0x78) >> 3);
947			}
948			/* async can only have one of these */
949#if 0				/* async not yet accepted */
950			if (async && highest_dlci) {
951				log(LOG_WARNING,
952				    "nglmi: Async with > 1 DLCI\n");
953				goto reject;
954			}
955#endif
956			/* Annex D says these will always be Ascending, but
957			 * the HP test for G4 says we should accept
958			 * duplicates, so for now allow that. ( <= vs. < ) */
959#if 0
960			/* MCI tests want us to accept out of order for AnxD */
961			if ((!GROUP4(sc)) && (dlci < highest_dlci)) {
962				/* duplicate or mis-ordered dlci */
963				/* (spec says they will increase in number) */
964				log(LOG_WARNING, "nglmi: DLCI out of order\n");
965				goto reject;
966			}
967#endif
968			if (dlci > 1023) {
969				log(LOG_WARNING, "nglmi: DLCI out of range\n");
970				goto reject;
971			}
972			highest_dlci = dlci;
973			break;
974		default:
975			log(LOG_WARNING,
976			    "nglmi: unknown LMI segment type %d\n", segtype);
977		}
978nextIE:
979		STEPBY(segsize + 2);
980	}
981	if (packetlen != 0) {	/* partial junk at end? */
982		log(LOG_WARNING,
983		    "nglmi: %d bytes extra at end of packet\n", packetlen);
984		goto print;
985	}
986	if (resptype_seen == 0) {
987		log(LOG_WARNING, "nglmi: No response type seen\n");
988		goto reject;	/* had no response type */
989	}
990	if (seq_seen == 0) {
991		log(LOG_WARNING, "nglmi: No sequence numbers seen\n");
992		goto reject;	/* had no sequence numbers */
993	}
994	return (1);
995
996print:
997	{
998		int     i, j, k, pos;
999		char    buf[100];
1000		int     loc;
1001		u_char *bp = mtod(m, u_char *);
1002
1003		k = i = 0;
1004		loc = (m->m_hdr.mh_len - packetlen);
1005		log(LOG_WARNING, "nglmi: error at location %d\n", loc);
1006		while (k < m->m_hdr.mh_len) {
1007			pos = 0;
1008			j = 0;
1009			while ((j++ < 16) && k < m->m_hdr.mh_len) {
1010				pos += sprintf(buf + pos, "%c%02x",
1011					       ((loc == k) ? '>' : ' '),
1012					       bp[k]);
1013				k++;
1014			}
1015			if (i == 0)
1016				log(LOG_WARNING, "nglmi: packet data:%s\n", buf);
1017			else
1018				log(LOG_WARNING, "%04d              :%s\n", k, buf);
1019			i++;
1020		}
1021	}
1022	return (1);
1023reject:
1024	{
1025		int     i, j, k, pos;
1026		char    buf[100];
1027		int     loc;
1028		u_char *bp = mtod(m, u_char *);
1029
1030		k = i = 0;
1031		loc = (m->m_hdr.mh_len - packetlen);
1032		log(LOG_WARNING, "nglmi: error at location %d\n", loc);
1033		while (k < m->m_hdr.mh_len) {
1034			pos = 0;
1035			j = 0;
1036			while ((j++ < 16) && k < m->m_hdr.mh_len) {
1037				pos += sprintf(buf + pos, "%c%02x",
1038					       ((loc == k) ? '>' : ' '),
1039					       bp[k]);
1040				k++;
1041			}
1042			if (i == 0)
1043				log(LOG_WARNING, "nglmi: packet data:%s\n", buf);
1044			else
1045				log(LOG_WARNING, "%04d              :%s\n", k, buf);
1046			i++;
1047		}
1048	}
1049	NG_FREE_DATA(m, meta);
1050	return (0);
1051}
1052
1053/*
1054 * Do local shutdown processing..
1055 * Cut any remaining links and free our local resources.
1056 */
1057static int
1058nglmi_rmnode(node_p node)
1059{
1060	const sc_p sc = node->private;
1061
1062	node->flags |= NG_INVALID;
1063	ng_cutlinks(node);
1064	ng_unname(node);
1065	node->private = NULL;
1066	ng_unref(sc->node);
1067	FREE(sc, M_NETGRAPH);
1068	return (0);
1069}
1070
1071/*
1072 * Hook disconnection
1073 * For this type, removal of any link except "debug" destroys the node.
1074 */
1075static int
1076nglmi_disconnect(hook_p hook)
1077{
1078	const sc_p sc = hook->node->private;
1079
1080	/* OK to remove debug hook(s) */
1081	if (hook->private == NULL)
1082		return (0);
1083
1084	/* Stop timer if it's currently active */
1085	if (sc->flags & SCF_CONNECTED)
1086		untimeout(LMI_ticker, sc, sc->handle);
1087
1088	/* Self-destruct */
1089	ng_rmnode(hook->node);
1090	return (0);
1091}
1092
1093