1 /* ngsniffer.c
2  *
3  * Wiretap Library
4  * Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
5  *
6  * SPDX-License-Identifier: GPL-2.0-or-later
7  */
8 
9 /* The code in ngsniffer.c that decodes the time fields for each packet in the
10  * Sniffer trace originally came from code from TCPVIEW:
11  *
12  * TCPVIEW
13  *
14  * Author:	Martin Hunt
15  *		Networks and Distributed Computing
16  *		Computing & Communications
17  *		University of Washington
18  *		Administration Building, AG-44
19  *		Seattle, WA  98195
20  *		Internet: martinh@cac.washington.edu
21  *
22  *
23  * Copyright 1992 by the University of Washington
24  *
25  * Permission to use, copy, modify, and distribute this software and its
26  * documentation for any purpose and without fee is hereby granted, provided
27  * that the above copyright notice appears in all copies and that both the
28  * above copyright notice and this permission notice appear in supporting
29  * documentation, and that the name of the University of Washington not be
30  * used in advertising or publicity pertaining to distribution of the software
31  * without specific, written prior permission.  This software is made
32  * available "as is", and
33  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
34  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
35  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
36  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
37  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
38  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
39  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
40  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
41  *
42  */
43 #include "config.h"
44 
45 #include <errno.h>
46 #include <string.h>
47 #include "wtap-int.h"
48 #include "file_wrappers.h"
49 #include "ngsniffer.h"
50 #include <wsutil/ws_assert.h>
51 
52 /* Magic number in Sniffer files. */
53 static const char ngsniffer_magic[] = {
54 	'T', 'R', 'S', 'N', 'I', 'F', 'F', ' ', 'd', 'a', 't', 'a',
55 	' ', ' ', ' ', ' ', 0x1a
56 };
57 
58 /*
59  * Sniffer record types.
60  */
61 #define REC_VERS	1	/* Version record (f_vers) */
62 #define REC_FRAME2	4	/* Frame data (f_frame2) */
63 #define	REC_FRAME4	8	/* Frame data (f_frame4) */
64 #define REC_FRAME6	12	/* Frame data (f_frame6) (see below) */
65 #define REC_EOF		3	/* End-of-file record (no data follows) */
66 /*
67  * and now for some unknown header types
68  */
69 #define REC_HEADER1	6	/* Header containing various information,
70 				 * not yet reverse engineered - some binary,
71 				 * some strings (Serial numbers?  Names
72 				 * under which the software is registered?
73 				 * Software version numbers?  Mysterious
74 				 * strings such as "PA-55X" and "PA-30X"
75 				 * and "PA-57X" and "PA-11X"?), some strings
76 				 * that are partially overwritten
77 				 * ("UNSERIALIZED", "Network General
78 				 * Corporation"), differing from major
79 				 * version to major version */
80 #define REC_HEADER2	7	/* Header containing ??? */
81 #define REC_V2DESC	8	/* In version 2 sniffer traces contains
82 				 * info about this capturing session,
83 				 * in the form of a multi-line string
84 				 * with NL as the line separator.
85 				 * Collides with REC_FRAME4 */
86 #define REC_HEADER3	13	/* Retransmission counts? */
87 #define REC_HEADER4	14	/* ? */
88 #define REC_HEADER5	15	/* ? */
89 #define REC_HEADER6	16	/* More broadcast/retransmission counts? */
90 #define REC_HEADER7	17	/* ? */
91 
92 /*
93  * Sniffer record header structure.
94  */
95 struct rec_header {
96 	guint16	type;		/* record type */
97 	guint16	length;		/* record length */
98 };
99 
100 /*
101  * Sniffer version record format.
102  */
103 struct vers_rec {
104 	gint16	maj_vers;	/* major version number */
105 	gint16	min_vers;	/* minor version number */
106 	gint16	time_dos;	/* DOS-format time */
107 	gint16	date;		/* DOS-format date */
108 	gint8	type;		/* what type of records follow */
109 	guint8	network;	/* network type */
110 	gint8	format;		/* format version */
111 	guint8	timeunit;	/* timestamp units */
112 	gint8	cmprs_vers;	/* compression version */
113 	gint8	cmprs_level;	/* compression level */
114 	gint16	rsvd[2];	/* reserved */
115 };
116 
117 /*
118  * Network types.
119  */
120 #define NETWORK_TRING		0	/* Token ring */
121 #define NETWORK_ENET		1	/* Ethernet */
122 #define NETWORK_ARCNET		2	/* ARCNET */
123 #define NETWORK_STARLAN		3	/* StarLAN */
124 #define NETWORK_PCNW		4	/* PC Network broadband (Sytek?) */
125 #define NETWORK_LOCALTALK	5	/* LocalTalk */
126 #define NETWORK_SYNCHRO		7	/* Internetwork analyzer (synchronous) */
127 #define NETWORK_ASYNC		8	/* Internetwork analyzer (asynchronous) */
128 #define NETWORK_FDDI		9	/* FDDI */
129 #define NETWORK_ATM		10	/* ATM */
130 
131 /*
132  * Sniffer type 2 data record format - followed by frame data.
133  *
134  * The Expert Sniffer Network Analyzer Operations manual, Release 5.50,
135  * documents some of the values used in "fs" and "flags".  "flags" don't
136  * look as if they'd be of much interest to us, as those are internal
137  * flags for state used by the Sniffer, but "fs" gives various status
138  * bits including error indications *and*:
139  *
140  *	ISDN channel information for ISDN;
141  *
142  *	PPP vs. SLIP information for Async.
143  *
144  * In that section it also refers to "FDDI analyzers using the NPI PCI
145  * FDDI adapter" and "FDDI analyzers using the NPI ISA FDDI adapter",
146  * referring to the first as "F1SNIFF" and the second as "FDSNIFF";
147  * those sound as if they *could* be replacements for "TRSNIFF" in
148  * the file header, but that manual says, earlier, that the header
149  * starts with "TRSNIFF data, no matter where the frames were
150  * collected".
151  *
152  * It also says that a type 2 record has an 8-bit "time_high"
153  * and an 8-bit "time_day" field; the code here used to have a
154  * 16-bit "time_high" value, but that gave wrong time stamps on at
155  * least some captures.  Did some older manual have it as a 16-bit
156  * "tstamp_high", so that perhaps it depends on the version number
157  * in the file, or is it "tstamp_high" plus "tstamp_day" in all
158  * versions?  (I forget whether this came purely from tcpview, or if
159  * I saw any of it in an NAI document.)
160  *
161  * We interpret them as unsigned, as interpreting them as signed
162  * would appear to allow time stamps that precede the start of the
163  * capture.  The description of the record format shows them as
164  * "char", but the section "How the Analyzer Stores Time" shows a
165  * time stamp structure with those fields being "unsigned char".
166  *
167  * In addition, the description of the record format has the comment
168  * for the "time_day" field saying it's the time in days since the
169  * start of the capture, but the "How the Analyzer Stores Time"
170  * section says it's increased by 1 if the capture continues past
171  * midnight - and also says that the time stamp structure has a time
172  * relative to midnight when the capture started, not since the
173  * actual capture start, so that might be a difference between
174  * the internal time stamp in the Sniffer software and the time
175  * stamp in capture files (i.e., the latter might be relative to
176  * the time when the capture starts).
177  */
178 struct frame2_rec {
179 	guint16	time_low;	/* low part of time stamp */
180 	guint16	time_med;	/* middle part of time stamp */
181 	guint8	time_high;	/* high part of the time stamp */
182 	guint8	time_day;	/* time in days since start of capture */
183 	gint16	size;		/* number of bytes of data */
184 	guint8	fs;		/* frame error status bits */
185 	guint8	flags;		/* buffer flags */
186 	gint16	true_size;	/* size of original frame, in bytes */
187 	gint16	rsvd;		/* reserved */
188 };
189 
190 /*
191  * Bits in "fs".
192  *
193  * The bits differ for different link-layer types.
194  */
195 
196 /*
197  * Ethernet.
198  */
199 #define FS_ETH_CRC		0x80	/* CRC error */
200 #define FS_ETH_ALIGN		0x40	/* bad alignment */
201 #define FS_ETH_RU		0x20	/* "RU out of resources" */
202 #define FS_ETH_OVERRUN		0x10	/* DMA overrun */
203 #define FS_ETH_RUNT		0x08	/* frame too small */
204 #define FS_ETH_COLLISION	0x02	/* collision fragment */
205 
206 /*
207  * FDDI.
208  */
209 #define FS_FDDI_INVALID		0x10	/* frame indicators are invalid */
210 #define FS_FDDI_ERROR		0x20	/* "frame error bit 1" */
211 #define FS_FDDI_PCI_VDL		0x01	/* VDL (Valid Data Length?) error on frame on PCI adapter */
212 #define FS_FDDI_PCI_CRC		0x02	/* CRC error on frame on PCI adapter */
213 #define FS_FDDI_ISA_CRC		0x20	/* CRC error on frame on ISA adapter */
214 
215 /*
216  * Internetwork analyzer (synchronous and asynchronous).
217  */
218 #define FS_WAN_DTE		0x80	/* DTE->DCE frame */
219 
220 /*
221  * Internetwork analyzer (synchronous).
222  */
223 #define FS_SYNC_LOST		0x01	/* some frames were lost */
224 #define FS_SYNC_CRC		0x02	/* CRC error */
225 #define FS_SYNC_ABORT		0x04	/* aborted frame */
226 #define FS_ISDN_CHAN_MASK	0x18	/* ISDN channel */
227 #define FS_ISDN_CHAN_D		0x18	/* ISDN channel D */
228 #define FS_ISDN_CHAN_B1		0x08	/* ISDN channel B1 */
229 #define FS_ISDN_CHAN_B2		0x10	/* ISDN channel B2 */
230 
231 /*
232  * Internetwork analyzer (asynchronous).
233  * XXX - are some of these synchronous flags?  They're listed with the
234  * asynchronous flags in the Sniffer 5.50 Network Analyzer Operations
235  * manual.  Is one of the "overrun" errors a synchronous overrun error?
236  */
237 #define FS_ASYNC_LOST		0x01	/* some frames were lost */
238 #define FS_ASYNC_OVERRUN	0x02	/* UART overrun, lost bytes */
239 #define FS_ASYNC_FRAMING	0x04	/* bad character (framing error?) */
240 #define FS_ASYNC_PPP		0x08	/* PPP frame */
241 #define FS_ASYNC_SLIP		0x10	/* SLIP frame */
242 #define FS_ASYNC_ALIGN		0x20	/* alignment or DLPP(?) error */
243 #define FS_ASYNC_OVERRUN2	0x40	/* overrun or bad frame length */
244 
245 /*
246  * Sniffer type 4 data record format - followed by frame data.
247  *
248  * The ATM Sniffer manual says that the "flags" field holds "buffer flags;
249  * BF_xxxx", but doesn't say what the BF_xxxx flags are.  They may
250  * be the same as they are in a type 2 record, in which case they're
251  * probably not of much interest to us.
252  *
253  * XXX - the manual also says there's an 8-byte "ATMTimeStamp" driver
254  * time stamp at the end of "ATMSaveInfo", but, from an ATM Sniffer capture
255  * file I've looked at, that appears not to be the case.
256  */
257 
258 /*
259  * Fields from the AAL5 trailer for the frame, if it's an AAL5 frame
260  * rather than a cell.
261  */
262 typedef struct _ATM_AAL5Trailer {
263 	guint16	aal5t_u2u;	/* user-to-user indicator */
264 	guint16	aal5t_len;	/* length of the packet */
265 	guint32	aal5t_chksum;	/* checksum for AAL5 packet */
266 } ATM_AAL5Trailer;
267 
268 typedef struct _ATMTimeStamp {
269 	guint32	msw;	/* most significant word */
270 	guint32	lsw;	/* least significant word */
271 } ATMTimeStamp;
272 
273 typedef struct _ATMSaveInfo {
274 	guint32 StatusWord;	/* status word from driver */
275 	ATM_AAL5Trailer Trailer; /* AAL5 trailer */
276 	guint8	AppTrafType;	/* traffic type */
277 	guint8	AppHLType;	/* protocol type */
278 	guint16	AppReserved;	/* reserved */
279 	guint16	Vpi;		/* virtual path identifier */
280 	guint16	Vci;		/* virtual circuit identifier */
281 	guint16	channel;	/* link: 0 for DCE, 1 for DTE */
282 	guint16	cells;		/* number of cells */
283 	guint32	AppVal1;	/* type-dependent */
284 	guint32	AppVal2;	/* type-dependent */
285 } ATMSaveInfo;
286 
287 /*
288  * Bits in StatusWord.
289  */
290 #define	SW_ERRMASK		0x0F	/* Error mask: */
291 #define	SW_RX_FIFO_UNDERRUN	0x01	/* Receive FIFO underrun */
292 #define	SW_RX_FIFO_OVERRUN	0x02	/* Receive FIFO overrun */
293 #define	SW_RX_PKT_TOO_LONG	0x03	/* Received packet > max size */
294 #define	SW_CRC_ERROR		0x04	/* CRC error */
295 #define	SW_USER_ABORTED_RX	0x05	/* User aborted receive */
296 #define	SW_BUF_LEN_TOO_LONG	0x06	/* buffer len > max buf */
297 #define	SW_INTERNAL_T1_ERROR	0x07	/* Internal T1 error */
298 #define	SW_RX_CHANNEL_DEACTIV8	0x08	/* Rx channel deactivate */
299 
300 #define	SW_ERROR		0x80	/* Error indicator */
301 #define	SW_CONGESTION		0x40	/* Congestion indicator */
302 #define	SW_CLP			0x20	/* Cell loss priority indicator */
303 #define	SW_RAW_CELL		0x100	/* RAW cell indicator */
304 #define	SW_OAM_CELL		0x200	/* OAM cell indicator */
305 
306 /*
307  * Bits in AppTrafType.
308  *
309  * For AAL types other than AAL5, the packet data is presumably for a
310  * single cell, not a reassembled frame, as the ATM Sniffer manual says
311  * it doesn't reassemble cells other than AAL5 cells.
312  */
313 #define	ATT_AALTYPE		0x0F	/* AAL type: */
314 #define	ATT_AAL_UNKNOWN		0x00	/* Unknown AAL */
315 #define	ATT_AAL1		0x01	/* AAL1 */
316 #define	ATT_AAL3_4		0x02	/* AAL3/4 */
317 #define	ATT_AAL5		0x03	/* AAL5 */
318 #define	ATT_AAL_USER		0x04	/* User AAL */
319 #define	ATT_AAL_SIGNALLING	0x05	/* Signaling AAL */
320 #define	ATT_OAMCELL		0x06	/* OAM cell */
321 
322 #define	ATT_HLTYPE		0xF0	/* Higher-layer type: */
323 #define	ATT_HL_UNKNOWN		0x00	/* unknown */
324 #define	ATT_HL_LLCMX		0x10	/* LLC multiplexed (probably RFC 1483) */
325 #define	ATT_HL_VCMX		0x20	/* VC multiplexed (probably RFC 1483) */
326 #define	ATT_HL_LANE		0x30	/* LAN Emulation */
327 #define	ATT_HL_ILMI		0x40	/* ILMI */
328 #define	ATT_HL_FRMR		0x50	/* Frame Relay */
329 #define	ATT_HL_SPANS		0x60	/* FORE SPANS */
330 #define	ATT_HL_IPSILON		0x70	/* Ipsilon */
331 
332 /*
333  * Values for AppHLType; the interpretation depends on the ATT_HLTYPE
334  * bits in AppTrafType.
335  */
336 #define	AHLT_UNKNOWN		0x0
337 #define	AHLT_VCMX_802_3_FCS	0x1	/* VCMX: 802.3 FCS */
338 #define	AHLT_LANE_LE_CTRL	0x1	/* LANE: LE Ctrl */
339 #define	AHLT_IPSILON_FT0	0x1	/* Ipsilon: Flow Type 0 */
340 #define	AHLT_VCMX_802_4_FCS	0x2	/* VCMX: 802.4 FCS */
341 #define	AHLT_LANE_802_3		0x2	/* LANE: 802.3 */
342 #define	AHLT_IPSILON_FT1	0x2	/* Ipsilon: Flow Type 1 */
343 #define	AHLT_VCMX_802_5_FCS	0x3	/* VCMX: 802.5 FCS */
344 #define	AHLT_LANE_802_5		0x3	/* LANE: 802.5 */
345 #define	AHLT_IPSILON_FT2	0x3	/* Ipsilon: Flow Type 2 */
346 #define	AHLT_VCMX_FDDI_FCS	0x4	/* VCMX: FDDI FCS */
347 #define	AHLT_LANE_802_3_MC	0x4	/* LANE: 802.3 multicast */
348 #define	AHLT_VCMX_802_6_FCS	0x5	/* VCMX: 802.6 FCS */
349 #define	AHLT_LANE_802_5_MC	0x5	/* LANE: 802.5 multicast */
350 #define	AHLT_VCMX_802_3		0x7	/* VCMX: 802.3 */
351 #define	AHLT_VCMX_802_4		0x8	/* VCMX: 802.4 */
352 #define	AHLT_VCMX_802_5		0x9	/* VCMX: 802.5 */
353 #define	AHLT_VCMX_FDDI		0xa	/* VCMX: FDDI */
354 #define	AHLT_VCMX_802_6		0xb	/* VCMX: 802.6 */
355 #define	AHLT_VCMX_FRAGMENTS	0xc	/* VCMX: Fragments */
356 #define	AHLT_VCMX_BPDU		0xe	/* VCMX: BPDU */
357 
358 struct frame4_rec {
359 	guint16	time_low;	/* low part of time stamp */
360 	guint16	time_med;	/* middle part of time stamp */
361 	guint8	time_high;	/* high part of time stamp */
362 	guint8	time_day;	/* time in days since start of capture */
363 	gint16	size;		/* number of bytes of data */
364 	gint8	fs;		/* frame error status bits */
365 	gint8	flags;		/* buffer flags */
366 	gint16	true_size;	/* size of original frame, in bytes */
367 	gint16	rsvd3;		/* reserved */
368 	gint16	atm_pad;	/* pad to 4-byte boundary */
369 	ATMSaveInfo atm_info;	/* ATM-specific stuff */
370 };
371 
372 /*
373  * XXX - I have a version 5.50 file with a bunch of token ring
374  * records listed as type "12".  The record format below was
375  * derived from frame4_rec and a bit of experimentation.
376  * - Gerald
377  */
378 struct frame6_rec {
379 	guint16	time_low;	/* low part of time stamp */
380 	guint16	time_med;	/* middle part of time stamp */
381 	guint8	time_high;	/* high part of time stamp */
382 	guint8	time_day;	/* time in days since start of capture */
383 	gint16	size;		/* number of bytes of data */
384 	guint8	fs;		/* frame error status bits */
385 	guint8	flags;		/* buffer flags */
386 	gint16	true_size;	/* size of original frame, in bytes */
387 	guint8	chemical_x[22];	/* ? */
388 };
389 
390 /*
391  * Network type values in some type 7 records.
392  *
393  * Captures with a major version number of 2 appear to have type 7
394  * records with text in them (at least one I have does).
395  *
396  * Captures with a major version of 4, and at least some captures with
397  * a major version of 5, have type 7 records with those values in the
398  * 5th byte.
399  *
400  * However, some captures with a major version number of 5 appear not to
401  * have type 7 records at all (at least one I have doesn't), but do appear
402  * to put non-zero values in the "rsvd" field of the version header (at
403  * least one I have does) - at least some other captures with smaller version
404  * numbers appear to put 0 there, so *maybe* that's where the network
405  * (sub)type is hidden in those captures.  The version 5 captures I've seen
406  * that *do* have type 7 records put 0 there, so it's not as if *all* V5
407  * captures have something in the "rsvd" field, however.
408  *
409  * The semantics of these network types is inferred from the Sniffer
410  * documentation, as they correspond to types described in the UI;
411  * in particular, see
412  *
413  *	http://www.mcafee.com/common/media/sniffer/support/sdos/operation.pdf
414  *
415  * starting at page 3-10 (56 of 496).
416  *
417  * XXX - I've seen X.25 captures with NET_ROUTER, and I've seen bridge/
418  * router captures with NET_HDLC.  Sigh....  Are those just captures for
419  * which the user set the wrong network type when capturing?
420  */
421 #define NET_SDLC	0	/* Probably "SDLC then SNA" */
422 #define NET_HDLC	1	/* Used for X.25; is it used for other
423 				   things as well, or is it "HDLC then
424 				   X.25", as referred to by the document
425 				   cited above, and only used for X.25? */
426 #define NET_FRAME_RELAY	2
427 #define NET_ROUTER	3	/* Probably "Router/Bridge", for various
428 				   point-to-point protocols for use between
429 				   bridges and routers, including PPP as well
430 				   as various proprietary protocols; also
431 				   used for ISDN, for reasons not obvious
432 				   to me, given that a Sniffer knows
433 				   whether it's using a WAN or an ISDN pod */
434 #define NET_PPP		4	/* "Asynchronous", which includes SLIP too */
435 #define NET_SMDS	5	/* Not mentioned in the document, but
436 				   that's a document for version 5.50 of
437 				   the Sniffer, and that version might use
438 				   version 5 in the file format and thus
439 				   might not be using type 7 records */
440 
441 /*
442  * Values for V.timeunit, in picoseconds, so that they can be represented
443  * as integers.  These values must be < 2^(64-40); see below.
444  *
445  * XXX - at least some captures with a V.timeunit value of 2 show
446  * packets with time stamps in 2011 if the time stamp is interpreted
447  * to be in units of 15 microseconds.  The capture predates 2008,
448  * so that interpretation is probably wrong.  Perhaps the interpretation
449  * of V.timeunit depends on the version number of the file?
450  */
451 static const guint32 Psec[] = {
452 	15000000,		/* 15.0 usecs = 15000000 psecs */
453 	  838096,		/* .838096 usecs = 838096 psecs */
454 	15000000,		/* 15.0 usecs = 15000000 psecs */
455 	  500000,		/* 0.5 usecs = 500000 psecs */
456 	 2000000,		/* 2.0 usecs = 2000000 psecs */
457 	 1000000,		/* 1.0 usecs = 1000000 psecs */
458 				/* XXX - Sniffer doc says 0.08 usecs = 80000 psecs */
459 	  100000		/* 0.1 usecs = 100000 psecs */
460 };
461 #define NUM_NGSNIFF_TIMEUNITS (sizeof Psec / sizeof Psec[0])
462 
463 /* Information for a compressed Sniffer data stream. */
464 typedef struct {
465 	unsigned char *buf;	/* buffer into which we uncompress data */
466 	unsigned int nbytes;	/* number of bytes of data in that buffer */
467 	int	nextout;	/* offset in that buffer of stream's current position */
468 	gint64	comp_offset;	/* current offset in compressed data stream */
469 	gint64	uncomp_offset;	/* current offset in uncompressed data stream */
470 } ngsniffer_comp_stream_t;
471 
472 typedef struct {
473 	guint	maj_vers;
474 	guint	min_vers;
475 	gboolean is_compressed;
476 	guint32	timeunit;
477 	time_t	start;
478 	guint	network;		/* network type */
479 	ngsniffer_comp_stream_t seq;	/* sequential access */
480 	ngsniffer_comp_stream_t rand;	/* random access */
481 	GList	*first_blob;		/* list element for first blob */
482 	GList	*last_blob;		/* list element for last blob */
483 	GList	*current_blob;		/* list element for current blob */
484 } ngsniffer_t;
485 
486 /*
487  * DOS date to "struct tm" conversion values.
488  */
489 /* DOS year = upper 7 bits */
490 #define DOS_YEAR_OFFSET (1980-1900)	/* tm_year = year+1900, DOS date year year+1980 */
491 #define DOS_YEAR_SHIFT	9
492 #define DOS_YEAR_MASK	(0x7F<<DOS_YEAR_SHIFT)
493 /* DOS month = next 4 bits */
494 #define DOS_MONTH_OFFSET	(-1)	/* tm_mon = month #-1, DOS date month = month # */
495 #define DOS_MONTH_SHIFT	5
496 #define DOS_MONTH_MASK	(0x0F<<DOS_MONTH_SHIFT)
497 /* DOS day = next 5 bits */
498 #define DOS_DAY_SHIFT	0
499 #define DOS_DAY_MASK	(0x1F<<DOS_DAY_SHIFT)
500 
501 static int process_header_records(wtap *wth, int *err, gchar **err_info,
502     gint16 maj_vers, guint8 network);
503 static int process_rec_header2_v2(wtap *wth, unsigned char *buffer,
504     guint16 length, int *err, gchar **err_info);
505 static int process_rec_header2_v145(wtap *wth, unsigned char *buffer,
506     guint16 length, gint16 maj_vers, int *err, gchar **err_info);
507 static gboolean ngsniffer_read(wtap *wth, wtap_rec *rec, Buffer *buf,
508     int *err, gchar **err_info, gint64 *data_offset);
509 static gboolean ngsniffer_seek_read(wtap *wth, gint64 seek_off,
510     wtap_rec *rec, Buffer *buf, int *err, gchar **err_info);
511 static gboolean read_rec_header(wtap *wth, gboolean is_random,
512     struct rec_header *hdr, int *err, gchar **err_info);
513 static gboolean process_frame_record(wtap *wth, gboolean is_random,
514     guint *padding, struct rec_header *hdr, wtap_rec *rec, Buffer *buf,
515     int *err, gchar **err_info);
516 static void set_metadata_frame2(wtap *wth, wtap_rec *rec,
517     struct frame2_rec *frame2);
518 static void set_pseudo_header_frame4(union wtap_pseudo_header *pseudo_header,
519     struct frame4_rec *frame4);
520 static void set_pseudo_header_frame6(wtap *wth,
521     union wtap_pseudo_header *pseudo_header, struct frame6_rec *frame6);
522 static int infer_pkt_encap(const guint8 *pd, int len);
523 static int fix_pseudo_header(int encap, Buffer *buf, int len,
524     union wtap_pseudo_header *pseudo_header);
525 static void ngsniffer_sequential_close(wtap *wth);
526 static void ngsniffer_close(wtap *wth);
527 static gboolean ngsniffer_dump(wtap_dumper *wdh, const wtap_rec *rec,
528     const guint8 *pd, int *err, gchar **err_info);
529 static gboolean ngsniffer_dump_finish(wtap_dumper *wdh, int *err,
530     gchar **err_info);
531 static int SnifferDecompress( unsigned char * inbuf, size_t inlen,
532     unsigned char * outbuf, size_t outlen, int *err, gchar **err_info );
533 static gboolean ng_read_bytes_or_eof(wtap *wth, void *buffer,
534     unsigned int nbytes, gboolean is_random, int *err, gchar **err_info);
535 static gboolean ng_read_bytes(wtap *wth, void *buffer, unsigned int nbytes,
536     gboolean is_random, int *err, gchar **err_info);
537 static gboolean read_blob(FILE_T infile, ngsniffer_comp_stream_t *comp_stream,
538     int *err, gchar **err_info);
539 static gboolean ng_skip_bytes_seq(wtap *wth, unsigned int count, int *err,
540     gchar **err_info);
541 static gboolean ng_file_seek_rand(wtap *wth, gint64 offset, int *err,
542     gchar **err_info);
543 
544 static int ngsniffer_uncompressed_file_type_subtype = -1;
545 static int ngsniffer_compressed_file_type_subtype = -1;
546 
547 void register_ngsniffer(void);
548 
549 wtap_open_return_val
ngsniffer_open(wtap * wth,int * err,gchar ** err_info)550 ngsniffer_open(wtap *wth, int *err, gchar **err_info)
551 {
552 	char magic[sizeof ngsniffer_magic];
553 	char record_type[2];
554 	char record_length[4]; /* only the first 2 bytes are length,
555 				  the last 2 are "reserved" and are thrown away */
556 	guint16 type;
557 	struct vers_rec version;
558 	guint16 maj_vers;
559 	guint16	start_date;
560 #if 0
561 	guint16	start_time;
562 #endif
563 	static const int sniffer_encap[] = {
564 		WTAP_ENCAP_TOKEN_RING,
565 		WTAP_ENCAP_ETHERNET,
566 		WTAP_ENCAP_ARCNET,
567 		WTAP_ENCAP_UNKNOWN,	/* StarLAN */
568 		WTAP_ENCAP_UNKNOWN,	/* PC Network broadband */
569 		WTAP_ENCAP_UNKNOWN,	/* LocalTalk */
570 		WTAP_ENCAP_UNKNOWN,	/* Znet */
571 		WTAP_ENCAP_PER_PACKET,	/* Internetwork analyzer (synchronous) */
572 		WTAP_ENCAP_PER_PACKET,	/* Internetwork analyzer (asynchronous) */
573 		WTAP_ENCAP_FDDI_BITSWAPPED,
574 		WTAP_ENCAP_ATM_PDUS
575 	};
576 	#define NUM_NGSNIFF_ENCAPS (sizeof sniffer_encap / sizeof sniffer_encap[0])
577 	struct tm tm;
578 	gint64 current_offset;
579 	ngsniffer_t *ngsniffer;
580 
581 	/* Read in the string that should be at the start of a Sniffer file */
582 	if (!wtap_read_bytes(wth->fh, magic, sizeof magic, err, err_info)) {
583 		if (*err != WTAP_ERR_SHORT_READ)
584 			return WTAP_OPEN_ERROR;
585 		return WTAP_OPEN_NOT_MINE;
586 	}
587 
588 	if (memcmp(magic, ngsniffer_magic, sizeof ngsniffer_magic)) {
589 		return WTAP_OPEN_NOT_MINE;
590 	}
591 
592 	/*
593 	 * Read the first record, which the manual says is a version
594 	 * record.
595 	 */
596 	if (!wtap_read_bytes(wth->fh, record_type, 2, err, err_info))
597 		return WTAP_OPEN_ERROR;
598 	if (!wtap_read_bytes(wth->fh, record_length, 4, err, err_info))
599 		return WTAP_OPEN_ERROR;
600 
601 	type = pletoh16(record_type);
602 
603 	if (type != REC_VERS) {
604 		*err = WTAP_ERR_BAD_FILE;
605 		*err_info = g_strdup("ngsniffer: Sniffer file doesn't start with a version record");
606 		return WTAP_OPEN_ERROR;
607 	}
608 
609 	if (!wtap_read_bytes(wth->fh, &version, sizeof version, err, err_info))
610 		return WTAP_OPEN_ERROR;
611 
612 	/* Check the data link type. */
613 	if (version.network >= NUM_NGSNIFF_ENCAPS
614 	    || sniffer_encap[version.network] == WTAP_ENCAP_UNKNOWN) {
615 		*err = WTAP_ERR_UNSUPPORTED;
616 		*err_info = g_strdup_printf("ngsniffer: network type %u unknown or unsupported",
617 		    version.network);
618 		return WTAP_OPEN_ERROR;
619 	}
620 
621 	/* Check the time unit */
622 	if (version.timeunit >= NUM_NGSNIFF_TIMEUNITS) {
623 		*err = WTAP_ERR_UNSUPPORTED;
624 		*err_info = g_strdup_printf("ngsniffer: Unknown timeunit %u", version.timeunit);
625 		return WTAP_OPEN_ERROR;
626 	}
627 
628 	/* Set encap type before reading header records because the
629 	 * header record may change encap type.
630 	 */
631 	wth->file_encap = sniffer_encap[version.network];
632 
633 	/*
634 	 * We don't know how to handle the remaining header record types,
635 	 * so we just skip them - except for REC_HEADER2 records, which
636 	 * we look at, for "Internetwork analyzer" captures, to attempt to
637 	 * determine what the link-layer encapsulation is.
638 	 *
639 	 * XXX - in some version 1.16 internetwork analyzer files
640 	 * generated by the Windows Sniffer when saving Windows
641 	 * Sniffer files as DOS Sniffer files, there's no REC_HEADER2
642 	 * record, but the first "rsvd" word is 1 for PRI ISDN files, 2
643 	 * for BRI ISDN files, and 0 for non-ISDN files; is that something
644 	 * the DOS Sniffer understands?
645 	 */
646 	maj_vers = pletoh16(&version.maj_vers);
647 	if (process_header_records(wth, err, err_info, maj_vers,
648 	    version.network) < 0)
649 		return WTAP_OPEN_ERROR;
650 	if ((version.network == NETWORK_SYNCHRO ||
651 	    version.network == NETWORK_ASYNC) &&
652 	    wth->file_encap == WTAP_ENCAP_PER_PACKET) {
653 		/*
654 		 * Well, we haven't determined the internetwork analyzer
655 		 * subtype yet...
656 		 */
657 		switch (maj_vers) {
658 
659 		case 1:
660 			/*
661 			 * ... and this is a version 1 capture; look
662 			 * at the first "rsvd" word.
663 			 */
664 			switch (pletoh16(&version.rsvd[0])) {
665 
666 			case 1:
667 			case 2:
668 				wth->file_encap = WTAP_ENCAP_ISDN;
669 				break;
670 			}
671 			break;
672 
673 		case 3:
674 			/*
675 			 * ...and this is a version 3 capture; we've
676 			 * seen nothing in those that obviously
677 			 * indicates the capture type, but the only
678 			 * one we've seen is a Frame Relay capture,
679 			 * so mark it as Frame Relay for now.
680 			 */
681 			wth->file_encap = WTAP_ENCAP_FRELAY_WITH_PHDR;
682 			break;
683 		}
684 	}
685 
686 	current_offset = file_tell(wth->fh);
687 
688 	/*
689 	 * Now, if we have a random stream open, position it to the same
690 	 * location, which should be the beginning of the real data, and
691 	 * should be the beginning of the compressed data.
692 	 *
693 	 * XXX - will we see any records other than REC_FRAME2, REC_FRAME4,
694 	 * or REC_EOF after this?  If not, we can get rid of the loop in
695 	 * "ngsniffer_read()".
696 	 */
697 	if (wth->random_fh != NULL) {
698 		if (file_seek(wth->random_fh, current_offset, SEEK_SET, err) == -1)
699 			return WTAP_OPEN_ERROR;
700 	}
701 
702 	/* This is a ngsniffer file */
703 	ngsniffer = g_new(ngsniffer_t, 1);
704 	wth->priv = (void *)ngsniffer;
705 
706 	/* compressed or uncompressed Sniffer file? */
707 	if (version.format != 1) {
708 		wth->file_type_subtype = ngsniffer_compressed_file_type_subtype;
709 		ngsniffer->is_compressed = TRUE;
710 	} else {
711 		wth->file_type_subtype = ngsniffer_uncompressed_file_type_subtype;
712 		ngsniffer->is_compressed = FALSE;
713 	}
714 
715 	ngsniffer->maj_vers = maj_vers;
716 	ngsniffer->min_vers = pletoh16(&version.min_vers);
717 
718 	/* We haven't allocated any uncompression buffers yet. */
719 	ngsniffer->seq.buf = NULL;
720 	ngsniffer->seq.nbytes = 0;
721 	ngsniffer->seq.nextout = 0;
722 	ngsniffer->rand.buf = NULL;
723 	ngsniffer->rand.nbytes = 0;
724 	ngsniffer->rand.nextout = 0;
725 
726 	/* Set the current file offset; the offset in the compressed file
727 	   and in the uncompressed data stream currently the same. */
728 	ngsniffer->seq.uncomp_offset = current_offset;
729 	ngsniffer->seq.comp_offset = current_offset;
730 	ngsniffer->rand.uncomp_offset = current_offset;
731 	ngsniffer->rand.comp_offset = current_offset;
732 
733 	/* We don't yet have any list of compressed blobs. */
734 	ngsniffer->first_blob = NULL;
735 	ngsniffer->last_blob = NULL;
736 	ngsniffer->current_blob = NULL;
737 
738 	wth->subtype_read = ngsniffer_read;
739 	wth->subtype_seek_read = ngsniffer_seek_read;
740 	wth->subtype_sequential_close = ngsniffer_sequential_close;
741 	wth->subtype_close = ngsniffer_close;
742 	wth->snapshot_length = 0;	/* not available in header, only in frame */
743 	ngsniffer->timeunit = Psec[version.timeunit];
744 	ngsniffer->network = version.network;
745 
746 	/* Get capture start time */
747 	start_date = pletoh16(&version.date);
748 	tm.tm_year = ((start_date&DOS_YEAR_MASK)>>DOS_YEAR_SHIFT) + DOS_YEAR_OFFSET;
749 	tm.tm_mon = ((start_date&DOS_MONTH_MASK)>>DOS_MONTH_SHIFT) + DOS_MONTH_OFFSET;
750 	tm.tm_mday = ((start_date&DOS_DAY_MASK)>>DOS_DAY_SHIFT);
751 	/*
752 	 * The time does not appear to act as an offset; only the date.
753 	 * XXX - sometimes it does appear to act as an offset; is this
754 	 * version-dependent?
755 	 */
756 #if 0
757 	start_time = pletoh16(&version.time_dos);
758 	tm.tm_hour = (start_time&0xf800)>>11;
759 	tm.tm_min = (start_time&0x7e0)>>5;
760 	tm.tm_sec = (start_time&0x1f)<<1;
761 #else
762 	tm.tm_hour = 0;
763 	tm.tm_min = 0;
764 	tm.tm_sec = 0;
765 #endif
766 	tm.tm_isdst = -1;
767 	ngsniffer->start = mktime(&tm);
768 	/*
769 	 * XXX - what if "secs" is -1?  Unlikely,
770 	 * but if the capture was done in a time
771 	 * zone that switches between standard and
772 	 * summer time sometime other than when we
773 	 * do, and thus the time was one that doesn't
774 	 * exist here because a switch from standard
775 	 * to summer time zips over it, it could
776 	 * happen.
777 	 *
778 	 * On the other hand, if the capture was done
779 	 * in a different time zone, this won't work
780 	 * right anyway; unfortunately, the time zone
781 	 * isn't stored in the capture file.
782 	 */
783 
784 	wth->file_tsprec = WTAP_TSPREC_NSEC;	/* XXX */
785 
786 	return WTAP_OPEN_MINE;
787 }
788 
789 static int
process_header_records(wtap * wth,int * err,gchar ** err_info,gint16 maj_vers,guint8 network)790 process_header_records(wtap *wth, int *err, gchar **err_info, gint16 maj_vers,
791     guint8 network)
792 {
793 	char record_type[2];
794 	char record_length[4]; /* only the first 2 bytes are length,
795 				  the last 2 are "reserved" and are thrown away */
796 	guint16 rec_type, rec_length_remaining;
797 	int bytes_to_read;
798 	unsigned char buffer[256];
799 
800 	for (;;) {
801 		if (!wtap_read_bytes_or_eof(wth->fh, record_type, 2, err, err_info)) {
802 			if (*err != 0)
803 				return -1;
804 			return 0;	/* EOF */
805 		}
806 
807 		rec_type = pletoh16(record_type);
808 		if ((rec_type != REC_HEADER1) && (rec_type != REC_HEADER2)
809 			&& (rec_type != REC_HEADER3) && (rec_type != REC_HEADER4)
810 			&& (rec_type != REC_HEADER5) && (rec_type != REC_HEADER6)
811 			&& (rec_type != REC_HEADER7)
812 			&& ((rec_type != REC_V2DESC) || (maj_vers > 2)) ) {
813 			/*
814 			 * Well, this is either some unknown header type
815 			 * (we ignore this case), an uncompressed data
816 			 * frame or the length of a compressed blob
817 			 * which implies data. Seek backwards over the
818 			 * two bytes we read, and return.
819 			 */
820 			if (file_seek(wth->fh, -2, SEEK_CUR, err) == -1)
821 				return -1;
822 			return 0;
823 		}
824 
825 		if (!wtap_read_bytes(wth->fh, record_length, 4,
826 		    err, err_info))
827 			return -1;
828 
829 		rec_length_remaining = pletoh16(record_length);
830 
831 		/*
832 		 * Is this is an "Internetwork analyzer" capture, and
833 		 * is this a REC_HEADER2 record?
834 		 *
835 		 * If so, it appears to specify the particular type
836 		 * of network we're on.
837 		 *
838 		 * XXX - handle sync and async differently?  (E.g.,
839 		 * does this apply only to sync?)
840 		 */
841 		if ((network == NETWORK_SYNCHRO || network == NETWORK_ASYNC) &&
842 		    rec_type == REC_HEADER2) {
843 			/*
844 			 * Yes, get the first up-to-256 bytes of the
845 			 * record data.
846 			 */
847 			bytes_to_read = MIN(rec_length_remaining, (int)sizeof buffer);
848 			if (!wtap_read_bytes(wth->fh, buffer,
849 			    bytes_to_read, err, err_info))
850 				return -1;
851 
852 			switch (maj_vers) {
853 
854 			case 2:
855 				if (process_rec_header2_v2(wth, buffer,
856 				    rec_length_remaining, err, err_info) < 0)
857 					return -1;
858 				break;
859 
860 			case 1:
861 			case 4:
862 			case 5:
863 				if (process_rec_header2_v145(wth, buffer,
864 				    rec_length_remaining, maj_vers, err, err_info) < 0)
865 					return -1;
866 				break;
867 			}
868 
869 			/*
870 			 * Skip the rest of the record.
871 			 */
872 			if (rec_length_remaining > sizeof buffer) {
873 				if (file_seek(wth->fh, rec_length_remaining - sizeof buffer,
874 				    SEEK_CUR, err) == -1)
875 					return -1;
876 			}
877 		} else {
878 			/* Nope, just skip over the data. */
879 			if (file_seek(wth->fh, rec_length_remaining, SEEK_CUR, err) == -1)
880 				return -1;
881 		}
882 	}
883 }
884 
885 static int
process_rec_header2_v2(wtap * wth,unsigned char * buffer,guint16 length,int * err,gchar ** err_info)886 process_rec_header2_v2(wtap *wth, unsigned char *buffer, guint16 length,
887     int *err, gchar **err_info)
888 {
889 	static const char x_25_str[] = "HDLC\nX.25\n";
890 
891 	/*
892 	 * There appears to be a string in a REC_HEADER2 record, with
893 	 * a list of protocols.  In one X.25 capture I've seen, the
894 	 * string was "HDLC\nX.25\nCLNP\nISO_TP\nSESS\nPRES\nVTP\nACSE".
895 	 * Presumably CLNP and everything else is per-packet, but
896 	 * we assume "HDLC\nX.25\n" indicates that it's an X.25 capture.
897 	 */
898 	if (length < sizeof x_25_str - 1) {
899 		/*
900 		 * There's not enough data to compare.
901 		 */
902 		*err = WTAP_ERR_UNSUPPORTED;
903 		*err_info = g_strdup("ngsniffer: WAN capture has too-short protocol list");
904 		return -1;
905 	}
906 
907 	if (strncmp((char *)buffer, x_25_str, sizeof x_25_str - 1) == 0) {
908 		/*
909 		 * X.25.
910 		 */
911 		wth->file_encap = WTAP_ENCAP_LAPB;
912 	} else {
913 		*err = WTAP_ERR_UNSUPPORTED;
914 		*err_info = g_strdup_printf("ngsniffer: WAN capture protocol string %.*s unknown",
915 		    length, buffer);
916 		return -1;
917 	}
918 	return 0;
919 }
920 
921 static int
process_rec_header2_v145(wtap * wth,unsigned char * buffer,guint16 length,gint16 maj_vers,int * err,gchar ** err_info)922 process_rec_header2_v145(wtap *wth, unsigned char *buffer, guint16 length,
923     gint16 maj_vers, int *err, gchar **err_info)
924 {
925 	/*
926 	 * The 5th byte of the REC_HEADER2 record appears to be a
927 	 * network type.
928 	 */
929 	if (length < 5) {
930 		/*
931 		 * There is no 5th byte; give up.
932 		 */
933 		*err = WTAP_ERR_UNSUPPORTED;
934 		*err_info = g_strdup("ngsniffer: WAN capture has no network subtype");
935 		return -1;
936 	}
937 
938 	/*
939 	 * The X.25 captures I've seen have a type of NET_HDLC, and the
940 	 * Sniffer documentation seems to imply that it's used for
941 	 * X.25, although it could be used for other purposes as well.
942 	 *
943 	 * NET_ROUTER is used for all sorts of point-to-point protocols,
944 	 * including ISDN.  It appears, from the documentation, that the
945 	 * Sniffer attempts to infer the particular protocol by looking
946 	 * at the traffic; it's not clear whether it stores in the file
947 	 * an indication of the protocol it inferred was being used.
948 	 *
949 	 * Unfortunately, it also appears that NET_HDLC is used for
950 	 * stuff other than X.25 as well, so we can't just interpret
951 	 * it unconditionally as X.25.
952 	 *
953 	 * For now, we interpret both NET_HDLC and NET_ROUTER as "per-packet
954 	 * encapsulation".  We remember that we saw NET_ROUTER, though,
955 	 * as it appears that we can infer whether a packet is PPP or
956 	 * ISDN based on the channel number subfield of the frame error
957 	 * status bits - if it's 0, it's PPP, otherwise it's ISDN and
958 	 * the channel number indicates which channel it is.  We assume
959 	 * NET_HDLC isn't used for ISDN.
960 	 */
961 	switch (buffer[4]) {
962 
963 	case NET_SDLC:
964 		wth->file_encap = WTAP_ENCAP_SDLC;
965 		break;
966 
967 	case NET_HDLC:
968 		wth->file_encap = WTAP_ENCAP_PER_PACKET;
969 		break;
970 
971 	case NET_FRAME_RELAY:
972 		wth->file_encap = WTAP_ENCAP_FRELAY_WITH_PHDR;
973 		break;
974 
975 	case NET_ROUTER:
976 		/*
977 		 * For most of the version 4 capture files I've seen,
978 		 * 0xfa in buffer[1] means the file is an ISDN capture,
979 		 * but there's one PPP file with 0xfa there; does that
980 		 * mean that the 0xfa has nothing to do with ISDN,
981 		 * or is that just an ISDN file with no D channel
982 		 * packets?  (The channel number is not 0 in any
983 		 * of the packets, so perhaps it is.)
984 		 *
985 		 * For one version 5 ISDN capture I've seen, there's
986 		 * a 0x01 in buffer[6]; none of the non-ISDN version
987 		 * 5 captures have it.
988 		 */
989 		wth->file_encap = WTAP_ENCAP_PER_PACKET;
990 		switch (maj_vers) {
991 
992 		case 4:
993 			if (buffer[1] == 0xfa)
994 				wth->file_encap = WTAP_ENCAP_ISDN;
995 			break;
996 
997 		case 5:
998 			if (length < 7) {
999 				/*
1000 				 * There is no 5th byte; give up.
1001 				 */
1002 				*err = WTAP_ERR_UNSUPPORTED;
1003 				*err_info = g_strdup("ngsniffer: WAN bridge/router capture has no ISDN flag");
1004 				return -1;
1005 			}
1006 			if (buffer[6] == 0x01)
1007 				wth->file_encap = WTAP_ENCAP_ISDN;
1008 			break;
1009 		}
1010 		break;
1011 
1012 	case NET_PPP:
1013 		wth->file_encap = WTAP_ENCAP_PPP_WITH_PHDR;
1014 		break;
1015 
1016 	default:
1017 		/*
1018 		 * Reject these until we can figure them out.
1019 		 */
1020 		*err = WTAP_ERR_UNSUPPORTED;
1021 		*err_info = g_strdup_printf("ngsniffer: WAN network subtype %u unknown or unsupported",
1022 		    buffer[4]);
1023 		return -1;
1024 	}
1025 	return 0;
1026 }
1027 
1028 /* Read the next packet */
1029 static gboolean
ngsniffer_read(wtap * wth,wtap_rec * rec,Buffer * buf,int * err,gchar ** err_info,gint64 * data_offset)1030 ngsniffer_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err,
1031     gchar **err_info, gint64 *data_offset)
1032 {
1033 	ngsniffer_t *ngsniffer;
1034 	struct rec_header hdr;
1035 	guint	padding;
1036 
1037 	ngsniffer = (ngsniffer_t *)wth->priv;
1038 	for (;;) {
1039 		/*
1040 		 * We use the uncompressed offset, as that's what
1041 		 * we need to use for compressed files.
1042 		 */
1043 		*data_offset = ngsniffer->seq.uncomp_offset;
1044 
1045 		/*
1046 		 * Read the record header.
1047 		 */
1048 		if (!read_rec_header(wth, FALSE, &hdr, err, err_info)) {
1049 			/* Read error or short read */
1050 			return FALSE;
1051 		}
1052 
1053 		/*
1054 		 * Process the record.
1055 		 */
1056 		switch (hdr.type) {
1057 
1058 		case REC_FRAME2:
1059 		case REC_FRAME4:
1060 		case REC_FRAME6:
1061 			/* Frame record */
1062 			if (!process_frame_record(wth, FALSE, &padding,
1063 			    &hdr, rec, buf, err, err_info)) {
1064 				/* Read error, short read, or other error */
1065 				return FALSE;
1066 			}
1067 
1068 			/*
1069 			 * Skip any extra data in the record.
1070 			 */
1071 			if (padding != 0) {
1072 				if (!ng_skip_bytes_seq(wth, padding, err,
1073 				    err_info))
1074 					return FALSE;
1075 			}
1076 			return TRUE;
1077 
1078 		case REC_EOF:
1079 			/*
1080 			 * End of file.  Skip past any data (if any),
1081 			 * the length of which is in hdr.length, and
1082 			 * return an EOF indication.
1083 			 */
1084 			if (hdr.length != 0) {
1085 				if (!ng_skip_bytes_seq(wth, hdr.length, err,
1086 				    err_info))
1087 					return FALSE;
1088 			}
1089 			*err = 0;	/* EOF, not error */
1090 			return FALSE;
1091 
1092 		default:
1093 			/*
1094 			 * Well, we don't know what it is, or we know what
1095 			 * it is but can't handle it.  Skip past the data
1096 			 * portion (if any), the length of which is in
1097 			 * hdr.length, and keep looping.
1098 			 */
1099 			if (hdr.length != 0) {
1100 				if (!ng_skip_bytes_seq(wth, hdr.length, err,
1101 				    err_info))
1102 					return FALSE;
1103 			}
1104 			break;
1105 		}
1106 	}
1107 }
1108 
1109 static gboolean
ngsniffer_seek_read(wtap * wth,gint64 seek_off,wtap_rec * rec,Buffer * buf,int * err,gchar ** err_info)1110 ngsniffer_seek_read(wtap *wth, gint64 seek_off,
1111     wtap_rec *rec, Buffer *buf, int *err, gchar **err_info)
1112 {
1113 	struct rec_header hdr;
1114 
1115 	if (!ng_file_seek_rand(wth, seek_off, err, err_info))
1116 		return FALSE;
1117 
1118 	if (!read_rec_header(wth, TRUE, &hdr, err, err_info)) {
1119 		/* Read error or short read */
1120 		return FALSE;
1121 	}
1122 
1123 	/*
1124 	 * hdr.type is the record type.
1125 	 */
1126 	switch (hdr.type) {
1127 
1128 	case REC_FRAME2:
1129 	case REC_FRAME4:
1130 	case REC_FRAME6:
1131 		/* Frame record */
1132 		if (!process_frame_record(wth, TRUE, NULL, &hdr, rec, buf,
1133 		    err, err_info)) {
1134 			/* Read error, short read, or other error */
1135 			return FALSE;
1136 		}
1137 		break;
1138 
1139 	default:
1140 		/*
1141 		 * Other record type, or EOF.
1142 		 * This "can't happen".
1143 		 */
1144 		ws_assert_not_reached();
1145 		return FALSE;
1146 	}
1147 
1148 	return TRUE;
1149 }
1150 
1151 /*
1152  * Read the record header.
1153  *
1154  * Returns TRUE on success, FALSE on error.
1155  */
1156 static gboolean
read_rec_header(wtap * wth,gboolean is_random,struct rec_header * hdr,int * err,gchar ** err_info)1157 read_rec_header(wtap *wth, gboolean is_random, struct rec_header *hdr,
1158     int *err, gchar **err_info)
1159 {
1160 	char	record_type[2];
1161 	char	record_length[4]; /* only 1st 2 bytes are length */
1162 
1163 	/*
1164 	 * Read the record type.
1165 	 */
1166 	if (!ng_read_bytes_or_eof(wth, record_type, 2, is_random, err, err_info)) {
1167 		if (*err != 0)
1168 			return FALSE;
1169 		/*
1170 		 * End-of-file; construct a fake EOF record.
1171 		 * (A file might have an EOF record at the end, or
1172 		 * it might just come to an end.)
1173 		 * (XXX - is that true of all Sniffer files?)
1174 		 */
1175 		hdr->type = REC_EOF;
1176 		hdr->length = 0;
1177 		return TRUE;
1178 	}
1179 
1180 	/*
1181 	 * Read the record length.
1182 	 */
1183 	if (!ng_read_bytes(wth, record_length, 4, is_random, err, err_info))
1184 		return FALSE;
1185 
1186 	hdr->type = pletoh16(record_type);
1187 	hdr->length = pletoh16(record_length);
1188 	return TRUE;
1189 }
1190 
1191 /*
1192  * Returns TRUE on success, FALSE on error.
1193  * If padding is non-null, sets *padding to the amount of padding at
1194  * the end of the record.
1195  */
1196 static gboolean
process_frame_record(wtap * wth,gboolean is_random,guint * padding,struct rec_header * hdr,wtap_rec * rec,Buffer * buf,int * err,gchar ** err_info)1197 process_frame_record(wtap *wth, gboolean is_random, guint *padding,
1198     struct rec_header *hdr, wtap_rec *rec, Buffer *buf, int *err,
1199     gchar **err_info)
1200 {
1201 	ngsniffer_t *ngsniffer;
1202 	guint	rec_length_remaining;
1203 	struct frame2_rec frame2;
1204 	struct frame4_rec frame4;
1205 	struct frame6_rec frame6;
1206 	guint16	time_low, time_med, true_size, size;
1207 	guint8	time_high, time_day;
1208 	guint64 t, tsecs, tpsecs;
1209 
1210 	rec_length_remaining = hdr->length;
1211 
1212 	/* Initialize - we'll be setting some presence flags below. */
1213 	rec->rec_type = REC_TYPE_PACKET;
1214 	rec->block = wtap_block_create(WTAP_BLOCK_PACKET);
1215 	rec->presence_flags = 0;
1216 
1217 	ngsniffer = (ngsniffer_t *)wth->priv;
1218 	switch (hdr->type) {
1219 
1220 	case REC_FRAME2:
1221 		if (ngsniffer->network == NETWORK_ATM) {
1222 			/*
1223 			 * We shouldn't get a frame2 record in
1224 			 * an ATM capture.
1225 			 */
1226 			*err = WTAP_ERR_BAD_FILE;
1227 			*err_info = g_strdup("ngsniffer: REC_FRAME2 record in an ATM Sniffer file");
1228 			return FALSE;
1229 		}
1230 
1231 		/* Do we have an f_frame2_struct worth of data? */
1232 		if (rec_length_remaining < sizeof frame2) {
1233 			*err = WTAP_ERR_BAD_FILE;
1234 			*err_info = g_strdup("ngsniffer: REC_FRAME2 record length is less than record header length");
1235 			return FALSE;
1236 		}
1237 
1238 		/* Read the f_frame2_struct */
1239 		if (!ng_read_bytes(wth, &frame2, (unsigned int)sizeof frame2,
1240 		   is_random, err, err_info))
1241 			return FALSE;
1242 		time_low = pletoh16(&frame2.time_low);
1243 		time_med = pletoh16(&frame2.time_med);
1244 		time_high = frame2.time_high;
1245 		time_day = frame2.time_day;
1246 		size = pletoh16(&frame2.size);
1247 		true_size = pletoh16(&frame2.true_size);
1248 
1249 		rec_length_remaining -= (guint)sizeof frame2;	/* we already read that much */
1250 
1251 		set_metadata_frame2(wth, rec, &frame2);
1252 		break;
1253 
1254 	case REC_FRAME4:
1255 		if (ngsniffer->network != NETWORK_ATM) {
1256 			/*
1257 			 * We shouldn't get a frame2 record in
1258 			 * a non-ATM capture.
1259 			 */
1260 			*err = WTAP_ERR_BAD_FILE;
1261 			*err_info = g_strdup("ngsniffer: REC_FRAME4 record in a non-ATM Sniffer file");
1262 			return FALSE;
1263 		}
1264 
1265 		/*
1266 		 * XXX - it looks as if some version 4 captures have
1267 		 * a bogus record length, based on the assumption
1268 		 * that the record is a frame2 record, i.e. the length
1269 		 * was calculated based on the record being a frame2
1270 		 * record, so it's too short by (sizeof frame4 - sizeof frame2).
1271 		 */
1272 		if (ngsniffer->maj_vers < 5 && ngsniffer->min_vers >= 95)
1273 			rec_length_remaining += (guint)(sizeof frame4 - sizeof frame2);
1274 
1275 		/* Do we have an f_frame4_struct worth of data? */
1276 		if (rec_length_remaining < sizeof frame4) {
1277 			*err = WTAP_ERR_BAD_FILE;
1278 			*err_info = g_strdup("ngsniffer: REC_FRAME4 record length is less than record header length");
1279 			return FALSE;
1280 		}
1281 
1282 		/* Read the f_frame4_struct */
1283 		if (!ng_read_bytes(wth, &frame4, (unsigned int)sizeof frame4,
1284 		    is_random, err, err_info))
1285 			return FALSE;
1286 		time_low = pletoh16(&frame4.time_low);
1287 		time_med = pletoh16(&frame4.time_med);
1288 		time_high = frame4.time_high;
1289 		time_day = frame4.time_day;
1290 		size = pletoh16(&frame4.size);
1291 		true_size = pletoh16(&frame4.true_size);
1292 
1293 		rec_length_remaining -= (guint)sizeof frame4;	/* we already read that much */
1294 
1295 		set_pseudo_header_frame4(&rec->rec_header.packet_header.pseudo_header, &frame4);
1296 		break;
1297 
1298 	case REC_FRAME6:
1299 		/* Do we have an f_frame6_struct worth of data? */
1300 		if (rec_length_remaining < sizeof frame6) {
1301 			*err = WTAP_ERR_BAD_FILE;
1302 			*err_info = g_strdup("ngsniffer: REC_FRAME6 record length is less than record header length");
1303 			return FALSE;
1304 		}
1305 
1306 		/* Read the f_frame6_struct */
1307 		if (!ng_read_bytes(wth, &frame6, (unsigned int)sizeof frame6,
1308 		    is_random, err, err_info))
1309 			return FALSE;
1310 		time_low = pletoh16(&frame6.time_low);
1311 		time_med = pletoh16(&frame6.time_med);
1312 		time_high = frame6.time_high;
1313 		time_day = frame6.time_day;
1314 		size = pletoh16(&frame6.size);
1315 		true_size = pletoh16(&frame6.true_size);
1316 
1317 		rec_length_remaining -= (guint)sizeof frame6;	/* we already read that much */
1318 
1319 		set_pseudo_header_frame6(wth, &rec->rec_header.packet_header.pseudo_header, &frame6);
1320 		break;
1321 
1322 	default:
1323 		/*
1324 		 * This should never happen.
1325 		 */
1326 		ws_assert_not_reached();
1327 		return FALSE;
1328 	}
1329 
1330 	/*
1331 	 * Is the frame data size greater than than what's left of the
1332 	 * record?
1333 	 */
1334 	if (size > rec_length_remaining) {
1335 		/*
1336 		 * Yes - treat this as an error.
1337 		 */
1338 		*err = WTAP_ERR_BAD_FILE;
1339 		*err_info = g_strdup("ngsniffer: Record length is less than packet size");
1340 		return FALSE;
1341 	}
1342 
1343 	/*
1344 	 * The maximum value of length is 65535, which is less than
1345 	 * WTAP_MAX_PACKET_SIZE_STANDARD will ever be, so we don't need to check
1346 	 * it.
1347 	 */
1348 	if (padding != NULL) {
1349 		/*
1350 		 * Padding, if the frame data size is less than what's
1351 		 * left of the record.
1352 		 */
1353 		*padding = rec_length_remaining - size;
1354 	}
1355 
1356 	rec->presence_flags |= true_size ? WTAP_HAS_TS|WTAP_HAS_CAP_LEN : WTAP_HAS_TS;
1357 	rec->rec_header.packet_header.len = true_size ? true_size : size;
1358 	rec->rec_header.packet_header.caplen = size;
1359 
1360 	/*
1361 	 * Read the packet data.
1362 	 */
1363 	ws_buffer_assure_space(buf, size);
1364 	if (!ng_read_bytes(wth, ws_buffer_start_ptr(buf), size, is_random,
1365 	    err, err_info))
1366 		return FALSE;
1367 
1368 	rec->rec_header.packet_header.pkt_encap = fix_pseudo_header(wth->file_encap,
1369 	    buf, size, &rec->rec_header.packet_header.pseudo_header);
1370 
1371 	/*
1372 	 * 40-bit time stamp, in units of timeunit picoseconds.
1373 	 */
1374 	t = (((guint64)time_high)<<32) | (((guint64)time_med) << 16) | time_low;
1375 
1376 	/*
1377 	 * timeunit is always < 2^(64-40), so t * timeunit fits in 64
1378 	 * bits.  That gives a 64-bit time stamp, in units of
1379 	 * picoseconds.
1380 	 */
1381 	t *= ngsniffer->timeunit;
1382 
1383 	/*
1384 	 * Convert to seconds and picoseconds.
1385 	 */
1386 	tsecs = t/G_GUINT64_CONSTANT(1000000000000);
1387 	tpsecs = t - tsecs*G_GUINT64_CONSTANT(1000000000000);
1388 
1389 	/*
1390 	 * Add in the time_day value (86400 seconds/day).
1391 	 */
1392 	tsecs += time_day*86400;
1393 
1394 	/*
1395 	 * Add in the capture start time.
1396 	 */
1397 	tsecs += ngsniffer->start;
1398 
1399 	rec->ts.secs = (time_t)tsecs;
1400 	rec->ts.nsecs = (int)(tpsecs/1000);	/* psecs to nsecs */
1401 
1402 	return TRUE;	/* success */
1403 }
1404 
1405 static void
set_metadata_frame2(wtap * wth,wtap_rec * rec,struct frame2_rec * frame2)1406 set_metadata_frame2(wtap *wth, wtap_rec *rec, struct frame2_rec *frame2)
1407 {
1408 	ngsniffer_t *ngsniffer;
1409 	guint32 pack_flags;
1410 	union wtap_pseudo_header *pseudo_header;
1411 
1412 	ngsniffer = (ngsniffer_t *)wth->priv;
1413 
1414 	/*
1415 	 * In one PPP "Internetwork analyzer" capture:
1416 	 *
1417 	 *	The only bit seen in "frame2.fs" is the 0x80 bit, which
1418 	 *	probably indicates the packet's direction; all other
1419 	 *	bits were zero.  The Expert Sniffer Network Analyzer
1420 	 *	5.50 Operations manual says that bit is the FS_DTE bit
1421 	 *	for async/PPP data.  The other bits are error bits
1422 	 *	plus bits indicating whether the frame is PPP or SLIP,
1423 	 *	but the PPP bit isn't set.
1424 	 *
1425 	 *	All bits in "frame2.flags" were zero.
1426 	 *
1427 	 * In one X.25 "Internetwork analyzer" capture:
1428 	 *
1429 	 *	The only bit seen in "frame2.fs" is the 0x80 bit, which
1430 	 *	probably indicates the packet's direction; all other
1431 	 *	bits were zero.
1432 	 *
1433 	 *	"frame2.flags" was always 0x18; however, the Sniffer
1434 	 *	manual says that just means that a display filter was
1435 	 *	calculated for the frame, and it should be displayed,
1436 	 *	so perhaps that's just a quirk of that particular capture.
1437 	 *
1438 	 * In one Ethernet capture:
1439 	 *
1440 	 *	"frame2.fs" was always 0; the Sniffer manual says they're
1441 	 *	error bits of various sorts.
1442 	 *
1443 	 *	"frame2.flags" was either 0 or 0x18, with no obvious
1444 	 *	correlation with anything.  See previous comment
1445 	 *	about display filters.
1446 	 *
1447 	 * In one Token Ring capture:
1448 	 *
1449 	 *	"frame2.fs" was either 0 or 0xcc; the Sniffer manual says
1450 	 *	nothing about those bits for Token Ring captures.
1451 	 *
1452 	 *	"frame2.flags" was either 0 or 0x18, with no obvious
1453 	 *	correlation with anything.  See previous comment
1454 	 *	about display filters.
1455 	 */
1456 	switch (ngsniffer->network) {
1457 
1458 	case NETWORK_ENET:
1459 		pack_flags = 0;
1460 		if (frame2->fs & FS_ETH_CRC)
1461 			pack_flags |= PACK_FLAGS_CRC_ERROR;
1462 		if (frame2->fs & FS_ETH_ALIGN)
1463 			pack_flags |= PACK_FLAGS_UNALIGNED_FRAME;
1464 		if (frame2->fs & FS_ETH_RUNT)
1465 			pack_flags |= PACK_FLAGS_PACKET_TOO_SHORT;
1466 		wtap_block_add_uint32_option(rec->block, OPT_PKT_FLAGS, pack_flags);
1467 		break;
1468 
1469 	case NETWORK_FDDI:
1470 		pack_flags = 0;
1471 		if (!(frame2->fs & FS_FDDI_INVALID) &&
1472 		    (frame2->fs & (FS_FDDI_PCI_CRC|FS_FDDI_ISA_CRC)))
1473 			pack_flags |= PACK_FLAGS_CRC_ERROR;
1474 		wtap_block_add_uint32_option(rec->block, OPT_PKT_FLAGS, pack_flags);
1475 		break;
1476 
1477 	case NETWORK_SYNCHRO:
1478 		pack_flags = 0;
1479 		if (frame2->fs & FS_SYNC_CRC)
1480 			pack_flags |= PACK_FLAGS_CRC_ERROR;
1481 		wtap_block_add_uint32_option(rec->block, OPT_PKT_FLAGS, pack_flags);
1482 		break;
1483 	}
1484 
1485 	pseudo_header = &rec->rec_header.packet_header.pseudo_header;
1486 	switch (wth->file_encap) {
1487 
1488 	case WTAP_ENCAP_ETHERNET:
1489 		/*
1490 		 * XXX - do we ever have an FCS?  If not, why do we often
1491 		 * have 4 extra bytes of stuff at the end?  Do some
1492 		 * PC Ethernet interfaces report the length including the
1493 		 * FCS but not store the FCS in the packet, or do some
1494 		 * Ethernet drivers work that way?
1495 		 */
1496 		pseudo_header->eth.fcs_len = 0;
1497 		break;
1498 
1499 	case WTAP_ENCAP_PPP_WITH_PHDR:
1500 	case WTAP_ENCAP_SDLC:
1501 		pseudo_header->p2p.sent = (frame2->fs & FS_WAN_DTE) ? TRUE : FALSE;
1502 		break;
1503 
1504 	case WTAP_ENCAP_LAPB:
1505 	case WTAP_ENCAP_FRELAY_WITH_PHDR:
1506 	case WTAP_ENCAP_PER_PACKET:
1507 		pseudo_header->dte_dce.flags = (frame2->fs & FS_WAN_DTE) ? 0x00 : FROM_DCE;
1508 		break;
1509 
1510 	case WTAP_ENCAP_ISDN:
1511 		pseudo_header->isdn.uton = (frame2->fs & FS_WAN_DTE) ? FALSE : TRUE;
1512 		switch (frame2->fs & FS_ISDN_CHAN_MASK) {
1513 
1514 		case FS_ISDN_CHAN_D:
1515 			pseudo_header->isdn.channel = 0;	/* D-channel */
1516 			break;
1517 
1518 		case FS_ISDN_CHAN_B1:
1519 			pseudo_header->isdn.channel = 1;	/* B1-channel */
1520 			break;
1521 
1522 		case FS_ISDN_CHAN_B2:
1523 			pseudo_header->isdn.channel = 2;	/* B2-channel */
1524 			break;
1525 
1526 		default:
1527 			pseudo_header->isdn.channel = 30;	/* XXX */
1528 			break;
1529 		}
1530 	}
1531 }
1532 
1533 static void
set_pseudo_header_frame4(union wtap_pseudo_header * pseudo_header,struct frame4_rec * frame4)1534 set_pseudo_header_frame4(union wtap_pseudo_header *pseudo_header,
1535     struct frame4_rec *frame4)
1536 {
1537 	guint32 StatusWord;
1538 	guint8 aal_type, hl_type;
1539 	guint16 vpi, vci;
1540 
1541 	/*
1542 	 * Map flags from frame4.atm_info.StatusWord.
1543 	 */
1544 	pseudo_header->atm.flags = 0;
1545 	StatusWord = pletoh32(&frame4->atm_info.StatusWord);
1546 	if (StatusWord & SW_RAW_CELL)
1547 		pseudo_header->atm.flags |= ATM_RAW_CELL;
1548 
1549 	aal_type = frame4->atm_info.AppTrafType & ATT_AALTYPE;
1550 	hl_type = frame4->atm_info.AppTrafType & ATT_HLTYPE;
1551 	vpi = pletoh16(&frame4->atm_info.Vpi);
1552 	vci = pletoh16(&frame4->atm_info.Vci);
1553 
1554 	switch (aal_type) {
1555 
1556 	case ATT_AAL_UNKNOWN:
1557 		/*
1558 		 * Map ATT_AAL_UNKNOWN on VPI 0, VCI 5 to ATT_AAL_SIGNALLING,
1559 		 * as that's the VPCI used for signalling.
1560 		 *
1561 		 * XXX - is this necessary, or will frames to 0/5 always
1562 		 * have ATT_AAL_SIGNALLING?
1563 		 */
1564 		if (vpi == 0 && vci == 5)
1565 			pseudo_header->atm.aal = AAL_SIGNALLING;
1566 		else
1567 			pseudo_header->atm.aal = AAL_UNKNOWN;
1568 		pseudo_header->atm.type = TRAF_UNKNOWN;
1569 		pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1570 		break;
1571 
1572 	case ATT_AAL1:
1573 		pseudo_header->atm.aal = AAL_1;
1574 		pseudo_header->atm.type = TRAF_UNKNOWN;
1575 		pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1576 		break;
1577 
1578 	case ATT_AAL3_4:
1579 		pseudo_header->atm.aal = AAL_3_4;
1580 		pseudo_header->atm.type = TRAF_UNKNOWN;
1581 		pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1582 		break;
1583 
1584 	case ATT_AAL5:
1585 		pseudo_header->atm.aal = AAL_5;
1586 		switch (hl_type) {
1587 
1588 		case ATT_HL_UNKNOWN:
1589 			pseudo_header->atm.type = TRAF_UNKNOWN;
1590 			pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1591 			break;
1592 
1593 		case ATT_HL_LLCMX:
1594 			pseudo_header->atm.type = TRAF_LLCMX;
1595 			pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1596 			break;
1597 
1598 		case ATT_HL_VCMX:
1599 			pseudo_header->atm.type = TRAF_VCMX;
1600 			switch (frame4->atm_info.AppHLType) {
1601 
1602 			case AHLT_UNKNOWN:
1603 				pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1604 				break;
1605 
1606 			case AHLT_VCMX_802_3_FCS:
1607 				pseudo_header->atm.subtype =
1608 				    TRAF_ST_VCMX_802_3_FCS;
1609 				break;
1610 
1611 			case AHLT_VCMX_802_4_FCS:
1612 				pseudo_header->atm.subtype =
1613 				    TRAF_ST_VCMX_802_4_FCS;
1614 				break;
1615 
1616 			case AHLT_VCMX_802_5_FCS:
1617 				pseudo_header->atm.subtype =
1618 				    TRAF_ST_VCMX_802_5_FCS;
1619 				break;
1620 
1621 			case AHLT_VCMX_FDDI_FCS:
1622 				pseudo_header->atm.subtype =
1623 				    TRAF_ST_VCMX_FDDI_FCS;
1624 				break;
1625 
1626 			case AHLT_VCMX_802_6_FCS:
1627 				pseudo_header->atm.subtype =
1628 				    TRAF_ST_VCMX_802_6_FCS;
1629 				break;
1630 
1631 			case AHLT_VCMX_802_3:
1632 				pseudo_header->atm.subtype = TRAF_ST_VCMX_802_3;
1633 				break;
1634 
1635 			case AHLT_VCMX_802_4:
1636 				pseudo_header->atm.subtype = TRAF_ST_VCMX_802_4;
1637 				break;
1638 
1639 			case AHLT_VCMX_802_5:
1640 				pseudo_header->atm.subtype = TRAF_ST_VCMX_802_5;
1641 				break;
1642 
1643 			case AHLT_VCMX_FDDI:
1644 				pseudo_header->atm.subtype = TRAF_ST_VCMX_FDDI;
1645 				break;
1646 
1647 			case AHLT_VCMX_802_6:
1648 				pseudo_header->atm.subtype = TRAF_ST_VCMX_802_6;
1649 				break;
1650 
1651 			case AHLT_VCMX_FRAGMENTS:
1652 				pseudo_header->atm.subtype =
1653 				    TRAF_ST_VCMX_FRAGMENTS;
1654 				break;
1655 
1656 			case AHLT_VCMX_BPDU:
1657 				pseudo_header->atm.subtype = TRAF_ST_VCMX_BPDU;
1658 				break;
1659 
1660 			default:
1661 				pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1662 				break;
1663 			}
1664 			break;
1665 
1666 		case ATT_HL_LANE:
1667 			pseudo_header->atm.type = TRAF_LANE;
1668 			switch (frame4->atm_info.AppHLType) {
1669 
1670 			case AHLT_UNKNOWN:
1671 				pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1672 				break;
1673 
1674 			case AHLT_LANE_LE_CTRL:
1675 				pseudo_header->atm.subtype =
1676 				    TRAF_ST_LANE_LE_CTRL;
1677 				break;
1678 
1679 			case AHLT_LANE_802_3:
1680 				pseudo_header->atm.subtype = TRAF_ST_LANE_802_3;
1681 				break;
1682 
1683 			case AHLT_LANE_802_5:
1684 				pseudo_header->atm.subtype = TRAF_ST_LANE_802_5;
1685 				break;
1686 
1687 			case AHLT_LANE_802_3_MC:
1688 				pseudo_header->atm.subtype =
1689 				    TRAF_ST_LANE_802_3_MC;
1690 				break;
1691 
1692 			case AHLT_LANE_802_5_MC:
1693 				pseudo_header->atm.subtype =
1694 				    TRAF_ST_LANE_802_5_MC;
1695 				break;
1696 
1697 			default:
1698 				pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1699 				break;
1700 			}
1701 			break;
1702 
1703 		case ATT_HL_ILMI:
1704 			pseudo_header->atm.type = TRAF_ILMI;
1705 			pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1706 			break;
1707 
1708 		case ATT_HL_FRMR:
1709 			pseudo_header->atm.type = TRAF_FR;
1710 			pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1711 			break;
1712 
1713 		case ATT_HL_SPANS:
1714 			pseudo_header->atm.type = TRAF_SPANS;
1715 			pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1716 			break;
1717 
1718 		case ATT_HL_IPSILON:
1719 			pseudo_header->atm.type = TRAF_IPSILON;
1720 			switch (frame4->atm_info.AppHLType) {
1721 
1722 			case AHLT_UNKNOWN:
1723 				pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1724 				break;
1725 
1726 			case AHLT_IPSILON_FT0:
1727 				pseudo_header->atm.subtype =
1728 				    TRAF_ST_IPSILON_FT0;
1729 				break;
1730 
1731 			case AHLT_IPSILON_FT1:
1732 				pseudo_header->atm.subtype =
1733 				    TRAF_ST_IPSILON_FT1;
1734 				break;
1735 
1736 			case AHLT_IPSILON_FT2:
1737 				pseudo_header->atm.subtype =
1738 				    TRAF_ST_IPSILON_FT2;
1739 				break;
1740 
1741 			default:
1742 				pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1743 				break;
1744 			}
1745 			break;
1746 
1747 		default:
1748 			pseudo_header->atm.type = TRAF_UNKNOWN;
1749 			pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1750 			break;
1751 		}
1752 		break;
1753 
1754 	case ATT_AAL_USER:
1755 		pseudo_header->atm.aal = AAL_USER;
1756 		pseudo_header->atm.type = TRAF_UNKNOWN;
1757 		pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1758 		break;
1759 
1760 	case ATT_AAL_SIGNALLING:
1761 		pseudo_header->atm.aal = AAL_SIGNALLING;
1762 		pseudo_header->atm.type = TRAF_UNKNOWN;
1763 		pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1764 		break;
1765 
1766 	case ATT_OAMCELL:
1767 		pseudo_header->atm.aal = AAL_OAMCELL;
1768 		pseudo_header->atm.type = TRAF_UNKNOWN;
1769 		pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1770 		break;
1771 
1772 	default:
1773 		pseudo_header->atm.aal = AAL_UNKNOWN;
1774 		pseudo_header->atm.type = TRAF_UNKNOWN;
1775 		pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1776 		break;
1777 	}
1778 	pseudo_header->atm.vpi = vpi;
1779 	pseudo_header->atm.vci = vci;
1780 	pseudo_header->atm.channel = pletoh16(&frame4->atm_info.channel);
1781 	pseudo_header->atm.cells = pletoh16(&frame4->atm_info.cells);
1782 	pseudo_header->atm.aal5t_u2u = pletoh16(&frame4->atm_info.Trailer.aal5t_u2u);
1783 	pseudo_header->atm.aal5t_len = pletoh16(&frame4->atm_info.Trailer.aal5t_len);
1784 	pseudo_header->atm.aal5t_chksum = pntoh32(&frame4->atm_info.Trailer.aal5t_chksum);
1785 }
1786 
1787 static void
set_pseudo_header_frame6(wtap * wth,union wtap_pseudo_header * pseudo_header,struct frame6_rec * frame6 _U_)1788 set_pseudo_header_frame6(wtap *wth, union wtap_pseudo_header *pseudo_header,
1789     struct frame6_rec *frame6 _U_)
1790 {
1791 	/* XXX - Once the frame format is divined, something will most likely go here */
1792 
1793 	switch (wth->file_encap) {
1794 
1795 	case WTAP_ENCAP_ETHERNET:
1796 		/* XXX - is there an FCS? */
1797 		pseudo_header->eth.fcs_len = -1;
1798 		break;
1799 	}
1800 }
1801 
1802 /*
1803  * OK, this capture is from an "Internetwork analyzer", and we either
1804  * didn't see a type 7 record or it had a network type such as NET_HDLC
1805  * that doesn't tell us which *particular* HDLC derivative this is;
1806  * let's look at the first few bytes of the packet, a pointer to which
1807  * was passed to us as an argument, and see whether it looks like PPP,
1808  * Frame Relay, Wellfleet HDLC, Cisco HDLC, or LAPB - or, if it's none
1809  * of those, assume it's LAPD.
1810  *
1811  * (XXX - are there any "Internetwork analyzer" captures that don't
1812  * have type 7 records?  If so, is there some other field that will
1813  * tell us what type of capture it is?)
1814  */
1815 static int
infer_pkt_encap(const guint8 * pd,int len)1816 infer_pkt_encap(const guint8 *pd, int len)
1817 {
1818 	int i;
1819 
1820 	if (len <= 0) {
1821 		/*
1822 		 * Nothing to infer, but it doesn't matter how you
1823 		 * dissect an empty packet.  Let's just say PPP.
1824 		 */
1825 		return WTAP_ENCAP_PPP_WITH_PHDR;
1826 	}
1827 
1828 	if (pd[0] == 0xFF) {
1829 		/*
1830 		 * PPP.  (XXX - check for 0xFF 0x03?)
1831 		 */
1832 		return WTAP_ENCAP_PPP_WITH_PHDR;
1833 	}
1834 
1835 	if (len >= 2) {
1836 		if (pd[0] == 0x07 && pd[1] == 0x03) {
1837 			/*
1838 			 * Wellfleet HDLC.
1839 			 */
1840 			return WTAP_ENCAP_WFLEET_HDLC;
1841 		} else if ((pd[0] == 0x0F && pd[1] == 0x00) ||
1842 			   (pd[0] == 0x8F && pd[1] == 0x00)) {
1843 			/*
1844 			 * Cisco HDLC.
1845 			 */
1846 			return WTAP_ENCAP_CHDLC_WITH_PHDR;
1847 		}
1848 
1849 		/*
1850 		 * Check for Frame Relay.  Look for packets with at least
1851 		 * 3 bytes of header - 2 bytes of DLCI followed by 1 byte
1852 		 * of control, which, for now, we require to be 0x03 (UI),
1853 		 * although there might be other frame types as well.
1854 		 * Scan forward until we see the last DLCI byte, with
1855 		 * the low-order bit being 1, and then check the next
1856 		 * byte, if it exists, to see if it's a control byte.
1857 		 *
1858 		 * XXX - in version 4 and 5 captures, wouldn't this just
1859 		 * have a capture subtype of NET_FRAME_RELAY?  Or is this
1860 		 * here only to handle other versions of the capture
1861 		 * file, where we might just not yet have found where
1862 		 * the subtype is specified in the capture?
1863 		 *
1864 		 * Bay Networks/Nortel Networks had a mechanism in the Optivity
1865 		 * software for some of their routers to save captures
1866 		 * in Sniffer format; they use a version number of 4.9, but
1867 		 * don't put out any header records before the first FRAME2
1868 		 * record. That means we have to use heuristics to guess
1869 		 * what type of packet we have.
1870 		 */
1871 		for (i = 0; i < len && (pd[i] & 0x01) == 0; i++)
1872 			;
1873 		if (i >= len - 1) {
1874 			/*
1875 			 * Either all the bytes have the low-order bit
1876 			 * clear, so we didn't even find the last DLCI
1877 			 * byte, or the very last byte had the low-order
1878 			 * bit set, so, if that's a DLCI, it fills the
1879 			 * buffer, so there is no control byte after
1880 			 * the last DLCI byte.
1881 			 */
1882 			return WTAP_ENCAP_LAPB;
1883 		}
1884 		i++;	/* advance to the byte after the last DLCI byte */
1885 		if (pd[i] == 0x03)
1886 			return WTAP_ENCAP_FRELAY_WITH_PHDR;
1887 	}
1888 
1889 	/*
1890 	 * Assume LAPB, for now.  If we support other HDLC encapsulations,
1891 	 * we can check whether the low-order bit of the first byte is
1892 	 * set (as it should be for LAPB) if no other checks pass.
1893 	 *
1894 	 * Or, if it's truly impossible to distinguish ISDN from non-ISDN
1895 	 * captures, we could assume it's ISDN if it's not anything
1896 	 * else.
1897 	 */
1898 	return WTAP_ENCAP_LAPB;
1899 }
1900 
1901 static int
fix_pseudo_header(int encap,Buffer * buf,int len,union wtap_pseudo_header * pseudo_header)1902 fix_pseudo_header(int encap, Buffer *buf, int len,
1903     union wtap_pseudo_header *pseudo_header)
1904 {
1905 	const guint8 *pd;
1906 
1907 	pd = ws_buffer_start_ptr(buf);
1908 	switch (encap) {
1909 
1910 	case WTAP_ENCAP_PER_PACKET:
1911 		/*
1912 		 * Infer the packet type from the first two bytes.
1913 		 */
1914 		encap = infer_pkt_encap(pd, len);
1915 
1916 		/*
1917 		 * Fix up the pseudo-header to match the new
1918 		 * encapsulation type.
1919 		 */
1920 		switch (encap) {
1921 
1922 		case WTAP_ENCAP_WFLEET_HDLC:
1923 		case WTAP_ENCAP_CHDLC_WITH_PHDR:
1924 		case WTAP_ENCAP_PPP_WITH_PHDR:
1925 			if (pseudo_header->dte_dce.flags == 0)
1926 				pseudo_header->p2p.sent = TRUE;
1927 			else
1928 				pseudo_header->p2p.sent = FALSE;
1929 			break;
1930 
1931 		case WTAP_ENCAP_ISDN:
1932 			if (pseudo_header->dte_dce.flags == 0x00)
1933 				pseudo_header->isdn.uton = FALSE;
1934 			else
1935 				pseudo_header->isdn.uton = TRUE;
1936 
1937 			/*
1938 			 * XXX - this is currently a per-packet
1939 			 * encapsulation type, and we can't determine
1940 			 * whether a capture is an ISDN capture before
1941 			 * seeing any packets, and B-channel PPP packets
1942 			 * look like PPP packets and are given
1943 			 * WTAP_ENCAP_PPP_WITH_PHDR, not WTAP_ENCAP_ISDN,
1944 			 * so we assume this is a D-channel packet and
1945 			 * thus give it a channel number of 0.
1946 			 */
1947 			pseudo_header->isdn.channel = 0;
1948 			break;
1949 		}
1950 		break;
1951 
1952 	case WTAP_ENCAP_ATM_PDUS:
1953 		/*
1954 		 * If the Windows Sniffer writes out one of its ATM
1955 		 * capture files in DOS Sniffer format, it doesn't
1956 		 * distinguish between LE Control and LANE encapsulated
1957 		 * LAN frames, it just marks them as LAN frames,
1958 		 * so we fix that up here.
1959 		 *
1960 		 * I've also seen DOS Sniffer captures claiming that
1961 		 * LANE packets that *don't* start with FF 00 are
1962 		 * marked as LE Control frames, so we fix that up
1963 		 * as well.
1964 		 */
1965 		if (pseudo_header->atm.type == TRAF_LANE && len >= 2) {
1966 			if (pd[0] == 0xff && pd[1] == 0x00) {
1967 				/*
1968 				 * This must be LE Control.
1969 				 */
1970 				pseudo_header->atm.subtype =
1971 				    TRAF_ST_LANE_LE_CTRL;
1972 			} else {
1973 				/*
1974 				 * This can't be LE Control.
1975 				 */
1976 				if (pseudo_header->atm.subtype ==
1977 				    TRAF_ST_LANE_LE_CTRL) {
1978 					/*
1979 					 * XXX - Ethernet or Token Ring?
1980 					 */
1981 					pseudo_header->atm.subtype =
1982 					    TRAF_ST_LANE_802_3;
1983 				}
1984 			}
1985 		}
1986 		break;
1987 	}
1988 	return encap;
1989 }
1990 
1991 /* Throw away the buffers used by the sequential I/O stream, but not
1992    those used by the random I/O stream. */
1993 static void
ngsniffer_sequential_close(wtap * wth)1994 ngsniffer_sequential_close(wtap *wth)
1995 {
1996 	ngsniffer_t *ngsniffer;
1997 
1998 	ngsniffer = (ngsniffer_t *)wth->priv;
1999 	if (ngsniffer->seq.buf != NULL) {
2000 		g_free(ngsniffer->seq.buf);
2001 		ngsniffer->seq.buf = NULL;
2002 	}
2003 }
2004 
2005 static void
free_blob(gpointer data,gpointer user_data _U_)2006 free_blob(gpointer data, gpointer user_data _U_)
2007 {
2008 	g_free(data);
2009 }
2010 
2011 /* Close stuff used by the random I/O stream, if any, and free up any
2012    private data structures.  (If there's a "sequential_close" routine
2013    for a capture file type, it'll be called before the "close" routine
2014    is called, so we don't have to free the sequential buffer here.) */
2015 static void
ngsniffer_close(wtap * wth)2016 ngsniffer_close(wtap *wth)
2017 {
2018 	ngsniffer_t *ngsniffer;
2019 
2020 	ngsniffer = (ngsniffer_t *)wth->priv;
2021 	g_free(ngsniffer->rand.buf);
2022 	g_list_foreach(ngsniffer->first_blob, free_blob, NULL);
2023 	g_list_free(ngsniffer->first_blob);
2024 }
2025 
2026 typedef struct {
2027 	gboolean first_frame;
2028 	time_t start;
2029 } ngsniffer_dump_t;
2030 
2031 static const int wtap_encap[] = {
2032 	-1,		/* WTAP_ENCAP_UNKNOWN -> unsupported */
2033 	1,		/* WTAP_ENCAP_ETHERNET */
2034 	0,		/* WTAP_ENCAP_TOKEN_RING */
2035 	-1,		/* WTAP_ENCAP_SLIP -> unsupported */
2036 	7,		/* WTAP_ENCAP_PPP -> Internetwork analyzer (synchronous) FIXME ! */
2037 	9,		/* WTAP_ENCAP_FDDI */
2038 	9,		/* WTAP_ENCAP_FDDI_BITSWAPPED */
2039 	-1,		/* WTAP_ENCAP_RAW_IP -> unsupported */
2040 	2,		/* WTAP_ENCAP_ARCNET */
2041 	-1,		/* WTAP_ENCAP_ARCNET_LINUX -> unsupported */
2042 	-1,		/* WTAP_ENCAP_ATM_RFC1483 */
2043 	-1,		/* WTAP_ENCAP_LINUX_ATM_CLIP */
2044 	7,		/* WTAP_ENCAP_LAPB -> Internetwork analyzer (synchronous) */
2045 	-1,		/* WTAP_ENCAP_ATM_PDUS */
2046 	-1,		/* WTAP_ENCAP_NULL -> unsupported */
2047 	-1,		/* WTAP_ENCAP_ASCEND -> unsupported */
2048 	-1,		/* WTAP_ENCAP_ISDN -> unsupported */
2049 	-1,		/* WTAP_ENCAP_IP_OVER_FC -> unsupported */
2050 	7,		/* WTAP_ENCAP_PPP_WITH_PHDR -> Internetwork analyzer (synchronous) FIXME ! */
2051 };
2052 #define NUM_WTAP_ENCAPS (sizeof wtap_encap / sizeof wtap_encap[0])
2053 
2054 /* Returns 0 if we could write the specified encapsulation type,
2055    an error indication otherwise. */
2056 static int
ngsniffer_dump_can_write_encap(int encap)2057 ngsniffer_dump_can_write_encap(int encap)
2058 {
2059 	/* Per-packet encapsulations aren't supported. */
2060 	if (encap == WTAP_ENCAP_PER_PACKET)
2061 		return WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
2062 
2063 	if (encap < 0 || (unsigned)encap >= NUM_WTAP_ENCAPS || wtap_encap[encap] == -1)
2064 		return WTAP_ERR_UNWRITABLE_ENCAP;
2065 
2066 	return 0;
2067 }
2068 
2069 /* Returns TRUE on success, FALSE on failure; sets "*err" to an error code on
2070    failure */
2071 static gboolean
ngsniffer_dump_open(wtap_dumper * wdh,int * err,gchar ** err_info _U_)2072 ngsniffer_dump_open(wtap_dumper *wdh, int *err, gchar **err_info _U_)
2073 {
2074 	ngsniffer_dump_t *ngsniffer;
2075 	char buf[6] = {REC_VERS, 0x00, 0x12, 0x00, 0x00, 0x00}; /* version record */
2076 
2077 	/* This is a sniffer file */
2078 	wdh->subtype_write = ngsniffer_dump;
2079 	wdh->subtype_finish = ngsniffer_dump_finish;
2080 
2081 	ngsniffer = g_new(ngsniffer_dump_t, 1);
2082 	wdh->priv = (void *)ngsniffer;
2083 	ngsniffer->first_frame = TRUE;
2084 	ngsniffer->start = 0;
2085 
2086 	/* Write the file header. */
2087 	if (!wtap_dump_file_write(wdh, ngsniffer_magic, sizeof ngsniffer_magic,
2088 				  err))
2089 		return FALSE;
2090 	if (!wtap_dump_file_write(wdh, buf, 6, err))
2091 		return FALSE;
2092 
2093 	return TRUE;
2094 }
2095 
2096 /* Write a record for a packet to a dump file.
2097    Returns TRUE on success, FALSE on failure. */
2098 static gboolean
ngsniffer_dump(wtap_dumper * wdh,const wtap_rec * rec,const guint8 * pd,int * err,gchar ** err_info _U_)2099 ngsniffer_dump(wtap_dumper *wdh, const wtap_rec *rec,
2100 	       const guint8 *pd, int *err, gchar **err_info _U_)
2101 {
2102 	const union wtap_pseudo_header *pseudo_header = &rec->rec_header.packet_header.pseudo_header;
2103 	ngsniffer_dump_t *ngsniffer = (ngsniffer_dump_t *)wdh->priv;
2104 	struct frame2_rec rec_hdr;
2105 	char buf[6];
2106 	time_t tsecs;
2107 	guint64 t;
2108 	guint16 t_low, t_med;
2109 	guint8 t_high;
2110 	struct vers_rec version;
2111 	gint16 maj_vers, min_vers;
2112 	guint16 start_date;
2113 	struct tm *tm;
2114 
2115 	/* We can only write packet records. */
2116 	if (rec->rec_type != REC_TYPE_PACKET) {
2117 		*err = WTAP_ERR_UNWRITABLE_REC_TYPE;
2118 		return FALSE;
2119 	}
2120 
2121 	/*
2122 	 * Make sure this packet doesn't have a link-layer type that
2123 	 * differs from the one for the file.
2124 	 */
2125 	if (wdh->encap != rec->rec_header.packet_header.pkt_encap) {
2126 		*err = WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
2127 		return FALSE;
2128 	}
2129 
2130 	/* The captured length field is 16 bits, so there's a hard
2131 	   limit of 65535. */
2132 	if (rec->rec_header.packet_header.caplen > 65535) {
2133 		*err = WTAP_ERR_PACKET_TOO_LARGE;
2134 		return FALSE;
2135 	}
2136 
2137 	/* Sniffer files have a capture start date in the file header, and
2138 	   have times relative to the beginning of that day in the packet
2139 	   headers; pick the date of the first packet as the capture start
2140 	   date. */
2141 	if (ngsniffer->first_frame) {
2142 		ngsniffer->first_frame=FALSE;
2143 		tm = localtime(&rec->ts.secs);
2144 		if (tm != NULL && tm->tm_year >= DOS_YEAR_OFFSET) {
2145 			start_date = (tm->tm_year - DOS_YEAR_OFFSET) << DOS_YEAR_SHIFT;
2146 			start_date |= (tm->tm_mon - DOS_MONTH_OFFSET) << DOS_MONTH_SHIFT;
2147 			start_date |= tm->tm_mday << DOS_DAY_SHIFT;
2148 			/* record the start date, not the start time */
2149 			ngsniffer->start = rec->ts.secs - (3600*tm->tm_hour + 60*tm->tm_min + tm->tm_sec);
2150 		} else {
2151 			start_date = 0;
2152 			ngsniffer->start = 0;
2153 		}
2154 
2155 		/* "sniffer" version ? */
2156 		maj_vers = 4;
2157 		min_vers = 0;
2158 		version.maj_vers = GUINT16_TO_LE(maj_vers);
2159 		version.min_vers = GUINT16_TO_LE(min_vers);
2160 		version.time_dos = 0;
2161 		version.date = GUINT16_TO_LE(start_date);
2162 		version.type = 4;
2163 		version.network = wtap_encap[wdh->encap];
2164 		version.format = 1;
2165 		version.timeunit = 1; /* 0.838096 */
2166 		version.cmprs_vers = 0;
2167 		version.cmprs_level = 0;
2168 		version.rsvd[0] = 0;
2169 		version.rsvd[1] = 0;
2170 		if (!wtap_dump_file_write(wdh, &version, sizeof version, err))
2171 			return FALSE;
2172 	}
2173 
2174 	buf[0] = REC_FRAME2;
2175 	buf[1] = 0x00;
2176 	buf[2] = (char)((rec->rec_header.packet_header.caplen + sizeof(struct frame2_rec))%256);
2177 	buf[3] = (char)((rec->rec_header.packet_header.caplen + sizeof(struct frame2_rec))/256);
2178 	buf[4] = 0x00;
2179 	buf[5] = 0x00;
2180 	if (!wtap_dump_file_write(wdh, buf, 6, err))
2181 		return FALSE;
2182 	/* Seconds since the start of the capture */
2183 	tsecs = rec->ts.secs - ngsniffer->start;
2184 	/* Extract the number of days since the start of the capture */
2185 	rec_hdr.time_day = (guint8)(tsecs / 86400);	/* # days of capture - 86400 secs/day */
2186 	tsecs -= rec_hdr.time_day * 86400;	/* time within day */
2187 	/* Convert to picoseconds */
2188 	t = tsecs*G_GUINT64_CONSTANT(1000000000000) +
2189 		rec->ts.nsecs*G_GUINT64_CONSTANT(1000);
2190 	/* Convert to units of timeunit = 1 */
2191 	t /= Psec[1];
2192 	t_low = (guint16)((t >> 0) & 0xFFFF);
2193 	t_med = (guint16)((t >> 16) & 0xFFFF);
2194 	t_high = (guint8)((t >> 32) & 0xFF);
2195 	rec_hdr.time_low = GUINT16_TO_LE(t_low);
2196 	rec_hdr.time_med = GUINT16_TO_LE(t_med);
2197 	rec_hdr.time_high = t_high;
2198 	rec_hdr.size = GUINT16_TO_LE(rec->rec_header.packet_header.caplen);
2199 	switch (wdh->encap) {
2200 
2201 	case WTAP_ENCAP_LAPB:
2202 	case WTAP_ENCAP_FRELAY_WITH_PHDR:
2203 		rec_hdr.fs = (pseudo_header->dte_dce.flags & FROM_DCE) ? 0x00 : FS_WAN_DTE;
2204 		break;
2205 
2206 	case WTAP_ENCAP_PPP_WITH_PHDR:
2207 	case WTAP_ENCAP_SDLC:
2208 		rec_hdr.fs = pseudo_header->p2p.sent ? 0x00 : FS_WAN_DTE;
2209 		break;
2210 
2211 	case WTAP_ENCAP_ISDN:
2212 		rec_hdr.fs = pseudo_header->isdn.uton ? FS_WAN_DTE : 0x00;
2213 		switch (pseudo_header->isdn.channel) {
2214 
2215 		case 0:		/* D-channel */
2216 			rec_hdr.fs |= FS_ISDN_CHAN_D;
2217 			break;
2218 
2219 		case 1:		/* B1-channel */
2220 			rec_hdr.fs |= FS_ISDN_CHAN_B1;
2221 			break;
2222 
2223 		case 2:		/* B2-channel */
2224 			rec_hdr.fs |= FS_ISDN_CHAN_B2;
2225 			break;
2226 		}
2227 		break;
2228 
2229 	default:
2230 		rec_hdr.fs = 0;
2231 		break;
2232 	}
2233 	rec_hdr.flags = 0;
2234 	rec_hdr.true_size = rec->rec_header.packet_header.len != rec->rec_header.packet_header.caplen ? GUINT16_TO_LE(rec->rec_header.packet_header.len) : 0;
2235 	rec_hdr.rsvd = 0;
2236 	if (!wtap_dump_file_write(wdh, &rec_hdr, sizeof rec_hdr, err))
2237 		return FALSE;
2238 	if (!wtap_dump_file_write(wdh, pd, rec->rec_header.packet_header.caplen, err))
2239 		return FALSE;
2240 	return TRUE;
2241 }
2242 
2243 /* Finish writing to a dump file.
2244    Returns TRUE on success, FALSE on failure. */
2245 static gboolean
ngsniffer_dump_finish(wtap_dumper * wdh,int * err,gchar ** err_info _U_)2246 ngsniffer_dump_finish(wtap_dumper *wdh, int *err, gchar **err_info _U_)
2247 {
2248 	/* EOF record */
2249 	char buf[6] = {REC_EOF, 0x00, 0x00, 0x00, 0x00, 0x00};
2250 
2251 	if (!wtap_dump_file_write(wdh, buf, 6, err))
2252 		return FALSE;
2253 	return TRUE;
2254 }
2255 
2256 /*
2257    SnifferDecompress() decompresses a blob of compressed data from a
2258    Sniffer(R) capture file.
2259 
2260    This function is Copyright (c) 1999-2999 Tim Farley
2261 
2262    Parameters
2263       inbuf - buffer of compressed bytes from file, not including
2264 	      the preceding length word
2265       inlen - length of inbuf in bytes (max 64k)
2266       outbuf - decompressed contents, could contain a partial Sniffer
2267 	      record at the end.
2268       outlen - length of outbuf.
2269       err - return error code here
2270       err_info - for WTAP_ERR_DECOMPRESS, return descriptive string here
2271 
2272    Return value is the number of bytes in outbuf on return.
2273 */
2274 
2275 /*
2276  * Make sure we have at least "length" bytes remaining
2277  * in the input buffer.
2278  */
2279 #define CHECK_INPUT_POINTER( length ) \
2280 	if ( pin + (length - 1) >= pin_end ) \
2281 	{ \
2282 		*err = WTAP_ERR_DECOMPRESS; \
2283 		*err_info = g_strdup("ngsniffer: Compressed data item goes past the end of the compressed block"); \
2284 		return ( -1 ); \
2285 	}
2286 
2287 /*
2288  * Make sure the byte containing the high order part of a buffer
2289  * offset is present.
2290  *
2291  * If it is, then fetch it and combine it with the low-order part.
2292  */
2293 #define FETCH_OFFSET_HIGH \
2294 	CHECK_INPUT_POINTER( 1 ); \
2295 	offset = code_low + ((unsigned int)(*pin++) << 4) + 3;
2296 
2297 /*
2298  * Make sure the output buffer is big enough to get "length"
2299  * bytes added to it.
2300  */
2301 #define CHECK_OUTPUT_LENGTH( length ) \
2302 	if ( pout + length > pout_end ) \
2303 	{ \
2304 		*err = WTAP_ERR_UNC_OVERFLOW; \
2305 		return ( -1 ); \
2306 	}
2307 
2308 /*
2309  * Make sure we have another byte to fetch, and then fetch it and
2310  * append it to the buffer "length" times.
2311  */
2312 #define APPEND_RLE_BYTE( length ) \
2313 	/* If length would put us past end of output, avoid overflow */ \
2314 	CHECK_OUTPUT_LENGTH( length ); \
2315 	CHECK_INPUT_POINTER( 1 ); \
2316 	memset( pout, *pin++, length ); \
2317 	pout += length;
2318 
2319 /*
2320  * Make sure the specified offset and length refer, in the output
2321  * buffer, to data that's entirely within the part of the output
2322  * buffer that we've already filled in.
2323  *
2324  * Then append the string from the specified offset, with the
2325  * specified length, to the output buffer.
2326  */
2327 #define APPEND_LZW_STRING( offset, length ) \
2328 	/* If length would put us past end of output, avoid overflow */ \
2329 	CHECK_OUTPUT_LENGTH( length ); \
2330 	/* Check if offset would put us back past begin of buffer */ \
2331 	if ( pout - offset < outbuf ) \
2332 	{ \
2333 		*err = WTAP_ERR_DECOMPRESS; \
2334 		*err_info = g_strdup("ngsniffer: LZ77 compressed data has bad offset to string"); \
2335 		return ( -1 ); \
2336 	} \
2337 	/* Check if offset would cause us to copy on top of ourselves */ \
2338 	if ( pout - offset + length > pout ) \
2339 	{ \
2340 		*err = WTAP_ERR_DECOMPRESS; \
2341 		*err_info = g_strdup("ngsniffer: LZ77 compressed data has bad offset to string"); \
2342 		return ( -1 ); \
2343 	} \
2344 	/* Copy the string from previous text to output position, \
2345 	   advance output pointer */ \
2346 	memcpy( pout, pout - offset, length ); \
2347 	pout += length;
2348 
2349 static int
SnifferDecompress(unsigned char * inbuf,size_t inlen,unsigned char * outbuf,size_t outlen,int * err,gchar ** err_info)2350 SnifferDecompress(unsigned char *inbuf, size_t inlen, unsigned char *outbuf,
2351 		  size_t outlen, int *err, gchar **err_info)
2352 {
2353 	unsigned char * pin  = inbuf;
2354 	unsigned char * pout = outbuf;
2355 	unsigned char * pin_end  = pin + inlen;
2356 	unsigned char * pout_end = pout + outlen;
2357 	unsigned int bit_mask;      /* one bit is set in this, to mask with bit_value */
2358 	unsigned int bit_value = 0; /* cache the last 16 coding bits we retrieved */
2359 	unsigned int code_type;     /* encoding type, from high 4 bits of byte */
2360 	unsigned int code_low;      /* other 4 bits from encoding byte */
2361 	int length;		    /* length of RLE sequence or repeated string */
2362 	int offset;		    /* offset of string to repeat */
2363 
2364 	if (inlen > G_MAXUINT16) {
2365 		return ( -1 );
2366 	}
2367 
2368 	bit_mask  = 0;  /* don't have any bits yet */
2369 	/* Process until we've consumed all the input */
2370 	while (pin < pin_end)
2371 	{
2372 		/* Shift down the bit mask we use to see what's encoded */
2373 		bit_mask = bit_mask >> 1;
2374 
2375 		/* If there are no bits left, time to get another 16 bits */
2376 		if ( 0 == bit_mask )
2377 		{
2378 			/* make sure there are at least *three* bytes
2379 			   available - the two bytes of the bit value,
2380 			   plus one byte after it */
2381 			CHECK_INPUT_POINTER( 3 );
2382 			bit_mask  = 0x8000;  /* start with the high bit */
2383 			bit_value = pletoh16(pin);   /* get the next 16 bits */
2384 			pin += 2;          /* skip over what we just grabbed */
2385 		}
2386 
2387 		/* Use the bits in bit_value to see what's encoded and what is raw data */
2388 		if ( !(bit_mask & bit_value) )
2389 		{
2390 			/* bit not set - raw byte we just copy */
2391 
2392 			/* If length would put us past end of output, avoid overflow */
2393 			CHECK_OUTPUT_LENGTH( 1 );
2394 			*(pout++) = *(pin++);
2395 		}
2396 		else
2397 		{
2398 			/* bit set - next item is encoded.  Peel off high nybble
2399 			   of next byte to see the encoding type.  Set aside low
2400 			   nybble while we are at it */
2401 			code_type = (unsigned int) ((*pin) >> 4 ) & 0xF;
2402 			code_low  = (unsigned int) ((*pin) & 0xF );
2403 			pin++;   /* increment over the code byte we just retrieved */
2404 
2405 			/* Based on the code type, decode the compressed string */
2406 			switch ( code_type )
2407 			{
2408 			case 0  :   /* RLE short runs */
2409 				/*
2410 				  Run length is the low nybble of the first code byte.
2411 				  Byte to repeat immediately follows.
2412 				  Total code size: 2 bytes.
2413 				*/
2414 				length = code_low + 3;
2415 
2416 				/* check the length and then, if it's OK,
2417 				   generate the repeated series of bytes */
2418 				APPEND_RLE_BYTE( length );
2419 				break;
2420 			case 1  :   /* RLE long runs */
2421 				/*
2422 				  Low 4 bits of run length is the low nybble of the
2423 				  first code byte, upper 8 bits of run length is in
2424 				  the next byte.
2425 				  Byte to repeat immediately follows.
2426 				  Total code size: 3 bytes.
2427 				*/
2428 				CHECK_INPUT_POINTER( 1 );
2429 				length = code_low + ((unsigned int)(*pin++) << 4) + 19;
2430 
2431 				/* check the length and then, if it's OK,
2432 				   generate the repeated series of bytes */
2433 				APPEND_RLE_BYTE( length );
2434 				break;
2435 			case 2  :   /* LZ77 long strings */
2436 				/*
2437 				  Low 4 bits of offset to string is the low nybble of the
2438 				  first code byte, upper 8 bits of offset is in
2439 				  the next byte.
2440 				  Length of string immediately follows.
2441 				  Total code size: 3 bytes.
2442 				*/
2443 				FETCH_OFFSET_HIGH;
2444 
2445 				/* get length from next byte, make sure it won't overrun buf */
2446 				CHECK_INPUT_POINTER( 1 );
2447 				length = (unsigned int)(*pin++) + 16;
2448 
2449 				/* check the offset and length and then, if
2450 				   they're OK, copy the data */
2451 				APPEND_LZW_STRING( offset, length );
2452 				break;
2453 			default :   /* (3 to 15): LZ77 short strings */
2454 				/*
2455 				  Low 4 bits of offset to string is the low nybble of the
2456 				  first code byte, upper 8 bits of offset is in
2457 				  the next byte.
2458 				  Length of string to repeat is overloaded into code_type.
2459 				  Total code size: 2 bytes.
2460 				*/
2461 				FETCH_OFFSET_HIGH;
2462 
2463 				/* get length from code_type */
2464 				length = code_type;
2465 
2466 				/* check the offset and length and then, if
2467 				   they're OK, copy the data */
2468 				APPEND_LZW_STRING( offset, length );
2469 				break;
2470 			}
2471 		}
2472 	}
2473 
2474 	return (int) ( pout - outbuf );  /* return length of expanded text */
2475 }
2476 
2477 /*
2478  * XXX - is there any guarantee that 65535 bytes is big enough to hold the
2479  * uncompressed data from any blob?
2480  */
2481 #define	OUTBUF_SIZE	65536
2482 #define	INBUF_SIZE	65536
2483 
2484 /* Information about a compressed blob; we save the offset in the
2485    underlying compressed file, and the offset in the uncompressed data
2486    stream, of the blob. */
2487 typedef struct {
2488 	gint64	blob_comp_offset;
2489 	gint64	blob_uncomp_offset;
2490 } blob_info_t;
2491 
2492 static gboolean
ng_read_bytes_or_eof(wtap * wth,void * buffer,unsigned int nbytes,gboolean is_random,int * err,gchar ** err_info)2493 ng_read_bytes_or_eof(wtap *wth, void *buffer, unsigned int nbytes, gboolean is_random,
2494     int *err, gchar **err_info)
2495 {
2496 	ngsniffer_t *ngsniffer;
2497 	FILE_T infile;
2498 	ngsniffer_comp_stream_t *comp_stream;
2499 	unsigned char *outbuffer = (unsigned char *)buffer; /* where to write next decompressed data */
2500 	blob_info_t *blob;
2501 	unsigned int bytes_to_copy;
2502 	unsigned int bytes_left;
2503 
2504 	ngsniffer = (ngsniffer_t *)wth->priv;
2505 	if (is_random) {
2506 		infile = wth->random_fh;
2507 		comp_stream = &ngsniffer->rand;
2508 	} else {
2509 		infile = wth->fh;
2510 		comp_stream = &ngsniffer->seq;
2511 	}
2512 
2513 	if (!ngsniffer->is_compressed) {
2514 		/* Uncompressed - just read bytes */
2515 		if (!wtap_read_bytes_or_eof(infile, buffer, nbytes, err, err_info))
2516 			return FALSE;
2517 		comp_stream->uncomp_offset += nbytes;
2518 		comp_stream->comp_offset += nbytes;
2519 		return TRUE;
2520 	}
2521 
2522 	/*
2523 	 * Compressed.
2524 	 *
2525 	 * Allocate the stream buffer if it hasn't already been allocated.
2526 	 */
2527 	if (comp_stream->buf == NULL) {
2528 		comp_stream->buf = (unsigned char *)g_malloc(OUTBUF_SIZE);
2529 
2530 		if (is_random) {
2531 			/* This is the first read of the random file, so we're at
2532 			   the beginning of the sequence of blobs in the file
2533 			   (as we've not done any random reads yet to move the
2534 			   current position in the random stream); set the
2535 			   current blob to be the first blob. */
2536 			ngsniffer->current_blob = ngsniffer->first_blob;
2537 		} else {
2538 			/* This is the first sequential read; if we also have a
2539 			   random stream open, allocate the first element for the
2540 			   list of blobs, and make it the last element as well. */
2541 			if (wth->random_fh != NULL) {
2542 				ws_assert(ngsniffer->first_blob == NULL);
2543 				blob = g_new(blob_info_t,1);
2544 				blob->blob_comp_offset = comp_stream->comp_offset;
2545 				blob->blob_uncomp_offset = comp_stream->uncomp_offset;
2546 				ngsniffer->first_blob = g_list_append(ngsniffer->first_blob,
2547 								      blob);
2548 				ngsniffer->last_blob = ngsniffer->first_blob;
2549 			}
2550 		}
2551 
2552 		/* Now read the first blob into the buffer. */
2553 		if (!read_blob(infile, comp_stream, err, err_info))
2554 			return FALSE;
2555 	}
2556 	while (nbytes > 0) {
2557 		bytes_left = comp_stream->nbytes - comp_stream->nextout;
2558 		if (bytes_left == 0) {
2559 			/* There's no decompressed stuff left to copy from the current
2560 			   blob; get the next blob. */
2561 
2562 			if (is_random) {
2563 				/* Move to the next blob in the list. */
2564 				ngsniffer->current_blob = g_list_next(ngsniffer->current_blob);
2565 				if (!ngsniffer->current_blob) {
2566 					/*
2567 					 * XXX - this "can't happen"; we should have a
2568 					 * blob for every byte in the file.
2569 					 */
2570 					*err = WTAP_ERR_CANT_SEEK;
2571 					return FALSE;
2572 				}
2573 			} else {
2574 				/* If we also have a random stream open, add a new element,
2575 				   for this blob, to the list of blobs; we know the list is
2576 				   non-empty, as we initialized it on the first sequential
2577 				   read, so we just add the new element at the end, and
2578 				   adjust the pointer to the last element to refer to it. */
2579 				if (wth->random_fh != NULL) {
2580 					blob = g_new(blob_info_t,1);
2581 					blob->blob_comp_offset = comp_stream->comp_offset;
2582 					blob->blob_uncomp_offset = comp_stream->uncomp_offset;
2583 					ngsniffer->last_blob = g_list_append(ngsniffer->last_blob,
2584 									     blob);
2585 				}
2586 			}
2587 
2588 			if (!read_blob(infile, comp_stream, err, err_info))
2589 				return FALSE;
2590 			bytes_left = comp_stream->nbytes - comp_stream->nextout;
2591 		}
2592 
2593 		bytes_to_copy = nbytes;
2594 		if (bytes_to_copy > bytes_left)
2595 			bytes_to_copy = bytes_left;
2596 		memcpy(outbuffer, &comp_stream->buf[comp_stream->nextout],
2597 		       bytes_to_copy);
2598 		nbytes -= bytes_to_copy;
2599 		outbuffer += bytes_to_copy;
2600 		comp_stream->nextout += bytes_to_copy;
2601 		comp_stream->uncomp_offset += bytes_to_copy;
2602 	}
2603 	return TRUE;
2604 }
2605 
2606 static gboolean
ng_read_bytes(wtap * wth,void * buffer,unsigned int nbytes,gboolean is_random,int * err,gchar ** err_info)2607 ng_read_bytes(wtap *wth, void *buffer, unsigned int nbytes, gboolean is_random,
2608     int *err, gchar **err_info)
2609 {
2610 	if (!ng_read_bytes_or_eof(wth, buffer, nbytes, is_random, err, err_info)) {
2611 		/*
2612 		 * In this case, even reading zero bytes, because we're at
2613 		 * the end of the file, is a short read.
2614 		 */
2615 		if (*err == 0)
2616 			*err = WTAP_ERR_SHORT_READ;
2617 		return FALSE;
2618 	}
2619 	return TRUE;
2620 }
2621 
2622 /* Read a blob from a compressed stream.
2623    Return FALSE and set "*err" and "*err_info" on error, otherwise return TRUE. */
2624 static gboolean
read_blob(FILE_T infile,ngsniffer_comp_stream_t * comp_stream,int * err,gchar ** err_info)2625 read_blob(FILE_T infile, ngsniffer_comp_stream_t *comp_stream, int *err,
2626 	  gchar **err_info)
2627 {
2628 	int in_len;
2629 	unsigned short blob_len;
2630 	gint16 blob_len_host;
2631 	gboolean uncompressed;
2632 	unsigned char *file_inbuf;
2633 	int out_len;
2634 
2635 	/* Read one 16-bit word which is length of next compressed blob */
2636 	if (!wtap_read_bytes_or_eof(infile, &blob_len, 2, err, err_info))
2637 		return FALSE;
2638 	comp_stream->comp_offset += 2;
2639 	blob_len_host = pletoh16(&blob_len);
2640 
2641 	/* Compressed or uncompressed? */
2642 	if (blob_len_host < 0) {
2643 		/* Uncompressed blob; blob length is absolute value of the number. */
2644 		in_len = -blob_len_host;
2645 		uncompressed = TRUE;
2646 	} else {
2647 		in_len = blob_len_host;
2648 		uncompressed = FALSE;
2649 	}
2650 
2651 	file_inbuf = (unsigned char *)g_malloc(INBUF_SIZE);
2652 
2653 	/* Read the blob */
2654 	if (!wtap_read_bytes(infile, file_inbuf, in_len, err, err_info)) {
2655 		g_free(file_inbuf);
2656 		return FALSE;
2657 	}
2658 	comp_stream->comp_offset += in_len;
2659 
2660 	if (uncompressed) {
2661 		memcpy(comp_stream->buf, file_inbuf, in_len);
2662 		out_len = in_len;
2663 	} else {
2664 		/* Decompress the blob */
2665 		out_len = SnifferDecompress(file_inbuf, in_len,
2666 					    comp_stream->buf, OUTBUF_SIZE, err,
2667 					    err_info);
2668 		if (out_len < 0) {
2669 			g_free(file_inbuf);
2670 			return FALSE;
2671 		}
2672 	}
2673 
2674 	g_free(file_inbuf);
2675 	comp_stream->nextout = 0;
2676 	comp_stream->nbytes = out_len;
2677 	return TRUE;
2678 }
2679 
2680 /* Skip some number of bytes forward in the sequential stream. */
2681 static gboolean
ng_skip_bytes_seq(wtap * wth,unsigned int count,int * err,gchar ** err_info)2682 ng_skip_bytes_seq(wtap *wth, unsigned int count, int *err, gchar **err_info)
2683 {
2684 	ngsniffer_t *ngsniffer;
2685 	char *buf;
2686 	unsigned int amount_to_read;
2687 
2688 	ngsniffer = (ngsniffer_t *)wth->priv;
2689 
2690 	if (!ngsniffer->is_compressed) {
2691 		/* Uncompressed - just read forward and discard data */
2692 		ngsniffer->seq.uncomp_offset += count;
2693 		return wtap_read_bytes(wth->fh, NULL, count, err, err_info);
2694 	}
2695 
2696 	/*
2697 	 * Compressed.
2698 	 *
2699 	 * Now read and discard "count" bytes.
2700 	 */
2701 	buf = (char *)g_malloc(INBUF_SIZE);
2702 	while (count != 0) {
2703 		if (count > INBUF_SIZE)
2704 			amount_to_read = INBUF_SIZE;
2705 		else
2706 			amount_to_read = count;
2707 
2708 		if (!ng_read_bytes(wth, buf, amount_to_read, FALSE, err, err_info)) {
2709 			g_free(buf);
2710 			return FALSE;	/* error */
2711 		}
2712 
2713 		count -= amount_to_read;
2714 	}
2715 
2716 	g_free(buf);
2717 	return TRUE;
2718 }
2719 
2720 /* Seek to a given offset in the random data stream.
2721 
2722    On compressed files, we see whether we're seeking to a position within
2723    the blob we currently have in memory and, if not, we find in the list
2724    of blobs the last blob that starts at or before the position to which
2725    we're seeking, and read that blob in.  We can then move to the appropriate
2726    position within the blob we have in memory (whether it's the blob we
2727    already had in memory or, if necessary, the one we read in). */
2728 static gboolean
ng_file_seek_rand(wtap * wth,gint64 offset,int * err,gchar ** err_info)2729 ng_file_seek_rand(wtap *wth, gint64 offset, int *err, gchar **err_info)
2730 {
2731 	ngsniffer_t *ngsniffer;
2732 	gint64 delta;
2733 	GList *new_list, *next_list;
2734 	blob_info_t *next_blob, *new_blob;
2735 
2736 	ngsniffer = (ngsniffer_t *)wth->priv;
2737 
2738 	if (!ngsniffer->is_compressed) {
2739 		/* Uncompressed - just seek. */
2740 		if (file_seek(wth->random_fh, offset, SEEK_SET, err) == -1)
2741 			return FALSE;
2742 		return TRUE;
2743 	}
2744 
2745 	/*
2746 	 * Compressed.
2747 	 *
2748 	 * How many *uncompressed* should we move forward or
2749 	 * backward?
2750 	 */
2751 	delta = offset - ngsniffer->rand.uncomp_offset;
2752 
2753 	/* Is the place to which we're seeking within the current buffer, or
2754 	   will we have to read a different blob into the buffer? */
2755 	new_list = NULL;
2756 	if (delta > 0) {
2757 		/* We're going forwards.
2758 		   Is the place to which we're seeking within the current buffer? */
2759 		if ((size_t)(ngsniffer->rand.nextout + delta) >= ngsniffer->rand.nbytes) {
2760 			/* No.  Search for a blob that contains the target
2761 			   offset in the uncompressed byte stream. */
2762 			if (ngsniffer->current_blob == NULL) {
2763 				/* We haven't read anything from the random
2764 				   file yet, so we have no current blob;
2765 				   search all the blobs, starting with
2766 				   the first one. */
2767 				new_list = ngsniffer->first_blob;
2768 			} else {
2769 				/* We're seeking forward, so start searching
2770 				   with the blob after the current one. */
2771 				new_list = g_list_next(ngsniffer->current_blob);
2772 			}
2773 			while (new_list) {
2774 				next_list = g_list_next(new_list);
2775 				if (next_list == NULL) {
2776 					/* No more blobs; the current one is it. */
2777 					break;
2778 				}
2779 
2780 				next_blob = (blob_info_t *)next_list->data;
2781 				/* Does the next blob start after the target offset?
2782 				   If so, the current blob is the one we want. */
2783 				if (next_blob->blob_uncomp_offset > offset)
2784 					break;
2785 
2786 				new_list = next_list;
2787 			}
2788 			if (new_list == NULL) {
2789 				/*
2790 				 * We're seeking past the end of what
2791 				 * we've read so far.
2792 				 */
2793 				*err = WTAP_ERR_CANT_SEEK;
2794 				return FALSE;
2795 			}
2796 		}
2797 	} else if (delta < 0) {
2798 		/* We're going backwards.
2799 		   Is the place to which we're seeking within the current buffer? */
2800 		if (ngsniffer->rand.nextout + delta < 0) {
2801 			/* No.  Search for a blob that contains the target
2802 			   offset in the uncompressed byte stream. */
2803 			if (ngsniffer->current_blob == NULL) {
2804 				/* We haven't read anything from the random
2805 				   file yet, so we have no current blob;
2806 				   search all the blobs, starting with
2807 				   the last one. */
2808 				new_list = ngsniffer->last_blob;
2809 			} else {
2810 				/* We're seeking backward, so start searching
2811 				   with the blob before the current one. */
2812 				new_list = g_list_previous(ngsniffer->current_blob);
2813 			}
2814 			while (new_list) {
2815 				/* Does this blob start at or before the target offset?
2816 				   If so, the current blob is the one we want. */
2817 				new_blob = (blob_info_t *)new_list->data;
2818 				if (new_blob->blob_uncomp_offset <= offset)
2819 					break;
2820 
2821 				/* It doesn't - skip to the previous blob. */
2822 				new_list = g_list_previous(new_list);
2823 			}
2824 			if (new_list == NULL) {
2825 				/*
2826 				 * XXX - shouldn't happen.
2827 				 */
2828 				*err = WTAP_ERR_CANT_SEEK;
2829 				return FALSE;
2830 			}
2831 		}
2832 	}
2833 
2834 	if (new_list != NULL) {
2835 		/* The place to which we're seeking isn't in the current buffer;
2836 		   move to a new blob. */
2837 		new_blob = (blob_info_t *)new_list->data;
2838 
2839 		/* Seek in the compressed file to the offset in the compressed file
2840 		   of the beginning of that blob. */
2841 		if (file_seek(wth->random_fh, new_blob->blob_comp_offset, SEEK_SET, err) == -1)
2842 			return FALSE;
2843 
2844 		/*
2845 		 * Do we have a buffer for the random stream yet?
2846 		 */
2847 		if (ngsniffer->rand.buf == NULL) {
2848 			/*
2849 			 * No - allocate it, as we'll be reading into it.
2850 			 */
2851 			ngsniffer->rand.buf = (unsigned char *)g_malloc(OUTBUF_SIZE);
2852 		}
2853 
2854 		/* Make the blob we found the current one. */
2855 		ngsniffer->current_blob = new_list;
2856 
2857 		/* Now set the current offsets to the offsets of the beginning
2858 		   of the blob. */
2859 		ngsniffer->rand.uncomp_offset = new_blob->blob_uncomp_offset;
2860 		ngsniffer->rand.comp_offset = new_blob->blob_comp_offset;
2861 
2862 		/* Now fill the buffer. */
2863 		if (!read_blob(wth->random_fh, &ngsniffer->rand, err, err_info))
2864 			return FALSE;
2865 
2866 		/* Set "delta" to the amount to move within this blob; it had
2867 		   better be >= 0, and < the amount of uncompressed data in
2868 		   the blob, as otherwise it'd mean we need to seek before
2869 		   the beginning or after the end of this blob. */
2870 		delta = offset - ngsniffer->rand.uncomp_offset;
2871 		ws_assert(delta >= 0 && (unsigned long)delta < ngsniffer->rand.nbytes);
2872 	}
2873 
2874 	/* OK, the place to which we're seeking is in the buffer; adjust
2875 	   "ngsniffer->rand.nextout" to point to the place to which
2876 	   we're seeking, and adjust "ngsniffer->rand.uncomp_offset" to be
2877 	   the destination offset. */
2878 	ngsniffer->rand.nextout += (int) delta;
2879 	ngsniffer->rand.uncomp_offset += delta;
2880 
2881 	return TRUE;
2882 }
2883 
2884 static const struct supported_block_type ngsniffer_uncompressed_blocks_supported[] = {
2885 	/*
2886 	 * We support packet blocks, with no comments or other options.
2887 	 */
2888 	{ WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, NO_OPTIONS_SUPPORTED }
2889 };
2890 
2891 static const struct file_type_subtype_info ngsniffer_uncompressed_info = {
2892 	"Sniffer (DOS)", "ngsniffer", "cap", "enc;trc;fdc;syc",
2893 	FALSE, BLOCKS_SUPPORTED(ngsniffer_uncompressed_blocks_supported),
2894 	ngsniffer_dump_can_write_encap, ngsniffer_dump_open, NULL
2895 };
2896 
2897 static const struct supported_block_type ngsniffer_compressed_blocks_supported[] = {
2898 	/*
2899 	 * We support packet blocks, with no comments or other options.
2900 	 */
2901 	{ WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, NO_OPTIONS_SUPPORTED }
2902 };
2903 
2904 static const struct file_type_subtype_info ngsniffer_compressed_info = {
2905 	"Sniffer (DOS), compressed", "ngsniffer_comp", "cap", "enc;trc;fdc;syc",
2906 	FALSE, BLOCKS_SUPPORTED(ngsniffer_compressed_blocks_supported),
2907 	NULL, NULL, NULL
2908 };
2909 
register_ngsniffer(void)2910 void register_ngsniffer(void)
2911 {
2912 	ngsniffer_uncompressed_file_type_subtype = wtap_register_file_type_subtype(&ngsniffer_uncompressed_info);
2913 	ngsniffer_compressed_file_type_subtype = wtap_register_file_type_subtype(&ngsniffer_compressed_info);
2914 
2915 	/*
2916 	 * Register names for backwards compatibility with the
2917 	 * wtap_filetypes table in Lua.
2918 	 */
2919 	wtap_register_backwards_compatibility_lua_name("NGSNIFFER_UNCOMPRESSED",
2920 	    ngsniffer_uncompressed_file_type_subtype);
2921 	wtap_register_backwards_compatibility_lua_name("NGSNIFFER_COMPRESSED",
2922 	    ngsniffer_compressed_file_type_subtype);
2923 }
2924 
2925 /*
2926  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
2927  *
2928  * Local variables:
2929  * c-basic-offset: 8
2930  * tab-width: 8
2931  * indent-tabs-mode: t
2932  * End:
2933  *
2934  * vi: set shiftwidth=8 tabstop=8 noexpandtab:
2935  * :indentSize=8:tabSize=8:noTabs=false:
2936  */
2937