xref: /openbsd-src/lib/libpcap/savefile.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$OpenBSD: savefile.c,v 1.7 1999/07/20 04:49:56 deraadt Exp $	*/
2 
3 /*
4  * Copyright (c) 1993, 1994, 1995, 1996, 1997
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that: (1) source code distributions
9  * retain the above copyright notice and this paragraph in its entirety, (2)
10  * distributions including binary code include the above copyright notice and
11  * this paragraph in its entirety in the documentation or other materials
12  * provided with the distribution, and (3) all advertising materials mentioning
13  * features or use of this software display the following acknowledgement:
14  * ``This product includes software developed by the University of California,
15  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
16  * the University nor the names of its contributors may be used to endorse
17  * or promote products derived from this software without specific prior
18  * written permission.
19  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
20  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
21  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
22  *
23  * savefile.c - supports offline use of tcpdump
24  *	Extraction/creation by Jeffrey Mogul, DECWRL
25  *	Modified by Steve McCanne, LBL.
26  *
27  * Used to save the received packet headers, after filtering, to
28  * a file, and then read them later.
29  * The first record in the file contains saved values for the machine
30  * dependent values so we can print the dump file on any architecture.
31  */
32 
33 #ifndef lint
34 static const char rcsid[] =
35     "@(#) $Header: /home/cvs/src/lib/libpcap/savefile.c,v 1.7 1999/07/20 04:49:56 deraadt Exp $ (LBL)";
36 #endif
37 
38 #include <sys/types.h>
39 #include <sys/time.h>
40 
41 #include <errno.h>
42 #include <memory.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <unistd.h>
46 
47 #ifdef HAVE_OS_PROTO_H
48 #include "os-proto.h"
49 #endif
50 
51 #include "pcap-int.h"
52 
53 #define TCPDUMP_MAGIC 0xa1b2c3d4
54 
55 /*
56  * We use the "receiver-makes-right" approach to byte order,
57  * because time is at a premium when we are writing the file.
58  * In other words, the pcap_file_header and pcap_pkthdr,
59  * records are written in host byte order.
60  * Note that the packets are always written in network byte order.
61  *
62  * ntoh[ls] aren't sufficient because we might need to swap on a big-endian
63  * machine (if the file was written in little-end order).
64  */
65 #define	SWAPLONG(y) \
66 ((((y)&0xff)<<24) | (((y)&0xff00)<<8) | (((y)&0xff0000)>>8) | (((y)>>24)&0xff))
67 #define	SWAPSHORT(y) \
68 	( (((y)&0xff)<<8) | ((u_short)((y)&0xff00)>>8) )
69 
70 #define SFERR_TRUNC		1
71 #define SFERR_BADVERSION	2
72 #define SFERR_BADF		3
73 #define SFERR_EOF		4 /* not really an error, just a status */
74 
75 static int
76 sf_write_header(FILE *fp, int linktype, int thiszone, int snaplen)
77 {
78 	struct pcap_file_header hdr;
79 
80 	hdr.magic = TCPDUMP_MAGIC;
81 	hdr.version_major = PCAP_VERSION_MAJOR;
82 	hdr.version_minor = PCAP_VERSION_MINOR;
83 
84 	hdr.thiszone = thiszone;
85 	hdr.snaplen = snaplen;
86 	hdr.sigfigs = 0;
87 	hdr.linktype = linktype;
88 
89 	if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1)
90 		return (-1);
91 
92 	return (0);
93 }
94 
95 static void
96 swap_hdr(struct pcap_file_header *hp)
97 {
98 	hp->version_major = SWAPSHORT(hp->version_major);
99 	hp->version_minor = SWAPSHORT(hp->version_minor);
100 	hp->thiszone = SWAPLONG(hp->thiszone);
101 	hp->sigfigs = SWAPLONG(hp->sigfigs);
102 	hp->snaplen = SWAPLONG(hp->snaplen);
103 	hp->linktype = SWAPLONG(hp->linktype);
104 }
105 
106 pcap_t *
107 pcap_open_offline(const char *fname, char *errbuf)
108 {
109 	register pcap_t *p;
110 	register FILE *fp;
111 	struct pcap_file_header hdr;
112 	int linklen;
113 
114 	p = (pcap_t *)malloc(sizeof(*p));
115 	if (p == NULL) {
116 		strlcpy(errbuf, "out of swap", PCAP_ERRBUF_SIZE);
117 		return (NULL);
118 	}
119 
120 	memset((char *)p, 0, sizeof(*p));
121 	/*
122 	 * Set this field so we don't close stdin in pcap_close!
123 	 */
124 	p->fd = -1;
125 
126 	if (fname[0] == '-' && fname[1] == '\0')
127 		fp = stdin;
128 	else {
129 		fp = fopen(fname, "r");
130 		if (fp == NULL) {
131 			snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", fname,
132 			    pcap_strerror(errno));
133 			goto bad;
134 		}
135 	}
136 	if (fread((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
137 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "fread: %s",
138 		    pcap_strerror(errno));
139 		goto bad;
140 	}
141 	if (hdr.magic != TCPDUMP_MAGIC) {
142 		if (SWAPLONG(hdr.magic) != TCPDUMP_MAGIC) {
143 			snprintf(errbuf, PCAP_ERRBUF_SIZE,
144 			    "bad dump file format");
145 			goto bad;
146 		}
147 		p->sf.swapped = 1;
148 		swap_hdr(&hdr);
149 	}
150 	if (hdr.version_major < PCAP_VERSION_MAJOR) {
151 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "archaic file format");
152 		goto bad;
153 	}
154 	p->tzoff = hdr.thiszone;
155 	p->snapshot = hdr.snaplen;
156 	p->linktype = hdr.linktype;
157 	p->sf.rfile = fp;
158 	p->bufsize = hdr.snaplen;
159 
160 	/* Align link header as required for proper data alignment */
161 	/* XXX should handle all types */
162 	switch (p->linktype) {
163 
164 	case DLT_EN10MB:
165 		linklen = 14;
166 		break;
167 
168 	case DLT_FDDI:
169 		linklen = 13 + 8;	/* fddi_header + llc */
170 		break;
171 
172 	case DLT_NULL:
173 	default:
174 		linklen = 0;
175 		break;
176 	}
177 
178 	if (p->bufsize < 0)
179 		p->bufsize = BPF_MAXBUFSIZE;
180 	p->sf.base = (u_char *)malloc(p->bufsize + BPF_ALIGNMENT);
181 	if (p->sf.base == NULL) {
182 		strlcpy(errbuf, "out of swap", PCAP_ERRBUF_SIZE);
183 		goto bad;
184 	}
185 	p->buffer = p->sf.base + BPF_ALIGNMENT - (linklen % BPF_ALIGNMENT);
186 	p->sf.version_major = hdr.version_major;
187 	p->sf.version_minor = hdr.version_minor;
188 #ifdef PCAP_FDDIPAD
189 	/* XXX padding only needed for kernel fcode */
190 	pcap_fddipad = 0;
191 #endif
192 
193 	return (p);
194  bad:
195 	free(p);
196 	return (NULL);
197 }
198 
199 /*
200  * Read sf_readfile and return the next packet.  Return the header in hdr
201  * and the contents in buf.  Return 0 on success, SFERR_EOF if there were
202  * no more packets, and SFERR_TRUNC if a partial packet was encountered.
203  */
204 static int
205 sf_next_packet(pcap_t *p, struct pcap_pkthdr *hdr, u_char *buf, int buflen)
206 {
207 	FILE *fp = p->sf.rfile;
208 
209 	/* read the stamp */
210 	if (fread((char *)hdr, sizeof(struct pcap_pkthdr), 1, fp) != 1) {
211 		/* probably an EOF, though could be a truncated packet */
212 		return (1);
213 	}
214 
215 	if (p->sf.swapped) {
216 		/* these were written in opposite byte order */
217 		hdr->caplen = SWAPLONG(hdr->caplen);
218 		hdr->len = SWAPLONG(hdr->len);
219 		hdr->ts.tv_sec = SWAPLONG(hdr->ts.tv_sec);
220 		hdr->ts.tv_usec = SWAPLONG(hdr->ts.tv_usec);
221 	}
222 	/*
223 	 * We interchanged the caplen and len fields at version 2.3,
224 	 * in order to match the bpf header layout.  But unfortunately
225 	 * some files were written with version 2.3 in their headers
226 	 * but without the interchanged fields.
227 	 */
228 	if (p->sf.version_minor < 3 ||
229 	    (p->sf.version_minor == 3 && hdr->caplen > hdr->len)) {
230 		int t = hdr->caplen;
231 		hdr->caplen = hdr->len;
232 		hdr->len = t;
233 	}
234 
235 	if (hdr->caplen > buflen) {
236 		/*
237 		 * This can happen due to Solaris 2.3 systems tripping
238 		 * over the BUFMOD problem and not setting the snapshot
239 		 * correctly in the savefile header.  If the caplen isn't
240 		 * grossly wrong, try to salvage.
241 		 */
242 		static u_char *tp = NULL;
243 		static int tsize = 0;
244 
245 		if (hdr->caplen > 65535) {
246 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
247 			    "bogus savefile header");
248 			return (-1);
249 		}
250 
251 		if (tsize < hdr->caplen) {
252 			tsize = ((hdr->caplen + 1023) / 1024) * 1024;
253 			if (tp != NULL)
254 				free((u_char *)tp);
255 			tp = (u_char *)malloc(tsize);
256 			if (tp == NULL) {
257 				tsize = 0;
258 				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
259 				    "BUFMOD hack malloc");
260 				return (-1);
261 			}
262 		}
263 		if (fread((char *)tp, hdr->caplen, 1, fp) != 1) {
264 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
265 			    "truncated dump file");
266 			return (-1);
267 		}
268 		/*
269 		 * We can only keep up to buflen bytes.  Since caplen > buflen
270 		 * is exactly how we got here, we know we can only keep the
271 		 * first buflen bytes and must drop the remainder.  Adjust
272 		 * caplen accordingly, so we don't get confused later as
273 		 * to how many bytes we have to play with.
274 		 */
275 		hdr->caplen = buflen;
276 		memcpy((char *)buf, (char *)tp, buflen);
277 
278 	} else {
279 		/* read the packet itself */
280 
281 		if (fread((char *)buf, hdr->caplen, 1, fp) != 1) {
282 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
283 			    "truncated dump file");
284 			return (-1);
285 		}
286 	}
287 	return (0);
288 }
289 
290 /*
291  * Print out packets stored in the file initialized by sf_read_init().
292  * If cnt > 0, return after 'cnt' packets, otherwise continue until eof.
293  */
294 int
295 pcap_offline_read(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
296 {
297 	struct bpf_insn *fcode = p->fcode.bf_insns;
298 	int status = 0;
299 	int n = 0;
300 
301 	while (status == 0) {
302 		struct pcap_pkthdr h;
303 
304 		status = sf_next_packet(p, &h, p->buffer, p->bufsize);
305 		if (status) {
306 			if (status == 1)
307 				return (0);
308 			return (status);
309 		}
310 
311 		if (fcode == NULL ||
312 		    bpf_filter(fcode, p->buffer, h.len, h.caplen)) {
313 			(*callback)(user, &h, p->buffer);
314 			if (++n >= cnt && cnt > 0)
315 				break;
316 		}
317 	}
318 	/*XXX this breaks semantics tcpslice expects */
319 	return (n);
320 }
321 
322 /*
323  * Output a packet to the initialized dump file.
324  */
325 void
326 pcap_dump(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
327 {
328 	register FILE *f;
329 
330 	f = (FILE *)user;
331 	/* XXX we should check the return status */
332 	(void)fwrite((char *)h, sizeof(*h), 1, f);
333 	(void)fwrite((char *)sp, h->caplen, 1, f);
334 }
335 
336 /*
337  * Initialize so that sf_write() will output to the file named 'fname'.
338  */
339 pcap_dumper_t *
340 pcap_dump_open(pcap_t *p, const char *fname)
341 {
342 	FILE *f;
343 	if (fname[0] == '-' && fname[1] == '\0')
344 		f = stdout;
345 	else {
346 		f = fopen(fname, "w");
347 		if (f == NULL) {
348 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "%s: %s",
349 			    fname, pcap_strerror(errno));
350 			return (NULL);
351 		}
352 	}
353 	(void)sf_write_header(f, p->linktype, p->tzoff, p->snapshot);
354 	return ((pcap_dumper_t *)f);
355 }
356 
357 void
358 pcap_dump_close(pcap_dumper_t *p)
359 {
360 
361 #ifdef notyet
362 	if (ferror((FILE *)p))
363 		return-an-error;
364 	/* XXX should check return from fclose() too */
365 #endif
366 	(void)fclose((FILE *)p);
367 }
368