]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - contrib/libpcap/savefile.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / contrib / libpcap / savefile.c
1 /*
2  * Copyright (c) 1993, 1994, 1995, 1996, 1997
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that: (1) source code distributions
7  * retain the above copyright notice and this paragraph in its entirety, (2)
8  * distributions including binary code include the above copyright notice and
9  * this paragraph in its entirety in the documentation or other materials
10  * provided with the distribution, and (3) all advertising materials mentioning
11  * features or use of this software display the following acknowledgement:
12  * ``This product includes software developed by the University of California,
13  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14  * the University nor the names of its contributors may be used to endorse
15  * or promote products derived from this software without specific prior
16  * written permission.
17  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20  *
21  * 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 #ifndef lint
32 static const char rcsid[] _U_ =
33     "@(#) $Header: /tcpdump/master/libpcap/savefile.c,v 1.126.2.30 2007/08/14 20:57:49 guy Exp $ (LBL)";
34 #endif
35
36 #ifdef HAVE_CONFIG_H
37 #include "config.h"
38 #endif
39
40 #include <errno.h>
41 #include <memory.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45
46 #include "pcap-int.h"
47
48 #ifdef HAVE_OS_PROTO_H
49 #include "os-proto.h"
50 #endif
51
52 /*
53  * Standard libpcap format.
54  */
55 #define TCPDUMP_MAGIC           0xa1b2c3d4
56
57 /*
58  * Alexey Kuznetzov's modified libpcap format.
59  */
60 #define KUZNETZOV_TCPDUMP_MAGIC 0xa1b2cd34
61
62 /*
63  * Reserved for Francisco Mesquita <francisco.mesquita@radiomovel.pt>
64  * for another modified format.
65  */
66 #define FMESQUITA_TCPDUMP_MAGIC 0xa1b234cd
67
68 /*
69  * Navtel Communcations' format, with nanosecond timestamps,
70  * as per a request from Dumas Hwang <dumas.hwang@navtelcom.com>.
71  */
72 #define NAVTEL_TCPDUMP_MAGIC    0xa12b3c4d
73
74 /*
75  * Normal libpcap format, except for seconds/nanoseconds timestamps,
76  * as per a request by Ulf Lamping <ulf.lamping@web.de>
77  */
78 #define NSEC_TCPDUMP_MAGIC      0xa1b23c4d
79
80 /*
81  * We use the "receiver-makes-right" approach to byte order,
82  * because time is at a premium when we are writing the file.
83  * In other words, the pcap_file_header and pcap_pkthdr,
84  * records are written in host byte order.
85  * Note that the bytes of packet data are written out in the order in
86  * which they were received, so multi-byte fields in packets are not
87  * written in host byte order, they're written in whatever order the
88  * sending machine put them in.
89  *
90  * ntoh[ls] aren't sufficient because we might need to swap on a big-endian
91  * machine (if the file was written in little-end order).
92  */
93 #define SWAPLONG(y) \
94 ((((y)&0xff)<<24) | (((y)&0xff00)<<8) | (((y)&0xff0000)>>8) | (((y)>>24)&0xff))
95 #define SWAPSHORT(y) \
96         ( (((y)&0xff)<<8) | ((u_short)((y)&0xff00)>>8) )
97
98 #define SFERR_TRUNC             1
99 #define SFERR_BADVERSION        2
100 #define SFERR_BADF              3
101 #define SFERR_EOF               4 /* not really an error, just a status */
102
103 /*
104  * Setting O_BINARY on DOS/Windows is a bit tricky
105  */
106 #if defined(WIN32)
107   #define SET_BINMODE(f)  _setmode(_fileno(f), _O_BINARY)
108 #elif defined(MSDOS)
109   #if defined(__HIGHC__)
110   #define SET_BINMODE(f)  setmode(f, O_BINARY)
111   #else
112   #define SET_BINMODE(f)  setmode(fileno(f), O_BINARY)
113   #endif
114 #endif
115
116 /*
117  * We don't write DLT_* values to the capture file header, because
118  * they're not the same on all platforms.
119  *
120  * Unfortunately, the various flavors of BSD have not always used the same
121  * numerical values for the same data types, and various patches to
122  * libpcap for non-BSD OSes have added their own DLT_* codes for link
123  * layer encapsulation types seen on those OSes, and those codes have had,
124  * in some cases, values that were also used, on other platforms, for other
125  * link layer encapsulation types.
126  *
127  * This means that capture files of a type whose numerical DLT_* code
128  * means different things on different BSDs, or with different versions
129  * of libpcap, can't always be read on systems other than those like
130  * the one running on the machine on which the capture was made.
131  *
132  * Instead, we define here a set of LINKTYPE_* codes, and map DLT_* codes
133  * to LINKTYPE_* codes when writing a savefile header, and map LINKTYPE_*
134  * codes to DLT_* codes when reading a savefile header.
135  *
136  * For those DLT_* codes that have, as far as we know, the same values on
137  * all platforms (DLT_NULL through DLT_FDDI), we define LINKTYPE_xxx as
138  * DLT_xxx; that way, captures of those types can still be read by
139  * versions of libpcap that map LINKTYPE_* values to DLT_* values, and
140  * captures of those types written by versions of libpcap that map DLT_
141  * values to LINKTYPE_ values can still be read by older versions
142  * of libpcap.
143  *
144  * The other LINKTYPE_* codes are given values starting at 100, in the
145  * hopes that no DLT_* code will be given one of those values.
146  *
147  * In order to ensure that a given LINKTYPE_* code's value will refer to
148  * the same encapsulation type on all platforms, you should not allocate
149  * a new LINKTYPE_* value without consulting "tcpdump-workers@tcpdump.org".
150  * The tcpdump developers will allocate a value for you, and will not
151  * subsequently allocate it to anybody else; that value will be added to
152  * the "pcap.h" in the tcpdump.org CVS repository, so that a future
153  * libpcap release will include it.
154  *
155  * You should, if possible, also contribute patches to libpcap and tcpdump
156  * to handle the new encapsulation type, so that they can also be checked
157  * into the tcpdump.org CVS repository and so that they will appear in
158  * future libpcap and tcpdump releases.
159  *
160  * Do *NOT* assume that any values after the largest value in this file
161  * are available; you might not have the most up-to-date version of this
162  * file, and new values after that one might have been assigned.  Also,
163  * do *NOT* use any values below 100 - those might already have been
164  * taken by one (or more!) organizations.
165  */
166 #define LINKTYPE_NULL           DLT_NULL
167 #define LINKTYPE_ETHERNET       DLT_EN10MB      /* also for 100Mb and up */
168 #define LINKTYPE_EXP_ETHERNET   DLT_EN3MB       /* 3Mb experimental Ethernet */
169 #define LINKTYPE_AX25           DLT_AX25
170 #define LINKTYPE_PRONET         DLT_PRONET
171 #define LINKTYPE_CHAOS          DLT_CHAOS
172 #define LINKTYPE_TOKEN_RING     DLT_IEEE802     /* DLT_IEEE802 is used for Token Ring */
173 #define LINKTYPE_ARCNET         DLT_ARCNET      /* BSD-style headers */
174 #define LINKTYPE_SLIP           DLT_SLIP
175 #define LINKTYPE_PPP            DLT_PPP
176 #define LINKTYPE_FDDI           DLT_FDDI
177
178 /*
179  * LINKTYPE_PPP is for use when there might, or might not, be an RFC 1662
180  * PPP in HDLC-like framing header (with 0xff 0x03 before the PPP protocol
181  * field) at the beginning of the packet.
182  *
183  * This is for use when there is always such a header; the address field
184  * might be 0xff, for regular PPP, or it might be an address field for Cisco
185  * point-to-point with HDLC framing as per section 4.3.1 of RFC 1547 ("Cisco
186  * HDLC").  This is, for example, what you get with NetBSD's DLT_PPP_SERIAL.
187  *
188  * We give it the same value as NetBSD's DLT_PPP_SERIAL, in the hopes that
189  * nobody else will choose a DLT_ value of 50, and so that DLT_PPP_SERIAL
190  * captures will be written out with a link type that NetBSD's tcpdump
191  * can read.
192  */
193 #define LINKTYPE_PPP_HDLC       50              /* PPP in HDLC-like framing */
194
195 #define LINKTYPE_PPP_ETHER      51              /* NetBSD PPP-over-Ethernet */
196
197 #define LINKTYPE_SYMANTEC_FIREWALL 99           /* Symantec Enterprise Firewall */
198
199 #define LINKTYPE_ATM_RFC1483    100             /* LLC/SNAP-encapsulated ATM */
200 #define LINKTYPE_RAW            101             /* raw IP */
201 #define LINKTYPE_SLIP_BSDOS     102             /* BSD/OS SLIP BPF header */
202 #define LINKTYPE_PPP_BSDOS      103             /* BSD/OS PPP BPF header */
203 #define LINKTYPE_C_HDLC         104             /* Cisco HDLC */
204 #define LINKTYPE_IEEE802_11     105             /* IEEE 802.11 (wireless) */
205 #define LINKTYPE_ATM_CLIP       106             /* Linux Classical IP over ATM */
206 #define LINKTYPE_FRELAY         107             /* Frame Relay */
207 #define LINKTYPE_LOOP           108             /* OpenBSD loopback */
208 #define LINKTYPE_ENC            109             /* OpenBSD IPSEC enc */
209
210 /*
211  * These three types are reserved for future use.
212  */
213 #define LINKTYPE_LANE8023       110             /* ATM LANE + 802.3 */
214 #define LINKTYPE_HIPPI          111             /* NetBSD HIPPI */
215 #define LINKTYPE_HDLC           112             /* NetBSD HDLC framing */
216
217 #define LINKTYPE_LINUX_SLL      113             /* Linux cooked socket capture */
218 #define LINKTYPE_LTALK          114             /* Apple LocalTalk hardware */
219 #define LINKTYPE_ECONET         115             /* Acorn Econet */
220
221 /*
222  * Reserved for use with OpenBSD ipfilter.
223  */
224 #define LINKTYPE_IPFILTER       116
225
226 #define LINKTYPE_PFLOG          117             /* OpenBSD DLT_PFLOG */
227 #define LINKTYPE_CISCO_IOS      118             /* For Cisco-internal use */
228 #define LINKTYPE_PRISM_HEADER   119             /* 802.11+Prism II monitor mode */
229 #define LINKTYPE_AIRONET_HEADER 120             /* FreeBSD Aironet driver stuff */
230
231 /*
232  * Reserved for Siemens HiPath HDLC.
233  */
234 #define LINKTYPE_HHDLC          121
235
236 #define LINKTYPE_IP_OVER_FC     122             /* RFC 2625 IP-over-Fibre Channel */
237 #define LINKTYPE_SUNATM         123             /* Solaris+SunATM */
238
239 /*
240  * Reserved as per request from Kent Dahlgren <kent@praesum.com>
241  * for private use.
242  */
243 #define LINKTYPE_RIO            124             /* RapidIO */
244 #define LINKTYPE_PCI_EXP        125             /* PCI Express */
245 #define LINKTYPE_AURORA         126             /* Xilinx Aurora link layer */
246
247 #define LINKTYPE_IEEE802_11_RADIO 127           /* 802.11 plus BSD radio header */
248
249 /*
250  * Reserved for the TZSP encapsulation, as per request from
251  * Chris Waters <chris.waters@networkchemistry.com>
252  * TZSP is a generic encapsulation for any other link type,
253  * which includes a means to include meta-information
254  * with the packet, e.g. signal strength and channel
255  * for 802.11 packets.
256  */
257 #define LINKTYPE_TZSP           128             /* Tazmen Sniffer Protocol */
258
259 #define LINKTYPE_ARCNET_LINUX   129             /* Linux-style headers */
260
261 /*
262  * Juniper-private data link types, as per request from
263  * Hannes Gredler <hannes@juniper.net>.  The corresponding
264  * DLT_s are used for passing on chassis-internal
265  * metainformation such as QOS profiles, etc..
266  */
267 #define LINKTYPE_JUNIPER_MLPPP  130
268 #define LINKTYPE_JUNIPER_MLFR   131
269 #define LINKTYPE_JUNIPER_ES     132
270 #define LINKTYPE_JUNIPER_GGSN   133
271 #define LINKTYPE_JUNIPER_MFR    134
272 #define LINKTYPE_JUNIPER_ATM2   135
273 #define LINKTYPE_JUNIPER_SERVICES 136
274 #define LINKTYPE_JUNIPER_ATM1   137
275
276 #define LINKTYPE_APPLE_IP_OVER_IEEE1394 138     /* Apple IP-over-IEEE 1394 cooked header */
277
278 #define LINKTYPE_MTP2_WITH_PHDR 139
279 #define LINKTYPE_MTP2           140
280 #define LINKTYPE_MTP3           141
281 #define LINKTYPE_SCCP           142
282
283 #define LINKTYPE_DOCSIS         143             /* DOCSIS MAC frames */
284
285 #define LINKTYPE_LINUX_IRDA     144             /* Linux-IrDA */
286
287 /*
288  * Reserved for IBM SP switch and IBM Next Federation switch.
289  */
290 #define LINKTYPE_IBM_SP         145
291 #define LINKTYPE_IBM_SN         146
292
293 /*
294  * Reserved for private use.  If you have some link-layer header type
295  * that you want to use within your organization, with the capture files
296  * using that link-layer header type not ever be sent outside your
297  * organization, you can use these values.
298  *
299  * No libpcap release will use these for any purpose, nor will any
300  * tcpdump release use them, either.
301  *
302  * Do *NOT* use these in capture files that you expect anybody not using
303  * your private versions of capture-file-reading tools to read; in
304  * particular, do *NOT* use them in products, otherwise you may find that
305  * people won't be able to use tcpdump, or snort, or Ethereal, or... to
306  * read capture files from your firewall/intrusion detection/traffic
307  * monitoring/etc. appliance, or whatever product uses that LINKTYPE_ value,
308  * and you may also find that the developers of those applications will
309  * not accept patches to let them read those files.
310  *
311  * Also, do not use them if somebody might send you a capture using them
312  * for *their* private type and tools using them for *your* private type
313  * would have to read them.
314  *
315  * Instead, in those cases, ask "tcpdump-workers@tcpdump.org" for a new DLT_
316  * and LINKTYPE_ value, as per the comment in pcap-bpf.h, and use the type
317  * you're given.
318  */
319 #define LINKTYPE_USER0          147
320 #define LINKTYPE_USER1          148
321 #define LINKTYPE_USER2          149
322 #define LINKTYPE_USER3          150
323 #define LINKTYPE_USER4          151
324 #define LINKTYPE_USER5          152
325 #define LINKTYPE_USER6          153
326 #define LINKTYPE_USER7          154
327 #define LINKTYPE_USER8          155
328 #define LINKTYPE_USER9          156
329 #define LINKTYPE_USER10         157
330 #define LINKTYPE_USER11         158
331 #define LINKTYPE_USER12         159
332 #define LINKTYPE_USER13         160
333 #define LINKTYPE_USER14         161
334 #define LINKTYPE_USER15         162
335
336 /*
337  * For future use with 802.11 captures - defined by AbsoluteValue
338  * Systems to store a number of bits of link-layer information
339  * including radio information:
340  *
341  *      http://www.shaftnet.org/~pizza/software/capturefrm.txt
342  *
343  * but could and arguably should also be used by non-AVS Linux
344  * 802.11 drivers; that may happen in the future.
345  */
346 #define LINKTYPE_IEEE802_11_RADIO_AVS 163       /* 802.11 plus AVS radio header */
347
348 /*
349  * Juniper-private data link type, as per request from
350  * Hannes Gredler <hannes@juniper.net>.  The corresponding
351  * DLT_s are used for passing on chassis-internal
352  * metainformation such as QOS profiles, etc..
353  */
354 #define LINKTYPE_JUNIPER_MONITOR 164
355
356 /*
357  * Reserved for BACnet MS/TP.
358  */
359 #define LINKTYPE_BACNET_MS_TP   165
360
361 /*
362  * Another PPP variant as per request from Karsten Keil <kkeil@suse.de>.
363  *
364  * This is used in some OSes to allow a kernel socket filter to distinguish
365  * between incoming and outgoing packets, on a socket intended to
366  * supply pppd with outgoing packets so it can do dial-on-demand and
367  * hangup-on-lack-of-demand; incoming packets are filtered out so they
368  * don't cause pppd to hold the connection up (you don't want random
369  * input packets such as port scans, packets from old lost connections,
370  * etc. to force the connection to stay up).
371  *
372  * The first byte of the PPP header (0xff03) is modified to accomodate
373  * the direction - 0x00 = IN, 0x01 = OUT.
374  */
375 #define LINKTYPE_PPP_PPPD       166
376
377 /*
378  * Juniper-private data link type, as per request from
379  * Hannes Gredler <hannes@juniper.net>.  The DLT_s are used
380  * for passing on chassis-internal metainformation such as
381  * QOS profiles, cookies, etc..
382  */
383 #define LINKTYPE_JUNIPER_PPPOE     167
384 #define LINKTYPE_JUNIPER_PPPOE_ATM 168
385
386 #define LINKTYPE_GPRS_LLC       169             /* GPRS LLC */
387 #define LINKTYPE_GPF_T          170             /* GPF-T (ITU-T G.7041/Y.1303) */
388 #define LINKTYPE_GPF_F          171             /* GPF-T (ITU-T G.7041/Y.1303) */
389
390 /*
391  * Requested by Oolan Zimmer <oz@gcom.com> for use in Gcom's T1/E1 line
392  * monitoring equipment.
393  */
394 #define LINKTYPE_GCOM_T1E1      172
395 #define LINKTYPE_GCOM_SERIAL    173
396
397 /*
398  * Juniper-private data link type, as per request from
399  * Hannes Gredler <hannes@juniper.net>.  The DLT_ is used
400  * for internal communication to Physical Interface Cards (PIC)
401  */
402 #define LINKTYPE_JUNIPER_PIC_PEER    174
403
404 /*
405  * Link types requested by Gregor Maier <gregor@endace.com> of Endace
406  * Measurement Systems.  They add an ERF header (see
407  * http://www.endace.com/support/EndaceRecordFormat.pdf) in front of
408  * the link-layer header.
409  */
410 #define LINKTYPE_ERF_ETH        175     /* Ethernet */
411 #define LINKTYPE_ERF_POS        176     /* Packet-over-SONET */
412
413 /*
414  * Requested by Daniele Orlandi <daniele@orlandi.com> for raw LAPD
415  * for vISDN (http://www.orlandi.com/visdn/).  Its link-layer header
416  * includes additional information before the LAPD header, so it's
417  * not necessarily a generic LAPD header.
418  */
419 #define LINKTYPE_LINUX_LAPD     177
420
421 /*
422  * Juniper-private data link type, as per request from
423  * Hannes Gredler <hannes@juniper.net>. 
424  * The Link Types are used for prepending meta-information
425  * like interface index, interface name
426  * before standard Ethernet, PPP, Frelay & C-HDLC Frames
427  */
428 #define LINKTYPE_JUNIPER_ETHER  178
429 #define LINKTYPE_JUNIPER_PPP    179
430 #define LINKTYPE_JUNIPER_FRELAY 180
431 #define LINKTYPE_JUNIPER_CHDLC  181
432
433 /*
434  * Multi Link Frame Relay (FRF.16)
435  */
436 #define LINKTYPE_MFR            182
437
438 /*
439  * Juniper-private data link type, as per request from
440  * Hannes Gredler <hannes@juniper.net>. 
441  * The DLT_ is used for internal communication with a
442  * voice Adapter Card (PIC)
443  */
444 #define LINKTYPE_JUNIPER_VP     183
445
446 /*
447  * Arinc 429 frames.
448  * DLT_ requested by Gianluca Varenni <gianluca.varenni@cacetech.com>.
449  * Every frame contains a 32bit A429 label.
450  * More documentation on Arinc 429 can be found at
451  * http://www.condoreng.com/support/downloads/tutorials/ARINCTutorial.pdf
452  */
453 #define LINKTYPE_A429           184
454
455 /*
456  * Arinc 653 Interpartition Communication messages.
457  * DLT_ requested by Gianluca Varenni <gianluca.varenni@cacetech.com>.
458  * Please refer to the A653-1 standard for more information.
459  */
460 #define LINKTYPE_A653_ICM       185
461
462 /*
463  * USB packets, beginning with a USB setup header; requested by
464  * Paolo Abeni <paolo.abeni@email.it>.
465  */
466 #define LINKTYPE_USB            186
467
468 /*
469  * Bluetooth HCI UART transport layer (part H:4); requested by
470  * Paolo Abeni.
471  */
472 #define LINKTYPE_BLUETOOTH_HCI_H4       187
473
474 /*
475  * IEEE 802.16 MAC Common Part Sublayer; requested by Maria Cruz
476  * <cruz_petagay@bah.com>.
477  */
478 #define LINKTYPE_IEEE802_16_MAC_CPS     188
479
480 /*
481  * USB packets, beginning with a Linux USB header; requested by
482  * Paolo Abeni <paolo.abeni@email.it>.
483  */
484 #define LINKTYPE_USB_LINUX      189
485
486 /*
487  * Controller Area Network (CAN) v. 2.0B packets.
488  * DLT_ requested by Gianluca Varenni <gianluca.varenni@cacetech.com>.
489  * Used to dump CAN packets coming from a CAN Vector board.
490  * More documentation on the CAN v2.0B frames can be found at
491  * http://www.can-cia.org/downloads/?269
492  */
493 #define LINKTYPE_CAN20B         190
494
495 /*
496  * IEEE 802.15.4, with address fields padded, as is done by Linux
497  * drivers; requested by Juergen Schimmer.
498  */
499 #define LINKTYPE_IEEE802_15_4_LINUX     191
500
501 /*
502  * Per Packet Information encapsulated packets.
503  * LINKTYPE_ requested by Gianluca Varenni <gianluca.varenni@cacetech.com>.
504  */
505 #define LINKTYPE_PPI                    192
506
507 /*
508  * Header for 802.16 MAC Common Part Sublayer plus a radiotap radio header;
509  * requested by Charles Clancy.
510  */
511 #define LINKTYPE_IEEE802_16_MAC_CPS_RADIO       193
512
513 /*
514  * Juniper-private data link type, as per request from
515  * Hannes Gredler <hannes@juniper.net>. 
516  * The DLT_ is used for internal communication with a
517  * integrated service module (ISM).
518  */
519 #define LINKTYPE_JUNIPER_ISM    194
520
521 /*
522  * IEEE 802.15.4, exactly as it appears in the spec (no padding, no
523  * nothing); requested by Mikko Saarnivala <mikko.saarnivala@sensinode.com>.
524  */
525 #define LINKTYPE_IEEE802_15_4   195
526
527 /*
528  * Various link-layer types, with a pseudo-header, for SITA
529  * (http://www.sita.aero/); requested by Fulko Hew (fulko.hew@gmail.com).
530  */
531 #define LINKTYPE_SITA           196
532
533 /*
534  * Various link-layer types, with a pseudo-header, for Endace DAG cards;
535  * encapsulates Endace ERF records.  Requested by Stephen Donnelly
536  * <stephen@endace.com>.
537  */
538 #define LINKTYPE_ERF            197
539
540 /*
541  * Special header prepended to Ethernet packets when capturing from a
542  * u10 Networks board.  Requested by Phil Mulholland
543  * <phil@u10networks.com>.
544  */
545 #define LINKTYPE_RAIF1          198
546
547 /*
548  * IPMB packet for IPMI, beginning with the I2C slave address, followed
549  * by the netFn and LUN, etc..  Requested by Chanthy Toeung
550  * <chanthy.toeung@ca.kontron.com>.
551  */
552 #define LINKTYPE_IPMB           199
553
554
555 static struct linktype_map {
556         int     dlt;
557         int     linktype;
558 } map[] = {
559         /*
560          * These DLT_* codes have LINKTYPE_* codes with values identical
561          * to the values of the corresponding DLT_* code.
562          */
563         { DLT_NULL,             LINKTYPE_NULL },
564         { DLT_EN10MB,           LINKTYPE_ETHERNET },
565         { DLT_EN3MB,            LINKTYPE_EXP_ETHERNET },
566         { DLT_AX25,             LINKTYPE_AX25 },
567         { DLT_PRONET,           LINKTYPE_PRONET },
568         { DLT_CHAOS,            LINKTYPE_CHAOS },
569         { DLT_IEEE802,          LINKTYPE_TOKEN_RING },
570         { DLT_ARCNET,           LINKTYPE_ARCNET },
571         { DLT_SLIP,             LINKTYPE_SLIP },
572         { DLT_PPP,              LINKTYPE_PPP },
573         { DLT_FDDI,             LINKTYPE_FDDI },
574
575         /*
576          * These DLT_* codes have different values on different
577          * platforms; we map them to LINKTYPE_* codes that
578          * have values that should never be equal to any DLT_*
579          * code.
580          */
581 #ifdef DLT_FR
582         /* BSD/OS Frame Relay */
583         { DLT_FR,               LINKTYPE_FRELAY },
584 #endif
585
586         { DLT_SYMANTEC_FIREWALL, LINKTYPE_SYMANTEC_FIREWALL },
587         { DLT_ATM_RFC1483,      LINKTYPE_ATM_RFC1483 },
588         { DLT_RAW,              LINKTYPE_RAW },
589         { DLT_SLIP_BSDOS,       LINKTYPE_SLIP_BSDOS },
590         { DLT_PPP_BSDOS,        LINKTYPE_PPP_BSDOS },
591
592         /* BSD/OS Cisco HDLC */
593         { DLT_C_HDLC,           LINKTYPE_C_HDLC },
594
595         /*
596          * These DLT_* codes are not on all platforms, but, so far,
597          * there don't appear to be any platforms that define
598          * other codes with those values; we map them to
599          * different LINKTYPE_* values anyway, just in case.
600          */
601
602         /* Linux ATM Classical IP */
603         { DLT_ATM_CLIP,         LINKTYPE_ATM_CLIP },
604
605         /* NetBSD sync/async serial PPP (or Cisco HDLC) */
606         { DLT_PPP_SERIAL,       LINKTYPE_PPP_HDLC },
607
608         /* NetBSD PPP over Ethernet */
609         { DLT_PPP_ETHER,        LINKTYPE_PPP_ETHER },
610
611         /* IEEE 802.11 wireless */
612         { DLT_IEEE802_11,       LINKTYPE_IEEE802_11 },
613
614         /* Frame Relay */
615         { DLT_FRELAY,           LINKTYPE_FRELAY },
616
617         /* OpenBSD loopback */
618         { DLT_LOOP,             LINKTYPE_LOOP },
619
620         /* Linux cooked socket capture */
621         { DLT_LINUX_SLL,        LINKTYPE_LINUX_SLL },
622
623         /* Apple LocalTalk hardware */
624         { DLT_LTALK,            LINKTYPE_LTALK },
625
626         /* Acorn Econet */
627         { DLT_ECONET,           LINKTYPE_ECONET },
628
629         /* OpenBSD DLT_PFLOG */
630         { DLT_PFLOG,            LINKTYPE_PFLOG },
631
632         /* For Cisco-internal use */
633         { DLT_CISCO_IOS,        LINKTYPE_CISCO_IOS },
634
635         /* Prism II monitor-mode header plus 802.11 header */
636         { DLT_PRISM_HEADER,     LINKTYPE_PRISM_HEADER },
637
638         /* FreeBSD Aironet driver stuff */
639         { DLT_AIRONET_HEADER,   LINKTYPE_AIRONET_HEADER },
640
641         /* Siemens HiPath HDLC */
642         { DLT_HHDLC,            LINKTYPE_HHDLC },
643
644         /* RFC 2625 IP-over-Fibre Channel */
645         { DLT_IP_OVER_FC,       LINKTYPE_IP_OVER_FC },
646
647         /* Solaris+SunATM */
648         { DLT_SUNATM,           LINKTYPE_SUNATM },
649
650         /* RapidIO */
651         { DLT_RIO,              LINKTYPE_RIO },
652
653         /* PCI Express */
654         { DLT_PCI_EXP,          LINKTYPE_PCI_EXP },
655
656         /* Xilinx Aurora link layer */
657         { DLT_AURORA,           LINKTYPE_AURORA },
658
659         /* 802.11 plus BSD radio header */
660         { DLT_IEEE802_11_RADIO, LINKTYPE_IEEE802_11_RADIO },
661
662         /* Tazmen Sniffer Protocol */
663         { DLT_TZSP,             LINKTYPE_TZSP },
664
665         /* Arcnet with Linux-style link-layer headers */
666         { DLT_ARCNET_LINUX,     LINKTYPE_ARCNET_LINUX },
667
668         /* Juniper-internal chassis encapsulation */
669         { DLT_JUNIPER_MLPPP,    LINKTYPE_JUNIPER_MLPPP },
670         { DLT_JUNIPER_MLFR,     LINKTYPE_JUNIPER_MLFR },
671         { DLT_JUNIPER_ES,       LINKTYPE_JUNIPER_ES },
672         { DLT_JUNIPER_GGSN,     LINKTYPE_JUNIPER_GGSN },
673         { DLT_JUNIPER_MFR,      LINKTYPE_JUNIPER_MFR },
674         { DLT_JUNIPER_ATM2,     LINKTYPE_JUNIPER_ATM2 },
675         { DLT_JUNIPER_SERVICES, LINKTYPE_JUNIPER_SERVICES },
676         { DLT_JUNIPER_ATM1,     LINKTYPE_JUNIPER_ATM1 },
677
678         /* Apple IP-over-IEEE 1394 cooked header */
679         { DLT_APPLE_IP_OVER_IEEE1394, LINKTYPE_APPLE_IP_OVER_IEEE1394 },
680
681         /* SS7 */
682         { DLT_MTP2_WITH_PHDR,   LINKTYPE_MTP2_WITH_PHDR },
683         { DLT_MTP2,             LINKTYPE_MTP2 },
684         { DLT_MTP3,             LINKTYPE_MTP3 },
685         { DLT_SCCP,             LINKTYPE_SCCP },
686
687         /* DOCSIS MAC frames */
688         { DLT_DOCSIS,           LINKTYPE_DOCSIS },
689
690         /* IrDA IrLAP packets + Linux-cooked header */
691         { DLT_LINUX_IRDA,       LINKTYPE_LINUX_IRDA },
692
693         /* IBM SP and Next Federation switches */
694         { DLT_IBM_SP,           LINKTYPE_IBM_SP },
695         { DLT_IBM_SN,           LINKTYPE_IBM_SN },
696
697         /* 802.11 plus AVS radio header */
698         { DLT_IEEE802_11_RADIO_AVS, LINKTYPE_IEEE802_11_RADIO_AVS },
699
700         /*
701          * Any platform that defines additional DLT_* codes should:
702          *
703          *      request a LINKTYPE_* code and value from tcpdump.org,
704          *      as per the above;
705          *
706          *      add, in their version of libpcap, an entry to map
707          *      those DLT_* codes to the corresponding LINKTYPE_*
708          *      code;
709          *
710          *      redefine, in their "net/bpf.h", any DLT_* values
711          *      that collide with the values used by their additional
712          *      DLT_* codes, to remove those collisions (but without
713          *      making them collide with any of the LINKTYPE_*
714          *      values equal to 50 or above; they should also avoid
715          *      defining DLT_* values that collide with those
716          *      LINKTYPE_* values, either).
717          */
718
719         /* Juniper-internal chassis encapsulation */
720         { DLT_JUNIPER_MONITOR,  LINKTYPE_JUNIPER_MONITOR },
721
722         /* BACnet MS/TP */
723         { DLT_BACNET_MS_TP,     LINKTYPE_BACNET_MS_TP },
724
725         /* PPP for pppd, with direction flag in the PPP header */
726         { DLT_PPP_PPPD,         LINKTYPE_PPP_PPPD},
727
728         /* Juniper-internal chassis encapsulation */
729         { DLT_JUNIPER_PPPOE,    LINKTYPE_JUNIPER_PPPOE },
730         { DLT_JUNIPER_PPPOE_ATM,LINKTYPE_JUNIPER_PPPOE_ATM },
731
732         /* GPRS LLC */
733         { DLT_GPRS_LLC,         LINKTYPE_GPRS_LLC },
734
735         /* Transparent Generic Framing Procedure (ITU-T G.7041/Y.1303) */
736         { DLT_GPF_T,            LINKTYPE_GPF_T },
737
738         /* Framed Generic Framing Procedure (ITU-T G.7041/Y.1303) */
739         { DLT_GPF_F,            LINKTYPE_GPF_F },
740
741         { DLT_GCOM_T1E1,        LINKTYPE_GCOM_T1E1 },
742         { DLT_GCOM_SERIAL,      LINKTYPE_GCOM_SERIAL },
743
744         /* Juniper-internal chassis encapsulation */
745         { DLT_JUNIPER_PIC_PEER, LINKTYPE_JUNIPER_PIC_PEER },
746
747         /* Endace types */
748         { DLT_ERF_ETH,          LINKTYPE_ERF_ETH },
749         { DLT_ERF_POS,          LINKTYPE_ERF_POS },
750
751         /* viSDN LAPD */
752         { DLT_LINUX_LAPD,       LINKTYPE_LINUX_LAPD },
753
754         /* Juniper meta-information before Ether, PPP, Frame Relay, C-HDLC Frames */
755         { DLT_JUNIPER_ETHER, LINKTYPE_JUNIPER_ETHER },
756         { DLT_JUNIPER_PPP, LINKTYPE_JUNIPER_PPP },
757         { DLT_JUNIPER_FRELAY, LINKTYPE_JUNIPER_FRELAY },
758         { DLT_JUNIPER_CHDLC, LINKTYPE_JUNIPER_CHDLC },
759
760         /* Multi Link Frame Relay (FRF.16) */
761         { DLT_MFR,              LINKTYPE_MFR },
762
763         /* Juniper Voice PIC */
764         { DLT_JUNIPER_VP,       LINKTYPE_JUNIPER_VP },
765
766         /* Controller Area Network (CAN) v2.0B */
767         { DLT_A429,             LINKTYPE_A429 },
768
769         /* Arinc 653 Interpartition Communication messages */
770         { DLT_A653_ICM,         LINKTYPE_A653_ICM },
771
772         /* USB */
773         { DLT_USB,              LINKTYPE_USB },
774
775         /* Bluetooth HCI UART transport layer */
776         { DLT_BLUETOOTH_HCI_H4, LINKTYPE_BLUETOOTH_HCI_H4 },
777
778         /* IEEE 802.16 MAC Common Part Sublayer */
779         { DLT_IEEE802_16_MAC_CPS,       LINKTYPE_IEEE802_16_MAC_CPS },
780
781         /* USB with Linux header */
782         { DLT_USB_LINUX,        LINKTYPE_USB_LINUX },
783
784         /* Controller Area Network (CAN) v2.0B */
785         { DLT_CAN20B,           LINKTYPE_CAN20B },
786
787         /* IEEE 802.15.4 with address fields padded */
788         { DLT_IEEE802_15_4_LINUX,       LINKTYPE_IEEE802_15_4_LINUX },
789
790         /* Per Packet Information encapsulated packets */
791         { DLT_PPI,                      LINKTYPE_PPI },
792
793         /* IEEE 802.16 MAC Common Part Sublayer plus radiotap header */
794         { DLT_IEEE802_16_MAC_CPS_RADIO, LINKTYPE_IEEE802_16_MAC_CPS_RADIO },
795
796         /* Juniper Voice ISM */
797         { DLT_JUNIPER_ISM,      LINKTYPE_JUNIPER_ISM },
798
799         /* IEEE 802.15.4 exactly as it appears in the spec */
800         { DLT_IEEE802_15_4,     LINKTYPE_IEEE802_15_4 },
801
802         /* Various link-layer types for SITA */
803         { DLT_SITA,             LINKTYPE_SITA },
804
805         /* Various link-layer types for Endace */
806         { DLT_ERF,              LINKTYPE_ERF },
807
808         /* Special header for u10 Networks boards */
809         { DLT_RAIF1,            LINKTYPE_RAIF1 },
810
811         /* IPMB */
812         { DLT_IPMB,             LINKTYPE_IPMB },
813
814         /* enc0 device */
815         { DLT_ENC,              LINKTYPE_ENC },
816
817         { -1,                   -1 }
818 };
819
820 static int
821 dlt_to_linktype(int dlt)
822 {
823         int i;
824
825         for (i = 0; map[i].dlt != -1; i++) {
826                 if (map[i].dlt == dlt)
827                         return (map[i].linktype);
828         }
829
830         /*
831          * If we don't have a mapping for this DLT_ code, return an
832          * error; that means that the table above needs to have an
833          * entry added.
834          */
835         return (-1);
836 }
837
838 static int
839 linktype_to_dlt(int linktype)
840 {
841         int i;
842
843         for (i = 0; map[i].linktype != -1; i++) {
844                 if (map[i].linktype == linktype)
845                         return (map[i].dlt);
846         }
847
848         /*
849          * If we don't have an entry for this link type, return
850          * the link type value; it may be a DLT_ value from an
851          * older version of libpcap.
852          */
853         return linktype;
854 }
855
856 static int
857 sf_write_header(FILE *fp, int linktype, int thiszone, int snaplen)
858 {
859         struct pcap_file_header hdr;
860
861         hdr.magic = TCPDUMP_MAGIC;
862         hdr.version_major = PCAP_VERSION_MAJOR;
863         hdr.version_minor = PCAP_VERSION_MINOR;
864
865         hdr.thiszone = thiszone;
866         hdr.snaplen = snaplen;
867         hdr.sigfigs = 0;
868         hdr.linktype = linktype;
869
870         if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1)
871                 return (-1);
872
873         return (0);
874 }
875
876 static void
877 swap_hdr(struct pcap_file_header *hp)
878 {
879         hp->version_major = SWAPSHORT(hp->version_major);
880         hp->version_minor = SWAPSHORT(hp->version_minor);
881         hp->thiszone = SWAPLONG(hp->thiszone);
882         hp->sigfigs = SWAPLONG(hp->sigfigs);
883         hp->snaplen = SWAPLONG(hp->snaplen);
884         hp->linktype = SWAPLONG(hp->linktype);
885 }
886
887 static int
888 sf_getnonblock(pcap_t *p, char *errbuf)
889 {
890         /*
891          * This is a savefile, not a live capture file, so never say
892          * it's in non-blocking mode.
893          */
894         return (0);
895 }
896
897 static int
898 sf_setnonblock(pcap_t *p, int nonblock, char *errbuf)
899 {
900         /*
901          * This is a savefile, not a live capture file, so ignore
902          * requests to put it in non-blocking mode.
903          */
904         return (0);
905 }
906
907 static int
908 sf_stats(pcap_t *p, struct pcap_stat *ps)
909 {
910         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
911             "Statistics aren't available from savefiles");
912         return (-1);
913 }
914
915 static int
916 sf_inject(pcap_t *p, const void *buf _U_, size_t size _U_)
917 {
918         strlcpy(p->errbuf, "Sending packets isn't supported on savefiles",
919             PCAP_ERRBUF_SIZE);
920         return (-1);
921 }
922
923 /*
924  * Set direction flag: Which packets do we accept on a forwarding
925  * single device? IN, OUT or both?
926  */
927 static int
928 sf_setdirection(pcap_t *p, pcap_direction_t d)
929 {
930         snprintf(p->errbuf, sizeof(p->errbuf),
931             "Setting direction is not supported on savefiles");
932         return (-1);
933 }
934
935 static void
936 sf_close(pcap_t *p)
937 {
938         if (p->sf.rfile != stdin)
939                 (void)fclose(p->sf.rfile);
940         if (p->sf.base != NULL)
941                 free(p->sf.base);
942 }
943
944 pcap_t *
945 pcap_open_offline(const char *fname, char *errbuf)
946 {
947         FILE *fp;
948         pcap_t *p;
949
950         if (fname[0] == '-' && fname[1] == '\0')
951         {
952                 fp = stdin;
953 #if defined(WIN32) || defined(MSDOS)
954                 /*
955                  * We're reading from the standard input, so put it in binary
956                  * mode, as savefiles are binary files.
957                  */
958                 SET_BINMODE(fp);
959 #endif
960         }
961         else {
962 #if !defined(WIN32) && !defined(MSDOS)
963                 fp = fopen(fname, "r");
964 #else
965                 fp = fopen(fname, "rb");
966 #endif
967                 if (fp == NULL) {
968                         snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", fname,
969                             pcap_strerror(errno));
970                         return (NULL);
971                 }
972         }
973         p = pcap_fopen_offline(fp, errbuf);
974         if (p == NULL) {
975                 if (fp != stdin)
976                         fclose(fp);
977         }
978         return (p);
979 }
980
981 pcap_t *
982 pcap_fopen_offline(FILE *fp, char *errbuf)
983 {
984         register pcap_t *p;
985         struct pcap_file_header hdr;
986         size_t amt_read;
987         bpf_u_int32 magic;
988         int linklen;
989
990         p = (pcap_t *)malloc(sizeof(*p));
991         if (p == NULL) {
992                 strlcpy(errbuf, "out of swap", PCAP_ERRBUF_SIZE);
993                 return (NULL);
994         }
995
996         memset((char *)p, 0, sizeof(*p));
997
998         amt_read = fread((char *)&hdr, 1, sizeof(hdr), fp);
999         if (amt_read != sizeof(hdr)) {
1000                 if (ferror(fp)) {
1001                         snprintf(errbuf, PCAP_ERRBUF_SIZE,
1002                             "error reading dump file: %s",
1003                             pcap_strerror(errno));
1004                 } else {
1005                         snprintf(errbuf, PCAP_ERRBUF_SIZE,
1006                             "truncated dump file; tried to read %lu file header bytes, only got %lu",
1007                             (unsigned long)sizeof(hdr),
1008                             (unsigned long)amt_read);
1009                 }
1010                 goto bad;
1011         }
1012         magic = hdr.magic;
1013         if (magic != TCPDUMP_MAGIC && magic != KUZNETZOV_TCPDUMP_MAGIC) {
1014                 magic = SWAPLONG(magic);
1015                 if (magic != TCPDUMP_MAGIC && magic != KUZNETZOV_TCPDUMP_MAGIC) {
1016                         snprintf(errbuf, PCAP_ERRBUF_SIZE,
1017                             "bad dump file format");
1018                         goto bad;
1019                 }
1020                 p->sf.swapped = 1;
1021                 swap_hdr(&hdr);
1022         }
1023         if (magic == KUZNETZOV_TCPDUMP_MAGIC) {
1024                 /*
1025                  * XXX - the patch that's in some versions of libpcap
1026                  * changes the packet header but not the magic number,
1027                  * and some other versions with this magic number have
1028                  * some extra debugging information in the packet header;
1029                  * we'd have to use some hacks^H^H^H^H^Hheuristics to
1030                  * detect those variants.
1031                  *
1032                  * Ethereal does that, but it does so by trying to read
1033                  * the first two packets of the file with each of the
1034                  * record header formats.  That currently means it seeks
1035                  * backwards and retries the reads, which doesn't work
1036                  * on pipes.  We want to be able to read from a pipe, so
1037                  * that strategy won't work; we'd have to buffer some
1038                  * data ourselves and read from that buffer in order to
1039                  * make that work.
1040                  */
1041                 p->sf.hdrsize = sizeof(struct pcap_sf_patched_pkthdr);
1042         } else
1043                 p->sf.hdrsize = sizeof(struct pcap_sf_pkthdr);
1044         if (hdr.version_major < PCAP_VERSION_MAJOR) {
1045                 snprintf(errbuf, PCAP_ERRBUF_SIZE, "archaic file format");
1046                 goto bad;
1047         }
1048         p->tzoff = hdr.thiszone;
1049         p->snapshot = hdr.snaplen;
1050         p->linktype = linktype_to_dlt(hdr.linktype);
1051         if (magic == KUZNETZOV_TCPDUMP_MAGIC && p->linktype == DLT_EN10MB) {
1052                 /*
1053                  * This capture might have been done in raw mode or cooked
1054                  * mode.
1055                  *
1056                  * If it was done in cooked mode, p->snapshot was passed
1057                  * to recvfrom() as the buffer size, meaning that the
1058                  * most packet data that would be copied would be
1059                  * p->snapshot.  However, a faked Ethernet header would
1060                  * then have been added to it, so the most data that would
1061                  * be in a packet in the file would be p->snapshot + 14.
1062                  *
1063                  * We can't easily tell whether the capture was done in
1064                  * raw mode or cooked mode, so we'll assume it was
1065                  * cooked mode, and add 14 to the snapshot length.  That
1066                  * means that, for a raw capture, the snapshot length will
1067                  * be misleading if you use it to figure out why a capture
1068                  * doesn't have all the packet data, but there's not much
1069                  * we can do to avoid that.
1070                  */
1071                 p->snapshot += 14;
1072         }
1073         p->sf.rfile = fp;
1074 #ifndef WIN32
1075         p->bufsize = hdr.snaplen;
1076 #else
1077         /* Allocate the space for pcap_pkthdr as well. It will be used by pcap_read_ex */
1078         p->bufsize = hdr.snaplen+sizeof(struct pcap_pkthdr);
1079 #endif
1080
1081         /* Align link header as required for proper data alignment */
1082         /* XXX should handle all types */
1083         switch (p->linktype) {
1084
1085         case DLT_EN10MB:
1086                 linklen = 14;
1087                 break;
1088
1089         case DLT_FDDI:
1090                 linklen = 13 + 8;       /* fddi_header + llc */
1091                 break;
1092
1093         case DLT_NULL:
1094         default:
1095                 linklen = 0;
1096                 break;
1097         }
1098
1099         if (p->bufsize < 0)
1100                 p->bufsize = BPF_MAXBUFSIZE;
1101         p->sf.base = (u_char *)malloc(p->bufsize + BPF_ALIGNMENT);
1102         if (p->sf.base == NULL) {
1103                 strlcpy(errbuf, "out of swap", PCAP_ERRBUF_SIZE);
1104                 goto bad;
1105         }
1106         p->buffer = p->sf.base + BPF_ALIGNMENT - (linklen % BPF_ALIGNMENT);
1107         p->sf.version_major = hdr.version_major;
1108         p->sf.version_minor = hdr.version_minor;
1109 #ifdef PCAP_FDDIPAD
1110         /* Padding only needed for live capture fcode */
1111         p->fddipad = 0;
1112 #endif
1113
1114         /*
1115          * We interchanged the caplen and len fields at version 2.3,
1116          * in order to match the bpf header layout.  But unfortunately
1117          * some files were written with version 2.3 in their headers
1118          * but without the interchanged fields.
1119          *
1120          * In addition, DG/UX tcpdump writes out files with a version
1121          * number of 543.0, and with the caplen and len fields in the
1122          * pre-2.3 order.
1123          */
1124         switch (hdr.version_major) {
1125
1126         case 2:
1127                 if (hdr.version_minor < 3)
1128                         p->sf.lengths_swapped = SWAPPED;
1129                 else if (hdr.version_minor == 3)
1130                         p->sf.lengths_swapped = MAYBE_SWAPPED;
1131                 else
1132                         p->sf.lengths_swapped = NOT_SWAPPED;
1133                 break;
1134
1135         case 543:
1136                 p->sf.lengths_swapped = SWAPPED;
1137                 break;
1138
1139         default:
1140                 p->sf.lengths_swapped = NOT_SWAPPED;
1141                 break;
1142         }
1143
1144 #if !defined(WIN32) && !defined(MSDOS)
1145         /*
1146          * You can do "select()" and "poll()" on plain files on most
1147          * platforms, and should be able to do so on pipes.
1148          *
1149          * You can't do "select()" on anything other than sockets in
1150          * Windows, so, on Win32 systems, we don't have "selectable_fd".
1151          */
1152         p->selectable_fd = fileno(fp);
1153 #endif
1154
1155         p->read_op = pcap_offline_read;
1156         p->inject_op = sf_inject;
1157         p->setfilter_op = install_bpf_program;
1158         p->setdirection_op = sf_setdirection;
1159         p->set_datalink_op = NULL;      /* we don't support munging link-layer headers */
1160         p->getnonblock_op = sf_getnonblock;
1161         p->setnonblock_op = sf_setnonblock;
1162         p->stats_op = sf_stats;
1163         p->close_op = sf_close;
1164
1165         return (p);
1166  bad:
1167         free(p);
1168         return (NULL);
1169 }
1170
1171 /*
1172  * Read sf_readfile and return the next packet.  Return the header in hdr
1173  * and the contents in buf.  Return 0 on success, SFERR_EOF if there were
1174  * no more packets, and SFERR_TRUNC if a partial packet was encountered.
1175  */
1176 static int
1177 sf_next_packet(pcap_t *p, struct pcap_pkthdr *hdr, u_char *buf, u_int buflen)
1178 {
1179         struct pcap_sf_patched_pkthdr sf_hdr;
1180         FILE *fp = p->sf.rfile;
1181         size_t amt_read;
1182         bpf_u_int32 t;
1183
1184         /*
1185          * Read the packet header; the structure we use as a buffer
1186          * is the longer structure for files generated by the patched
1187          * libpcap, but if the file has the magic number for an
1188          * unpatched libpcap we only read as many bytes as the regular
1189          * header has.
1190          */
1191         amt_read = fread(&sf_hdr, 1, p->sf.hdrsize, fp);
1192         if (amt_read != p->sf.hdrsize) {
1193                 if (ferror(fp)) {
1194                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1195                             "error reading dump file: %s",
1196                             pcap_strerror(errno));
1197                         return (-1);
1198                 } else {
1199                         if (amt_read != 0) {
1200                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1201                                     "truncated dump file; tried to read %d header bytes, only got %lu",
1202                                     p->sf.hdrsize, (unsigned long)amt_read);
1203                                 return (-1);
1204                         }
1205                         /* EOF */
1206                         return (1);
1207                 }
1208         }
1209
1210         if (p->sf.swapped) {
1211                 /* these were written in opposite byte order */
1212                 hdr->caplen = SWAPLONG(sf_hdr.caplen);
1213                 hdr->len = SWAPLONG(sf_hdr.len);
1214                 hdr->ts.tv_sec = SWAPLONG(sf_hdr.ts.tv_sec);
1215                 hdr->ts.tv_usec = SWAPLONG(sf_hdr.ts.tv_usec);
1216         } else {
1217                 hdr->caplen = sf_hdr.caplen;
1218                 hdr->len = sf_hdr.len;
1219                 hdr->ts.tv_sec = sf_hdr.ts.tv_sec;
1220                 hdr->ts.tv_usec = sf_hdr.ts.tv_usec;
1221         }
1222         /* Swap the caplen and len fields, if necessary. */
1223         switch (p->sf.lengths_swapped) {
1224
1225         case NOT_SWAPPED:
1226                 break;
1227
1228         case MAYBE_SWAPPED:
1229                 if (hdr->caplen <= hdr->len) {
1230                         /*
1231                          * The captured length is <= the actual length,
1232                          * so presumably they weren't swapped.
1233                          */
1234                         break;
1235                 }
1236                 /* FALLTHROUGH */
1237
1238         case SWAPPED:
1239                 t = hdr->caplen;
1240                 hdr->caplen = hdr->len;
1241                 hdr->len = t;
1242                 break;
1243         }
1244
1245         if (hdr->caplen > buflen) {
1246                 /*
1247                  * This can happen due to Solaris 2.3 systems tripping
1248                  * over the BUFMOD problem and not setting the snapshot
1249                  * correctly in the savefile header.  If the caplen isn't
1250                  * grossly wrong, try to salvage.
1251                  */
1252                 static u_char *tp = NULL;
1253                 static size_t tsize = 0;
1254
1255                 if (hdr->caplen > 65535) {
1256                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1257                             "bogus savefile header");
1258                         return (-1);
1259                 }
1260
1261                 if (tsize < hdr->caplen) {
1262                         tsize = ((hdr->caplen + 1023) / 1024) * 1024;
1263                         if (tp != NULL)
1264                                 free((u_char *)tp);
1265                         tp = (u_char *)malloc(tsize);
1266                         if (tp == NULL) {
1267                                 tsize = 0;
1268                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1269                                     "BUFMOD hack malloc");
1270                                 return (-1);
1271                         }
1272                 }
1273                 amt_read = fread((char *)tp, 1, hdr->caplen, fp);
1274                 if (amt_read != hdr->caplen) {
1275                         if (ferror(fp)) {
1276                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1277                                     "error reading dump file: %s",
1278                                     pcap_strerror(errno));
1279                         } else {
1280                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1281                                     "truncated dump file; tried to read %u captured bytes, only got %lu",
1282                                     hdr->caplen, (unsigned long)amt_read);
1283                         }
1284                         return (-1);
1285                 }
1286                 /*
1287                  * We can only keep up to buflen bytes.  Since caplen > buflen
1288                  * is exactly how we got here, we know we can only keep the
1289                  * first buflen bytes and must drop the remainder.  Adjust
1290                  * caplen accordingly, so we don't get confused later as
1291                  * to how many bytes we have to play with.
1292                  */
1293                 hdr->caplen = buflen;
1294                 memcpy((char *)buf, (char *)tp, buflen);
1295
1296         } else {
1297                 /* read the packet itself */
1298                 amt_read = fread((char *)buf, 1, hdr->caplen, fp);
1299                 if (amt_read != hdr->caplen) {
1300                         if (ferror(fp)) {
1301                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1302                                     "error reading dump file: %s",
1303                                     pcap_strerror(errno));
1304                         } else {
1305                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1306                                     "truncated dump file; tried to read %u captured bytes, only got %lu",
1307                                     hdr->caplen, (unsigned long)amt_read);
1308                         }
1309                         return (-1);
1310                 }
1311         }
1312         return (0);
1313 }
1314
1315 /*
1316  * Print out packets stored in the file initialized by sf_read_init().
1317  * If cnt > 0, return after 'cnt' packets, otherwise continue until eof.
1318  */
1319 int
1320 pcap_offline_read(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
1321 {
1322         struct bpf_insn *fcode;
1323         int status = 0;
1324         int n = 0;
1325
1326         while (status == 0) {
1327                 struct pcap_pkthdr h;
1328
1329                 /*
1330                  * Has "pcap_breakloop()" been called?
1331                  * If so, return immediately - if we haven't read any
1332                  * packets, clear the flag and return -2 to indicate
1333                  * that we were told to break out of the loop, otherwise
1334                  * leave the flag set, so that the *next* call will break
1335                  * out of the loop without having read any packets, and
1336                  * return the number of packets we've processed so far.
1337                  */
1338                 if (p->break_loop) {
1339                         if (n == 0) {
1340                                 p->break_loop = 0;
1341                                 return (-2);
1342                         } else
1343                                 return (n);
1344                 }
1345
1346                 status = sf_next_packet(p, &h, p->buffer, p->bufsize);
1347                 if (status) {
1348                         if (status == 1)
1349                                 return (0);
1350                         return (status);
1351                 }
1352
1353                 if ((fcode = p->fcode.bf_insns) == NULL ||
1354                     bpf_filter(fcode, p->buffer, h.len, h.caplen)) {
1355                         (*callback)(user, &h, p->buffer);
1356                         if (++n >= cnt && cnt > 0)
1357                                 break;
1358                 }
1359         }
1360         /*XXX this breaks semantics tcpslice expects */
1361         return (n);
1362 }
1363
1364 /*
1365  * Output a packet to the initialized dump file.
1366  */
1367 void
1368 pcap_dump(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1369 {
1370         register FILE *f;
1371         struct pcap_sf_pkthdr sf_hdr;
1372
1373         f = (FILE *)user;
1374         sf_hdr.ts.tv_sec  = h->ts.tv_sec;
1375         sf_hdr.ts.tv_usec = h->ts.tv_usec;
1376         sf_hdr.caplen     = h->caplen;
1377         sf_hdr.len        = h->len;
1378         /* XXX we should check the return status */
1379         (void)fwrite(&sf_hdr, sizeof(sf_hdr), 1, f);
1380         (void)fwrite(sp, h->caplen, 1, f);
1381 }
1382
1383 static pcap_dumper_t *
1384 pcap_setup_dump(pcap_t *p, int linktype, FILE *f, const char *fname)
1385 {
1386
1387 #if defined(WIN32) || defined(MSDOS)
1388         /*
1389          * If we're writing to the standard output, put it in binary
1390          * mode, as savefiles are binary files.
1391          *
1392          * Otherwise, we turn off buffering.
1393          * XXX - why?  And why not on the standard output?
1394          */
1395         if (f == stdout)
1396                 SET_BINMODE(f);
1397         else
1398                 setbuf(f, NULL);
1399 #endif
1400         if (sf_write_header(f, linktype, p->tzoff, p->snapshot) == -1) {
1401                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Can't write to %s: %s",
1402                     fname, pcap_strerror(errno));
1403                 if (f != stdout)
1404                         (void)fclose(f);
1405                 return (NULL);
1406         }
1407         return ((pcap_dumper_t *)f);
1408 }
1409
1410 /*
1411  * Initialize so that sf_write() will output to the file named 'fname'.
1412  */
1413 pcap_dumper_t *
1414 pcap_dump_open(pcap_t *p, const char *fname)
1415 {
1416         FILE *f;
1417         int linktype;
1418
1419         linktype = dlt_to_linktype(p->linktype);
1420         if (linktype == -1) {
1421                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1422                     "%s: link-layer type %d isn't supported in savefiles",
1423                     fname, linktype);
1424                 return (NULL);
1425         }
1426
1427         if (fname[0] == '-' && fname[1] == '\0') {
1428                 f = stdout;
1429                 fname = "standard output";
1430         } else {
1431 #if !defined(WIN32) && !defined(MSDOS)
1432                 f = fopen(fname, "w");
1433 #else
1434                 f = fopen(fname, "wb");
1435 #endif
1436                 if (f == NULL) {
1437                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "%s: %s",
1438                             fname, pcap_strerror(errno));
1439                         return (NULL);
1440                 }
1441         }
1442         return (pcap_setup_dump(p, linktype, f, fname));
1443 }
1444
1445 /*
1446  * Initialize so that sf_write() will output to the given stream.
1447  */
1448 pcap_dumper_t *
1449 pcap_dump_fopen(pcap_t *p, FILE *f)
1450 {       
1451         int linktype;
1452
1453         linktype = dlt_to_linktype(p->linktype);
1454         if (linktype == -1) {
1455                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1456                     "stream: link-layer type %d isn't supported in savefiles",
1457                     linktype);
1458                 return (NULL);
1459         }
1460
1461         return (pcap_setup_dump(p, linktype, f, "stream"));
1462 }
1463
1464 FILE *
1465 pcap_dump_file(pcap_dumper_t *p)
1466 {
1467         return ((FILE *)p);
1468 }
1469
1470 long
1471 pcap_dump_ftell(pcap_dumper_t *p)
1472 {
1473         return (ftell((FILE *)p));
1474 }
1475
1476 int
1477 pcap_dump_flush(pcap_dumper_t *p)
1478 {
1479
1480         if (fflush((FILE *)p) == EOF)
1481                 return (-1);
1482         else
1483                 return (0);
1484 }
1485
1486 void
1487 pcap_dump_close(pcap_dumper_t *p)
1488 {
1489
1490 #ifdef notyet
1491         if (ferror((FILE *)p))
1492                 return-an-error;
1493         /* XXX should check return from fclose() too */
1494 #endif
1495         (void)fclose((FILE *)p);
1496 }