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