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