]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/libpcap/sf-pcap-ng.c
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / libpcap / sf-pcap-ng.c
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
25 static 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  */
70 struct 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  */
78 struct 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  */
91 struct 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
106 struct 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
130 struct 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
159 struct 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
173 struct 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
183 struct 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  */
198 struct block_cursor {
199         u_char          *data;
200         size_t          data_remaining;
201         bpf_u_int32     block_type;
202 };
203
204 static int pcap_ng_next_packet(pcap_t *p, struct pcap_pkthdr *hdr,
205     u_char **data);
206
207 static int
208 read_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
232 static int
233 read_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
307 static void *
308 get_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
333 static struct option_header *
334 get_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
357 static void *
358 get_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
379 static int
380 process_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
493 done:
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  */
501 int
502 pcap_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
746 done:
747         p->tzoff = 0;   /* XXX - not used in pcap */
748         p->snapshot = idbp->snaplen;
749         p->linktype = idbp->linktype;
750         p->linktype_ext = 0;
751
752         p->sf.next_packet_op = pcap_ng_next_packet;
753
754         return (1);
755
756 fail:
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  */
766 static int
767 pcap_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         size_t pblock_len;
776         struct interface_description_block *idbp;
777         struct section_header_block *shbp;
778         FILE *fp = p->sf.rfile;
779         u_int tsresol;
780         u_int64_t tsoffset;
781         u_int64_t t, sec, frac;
782
783         /*
784          * Look for an Enhanced Packet Block, a Simple Packet Block,
785          * or a Packet Block.
786          */
787         for (;;) {
788                 /*
789                  * Read the block type and length; those are common
790                  * to all blocks.
791                  */
792                 status = read_block(fp, p, &cursor, p->errbuf);
793                 if (status == 0)
794                         return (1);     /* EOF */
795                 if (status == -1)
796                         return (-1);    /* error */
797                 switch (cursor.block_type) {
798
799                 case BT_EPB:
800                         /*
801                          * Get a pointer to the fixed-length portion of the
802                          * EPB.
803                          */
804                         epbp = get_from_block_data(&cursor, sizeof(*epbp),
805                             p->errbuf);
806                         if (epbp == NULL)
807                                 return (-1);    /* error */
808
809                         /*
810                          * Byte-swap it if necessary.
811                          */
812                         if (p->sf.swapped) {
813                                 /* these were written in opposite byte order */
814                                 interface_id = SWAPLONG(epbp->interface_id);
815                                 hdr->caplen = SWAPLONG(epbp->caplen);
816                                 hdr->len = SWAPLONG(epbp->len);
817                                 t = ((u_int64_t)SWAPLONG(epbp->timestamp_high)) << 32 |
818                                     SWAPLONG(epbp->timestamp_low);
819                         } else {
820                                 interface_id = epbp->interface_id;
821                                 hdr->caplen = epbp->caplen;
822                                 hdr->len = epbp->len;
823                                 t = ((u_int64_t)epbp->timestamp_high) << 32 |
824                                     epbp->timestamp_low;
825                         }
826                         pblock_len = sizeof(*epbp);
827                         goto found;
828                         
829                 case BT_SPB:
830                         /*
831                          * Get a pointer to the fixed-length portion of the
832                          * SPB.
833                          */
834                         spbp = get_from_block_data(&cursor, sizeof(*spbp),
835                             p->errbuf);
836                         if (spbp == NULL)
837                                 return (-1);    /* error */
838
839                         /*
840                          * SPB packets are assumed to have arrived on
841                          * the first interface.
842                          */
843                         interface_id = 0;
844
845                         /*
846                          * Byte-swap it if necessary.
847                          */
848                         if (p->sf.swapped) {
849                                 /* these were written in opposite byte order */
850                                 hdr->len = SWAPLONG(spbp->len);
851                         } else
852                                 hdr->len = spbp->len;
853
854                         /*
855                          * The SPB doesn't give the captured length;
856                          * it's the minimum of the snapshot length
857                          * and the packet length.
858                          */
859                         hdr->caplen = hdr->len;
860                         if (hdr->caplen > p->snapshot)
861                                 hdr->caplen = p->snapshot;
862                         t = 0;  /* no time stamps */
863                         pblock_len = sizeof(*spbp);
864                         goto found;
865
866                 case BT_PB:
867                         /*
868                          * Get a pointer to the fixed-length portion of the
869                          * PB.
870                          */
871                         pbp = get_from_block_data(&cursor, sizeof(*pbp),
872                             p->errbuf);
873                         if (pbp == NULL)
874                                 return (-1);    /* error */
875
876                         /*
877                          * Byte-swap it if necessary.
878                          */
879                         if (p->sf.swapped) {
880                                 /* these were written in opposite byte order */
881                                 interface_id = SWAPSHORT(pbp->interface_id);
882                                 hdr->caplen = SWAPLONG(pbp->caplen);
883                                 hdr->len = SWAPLONG(pbp->len);
884                                 t = ((u_int64_t)SWAPLONG(pbp->timestamp_high)) << 32 |
885                                     SWAPLONG(pbp->timestamp_low);
886                         } else {
887                                 interface_id = pbp->interface_id;
888                                 hdr->caplen = pbp->caplen;
889                                 hdr->len = pbp->len;
890                                 t = ((u_int64_t)pbp->timestamp_high) << 32 |
891                                     pbp->timestamp_low;
892                         }
893                         pblock_len = sizeof(*pbp);
894                         goto found;
895
896                 case BT_IDB:
897                         /*
898                          * Interface Description Block.  Get a pointer
899                          * to its fixed-length portion.
900                          */
901                         idbp = get_from_block_data(&cursor, sizeof(*idbp),
902                             p->errbuf);
903                         if (idbp == NULL)
904                                 return (-1);    /* error */
905
906                         /*
907                          * Byte-swap it if necessary.
908                          */
909                         if (p->sf.swapped) {
910                                 idbp->linktype = SWAPSHORT(idbp->linktype);
911                                 idbp->snaplen = SWAPLONG(idbp->snaplen);
912                         }
913
914                         /*
915                          * If the link-layer type or snapshot length
916                          * differ from the ones for the first IDB we
917                          * saw, quit.
918                          *
919                          * XXX - just discard packets from those
920                          * interfaces?
921                          */
922                         if (p->linktype != idbp->linktype) {
923                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
924                                     "an interface has a type %u different from the type of the first interface",
925                                     idbp->linktype);
926                                 return (-1);
927                         }
928                         if (p->snapshot != idbp->snaplen) {
929                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
930                                     "an interface has a snapshot length %u different from the type of the first interface",
931                                     idbp->snaplen);
932                                 return (-1);
933                         }
934
935                         /*
936                          * Count this interface.
937                          */
938                         p->sf.ifcount++;
939
940                         /*
941                          * Set the default time stamp resolution and offset.
942                          */
943                         tsresol = 1000000;      /* microsecond resolution */
944                         tsoffset = 0;           /* absolute timestamps */
945
946                         /*
947                          * Now look for various time stamp options, to
948                          * make sure they're the same.
949                          *
950                          * XXX - we could, in theory, handle multiple
951                          * different resolutions and offsets, but we
952                          * don't do so for now.
953                          */
954                         if (process_idb_options(p, &cursor, &tsresol, &tsoffset,
955                             p->errbuf) == -1)
956                                 return (-1);
957                         if (tsresol != p->sf.tsresol) {
958                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
959                                     "an interface has a time stamp resolution different from the time stamp resolution of the first interface");
960                                 return (-1);
961                         }
962                         if (tsoffset != p->sf.tsoffset) {
963                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
964                                     "an interface has a time stamp offset different from the time stamp offset of the first interface");
965                                 return (-1);
966                         }
967                         break;
968
969                 case BT_SHB:
970                         /*
971                          * Section Header Block.  Get a pointer
972                          * to its fixed-length portion.
973                          */
974                         shbp = get_from_block_data(&cursor, sizeof(*shbp),
975                             p->errbuf);
976                         if (shbp == NULL)
977                                 return (-1);    /* error */
978
979                         /*
980                          * Assume the byte order of this section is
981                          * the same as that of the previous section.
982                          * We'll check for that later.
983                          */
984                         if (p->sf.swapped) {
985                                 shbp->byte_order_magic =
986                                     SWAPLONG(shbp->byte_order_magic);
987                                 shbp->major_version =
988                                     SWAPSHORT(shbp->major_version);
989                         }
990
991                         /*
992                          * Make sure the byte order doesn't change;
993                          * pcap_is_swapped() shouldn't change its
994                          * return value in the middle of reading a capture.
995                          */
996                         switch (shbp->byte_order_magic) {
997
998                         case BYTE_ORDER_MAGIC:
999                                 /*
1000                                  * OK.
1001                                  */
1002                                 break;
1003
1004                         case SWAPLONG(BYTE_ORDER_MAGIC):
1005                                 /*
1006                                  * Byte order changes.
1007                                  */
1008                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1009                                     "the file has sections with different byte orders");
1010                                 return (-1);
1011
1012                         default:
1013                                 /*
1014                                  * Not a valid SHB.
1015                                  */
1016                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1017                                     "the file has a section with a bad byte order magic field");
1018                                 return (-1);
1019                         }
1020
1021                         /*
1022                          * Make sure the major version is the version
1023                          * we handle.
1024                          */
1025                         if (shbp->major_version != PCAP_NG_VERSION_MAJOR) {
1026                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1027                                     "unknown pcap-ng savefile major version number %u",
1028                                     shbp->major_version);
1029                                 return (-1);
1030                         }
1031
1032                         /*
1033                          * Reset the interface count; this section should
1034                          * have its own set of IDBs.  If any of them
1035                          * don't have the same interface type, snapshot
1036                          * length, or resolution as the first interface
1037                          * we saw, we'll fail.  (And if we don't see
1038                          * any IDBs, we'll fail when we see a packet
1039                          * block.)
1040                          */
1041                         p->sf.ifcount = 0;
1042                         break;
1043
1044                 default:
1045                         /*
1046                          * Not a packet block, IDB, or SHB; ignore it.
1047                          */
1048                         break;
1049                 }                
1050         }
1051
1052 found:
1053         /*
1054          * Is the interface ID an interface we know?
1055          */
1056         if (interface_id > p->sf.ifcount) {
1057                 /*
1058                  * Yes.  Fail.
1059                  */
1060                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1061                     "a packet arrived on interface %u, but there's no Interface Description Block for that interface",
1062                     interface_id);
1063                 return (-1);
1064         }
1065
1066         /*
1067          * Convert the time stamp to a struct timeval.
1068          */
1069         sec = t / p->sf.tsresol + p->sf.tsoffset;
1070         frac = t % p->sf.tsresol;
1071         if (p->sf.tsresol > 1000000) {
1072                 /*
1073                  * Higher than microsecond resolution; scale down to
1074                  * microseconds.
1075                  */
1076                 frac /= p->sf.tsscale;
1077         } else {
1078                 /*
1079                  * Lower than microsecond resolution; scale up to
1080                  * microseconds.
1081                  */
1082                 frac *= p->sf.tsscale;
1083         }
1084         hdr->ts.tv_sec = sec;
1085         hdr->ts.tv_usec = frac;
1086
1087         /*
1088          * Get a pointer to the packet data.
1089          */
1090         *data = get_from_block_data(&cursor, hdr->caplen, p->errbuf);
1091         if (*data == NULL)
1092                 return (-1);
1093
1094         if (p->sf.swapped) {
1095                 /*
1096                  * Convert pseudo-headers from the byte order of
1097                  * the host on which the file was saved to our
1098                  * byte order, as necessary.
1099                  */
1100                 switch (p->linktype) {
1101
1102                 case DLT_USB_LINUX:
1103                         swap_linux_usb_header(hdr, *data, 0);
1104                         break;
1105
1106                 case DLT_USB_LINUX_MMAPPED:
1107                         swap_linux_usb_header(hdr, *data, 1);
1108                         break;
1109                 }
1110         }
1111
1112         return (0);
1113 }