]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/libpcap/sf-pcap.c
Merge commit 'acb089b983171667467adc66f56a723b609ed22e' into kbsd/vis
[FreeBSD/FreeBSD.git] / contrib / libpcap / sf-pcap.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.c - libpcap-file-format-specific code from savefile.c
22  *      Extraction/creation by Jeffrey Mogul, DECWRL
23  *      Modified by Steve McCanne, LBL.
24  *
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.
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include <config.h>
33 #endif
34
35 #include <pcap-types.h>
36 #ifdef _WIN32
37 #include <io.h>
38 #include <fcntl.h>
39 #endif /* _WIN32 */
40
41 #include <errno.h>
42 #include <memory.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <limits.h> /* for INT_MAX */
47
48 #include "pcap-int.h"
49 #include "pcap-util.h"
50
51 #include "pcap-common.h"
52
53 #ifdef HAVE_OS_PROTO_H
54 #include "os-proto.h"
55 #endif
56
57 #include "sf-pcap.h"
58
59 /*
60  * Setting O_BINARY on DOS/Windows is a bit tricky
61  */
62 #if defined(_WIN32)
63   #define SET_BINMODE(f)  _setmode(_fileno(f), _O_BINARY)
64 #elif defined(MSDOS)
65   #if defined(__HIGHC__)
66   #define SET_BINMODE(f)  setmode(f, O_BINARY)
67   #else
68   #define SET_BINMODE(f)  setmode(fileno(f), O_BINARY)
69   #endif
70 #endif
71
72 /*
73  * Standard libpcap format.
74  *
75  * The same value is used in the rpcap protocol as an indication of
76  * the server byte order, to let the client know whether it needs to
77  * byte-swap some host-byte-order metadata.
78  */
79 #define TCPDUMP_MAGIC           0xa1b2c3d4
80
81 /*
82  * Alexey Kuznetzov's modified libpcap format.
83  */
84 #define KUZNETZOV_TCPDUMP_MAGIC 0xa1b2cd34
85
86 /*
87  * Reserved for Francisco Mesquita <francisco.mesquita@radiomovel.pt>
88  * for another modified format.
89  */
90 #define FMESQUITA_TCPDUMP_MAGIC 0xa1b234cd
91
92 /*
93  * Navtel Communcations' format, with nanosecond timestamps,
94  * as per a request from Dumas Hwang <dumas.hwang@navtelcom.com>.
95  */
96 #define NAVTEL_TCPDUMP_MAGIC    0xa12b3c4d
97
98 /*
99  * Normal libpcap format, except for seconds/nanoseconds timestamps,
100  * as per a request by Ulf Lamping <ulf.lamping@web.de>
101  */
102 #define NSEC_TCPDUMP_MAGIC      0xa1b23c4d
103
104 /*
105  * Mechanism for storing information about a capture in the upper
106  * 6 bits of a linktype value in a capture file.
107  *
108  * LT_LINKTYPE_EXT(x) extracts the additional information.
109  *
110  * The rest of the bits are for a value describing the link-layer
111  * value.  LT_LINKTYPE(x) extracts that value.
112  */
113 #define LT_LINKTYPE(x)          ((x) & 0x03FFFFFF)
114 #define LT_LINKTYPE_EXT(x)      ((x) & 0xFC000000)
115
116 static int pcap_next_packet(pcap_t *p, struct pcap_pkthdr *hdr, u_char **datap);
117
118 #ifdef _WIN32
119 /*
120  * This isn't exported on Windows, because it would only work if both
121  * libpcap and the code using it were using the same C runtime; otherwise they
122  * would be using different definitions of a FILE structure.
123  *
124  * Instead we define this as a macro in pcap/pcap.h that wraps the hopen
125  * version that we do export, passing it a raw OS HANDLE, as defined by the
126  * Win32 / Win64 ABI, obtained from the _fileno() and _get_osfhandle()
127  * functions of the appropriate CRT.
128  */
129 static pcap_dumper_t *pcap_dump_fopen(pcap_t *p, FILE *f);
130 #endif /* _WIN32 */
131
132 /*
133  * Private data for reading pcap savefiles.
134  */
135 typedef enum {
136         NOT_SWAPPED,
137         SWAPPED,
138         MAYBE_SWAPPED
139 } swapped_type_t;
140
141 typedef enum {
142         PASS_THROUGH,
143         SCALE_UP,
144         SCALE_DOWN
145 } tstamp_scale_type_t;
146
147 struct pcap_sf {
148         size_t hdrsize;
149         swapped_type_t lengths_swapped;
150         tstamp_scale_type_t scale_type;
151 };
152
153 /*
154  * Check whether this is a pcap savefile and, if it is, extract the
155  * relevant information from the header.
156  */
157 pcap_t *
158 pcap_check_header(const uint8_t *magic, FILE *fp, u_int precision, char *errbuf,
159                   int *err)
160 {
161         bpf_u_int32 magic_int;
162         struct pcap_file_header hdr;
163         size_t amt_read;
164         pcap_t *p;
165         int swapped = 0;
166         struct pcap_sf *ps;
167
168         /*
169          * Assume no read errors.
170          */
171         *err = 0;
172
173         /*
174          * Check whether the first 4 bytes of the file are the magic
175          * number for a pcap savefile, or for a byte-swapped pcap
176          * savefile.
177          */
178         memcpy(&magic_int, magic, sizeof(magic_int));
179         if (magic_int != TCPDUMP_MAGIC &&
180             magic_int != KUZNETZOV_TCPDUMP_MAGIC &&
181             magic_int != NSEC_TCPDUMP_MAGIC) {
182                 magic_int = SWAPLONG(magic_int);
183                 if (magic_int != TCPDUMP_MAGIC &&
184                     magic_int != KUZNETZOV_TCPDUMP_MAGIC &&
185                     magic_int != NSEC_TCPDUMP_MAGIC)
186                         return (NULL);  /* nope */
187                 swapped = 1;
188         }
189
190         /*
191          * They are.  Put the magic number in the header, and read
192          * the rest of the header.
193          */
194         hdr.magic = magic_int;
195         amt_read = fread(((char *)&hdr) + sizeof hdr.magic, 1,
196             sizeof(hdr) - sizeof(hdr.magic), fp);
197         if (amt_read != sizeof(hdr) - sizeof(hdr.magic)) {
198                 if (ferror(fp)) {
199                         pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
200                             errno, "error reading dump file");
201                 } else {
202                         snprintf(errbuf, PCAP_ERRBUF_SIZE,
203                             "truncated dump file; tried to read %zu file header bytes, only got %zu",
204                             sizeof(hdr), amt_read);
205                 }
206                 *err = 1;
207                 return (NULL);
208         }
209
210         /*
211          * If it's a byte-swapped capture file, byte-swap the header.
212          */
213         if (swapped) {
214                 hdr.version_major = SWAPSHORT(hdr.version_major);
215                 hdr.version_minor = SWAPSHORT(hdr.version_minor);
216                 hdr.thiszone = SWAPLONG(hdr.thiszone);
217                 hdr.sigfigs = SWAPLONG(hdr.sigfigs);
218                 hdr.snaplen = SWAPLONG(hdr.snaplen);
219                 hdr.linktype = SWAPLONG(hdr.linktype);
220         }
221
222         if (hdr.version_major < PCAP_VERSION_MAJOR) {
223                 snprintf(errbuf, PCAP_ERRBUF_SIZE,
224                     "archaic pcap savefile format");
225                 *err = 1;
226                 return (NULL);
227         }
228
229         /*
230          * currently only versions 2.[0-4] are supported with
231          * the exception of 543.0 for DG/UX tcpdump.
232          */
233         if (! ((hdr.version_major == PCAP_VERSION_MAJOR &&
234                 hdr.version_minor <= PCAP_VERSION_MINOR) ||
235                (hdr.version_major == 543 &&
236                 hdr.version_minor == 0))) {
237                 snprintf(errbuf, PCAP_ERRBUF_SIZE,
238                          "unsupported pcap savefile version %u.%u",
239                          hdr.version_major, hdr.version_minor);
240                 *err = 1;
241                 return NULL;
242         }
243
244         /*
245          * OK, this is a good pcap file.
246          * Allocate a pcap_t for it.
247          */
248         p = PCAP_OPEN_OFFLINE_COMMON(errbuf, struct pcap_sf);
249         if (p == NULL) {
250                 /* Allocation failed. */
251                 *err = 1;
252                 return (NULL);
253         }
254         p->swapped = swapped;
255         p->version_major = hdr.version_major;
256         p->version_minor = hdr.version_minor;
257         p->linktype = linktype_to_dlt(LT_LINKTYPE(hdr.linktype));
258         p->linktype_ext = LT_LINKTYPE_EXT(hdr.linktype);
259         p->snapshot = pcap_adjust_snapshot(p->linktype, hdr.snaplen);
260
261         p->next_packet_op = pcap_next_packet;
262
263         ps = p->priv;
264
265         p->opt.tstamp_precision = precision;
266
267         /*
268          * Will we need to scale the timestamps to match what the
269          * user wants?
270          */
271         switch (precision) {
272
273         case PCAP_TSTAMP_PRECISION_MICRO:
274                 if (magic_int == NSEC_TCPDUMP_MAGIC) {
275                         /*
276                          * The file has nanoseconds, the user
277                          * wants microseconds; scale the
278                          * precision down.
279                          */
280                         ps->scale_type = SCALE_DOWN;
281                 } else {
282                         /*
283                          * The file has microseconds, the
284                          * user wants microseconds; nothing to do.
285                          */
286                         ps->scale_type = PASS_THROUGH;
287                 }
288                 break;
289
290         case PCAP_TSTAMP_PRECISION_NANO:
291                 if (magic_int == NSEC_TCPDUMP_MAGIC) {
292                         /*
293                          * The file has nanoseconds, the
294                          * user wants nanoseconds; nothing to do.
295                          */
296                         ps->scale_type = PASS_THROUGH;
297                 } else {
298                         /*
299                          * The file has microseconds, the user
300                          * wants nanoseconds; scale the
301                          * precision up.
302                          */
303                         ps->scale_type = SCALE_UP;
304                 }
305                 break;
306
307         default:
308                 snprintf(errbuf, PCAP_ERRBUF_SIZE,
309                     "unknown time stamp resolution %u", precision);
310                 free(p);
311                 *err = 1;
312                 return (NULL);
313         }
314
315         /*
316          * We interchanged the caplen and len fields at version 2.3,
317          * in order to match the bpf header layout.  But unfortunately
318          * some files were written with version 2.3 in their headers
319          * but without the interchanged fields.
320          *
321          * In addition, DG/UX tcpdump writes out files with a version
322          * number of 543.0, and with the caplen and len fields in the
323          * pre-2.3 order.
324          */
325         switch (hdr.version_major) {
326
327         case 2:
328                 if (hdr.version_minor < 3)
329                         ps->lengths_swapped = SWAPPED;
330                 else if (hdr.version_minor == 3)
331                         ps->lengths_swapped = MAYBE_SWAPPED;
332                 else
333                         ps->lengths_swapped = NOT_SWAPPED;
334                 break;
335
336         case 543:
337                 ps->lengths_swapped = SWAPPED;
338                 break;
339
340         default:
341                 ps->lengths_swapped = NOT_SWAPPED;
342                 break;
343         }
344
345         if (magic_int == KUZNETZOV_TCPDUMP_MAGIC) {
346                 /*
347                  * XXX - the patch that's in some versions of libpcap
348                  * changes the packet header but not the magic number,
349                  * and some other versions with this magic number have
350                  * some extra debugging information in the packet header;
351                  * we'd have to use some hacks^H^H^H^H^Hheuristics to
352                  * detect those variants.
353                  *
354                  * Ethereal does that, but it does so by trying to read
355                  * the first two packets of the file with each of the
356                  * record header formats.  That currently means it seeks
357                  * backwards and retries the reads, which doesn't work
358                  * on pipes.  We want to be able to read from a pipe, so
359                  * that strategy won't work; we'd have to buffer some
360                  * data ourselves and read from that buffer in order to
361                  * make that work.
362                  */
363                 ps->hdrsize = sizeof(struct pcap_sf_patched_pkthdr);
364
365                 if (p->linktype == DLT_EN10MB) {
366                         /*
367                          * This capture might have been done in raw mode
368                          * or cooked mode.
369                          *
370                          * If it was done in cooked mode, p->snapshot was
371                          * passed to recvfrom() as the buffer size, meaning
372                          * that the most packet data that would be copied
373                          * would be p->snapshot.  However, a faked Ethernet
374                          * header would then have been added to it, so the
375                          * most data that would be in a packet in the file
376                          * would be p->snapshot + 14.
377                          *
378                          * We can't easily tell whether the capture was done
379                          * in raw mode or cooked mode, so we'll assume it was
380                          * cooked mode, and add 14 to the snapshot length.
381                          * That means that, for a raw capture, the snapshot
382                          * length will be misleading if you use it to figure
383                          * out why a capture doesn't have all the packet data,
384                          * but there's not much we can do to avoid that.
385                          *
386                          * But don't grow the snapshot length past the
387                          * maximum value of an int.
388                          */
389                         if (p->snapshot <= INT_MAX - 14)
390                                 p->snapshot += 14;
391                         else
392                                 p->snapshot = INT_MAX;
393                 }
394         } else
395                 ps->hdrsize = sizeof(struct pcap_sf_pkthdr);
396
397         /*
398          * Allocate a buffer for the packet data.
399          * Choose the minimum of the file's snapshot length and 2K bytes;
400          * that should be enough for most network packets - we'll grow it
401          * if necessary.  That way, we don't allocate a huge chunk of
402          * memory just because there's a huge snapshot length, as the
403          * snapshot length might be larger than the size of the largest
404          * packet.
405          */
406         p->bufsize = p->snapshot;
407         if (p->bufsize > 2048)
408                 p->bufsize = 2048;
409         p->buffer = malloc(p->bufsize);
410         if (p->buffer == NULL) {
411                 snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
412                 free(p);
413                 *err = 1;
414                 return (NULL);
415         }
416
417         p->cleanup_op = sf_cleanup;
418
419         return (p);
420 }
421
422 /*
423  * Grow the packet buffer to the specified size.
424  */
425 static int
426 grow_buffer(pcap_t *p, u_int bufsize)
427 {
428         void *bigger_buffer;
429
430         bigger_buffer = realloc(p->buffer, bufsize);
431         if (bigger_buffer == NULL) {
432                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "out of memory");
433                 return (0);
434         }
435         p->buffer = bigger_buffer;
436         p->bufsize = bufsize;
437         return (1);
438 }
439
440 /*
441  * Read and return the next packet from the savefile.  Return the header
442  * in hdr and a pointer to the contents in data.  Return 1 on success, 0
443  * if there were no more packets, and -1 on an error.
444  */
445 static int
446 pcap_next_packet(pcap_t *p, struct pcap_pkthdr *hdr, u_char **data)
447 {
448         struct pcap_sf *ps = p->priv;
449         struct pcap_sf_patched_pkthdr sf_hdr;
450         FILE *fp = p->rfile;
451         size_t amt_read;
452         bpf_u_int32 t;
453
454         /*
455          * Read the packet header; the structure we use as a buffer
456          * is the longer structure for files generated by the patched
457          * libpcap, but if the file has the magic number for an
458          * unpatched libpcap we only read as many bytes as the regular
459          * header has.
460          */
461         amt_read = fread(&sf_hdr, 1, ps->hdrsize, fp);
462         if (amt_read != ps->hdrsize) {
463                 if (ferror(fp)) {
464                         pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
465                             errno, "error reading dump file");
466                         return (-1);
467                 } else {
468                         if (amt_read != 0) {
469                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
470                                     "truncated dump file; tried to read %zu header bytes, only got %zu",
471                                     ps->hdrsize, amt_read);
472                                 return (-1);
473                         }
474                         /* EOF */
475                         return (0);
476                 }
477         }
478
479         if (p->swapped) {
480                 /* these were written in opposite byte order */
481                 hdr->caplen = SWAPLONG(sf_hdr.caplen);
482                 hdr->len = SWAPLONG(sf_hdr.len);
483                 hdr->ts.tv_sec = SWAPLONG(sf_hdr.ts.tv_sec);
484                 hdr->ts.tv_usec = SWAPLONG(sf_hdr.ts.tv_usec);
485         } else {
486                 hdr->caplen = sf_hdr.caplen;
487                 hdr->len = sf_hdr.len;
488                 hdr->ts.tv_sec = sf_hdr.ts.tv_sec;
489                 hdr->ts.tv_usec = sf_hdr.ts.tv_usec;
490         }
491
492         switch (ps->scale_type) {
493
494         case PASS_THROUGH:
495                 /*
496                  * Just pass the time stamp through.
497                  */
498                 break;
499
500         case SCALE_UP:
501                 /*
502                  * File has microseconds, user wants nanoseconds; convert
503                  * it.
504                  */
505                 hdr->ts.tv_usec = hdr->ts.tv_usec * 1000;
506                 break;
507
508         case SCALE_DOWN:
509                 /*
510                  * File has nanoseconds, user wants microseconds; convert
511                  * it.
512                  */
513                 hdr->ts.tv_usec = hdr->ts.tv_usec / 1000;
514                 break;
515         }
516
517         /* Swap the caplen and len fields, if necessary. */
518         switch (ps->lengths_swapped) {
519
520         case NOT_SWAPPED:
521                 break;
522
523         case MAYBE_SWAPPED:
524                 if (hdr->caplen <= hdr->len) {
525                         /*
526                          * The captured length is <= the actual length,
527                          * so presumably they weren't swapped.
528                          */
529                         break;
530                 }
531                 /* FALLTHROUGH */
532
533         case SWAPPED:
534                 t = hdr->caplen;
535                 hdr->caplen = hdr->len;
536                 hdr->len = t;
537                 break;
538         }
539
540         /*
541          * Is the packet bigger than we consider sane?
542          */
543         if (hdr->caplen > max_snaplen_for_dlt(p->linktype)) {
544                 /*
545                  * Yes.  This may be a damaged or fuzzed file.
546                  *
547                  * Is it bigger than the snapshot length?
548                  * (We don't treat that as an error if it's not
549                  * bigger than the maximum we consider sane; see
550                  * below.)
551                  */
552                 if (hdr->caplen > (bpf_u_int32)p->snapshot) {
553                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
554                             "invalid packet capture length %u, bigger than "
555                             "snaplen of %d", hdr->caplen, p->snapshot);
556                 } else {
557                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
558                             "invalid packet capture length %u, bigger than "
559                             "maximum of %u", hdr->caplen,
560                             max_snaplen_for_dlt(p->linktype));
561                 }
562                 return (-1);
563         }
564
565         if (hdr->caplen > (bpf_u_int32)p->snapshot) {
566                 /*
567                  * The packet is bigger than the snapshot length
568                  * for this file.
569                  *
570                  * This can happen due to Solaris 2.3 systems tripping
571                  * over the BUFMOD problem and not setting the snapshot
572                  * length correctly in the savefile header.
573                  *
574                  * libpcap 0.4 and later on Solaris 2.3 should set the
575                  * snapshot length correctly in the pcap file header,
576                  * even though they don't set a snapshot length in bufmod
577                  * (the buggy bufmod chops off the *beginning* of the
578                  * packet if a snapshot length is specified); they should
579                  * also reduce the captured length, as supplied to the
580                  * per-packet callback, to the snapshot length if it's
581                  * greater than the snapshot length, so the code using
582                  * libpcap should see the packet cut off at the snapshot
583                  * length, even though the full packet is copied up to
584                  * userland.
585                  *
586                  * However, perhaps some versions of libpcap failed to
587                  * set the snapshot length correctly in the file header
588                  * or the per-packet header, or perhaps this is a
589                  * corrupted safefile or a savefile built/modified by a
590                  * fuzz tester, so we check anyway.  We grow the buffer
591                  * to be big enough for the snapshot length, read up
592                  * to the snapshot length, discard the rest of the
593                  * packet, and report the snapshot length as the captured
594                  * length; we don't want to hand our caller a packet
595                  * bigger than the snapshot length, because they might
596                  * be assuming they'll never be handed such a packet,
597                  * and might copy the packet into a snapshot-length-
598                  * sized buffer, assuming it'll fit.
599                  */
600                 size_t bytes_to_discard;
601                 size_t bytes_to_read, bytes_read;
602                 char discard_buf[4096];
603
604                 if (hdr->caplen > p->bufsize) {
605                         /*
606                          * Grow the buffer to the snapshot length.
607                          */
608                         if (!grow_buffer(p, p->snapshot))
609                                 return (-1);
610                 }
611
612                 /*
613                  * Read the first p->snapshot bytes into the buffer.
614                  */
615                 amt_read = fread(p->buffer, 1, p->snapshot, fp);
616                 if (amt_read != (bpf_u_int32)p->snapshot) {
617                         if (ferror(fp)) {
618                                 pcap_fmt_errmsg_for_errno(p->errbuf,
619                                      PCAP_ERRBUF_SIZE, errno,
620                                     "error reading dump file");
621                         } else {
622                                 /*
623                                  * Yes, this uses hdr->caplen; technically,
624                                  * it's true, because we would try to read
625                                  * and discard the rest of those bytes, and
626                                  * that would fail because we got EOF before
627                                  * the read finished.
628                                  */
629                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
630                                     "truncated dump file; tried to read %d captured bytes, only got %zu",
631                                     p->snapshot, amt_read);
632                         }
633                         return (-1);
634                 }
635
636                 /*
637                  * Now read and discard what's left.
638                  */
639                 bytes_to_discard = hdr->caplen - p->snapshot;
640                 bytes_read = amt_read;
641                 while (bytes_to_discard != 0) {
642                         bytes_to_read = bytes_to_discard;
643                         if (bytes_to_read > sizeof (discard_buf))
644                                 bytes_to_read = sizeof (discard_buf);
645                         amt_read = fread(discard_buf, 1, bytes_to_read, fp);
646                         bytes_read += amt_read;
647                         if (amt_read != bytes_to_read) {
648                                 if (ferror(fp)) {
649                                         pcap_fmt_errmsg_for_errno(p->errbuf,
650                                             PCAP_ERRBUF_SIZE, errno,
651                                             "error reading dump file");
652                                 } else {
653                                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
654                                             "truncated dump file; tried to read %u captured bytes, only got %zu",
655                                             hdr->caplen, bytes_read);
656                                 }
657                                 return (-1);
658                         }
659                         bytes_to_discard -= amt_read;
660                 }
661
662                 /*
663                  * Adjust caplen accordingly, so we don't get confused later
664                  * as to how many bytes we have to play with.
665                  */
666                 hdr->caplen = p->snapshot;
667         } else {
668                 /*
669                  * The packet is within the snapshot length for this file.
670                  */
671                 if (hdr->caplen > p->bufsize) {
672                         /*
673                          * Grow the buffer to the next power of 2, or
674                          * the snaplen, whichever is lower.
675                          */
676                         u_int new_bufsize;
677
678                         new_bufsize = hdr->caplen;
679                         /*
680                          * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
681                          */
682                         new_bufsize--;
683                         new_bufsize |= new_bufsize >> 1;
684                         new_bufsize |= new_bufsize >> 2;
685                         new_bufsize |= new_bufsize >> 4;
686                         new_bufsize |= new_bufsize >> 8;
687                         new_bufsize |= new_bufsize >> 16;
688                         new_bufsize++;
689
690                         if (new_bufsize > (u_int)p->snapshot)
691                                 new_bufsize = p->snapshot;
692
693                         if (!grow_buffer(p, new_bufsize))
694                                 return (-1);
695                 }
696
697                 /* read the packet itself */
698                 amt_read = fread(p->buffer, 1, hdr->caplen, fp);
699                 if (amt_read != hdr->caplen) {
700                         if (ferror(fp)) {
701                                 pcap_fmt_errmsg_for_errno(p->errbuf,
702                                     PCAP_ERRBUF_SIZE, errno,
703                                     "error reading dump file");
704                         } else {
705                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
706                                     "truncated dump file; tried to read %u captured bytes, only got %zu",
707                                     hdr->caplen, amt_read);
708                         }
709                         return (-1);
710                 }
711         }
712         *data = p->buffer;
713
714         pcap_post_process(p->linktype, p->swapped, hdr, *data);
715
716         return (1);
717 }
718
719 static int
720 sf_write_header(pcap_t *p, FILE *fp, int linktype, int snaplen)
721 {
722         struct pcap_file_header hdr;
723
724         hdr.magic = p->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? NSEC_TCPDUMP_MAGIC : TCPDUMP_MAGIC;
725         hdr.version_major = PCAP_VERSION_MAJOR;
726         hdr.version_minor = PCAP_VERSION_MINOR;
727
728         /*
729          * https://www.tcpdump.org/manpages/pcap-savefile.5.txt states:
730          * thiszone: 4-byte time zone offset; this is always 0.
731          * sigfigs:  4-byte number giving the accuracy of time stamps
732          *           in the file; this is always 0.
733          */
734         hdr.thiszone = 0;
735         hdr.sigfigs = 0;
736         hdr.snaplen = snaplen;
737         hdr.linktype = linktype;
738
739         if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1)
740                 return (-1);
741
742         return (0);
743 }
744
745 /*
746  * Output a packet to the initialized dump file.
747  */
748 void
749 pcap_dump(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
750 {
751         register FILE *f;
752         struct pcap_sf_pkthdr sf_hdr;
753
754         f = (FILE *)user;
755         /*
756          * If the output file handle is in an error state, don't write
757          * anything.
758          *
759          * While in principle a file handle can return from an error state
760          * to a normal state (for example if a disk that is full has space
761          * freed), we have possibly left a broken file already, and won't
762          * be able to clean it up. The safest option is to do nothing.
763          *
764          * Note that if we could guarantee that fwrite() was atomic we
765          * might be able to insure that we don't produce a corrupted file,
766          * but the standard defines fwrite() as a series of fputc() calls,
767          * so we really have no insurance that things are not fubared.
768          *
769          * http://pubs.opengroup.org/onlinepubs/009695399/functions/fwrite.html
770          */
771         if (ferror(f))
772                 return;
773         /*
774          * Better not try writing pcap files after
775          * 2038-01-19 03:14:07 UTC; switch to pcapng.
776          */
777         sf_hdr.ts.tv_sec  = (bpf_int32)h->ts.tv_sec;
778         sf_hdr.ts.tv_usec = (bpf_int32)h->ts.tv_usec;
779         sf_hdr.caplen     = h->caplen;
780         sf_hdr.len        = h->len;
781         /*
782          * We only write the packet if we can write the header properly.
783          *
784          * This doesn't prevent us from having corrupted output, and if we
785          * for some reason don't get a complete write we don't have any
786          * way to set ferror() to prevent future writes from being
787          * attempted, but it is better than nothing.
788          */
789         if (fwrite(&sf_hdr, sizeof(sf_hdr), 1, f) == 1) {
790                 (void)fwrite(sp, h->caplen, 1, f);
791         }
792 }
793
794 static pcap_dumper_t *
795 pcap_setup_dump(pcap_t *p, int linktype, FILE *f, const char *fname)
796 {
797
798 #if defined(_WIN32) || defined(MSDOS)
799         /*
800          * If we're writing to the standard output, put it in binary
801          * mode, as savefiles are binary files.
802          *
803          * Otherwise, we turn off buffering.
804          * XXX - why?  And why not on the standard output?
805          */
806         if (f == stdout)
807                 SET_BINMODE(f);
808         else
809                 setvbuf(f, NULL, _IONBF, 0);
810 #endif
811         if (sf_write_header(p, f, linktype, p->snapshot) == -1) {
812                 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
813                     errno, "Can't write to %s", fname);
814                 if (f != stdout)
815                         (void)fclose(f);
816                 return (NULL);
817         }
818         return ((pcap_dumper_t *)f);
819 }
820
821 /*
822  * Initialize so that sf_write() will output to the file named 'fname'.
823  */
824 pcap_dumper_t *
825 pcap_dump_open(pcap_t *p, const char *fname)
826 {
827         FILE *f;
828         int linktype;
829
830         /*
831          * If this pcap_t hasn't been activated, it doesn't have a
832          * link-layer type, so we can't use it.
833          */
834         if (!p->activated) {
835                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
836                     "%s: not-yet-activated pcap_t passed to pcap_dump_open",
837                     fname);
838                 return (NULL);
839         }
840         linktype = dlt_to_linktype(p->linktype);
841         if (linktype == -1) {
842                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
843                     "%s: link-layer type %d isn't supported in savefiles",
844                     fname, p->linktype);
845                 return (NULL);
846         }
847         linktype |= p->linktype_ext;
848
849         if (fname == NULL) {
850                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
851                     "A null pointer was supplied as the file name");
852                 return NULL;
853         }
854         if (fname[0] == '-' && fname[1] == '\0') {
855                 f = stdout;
856                 fname = "standard output";
857         } else {
858                 /*
859                  * "b" is supported as of C90, so *all* UN*Xes should
860                  * support it, even though it does nothing.  It's
861                  * required on Windows, as the file is a binary file
862                  * and must be written in binary mode.
863                  */
864                 f = charset_fopen(fname, "wb");
865                 if (f == NULL) {
866                         pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
867                             errno, "%s", fname);
868                         return (NULL);
869                 }
870         }
871         return (pcap_setup_dump(p, linktype, f, fname));
872 }
873
874 #ifdef _WIN32
875 /*
876  * Initialize so that sf_write() will output to a stream wrapping the given raw
877  * OS file HANDLE.
878  */
879 pcap_dumper_t *
880 pcap_dump_hopen(pcap_t *p, intptr_t osfd)
881 {
882         int fd;
883         FILE *file;
884
885         fd = _open_osfhandle(osfd, _O_APPEND);
886         if (fd < 0) {
887                 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
888                     errno, "_open_osfhandle");
889                 return NULL;
890         }
891
892         file = _fdopen(fd, "wb");
893         if (file == NULL) {
894                 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
895                     errno, "_fdopen");
896                 _close(fd);
897                 return NULL;
898         }
899
900         return pcap_dump_fopen(p, file);
901 }
902 #endif /* _WIN32 */
903
904 /*
905  * Initialize so that sf_write() will output to the given stream.
906  */
907 #ifdef _WIN32
908 static
909 #endif /* _WIN32 */
910 pcap_dumper_t *
911 pcap_dump_fopen(pcap_t *p, FILE *f)
912 {
913         int linktype;
914
915         linktype = dlt_to_linktype(p->linktype);
916         if (linktype == -1) {
917                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
918                     "stream: link-layer type %d isn't supported in savefiles",
919                     p->linktype);
920                 return (NULL);
921         }
922         linktype |= p->linktype_ext;
923
924         return (pcap_setup_dump(p, linktype, f, "stream"));
925 }
926
927 pcap_dumper_t *
928 pcap_dump_open_append(pcap_t *p, const char *fname)
929 {
930         FILE *f;
931         int linktype;
932         size_t amt_read;
933         struct pcap_file_header ph;
934
935         linktype = dlt_to_linktype(p->linktype);
936         if (linktype == -1) {
937                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
938                     "%s: link-layer type %d isn't supported in savefiles",
939                     fname, linktype);
940                 return (NULL);
941         }
942
943         if (fname == NULL) {
944                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
945                     "A null pointer was supplied as the file name");
946                 return NULL;
947         }
948         if (fname[0] == '-' && fname[1] == '\0')
949                 return (pcap_setup_dump(p, linktype, stdout, "standard output"));
950
951         /*
952          * "a" will cause the file *not* to be truncated if it exists
953          * but will cause it to be created if it doesn't.  It will
954          * also cause all writes to be done at the end of the file,
955          * but will allow reads to be done anywhere in the file.  This
956          * is what we need, because we need to read from the beginning
957          * of the file to see if it already has a header and packets
958          * or if it doesn't.
959          *
960          * "b" is supported as of C90, so *all* UN*Xes should support it,
961          * even though it does nothing.  It's required on Windows, as the
962          * file is a binary file and must be read in binary mode.
963          */
964         f = charset_fopen(fname, "ab+");
965         if (f == NULL) {
966                 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
967                     errno, "%s", fname);
968                 return (NULL);
969         }
970
971         /*
972          * Try to read a pcap header.
973          *
974          * We do not assume that the file will be positioned at the
975          * beginning immediately after we've opened it - we seek to
976          * the beginning.  ISO C says it's implementation-defined
977          * whether the file position indicator is at the beginning
978          * or the end of the file after an append-mode open, and
979          * it wasn't obvious from the Single UNIX Specification
980          * or the Microsoft documentation how that works on SUS-
981          * compliant systems or on Windows.
982          */
983         if (fseek(f, 0, SEEK_SET) == -1) {
984                 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
985                     errno, "Can't seek to the beginning of %s", fname);
986                 (void)fclose(f);
987                 return (NULL);
988         }
989         amt_read = fread(&ph, 1, sizeof (ph), f);
990         if (amt_read != sizeof (ph)) {
991                 if (ferror(f)) {
992                         pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
993                             errno, "%s", fname);
994                         (void)fclose(f);
995                         return (NULL);
996                 } else if (feof(f) && amt_read > 0) {
997                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
998                             "%s: truncated pcap file header", fname);
999                         (void)fclose(f);
1000                         return (NULL);
1001                 }
1002         }
1003
1004 #if defined(_WIN32) || defined(MSDOS)
1005         /*
1006          * We turn off buffering.
1007          * XXX - why?  And why not on the standard output?
1008          */
1009         setvbuf(f, NULL, _IONBF, 0);
1010 #endif
1011
1012         /*
1013          * If a header is already present and:
1014          *
1015          *      it's not for a pcap file of the appropriate resolution
1016          *      and the right byte order for this machine;
1017          *
1018          *      the link-layer header types don't match;
1019          *
1020          *      the snapshot lengths don't match;
1021          *
1022          * return an error.
1023          */
1024         if (amt_read > 0) {
1025                 /*
1026                  * A header is already present.
1027                  * Do the checks.
1028                  */
1029                 switch (ph.magic) {
1030
1031                 case TCPDUMP_MAGIC:
1032                         if (p->opt.tstamp_precision != PCAP_TSTAMP_PRECISION_MICRO) {
1033                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1034                                     "%s: different time stamp precision, cannot append to file", fname);
1035                                 (void)fclose(f);
1036                                 return (NULL);
1037                         }
1038                         break;
1039
1040                 case NSEC_TCPDUMP_MAGIC:
1041                         if (p->opt.tstamp_precision != PCAP_TSTAMP_PRECISION_NANO) {
1042                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1043                                     "%s: different time stamp precision, cannot append to file", fname);
1044                                 (void)fclose(f);
1045                                 return (NULL);
1046                         }
1047                         break;
1048
1049                 case SWAPLONG(TCPDUMP_MAGIC):
1050                 case SWAPLONG(NSEC_TCPDUMP_MAGIC):
1051                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1052                             "%s: different byte order, cannot append to file", fname);
1053                         (void)fclose(f);
1054                         return (NULL);
1055
1056                 case KUZNETZOV_TCPDUMP_MAGIC:
1057                 case SWAPLONG(KUZNETZOV_TCPDUMP_MAGIC):
1058                 case NAVTEL_TCPDUMP_MAGIC:
1059                 case SWAPLONG(NAVTEL_TCPDUMP_MAGIC):
1060                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1061                             "%s: not a pcap file to which we can append", fname);
1062                         (void)fclose(f);
1063                         return (NULL);
1064
1065                 default:
1066                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1067                             "%s: not a pcap file", fname);
1068                         (void)fclose(f);
1069                         return (NULL);
1070                 }
1071
1072                 /*
1073                  * Good version?
1074                  */
1075                 if (ph.version_major != PCAP_VERSION_MAJOR ||
1076                     ph.version_minor != PCAP_VERSION_MINOR) {
1077                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1078                             "%s: version is %u.%u, cannot append to file", fname,
1079                             ph.version_major, ph.version_minor);
1080                         (void)fclose(f);
1081                         return (NULL);
1082                 }
1083                 if ((bpf_u_int32)linktype != ph.linktype) {
1084                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1085                             "%s: different linktype, cannot append to file", fname);
1086                         (void)fclose(f);
1087                         return (NULL);
1088                 }
1089                 if ((bpf_u_int32)p->snapshot != ph.snaplen) {
1090                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1091                             "%s: different snaplen, cannot append to file", fname);
1092                         (void)fclose(f);
1093                         return (NULL);
1094                 }
1095         } else {
1096                 /*
1097                  * A header isn't present; attempt to write it.
1098                  */
1099                 if (sf_write_header(p, f, linktype, p->snapshot) == -1) {
1100                         pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1101                             errno, "Can't write to %s", fname);
1102                         (void)fclose(f);
1103                         return (NULL);
1104                 }
1105         }
1106
1107         /*
1108          * Start writing at the end of the file.
1109          *
1110          * XXX - this shouldn't be necessary, given that we're opening
1111          * the file in append mode, and ISO C specifies that all writes
1112          * are done at the end of the file in that mode.
1113          */
1114         if (fseek(f, 0, SEEK_END) == -1) {
1115                 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1116                     errno, "Can't seek to the end of %s", fname);
1117                 (void)fclose(f);
1118                 return (NULL);
1119         }
1120         return ((pcap_dumper_t *)f);
1121 }
1122
1123 FILE *
1124 pcap_dump_file(pcap_dumper_t *p)
1125 {
1126         return ((FILE *)p);
1127 }
1128
1129 long
1130 pcap_dump_ftell(pcap_dumper_t *p)
1131 {
1132         return (ftell((FILE *)p));
1133 }
1134
1135 #if defined(HAVE_FSEEKO)
1136 /*
1137  * We have fseeko(), so we have ftello().
1138  * If we have large file support (files larger than 2^31-1 bytes),
1139  * ftello() will give us a current file position with more than 32
1140  * bits.
1141  */
1142 int64_t
1143 pcap_dump_ftell64(pcap_dumper_t *p)
1144 {
1145         return (ftello((FILE *)p));
1146 }
1147 #elif defined(_MSC_VER)
1148 /*
1149  * We have Visual Studio; we support only 2005 and later, so we have
1150  * _ftelli64().
1151  */
1152 int64_t
1153 pcap_dump_ftell64(pcap_dumper_t *p)
1154 {
1155         return (_ftelli64((FILE *)p));
1156 }
1157 #else
1158 /*
1159  * We don't have ftello() or _ftelli64(), so fall back on ftell().
1160  * Either long is 64 bits, in which case ftell() should suffice,
1161  * or this is probably an older 32-bit UN*X without large file
1162  * support, which means you'll probably get errors trying to
1163  * write files > 2^31-1, so it won't matter anyway.
1164  *
1165  * XXX - what about MinGW?
1166  */
1167 int64_t
1168 pcap_dump_ftell64(pcap_dumper_t *p)
1169 {
1170         return (ftell((FILE *)p));
1171 }
1172 #endif
1173
1174 int
1175 pcap_dump_flush(pcap_dumper_t *p)
1176 {
1177
1178         if (fflush((FILE *)p) == EOF)
1179                 return (-1);
1180         else
1181                 return (0);
1182 }
1183
1184 void
1185 pcap_dump_close(pcap_dumper_t *p)
1186 {
1187
1188 #ifdef notyet
1189         if (ferror((FILE *)p))
1190                 return-an-error;
1191         /* XXX should check return from fclose() too */
1192 #endif
1193         (void)fclose((FILE *)p);
1194 }