xref: /freebsd/contrib/libpcap/savefile.c (revision 7fdf597e96a02165cfe22ff357b857d5fa15ed8a)
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  * savefile.c - supports offline use of tcpdump
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 
48 #ifdef HAVE_OS_PROTO_H
49 #include "os-proto.h"
50 #endif
51 
52 #include "sf-pcap.h"
53 #include "sf-pcapng.h"
54 #include "pcap-common.h"
55 #include "charconv.h"
56 
57 #ifdef _WIN32
58 /*
59  * This isn't exported on Windows, because it would only work if both
60  * WinPcap/Npcap and the code using it were to use the Universal CRT; otherwise,
61  * a FILE structure in WinPcap/Npcap and a FILE structure in the code using it
62  * could be different if they're using different versions of the C runtime.
63  *
64  * Instead, pcap/pcap.h defines it as a macro that wraps the hopen version,
65  * with the wrapper calling _fileno() and _get_osfhandle() themselves,
66  * so that it convert the appropriate CRT version's FILE structure to
67  * a HANDLE (which is OS-defined, not CRT-defined, and is part of the Win32
68  * and Win64 ABIs).
69  */
70 static pcap_t *pcap_fopen_offline_with_tstamp_precision(FILE *, u_int, char *);
71 #endif
72 
73 /*
74  * Setting O_BINARY on DOS/Windows is a bit tricky
75  */
76 #if defined(_WIN32)
77   #define SET_BINMODE(f)  _setmode(_fileno(f), _O_BINARY)
78 #elif defined(MSDOS)
79   #if defined(__HIGHC__)
80   #define SET_BINMODE(f)  setmode(f, O_BINARY)
81   #else
82   #define SET_BINMODE(f)  setmode(fileno(f), O_BINARY)
83   #endif
84 #endif
85 
86 static int
87 sf_getnonblock(pcap_t *p _U_)
88 {
89 	/*
90 	 * This is a savefile, not a live capture file, so never say
91 	 * it's in non-blocking mode.
92 	 */
93 	return (0);
94 }
95 
96 static int
97 sf_setnonblock(pcap_t *p, int nonblock _U_)
98 {
99 	/*
100 	 * This is a savefile, not a live capture file, so reject
101 	 * requests to put it in non-blocking mode.  (If it's a
102 	 * pipe, it could be put in non-blocking mode, but that
103 	 * would significantly complicate the code to read packets,
104 	 * as it would have to handle reading partial packets and
105 	 * keeping the state of the read.)
106 	 */
107 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
108 	    "Savefiles cannot be put into non-blocking mode");
109 	return (-1);
110 }
111 
112 static int
113 sf_cant_set_rfmon(pcap_t *p _U_)
114 {
115 	/*
116 	 * This is a savefile, not a device on which you can capture,
117 	 * so never say it supports being put into monitor mode.
118 	 */
119 	return (0);
120 }
121 
122 static int
123 sf_stats(pcap_t *p, struct pcap_stat *ps _U_)
124 {
125 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
126 	    "Statistics aren't available from savefiles");
127 	return (-1);
128 }
129 
130 #ifdef _WIN32
131 static struct pcap_stat *
132 sf_stats_ex(pcap_t *p, int *size _U_)
133 {
134 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
135 	    "Statistics aren't available from savefiles");
136 	return (NULL);
137 }
138 
139 static int
140 sf_setbuff(pcap_t *p, int dim _U_)
141 {
142 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
143 	    "The kernel buffer size cannot be set while reading from a file");
144 	return (-1);
145 }
146 
147 static int
148 sf_setmode(pcap_t *p, int mode _U_)
149 {
150 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
151 	    "impossible to set mode while reading from a file");
152 	return (-1);
153 }
154 
155 static int
156 sf_setmintocopy(pcap_t *p, int size _U_)
157 {
158 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
159 	    "The mintocopy parameter cannot be set while reading from a file");
160 	return (-1);
161 }
162 
163 static HANDLE
164 sf_getevent(pcap_t *pcap)
165 {
166 	(void)snprintf(pcap->errbuf, sizeof(pcap->errbuf),
167 	    "The read event cannot be retrieved while reading from a file");
168 	return (INVALID_HANDLE_VALUE);
169 }
170 
171 static int
172 sf_oid_get_request(pcap_t *p, bpf_u_int32 oid _U_, void *data _U_,
173     size_t *lenp _U_)
174 {
175 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
176 	    "An OID get request cannot be performed on a file");
177 	return (PCAP_ERROR);
178 }
179 
180 static int
181 sf_oid_set_request(pcap_t *p, bpf_u_int32 oid _U_, const void *data _U_,
182     size_t *lenp _U_)
183 {
184 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
185 	    "An OID set request cannot be performed on a file");
186 	return (PCAP_ERROR);
187 }
188 
189 static u_int
190 sf_sendqueue_transmit(pcap_t *p, pcap_send_queue *queue _U_, int sync _U_)
191 {
192 	pcapint_strlcpy(p->errbuf, "Sending packets isn't supported on savefiles",
193 	    PCAP_ERRBUF_SIZE);
194 	return (0);
195 }
196 
197 static int
198 sf_setuserbuffer(pcap_t *p, int size _U_)
199 {
200 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
201 	    "The user buffer cannot be set when reading from a file");
202 	return (-1);
203 }
204 
205 static int
206 sf_live_dump(pcap_t *p, char *filename _U_, int maxsize _U_, int maxpacks _U_)
207 {
208 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
209 	    "Live packet dumping cannot be performed when reading from a file");
210 	return (-1);
211 }
212 
213 static int
214 sf_live_dump_ended(pcap_t *p, int sync _U_)
215 {
216 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
217 	    "Live packet dumping cannot be performed on a pcap_open_dead pcap_t");
218 	return (-1);
219 }
220 
221 static PAirpcapHandle
222 sf_get_airpcap_handle(pcap_t *pcap _U_)
223 {
224 	return (NULL);
225 }
226 #endif
227 
228 static int
229 sf_inject(pcap_t *p, const void *buf _U_, int size _U_)
230 {
231 	pcapint_strlcpy(p->errbuf, "Sending packets isn't supported on savefiles",
232 	    PCAP_ERRBUF_SIZE);
233 	return (-1);
234 }
235 
236 /*
237  * Set direction flag: Which packets do we accept on a forwarding
238  * single device? IN, OUT or both?
239  */
240 static int
241 sf_setdirection(pcap_t *p, pcap_direction_t d _U_)
242 {
243 	snprintf(p->errbuf, sizeof(p->errbuf),
244 	    "Setting direction is not supported on savefiles");
245 	return (-1);
246 }
247 
248 void
249 pcapint_sf_cleanup(pcap_t *p)
250 {
251 	if (p->rfile != stdin)
252 		(void)fclose(p->rfile);
253 	if (p->buffer != NULL)
254 		free(p->buffer);
255 	pcap_freecode(&p->fcode);
256 }
257 
258 #ifdef _WIN32
259 /*
260  * Wrapper for fopen() and _wfopen().
261  *
262  * If we're in UTF-8 mode, map the pathname from UTF-8 to UTF-16LE and
263  * call _wfopen().
264  *
265  * If we're not, just use fopen(); that'll treat it as being in the
266  * local code page.
267  */
268 FILE *
269 pcapint_charset_fopen(const char *path, const char *mode)
270 {
271 	wchar_t *utf16_path;
272 #define MAX_MODE_LEN	16
273 	wchar_t utf16_mode[MAX_MODE_LEN+1];
274 	int i;
275 	char c;
276 	FILE *fp;
277 	int save_errno;
278 
279 	if (pcapint_utf_8_mode) {
280 		/*
281 		 * Map from UTF-8 to UTF-16LE.
282 		 * Fail if there are invalid characters in the input
283 		 * string, rather than converting them to REPLACEMENT
284 		 * CHARACTER; the latter is appropriate for strings
285 		 * to be displayed to the user, but for file names
286 		 * you just want the attempt to open the file to fail.
287 		 */
288 		utf16_path = cp_to_utf_16le(CP_UTF8, path,
289 		    MB_ERR_INVALID_CHARS);
290 		if (utf16_path == NULL) {
291 			/*
292 			 * Error.  Assume errno has been set.
293 			 *
294 			 * XXX - what about Windows errors?
295 			 */
296 			return (NULL);
297 		}
298 
299 		/*
300 		 * Now convert the mode to UTF-16LE as well.
301 		 * We assume the mode is ASCII, and that
302 		 * it's short, so that's easy.
303 		 */
304 		for (i = 0; (c = *mode) != '\0'; i++, mode++) {
305 			if (c > 0x7F) {
306 				/* Not an ASCII character; fail with EINVAL. */
307 				free(utf16_path);
308 				errno = EINVAL;
309 				return (NULL);
310 			}
311 			if (i >= MAX_MODE_LEN) {
312 				/* The mode string is longer than we allow. */
313 				free(utf16_path);
314 				errno = EINVAL;
315 				return (NULL);
316 			}
317 			utf16_mode[i] = c;
318 		}
319 		utf16_mode[i] = '\0';
320 
321 		/*
322 		 * OK, we have UTF-16LE strings; hand them to
323 		 * _wfopen().
324 		 */
325 		fp = _wfopen(utf16_path, utf16_mode);
326 
327 		/*
328 		 * Make sure freeing the UTF-16LE string doesn't
329 		 * overwrite the error code we got from _wfopen().
330 		 */
331 		save_errno = errno;
332 		free(utf16_path);
333 		errno = save_errno;
334 
335 		return (fp);
336 	} else {
337 		/*
338 		 * This takes strings in the local code page as an
339 		 * argument.
340 		 */
341 		return (fopen(path, mode));
342 	}
343 }
344 #endif
345 
346 pcap_t *
347 pcap_open_offline_with_tstamp_precision(const char *fname, u_int precision,
348 					char *errbuf)
349 {
350 	FILE *fp;
351 	pcap_t *p;
352 
353 	if (fname == NULL) {
354 		snprintf(errbuf, PCAP_ERRBUF_SIZE,
355 		    "A null pointer was supplied as the file name");
356 		return (NULL);
357 	}
358 	if (fname[0] == '-' && fname[1] == '\0')
359 	{
360 		fp = stdin;
361 		if (fp == NULL) {
362 			snprintf(errbuf, PCAP_ERRBUF_SIZE,
363 			    "The standard input is not open");
364 			return (NULL);
365 		}
366 #if defined(_WIN32) || defined(MSDOS)
367 		/*
368 		 * We're reading from the standard input, so put it in binary
369 		 * mode, as savefiles are binary files.
370 		 */
371 		SET_BINMODE(fp);
372 #endif
373 	}
374 	else {
375 		/*
376 		 * Use pcapint_charset_fopen(); on Windows, it tests whether we're
377 		 * in "local code page" or "UTF-8" mode, and treats the
378 		 * pathname appropriately, and on other platforms, it just
379 		 * wraps fopen().
380 		 *
381 		 * "b" is supported as of C90, so *all* UN*Xes should
382 		 * support it, even though it does nothing.  For MS-DOS,
383 		 * we again need it.
384 		 */
385 		fp = pcapint_charset_fopen(fname, "rb");
386 		if (fp == NULL) {
387 			pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
388 			    errno, "%s", fname);
389 			return (NULL);
390 		}
391 	}
392 	p = pcap_fopen_offline_with_tstamp_precision(fp, precision, errbuf);
393 	if (p == NULL) {
394 		if (fp != stdin)
395 			fclose(fp);
396 	}
397 	return (p);
398 }
399 
400 pcap_t *
401 pcap_open_offline(const char *fname, char *errbuf)
402 {
403 	return (pcap_open_offline_with_tstamp_precision(fname,
404 	    PCAP_TSTAMP_PRECISION_MICRO, errbuf));
405 }
406 
407 #ifdef _WIN32
408 pcap_t* pcap_hopen_offline_with_tstamp_precision(intptr_t osfd, u_int precision,
409     char *errbuf)
410 {
411 	int fd;
412 	FILE *file;
413 
414 	fd = _open_osfhandle(osfd, _O_RDONLY);
415 	if ( fd < 0 )
416 	{
417 		pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
418 		    errno, "_open_osfhandle");
419 		return NULL;
420 	}
421 
422 	file = _fdopen(fd, "rb");
423 	if ( file == NULL )
424 	{
425 		pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
426 		    errno, "_fdopen");
427 		_close(fd);
428 		return NULL;
429 	}
430 
431 	return pcap_fopen_offline_with_tstamp_precision(file, precision,
432 	    errbuf);
433 }
434 
435 pcap_t* pcap_hopen_offline(intptr_t osfd, char *errbuf)
436 {
437 	return pcap_hopen_offline_with_tstamp_precision(osfd,
438 	    PCAP_TSTAMP_PRECISION_MICRO, errbuf);
439 }
440 #endif
441 
442 /*
443  * Given a link-layer header type and snapshot length, return a
444  * snapshot length to use when reading the file; it's guaranteed
445  * to be > 0 and <= INT_MAX.
446  *
447  * XXX - the only reason why we limit it to <= INT_MAX is so that
448  * it fits in p->snapshot, and the only reason that p->snapshot is
449  * signed is that pcap_snapshot() returns an int, not an unsigned int.
450  */
451 bpf_u_int32
452 pcapint_adjust_snapshot(bpf_u_int32 linktype, bpf_u_int32 snaplen)
453 {
454 	if (snaplen == 0 || snaplen > INT_MAX) {
455 		/*
456 		 * Bogus snapshot length; use the maximum for this
457 		 * link-layer type as a fallback.
458 		 *
459 		 * XXX - we don't clamp snapshot lengths that are
460 		 * <= INT_MAX but > max_snaplen_for_dlt(linktype),
461 		 * so a capture file could cause us to allocate
462 		 * a Really Big Buffer.
463 		 */
464 		snaplen = max_snaplen_for_dlt(linktype);
465 	}
466 	return snaplen;
467 }
468 
469 static pcap_t *(*check_headers[])(const uint8_t *, FILE *, u_int, char *, int *) = {
470 	pcap_check_header,
471 	pcap_ng_check_header
472 };
473 
474 #define	N_FILE_TYPES	(sizeof check_headers / sizeof check_headers[0])
475 
476 #ifdef _WIN32
477 static
478 #endif
479 pcap_t *
480 pcap_fopen_offline_with_tstamp_precision(FILE *fp, u_int precision,
481     char *errbuf)
482 {
483 	register pcap_t *p;
484 	uint8_t magic[4];
485 	size_t amt_read;
486 	u_int i;
487 	int err;
488 
489 	/*
490 	 * Fail if we were passed a NULL fp.
491 	 *
492 	 * That shouldn't happen if we're opening with a path name, but
493 	 * it could happen if buggy code is opening with a FILE * and
494 	 * didn't bother to make sure the FILE * isn't null.
495 	 */
496 	if (fp == NULL) {
497 		snprintf(errbuf, PCAP_ERRBUF_SIZE,
498 		    "Null FILE * pointer provided to savefile open routine");
499 		return (NULL);
500 	}
501 
502 	/*
503 	 * Read the first 4 bytes of the file; the network analyzer dump
504 	 * file formats we support (pcap and pcapng), and several other
505 	 * formats we might support in the future (such as snoop, DOS and
506 	 * Windows Sniffer, and Microsoft Network Monitor) all have magic
507 	 * numbers that are unique in their first 4 bytes.
508 	 */
509 	amt_read = fread(&magic, 1, sizeof(magic), fp);
510 	if (amt_read != sizeof(magic)) {
511 		if (ferror(fp)) {
512 			pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
513 			    errno, "error reading dump file");
514 		} else {
515 			snprintf(errbuf, PCAP_ERRBUF_SIZE,
516 			    "truncated dump file; tried to read %zu file header bytes, only got %zu",
517 			    sizeof(magic), amt_read);
518 		}
519 		return (NULL);
520 	}
521 
522 	/*
523 	 * Try all file types.
524 	 */
525 	for (i = 0; i < N_FILE_TYPES; i++) {
526 		p = (*check_headers[i])(magic, fp, precision, errbuf, &err);
527 		if (p != NULL) {
528 			/* Yup, that's it. */
529 			goto found;
530 		}
531 		if (err) {
532 			/*
533 			 * Error trying to read the header.
534 			 */
535 			return (NULL);
536 		}
537 	}
538 
539 	/*
540 	 * Well, who knows what this mess is....
541 	 */
542 	snprintf(errbuf, PCAP_ERRBUF_SIZE, "unknown file format");
543 	return (NULL);
544 
545 found:
546 	p->rfile = fp;
547 
548 	/* Padding only needed for live capture fcode */
549 	p->fddipad = 0;
550 
551 #if !defined(_WIN32) && !defined(MSDOS)
552 	/*
553 	 * You can do "select()" and "poll()" on plain files on most
554 	 * platforms, and should be able to do so on pipes.
555 	 *
556 	 * You can't do "select()" on anything other than sockets in
557 	 * Windows, so, on Win32 systems, we don't have "selectable_fd".
558 	 */
559 	p->selectable_fd = fileno(fp);
560 #endif
561 
562 	p->can_set_rfmon_op = sf_cant_set_rfmon;
563 	p->read_op = pcapint_offline_read;
564 	p->inject_op = sf_inject;
565 	p->setfilter_op = pcapint_install_bpf_program;
566 	p->setdirection_op = sf_setdirection;
567 	p->set_datalink_op = NULL;	/* we don't support munging link-layer headers */
568 	p->getnonblock_op = sf_getnonblock;
569 	p->setnonblock_op = sf_setnonblock;
570 	p->stats_op = sf_stats;
571 #ifdef _WIN32
572 	p->stats_ex_op = sf_stats_ex;
573 	p->setbuff_op = sf_setbuff;
574 	p->setmode_op = sf_setmode;
575 	p->setmintocopy_op = sf_setmintocopy;
576 	p->getevent_op = sf_getevent;
577 	p->oid_get_request_op = sf_oid_get_request;
578 	p->oid_set_request_op = sf_oid_set_request;
579 	p->sendqueue_transmit_op = sf_sendqueue_transmit;
580 	p->setuserbuffer_op = sf_setuserbuffer;
581 	p->live_dump_op = sf_live_dump;
582 	p->live_dump_ended_op = sf_live_dump_ended;
583 	p->get_airpcap_handle_op = sf_get_airpcap_handle;
584 #endif
585 
586 	/*
587 	 * For offline captures, the standard one-shot callback can
588 	 * be used for pcap_next()/pcap_next_ex().
589 	 */
590 	p->oneshot_callback = pcapint_oneshot;
591 
592 	/*
593 	 * Default breakloop operation.
594 	 */
595 	p->breakloop_op = pcapint_breakloop_common;
596 
597 	/*
598 	 * Savefiles never require special BPF code generation.
599 	 */
600 	p->bpf_codegen_flags = 0;
601 
602 	p->activated = 1;
603 
604 	return (p);
605 }
606 
607 /*
608  * This isn't needed on Windows; we #define pcap_fopen_offline() as
609  * a wrapper around pcap_hopen_offline(), and we don't call it from
610  * inside this file, so it's unused.
611  */
612 #ifndef _WIN32
613 pcap_t *
614 pcap_fopen_offline(FILE *fp, char *errbuf)
615 {
616 	return (pcap_fopen_offline_with_tstamp_precision(fp,
617 	    PCAP_TSTAMP_PRECISION_MICRO, errbuf));
618 }
619 #endif
620 
621 /*
622  * Read packets from a capture file, and call the callback for each
623  * packet.
624  * If cnt > 0, return after 'cnt' packets, otherwise continue until eof.
625  */
626 int
627 pcapint_offline_read(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
628 {
629 	struct bpf_insn *fcode;
630 	int n = 0;
631 	u_char *data;
632 
633 	/*
634 	 * This can conceivably process more than INT_MAX packets,
635 	 * which would overflow the packet count, causing it either
636 	 * to look like a negative number, and thus cause us to
637 	 * return a value that looks like an error, or overflow
638 	 * back into positive territory, and thus cause us to
639 	 * return a too-low count.
640 	 *
641 	 * Therefore, if the packet count is unlimited, we clip
642 	 * it at INT_MAX; this routine is not expected to
643 	 * process packets indefinitely, so that's not an issue.
644 	 */
645 	if (PACKET_COUNT_IS_UNLIMITED(cnt))
646 		cnt = INT_MAX;
647 
648 	for (;;) {
649 		struct pcap_pkthdr h;
650 		int status;
651 
652 		/*
653 		 * Has "pcap_breakloop()" been called?
654 		 * If so, return immediately - if we haven't read any
655 		 * packets, clear the flag and return -2 to indicate
656 		 * that we were told to break out of the loop, otherwise
657 		 * leave the flag set, so that the *next* call will break
658 		 * out of the loop without having read any packets, and
659 		 * return the number of packets we've processed so far.
660 		 */
661 		if (p->break_loop) {
662 			if (n == 0) {
663 				p->break_loop = 0;
664 				return (-2);
665 			} else
666 				return (n);
667 		}
668 
669 		status = p->next_packet_op(p, &h, &data);
670 		if (status < 0) {
671 			/*
672 			 * Error.  Pass it back to the caller.
673 			 */
674 			return (status);
675 		}
676 		if (status == 0) {
677 			/*
678 			 * EOF.  Nothing more to process;
679 			 */
680 			break;
681 		}
682 
683 		/*
684 		 * OK, we've read a packet; run it through the filter
685 		 * and, if it passes, process it.
686 		 */
687 		if ((fcode = p->fcode.bf_insns) == NULL ||
688 		    pcapint_filter(fcode, data, h.len, h.caplen)) {
689 			(*callback)(user, &h, data);
690 			n++;	/* count the packet */
691 			if (n >= cnt)
692 				break;
693 		}
694 	}
695 	/*XXX this breaks semantics tcpslice expects */
696 	return (n);
697 }
698