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