cdb07aaf362515d3e8057f414af1f6417c24443e
[metze/wireshark/wip.git] / wiretap / libpcap.c
1 /* libpcap.c
2  *
3  * $Id: libpcap.c,v 1.66 2002/02/27 08:57:25 guy Exp $
4  *
5  * Wiretap Library
6  * Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
7  * 
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  * 
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26 #include <stdlib.h>
27 #include <errno.h>
28 #include "wtap-int.h"
29 #include "file_wrappers.h"
30 #include "buffer.h"
31 #include "libpcap.h"
32
33 /* See source to the "libpcap" library for information on the "libpcap"
34    file format. */
35
36 /* On some systems, the FDDI MAC addresses are bit-swapped. */
37 #if !defined(ultrix) && !defined(__alpha) && !defined(__bsdi__)
38 #define BIT_SWAPPED_MAC_ADDRS
39 #endif
40
41
42 /* Try to read the first two records of the capture file. */
43 typedef enum {
44         THIS_FORMAT,            /* the reads succeeded, assume it's this format */
45         BAD_READ,               /* the file is probably not valid */
46         OTHER_FORMAT            /* the file may be valid, but not in this format */
47 } libpcap_try_t;
48 static libpcap_try_t libpcap_try(wtap *wth, int *err);
49
50 static gboolean libpcap_read(wtap *wth, int *err, long *data_offset);
51 static int libpcap_read_header(wtap *wth, int *err,
52     struct pcaprec_ss990915_hdr *hdr, gboolean silent);
53 static void adjust_header(wtap *wth, struct pcaprec_hdr *hdr);
54 static void libpcap_close(wtap *wth);
55 static gboolean libpcap_dump(wtap_dumper *wdh, const struct wtap_pkthdr *phdr,
56     const union wtap_pseudo_header *pseudo_header, const u_char *pd, int *err);
57
58 /*
59  * Either LBL NRG wasn't an adequate central registry (e.g., because of
60  * the slow rate of releases from them), or nobody bothered using them
61  * as a central registry, as many different groups have patched libpcap
62  * (and BPF, on the BSDs) to add new encapsulation types, and have ended
63  * up using the same DLT_ values for different encapsulation types.
64  *
65  * For those numerical encapsulation type values that everybody uses for
66  * the same encapsulation type (which inclues those that some platforms
67  * specify different DLT_ names for but don't appear to use), we map
68  * those values to the appropriate Wiretap values.
69  *
70  * For those numerical encapsulation type values that different libpcap
71  * variants use for different encapsulation types, we check what
72  * <pcap.h> defined to determine how to interpret them, so that we
73  * interpret them the way the libpcap with which we're building
74  * Ethereal/Wiretap interprets them (which, if it doesn't support
75  * them at all, means we don't support them either - any capture files
76  * using them are foreign, and we don't hazard a guess as to which
77  * platform they came from; we could, I guess, choose the most likely
78  * platform).
79  */
80
81 #ifdef HAVE_PCAP_H
82 #include <pcap.h>
83 #endif
84
85 static const struct {
86         int     dlt_value;
87         int     wtap_encap_value;
88 } pcap_to_wtap_map[] = {
89         /*
90          * These are the values that are almost certainly the same
91          * in all libpcaps (I've yet to find one where the values
92          * in question are used for some purpose other than the
93          * one below, but...), and that Wiretap and Ethereal
94          * currently support.
95          */
96         { 0,            WTAP_ENCAP_NULL },      /* null encapsulation */
97         { 1,            WTAP_ENCAP_ETHERNET },
98         { 6,            WTAP_ENCAP_TOKEN_RING },        /* IEEE 802 Networks - assume token ring */
99         { 7,            WTAP_ENCAP_ARCNET },
100         { 8,            WTAP_ENCAP_SLIP },
101         { 9,            WTAP_ENCAP_PPP },
102 #ifdef BIT_SWAPPED_MAC_ADDRS
103         { 10,           WTAP_ENCAP_FDDI_BITSWAPPED },
104 #else
105         { 10,           WTAP_ENCAP_FDDI },
106 #endif
107
108         /*
109          * 11 is DLT_ATM_RFC1483 on most platforms; the only libpcaps I've
110          * seen that define anything other than DLT_ATM_RFC1483 as 11 are
111          * the BSD/OS one, which defines DLT_FR as 11, and libpcap 0.5,
112          * which define it as 100, mapping the kernel's value to 100, in
113          * an attempt to hide the different values used on different
114          * platforms.
115          *
116          * If this is a platform where DLT_FR is defined as 11, we
117          * don't handle 11 at all; otherwise, we handle it as
118          * DLT_ATM_RFC1483 (this means we'd misinterpret Frame Relay
119          * captures from BSD/OS if running on platforms other than BSD/OS,
120          * but
121          *
122          *      1) we don't yet support DLT_FR
123          *
124          * and
125          *
126          *      2) nothing short of a heuristic would let us interpret
127          *         them correctly).
128          */
129 #if defined(DLT_FR) && (DLT_FR == 11)
130         /* Put entry for Frame Relay here */
131 #else
132         { 11,           WTAP_ENCAP_ATM_RFC1483 },
133 #endif
134
135         /*
136          * 12 is DLT_RAW on most platforms, but it's DLT_C_HDLC on
137          * BSD/OS, and DLT_LOOP on OpenBSD.
138          *
139          * We don't yet handle DLT_C_HDLC, but we can handle DLT_LOOP
140          * (it's just like DLT_NULL, only with the AF_ value in network
141          * rather than host byte order - Ethereal figures out the
142          * byte order from the data, so we don't care what byte order
143          * it's in), so if DLT_LOOP is defined as 12, interpret 12
144          * as WTAP_ENCAP_NULL, otherwise, unless DLT_C_HDLC is defined
145          * as 12, interpret it as WTAP_ENCAP_RAW_IP.
146          */
147 #if defined(DLT_LOOP) && (DLT_LOOP == 12)
148         { 12,           WTAP_ENCAP_NULL },
149 #elif defined(DLT_C_HDLC) && (DLT_C_HDLC == 12)
150         /*
151          * Put entry for Cisco HDLC here.
152          * XXX - is this just WTAP_ENCAP_CHDLC, i.e. does the frame
153          * start with a 4-byte Cisco HDLC header?
154          */
155 #else
156         { 12,           WTAP_ENCAP_RAW_IP },
157 #endif
158
159         /*
160          * 13 is DLT_SLIP_BSDOS on FreeBSD and NetBSD, but those OSes
161          * don't actually generate it.  I infer that BSD/OS translates
162          * DLT_SLIP from the kernel BPF code to DLT_SLIP_BSDOS in
163          * libpcap, as the BSD/OS link-layer header is different;
164          * however, in BSD/OS, DLT_SLIP_BSDOS is 15.
165          *
166          * From this, I infer that there's no point in handling 13
167          * as DLT_SLIP_BSDOS.
168          *
169          * 13 is DLT_ATM_RFC1483 on BSD/OS.
170          *
171          * 13 is DLT_ENC in OpenBSD, which is, I suspect, some kind
172          * of decrypted IPSEC traffic.
173          */
174 #if defined(DLT_ATM_RFC1483) && (DLT_ATM_RFC1483 == 13)
175         { 13,           WTAP_ENCAP_ATM_RFC1483 },
176 #elif defined(DLT_ENC) && (DLT_ENC == 13)
177         /* Put entry for DLT_ENC here */
178 #endif
179
180         /*
181          * 14 is DLT_PPP_BSDOS on FreeBSD and NetBSD, but those OSes
182          * don't actually generate it.  I infer that BSD/OS translates
183          * DLT_PPP from the kernel BPF code to DLT_PPP_BSDOS in
184          * libpcap, as the BSD/OS link-layer header is different;
185          * however, in BSD/OS, DLT_PPP_BSDOS is 16.
186          *
187          * From this, I infer that there's no point in handling 14
188          * as DLT_PPP_BSDOS.
189          *
190          * 14 is DLT_RAW on BSD/OS and OpenBSD.
191          */
192         { 14,           WTAP_ENCAP_RAW_IP },
193
194         /*
195          * 15 is:
196          *
197          *      DLT_SLIP_BSDOS on BSD/OS;
198          *
199          *      DLT_HIPPI on NetBSD;
200          *
201          *      DLT_LANE8023 with Alexey Kuznetzov's patches for
202          *      Linux libpcap;
203          *
204          *      DLT_I4L_RAWIP with the ISDN4Linux patches for libpcap
205          *      (and on SuSE 6.3);
206          *
207          * but we don't currently handle any of those.
208          */
209
210         /*
211          * 16 is:
212          *
213          *      DLT_PPP_BSDOS on BSD/OS;
214          *
215          *      DLT_HDLC on NetBSD (Cisco HDLC);
216          *
217          *      DLT_CIP with Alexey Kuznetzov's patches for
218          *      Linux libpcap - this is WTAP_ENCAP_LINUX_ATM_CLIP;
219          *
220          *      DLT_I4L_IP with the ISDN4Linux patches for libpcap
221          *      (and on SuSE 6.3).
222          */
223 #if defined(DLT_CIP) && (DLT_CIP == 16)
224         { 16,           WTAP_ENCAP_LINUX_ATM_CLIP },
225 #endif
226 #if defined(DLT_HDLC) && (DLT_HDLC == 16)
227         { 16,           WTAP_ENCAP_CHDLC },
228 #endif
229
230         /*
231          * 17 is DLT_LANE8023 in SuSE 6.3 libpcap; we don't currently
232          * handle it.
233          * It is also used as the PF (Packet Filter) logging format beginning
234          * with OpenBSD 3.0; we use 17 for PF logs unless DLT_LANE8023 is
235          * defined with the value 17.
236          */
237 #if !defined(DLT_LANE8023) || (DLT_LANE8023 != 17)
238         { 17,           WTAP_ENCAP_PFLOG },
239 #endif
240
241         /*
242          * 18 is DLT_CIP in SuSE 6.3 libpcap; if it's the same as the
243          * DLT_CIP of 16 that the Alexey Kuznetzov patches for
244          * libpcap/tcpdump define, it's WTAP_ENCAP_LINUX_ATM_CLIP.
245          * I've not found any libpcap that uses it for any other purpose -
246          * hopefully nobody will do so in the future.
247          */
248         { 18,           WTAP_ENCAP_LINUX_ATM_CLIP },
249
250         /*
251          * 19 is DLT_ATM_CLIP in the libpcap/tcpdump patches in the
252          * recent versions I've seen of the Linux ATM distribution;
253          * I've not yet found any libpcap that uses it for any other
254          * purpose - hopefully nobody will do so in the future.
255          */
256         { 19,           WTAP_ENCAP_LINUX_ATM_CLIP },
257
258         /*
259          * 50 is DLT_PPP_SERIAL in NetBSD; it appears that DLT_PPP
260          * on BSD (at least according to standard tcpdump) has, as
261          * the first octet, an indication of whether the packet was
262          * transmitted or received (rather than having the standard
263          * PPP address value of 0xff), but that DLT_PPP_SERIAL puts
264          * a real live PPP header there, or perhaps a Cisco PPP header
265          * as per section 4.3.1 of RFC 1547 (implementations of this
266          * exist in various BSDs in "sys/net/if_spppsubr.c", and
267          * I think also exist either in standard Linux or in
268          * various Linux patches; the implementations show how to handle
269          * Cisco keepalive packets).
270          *
271          * However, I don't see any obvious place in FreeBSD "if_ppp.c"
272          * where anything other than the standard PPP header would be
273          * passed up.  I see some stuff that sets the first octet
274          * to 0 for incoming and 1 for outgoing packets before applying
275          * a BPF filter to see whether to drop packets whose protocol
276          * field has the 0x8000 bit set, i.e. network control protocols -
277          * those are handed up to userland - but that code puts the
278          * address field back before passing the packet up.
279          *
280          * I also don't see anything immediately obvious that munges
281          * the address field for sync PPP, either.
282          *
283          * Ethereal currently assumes that if the first octet of a
284          * PPP frame is 0xFF, it's the address field and is followed
285          * by a control field and a 2-byte protocol, otherwise the
286          * address and control fields are absent and the frame begins
287          * with a protocol field.  If we ever see a BSD/OS PPP
288          * capture, we'll have to handle it differently, and we may
289          * have to handle standard BSD captures differently if, in fact,
290          * they don't have 0xff 0x03 as the first two bytes - but, as per
291          * the two paragraphs preceding this, it's not clear that
292          * the address field *is* munged into an incoming/outgoing
293          * field when the packet is handed to the BPF device.
294          *
295          * For now, we just map DLT_PPP_SERIAL to WTAP_ENCAP_PPP, as
296          * we treat WTAP_ENCAP_PPP packets as if those beginning with
297          * 0xff have the standard RFC 1662 "PPP in HDLC-like Framing"
298          * 0xff 0x03 address/control header, and DLT_PPP_SERIAL frames
299          * appear to contain that unless they're Cisco frames (if we
300          * ever see a capture with them, we'd need to implement the
301          * RFC 1547 stuff, and the keepalive protocol stuff).
302          *
303          * We may have to distinguish between "PPP where if it doesn't
304          * begin with 0xff there's no HDLC encapsulation and the frame
305          * begins with the protocol field" (which is how we handle
306          * WTAP_ENCAP_PPP now) and "PPP where there's either HDLC
307          * encapsulation or Cisco PPP" (which is what DLT_PPP_SERIAL
308          * is) at some point.
309          *
310          * XXX - NetBSD has DLT_HDLC, which appears to be used for
311          * Cisco HDLC.  Ideally, they should use DLT_PPP_SERIAL
312          * only for real live HDLC-encapsulated PPP, not for Cisco
313          * HDLC.
314          */
315         { 50,           WTAP_ENCAP_PPP },
316
317         /*
318          * These are the values that libpcap 0.5 uses, in an attempt
319          * to work around the confusion decried above, and that Wiretap
320          * and Ethereal currently support.
321          *
322          * The next version of libpcap will probably not use them as
323          * DLT_ values in its API, but will probably use them in capture
324          * file headers.
325          */
326         { 100,          WTAP_ENCAP_ATM_RFC1483 },
327         { 101,          WTAP_ENCAP_RAW_IP },
328 #if 0
329         /*
330          * More values used by libpcap 0.5 as DLT_ values and used by the
331          * current CVS version of libpcap in capture file headers.
332          * They are not yet handled in Ethereal.
333          * If we get a capture that contains them, we'll implement them.
334          */
335         { 102,          WTAP_ENCAP_SLIP_BSDOS },
336         { 103,          WTAP_ENCAP_PPP_BSDOS },
337 #endif
338
339         /*
340          * These ones are handled in Ethereal, though.
341          */
342         { 104,          WTAP_ENCAP_CHDLC },     /* Cisco HDLC */
343         { 106,          WTAP_ENCAP_LINUX_ATM_CLIP },
344
345         /*
346          * Values not yet used by the current CVS version of libpcap,
347          * but reserved for future use; the IEEE 802.11 value is
348          * there for use with a capture program from Axis Communications.
349          */
350         { 105,          WTAP_ENCAP_IEEE_802_11 },
351 #if 0
352         /*
353          * Not yet handled in Ethereal; we don't know what encapsulation
354          * BSD/OS uses, so we don't know whether it can be handed to
355          * the Frame Relay dissector or not.
356          */
357         { 107,          WTAP_ENCAP_FR },        /* Frame Relay */
358 #endif
359         { 108,          WTAP_ENCAP_NULL },      /* OpenBSD loopback */
360 #if 0
361         { 109,          WTAP_ENCAP_ENC },       /* OpenBSD IPSEC enc */
362         { 110,          WTAP_ENCAP_LANE_802_3 },/* ATM LANE 802.3 */
363         { 111,          WTAP_ENCAP_HIPPI },     /* NetBSD HIPPI */
364 #endif
365         { 112,          WTAP_ENCAP_CHDLC },     /* NetBSD HDLC framing */
366
367         /*
368          * Linux "cooked mode" captures, used by the current CVS version
369          * of libpcap.
370          */
371         { 113,          WTAP_ENCAP_SLL },       /* Linux cooked capture */
372
373         { 114,          WTAP_ENCAP_LOCALTALK }, /* Localtalk */
374
375         /*
376          * The tcpdump.org version of libpcap uses 117, rather than 17,
377          * for OpenBSD packet filter logging, so as to avoid conflicting
378          * with DLT_LANE8023 in SuSE 6.3 libpcap.
379          */
380         { 117,          WTAP_ENCAP_PFLOG },
381
382         { 118,          WTAP_ENCAP_CISCO_IOS },
383         { 119,          WTAP_ENCAP_PRISM_HEADER }, /* Prism monitor mode hdr */
384         { 121,          WTAP_ENCAP_HHDLC },     /* HiPath HDLC */
385 };
386 #define NUM_PCAP_ENCAPS (sizeof pcap_to_wtap_map / sizeof pcap_to_wtap_map[0])
387
388 int libpcap_open(wtap *wth, int *err)
389 {
390         int bytes_read;
391         guint32 magic;
392         struct pcap_hdr hdr;
393         gboolean byte_swapped;
394         gboolean modified;
395         gboolean aix;
396         int file_encap;
397
398         /* Read in the number that should be at the start of a "libpcap" file */
399         errno = WTAP_ERR_CANT_READ;
400         bytes_read = file_read(&magic, 1, sizeof magic, wth->fh);
401         if (bytes_read != sizeof magic) {
402                 *err = file_error(wth->fh);
403                 if (*err != 0)
404                         return -1;
405                 return 0;
406         }
407         wth->data_offset += sizeof magic;
408
409         switch (magic) {
410
411         case PCAP_MAGIC:
412                 /* Host that wrote it has our byte order, and was running
413                    a program using either standard or ss990417 libpcap. */
414                 byte_swapped = FALSE;
415                 modified = FALSE;
416                 break;
417
418         case PCAP_MODIFIED_MAGIC:
419                 /* Host that wrote it has our byte order, and was running
420                    a program using either ss990915 or ss991029 libpcap. */
421                 byte_swapped = FALSE;
422                 modified = TRUE;
423                 break;
424
425         case PCAP_SWAPPED_MAGIC:
426                 /* Host that wrote it has a byte order opposite to ours,
427                    and was running a program using either standard or
428                    ss990417 libpcap. */
429                 byte_swapped = TRUE;
430                 modified = FALSE;
431                 break;
432
433         case PCAP_SWAPPED_MODIFIED_MAGIC:
434                 /* Host that wrote it out has a byte order opposite to
435                    ours, and was running a program using either ss990915
436                    or ss991029 libpcap. */
437                 byte_swapped = TRUE;
438                 modified = TRUE;
439                 break;
440
441         default:
442                 /* Not a "libpcap" type we know about. */
443                 return 0;
444         }
445
446         /* Read the rest of the header. */
447         errno = WTAP_ERR_CANT_READ;
448         bytes_read = file_read(&hdr, 1, sizeof hdr, wth->fh);
449         if (bytes_read != sizeof hdr) {
450                 *err = file_error(wth->fh);
451                 if (*err != 0)
452                         return -1;
453                 return 0;
454         }
455         wth->data_offset += sizeof hdr;
456
457         if (byte_swapped) {
458                 /* Byte-swap the header fields about which we care. */
459                 hdr.version_major = BSWAP16(hdr.version_major);
460                 hdr.version_minor = BSWAP16(hdr.version_minor);
461                 hdr.snaplen = BSWAP32(hdr.snaplen);
462                 hdr.network = BSWAP32(hdr.network);
463         }
464         if (hdr.version_major < 2) {
465                 /* We only support version 2.0 and later. */
466                 g_message("pcap: major version %u unsupported",
467                     hdr.version_major);
468                 *err = WTAP_ERR_UNSUPPORTED;
469                 return -1;
470         }
471
472         /*
473          * AIX's non-standard tcpdump uses a minor version number of 2.
474          * Unfortunately, older versions of libpcap might have used
475          * that as well.
476          *
477          * The AIX libpcap uses RFC 1573 ifType values rather than
478          * DLT_ values in the header; the ifType values for LAN devices
479          * are:
480          *
481          *      Ethernet        6
482          *      Token Ring      9
483          *      FDDI            15
484          *
485          * which correspond to DLT_IEEE802 (used for Token Ring),
486          * DLT_PPP, and DLT_SLIP_BSDOS, respectively.  We shall
487          * assume that if the minor version number is 2, and
488          * the network type is 6, 9, or 15, that it's AIX libpcap;
489          *
490          * I'm assuming those older versions of libpcap didn't
491          * use DLT_IEEE802 for Token Ring, and didn't use DLT_SLIP_BSDOS
492          * as that came later.  It may have used DLT_SLIP, however, in
493          * which case we're out of luck; we assume it's Token Ring
494          * in AIX libpcap rather than PPP in standard libpcap, as
495          * you're probably more likely to be handing an AIX libpcap
496          * token-ring capture than an old (pre-libpcap 0.4) PPP capture
497          * to Ethereal.
498          */
499         aix = FALSE;    /* assume it's not AIX */
500         if (hdr.version_major == 2 && hdr.version_minor == 2) {
501                 switch (hdr.network) {
502
503                 case 6:
504                         hdr.network = 1;        /* DLT_EN10MB, Ethernet */
505                         aix = TRUE;
506                         break;
507
508                 case 8:
509                         hdr.network = 6;        /* DLT_IEEE802, Token Ring */
510                         aix = TRUE;
511                         break;
512
513                 case 15:
514                         hdr.network = 10;       /* DLT_FDDI, FDDI */
515                         aix = TRUE;
516                         break;
517                 }
518         }
519         file_encap = wtap_pcap_encap_to_wtap_encap(hdr.network);
520         if (file_encap == WTAP_ENCAP_UNKNOWN) {
521                 g_message("pcap: network type %u unknown or unsupported",
522                     hdr.network);
523                 *err = WTAP_ERR_UNSUPPORTED_ENCAP;
524                 return -1;
525         }
526
527         /* This is a libpcap file */
528         wth->capture.pcap = g_malloc(sizeof(libpcap_t));
529         wth->capture.pcap->byte_swapped = byte_swapped;
530         wth->capture.pcap->version_major = hdr.version_major;
531         wth->capture.pcap->version_minor = hdr.version_minor;
532         wth->subtype_read = libpcap_read;
533         wth->subtype_seek_read = wtap_def_seek_read;
534         wth->subtype_close = libpcap_close;
535         wth->file_encap = file_encap;
536         wth->snapshot_length = hdr.snaplen;
537
538         /*
539          * Is this AIX format?
540          */
541         if (aix) {
542                 /*
543                  * Yes.  Skip all the tests for other mutant formats.
544                  */
545                 wth->file_type = WTAP_FILE_PCAP_AIX;
546                 return 1;
547         }
548
549         /*
550          * No.  Let's look at the header for the first record,
551          * and see if, interpreting it as a standard header (if the
552          * magic number was standard) or a modified header (if the
553          * magic number was modified), the position where it says the
554          * header for the *second* record is contains a corrupted header.
555          *
556          * If so, then:
557          *
558          *      If this file had the standard magic number, it may be
559          *      an ss990417 capture file - in that version of Alexey's
560          *      patch, the packet header format was changed but the
561          *      magic number wasn't, and, alas, Red Hat appear to have
562          *      picked up that version of the patch for RH 6.1, meaning
563          *      RH 6.1 has a tcpdump that writes out files that can't
564          *      be read by any software that expects non-modified headers
565          *      if the magic number isn't the modified magic number (e.g.,
566          *      any normal version of tcpdump, and Ethereal if we don't
567          *      do this gross heuristic).
568          *
569          *      If this file had the modified magic number, it may be
570          *      an ss990915 capture file - in that version of Alexey's
571          *      patch, the magic number was changed, but the record
572          *      header had some extra fields, and, alas, SuSE appear
573          *      to have picked up that version of the patch for SuSE
574          *      6.3, meaning that programs expecting the standard per-
575          *      packet header in captures with the modified magic number
576          *      can't read dumps from its tcpdump.
577          *
578          * Oh, and if it has the standard magic number, it might, instead,
579          * be a Nokia libpcap file, so we may need to try that if
580          * neither normal nor ss990417 headers work.
581          */
582         if (modified) {
583                 /*
584                  * Well, we have the magic number from Alexey's
585                  * later two patches.
586                  *
587                  * Try ss991029, the last of his patches, first.
588                  */
589                 wth->file_type = WTAP_FILE_PCAP_SS991029;
590                 switch (libpcap_try(wth, err)) {
591
592                 case BAD_READ:
593                         /*
594                          * Well, we couldn't even read it.
595                          * Give up.
596                          */
597                         return -1;
598
599                 case THIS_FORMAT:
600                         /*
601                          * Well, it looks as if it might be 991029.
602                          * Put the seek pointer back, and return success.
603                          */
604                         file_seek(wth->fh, wth->data_offset, SEEK_SET);
605                         return 1;
606
607                 case OTHER_FORMAT:
608                         /*
609                          * Try the next format.
610                          */
611                         break;
612                 }
613
614                 /*
615                  * Well, it's not completely unreadable,
616                  * but it's not ss991029.  Try ss990915;
617                  * there are no other types to try after that,
618                  * so we put the seek pointer back and treat
619                  * it as 990915.
620                  */
621                 wth->file_type = WTAP_FILE_PCAP_SS990915;
622                 file_seek(wth->fh, wth->data_offset, SEEK_SET);
623         } else {
624                 /*
625                  * Well, we have the standard magic number.
626                  *
627                  * Try the standard format first.
628                  */
629                 wth->file_type = WTAP_FILE_PCAP;
630                 switch (libpcap_try(wth, err)) {
631
632                 case BAD_READ:
633                         /*
634                          * Well, we couldn't even read it.
635                          * Give up.
636                          */
637                         return -1;
638
639                 case THIS_FORMAT:
640                         /*
641                          * Well, it looks as if it might be a standard
642                          * libpcap file.
643                          * Put the seek pointer back, and return success.
644                          */
645                         file_seek(wth->fh, wth->data_offset, SEEK_SET);
646                         return 1;
647
648                 case OTHER_FORMAT:
649                         /*
650                          * Try the next format.
651                          */
652                         break;
653                 }
654
655                 /*
656                  * Well, it's not completely unreadable, but it's not
657                  * a standard file.  Put the seek pointer back and try
658                  * ss990417.
659                  */
660                 wth->file_type = WTAP_FILE_PCAP_SS990417;
661                 file_seek(wth->fh, wth->data_offset, SEEK_SET);
662                 switch (libpcap_try(wth, err)) {
663
664                 case BAD_READ:
665                         /*
666                          * Well, we couldn't even read it.
667                          * Give up.
668                          */
669                         return -1;
670
671                 case THIS_FORMAT:
672                         /*
673                          * Well, it looks as if it might be ss990417.
674                          * Put the seek pointer back, and return success.
675                          */
676                         file_seek(wth->fh, wth->data_offset, SEEK_SET);
677                         return 1;
678
679                 case OTHER_FORMAT:
680                         /*
681                          * Try the next format.
682                          */
683                         break;
684                 }
685
686                 /*
687                  * Well, it's not completely unreadable,
688                  * but it's not a standard file *nor* is it ss990417.
689                  * Try it as a Nokia file; there are no other types
690                  * to try after that, so we put the seek pointer back
691                  * and treat it as a Nokia file.
692                  */
693                 wth->file_type = WTAP_FILE_PCAP_NOKIA;
694                 file_seek(wth->fh, wth->data_offset, SEEK_SET);
695         }
696
697         return 1;
698 }
699
700 /* Try to read the first two records of the capture file. */
701 static libpcap_try_t libpcap_try(wtap *wth, int *err)
702 {
703         /*
704          * pcaprec_ss990915_hdr is the largest header type.
705          */
706         struct pcaprec_ss990915_hdr first_rec_hdr, second_rec_hdr;
707
708         /*
709          * Attempt to read the first record's header.
710          */
711         if (libpcap_read_header(wth, err, &first_rec_hdr, TRUE) == -1) {
712                 if (*err == 0 || *err == WTAP_ERR_SHORT_READ) {
713                         /*
714                          * EOF or short read - assume the file is in this
715                          * format.
716                          * When our client tries to read the first packet
717                          * they will presumably get the same EOF or short
718                          * read.
719                          */
720                         return THIS_FORMAT;
721                 }
722
723                 if (*err == WTAP_ERR_BAD_RECORD) {
724                         /*
725                          * The first record is bogus, so this is probably
726                          * a corrupt file.  Assume the file is in this
727                          * format.  When our client tries to read the
728                          * first packet they will presumably get the
729                          * same bogus record.
730                          */
731                         return THIS_FORMAT;
732                 }
733
734                 /*
735                  * Some other error, e.g. an I/O error; just give up.
736                  */
737                 return BAD_READ;
738         }
739
740         /*
741          * Now skip over the first record's data, under the assumption
742          * that the header is sane.
743          */
744         file_seek(wth->fh, first_rec_hdr.hdr.incl_len, SEEK_CUR);
745
746         /*
747          * Now attempt to read the second record's header.
748          */
749         if (libpcap_read_header(wth, err, &second_rec_hdr, TRUE) == -1) {
750                 if (*err == 0 || *err == WTAP_ERR_SHORT_READ) {
751                         /*
752                          * EOF or short read - assume the file is in this
753                          * format.
754                          * When our client tries to read the second packet
755                          * they will presumably get the same EOF or short
756                          * read.
757                          */
758                         return THIS_FORMAT;
759                 }
760
761                 if (*err == WTAP_ERR_BAD_RECORD) {
762                         /*
763                          * The second record is bogus; maybe it's a
764                          * Capture File From Hell, and what looks like
765                          * the "header" of the next packet is actually
766                          * random junk from the middle of a packet.
767                          * Try the next format; if we run out of formats,
768                          * it probably *is* a corrupt file.
769                          */
770                         return OTHER_FORMAT;
771                 }
772
773                 /*
774                  * Some other error, e.g. an I/O error; just give up.
775                  */
776                 return BAD_READ;
777         }
778
779         /*
780          * OK, the first two records look OK; assume this is the
781          * right format.
782          */
783         return THIS_FORMAT;
784 }
785
786 /* Read the next packet */
787 static gboolean libpcap_read(wtap *wth, int *err, long *data_offset)
788 {
789         struct pcaprec_ss990915_hdr hdr;
790         guint packet_size;
791         int bytes_read;
792
793         bytes_read = libpcap_read_header(wth, err, &hdr, FALSE);
794         if (bytes_read == -1) {
795                 /*
796                  * We failed to read the header.
797                  */
798                 return FALSE;
799         }
800
801         wth->data_offset += bytes_read;
802         packet_size = hdr.hdr.incl_len;
803
804         buffer_assure_space(wth->frame_buffer, packet_size);
805         *data_offset = wth->data_offset;
806         errno = WTAP_ERR_CANT_READ;
807         bytes_read = file_read(buffer_start_ptr(wth->frame_buffer), 1,
808                         packet_size, wth->fh);
809
810         if ((guint)bytes_read != packet_size) {
811                 *err = file_error(wth->fh);
812                 if (*err == 0)
813                         *err = WTAP_ERR_SHORT_READ;
814                 return FALSE;
815         }
816         wth->data_offset += packet_size;
817
818         wth->phdr.ts.tv_sec = hdr.hdr.ts_sec;
819         wth->phdr.ts.tv_usec = hdr.hdr.ts_usec;
820         wth->phdr.caplen = packet_size;
821         wth->phdr.len = hdr.hdr.orig_len;
822         wth->phdr.pkt_encap = wth->file_encap;
823
824         return TRUE;
825 }
826
827 /* Read the header of the next packet; if "silent" is TRUE, don't complain
828    to the console, as we're testing to see if the file appears to be of a
829    particular type.
830
831    Return -1 on an error, or the number of bytes of header read on success. */
832 static int libpcap_read_header(wtap *wth, int *err,
833     struct pcaprec_ss990915_hdr *hdr, gboolean silent)
834 {
835         int     bytes_to_read, bytes_read;
836
837         /* Read record header. */
838         errno = WTAP_ERR_CANT_READ;
839         switch (wth->file_type) {
840
841         case WTAP_FILE_PCAP:
842         case WTAP_FILE_PCAP_AIX:
843                 bytes_to_read = sizeof (struct pcaprec_hdr);
844                 break;
845
846         case WTAP_FILE_PCAP_SS990417:
847         case WTAP_FILE_PCAP_SS991029:
848                 bytes_to_read = sizeof (struct pcaprec_modified_hdr);
849                 break;
850
851         case WTAP_FILE_PCAP_SS990915:
852                 bytes_to_read = sizeof (struct pcaprec_ss990915_hdr);
853                 break;
854
855         case WTAP_FILE_PCAP_NOKIA:
856                 bytes_to_read = sizeof (struct pcaprec_nokia_hdr);
857                 break;
858
859         default:
860                 g_assert_not_reached();
861                 bytes_to_read = 0;
862         }
863         bytes_read = file_read(hdr, 1, bytes_to_read, wth->fh);
864         if (bytes_read != bytes_to_read) {
865                 *err = file_error(wth->fh);
866                 if (*err == 0 && bytes_read != 0) {
867                         *err = WTAP_ERR_SHORT_READ;
868                 }
869                 return -1;
870         }
871
872         adjust_header(wth, &hdr->hdr);
873
874         if (hdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
875                 /*
876                  * Probably a corrupt capture file; return an error,
877                  * so that our caller doesn't blow up trying to allocate
878                  * space for an immensely-large packet, and so that
879                  * the code to try to guess what type of libpcap file
880                  * this is can tell when it's not the type we're guessing
881                  * it is.
882                  */
883                 if (!silent) {
884                         g_message("pcap: File has %u-byte packet, bigger than maximum of %u",
885                             hdr->hdr.incl_len, WTAP_MAX_PACKET_SIZE);
886                 }
887                 *err = WTAP_ERR_BAD_RECORD;
888                 return -1;
889         }
890
891         if (hdr->hdr.orig_len > WTAP_MAX_PACKET_SIZE) {
892                 /*
893                  * Probably a corrupt capture file; return an error,
894                  * so that our caller doesn't blow up trying to
895                  * cope with a huge "real" packet length, and so that
896                  * the code to try to guess what type of libpcap file
897                  * this is can tell when it's not the type we're guessing
898                  * it is.
899                  */
900                 if (!silent) {
901                         g_message("pcap: File has %u-byte packet, bigger than maximum of %u",
902                             hdr->hdr.orig_len, WTAP_MAX_PACKET_SIZE);
903                 }
904                 *err = WTAP_ERR_BAD_RECORD;
905                 return -1;
906         }
907
908         return bytes_read;
909 }
910
911 static void
912 adjust_header(wtap *wth, struct pcaprec_hdr *hdr)
913 {
914         if (wth->capture.pcap->byte_swapped) {
915                 /* Byte-swap the record header fields. */
916                 hdr->ts_sec = BSWAP32(hdr->ts_sec);
917                 hdr->ts_usec = BSWAP32(hdr->ts_usec);
918                 hdr->incl_len = BSWAP32(hdr->incl_len);
919                 hdr->orig_len = BSWAP32(hdr->orig_len);
920         }
921
922         /* If this is AIX, convert the time stamp from seconds/nanoseconds
923            to seconds/microseconds.  */
924         if (wth->file_type == WTAP_FILE_PCAP_AIX)
925                 hdr->ts_usec = hdr->ts_usec/1000;
926
927         /* In file format version 2.3, the "incl_len" and "orig_len" fields
928            were swapped, in order to match the BPF header layout.
929
930            Unfortunately, some files were, according to a comment in the
931            "libpcap" source, written with version 2.3 in their headers
932            but without the interchanged fields, so if "incl_len" is
933            greater than "orig_len" - which would make no sense - we
934            assume that we need to swap them.  */
935         if (wth->capture.pcap->version_major == 2 &&
936             (wth->capture.pcap->version_minor < 3 ||
937              (wth->capture.pcap->version_minor == 3 &&
938               hdr->incl_len > hdr->orig_len))) {
939                 guint32 temp;
940
941                 temp = hdr->orig_len;
942                 hdr->orig_len = hdr->incl_len;
943                 hdr->incl_len = temp;
944         }
945 }
946
947 static void
948 libpcap_close(wtap *wth)
949 {
950         g_free(wth->capture.pcap);
951 }
952
953 int wtap_pcap_encap_to_wtap_encap(int encap)
954 {
955         unsigned int i;
956
957         for (i = 0; i < NUM_PCAP_ENCAPS; i++) {
958                 if (pcap_to_wtap_map[i].dlt_value == encap)
959                         return pcap_to_wtap_map[i].wtap_encap_value;
960         }
961         return WTAP_ENCAP_UNKNOWN;
962 }
963
964 static int wtap_wtap_encap_to_pcap_encap(int encap)
965 {
966         unsigned int i;
967
968         /*
969          * Special-case WTAP_ENCAP_FDDI and WTAP_ENCAP_FDDI_BITSWAPPED;
970          * both of them get mapped to DLT_FDDI (even though that may
971          * mean that the bit order in the FDDI MAC addresses is wrong;
972          * so it goes - libpcap format doesn't record the byte order,
973          * so that's not fixable).
974          */
975         if (encap == WTAP_ENCAP_FDDI || encap == WTAP_ENCAP_FDDI_BITSWAPPED)
976                 return 10;      /* that's DLT_FDDI */
977         for (i = 0; i < NUM_PCAP_ENCAPS; i++) {
978                 if (pcap_to_wtap_map[i].wtap_encap_value == encap)
979                         return pcap_to_wtap_map[i].dlt_value;
980         }
981         return -1;
982 }
983
984 /* Returns 0 if we could write the specified encapsulation type,
985    an error indication otherwise. */
986 int libpcap_dump_can_write_encap(int encap)
987 {
988         /* Per-packet encapsulations aren't supported. */
989         if (encap == WTAP_ENCAP_PER_PACKET)
990                 return WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
991
992         if (wtap_wtap_encap_to_pcap_encap(encap) == -1)
993                 return WTAP_ERR_UNSUPPORTED_ENCAP;
994
995         return 0;
996 }
997
998 /* Returns TRUE on success, FALSE on failure; sets "*err" to an error code on
999    failure */
1000 gboolean libpcap_dump_open(wtap_dumper *wdh, int *err)
1001 {
1002         guint32 magic;
1003         struct pcap_hdr file_hdr;
1004         size_t nwritten;
1005
1006         /* This is a libpcap file */
1007         wdh->subtype_write = libpcap_dump;
1008         wdh->subtype_close = NULL;
1009
1010         /* Write the file header. */
1011         switch (wdh->file_type) {
1012
1013         case WTAP_FILE_PCAP:
1014         case WTAP_FILE_PCAP_SS990417:   /* modified, but with the old magic, sigh */
1015         case WTAP_FILE_PCAP_NOKIA:      /* Nokia libpcap of some sort */
1016                 magic = PCAP_MAGIC;
1017                 break;
1018
1019         case WTAP_FILE_PCAP_SS990915:   /* new magic, extra crap */
1020         case WTAP_FILE_PCAP_SS991029:
1021                 magic = PCAP_MODIFIED_MAGIC;
1022                 break;
1023
1024         default:
1025                 /* We should never get here - our open routine
1026                    should only get called for the types above. */
1027                 *err = WTAP_ERR_UNSUPPORTED_FILE_TYPE;
1028                 return FALSE;
1029         }
1030
1031         nwritten = fwrite(&magic, 1, sizeof magic, wdh->fh);
1032         if (nwritten != sizeof magic) {
1033                 if (nwritten == 0 && ferror(wdh->fh))
1034                         *err = errno;
1035                 else
1036                         *err = WTAP_ERR_SHORT_WRITE;
1037                 return FALSE;
1038         }
1039         wdh->bytes_dumped += sizeof magic;
1040
1041         /* current "libpcap" format is 2.4 */
1042         file_hdr.version_major = 2;
1043         file_hdr.version_minor = 4;
1044         file_hdr.thiszone = 0;  /* XXX - current offset? */
1045         file_hdr.sigfigs = 0;   /* unknown, but also apparently unused */
1046         file_hdr.snaplen = wdh->snaplen;
1047         file_hdr.network = wtap_wtap_encap_to_pcap_encap(wdh->encap);
1048         nwritten = fwrite(&file_hdr, 1, sizeof file_hdr, wdh->fh);
1049         if (nwritten != sizeof file_hdr) {
1050                 if (nwritten == 0 && ferror(wdh->fh))
1051                         *err = errno;
1052                 else
1053                         *err = WTAP_ERR_SHORT_WRITE;
1054                 return FALSE;
1055         }
1056         wdh->bytes_dumped += sizeof file_hdr;
1057
1058         return TRUE;
1059 }
1060
1061 /* Write a record for a packet to a dump file.
1062    Returns TRUE on success, FALSE on failure. */
1063 static gboolean libpcap_dump(wtap_dumper *wdh, const struct wtap_pkthdr *phdr,
1064     const union wtap_pseudo_header *pseudo_header, const u_char *pd, int *err)
1065 {
1066         struct pcaprec_ss990915_hdr rec_hdr;
1067         size_t hdr_size;
1068         size_t nwritten;
1069
1070         rec_hdr.hdr.ts_sec = phdr->ts.tv_sec;
1071         rec_hdr.hdr.ts_usec = phdr->ts.tv_usec;
1072         rec_hdr.hdr.incl_len = phdr->caplen;
1073         rec_hdr.hdr.orig_len = phdr->len;
1074         switch (wdh->file_type) {
1075
1076         case WTAP_FILE_PCAP:
1077                 hdr_size = sizeof (struct pcaprec_hdr);
1078                 break;
1079
1080         case WTAP_FILE_PCAP_SS990417:   /* modified, but with the old magic, sigh */
1081         case WTAP_FILE_PCAP_SS991029:
1082                 /* XXX - what should we supply here?
1083
1084                    Alexey's "libpcap" looks up the interface in the system's
1085                    interface list if "ifindex" is non-zero, and prints
1086                    the interface name.  It ignores "protocol", and uses
1087                    "pkt_type" to tag the packet as "host", "broadcast",
1088                    "multicast", "other host", "outgoing", or "none of the
1089                    above", but that's it.
1090
1091                    If the capture we're writing isn't a modified or
1092                    RH 6.1 capture, we'd have to do some work to
1093                    generate the packet type and interface index - and
1094                    we can't generate the interface index unless we
1095                    just did the capture ourselves in any case.
1096
1097                    I'm inclined to continue to punt; systems other than
1098                    those with the older patch can read standard "libpcap"
1099                    files, and systems with the older patch, e.g. RH 6.1,
1100                    will just have to live with this. */
1101                 rec_hdr.ifindex = 0;
1102                 rec_hdr.protocol = 0;
1103                 rec_hdr.pkt_type = 0;
1104                 hdr_size = sizeof (struct pcaprec_modified_hdr);
1105                 break;
1106
1107         case WTAP_FILE_PCAP_SS990915:   /* new magic, extra crap at the end */
1108                 rec_hdr.ifindex = 0;
1109                 rec_hdr.protocol = 0;
1110                 rec_hdr.pkt_type = 0;
1111                 rec_hdr.cpu1 = 0;
1112                 rec_hdr.cpu2 = 0;
1113                 hdr_size = sizeof (struct pcaprec_ss990915_hdr);
1114                 break;
1115
1116         case WTAP_FILE_PCAP_NOKIA:      /* old magic, extra crap at the end */
1117                 rec_hdr.ifindex = 0;
1118                 rec_hdr.protocol = 0;
1119                 rec_hdr.pkt_type = 0;
1120                 rec_hdr.cpu1 = 0;
1121                 rec_hdr.cpu2 = 0;
1122                 hdr_size = sizeof (struct pcaprec_nokia_hdr);
1123                 break;
1124
1125         default:
1126                 /* We should never get here - our open routine
1127                    should only get called for the types above. */
1128                 g_assert_not_reached();
1129                 *err = WTAP_ERR_UNSUPPORTED_FILE_TYPE;
1130                 return FALSE;
1131         }
1132
1133         nwritten = fwrite(&rec_hdr, 1, hdr_size, wdh->fh);
1134         if (nwritten != hdr_size) {
1135                 if (nwritten == 0 && ferror(wdh->fh))
1136                         *err = errno;
1137                 else
1138                         *err = WTAP_ERR_SHORT_WRITE;
1139                 return FALSE;
1140         }
1141         wdh->bytes_dumped += hdr_size;
1142         nwritten = fwrite(pd, 1, phdr->caplen, wdh->fh);
1143         if (nwritten != phdr->caplen) {
1144                 if (nwritten == 0 && ferror(wdh->fh))
1145                         *err = errno;
1146                 else
1147                         *err = WTAP_ERR_SHORT_WRITE;
1148                 return FALSE;
1149         }
1150         wdh->bytes_dumped += phdr->caplen;
1151         return TRUE;
1152 }