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