1/*
2 * Copyright (c) 1993, 1994, 1995, 1996, 1997
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the University of California,
13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
16 * written permission.
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20 *
21 * sf-pcap-ng.c - pcap-ng-file-format-specific code from savefile.c
22 */
23
24#ifndef lint
25static const char rcsid[] _U_ =
26    "@(#) $Header$ (LBL)";
27#endif
28
29#ifdef HAVE_CONFIG_H
30#include "config.h"
31#endif
32
33#ifdef WIN32
34#include <pcap-stdinc.h>
35#else /* WIN32 */
36#if HAVE_INTTYPES_H
37#include <inttypes.h>
38#elif HAVE_STDINT_H
39#include <stdint.h>
40#endif
41#ifdef HAVE_SYS_BITYPES_H
42#include <sys/bitypes.h>
43#endif
44#include <sys/types.h>
45#endif /* WIN32 */
46
47#include <errno.h>
48#include <memory.h>
49#include <stdio.h>
50#include <stdlib.h>
51#include <string.h>
52
53#include "pcap-int.h"
54
55#include "pcap-common.h"
56
57#ifdef HAVE_OS_PROTO_H
58#include "os-proto.h"
59#endif
60
61#include "sf-pcap-ng.h"
62
63/*
64 * Block types.
65 */
66
67/*
68 * Common part at the beginning of all blocks.
69 */
70struct block_header {
71	bpf_u_int32	block_type;
72	bpf_u_int32	total_length;
73};
74
75/*
76 * Common trailer at the end of all blocks.
77 */
78struct block_trailer {
79	bpf_u_int32	total_length;
80};
81
82/*
83 * Common options.
84 */
85#define OPT_ENDOFOPT	0	/* end of options */
86#define OPT_COMMENT	1	/* comment string */
87
88/*
89 * Option header.
90 */
91struct option_header {
92	u_short		option_code;
93	u_short		option_length;
94};
95
96/*
97 * Structures for the part of each block type following the common
98 * part.
99 */
100
101/*
102 * Section Header Block.
103 */
104#define BT_SHB			0x0A0D0D0A
105
106struct section_header_block {
107	bpf_u_int32	byte_order_magic;
108	u_short		major_version;
109	u_short		minor_version;
110	u_int64_t	section_length;
111	/* followed by options and trailer */
112};
113
114/*
115 * Byte-order magic value.
116 */
117#define BYTE_ORDER_MAGIC	0x1A2B3C4D
118
119/*
120 * Current version number.  If major_version isn't PCAP_NG_VERSION_MAJOR,
121 * that means that this code can't read the file.
122 */
123#define PCAP_NG_VERSION_MAJOR	1
124
125/*
126 * Interface Description Block.
127 */
128#define BT_IDB			0x00000001
129
130struct interface_description_block {
131	u_short		linktype;
132	u_short		reserved;
133	bpf_u_int32	snaplen;
134	/* followed by options and trailer */
135};
136
137/*
138 * Options in the IDB.
139 */
140#define IF_NAME		2	/* interface name string */
141#define IF_DESCRIPTION	3	/* interface description string */
142#define IF_IPV4ADDR	4	/* interface's IPv4 address and netmask */
143#define IF_IPV6ADDR	5	/* interface's IPv6 address and prefix length */
144#define IF_MACADDR	6	/* interface's MAC address */
145#define IF_EUIADDR	7	/* interface's EUI address */
146#define IF_SPEED	8	/* interface's speed, in bits/s */
147#define IF_TSRESOL	9	/* interface's time stamp resolution */
148#define IF_TZONE	10	/* interface's time zone */
149#define IF_FILTER	11	/* filter used when capturing on interface */
150#define IF_OS		12	/* string OS on which capture on this interface was done */
151#define IF_FCSLEN	13	/* FCS length for this interface */
152#define IF_TSOFFSET	14	/* time stamp offset for this interface */
153
154/*
155 * Enhanced Packet Block.
156 */
157#define BT_EPB			0x00000006
158
159struct enhanced_packet_block {
160	bpf_u_int32	interface_id;
161	bpf_u_int32	timestamp_high;
162	bpf_u_int32	timestamp_low;
163	bpf_u_int32	caplen;
164	bpf_u_int32	len;
165	/* followed by packet data, options, and trailer */
166};
167
168/*
169 * Simple Packet Block.
170 */
171#define BT_SPB			0x00000003
172
173struct simple_packet_block {
174	bpf_u_int32	len;
175	/* followed by packet data and trailer */
176};
177
178/*
179 * Packet Block.
180 */
181#define BT_PB			0x00000002
182
183struct packet_block {
184	u_short		interface_id;
185	u_short		drops_count;
186	bpf_u_int32	timestamp_high;
187	bpf_u_int32	timestamp_low;
188	bpf_u_int32	caplen;
189	bpf_u_int32	len;
190	/* followed by packet data, options, and trailer */
191};
192
193/*
194 * Block cursor - used when processing the contents of a block.
195 * Contains a pointer into the data being processed and a count
196 * of bytes remaining in the block.
197 */
198struct block_cursor {
199	u_char		*data;
200	size_t		data_remaining;
201	bpf_u_int32	block_type;
202};
203
204static int pcap_ng_next_packet(pcap_t *p, struct pcap_pkthdr *hdr,
205    u_char **data);
206
207static int
208read_bytes(FILE *fp, void *buf, size_t bytes_to_read, int fail_on_eof,
209    char *errbuf)
210{
211	size_t amt_read;
212
213	amt_read = fread(buf, 1, bytes_to_read, fp);
214	if (amt_read != bytes_to_read) {
215		if (ferror(fp)) {
216			snprintf(errbuf, PCAP_ERRBUF_SIZE,
217			    "error reading dump file: %s",
218			    pcap_strerror(errno));
219		} else {
220			if (amt_read == 0 && !fail_on_eof)
221				return (0);	/* EOF */
222			snprintf(errbuf, PCAP_ERRBUF_SIZE,
223			    "truncated dump file; tried to read %lu bytes, only got %lu",
224			    (unsigned long)bytes_to_read,
225			    (unsigned long)amt_read);
226		}
227		return (-1);
228	}
229	return (1);
230}
231
232static int
233read_block(FILE *fp, pcap_t *p, struct block_cursor *cursor, char *errbuf)
234{
235	int status;
236	struct block_header bhdr;
237
238	status = read_bytes(fp, &bhdr, sizeof(bhdr), 0, errbuf);
239	if (status <= 0)
240		return (status);	/* error or EOF */
241
242	if (p->sf.swapped) {
243		bhdr.block_type = SWAPLONG(bhdr.block_type);
244		bhdr.total_length = SWAPLONG(bhdr.total_length);
245	}
246
247	/*
248	 * Is this block "too big"?
249	 *
250	 * We choose 16MB as "too big", for now, so that we handle
251	 * "reasonably" large buffers but don't chew up all the
252	 * memory if we read a malformed file.
253	 */
254	if (bhdr.total_length > 16*1024*1024) {
255		snprintf(errbuf, PCAP_ERRBUF_SIZE,
256		    "pcap-ng block size %u > maximum %u",
257		    bhdr.total_length, 16*1024*1024);
258		    return (-1);
259	}
260
261	/*
262	 * Is this block "too small" - i.e., is it shorter than a block
263	 * header plus a block trailer?
264	 */
265	if (bhdr.total_length < sizeof(struct block_header) +
266	    sizeof(struct block_trailer)) {
267		snprintf(errbuf, PCAP_ERRBUF_SIZE,
268		    "block in pcap-ng dump file has a length of %u < %lu",
269		    bhdr.total_length,
270		    (unsigned long)(sizeof(struct block_header) + sizeof(struct block_trailer)));
271		return (-1);
272	}
273
274	/*
275	 * Is the buffer big enough?
276	 */
277	if (p->bufsize < bhdr.total_length) {
278		/*
279		 * No - make it big enough.
280		 */
281		p->buffer = realloc(p->buffer, bhdr.total_length);
282		if (p->buffer == NULL) {
283			snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
284			return (-1);
285		}
286	}
287
288	/*
289	 * Copy the stuff we've read to the buffer, and read the rest
290	 * of the block.
291	 */
292	memcpy(p->buffer, &bhdr, sizeof(bhdr));
293	if (read_bytes(fp, p->buffer + sizeof(bhdr),
294	    bhdr.total_length - sizeof(bhdr), 1, errbuf) == -1)
295		return (-1);
296
297	/*
298	 * Initialize the cursor.
299	 */
300	cursor->data = p->buffer + sizeof(bhdr);
301	cursor->data_remaining = bhdr.total_length - sizeof(bhdr) -
302	    sizeof(struct block_trailer);
303	cursor->block_type = bhdr.block_type;
304	return (1);
305}
306
307static void *
308get_from_block_data(struct block_cursor *cursor, size_t chunk_size,
309    char *errbuf)
310{
311	void *data;
312
313	/*
314	 * Make sure we have the specified amount of data remaining in
315	 * the block data.
316	 */
317	if (cursor->data_remaining < chunk_size) {
318		snprintf(errbuf, PCAP_ERRBUF_SIZE,
319		    "block of type %u in pcap-ng dump file is too short",
320		    cursor->block_type);
321		return (NULL);
322	}
323
324	/*
325	 * Return the current pointer, and skip past the chunk.
326	 */
327	data = cursor->data;
328	cursor->data += chunk_size;
329	cursor->data_remaining -= chunk_size;
330	return (data);
331}
332
333static struct option_header *
334get_opthdr_from_block_data(pcap_t *p, struct block_cursor *cursor, char *errbuf)
335{
336	struct option_header *opthdr;
337
338	opthdr = get_from_block_data(cursor, sizeof(*opthdr), errbuf);
339	if (opthdr == NULL) {
340		/*
341		 * Option header is cut short.
342		 */
343		return (NULL);
344	}
345
346	/*
347	 * Byte-swap it if necessary.
348	 */
349	if (p->sf.swapped) {
350		opthdr->option_code = SWAPSHORT(opthdr->option_code);
351		opthdr->option_length = SWAPSHORT(opthdr->option_length);
352	}
353
354	return (opthdr);
355}
356
357static void *
358get_optvalue_from_block_data(struct block_cursor *cursor,
359    struct option_header *opthdr, char *errbuf)
360{
361	size_t padded_option_len;
362	void *optvalue;
363
364	/* Pad option length to 4-byte boundary */
365	padded_option_len = opthdr->option_length;
366	padded_option_len = ((padded_option_len + 3)/4)*4;
367
368	optvalue = get_from_block_data(cursor, padded_option_len, errbuf);
369	if (optvalue == NULL) {
370		/*
371		 * Option value is cut short.
372		 */
373		return (NULL);
374	}
375
376	return (optvalue);
377}
378
379static int
380process_idb_options(pcap_t *p, struct block_cursor *cursor, u_int *tsresol,
381    u_int64_t *tsoffset, char *errbuf)
382{
383	struct option_header *opthdr;
384	void *optvalue;
385	int saw_tsresol, saw_tsoffset;
386	u_char tsresol_opt;
387	u_int i;
388
389	saw_tsresol = 0;
390	saw_tsoffset = 0;
391	while (cursor->data_remaining != 0) {
392		/*
393		 * Get the option header.
394		 */
395		opthdr = get_opthdr_from_block_data(p, cursor, errbuf);
396		if (opthdr == NULL) {
397			/*
398			 * Option header is cut short.
399			 */
400			return (-1);
401		}
402
403		/*
404		 * Get option value.
405		 */
406		optvalue = get_optvalue_from_block_data(cursor, opthdr,
407		    errbuf);
408		if (optvalue == NULL) {
409			/*
410			 * Option value is cut short.
411			 */
412			return (-1);
413		}
414
415		switch (opthdr->option_code) {
416
417		case OPT_ENDOFOPT:
418			if (opthdr->option_length != 0) {
419				snprintf(errbuf, PCAP_ERRBUF_SIZE,
420				    "Interface Description Block has opt_endofopt option with length %u != 0",
421				    opthdr->option_length);
422				return (-1);
423			}
424			goto done;
425
426		case IF_TSRESOL:
427			if (opthdr->option_length != 1) {
428				snprintf(errbuf, PCAP_ERRBUF_SIZE,
429				    "Interface Description Block has if_tsresol option with length %u != 1",
430				    opthdr->option_length);
431				return (-1);
432			}
433			if (saw_tsresol) {
434				snprintf(errbuf, PCAP_ERRBUF_SIZE,
435				    "Interface Description Block has more than one if_tsresol option");
436				return (-1);
437			}
438			saw_tsresol = 1;
439			tsresol_opt = *(u_int *)optvalue;
440			if (tsresol_opt & 0x80) {
441				/*
442				 * Resolution is negative power of 2.
443				 */
444				*tsresol = 1 << (tsresol_opt & 0x7F);
445			} else {
446				/*
447				 * Resolution is negative power of 10.
448				 */
449				*tsresol = 1;
450				for (i = 0; i < tsresol_opt; i++)
451					*tsresol *= 10;
452			}
453			if (*tsresol == 0) {
454				/*
455				 * Resolution is too high.
456				 */
457				if (tsresol_opt & 0x80) {
458					snprintf(errbuf, PCAP_ERRBUF_SIZE,
459					    "Interface Description Block if_tsresol option resolution 2^-%u is too high",
460					    tsresol_opt & 0x7F);
461				} else {
462					snprintf(errbuf, PCAP_ERRBUF_SIZE,
463					    "Interface Description Block if_tsresol option resolution 10^-%u is too high",
464					    tsresol_opt);
465				}
466				return (-1);
467			}
468			break;
469
470		case IF_TSOFFSET:
471			if (opthdr->option_length != 8) {
472				snprintf(errbuf, PCAP_ERRBUF_SIZE,
473				    "Interface Description Block has if_tsoffset option with length %u != 8",
474				    opthdr->option_length);
475				return (-1);
476			}
477			if (saw_tsoffset) {
478				snprintf(errbuf, PCAP_ERRBUF_SIZE,
479				    "Interface Description Block has more than one if_tsoffset option");
480				return (-1);
481			}
482			saw_tsoffset = 1;
483			memcpy(tsoffset, optvalue, sizeof(*tsoffset));
484			if (p->sf.swapped)
485				*tsoffset = SWAPLL(*tsoffset);
486			break;
487
488		default:
489			break;
490		}
491	}
492
493done:
494	return (0);
495}
496
497/*
498 * Check whether this is a pcap-ng savefile and, if it is, extract the
499 * relevant information from the header.
500 */
501int
502pcap_ng_check_header(pcap_t *p, bpf_u_int32 magic, FILE *fp, char *errbuf)
503{
504	size_t amt_read;
505	bpf_u_int32 total_length;
506	bpf_u_int32 byte_order_magic;
507	struct block_header *bhdrp;
508	struct section_header_block *shbp;
509	int status;
510	struct block_cursor cursor;
511	struct interface_description_block *idbp;
512
513	/*
514	 * Check whether the first 4 bytes of the file are the block
515	 * type for a pcap-ng savefile.
516	 */
517	if (magic != BT_SHB) {
518		/*
519		 * XXX - check whether this looks like what the block
520		 * type would be after being munged by mapping between
521		 * UN*X and DOS/Windows text file format and, if it
522		 * does, look for the byte-order magic number in
523		 * the appropriate place and, if we find it, report
524		 * this as possibly being a pcap-ng file transferred
525		 * between UN*X and Windows in text file format?
526		 */
527		return (0);	/* nope */
528	}
529
530	/*
531	 * OK, they are.  However, that's just \n\r\r\n, so it could,
532	 * conceivably, be an ordinary text file.
533	 *
534	 * It could not, however, conceivably be any other type of
535	 * capture file, so we can read the rest of the putative
536	 * Section Header Block; put the block type in the common
537	 * header, read the rest of the common header and the
538	 * fixed-length portion of the SHB, and look for the byte-order
539	 * magic value.
540	 */
541	amt_read = fread(&total_length, 1, sizeof(total_length), fp);
542	if (amt_read < sizeof(total_length)) {
543		if (ferror(fp)) {
544			snprintf(errbuf, PCAP_ERRBUF_SIZE,
545			    "error reading dump file: %s",
546			    pcap_strerror(errno));
547			return (-1);	/* fail */
548		}
549
550		/*
551		 * Possibly a weird short text file, so just say
552		 * "not pcap-ng".
553		 */
554		return (0);
555	}
556	amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp);
557	if (amt_read < sizeof(byte_order_magic)) {
558		if (ferror(fp)) {
559			snprintf(errbuf, PCAP_ERRBUF_SIZE,
560			    "error reading dump file: %s",
561			    pcap_strerror(errno));
562			return (-1);	/* fail */
563		}
564
565		/*
566		 * Possibly a weird short text file, so just say
567		 * "not pcap-ng".
568		 */
569		return (0);
570	}
571	if (byte_order_magic != BYTE_ORDER_MAGIC) {
572		byte_order_magic = SWAPLONG(byte_order_magic);
573		if (byte_order_magic != BYTE_ORDER_MAGIC) {
574			/*
575			 * Not a pcap-ng file.
576			 */
577			return (0);
578		}
579		p->sf.swapped = 1;
580		total_length = SWAPLONG(total_length);
581	}
582
583	/*
584	 * Check the sanity of the total length.
585	 */
586	if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer)) {
587		snprintf(errbuf, PCAP_ERRBUF_SIZE,
588		    "Section Header Block in pcap-ng dump file has a length of %u < %lu",
589		    total_length,
590		    (unsigned long)(sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer)));
591		return (-1);
592	}
593
594	/*
595	 * Allocate a buffer into which to read blocks.  We default to
596	 * the maximum of:
597	 *
598	 *	the total length of the SHB for which we read the header;
599	 *
600	 *	2K, which should be more than large enough for an Enhanced
601	 *	Packet Block containing a full-size Ethernet frame, and
602	 *	leaving room for some options.
603	 *
604	 * If we find a bigger block, we reallocate the buffer.
605	 */
606	p->bufsize = 2048;
607	if (p->bufsize < total_length)
608		p->bufsize = total_length;
609	p->buffer = malloc(p->bufsize);
610	if (p->buffer == NULL) {
611		snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
612		return (-1);
613	}
614
615	/*
616	 * Copy the stuff we've read to the buffer, and read the rest
617	 * of the SHB.
618	 */
619	bhdrp = (struct block_header *)p->buffer;
620	shbp = (struct section_header_block *)(p->buffer + sizeof(struct block_header));
621	bhdrp->block_type = magic;
622	bhdrp->total_length = total_length;
623	shbp->byte_order_magic = byte_order_magic;
624	if (read_bytes(fp,
625	    p->buffer + (sizeof(magic) + sizeof(total_length) + sizeof(byte_order_magic)),
626	    total_length - (sizeof(magic) + sizeof(total_length) + sizeof(byte_order_magic)),
627	    1, errbuf) == -1)
628		goto fail;
629
630	if (p->sf.swapped) {
631		/*
632		 * Byte-swap the fields we've read.
633		 */
634		shbp->major_version = SWAPSHORT(shbp->major_version);
635		shbp->minor_version = SWAPSHORT(shbp->minor_version);
636
637		/*
638		 * XXX - we don't care about the section length.
639		 */
640	}
641	if (shbp->major_version != PCAP_NG_VERSION_MAJOR) {
642		snprintf(errbuf, PCAP_ERRBUF_SIZE,
643		    "unknown pcap-ng savefile major version number %u",
644		    shbp->major_version);
645		goto fail;
646	}
647	p->sf.version_major = shbp->major_version;
648	p->sf.version_minor = shbp->minor_version;
649
650	/*
651	 * Set the default time stamp resolution and offset.
652	 */
653	p->sf.tsresol = 1000000;	/* microsecond resolution */
654	p->sf.tsscale = 1;		/* multiply by 1 to scale to microseconds */
655	p->sf.tsoffset = 0;		/* absolute timestamps */
656
657	/*
658	 * Now start looking for an Interface Description Block.
659	 */
660	for (;;) {
661		/*
662		 * Read the next block.
663		 */
664		status = read_block(fp, p, &cursor, errbuf);
665		if (status == 0) {
666			/* EOF - no IDB in this file */
667			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
668			    "the capture file has no Interface Description Blocks");
669			goto fail;
670		}
671		if (status == -1)
672			goto fail;	/* error */
673		switch (cursor.block_type) {
674
675		case BT_IDB:
676			/*
677			 * Get a pointer to the fixed-length portion of the
678			 * IDB.
679			 */
680			idbp = get_from_block_data(&cursor, sizeof(*idbp),
681			    errbuf);
682			if (idbp == NULL)
683				goto fail;	/* error */
684
685			/*
686			 * Byte-swap it if necessary.
687			 */
688			if (p->sf.swapped) {
689				idbp->linktype = SWAPSHORT(idbp->linktype);
690				idbp->snaplen = SWAPLONG(idbp->snaplen);
691			}
692
693			/*
694			 * Count this interface.
695			 */
696			p->sf.ifcount++;
697
698			/*
699			 * Now look for various time stamp options, so
700			 * we know how to interpret the time stamps.
701			 */
702			if (process_idb_options(p, &cursor, &p->sf.tsresol,
703			    &p->sf.tsoffset, errbuf) == -1)
704				goto fail;
705
706			/*
707			 * Compute the scaling factor to convert the
708			 * sub-second part of the time stamp to
709			 * microseconds.
710			 */
711			if (p->sf.tsresol > 1000000) {
712				/*
713				 * Higher than microsecond resolution;
714				 * scale down to microseconds.
715				 */
716				p->sf.tsscale = (p->sf.tsresol / 1000000);
717			} else {
718				/*
719				 * Lower than microsecond resolution;
720				 * scale up to microseconds.
721				 */
722				p->sf.tsscale = (1000000 / p->sf.tsresol);
723			}
724			goto done;
725
726		case BT_EPB:
727		case BT_SPB:
728		case BT_PB:
729			/*
730			 * Saw a packet before we saw any IDBs.  That's
731			 * not valid, as we don't know what link-layer
732			 * encapsulation the packet has.
733			 */
734			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
735			    "the capture file has a packet block before any Interface Description Blocks");
736			goto fail;
737
738		default:
739			/*
740			 * Just ignore it.
741			 */
742			break;
743		}
744	}
745
746done:
747	p->tzoff = 0;	/* XXX - not used in pcap */
748	p->snapshot = idbp->snaplen;
749	p->linktype = linktype_to_dlt(idbp->linktype);
750	p->linktype_ext = 0;
751
752	p->sf.next_packet_op = pcap_ng_next_packet;
753
754	return (1);
755
756fail:
757	free(p->buffer);
758	return (-1);
759}
760
761/*
762 * Read and return the next packet from the savefile.  Return the header
763 * in hdr and a pointer to the contents in data.  Return 0 on success, 1
764 * if there were no more packets, and -1 on an error.
765 */
766static int
767pcap_ng_next_packet(pcap_t *p, struct pcap_pkthdr *hdr, u_char **data)
768{
769	struct block_cursor cursor;
770	int status;
771	struct enhanced_packet_block *epbp;
772	struct simple_packet_block *spbp;
773	struct packet_block *pbp;
774	bpf_u_int32 interface_id = 0xFFFFFFFF;
775	struct interface_description_block *idbp;
776	struct section_header_block *shbp;
777	FILE *fp = p->sf.rfile;
778	u_int tsresol;
779	u_int64_t tsoffset;
780	u_int64_t t, sec, frac;
781
782	/*
783	 * Look for an Enhanced Packet Block, a Simple Packet Block,
784	 * or a Packet Block.
785	 */
786	for (;;) {
787		/*
788		 * Read the block type and length; those are common
789		 * to all blocks.
790		 */
791		status = read_block(fp, p, &cursor, p->errbuf);
792		if (status == 0)
793			return (1);	/* EOF */
794		if (status == -1)
795			return (-1);	/* error */
796		switch (cursor.block_type) {
797
798		case BT_EPB:
799			/*
800			 * Get a pointer to the fixed-length portion of the
801			 * EPB.
802			 */
803			epbp = get_from_block_data(&cursor, sizeof(*epbp),
804			    p->errbuf);
805			if (epbp == NULL)
806				return (-1);	/* error */
807
808			/*
809			 * Byte-swap it if necessary.
810			 */
811			if (p->sf.swapped) {
812				/* these were written in opposite byte order */
813				interface_id = SWAPLONG(epbp->interface_id);
814				hdr->caplen = SWAPLONG(epbp->caplen);
815				hdr->len = SWAPLONG(epbp->len);
816				t = ((u_int64_t)SWAPLONG(epbp->timestamp_high)) << 32 |
817				    SWAPLONG(epbp->timestamp_low);
818			} else {
819				interface_id = epbp->interface_id;
820				hdr->caplen = epbp->caplen;
821				hdr->len = epbp->len;
822				t = ((u_int64_t)epbp->timestamp_high) << 32 |
823				    epbp->timestamp_low;
824			}
825			goto found;
826
827		case BT_SPB:
828			/*
829			 * Get a pointer to the fixed-length portion of the
830			 * SPB.
831			 */
832			spbp = get_from_block_data(&cursor, sizeof(*spbp),
833			    p->errbuf);
834			if (spbp == NULL)
835				return (-1);	/* error */
836
837			/*
838			 * SPB packets are assumed to have arrived on
839			 * the first interface.
840			 */
841			interface_id = 0;
842
843			/*
844			 * Byte-swap it if necessary.
845			 */
846			if (p->sf.swapped) {
847				/* these were written in opposite byte order */
848				hdr->len = SWAPLONG(spbp->len);
849			} else
850				hdr->len = spbp->len;
851
852			/*
853			 * The SPB doesn't give the captured length;
854			 * it's the minimum of the snapshot length
855			 * and the packet length.
856			 */
857			hdr->caplen = hdr->len;
858			if (hdr->caplen > p->snapshot)
859				hdr->caplen = p->snapshot;
860			t = 0;	/* no time stamps */
861			goto found;
862
863		case BT_PB:
864			/*
865			 * Get a pointer to the fixed-length portion of the
866			 * PB.
867			 */
868			pbp = get_from_block_data(&cursor, sizeof(*pbp),
869			    p->errbuf);
870			if (pbp == NULL)
871				return (-1);	/* error */
872
873			/*
874			 * Byte-swap it if necessary.
875			 */
876			if (p->sf.swapped) {
877				/* these were written in opposite byte order */
878				interface_id = SWAPSHORT(pbp->interface_id);
879				hdr->caplen = SWAPLONG(pbp->caplen);
880				hdr->len = SWAPLONG(pbp->len);
881				t = ((u_int64_t)SWAPLONG(pbp->timestamp_high)) << 32 |
882				    SWAPLONG(pbp->timestamp_low);
883			} else {
884				interface_id = pbp->interface_id;
885				hdr->caplen = pbp->caplen;
886				hdr->len = pbp->len;
887				t = ((u_int64_t)pbp->timestamp_high) << 32 |
888				    pbp->timestamp_low;
889			}
890			goto found;
891
892		case BT_IDB:
893			/*
894			 * Interface Description Block.  Get a pointer
895			 * to its fixed-length portion.
896			 */
897			idbp = get_from_block_data(&cursor, sizeof(*idbp),
898			    p->errbuf);
899			if (idbp == NULL)
900				return (-1);	/* error */
901
902			/*
903			 * Byte-swap it if necessary.
904			 */
905			if (p->sf.swapped) {
906				idbp->linktype = SWAPSHORT(idbp->linktype);
907				idbp->snaplen = SWAPLONG(idbp->snaplen);
908			}
909
910			/*
911			 * If the link-layer type or snapshot length
912			 * differ from the ones for the first IDB we
913			 * saw, quit.
914			 *
915			 * XXX - just discard packets from those
916			 * interfaces?
917			 */
918			if (p->linktype != idbp->linktype) {
919				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
920				    "an interface has a type %u different from the type of the first interface",
921				    idbp->linktype);
922				return (-1);
923			}
924			if (p->snapshot != idbp->snaplen) {
925				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
926				    "an interface has a snapshot length %u different from the type of the first interface",
927				    idbp->snaplen);
928				return (-1);
929			}
930
931			/*
932			 * Count this interface.
933			 */
934			p->sf.ifcount++;
935
936			/*
937			 * Set the default time stamp resolution and offset.
938			 */
939			tsresol = 1000000;	/* microsecond resolution */
940			tsoffset = 0;		/* absolute timestamps */
941
942			/*
943			 * Now look for various time stamp options, to
944			 * make sure they're the same.
945			 *
946			 * XXX - we could, in theory, handle multiple
947			 * different resolutions and offsets, but we
948			 * don't do so for now.
949			 */
950			if (process_idb_options(p, &cursor, &tsresol, &tsoffset,
951			    p->errbuf) == -1)
952				return (-1);
953			if (tsresol != p->sf.tsresol) {
954				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
955				    "an interface has a time stamp resolution different from the time stamp resolution of the first interface");
956				return (-1);
957			}
958			if (tsoffset != p->sf.tsoffset) {
959				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
960				    "an interface has a time stamp offset different from the time stamp offset of the first interface");
961				return (-1);
962			}
963			break;
964
965		case BT_SHB:
966			/*
967			 * Section Header Block.  Get a pointer
968			 * to its fixed-length portion.
969			 */
970			shbp = get_from_block_data(&cursor, sizeof(*shbp),
971			    p->errbuf);
972			if (shbp == NULL)
973				return (-1);	/* error */
974
975			/*
976			 * Assume the byte order of this section is
977			 * the same as that of the previous section.
978			 * We'll check for that later.
979			 */
980			if (p->sf.swapped) {
981				shbp->byte_order_magic =
982				    SWAPLONG(shbp->byte_order_magic);
983				shbp->major_version =
984				    SWAPSHORT(shbp->major_version);
985			}
986
987			/*
988			 * Make sure the byte order doesn't change;
989			 * pcap_is_swapped() shouldn't change its
990			 * return value in the middle of reading a capture.
991			 */
992			switch (shbp->byte_order_magic) {
993
994			case BYTE_ORDER_MAGIC:
995				/*
996				 * OK.
997				 */
998				break;
999
1000			case SWAPLONG(BYTE_ORDER_MAGIC):
1001				/*
1002				 * Byte order changes.
1003				 */
1004				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1005				    "the file has sections with different byte orders");
1006				return (-1);
1007
1008			default:
1009				/*
1010				 * Not a valid SHB.
1011				 */
1012				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1013				    "the file has a section with a bad byte order magic field");
1014				return (-1);
1015			}
1016
1017			/*
1018			 * Make sure the major version is the version
1019			 * we handle.
1020			 */
1021			if (shbp->major_version != PCAP_NG_VERSION_MAJOR) {
1022				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1023				    "unknown pcap-ng savefile major version number %u",
1024				    shbp->major_version);
1025				return (-1);
1026			}
1027
1028			/*
1029			 * Reset the interface count; this section should
1030			 * have its own set of IDBs.  If any of them
1031			 * don't have the same interface type, snapshot
1032			 * length, or resolution as the first interface
1033			 * we saw, we'll fail.  (And if we don't see
1034			 * any IDBs, we'll fail when we see a packet
1035			 * block.)
1036			 */
1037			p->sf.ifcount = 0;
1038			break;
1039
1040		default:
1041			/*
1042			 * Not a packet block, IDB, or SHB; ignore it.
1043			 */
1044			break;
1045		}
1046	}
1047
1048found:
1049	/*
1050	 * Is the interface ID an interface we know?
1051	 */
1052	if (interface_id >= p->sf.ifcount) {
1053		/*
1054		 * Yes.  Fail.
1055		 */
1056		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1057		    "a packet arrived on interface %u, but there's no Interface Description Block for that interface",
1058		    interface_id);
1059		return (-1);
1060	}
1061
1062	/*
1063	 * Convert the time stamp to a struct timeval.
1064	 */
1065	sec = t / p->sf.tsresol + p->sf.tsoffset;
1066	frac = t % p->sf.tsresol;
1067	if (p->sf.tsresol > 1000000) {
1068		/*
1069		 * Higher than microsecond resolution; scale down to
1070		 * microseconds.
1071		 */
1072		frac /= p->sf.tsscale;
1073	} else {
1074		/*
1075		 * Lower than microsecond resolution; scale up to
1076		 * microseconds.
1077		 */
1078		frac *= p->sf.tsscale;
1079	}
1080	hdr->ts.tv_sec = sec;
1081	hdr->ts.tv_usec = frac;
1082
1083	/*
1084	 * Get a pointer to the packet data.
1085	 */
1086	*data = get_from_block_data(&cursor, hdr->caplen, p->errbuf);
1087	if (*data == NULL)
1088		return (-1);
1089
1090	if (p->sf.swapped) {
1091		/*
1092		 * Convert pseudo-headers from the byte order of
1093		 * the host on which the file was saved to our
1094		 * byte order, as necessary.
1095		 */
1096		switch (p->linktype) {
1097
1098		case DLT_USB_LINUX:
1099			swap_linux_usb_header(hdr, *data, 0);
1100			break;
1101
1102		case DLT_USB_LINUX_MMAPPED:
1103			swap_linux_usb_header(hdr, *data, 1);
1104			break;
1105		}
1106	}
1107
1108	return (0);
1109}
1110