2 * Copyright (c) 1993, 1994, 1995, 1996, 1997
3 * The Regents of the University of California. All rights reserved.
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
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.
21 * sf-pcap.c - libpcap-file-format-specific code from savefile.c
22 * Extraction/creation by Jeffrey Mogul, DECWRL
23 * Modified by Steve McCanne, LBL.
25 * Used to save the received packet headers, after filtering, to
26 * a file, and then read them later.
27 * The first record in the file contains saved values for the machine
28 * dependent values so we can print the dump file on any architecture.
33 #include <pcap-types.h>
44 #include <limits.h> /* for INT_MAX */
47 #include "pcap-util.h"
49 #include "pcap-common.h"
51 #ifdef HAVE_OS_PROTO_H
58 * Setting O_BINARY on Windows is a bit tricky.
61 #define SET_BINMODE(f) _setmode(_fileno(f), _O_BINARY)
65 * Standard libpcap format.
67 * The same value is used in the rpcap protocol as an indication of
68 * the server byte order, to let the client know whether it needs to
69 * byte-swap some host-byte-order metadata.
71 #define TCPDUMP_MAGIC 0xa1b2c3d4
74 * Alexey Kuznetzov's modified libpcap format.
76 #define KUZNETZOV_TCPDUMP_MAGIC 0xa1b2cd34
79 * Reserved for Francisco Mesquita <francisco.mesquita@radiomovel.pt>
80 * for another modified format.
82 #define FMESQUITA_TCPDUMP_MAGIC 0xa1b234cd
85 * Navtel Communications' format, with nanosecond timestamps,
86 * as per a request from Dumas Hwang <dumas.hwang@navtelcom.com>.
88 #define NAVTEL_TCPDUMP_MAGIC 0xa12b3c4d
91 * Normal libpcap format, except for seconds/nanoseconds timestamps,
92 * as per a request by Ulf Lamping <ulf.lamping@web.de>
94 #define NSEC_TCPDUMP_MAGIC 0xa1b23c4d
97 * Used for identification of cbpf-savefile(5).
99 #define CBPF_SAVEFILE_MAGIC 0xa1b2c3cb
102 * This is a timeval as stored in a savefile.
103 * It has to use the same types everywhere, independent of the actual
104 * `struct timeval'; `struct timeval' has 32-bit tv_sec values on some
105 * platforms and 64-bit tv_sec values on other platforms, and writing
106 * out native `struct timeval' values would mean files could only be
107 * read on systems with the same tv_sec size as the system on which
108 * the file was written.
110 * The fields are unsigned, as that's what the pcap draft specification
111 * says they are. (That gives pcap a 68-year Y2.038K reprieve, although
112 * in 2106 it runs out for good. pcapng doesn't have that problem,
113 * unless you pick a *really* high time stamp precision.)
116 struct pcap_timeval
{
117 bpf_u_int32 tv_sec
; /* seconds */
118 bpf_u_int32 tv_usec
; /* microseconds */
122 * This is a `pcap_pkthdr' as actually stored in a savefile.
124 * Do not change the format of this structure, in any way (this includes
125 * changes that only affect the length of fields in this structure),
126 * and do not make the time stamp anything other than seconds and
127 * microseconds (e.g., seconds and nanoseconds). Instead:
129 * introduce a new structure for the new format;
131 * send mail to "tcpdump-workers@lists.tcpdump.org", requesting
132 * a new magic number for your new capture file format, and, when
133 * you get the new magic number, put it in "savefile.c";
135 * use that magic number for save files with the changed record
138 * make the code in "savefile.c" capable of reading files with
139 * the old record header as well as files with the new record header
140 * (using the magic number to determine the header format).
142 * Then supply the changes by forking the branch at
144 * https://github.com/the-tcpdump-group/libpcap/tree/master
146 * and issuing a pull request, so that future versions of libpcap and
147 * programs that use it (such as tcpdump) will be able to read your new
148 * capture file format.
151 struct pcap_sf_pkthdr
{
152 struct pcap_timeval ts
; /* time stamp */
153 bpf_u_int32 caplen
; /* length of portion present */
154 bpf_u_int32 len
; /* length of this packet (off wire) */
158 * How a `pcap_pkthdr' is actually stored in savefiles written
159 * by some patched versions of libpcap (e.g. the ones in Red
160 * Hat Linux 6.1 and 6.2).
162 * Do not change the format of this structure, in any way (this includes
163 * changes that only affect the length of fields in this structure).
164 * Instead, introduce a new structure, as per the above.
167 struct pcap_sf_patched_pkthdr
{
168 struct pcap_timeval ts
; /* time stamp */
169 bpf_u_int32 caplen
; /* length of portion present */
170 bpf_u_int32 len
; /* length of this packet (off wire) */
172 unsigned short protocol
;
173 unsigned char pkt_type
;
176 static int pcap_next_packet(pcap_t
*p
, struct pcap_pkthdr
*hdr
, u_char
**datap
);
180 * This isn't exported on Windows, because it would only work if both
181 * libpcap and the code using it were using the same C runtime; otherwise they
182 * would be using different definitions of a FILE structure.
184 * Instead we define this as a macro in pcap/pcap.h that wraps the hopen
185 * version that we do export, passing it a raw OS HANDLE, as defined by the
186 * Win32 / Win64 ABI, obtained from the _fileno() and _get_osfhandle()
187 * functions of the appropriate CRT.
189 static pcap_dumper_t
*pcap_dump_fopen(pcap_t
*p
, FILE *f
);
193 * Private data for reading pcap savefiles.
205 } tstamp_scale_type_t
;
209 swapped_type_t lengths_swapped
;
210 tstamp_scale_type_t scale_type
;
214 * Check whether this is a pcap savefile and, if it is, extract the
215 * relevant information from the header.
218 pcap_check_header(const uint8_t *magic
, FILE *fp
, u_int precision
, char *errbuf
,
221 bpf_u_int32 magic_int
;
222 struct pcap_file_header hdr
;
229 * Assume no read errors.
234 * Check whether the first 4 bytes of the file are the magic
235 * number for a pcap savefile, or for a byte-swapped pcap
238 memcpy(&magic_int
, magic
, sizeof(magic_int
));
239 if (magic_int
!= TCPDUMP_MAGIC
&&
240 magic_int
!= KUZNETZOV_TCPDUMP_MAGIC
&&
241 magic_int
!= NSEC_TCPDUMP_MAGIC
) {
242 magic_int
= SWAPLONG(magic_int
);
243 if (magic_int
!= TCPDUMP_MAGIC
&&
244 magic_int
!= KUZNETZOV_TCPDUMP_MAGIC
&&
245 magic_int
!= NSEC_TCPDUMP_MAGIC
)
246 return (NULL
); /* nope */
251 * They are. Put the magic number in the header, and read
252 * the rest of the header.
254 hdr
.magic
= magic_int
;
255 amt_read
= fread(((char *)&hdr
) + sizeof hdr
.magic
, 1,
256 sizeof(hdr
) - sizeof(hdr
.magic
), fp
);
257 if (amt_read
!= sizeof(hdr
) - sizeof(hdr
.magic
)) {
259 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
260 errno
, "error reading dump file");
262 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
263 "truncated dump file; tried to read %zu file header bytes, only got %zu",
264 sizeof(hdr
), amt_read
);
271 * If it's a byte-swapped capture file, byte-swap the header.
274 hdr
.version_major
= SWAPSHORT(hdr
.version_major
);
275 hdr
.version_minor
= SWAPSHORT(hdr
.version_minor
);
276 hdr
.thiszone
= SWAPLONG(hdr
.thiszone
);
277 hdr
.sigfigs
= SWAPLONG(hdr
.sigfigs
);
278 hdr
.snaplen
= SWAPLONG(hdr
.snaplen
);
279 hdr
.linktype
= SWAPLONG(hdr
.linktype
);
282 if (hdr
.version_major
< PCAP_VERSION_MAJOR
) {
283 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
284 "archaic pcap savefile format");
290 * currently only versions 2.[0-4] are supported with
291 * the exception of 543.0 for DG/UX tcpdump.
293 if (! ((hdr
.version_major
== PCAP_VERSION_MAJOR
&&
294 hdr
.version_minor
<= PCAP_VERSION_MINOR
) ||
295 (hdr
.version_major
== 543 &&
296 hdr
.version_minor
== 0))) {
297 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
298 "unsupported pcap savefile version %u.%u",
299 hdr
.version_major
, hdr
.version_minor
);
305 * Check the main reserved field.
307 if (LT_RESERVED1(hdr
.linktype
) != 0) {
308 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
309 "savefile linktype reserved field not zero (0x%08x)",
310 LT_RESERVED1(hdr
.linktype
));
316 * OK, this is a good pcap file.
317 * Allocate a pcap_t for it.
319 p
= PCAP_OPEN_OFFLINE_COMMON(errbuf
, struct pcap_sf
);
321 /* Allocation failed. */
325 p
->swapped
= swapped
;
326 p
->version_major
= hdr
.version_major
;
327 p
->version_minor
= hdr
.version_minor
;
328 p
->linktype
= linktype_to_dlt(LT_LINKTYPE(hdr
.linktype
));
329 p
->linktype_ext
= LT_LINKTYPE_EXT(hdr
.linktype
);
330 p
->snapshot
= pcapint_adjust_snapshot(p
->linktype
, hdr
.snaplen
);
332 p
->next_packet_op
= pcap_next_packet
;
336 p
->opt
.tstamp_precision
= precision
;
339 * Will we need to scale the timestamps to match what the
344 case PCAP_TSTAMP_PRECISION_MICRO
:
345 if (magic_int
== NSEC_TCPDUMP_MAGIC
) {
347 * The file has nanoseconds, the user
348 * wants microseconds; scale the
351 ps
->scale_type
= SCALE_DOWN
;
354 * The file has microseconds, the
355 * user wants microseconds; nothing to do.
357 ps
->scale_type
= PASS_THROUGH
;
361 case PCAP_TSTAMP_PRECISION_NANO
:
362 if (magic_int
== NSEC_TCPDUMP_MAGIC
) {
364 * The file has nanoseconds, the
365 * user wants nanoseconds; nothing to do.
367 ps
->scale_type
= PASS_THROUGH
;
370 * The file has microseconds, the user
371 * wants nanoseconds; scale the
374 ps
->scale_type
= SCALE_UP
;
379 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
380 "unknown time stamp resolution %u", precision
);
387 * We interchanged the caplen and len fields at version 2.3,
388 * in order to match the bpf header layout. But unfortunately
389 * some files were written with version 2.3 in their headers
390 * but without the interchanged fields.
392 * In addition, DG/UX tcpdump writes out files with a version
393 * number of 543.0, and with the caplen and len fields in the
396 switch (hdr
.version_major
) {
399 if (hdr
.version_minor
< 3)
400 ps
->lengths_swapped
= SWAPPED
;
401 else if (hdr
.version_minor
== 3)
402 ps
->lengths_swapped
= MAYBE_SWAPPED
;
404 ps
->lengths_swapped
= NOT_SWAPPED
;
408 ps
->lengths_swapped
= SWAPPED
;
412 ps
->lengths_swapped
= NOT_SWAPPED
;
416 if (magic_int
== KUZNETZOV_TCPDUMP_MAGIC
) {
418 * XXX - the patch that's in some versions of libpcap
419 * changes the packet header but not the magic number,
420 * and some other versions with this magic number have
421 * some extra debugging information in the packet header;
422 * we'd have to use some hacks^H^H^H^H^Hheuristics to
423 * detect those variants.
425 * Ethereal does that, but it does so by trying to read
426 * the first two packets of the file with each of the
427 * record header formats. That currently means it seeks
428 * backwards and retries the reads, which doesn't work
429 * on pipes. We want to be able to read from a pipe, so
430 * that strategy won't work; we'd have to buffer some
431 * data ourselves and read from that buffer in order to
434 ps
->hdrsize
= sizeof(struct pcap_sf_patched_pkthdr
);
436 if (p
->linktype
== DLT_EN10MB
) {
438 * This capture might have been done in raw mode
441 * If it was done in cooked mode, p->snapshot was
442 * passed to recvfrom() as the buffer size, meaning
443 * that the most packet data that would be copied
444 * would be p->snapshot. However, a faked Ethernet
445 * header would then have been added to it, so the
446 * most data that would be in a packet in the file
447 * would be p->snapshot + 14.
449 * We can't easily tell whether the capture was done
450 * in raw mode or cooked mode, so we'll assume it was
451 * cooked mode, and add 14 to the snapshot length.
452 * That means that, for a raw capture, the snapshot
453 * length will be misleading if you use it to figure
454 * out why a capture doesn't have all the packet data,
455 * but there's not much we can do to avoid that.
457 * But don't grow the snapshot length past the
458 * maximum value of an int.
460 if (p
->snapshot
<= INT_MAX
- 14)
463 p
->snapshot
= INT_MAX
;
466 ps
->hdrsize
= sizeof(struct pcap_sf_pkthdr
);
469 * Allocate a buffer for the packet data.
470 * Choose the minimum of the file's snapshot length and 2K bytes;
471 * that should be enough for most network packets - we'll grow it
472 * if necessary. That way, we don't allocate a huge chunk of
473 * memory just because there's a huge snapshot length, as the
474 * snapshot length might be larger than the size of the largest
477 p
->bufsize
= p
->snapshot
;
478 if (p
->bufsize
> 2048)
480 p
->buffer
= malloc(p
->bufsize
);
481 if (p
->buffer
== NULL
) {
482 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "out of memory");
488 p
->cleanup_op
= pcapint_sf_cleanup
;
494 * Grow the packet buffer to the specified size.
497 grow_buffer(pcap_t
*p
, u_int bufsize
)
501 bigger_buffer
= realloc(p
->buffer
, bufsize
);
502 if (bigger_buffer
== NULL
) {
503 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "out of memory");
506 p
->buffer
= bigger_buffer
;
507 p
->bufsize
= bufsize
;
512 * Read and return the next packet from the savefile. Return the header
513 * in hdr and a pointer to the contents in data. Return 1 on success, 0
514 * if there were no more packets, and -1 on an error.
517 pcap_next_packet(pcap_t
*p
, struct pcap_pkthdr
*hdr
, u_char
**data
)
519 struct pcap_sf
*ps
= p
->priv
;
520 struct pcap_sf_patched_pkthdr sf_hdr
;
526 * Read the packet header; the structure we use as a buffer
527 * is the longer structure for files generated by the patched
528 * libpcap, but if the file has the magic number for an
529 * unpatched libpcap we only read as many bytes as the regular
532 amt_read
= fread(&sf_hdr
, 1, ps
->hdrsize
, fp
);
533 if (amt_read
!= ps
->hdrsize
) {
535 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
536 errno
, "error reading dump file");
540 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
541 "truncated dump file; tried to read %zu header bytes, only got %zu",
542 ps
->hdrsize
, amt_read
);
551 /* these were written in opposite byte order */
552 hdr
->caplen
= SWAPLONG(sf_hdr
.caplen
);
553 hdr
->len
= SWAPLONG(sf_hdr
.len
);
554 hdr
->ts
.tv_sec
= SWAPLONG(sf_hdr
.ts
.tv_sec
);
555 hdr
->ts
.tv_usec
= SWAPLONG(sf_hdr
.ts
.tv_usec
);
557 hdr
->caplen
= sf_hdr
.caplen
;
558 hdr
->len
= sf_hdr
.len
;
559 hdr
->ts
.tv_sec
= sf_hdr
.ts
.tv_sec
;
560 hdr
->ts
.tv_usec
= sf_hdr
.ts
.tv_usec
;
563 switch (ps
->scale_type
) {
567 * Just pass the time stamp through.
573 * File has microseconds, user wants nanoseconds; convert
576 hdr
->ts
.tv_usec
= hdr
->ts
.tv_usec
* 1000;
581 * File has nanoseconds, user wants microseconds; convert
584 hdr
->ts
.tv_usec
= hdr
->ts
.tv_usec
/ 1000;
588 /* Swap the caplen and len fields, if necessary. */
589 switch (ps
->lengths_swapped
) {
595 if (hdr
->caplen
<= hdr
->len
) {
597 * The captured length is <= the actual length,
598 * so presumably they weren't swapped.
606 hdr
->caplen
= hdr
->len
;
612 * Is the packet bigger than we consider sane?
614 if (hdr
->caplen
> max_snaplen_for_dlt(p
->linktype
)) {
616 * Yes. This may be a damaged or fuzzed file.
618 * Is it bigger than the snapshot length?
619 * (We don't treat that as an error if it's not
620 * bigger than the maximum we consider sane; see
623 if (hdr
->caplen
> (bpf_u_int32
)p
->snapshot
) {
624 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
625 "invalid packet capture length %u, bigger than "
626 "snaplen of %d", hdr
->caplen
, p
->snapshot
);
628 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
629 "invalid packet capture length %u, bigger than "
630 "maximum of %u", hdr
->caplen
,
631 max_snaplen_for_dlt(p
->linktype
));
636 if (hdr
->caplen
> (bpf_u_int32
)p
->snapshot
) {
638 * The packet is bigger than the snapshot length
641 * This can happen due to Solaris 2.3 systems tripping
642 * over the BUFMOD problem and not setting the snapshot
643 * length correctly in the savefile header.
645 * libpcap 0.4 and later on Solaris 2.3 should set the
646 * snapshot length correctly in the pcap file header,
647 * even though they don't set a snapshot length in bufmod
648 * (the buggy bufmod chops off the *beginning* of the
649 * packet if a snapshot length is specified); they should
650 * also reduce the captured length, as supplied to the
651 * per-packet callback, to the snapshot length if it's
652 * greater than the snapshot length, so the code using
653 * libpcap should see the packet cut off at the snapshot
654 * length, even though the full packet is copied up to
657 * However, perhaps some versions of libpcap failed to
658 * set the snapshot length correctly in the file header
659 * or the per-packet header, or perhaps this is a
660 * corrupted savefile or a savefile built/modified by a
661 * fuzz tester, so we check anyway. We grow the buffer
662 * to be big enough for the snapshot length, read up
663 * to the snapshot length, discard the rest of the
664 * packet, and report the snapshot length as the captured
665 * length; we don't want to hand our caller a packet
666 * bigger than the snapshot length, because they might
667 * be assuming they'll never be handed such a packet,
668 * and might copy the packet into a snapshot-length-
669 * sized buffer, assuming it'll fit.
671 size_t bytes_to_discard
;
672 size_t bytes_to_read
, bytes_read
;
673 char discard_buf
[4096];
675 if (hdr
->caplen
> p
->bufsize
) {
677 * Grow the buffer to the snapshot length.
679 if (!grow_buffer(p
, p
->snapshot
))
684 * Read the first p->snapshot bytes into the buffer.
686 amt_read
= fread(p
->buffer
, 1, p
->snapshot
, fp
);
687 if (amt_read
!= (bpf_u_int32
)p
->snapshot
) {
689 pcapint_fmt_errmsg_for_errno(p
->errbuf
,
690 PCAP_ERRBUF_SIZE
, errno
,
691 "error reading dump file");
694 * Yes, this uses hdr->caplen; technically,
695 * it's true, because we would try to read
696 * and discard the rest of those bytes, and
697 * that would fail because we got EOF before
700 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
701 "truncated dump file; tried to read %d captured bytes, only got %zu",
702 p
->snapshot
, amt_read
);
708 * Now read and discard what's left.
710 bytes_to_discard
= hdr
->caplen
- p
->snapshot
;
711 bytes_read
= amt_read
;
712 while (bytes_to_discard
!= 0) {
713 bytes_to_read
= bytes_to_discard
;
714 if (bytes_to_read
> sizeof (discard_buf
))
715 bytes_to_read
= sizeof (discard_buf
);
716 amt_read
= fread(discard_buf
, 1, bytes_to_read
, fp
);
717 bytes_read
+= amt_read
;
718 if (amt_read
!= bytes_to_read
) {
720 pcapint_fmt_errmsg_for_errno(p
->errbuf
,
721 PCAP_ERRBUF_SIZE
, errno
,
722 "error reading dump file");
724 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
725 "truncated dump file; tried to read %u captured bytes, only got %zu",
726 hdr
->caplen
, bytes_read
);
730 bytes_to_discard
-= amt_read
;
734 * Adjust caplen accordingly, so we don't get confused later
735 * as to how many bytes we have to play with.
737 hdr
->caplen
= p
->snapshot
;
740 * The packet is within the snapshot length for this file.
742 if (hdr
->caplen
> p
->bufsize
) {
744 * Grow the buffer to the next power of 2, or
745 * the snaplen, whichever is lower.
749 new_bufsize
= hdr
->caplen
;
751 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
754 new_bufsize
|= new_bufsize
>> 1;
755 new_bufsize
|= new_bufsize
>> 2;
756 new_bufsize
|= new_bufsize
>> 4;
757 new_bufsize
|= new_bufsize
>> 8;
758 new_bufsize
|= new_bufsize
>> 16;
761 if (new_bufsize
> (u_int
)p
->snapshot
)
762 new_bufsize
= p
->snapshot
;
764 if (!grow_buffer(p
, new_bufsize
))
768 /* read the packet itself */
769 amt_read
= fread(p
->buffer
, 1, hdr
->caplen
, fp
);
770 if (amt_read
!= hdr
->caplen
) {
772 pcapint_fmt_errmsg_for_errno(p
->errbuf
,
773 PCAP_ERRBUF_SIZE
, errno
,
774 "error reading dump file");
776 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
777 "truncated dump file; tried to read %u captured bytes, only got %zu",
778 hdr
->caplen
, amt_read
);
785 pcapint_post_process(p
->linktype
, p
->swapped
, hdr
, *data
);
791 sf_write_header(pcap_t
*p
, FILE *fp
, int linktype
, int snaplen
)
793 struct pcap_file_header hdr
;
795 hdr
.magic
= p
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? NSEC_TCPDUMP_MAGIC
: TCPDUMP_MAGIC
;
796 hdr
.version_major
= PCAP_VERSION_MAJOR
;
797 hdr
.version_minor
= PCAP_VERSION_MINOR
;
800 * https://www.tcpdump.org/manpages/pcap-savefile.5.txt states:
801 * thiszone (Reserved1): 4-byte not used - SHOULD be filled with 0
802 * sigfigs (Reserved2): 4-byte not used - SHOULD be filled with 0
806 hdr
.snaplen
= snaplen
;
807 hdr
.linktype
= linktype
;
809 if (fwrite((char *)&hdr
, sizeof(hdr
), 1, fp
) != 1)
816 * Output a packet to the initialized dump file.
819 pcap_dump(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
822 struct pcap_sf_pkthdr sf_hdr
;
826 * If the output file handle is in an error state, don't write
829 * While in principle a file handle can return from an error state
830 * to a normal state (for example if a disk that is full has space
831 * freed), we have possibly left a broken file already, and won't
832 * be able to clean it up. The safest option is to do nothing.
834 * Note that if we could guarantee that fwrite() was atomic we
835 * might be able to insure that we don't produce a corrupted file,
836 * but the standard defines fwrite() as a series of fputc() calls,
837 * so we really have no insurance that things are not fubared.
839 * http://pubs.opengroup.org/onlinepubs/009695399/functions/fwrite.html
844 * Better not try writing pcap files after
845 * 2106-02-07 06:28:15 UTC; switch to pcapng.
846 * (And better not try writing pcap files with time stamps
847 * that predate 1970-01-01 00:00:00 UTC; that's not supported.
848 * You could try using pcapng with the if_tsoffset field in
849 * the IDB for the interface(s) with packets with those time
850 * stamps, but you may also have to get a link-layer type for
851 * IBM Bisync or whatever link layer even older forms
852 * of computer communication used.)
854 sf_hdr
.ts
.tv_sec
= (bpf_u_int32
)h
->ts
.tv_sec
;
855 sf_hdr
.ts
.tv_usec
= (bpf_u_int32
)h
->ts
.tv_usec
;
856 sf_hdr
.caplen
= h
->caplen
;
859 * We only write the packet if we can write the header properly.
861 * This doesn't prevent us from having corrupted output, and if we
862 * for some reason don't get a complete write we don't have any
863 * way to set ferror() to prevent future writes from being
864 * attempted, but it is better than nothing.
866 if (fwrite(&sf_hdr
, sizeof(sf_hdr
), 1, f
) == 1) {
867 (void)fwrite(sp
, h
->caplen
, 1, f
);
871 static pcap_dumper_t
*
872 pcap_setup_dump(pcap_t
*p
, int linktype
, FILE *f
, const char *fname
)
877 * If we're writing to the standard output, put it in binary
878 * mode, as savefiles are binary files.
880 * Otherwise, we turn off buffering.
881 * XXX - why? And why not on the standard output?
886 setvbuf(f
, NULL
, _IONBF
, 0);
888 if (sf_write_header(p
, f
, linktype
, p
->snapshot
) == -1) {
889 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
890 errno
, "Can't write to %s", fname
);
895 return ((pcap_dumper_t
*)f
);
899 * Initialize so that sf_write() will output to the file named 'fname'.
902 pcap_dump_open(pcap_t
*p
, const char *fname
)
908 * If this pcap_t hasn't been activated, it doesn't have a
909 * link-layer type, so we can't use it.
912 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
913 "%s: not-yet-activated pcap_t passed to pcap_dump_open",
917 linktype
= dlt_to_linktype(p
->linktype
);
918 if (linktype
== -1) {
919 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
920 "%s: link-layer type %d isn't supported in savefiles",
924 linktype
|= p
->linktype_ext
;
927 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
928 "A null pointer was supplied as the file name");
931 if (fname
[0] == '-' && fname
[1] == '\0') {
933 fname
= "standard output";
936 * "b" is supported as of C90, so *all* UN*Xes should
937 * support it, even though it does nothing. It's
938 * required on Windows, as the file is a binary file
939 * and must be written in binary mode.
941 f
= pcapint_charset_fopen(fname
, "wb");
943 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
948 return (pcap_setup_dump(p
, linktype
, f
, fname
));
953 * Initialize so that sf_write() will output to a stream wrapping the given raw
957 pcap_dump_hopen(pcap_t
*p
, intptr_t osfd
)
962 fd
= _open_osfhandle(osfd
, _O_APPEND
);
964 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
965 errno
, "_open_osfhandle");
969 file
= _fdopen(fd
, "wb");
971 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
977 return pcap_dump_fopen(p
, file
);
982 * Initialize so that sf_write() will output to the given stream.
988 pcap_dump_fopen(pcap_t
*p
, FILE *f
)
992 linktype
= dlt_to_linktype(p
->linktype
);
993 if (linktype
== -1) {
994 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
995 "stream: link-layer type %d isn't supported in savefiles",
999 linktype
|= p
->linktype_ext
;
1001 return (pcap_setup_dump(p
, linktype
, f
, "stream"));
1005 pcap_dump_open_append(pcap_t
*p
, const char *fname
)
1010 struct pcap_file_header ph
;
1012 linktype
= dlt_to_linktype(p
->linktype
);
1013 if (linktype
== -1) {
1014 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1015 "%s: link-layer type %d isn't supported in savefiles",
1020 if (fname
== NULL
) {
1021 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1022 "A null pointer was supplied as the file name");
1025 if (fname
[0] == '-' && fname
[1] == '\0')
1026 return (pcap_setup_dump(p
, linktype
, stdout
, "standard output"));
1029 * "a" will cause the file *not* to be truncated if it exists
1030 * but will cause it to be created if it doesn't. It will
1031 * also cause all writes to be done at the end of the file,
1032 * but will allow reads to be done anywhere in the file. This
1033 * is what we need, because we need to read from the beginning
1034 * of the file to see if it already has a header and packets
1037 * "b" is supported as of C90, so *all* UN*Xes should support it,
1038 * even though it does nothing. It's required on Windows, as the
1039 * file is a binary file and must be read in binary mode.
1041 f
= pcapint_charset_fopen(fname
, "ab+");
1043 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1044 errno
, "%s", fname
);
1049 * Try to read a pcap header.
1051 * We do not assume that the file will be positioned at the
1052 * beginning immediately after we've opened it - we seek to
1053 * the beginning. ISO C says it's implementation-defined
1054 * whether the file position indicator is at the beginning
1055 * or the end of the file after an append-mode open, and
1056 * it wasn't obvious from the Single UNIX Specification
1057 * or the Microsoft documentation how that works on SUS-
1058 * compliant systems or on Windows.
1060 if (fseek(f
, 0, SEEK_SET
) == -1) {
1061 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1062 errno
, "Can't seek to the beginning of %s", fname
);
1066 amt_read
= fread(&ph
, 1, sizeof (ph
), f
);
1067 if (amt_read
!= sizeof (ph
)) {
1069 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1070 errno
, "%s", fname
);
1073 } else if (feof(f
) && amt_read
> 0) {
1074 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1075 "%s: truncated pcap file header", fname
);
1083 * We turn off buffering.
1084 * XXX - why? And why not on the standard output?
1086 setvbuf(f
, NULL
, _IONBF
, 0);
1090 * If a header is already present and:
1092 * it's not for a pcap file of the appropriate resolution
1093 * and the right byte order for this machine;
1095 * the link-layer header types don't match;
1097 * the snapshot lengths don't match;
1103 * A header is already present.
1109 if (p
->opt
.tstamp_precision
!= PCAP_TSTAMP_PRECISION_MICRO
) {
1110 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1111 "%s: different time stamp precision, cannot append to file", fname
);
1117 case NSEC_TCPDUMP_MAGIC
:
1118 if (p
->opt
.tstamp_precision
!= PCAP_TSTAMP_PRECISION_NANO
) {
1119 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1120 "%s: different time stamp precision, cannot append to file", fname
);
1126 case SWAPLONG(TCPDUMP_MAGIC
):
1127 case SWAPLONG(NSEC_TCPDUMP_MAGIC
):
1128 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1129 "%s: different byte order, cannot append to file", fname
);
1133 case KUZNETZOV_TCPDUMP_MAGIC
:
1134 case SWAPLONG(KUZNETZOV_TCPDUMP_MAGIC
):
1135 case NAVTEL_TCPDUMP_MAGIC
:
1136 case SWAPLONG(NAVTEL_TCPDUMP_MAGIC
):
1137 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1138 "%s: not a pcap file to which we can append", fname
);
1143 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1144 "%s: not a pcap file", fname
);
1152 if (ph
.version_major
!= PCAP_VERSION_MAJOR
||
1153 ph
.version_minor
!= PCAP_VERSION_MINOR
) {
1154 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1155 "%s: version is %u.%u, cannot append to file", fname
,
1156 ph
.version_major
, ph
.version_minor
);
1160 if ((bpf_u_int32
)linktype
!= ph
.linktype
) {
1161 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1162 "%s: different linktype, cannot append to file", fname
);
1166 if ((bpf_u_int32
)p
->snapshot
!= ph
.snaplen
) {
1167 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1168 "%s: different snaplen, cannot append to file", fname
);
1174 * A header isn't present; attempt to write it.
1176 if (sf_write_header(p
, f
, linktype
, p
->snapshot
) == -1) {
1177 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1178 errno
, "Can't write to %s", fname
);
1185 * Start writing at the end of the file.
1187 * XXX - this shouldn't be necessary, given that we're opening
1188 * the file in append mode, and ISO C specifies that all writes
1189 * are done at the end of the file in that mode.
1191 if (fseek(f
, 0, SEEK_END
) == -1) {
1192 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1193 errno
, "Can't seek to the end of %s", fname
);
1197 return ((pcap_dumper_t
*)f
);
1201 pcap_dump_file(pcap_dumper_t
*p
)
1207 pcap_dump_ftell(pcap_dumper_t
*p
)
1209 return (ftell((FILE *)p
));
1212 #if defined(HAVE_FSEEKO)
1214 * We have fseeko(), so we have ftello().
1215 * If we have large file support (files larger than 2^31-1 bytes),
1216 * ftello() will give us a current file position with more than 32
1220 pcap_dump_ftell64(pcap_dumper_t
*p
)
1222 return (ftello((FILE *)p
));
1224 #elif defined(_MSC_VER)
1226 * We have Visual Studio; we support only 2015 and later, so we have
1230 pcap_dump_ftell64(pcap_dumper_t
*p
)
1232 return (_ftelli64((FILE *)p
));
1236 * We don't have ftello() or _ftelli64(), so fall back on ftell().
1237 * Either long is 64 bits, in which case ftell() should suffice,
1238 * or this is probably an older 32-bit UN*X without large file
1239 * support, which means you'll probably get errors trying to
1240 * write files > 2^31-1, so it won't matter anyway.
1242 * XXX - what about MinGW?
1245 pcap_dump_ftell64(pcap_dumper_t
*p
)
1247 return (ftell((FILE *)p
));
1252 pcap_dump_flush(pcap_dumper_t
*p
)
1255 if (fflush((FILE *)p
) == EOF
)
1262 pcap_dump_close(pcap_dumper_t
*p
)
1264 FILE *fp
= (FILE *)p
;
1269 /* XXX should check return from fflush()/fclose() too */
1271 /* Don't close the standard output, but *do* flush it */