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