cdace5f5224cc925408932bee3432248e13595b7
[obnox/wireshark/wip.git] / wiretap / libpcap.c
1 /* libpcap.c
2  *
3  * $Id: libpcap.c,v 1.102 2003/12/18 19:07:13 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
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.h>
30 #include "wtap-int.h"
31 #include "file_wrappers.h"
32 #include "buffer.h"
33 #include "atm.h"
34 #include "libpcap.h"
35
36 #ifdef HAVE_PCAP_H
37 # ifdef HAVE_SYS_TYPES_H
38 #   include <sys/types.h>
39 # endif
40 #include <pcap.h>
41 #include "wtap-capture.h"
42 #endif
43
44 /*
45  * The link-layer header on ATM packets.
46  */
47 struct sunatm_hdr {
48         guint8  flags;          /* destination and traffic type */
49         guint8  vpi;            /* VPI */
50         guint16 vci;            /* VCI */
51 };
52
53 /*
54  * The fake link-layer header of IrDA packets as introduced by Jean Tourrilhes
55  * to libpcap.
56  */
57 struct irda_sll_hdr {
58     guint16 sll_pkttype;    /* packet type */
59     guint8 unused[12];      /* usused SLL header fields */
60     guint16 sll_protocol;   /* protocol, should be 0x0017 */
61 };
62
63 /* See source to the "libpcap" library for information on the "libpcap"
64    file format. */
65
66 /* On some systems, the FDDI MAC addresses are bit-swapped. */
67 #if !defined(ultrix) && !defined(__alpha) && !defined(__bsdi__)
68 #define BIT_SWAPPED_MAC_ADDRS
69 #endif
70
71 /* Try to read the first two records of the capture file. */
72 typedef enum {
73         THIS_FORMAT,            /* the reads succeeded, assume it's this format */
74         BAD_READ,               /* the file is probably not valid */
75         OTHER_FORMAT            /* the file may be valid, but not in this format */
76 } libpcap_try_t;
77 static libpcap_try_t libpcap_try(wtap *wth, int *err);
78
79 static gboolean libpcap_read(wtap *wth, int *err, long *data_offset);
80 static gboolean libpcap_seek_read(wtap *wth, long seek_off,
81     union wtap_pseudo_header *pseudo_header, guchar *pd, int length, int *err);
82 static int libpcap_read_header(wtap *wth, int *err,
83     struct pcaprec_ss990915_hdr *hdr, gboolean silent);
84 static void adjust_header(wtap *wth, struct pcaprec_hdr *hdr);
85 static void libpcap_get_atm_pseudoheader(const struct sunatm_hdr *atm_phdr,
86     union wtap_pseudo_header *pseudo_header);
87 static gboolean libpcap_read_atm_pseudoheader(FILE_T fh,
88     union wtap_pseudo_header *pseudo_header, int *err);
89 static gboolean libpcap_get_irda_pseudoheader(const struct irda_sll_hdr *irda_phdr,
90     union wtap_pseudo_header *pseudo_header, int *err);
91 static gboolean libpcap_read_irda_pseudoheader(FILE_T fh,
92     union wtap_pseudo_header *pseudo_header, int *err);
93 static gboolean libpcap_read_rec_data(FILE_T fh, guchar *pd, int length,
94     int *err);
95 static void libpcap_close(wtap *wth);
96 static gboolean libpcap_dump(wtap_dumper *wdh, const struct wtap_pkthdr *phdr,
97     const union wtap_pseudo_header *pseudo_header, const guchar *pd, int *err);
98
99 /*
100  * Either LBL NRG wasn't an adequate central registry (e.g., because of
101  * the slow rate of releases from them), or nobody bothered using them
102  * as a central registry, as many different groups have patched libpcap
103  * (and BPF, on the BSDs) to add new encapsulation types, and have ended
104  * up using the same DLT_ values for different encapsulation types.
105  *
106  * For those numerical encapsulation type values that everybody uses for
107  * the same encapsulation type (which inclues those that some platforms
108  * specify different DLT_ names for but don't appear to use), we map
109  * those values to the appropriate Wiretap values.
110  *
111  * For those numerical encapsulation type values that different libpcap
112  * variants use for different encapsulation types, we check what
113  * <pcap.h> defined to determine how to interpret them, so that we
114  * interpret them the way the libpcap with which we're building
115  * Ethereal/Wiretap interprets them (which, if it doesn't support
116  * them at all, means we don't support them either - any capture files
117  * using them are foreign, and we don't hazard a guess as to which
118  * platform they came from; we could, I guess, choose the most likely
119  * platform).
120  *
121  * Note: if you need a new encapsulation type for libpcap files, do
122  * *N*O*T* use *ANY* of the values listed here!  I.e., do *NOT*
123  * add a new encapsulation type by changing an existing entry;
124  * leave the existing entries alone.
125  *
126  * Instead, send mail to tcpdump-workers@tcpdump.org, asking for a new
127  * DLT_ value, and specifying the purpose of the new value.  When you
128  * get the new DLT_ value, use that numerical value in the "dlt_value"
129  * field of "pcap_to_wtap_map[]".
130  */
131
132 static const struct {
133         int     dlt_value;
134         int     wtap_encap_value;
135 } pcap_to_wtap_map[] = {
136         /*
137          * These are the values that are almost certainly the same
138          * in all libpcaps (I've yet to find one where the values
139          * in question are used for some purpose other than the
140          * one below, but...), and that Wiretap and Ethereal
141          * currently support.
142          */
143         { 0,            WTAP_ENCAP_NULL },      /* null encapsulation */
144         { 1,            WTAP_ENCAP_ETHERNET },
145         { 6,            WTAP_ENCAP_TOKEN_RING },        /* IEEE 802 Networks - assume token ring */
146         { 7,            WTAP_ENCAP_ARCNET },
147         { 8,            WTAP_ENCAP_SLIP },
148         { 9,            WTAP_ENCAP_PPP },
149 #ifdef BIT_SWAPPED_MAC_ADDRS
150         { 10,           WTAP_ENCAP_FDDI_BITSWAPPED },
151 #else
152         { 10,           WTAP_ENCAP_FDDI },
153 #endif
154
155         /*
156          * 50 is DLT_PPP_SERIAL in NetBSD; it appears that DLT_PPP
157          * on BSD (at least according to standard tcpdump) has, as
158          * the first octet, an indication of whether the packet was
159          * transmitted or received (rather than having the standard
160          * PPP address value of 0xff), but that DLT_PPP_SERIAL puts
161          * a real live PPP header there, or perhaps a Cisco PPP header
162          * as per section 4.3.1 of RFC 1547 (implementations of this
163          * exist in various BSDs in "sys/net/if_spppsubr.c", and
164          * I think also exist either in standard Linux or in
165          * various Linux patches; the implementations show how to handle
166          * Cisco keepalive packets).
167          *
168          * However, I don't see any obvious place in FreeBSD "if_ppp.c"
169          * where anything other than the standard PPP header would be
170          * passed up.  I see some stuff that sets the first octet
171          * to 0 for incoming and 1 for outgoing packets before applying
172          * a BPF filter to see whether to drop packets whose protocol
173          * field has the 0x8000 bit set, i.e. network control protocols -
174          * those are handed up to userland - but that code puts the
175          * address field back before passing the packet up.
176          *
177          * I also don't see anything immediately obvious that munges
178          * the address field for sync PPP, either.
179          *
180          * Ethereal currently assumes that if the first octet of a
181          * PPP frame is 0xFF, it's the address field and is followed
182          * by a control field and a 2-byte protocol, otherwise the
183          * address and control fields are absent and the frame begins
184          * with a protocol field.  If we ever see a BSD/OS PPP
185          * capture, we'll have to handle it differently, and we may
186          * have to handle standard BSD captures differently if, in fact,
187          * they don't have 0xff 0x03 as the first two bytes - but, as per
188          * the two paragraphs preceding this, it's not clear that
189          * the address field *is* munged into an incoming/outgoing
190          * field when the packet is handed to the BPF device.
191          *
192          * For now, we just map DLT_PPP_SERIAL to WTAP_ENCAP_PPP, as
193          * we treat WTAP_ENCAP_PPP packets as if those beginning with
194          * 0xff have the standard RFC 1662 "PPP in HDLC-like Framing"
195          * 0xff 0x03 address/control header, and DLT_PPP_SERIAL frames
196          * appear to contain that unless they're Cisco frames (if we
197          * ever see a capture with them, we'd need to implement the
198          * RFC 1547 stuff, and the keepalive protocol stuff).
199          *
200          * We may have to distinguish between "PPP where if it doesn't
201          * begin with 0xff there's no HDLC encapsulation and the frame
202          * begins with the protocol field" (which is how we handle
203          * WTAP_ENCAP_PPP now) and "PPP where there's either HDLC
204          * encapsulation or Cisco PPP" (which is what DLT_PPP_SERIAL
205          * is) at some point.
206          *
207          * XXX - NetBSD has DLT_HDLC, which appears to be used for
208          * Cisco HDLC.  Ideally, they should use DLT_PPP_SERIAL
209          * only for real live HDLC-encapsulated PPP, not for Cisco
210          * HDLC.
211          */
212         { 50,           WTAP_ENCAP_PPP },
213
214         /*
215          * These are the values that libpcap 0.5 and later use in
216          * capture file headers, in an attempt to work around the
217          * confusion decried above, and that Wiretap and Ethereal
218          * currently support.
219          */
220         { 100,          WTAP_ENCAP_ATM_RFC1483 },
221         { 101,          WTAP_ENCAP_RAW_IP },
222 #if 0
223         /*
224          * More values used by libpcap 0.5 as DLT_ values and used by the
225          * current CVS version of libpcap in capture file headers.
226          * They are not yet handled in Ethereal.
227          * If we get a capture that contains them, we'll implement them.
228          */
229         { 102,          WTAP_ENCAP_SLIP_BSDOS },
230         { 103,          WTAP_ENCAP_PPP_BSDOS },
231 #endif
232
233         /*
234          * These ones are handled in Ethereal, though.
235          */
236         { 104,          WTAP_ENCAP_CHDLC },     /* Cisco HDLC */
237         { 105,          WTAP_ENCAP_IEEE_802_11 }, /* IEEE 802.11 */
238         { 106,          WTAP_ENCAP_LINUX_ATM_CLIP },
239         { 107,          WTAP_ENCAP_FRELAY },    /* Frame Relay */
240         { 108,          WTAP_ENCAP_NULL },      /* OpenBSD loopback */
241         { 109,          WTAP_ENCAP_ENC },       /* OpenBSD IPSEC enc */
242 #if 0
243         { 110,          WTAP_ENCAP_LANE_802_3 },/* ATM LANE 802.3 */
244         { 111,          WTAP_ENCAP_HIPPI },     /* NetBSD HIPPI */
245 #endif
246         { 112,          WTAP_ENCAP_CHDLC },     /* NetBSD HDLC framing */
247
248         /*
249          * Linux "cooked mode" captures, used by the current CVS version
250          * of libpcap.
251          */
252         { 113,          WTAP_ENCAP_SLL },       /* Linux cooked capture */
253
254         { 114,          WTAP_ENCAP_LOCALTALK }, /* Localtalk */
255
256         /*
257          * The tcpdump.org version of libpcap uses 117, rather than 17,
258          * for OpenBSD packet filter logging, so as to avoid conflicting
259          * with DLT_LANE8023 in SuSE 6.3 libpcap.
260          */
261         { 117,          WTAP_ENCAP_PFLOG },
262
263         { 118,          WTAP_ENCAP_CISCO_IOS },
264         { 119,          WTAP_ENCAP_PRISM_HEADER }, /* Prism monitor mode hdr */
265         { 121,          WTAP_ENCAP_HHDLC },     /* HiPath HDLC */
266         { 122,          WTAP_ENCAP_IP_OVER_FC },   /* RFC 2625 IP-over-FC */
267         { 123,          WTAP_ENCAP_ATM_PDUS },  /* SunATM */
268         { 127,          WTAP_ENCAP_WLAN_HEADER },  /* 802.11 plus WLAN header */
269         { 128,          WTAP_ENCAP_TZSP },      /* Tazmen Sniffer Protocol */
270         { 129,          WTAP_ENCAP_ARCNET_LINUX },
271
272         /*
273          * Values 130 thorugh 137 are reserved for use in Juniper
274          * hardware.
275          *
276          * 138 is reserved for Apple IP-over-IEEE 1394.
277          */
278
279         { 144,          WTAP_ENCAP_IRDA },      /* IrDA capture */
280
281         { 140,          WTAP_ENCAP_MTP2 },
282         { 141,          WTAP_ENCAP_MTP3 },
283
284         /*
285          * To repeat:
286          *
287          * If you need a new encapsulation type for libpcap files, do
288          * *N*O*T* use *ANY* of the values listed here!  I.e., do *NOT*
289          * add a new encapsulation type by changing an existing entry;
290          * leave the existing entries alone.
291          *
292          * Instead, send mail to tcpdump-workers@tcpdump.org, asking for
293          * a new DLT_ value, and specifying the purpose of the new value.
294          * When you get the new DLT_ value, use that numerical value in
295          * the "dlt_value" field of "pcap_to_wtap_map[]".
296          */
297
298         /*
299          * The following are entries for libpcap type values that have
300          * different meanings on different OSes.
301          *
302          * We put these *after* the entries for the platform-independent
303          * libpcap type values for those Wiretap encapsulation types, so
304          * that Ethereal chooses the platform-independent libpcap type
305          * value for those encapsulatioin types, not the platform-dependent
306          * one.
307          */
308
309         /*
310          * 11 is DLT_ATM_RFC1483 on most platforms; the only libpcaps I've
311          * seen that define anything other than DLT_ATM_RFC1483 as 11 are
312          * the BSD/OS one, which defines DLT_FR as 11, and libpcap 0.5,
313          * which define it as 100, mapping the kernel's value to 100, in
314          * an attempt to hide the different values used on different
315          * platforms.
316          *
317          * If this is a platform where DLT_FR is defined as 11, we
318          * don't handle 11 at all; otherwise, we handle it as
319          * DLT_ATM_RFC1483 (this means we'd misinterpret Frame Relay
320          * captures from BSD/OS if running on platforms other than BSD/OS,
321          * but
322          *
323          *      1) we don't yet support DLT_FR
324          *
325          * and
326          *
327          *      2) nothing short of a heuristic would let us interpret
328          *         them correctly).
329          */
330 #if defined(DLT_FR) && (DLT_FR == 11)
331         { 11,           WTAP_ENCAP_FRELAY },
332 #else
333         { 11,           WTAP_ENCAP_ATM_RFC1483 },
334 #endif
335
336         /*
337          * 12 is DLT_RAW on most platforms, but it's DLT_C_HDLC on
338          * BSD/OS, and DLT_LOOP on OpenBSD.
339          *
340          * We don't yet handle DLT_C_HDLC, but we can handle DLT_LOOP
341          * (it's just like DLT_NULL, only with the AF_ value in network
342          * rather than host byte order - Ethereal figures out the
343          * byte order from the data, so we don't care what byte order
344          * it's in), so if DLT_LOOP is defined as 12, interpret 12
345          * as WTAP_ENCAP_NULL, otherwise, unless DLT_C_HDLC is defined
346          * as 12, interpret it as WTAP_ENCAP_RAW_IP.
347          */
348 #if defined(DLT_LOOP) && (DLT_LOOP == 12)
349         { 12,           WTAP_ENCAP_NULL },
350 #elif defined(DLT_C_HDLC) && (DLT_C_HDLC == 12)
351         /*
352          * Put entry for Cisco HDLC here.
353          * XXX - is this just WTAP_ENCAP_CHDLC, i.e. does the frame
354          * start with a 4-byte Cisco HDLC header?
355          */
356 #else
357         { 12,           WTAP_ENCAP_RAW_IP },
358 #endif
359
360         /*
361          * 13 is DLT_SLIP_BSDOS on FreeBSD and NetBSD, but those OSes
362          * don't actually generate it.  I infer that BSD/OS translates
363          * DLT_SLIP from the kernel BPF code to DLT_SLIP_BSDOS in
364          * libpcap, as the BSD/OS link-layer header is different;
365          * however, in BSD/OS, DLT_SLIP_BSDOS is 15.
366          *
367          * From this, I infer that there's no point in handling 13
368          * as DLT_SLIP_BSDOS.
369          *
370          * 13 is DLT_ATM_RFC1483 on BSD/OS.
371          *
372          * 13 is DLT_ENC in OpenBSD, which is, I suspect, some kind
373          * of decrypted IPSEC traffic.
374          */
375 #if defined(DLT_ATM_RFC1483) && (DLT_ATM_RFC1483 == 13)
376         { 13,           WTAP_ENCAP_ATM_RFC1483 },
377 #elif defined(DLT_ENC) && (DLT_ENC == 13)
378         { 13,           WTAP_ENCAP_ENC },
379 #endif
380
381         /*
382          * 14 is DLT_PPP_BSDOS on FreeBSD and NetBSD, but those OSes
383          * don't actually generate it.  I infer that BSD/OS translates
384          * DLT_PPP from the kernel BPF code to DLT_PPP_BSDOS in
385          * libpcap, as the BSD/OS link-layer header is different;
386          * however, in BSD/OS, DLT_PPP_BSDOS is 16.
387          *
388          * From this, I infer that there's no point in handling 14
389          * as DLT_PPP_BSDOS.
390          *
391          * 14 is DLT_RAW on BSD/OS and OpenBSD.
392          */
393         { 14,           WTAP_ENCAP_RAW_IP },
394
395         /*
396          * 15 is:
397          *
398          *      DLT_SLIP_BSDOS on BSD/OS;
399          *
400          *      DLT_HIPPI on NetBSD;
401          *
402          *      DLT_LANE8023 with Alexey Kuznetzov's patches for
403          *      Linux libpcap;
404          *
405          *      DLT_I4L_RAWIP with the ISDN4Linux patches for libpcap
406          *      (and on SuSE 6.3);
407          *
408          * but we don't currently handle any of those.
409          */
410
411         /*
412          * 16 is:
413          *
414          *      DLT_PPP_BSDOS on BSD/OS;
415          *
416          *      DLT_HDLC on NetBSD (Cisco HDLC);
417          *
418          *      DLT_CIP with Alexey Kuznetzov's patches for
419          *      Linux libpcap - this is WTAP_ENCAP_LINUX_ATM_CLIP;
420          *
421          *      DLT_I4L_IP with the ISDN4Linux patches for libpcap
422          *      (and on SuSE 6.3).
423          */
424 #if defined(DLT_CIP) && (DLT_CIP == 16)
425         { 16,           WTAP_ENCAP_LINUX_ATM_CLIP },
426 #endif
427 #if defined(DLT_HDLC) && (DLT_HDLC == 16)
428         { 16,           WTAP_ENCAP_CHDLC },
429 #endif
430
431         /*
432          * 17 is DLT_LANE8023 in SuSE 6.3 libpcap; we don't currently
433          * handle it.
434          * It is also used as the PF (Packet Filter) logging format beginning
435          * with OpenBSD 3.0; we use 17 for PF logs unless DLT_LANE8023 is
436          * defined with the value 17.
437          */
438 #if !defined(DLT_LANE8023) || (DLT_LANE8023 != 17)
439         { 17,           WTAP_ENCAP_OLD_PFLOG },
440 #endif
441
442         /*
443          * 18 is DLT_CIP in SuSE 6.3 libpcap; if it's the same as the
444          * DLT_CIP of 16 that the Alexey Kuznetzov patches for
445          * libpcap/tcpdump define, it's WTAP_ENCAP_LINUX_ATM_CLIP.
446          * I've not found any libpcap that uses it for any other purpose -
447          * hopefully nobody will do so in the future.
448          */
449         { 18,           WTAP_ENCAP_LINUX_ATM_CLIP },
450
451         /*
452          * 19 is DLT_ATM_CLIP in the libpcap/tcpdump patches in the
453          * recent versions I've seen of the Linux ATM distribution;
454          * I've not yet found any libpcap that uses it for any other
455          * purpose - hopefully nobody will do so in the future.
456          */
457         { 19,           WTAP_ENCAP_LINUX_ATM_CLIP },
458
459         /*
460          * To repeat:
461          *
462          * If you need a new encapsulation type for libpcap files, do
463          * *N*O*T* use *ANY* of the values listed here!  I.e., do *NOT*
464          * add a new encapsulation type by changing an existing entry;
465          * leave the existing entries alone.
466          *
467          * Instead, send mail to tcpdump-workers@tcpdump.org, asking for
468          * a new DLT_ value, and specifying the purpose of the new value.
469          * When you get the new DLT_ value, use that numerical value in
470          * the "dlt_value" field of "pcap_to_wtap_map[]".
471          */
472
473 };
474 #define NUM_PCAP_ENCAPS (sizeof pcap_to_wtap_map / sizeof pcap_to_wtap_map[0])
475
476 int wtap_pcap_encap_to_wtap_encap(int encap)
477 {
478         unsigned int i;
479
480         for (i = 0; i < NUM_PCAP_ENCAPS; i++) {
481                 if (pcap_to_wtap_map[i].dlt_value == encap)
482                         return pcap_to_wtap_map[i].wtap_encap_value;
483         }
484         return WTAP_ENCAP_UNKNOWN;
485 }
486
487
488 int libpcap_open(wtap *wth, int *err)
489 {
490         int bytes_read;
491         guint32 magic;
492         struct pcap_hdr hdr;
493         gboolean byte_swapped;
494         gboolean modified;
495         gboolean aix;
496         int file_encap;
497
498         /* Read in the number that should be at the start of a "libpcap" file */
499         errno = WTAP_ERR_CANT_READ;
500         bytes_read = file_read(&magic, 1, sizeof magic, wth->fh);
501         if (bytes_read != sizeof magic) {
502                 *err = file_error(wth->fh);
503                 if (*err != 0)
504                         return -1;
505                 return 0;
506         }
507         wth->data_offset += sizeof magic;
508
509         switch (magic) {
510
511         case PCAP_MAGIC:
512                 /* Host that wrote it has our byte order, and was running
513                    a program using either standard or ss990417 libpcap. */
514                 byte_swapped = FALSE;
515                 modified = FALSE;
516                 break;
517
518         case PCAP_MODIFIED_MAGIC:
519                 /* Host that wrote it has our byte order, and was running
520                    a program using either ss990915 or ss991029 libpcap. */
521                 byte_swapped = FALSE;
522                 modified = TRUE;
523                 break;
524
525         case PCAP_SWAPPED_MAGIC:
526                 /* Host that wrote it has a byte order opposite to ours,
527                    and was running a program using either standard or
528                    ss990417 libpcap. */
529                 byte_swapped = TRUE;
530                 modified = FALSE;
531                 break;
532
533         case PCAP_SWAPPED_MODIFIED_MAGIC:
534                 /* Host that wrote it out has a byte order opposite to
535                    ours, and was running a program using either ss990915
536                    or ss991029 libpcap. */
537                 byte_swapped = TRUE;
538                 modified = TRUE;
539                 break;
540
541         default:
542                 /* Not a "libpcap" type we know about. */
543                 return 0;
544         }
545
546         /* Read the rest of the header. */
547         errno = WTAP_ERR_CANT_READ;
548         bytes_read = file_read(&hdr, 1, sizeof hdr, wth->fh);
549         if (bytes_read != sizeof hdr) {
550                 *err = file_error(wth->fh);
551                 if (*err != 0)
552                         return -1;
553                 return 0;
554         }
555         wth->data_offset += sizeof hdr;
556
557         if (byte_swapped) {
558                 /* Byte-swap the header fields about which we care. */
559                 hdr.version_major = BSWAP16(hdr.version_major);
560                 hdr.version_minor = BSWAP16(hdr.version_minor);
561                 hdr.snaplen = BSWAP32(hdr.snaplen);
562                 hdr.network = BSWAP32(hdr.network);
563         }
564         if (hdr.version_major < 2) {
565                 /* We only support version 2.0 and later. */
566                 g_message("pcap: major version %u unsupported",
567                     hdr.version_major);
568                 *err = WTAP_ERR_UNSUPPORTED;
569                 return -1;
570         }
571
572         /*
573          * AIX's non-standard tcpdump uses a minor version number of 2.
574          * Unfortunately, older versions of libpcap might have used
575          * that as well.
576          *
577          * The AIX libpcap uses RFC 1573 ifType values rather than
578          * DLT_ values in the header; the ifType values for LAN devices
579          * are:
580          *
581          *      Ethernet        6
582          *      Token Ring      9
583          *      FDDI            15
584          *
585          * which correspond to DLT_IEEE802 (used for Token Ring),
586          * DLT_PPP, and DLT_SLIP_BSDOS, respectively.  The ifType value
587          * for a loopback interface is 24, which currently isn't
588          * used by any version of libpcap I know about (and, as
589          * tcpdump.org are assigning DLT_ values above 100, and
590          * NetBSD started assigning values starting at 50, and
591          * the values chosen by other libpcaps appear to stop at
592          * 19, it's probably not going to be used by any libpcap
593          * in the future).
594          *
595          * We shall assume that if the minor version number is 2, and
596          * the network type is 6, 9, 15, or 24, that it's AIX libpcap.
597          *
598          * I'm assuming those older versions of libpcap didn't
599          * use DLT_IEEE802 for Token Ring, and didn't use DLT_SLIP_BSDOS
600          * as that came later.  It may have used DLT_PPP, however, in
601          * which case we're out of luck; we assume it's Token Ring
602          * in AIX libpcap rather than PPP in standard libpcap, as
603          * you're probably more likely to be handing an AIX libpcap
604          * token-ring capture than an old (pre-libpcap 0.4) PPP capture
605          * to Ethereal.
606          */
607         aix = FALSE;    /* assume it's not AIX */
608         if (hdr.version_major == 2 && hdr.version_minor == 2) {
609                 switch (hdr.network) {
610
611                 case 6:
612                         hdr.network = 1;        /* DLT_EN10MB, Ethernet */
613                         aix = TRUE;
614                         break;
615
616                 case 9:
617                         hdr.network = 6;        /* DLT_IEEE802, Token Ring */
618                         aix = TRUE;
619                         break;
620
621                 case 15:
622                         hdr.network = 10;       /* DLT_FDDI, FDDI */
623                         aix = TRUE;
624                         break;
625
626                 case 24:
627                         hdr.network = 0;        /* DLT_NULL, loopback */
628                         aix = TRUE;
629                         break;
630                 }
631         }
632         file_encap = wtap_pcap_encap_to_wtap_encap(hdr.network);
633         if (file_encap == WTAP_ENCAP_UNKNOWN) {
634                 g_message("pcap: network type %u unknown or unsupported",
635                     hdr.network);
636                 *err = WTAP_ERR_UNSUPPORTED_ENCAP;
637                 return -1;
638         }
639
640         /* This is a libpcap file */
641         wth->capture.pcap = g_malloc(sizeof(libpcap_t));
642         wth->capture.pcap->byte_swapped = byte_swapped;
643         wth->capture.pcap->version_major = hdr.version_major;
644         wth->capture.pcap->version_minor = hdr.version_minor;
645         wth->subtype_read = libpcap_read;
646         wth->subtype_seek_read = libpcap_seek_read;
647         wth->subtype_close = libpcap_close;
648         wth->file_encap = file_encap;
649         wth->snapshot_length = hdr.snaplen;
650
651         /* In file format version 2.3, the order of the "incl_len" and
652            "orig_len" fields in the per-packet header was reversed,
653            in order to match the BPF header layout.
654
655            Therefore, in files with versions prior to that, we must swap
656            those two fields.
657
658            Unfortunately, some files were, according to a comment in the
659            "libpcap" source, written with version 2.3 in their headers
660            but without the interchanged fields, so if "incl_len" is
661            greater than "orig_len" - which would make no sense - we
662            assume that we need to swap them in version 2.3 files
663            as well.
664
665            In addition, DG/UX's tcpdump uses version 543.0, and writes
666            the two fields in the pre-2.3 order. */
667         switch (hdr.version_major) {
668
669         case 2:
670                 if (hdr.version_minor < 3)
671                         wth->capture.pcap->lengths_swapped = SWAPPED;
672                 else if (hdr.version_minor == 3)
673                         wth->capture.pcap->lengths_swapped = MAYBE_SWAPPED;
674                 else
675                         wth->capture.pcap->lengths_swapped = NOT_SWAPPED;
676                 break;
677
678         case 543:
679                 wth->capture.pcap->lengths_swapped = SWAPPED;
680                 break;
681
682         default:
683                 wth->capture.pcap->lengths_swapped = NOT_SWAPPED;
684                 break;
685         }
686
687         /*
688          * Is this AIX format?
689          */
690         if (aix) {
691                 /*
692                  * Yes.  Skip all the tests for other mutant formats.
693                  */
694                 wth->file_type = WTAP_FILE_PCAP_AIX;
695                 return 1;
696         }
697
698         /*
699          * No.  Let's look at the header for the first record,
700          * and see if, interpreting it as a standard header (if the
701          * magic number was standard) or a modified header (if the
702          * magic number was modified), the position where it says the
703          * header for the *second* record is contains a corrupted header.
704          *
705          * If so, then:
706          *
707          *      If this file had the standard magic number, it may be
708          *      an ss990417 capture file - in that version of Alexey's
709          *      patch, the packet header format was changed but the
710          *      magic number wasn't, and, alas, Red Hat appear to have
711          *      picked up that version of the patch for RH 6.1, meaning
712          *      RH 6.1 has a tcpdump that writes out files that can't
713          *      be read by any software that expects non-modified headers
714          *      if the magic number isn't the modified magic number (e.g.,
715          *      any normal version of tcpdump, and Ethereal if we don't
716          *      do this gross heuristic).
717          *
718          *      If this file had the modified magic number, it may be
719          *      an ss990915 capture file - in that version of Alexey's
720          *      patch, the magic number was changed, but the record
721          *      header had some extra fields, and, alas, SuSE appear
722          *      to have picked up that version of the patch for SuSE
723          *      6.3, meaning that programs expecting the standard per-
724          *      packet header in captures with the modified magic number
725          *      can't read dumps from its tcpdump.
726          *
727          * Oh, and if it has the standard magic number, it might, instead,
728          * be a Nokia libpcap file, so we may need to try that if
729          * neither normal nor ss990417 headers work.
730          */
731         if (modified) {
732                 /*
733                  * Well, we have the magic number from Alexey's
734                  * later two patches.
735                  *
736                  * Try ss991029, the last of his patches, first.
737                  */
738                 wth->file_type = WTAP_FILE_PCAP_SS991029;
739                 switch (libpcap_try(wth, err)) {
740
741                 case BAD_READ:
742                         /*
743                          * Well, we couldn't even read it.
744                          * Give up.
745                          */
746                         g_free(wth->capture.pcap);
747                         return -1;
748
749                 case THIS_FORMAT:
750                         /*
751                          * Well, it looks as if it might be 991029.
752                          * Put the seek pointer back, and return success.
753                          */
754                         if (file_seek(wth->fh, wth->data_offset, SEEK_SET, err) == -1) {
755                                 g_free(wth->capture.pcap);
756                                 return -1;
757                         }
758                         return 1;
759
760                 case OTHER_FORMAT:
761                         /*
762                          * Try the next format.
763                          */
764                         break;
765                 }
766
767                 /*
768                  * Well, it's not completely unreadable,
769                  * but it's not ss991029.  Try ss990915;
770                  * there are no other types to try after that,
771                  * so we put the seek pointer back and treat
772                  * it as 990915.
773                  */
774                 wth->file_type = WTAP_FILE_PCAP_SS990915;
775                 if (file_seek(wth->fh, wth->data_offset, SEEK_SET, err) == -1) {
776                         g_free(wth->capture.pcap);
777                         return -1;
778                 }
779         } else {
780                 /*
781                  * Well, we have the standard magic number.
782                  *
783                  * Try the standard format first.
784                  */
785                 wth->file_type = WTAP_FILE_PCAP;
786                 switch (libpcap_try(wth, err)) {
787
788                 case BAD_READ:
789                         /*
790                          * Well, we couldn't even read it.
791                          * Give up.
792                          */
793                         g_free(wth->capture.pcap);
794                         return -1;
795
796                 case THIS_FORMAT:
797                         /*
798                          * Well, it looks as if it might be a standard
799                          * libpcap file.
800                          * Put the seek pointer back, and return success.
801                          */
802                         if (file_seek(wth->fh, wth->data_offset, SEEK_SET, err) == -1) {
803                                 g_free(wth->capture.pcap);
804                                 return -1;
805                         }
806                         return 1;
807
808                 case OTHER_FORMAT:
809                         /*
810                          * Try the next format.
811                          */
812                         break;
813                 }
814
815                 /*
816                  * Well, it's not completely unreadable, but it's not
817                  * a standard file.  Put the seek pointer back and try
818                  * ss990417.
819                  */
820                 wth->file_type = WTAP_FILE_PCAP_SS990417;
821                 if (file_seek(wth->fh, wth->data_offset, SEEK_SET, err) == -1) {
822                         g_free(wth->capture.pcap);
823                         return -1;
824                 }
825                 switch (libpcap_try(wth, err)) {
826
827                 case BAD_READ:
828                         /*
829                          * Well, we couldn't even read it.
830                          * Give up.
831                          */
832                         g_free(wth->capture.pcap);
833                         return -1;
834
835                 case THIS_FORMAT:
836                         /*
837                          * Well, it looks as if it might be ss990417.
838                          * Put the seek pointer back, and return success.
839                          */
840                         if (file_seek(wth->fh, wth->data_offset, SEEK_SET, err) == -1) {
841                                 g_free(wth->capture.pcap);
842                                 return -1;
843                         }
844                         return 1;
845
846                 case OTHER_FORMAT:
847                         /*
848                          * Try the next format.
849                          */
850                         break;
851                 }
852
853                 /*
854                  * Well, it's not completely unreadable,
855                  * but it's not a standard file *nor* is it ss990417.
856                  * Try it as a Nokia file; there are no other types
857                  * to try after that, so we put the seek pointer back
858                  * and treat it as a Nokia file.
859                  */
860                 wth->file_type = WTAP_FILE_PCAP_NOKIA;
861                 if (file_seek(wth->fh, wth->data_offset, SEEK_SET, err) == -1) {
862                         g_free(wth->capture.pcap);
863                         return -1;
864                 }
865         }
866
867         return 1;
868 }
869
870 /* Try to read the first two records of the capture file. */
871 static libpcap_try_t libpcap_try(wtap *wth, int *err)
872 {
873         /*
874          * pcaprec_ss990915_hdr is the largest header type.
875          */
876         struct pcaprec_ss990915_hdr first_rec_hdr, second_rec_hdr;
877
878         /*
879          * Attempt to read the first record's header.
880          */
881         if (libpcap_read_header(wth, err, &first_rec_hdr, TRUE) == -1) {
882                 if (*err == 0 || *err == WTAP_ERR_SHORT_READ) {
883                         /*
884                          * EOF or short read - assume the file is in this
885                          * format.
886                          * When our client tries to read the first packet
887                          * they will presumably get the same EOF or short
888                          * read.
889                          */
890                         return THIS_FORMAT;
891                 }
892
893                 if (*err == WTAP_ERR_BAD_RECORD) {
894                         /*
895                          * The first record is bogus, so this is probably
896                          * a corrupt file.  Assume the file is in this
897                          * format.  When our client tries to read the
898                          * first packet they will presumably get the
899                          * same bogus record.
900                          */
901                         return THIS_FORMAT;
902                 }
903
904                 /*
905                  * Some other error, e.g. an I/O error; just give up.
906                  */
907                 return BAD_READ;
908         }
909
910         /*
911          * Now skip over the first record's data, under the assumption
912          * that the header is sane.
913          */
914         if (file_seek(wth->fh, first_rec_hdr.hdr.incl_len, SEEK_CUR, err) == -1)
915                 return BAD_READ;
916
917         /*
918          * Now attempt to read the second record's header.
919          */
920         if (libpcap_read_header(wth, err, &second_rec_hdr, TRUE) == -1) {
921                 if (*err == 0 || *err == WTAP_ERR_SHORT_READ) {
922                         /*
923                          * EOF or short read - assume the file is in this
924                          * format.
925                          * When our client tries to read the second packet
926                          * they will presumably get the same EOF or short
927                          * read.
928                          */
929                         return THIS_FORMAT;
930                 }
931
932                 if (*err == WTAP_ERR_BAD_RECORD) {
933                         /*
934                          * The second record is bogus; maybe it's a
935                          * Capture File From Hell, and what looks like
936                          * the "header" of the next packet is actually
937                          * random junk from the middle of a packet.
938                          * Try the next format; if we run out of formats,
939                          * it probably *is* a corrupt file.
940                          */
941                         return OTHER_FORMAT;
942                 }
943
944                 /*
945                  * Some other error, e.g. an I/O error; just give up.
946                  */
947                 return BAD_READ;
948         }
949
950         /*
951          * OK, the first two records look OK; assume this is the
952          * right format.
953          */
954         return THIS_FORMAT;
955 }
956
957 /* Read the next packet */
958 static gboolean libpcap_read(wtap *wth, int *err, long *data_offset)
959 {
960         struct pcaprec_ss990915_hdr hdr;
961         guint packet_size;
962         guint orig_size;
963         int bytes_read;
964         char fddi_padding[3];
965
966         bytes_read = libpcap_read_header(wth, err, &hdr, FALSE);
967         if (bytes_read == -1) {
968                 /*
969                  * We failed to read the header.
970                  */
971                 return FALSE;
972         }
973
974         wth->data_offset += bytes_read;
975         packet_size = hdr.hdr.incl_len;
976         orig_size = hdr.hdr.orig_len;
977
978         /*
979          * AIX appears to put 3 bytes of padding in front of FDDI
980          * frames; strip that crap off.
981          */
982         if (wth->file_type == WTAP_FILE_PCAP_AIX &&
983             (wth->file_encap == WTAP_ENCAP_FDDI ||
984              wth->file_encap == WTAP_ENCAP_FDDI_BITSWAPPED)) {
985                 /*
986                  * The packet size is really a record size and includes
987                  * the padding.
988                  */
989                 packet_size -= 3;
990                 orig_size -= 3;
991                 wth->data_offset += 3;
992
993                 /*
994                  * Read the padding.
995                  */
996                 if (!libpcap_read_rec_data(wth->fh, fddi_padding, 3, err))
997                         return FALSE;   /* Read error */
998         }
999
1000         *data_offset = wth->data_offset;
1001
1002         /*
1003          * If this is an ATM packet, the first four bytes are the
1004          * direction of the packet (transmit/receive), the VPI, and
1005          * the VCI; read them and generate the pseudo-header from
1006          * them.
1007          */
1008         switch (wth->file_encap) {
1009
1010         case WTAP_ENCAP_ATM_PDUS:
1011                 if (packet_size < sizeof (struct sunatm_hdr)) {
1012                         /*
1013                          * Uh-oh, the packet isn't big enough to even
1014                          * have a pseudo-header.
1015                          */
1016                         g_message("libpcap: SunATM file has a %u-byte packet, too small to have even an ATM pseudo-header\n",
1017                             packet_size);
1018                         *err = WTAP_ERR_BAD_RECORD;
1019                         return FALSE;
1020                 }
1021                 if (!libpcap_read_atm_pseudoheader(wth->fh, &wth->pseudo_header,
1022                     err))
1023                         return FALSE;   /* Read error */
1024
1025                 /*
1026                  * Don't count the pseudo-header as part of the packet.
1027                  */
1028                 orig_size -= sizeof (struct sunatm_hdr);
1029                 packet_size -= sizeof (struct sunatm_hdr);
1030                 wth->data_offset += sizeof (struct sunatm_hdr);
1031                 break;
1032
1033         case WTAP_ENCAP_ETHERNET:
1034                 /*
1035                  * We don't know whether there's an FCS in this frame or not.
1036                  */
1037                 wth->pseudo_header.eth.fcs_len = -1;
1038                 break;
1039
1040         case WTAP_ENCAP_IRDA:
1041                 if (packet_size < sizeof (struct irda_sll_hdr)) {
1042                         /*
1043                          * Uh-oh, the packet isn't big enough to even
1044                          * have a pseudo-header.
1045                          */
1046                         g_message("libpcap: IrDA file has a %u-byte packet, too small to have even an IrDA pseudo-header\n",
1047                             packet_size);
1048                         *err = WTAP_ERR_BAD_RECORD;
1049                         return FALSE;
1050                 }
1051                 if (!libpcap_read_irda_pseudoheader(wth->fh, &wth->pseudo_header,
1052                     err))
1053                         return FALSE;   /* Read error */
1054
1055                 /*
1056                  * Don't count the pseudo-header as part of the packet.
1057                  */
1058                 orig_size -= sizeof (struct irda_sll_hdr);
1059                 packet_size -= sizeof (struct irda_sll_hdr);
1060                 wth->data_offset += sizeof (struct irda_sll_hdr);
1061                 break;
1062         }
1063
1064         buffer_assure_space(wth->frame_buffer, packet_size);
1065         if (!libpcap_read_rec_data(wth->fh, buffer_start_ptr(wth->frame_buffer),
1066             packet_size, err))
1067                 return FALSE;   /* Read error */
1068         wth->data_offset += packet_size;
1069
1070         wth->phdr.ts.tv_sec = hdr.hdr.ts_sec;
1071         wth->phdr.ts.tv_usec = hdr.hdr.ts_usec;
1072         wth->phdr.caplen = packet_size;
1073         wth->phdr.len = orig_size;
1074         wth->phdr.pkt_encap = wth->file_encap;
1075
1076         /*
1077          * If this is ATM LANE traffic, try to guess what type of LANE
1078          * traffic it is based on the packet contents.
1079          */
1080         if (wth->file_encap == WTAP_ENCAP_ATM_PDUS &&
1081             wth->pseudo_header.atm.type == TRAF_LANE) {
1082                 atm_guess_lane_type(buffer_start_ptr(wth->frame_buffer),
1083                     wth->phdr.caplen, &wth->pseudo_header);
1084         }
1085
1086         return TRUE;
1087 }
1088
1089 static gboolean
1090 libpcap_seek_read(wtap *wth, long seek_off,
1091     union wtap_pseudo_header *pseudo_header, guchar *pd, int length, int *err)
1092 {
1093         if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
1094                 return FALSE;
1095
1096         switch (wth->file_encap) {
1097
1098         case WTAP_ENCAP_ATM_PDUS:
1099                 if (!libpcap_read_atm_pseudoheader(wth->random_fh, pseudo_header,
1100                     err)) {
1101                         /* Read error */
1102                         return FALSE;
1103                 }
1104                 break;
1105
1106         case WTAP_ENCAP_ETHERNET:
1107                 /*
1108                  * We don't know whether there's an FCS in this frame or not.
1109                  */
1110                 pseudo_header->eth.fcs_len = -1;
1111                 break;
1112
1113         case WTAP_ENCAP_IRDA:
1114                 if (!libpcap_read_irda_pseudoheader(wth->random_fh, pseudo_header,
1115                     err)) {
1116                         /* Read error */
1117                         return FALSE;
1118                 }
1119                 break;
1120         }
1121
1122         /*
1123          * Read the packet data.
1124          */
1125         if (!libpcap_read_rec_data(wth->random_fh, pd, length, err))
1126                 return FALSE;   /* failed */
1127
1128         /*
1129          * If this is ATM LANE traffic, try to guess what type of LANE
1130          * traffic it is based on the packet contents.
1131          */
1132         if (wth->file_encap == WTAP_ENCAP_ATM_PDUS &&
1133             pseudo_header->atm.type == TRAF_LANE)
1134                 atm_guess_lane_type(pd, length, pseudo_header);
1135         return TRUE;
1136 }
1137
1138 /* Read the header of the next packet; if "silent" is TRUE, don't complain
1139    to the console, as we're testing to see if the file appears to be of a
1140    particular type.
1141
1142    Return -1 on an error, or the number of bytes of header read on success. */
1143 static int libpcap_read_header(wtap *wth, int *err,
1144     struct pcaprec_ss990915_hdr *hdr, gboolean silent)
1145 {
1146         int     bytes_to_read, bytes_read;
1147
1148         /* Read record header. */
1149         errno = WTAP_ERR_CANT_READ;
1150         switch (wth->file_type) {
1151
1152         case WTAP_FILE_PCAP:
1153         case WTAP_FILE_PCAP_AIX:
1154                 bytes_to_read = sizeof (struct pcaprec_hdr);
1155                 break;
1156
1157         case WTAP_FILE_PCAP_SS990417:
1158         case WTAP_FILE_PCAP_SS991029:
1159                 bytes_to_read = sizeof (struct pcaprec_modified_hdr);
1160                 break;
1161
1162         case WTAP_FILE_PCAP_SS990915:
1163                 bytes_to_read = sizeof (struct pcaprec_ss990915_hdr);
1164                 break;
1165
1166         case WTAP_FILE_PCAP_NOKIA:
1167                 bytes_to_read = sizeof (struct pcaprec_nokia_hdr);
1168                 break;
1169
1170         default:
1171                 g_assert_not_reached();
1172                 bytes_to_read = 0;
1173         }
1174         bytes_read = file_read(hdr, 1, bytes_to_read, wth->fh);
1175         if (bytes_read != bytes_to_read) {
1176                 *err = file_error(wth->fh);
1177                 if (*err == 0 && bytes_read != 0) {
1178                         *err = WTAP_ERR_SHORT_READ;
1179                 }
1180                 return -1;
1181         }
1182
1183         adjust_header(wth, &hdr->hdr);
1184
1185         if (hdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1186                 /*
1187                  * Probably a corrupt capture file; return an error,
1188                  * so that our caller doesn't blow up trying to allocate
1189                  * space for an immensely-large packet, and so that
1190                  * the code to try to guess what type of libpcap file
1191                  * this is can tell when it's not the type we're guessing
1192                  * it is.
1193                  */
1194                 if (!silent) {
1195                         g_message("pcap: File has %u-byte packet, bigger than maximum of %u",
1196                             hdr->hdr.incl_len, WTAP_MAX_PACKET_SIZE);
1197                 }
1198                 *err = WTAP_ERR_BAD_RECORD;
1199                 return -1;
1200         }
1201
1202         if (hdr->hdr.orig_len > WTAP_MAX_PACKET_SIZE) {
1203                 /*
1204                  * Probably a corrupt capture file; return an error,
1205                  * so that our caller doesn't blow up trying to
1206                  * cope with a huge "real" packet length, and so that
1207                  * the code to try to guess what type of libpcap file
1208                  * this is can tell when it's not the type we're guessing
1209                  * it is.
1210                  */
1211                 if (!silent) {
1212                         g_message("pcap: File has %u-byte packet, bigger than maximum of %u",
1213                             hdr->hdr.orig_len, WTAP_MAX_PACKET_SIZE);
1214                 }
1215                 *err = WTAP_ERR_BAD_RECORD;
1216                 return -1;
1217         }
1218
1219         return bytes_read;
1220 }
1221
1222 static void
1223 adjust_header(wtap *wth, struct pcaprec_hdr *hdr)
1224 {
1225         guint32 temp;
1226
1227         if (wth->capture.pcap->byte_swapped) {
1228                 /* Byte-swap the record header fields. */
1229                 hdr->ts_sec = BSWAP32(hdr->ts_sec);
1230                 hdr->ts_usec = BSWAP32(hdr->ts_usec);
1231                 hdr->incl_len = BSWAP32(hdr->incl_len);
1232                 hdr->orig_len = BSWAP32(hdr->orig_len);
1233         }
1234
1235         /* If this is AIX, convert the time stamp from seconds/nanoseconds
1236            to seconds/microseconds.  */
1237         if (wth->file_type == WTAP_FILE_PCAP_AIX)
1238                 hdr->ts_usec = hdr->ts_usec/1000;
1239
1240         /* Swap the "incl_len" and "orig_len" fields, if necessary. */
1241         switch (wth->capture.pcap->lengths_swapped) {
1242
1243         case NOT_SWAPPED:
1244                 break;
1245
1246         case MAYBE_SWAPPED:
1247                 if (hdr->incl_len <= hdr->orig_len) {
1248                         /*
1249                          * The captured length is <= the actual length,
1250                          * so presumably they weren't swapped.
1251                          */
1252                         break;
1253                 }
1254                 /* FALLTHROUGH */
1255
1256         case SWAPPED:
1257                 temp = hdr->orig_len;
1258                 hdr->orig_len = hdr->incl_len;
1259                 hdr->incl_len = temp;
1260                 break;
1261         }
1262 }
1263
1264 static void
1265 libpcap_get_atm_pseudoheader(const struct sunatm_hdr *atm_phdr,
1266     union wtap_pseudo_header *pseudo_header)
1267 {
1268         guint8  vpi;
1269         guint16 vci;
1270
1271         vpi = atm_phdr->vpi;
1272         vci = pntohs(&atm_phdr->vci);
1273
1274         /*
1275          * The lower 4 bits of the first byte of the header indicate
1276          * the type of traffic, as per the "atmioctl.h" header in
1277          * SunATM.
1278          */
1279         switch (atm_phdr->flags & 0x0F) {
1280
1281         case 0x01:      /* LANE */
1282                 pseudo_header->atm.aal = AAL_5;
1283                 pseudo_header->atm.type = TRAF_LANE;
1284                 break;
1285
1286         case 0x02:      /* RFC 1483 LLC multiplexed traffic */
1287                 pseudo_header->atm.aal = AAL_5;
1288                 pseudo_header->atm.type = TRAF_LLCMX;
1289                 break;
1290
1291         case 0x05:      /* ILMI */
1292                 pseudo_header->atm.aal = AAL_5;
1293                 pseudo_header->atm.type = TRAF_ILMI;
1294                 break;
1295
1296         case 0x06:      /* Q.2931 */
1297                 pseudo_header->atm.aal = AAL_SIGNALLING;
1298                 pseudo_header->atm.type = TRAF_UNKNOWN;
1299                 break;
1300
1301         case 0x03:      /* MARS (RFC 2022) */
1302                 pseudo_header->atm.aal = AAL_5;
1303                 pseudo_header->atm.type = TRAF_UNKNOWN;
1304                 break;
1305
1306         case 0x04:      /* IFMP (Ipsilon Flow Management Protocol; see RFC 1954) */
1307                 pseudo_header->atm.aal = AAL_5;
1308                 pseudo_header->atm.type = TRAF_UNKNOWN; /* XXX - TRAF_IPSILON? */
1309                 break;
1310
1311         default:
1312                 /*
1313                  * Assume it's AAL5, unless it's VPI 0 and VCI 5, in which
1314                  * case assume it's AAL_SIGNALLING; we know nothing more
1315                  * about it.
1316                  *
1317                  * XXX - is this necessary?  Or are we guaranteed that
1318                  * all signalling traffic has a type of 0x06?
1319                  *
1320                  * XXX - is this guaranteed to be AAL5?  Or, if the type is
1321                  * 0x00 ("raw"), might it be non-AAL5 traffic?
1322                  */
1323                 if (vpi == 0 && vci == 5)
1324                         pseudo_header->atm.aal = AAL_SIGNALLING;
1325                 else
1326                         pseudo_header->atm.aal = AAL_5;
1327                 pseudo_header->atm.type = TRAF_UNKNOWN;
1328                 break;
1329         }
1330         pseudo_header->atm.subtype = TRAF_ST_UNKNOWN;
1331
1332         pseudo_header->atm.vpi = vpi;
1333         pseudo_header->atm.vci = vci;
1334         pseudo_header->atm.channel = (atm_phdr->flags & 0x80) ? 0 : 1;
1335
1336         /* We don't have this information */
1337         pseudo_header->atm.flags = 0;
1338         pseudo_header->atm.cells = 0;
1339         pseudo_header->atm.aal5t_u2u = 0;
1340         pseudo_header->atm.aal5t_len = 0;
1341         pseudo_header->atm.aal5t_chksum = 0;
1342 }
1343
1344 static gboolean
1345 libpcap_read_atm_pseudoheader(FILE_T fh, union wtap_pseudo_header *pseudo_header,
1346     int *err)
1347 {
1348         struct sunatm_hdr atm_phdr;
1349         int     bytes_read;
1350
1351         errno = WTAP_ERR_CANT_READ;
1352         bytes_read = file_read(&atm_phdr, 1, sizeof (struct sunatm_hdr), fh);
1353         if (bytes_read != sizeof (struct sunatm_hdr)) {
1354                 *err = file_error(fh);
1355                 if (*err == 0)
1356                         *err = WTAP_ERR_SHORT_READ;
1357                 return FALSE;
1358         }
1359
1360         libpcap_get_atm_pseudoheader(&atm_phdr, pseudo_header);
1361
1362         return TRUE;
1363 }
1364
1365 static gboolean
1366 libpcap_get_irda_pseudoheader(const struct irda_sll_hdr *irda_phdr,
1367     union wtap_pseudo_header *pseudo_header, int *err)
1368 {
1369         if (pntohs(&irda_phdr->sll_protocol) != 0x0017) {
1370                 g_message("libpcap: IrDA capture has a packet with an invalid sll_protocol field\n");
1371                 *err = WTAP_ERR_BAD_RECORD;
1372                 return FALSE;
1373         }
1374
1375         pseudo_header->irda.pkttype = pntohs(&irda_phdr->sll_pkttype);
1376
1377     return TRUE;
1378 }
1379
1380 static gboolean
1381 libpcap_read_irda_pseudoheader(FILE_T fh, union wtap_pseudo_header *pseudo_header,
1382     int *err)
1383 {
1384         struct irda_sll_hdr irda_phdr;
1385         int     bytes_read;
1386
1387         errno = WTAP_ERR_CANT_READ;
1388         bytes_read = file_read(&irda_phdr, 1, sizeof (struct irda_sll_hdr), fh);
1389         if (bytes_read != sizeof (struct irda_sll_hdr)) {
1390                 *err = file_error(fh);
1391                 if (*err == 0)
1392                         *err = WTAP_ERR_SHORT_READ;
1393                 return FALSE;
1394         }
1395
1396         return libpcap_get_irda_pseudoheader(&irda_phdr, pseudo_header, err);
1397 }
1398
1399 static gboolean
1400 libpcap_read_rec_data(FILE_T fh, guchar *pd, int length, int *err)
1401 {
1402         int     bytes_read;
1403
1404         errno = WTAP_ERR_CANT_READ;
1405         bytes_read = file_read(pd, 1, length, fh);
1406
1407         if (bytes_read != length) {
1408                 *err = file_error(fh);
1409                 if (*err == 0)
1410                         *err = WTAP_ERR_SHORT_READ;
1411                 return FALSE;
1412         }
1413         return TRUE;
1414 }
1415
1416 static void
1417 libpcap_close(wtap *wth)
1418 {
1419         g_free(wth->capture.pcap);
1420 }
1421
1422 static int wtap_wtap_encap_to_pcap_encap(int encap)
1423 {
1424         unsigned int i;
1425
1426         switch (encap) {
1427
1428         case WTAP_ENCAP_FDDI:
1429         case WTAP_ENCAP_FDDI_BITSWAPPED:
1430                 /*
1431                  * Special-case WTAP_ENCAP_FDDI and
1432                  * WTAP_ENCAP_FDDI_BITSWAPPED; both of them get mapped
1433                  * to DLT_FDDI (even though that may mean that the bit
1434                  * order in the FDDI MAC addresses is wrong; so it goes
1435                  * - libpcap format doesn't record the byte order,
1436                  * so that's not fixable).
1437                  */
1438                 return 10;      /* that's DLT_FDDI */
1439
1440         case WTAP_ENCAP_PPP_WITH_PHDR:
1441                 /*
1442                  * Also special-case PPP and Frame Relay with direction
1443                  * bits; map them to PPP and Frame Relay, even though
1444                  * that means that the direction of the packet is lost.
1445                  */
1446                 return 9;
1447
1448         case WTAP_ENCAP_FRELAY_WITH_PHDR:
1449                 return 107;
1450         }
1451
1452         for (i = 0; i < NUM_PCAP_ENCAPS; i++) {
1453                 if (pcap_to_wtap_map[i].wtap_encap_value == encap)
1454                         return pcap_to_wtap_map[i].dlt_value;
1455         }
1456         return -1;
1457 }
1458
1459 #ifdef HAVE_PCAP_H
1460 /*
1461  * Given a Wiretap encapsulation type, and raw packet data and the packet
1462  * header from libpcap, process any pseudo-header in the packet,
1463  * fill in the Wiretap packet header, and return a pointer to the
1464  * beginning of the non-pseudo-header data in the packet.
1465  */
1466 const guchar *
1467 wtap_process_pcap_packet(gint linktype, const struct pcap_pkthdr *phdr,
1468     const guchar *pd, union wtap_pseudo_header *pseudo_header,
1469     struct wtap_pkthdr *whdr, int *err)
1470 {
1471         /* "phdr->ts" may not necessarily be a "struct timeval" - it may
1472            be a "struct bpf_timeval", with member sizes wired to 32
1473            bits - and we may go that way ourselves in the future, so
1474            copy the members individually. */
1475         whdr->ts.tv_sec = phdr->ts.tv_sec;
1476         whdr->ts.tv_usec = phdr->ts.tv_usec;
1477         whdr->caplen = phdr->caplen;
1478         whdr->len = phdr->len;
1479         whdr->pkt_encap = linktype;
1480
1481         /*
1482          * If this is an ATM packet, the first four bytes are the
1483          * direction of the packet (transmit/receive), the VPI, and
1484          * the VCI; read them and generate the pseudo-header from
1485          * them.
1486          */
1487         if (linktype == WTAP_ENCAP_ATM_PDUS) {
1488                 if (whdr->caplen < sizeof (struct sunatm_hdr)) {
1489                         /*
1490                          * Uh-oh, the packet isn't big enough to even
1491                          * have a pseudo-header.
1492                          */
1493                         g_message("libpcap: SunATM capture has a %u-byte packet, too small to have even an ATM pseudo-header\n",
1494                             whdr->caplen);
1495                         *err = WTAP_ERR_BAD_RECORD;
1496                         return NULL;
1497                 }
1498                 libpcap_get_atm_pseudoheader((const struct sunatm_hdr *)pd,
1499                     pseudo_header);
1500
1501                 /*
1502                  * Don't count the pseudo-header as part of the packet.
1503                  */
1504                 whdr->len -= sizeof (struct sunatm_hdr);
1505                 whdr->caplen -= sizeof (struct sunatm_hdr);
1506                 pd += sizeof (struct sunatm_hdr);
1507
1508                 /*
1509                  * If this is ATM LANE traffic, try to guess what type of
1510                  * LANE traffic it is based on the packet contents.
1511                  */
1512                 if (pseudo_header->atm.type == TRAF_LANE)
1513                         atm_guess_lane_type(pd, whdr->caplen, pseudo_header);
1514         }
1515         else if (linktype == WTAP_ENCAP_IRDA) {
1516                 if (whdr->caplen < sizeof (struct irda_sll_hdr)) {
1517                         /*
1518                          * Uh-oh, the packet isn't big enough to even
1519                          * have a pseudo-header.
1520                          */
1521                         g_message("libpcap: IrDA capture has a %u-byte packet, too small to have even an IrDA pseudo-header\n",
1522                             whdr->caplen);
1523                         *err = WTAP_ERR_BAD_RECORD;
1524                         return NULL;
1525                 }
1526                 if (!libpcap_get_irda_pseudoheader((const struct irda_sll_hdr *)pd,
1527                         pseudo_header, err))
1528                         return NULL;
1529
1530                 /*
1531                  * Don't count the pseudo-header as part of the packet.
1532                  */
1533                 whdr->len -= sizeof (struct irda_sll_hdr);
1534                 whdr->caplen -= sizeof (struct irda_sll_hdr);
1535                 pd += sizeof (struct irda_sll_hdr);
1536         }
1537         return pd;
1538 }
1539 #endif
1540
1541 /* Returns 0 if we could write the specified encapsulation type,
1542    an error indication otherwise. */
1543 int libpcap_dump_can_write_encap(int encap)
1544 {
1545         /* Per-packet encapsulations aren't supported. */
1546         if (encap == WTAP_ENCAP_PER_PACKET)
1547                 return WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
1548
1549         if (wtap_wtap_encap_to_pcap_encap(encap) == -1)
1550                 return WTAP_ERR_UNSUPPORTED_ENCAP;
1551
1552         return 0;
1553 }
1554
1555 /* Returns TRUE on success, FALSE on failure; sets "*err" to an error code on
1556    failure */
1557 gboolean libpcap_dump_open(wtap_dumper *wdh, gboolean cant_seek _U_, int *err)
1558 {
1559         guint32 magic;
1560         struct pcap_hdr file_hdr;
1561         size_t nwritten;
1562
1563         /* This is a libpcap file */
1564         wdh->subtype_write = libpcap_dump;
1565         wdh->subtype_close = NULL;
1566
1567         /* Write the file header. */
1568         switch (wdh->file_type) {
1569
1570         case WTAP_FILE_PCAP:
1571         case WTAP_FILE_PCAP_SS990417:   /* modified, but with the old magic, sigh */
1572         case WTAP_FILE_PCAP_NOKIA:      /* Nokia libpcap of some sort */
1573                 magic = PCAP_MAGIC;
1574                 break;
1575
1576         case WTAP_FILE_PCAP_SS990915:   /* new magic, extra crap */
1577         case WTAP_FILE_PCAP_SS991029:
1578                 magic = PCAP_MODIFIED_MAGIC;
1579                 break;
1580
1581         default:
1582                 /* We should never get here - our open routine
1583                    should only get called for the types above. */
1584                 *err = WTAP_ERR_UNSUPPORTED_FILE_TYPE;
1585                 return FALSE;
1586         }
1587
1588         nwritten = fwrite(&magic, 1, sizeof magic, wdh->fh);
1589         if (nwritten != sizeof magic) {
1590                 if (nwritten == 0 && ferror(wdh->fh))
1591                         *err = errno;
1592                 else
1593                         *err = WTAP_ERR_SHORT_WRITE;
1594                 return FALSE;
1595         }
1596         wdh->bytes_dumped += sizeof magic;
1597
1598         /* current "libpcap" format is 2.4 */
1599         file_hdr.version_major = 2;
1600         file_hdr.version_minor = 4;
1601         file_hdr.thiszone = 0;  /* XXX - current offset? */
1602         file_hdr.sigfigs = 0;   /* unknown, but also apparently unused */
1603         /*
1604          * Tcpdump cannot handle capture files with a snapshot length of 0,
1605          * as BPF filters return either 0 if they fail or the snapshot length
1606          * if they succeed, and a snapshot length of 0 means success is
1607          * indistinguishable from failure and the filter expression would
1608          * reject all packets.
1609          *
1610          * A snapshot length of 0, inside Wiretap, means "snapshot length
1611          * unknown"; if the snapshot length supplied to us is 0, we make
1612          * the snapshot length in the header file WTAP_MAX_PACKET_SIZE.
1613          */
1614         file_hdr.snaplen = (wdh->snaplen != 0) ? wdh->snaplen :
1615                                                  WTAP_MAX_PACKET_SIZE;
1616         file_hdr.network = wtap_wtap_encap_to_pcap_encap(wdh->encap);
1617         nwritten = fwrite(&file_hdr, 1, sizeof file_hdr, wdh->fh);
1618         if (nwritten != sizeof file_hdr) {
1619                 if (nwritten == 0 && ferror(wdh->fh))
1620                         *err = errno;
1621                 else
1622                         *err = WTAP_ERR_SHORT_WRITE;
1623                 return FALSE;
1624         }
1625         wdh->bytes_dumped += sizeof file_hdr;
1626
1627         return TRUE;
1628 }
1629
1630 /* Write a record for a packet to a dump file.
1631    Returns TRUE on success, FALSE on failure. */
1632 static gboolean libpcap_dump(wtap_dumper *wdh,
1633         const struct wtap_pkthdr *phdr,
1634         const union wtap_pseudo_header *pseudo_header _U_,
1635         const guchar *pd, int *err)
1636 {
1637         struct pcaprec_ss990915_hdr rec_hdr;
1638         size_t hdr_size;
1639         size_t nwritten;
1640         struct sunatm_hdr atm_hdr;
1641         struct irda_sll_hdr irda_hdr;
1642         int hdrsize;
1643
1644         if (wdh->encap == WTAP_ENCAP_ATM_PDUS)
1645                 hdrsize = sizeof (struct sunatm_hdr);
1646         else if (wdh->encap == WTAP_ENCAP_IRDA)
1647                 hdrsize = sizeof (struct irda_sll_hdr);
1648         else
1649                 hdrsize = 0;
1650
1651         rec_hdr.hdr.ts_sec = phdr->ts.tv_sec;
1652         rec_hdr.hdr.ts_usec = phdr->ts.tv_usec;
1653         rec_hdr.hdr.incl_len = phdr->caplen + hdrsize;
1654         rec_hdr.hdr.orig_len = phdr->len + hdrsize;
1655         switch (wdh->file_type) {
1656
1657         case WTAP_FILE_PCAP:
1658                 hdr_size = sizeof (struct pcaprec_hdr);
1659                 break;
1660
1661         case WTAP_FILE_PCAP_SS990417:   /* modified, but with the old magic, sigh */
1662         case WTAP_FILE_PCAP_SS991029:
1663                 /* XXX - what should we supply here?
1664
1665                    Alexey's "libpcap" looks up the interface in the system's
1666                    interface list if "ifindex" is non-zero, and prints
1667                    the interface name.  It ignores "protocol", and uses
1668                    "pkt_type" to tag the packet as "host", "broadcast",
1669                    "multicast", "other host", "outgoing", or "none of the
1670                    above", but that's it.
1671
1672                    If the capture we're writing isn't a modified or
1673                    RH 6.1 capture, we'd have to do some work to
1674                    generate the packet type and interface index - and
1675                    we can't generate the interface index unless we
1676                    just did the capture ourselves in any case.
1677
1678                    I'm inclined to continue to punt; systems other than
1679                    those with the older patch can read standard "libpcap"
1680                    files, and systems with the older patch, e.g. RH 6.1,
1681                    will just have to live with this. */
1682                 rec_hdr.ifindex = 0;
1683                 rec_hdr.protocol = 0;
1684                 rec_hdr.pkt_type = 0;
1685                 hdr_size = sizeof (struct pcaprec_modified_hdr);
1686                 break;
1687
1688         case WTAP_FILE_PCAP_SS990915:   /* new magic, extra crap at the end */
1689                 rec_hdr.ifindex = 0;
1690                 rec_hdr.protocol = 0;
1691                 rec_hdr.pkt_type = 0;
1692                 rec_hdr.cpu1 = 0;
1693                 rec_hdr.cpu2 = 0;
1694                 hdr_size = sizeof (struct pcaprec_ss990915_hdr);
1695                 break;
1696
1697         case WTAP_FILE_PCAP_NOKIA:      /* old magic, extra crap at the end */
1698                 rec_hdr.ifindex = 0;
1699                 rec_hdr.protocol = 0;
1700                 rec_hdr.pkt_type = 0;
1701                 rec_hdr.cpu1 = 0;
1702                 rec_hdr.cpu2 = 0;
1703                 hdr_size = sizeof (struct pcaprec_nokia_hdr);
1704                 break;
1705
1706         default:
1707                 /* We should never get here - our open routine
1708                    should only get called for the types above. */
1709                 g_assert_not_reached();
1710                 *err = WTAP_ERR_UNSUPPORTED_FILE_TYPE;
1711                 return FALSE;
1712         }
1713
1714         nwritten = fwrite(&rec_hdr, 1, hdr_size, wdh->fh);
1715         if (nwritten != hdr_size) {
1716                 if (nwritten == 0 && ferror(wdh->fh))
1717                         *err = errno;
1718                 else
1719                         *err = WTAP_ERR_SHORT_WRITE;
1720                 return FALSE;
1721         }
1722         wdh->bytes_dumped += hdr_size;
1723
1724         if (wdh->encap == WTAP_ENCAP_ATM_PDUS) {
1725                 /*
1726                  * Write the ATM header.
1727                  */
1728                 atm_hdr.flags =
1729                     (pseudo_header->atm.channel == 0) ? 0x80 : 0x00;
1730                 switch (pseudo_header->atm.aal) {
1731
1732                 case AAL_SIGNALLING:
1733                         /* Q.2931 */
1734                         atm_hdr.flags |= 0x06;
1735                         break;
1736
1737                 case AAL_5:
1738                         switch (pseudo_header->atm.type) {
1739
1740                         case TRAF_LANE:
1741                                 /* LANE */
1742                                 atm_hdr.flags |= 0x01;
1743                                 break;
1744
1745                         case TRAF_LLCMX:
1746                                 /* RFC 1483 LLC multiplexed traffic */
1747                                 atm_hdr.flags |= 0x02;
1748                                 break;
1749
1750                         case TRAF_ILMI:
1751                                 /* ILMI */
1752                                 atm_hdr.flags |= 0x05;
1753                                 break;
1754                         }
1755                         break;
1756                 }
1757                 atm_hdr.vpi = pseudo_header->atm.vpi;
1758                 atm_hdr.vci = phtons(&pseudo_header->atm.vci);
1759                 nwritten = fwrite(&atm_hdr, 1, sizeof atm_hdr, wdh->fh);
1760                 if (nwritten != sizeof atm_hdr) {
1761                         if (nwritten == 0 && ferror(wdh->fh))
1762                                 *err = errno;
1763                         else
1764                                 *err = WTAP_ERR_SHORT_WRITE;
1765                         return FALSE;
1766                 }
1767                 wdh->bytes_dumped += sizeof atm_hdr;
1768         }
1769         else if (wdh->encap == WTAP_ENCAP_IRDA) {
1770                 /*
1771                  * Write the IrDA header.
1772                  */
1773                 memset(&irda_hdr, 0, sizeof(irda_hdr));
1774                 irda_hdr.sll_pkttype  = phtons(&pseudo_header->irda.pkttype);
1775                 irda_hdr.sll_protocol = htons(0x0017);
1776                 nwritten = fwrite(&irda_hdr, 1, sizeof(irda_hdr), wdh->fh);
1777                 if (nwritten != sizeof(irda_hdr)) {
1778                         if (nwritten == 0 && ferror(wdh->fh))
1779                                 *err = errno;
1780                         else
1781                                 *err = WTAP_ERR_SHORT_WRITE;
1782                         return FALSE;
1783                 }
1784                 wdh->bytes_dumped += sizeof(irda_hdr);
1785         }
1786
1787         nwritten = fwrite(pd, 1, phdr->caplen, wdh->fh);
1788         if (nwritten != phdr->caplen) {
1789                 if (nwritten == 0 && ferror(wdh->fh))
1790                         *err = errno;
1791                 else
1792                         *err = WTAP_ERR_SHORT_WRITE;
1793                 return FALSE;
1794         }
1795         wdh->bytes_dumped += phdr->caplen;
1796         return TRUE;
1797 }