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