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