When writing an option in an IDB, also write an endofoption option.
[obnox/wireshark/wip.git] / wiretap / libpcap.c
1 /* libpcap.c
2  *
3  * $Id$
4  *
5  * Wiretap Library
6  * Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.h>
30 #include "wtap-int.h"
31 #include "file_wrappers.h"
32 #include "buffer.h"
33 #include "pcap-common.h"
34 #include "pcap-encap.h"
35 #include "libpcap.h"
36
37 /* See source to the "libpcap" library for information on the "libpcap"
38    file format. */
39
40 /*
41  * Private per-wtap_t data needed to read a file.
42  */
43 typedef enum {
44         NOT_SWAPPED,
45         SWAPPED,
46         MAYBE_SWAPPED
47 } swapped_type_t;
48
49 typedef struct {
50         gboolean byte_swapped;
51         swapped_type_t lengths_swapped;
52         guint16 version_major;
53         guint16 version_minor;
54 } libpcap_t;
55
56 /* On some systems, the FDDI MAC addresses are bit-swapped. */
57 #if !defined(ultrix) && !defined(__alpha) && !defined(__bsdi__)
58 #define BIT_SWAPPED_MAC_ADDRS
59 #endif
60
61 /* Try to read the first two records of the capture file. */
62 typedef enum {
63         THIS_FORMAT,            /* the reads succeeded, assume it's this format */
64         BAD_READ,               /* the file is probably not valid */
65         OTHER_FORMAT            /* the file may be valid, but not in this format */
66 } libpcap_try_t;
67 static libpcap_try_t libpcap_try(wtap *wth, int *err);
68
69 static gboolean libpcap_read(wtap *wth, int *err, gchar **err_info,
70     gint64 *data_offset);
71 static gboolean libpcap_seek_read(wtap *wth, gint64 seek_off,
72     union wtap_pseudo_header *pseudo_header, guint8 *pd, int length,
73     int *err, gchar **err_info);
74 static int libpcap_read_header(wtap *wth, int *err, gchar **err_info,
75     struct pcaprec_ss990915_hdr *hdr);
76 static void adjust_header(wtap *wth, struct pcaprec_hdr *hdr);
77 static gboolean libpcap_read_rec_data(FILE_T fh, guint8 *pd, int length,
78     int *err, gchar **err_info);
79 static gboolean libpcap_dump(wtap_dumper *wdh, const struct wtap_pkthdr *phdr,
80     const union wtap_pseudo_header *pseudo_header, const guint8 *pd, int *err);
81
82 int libpcap_open(wtap *wth, int *err, gchar **err_info)
83 {
84         int bytes_read;
85         guint32 magic;
86         struct pcap_hdr hdr;
87         gboolean byte_swapped;
88         gboolean modified;
89         gboolean aix;
90         int file_encap;
91         libpcap_t *libpcap;
92
93         /* Read in the number that should be at the start of a "libpcap" file */
94         errno = WTAP_ERR_CANT_READ;
95         bytes_read = file_read(&magic, sizeof magic, wth->fh);
96         if (bytes_read != sizeof magic) {
97                 *err = file_error(wth->fh, err_info);
98                 if (*err != 0)
99                         return -1;
100                 return 0;
101         }
102         wth->data_offset += sizeof magic;
103
104         switch (magic) {
105
106         case PCAP_MAGIC:
107                 /* Host that wrote it has our byte order, and was running
108                    a program using either standard or ss990417 libpcap. */
109                 byte_swapped = FALSE;
110                 modified = FALSE;
111                 wth->tsprecision = WTAP_FILE_TSPREC_USEC;
112                 break;
113
114         case PCAP_MODIFIED_MAGIC:
115                 /* Host that wrote it has our byte order, and was running
116                    a program using either ss990915 or ss991029 libpcap. */
117                 byte_swapped = FALSE;
118                 modified = TRUE;
119                 wth->tsprecision = WTAP_FILE_TSPREC_USEC;
120                 break;
121
122         case PCAP_SWAPPED_MAGIC:
123                 /* Host that wrote it has a byte order opposite to ours,
124                    and was running a program using either standard or
125                    ss990417 libpcap. */
126                 byte_swapped = TRUE;
127                 modified = FALSE;
128                 wth->tsprecision = WTAP_FILE_TSPREC_USEC;
129                 break;
130
131         case PCAP_SWAPPED_MODIFIED_MAGIC:
132                 /* Host that wrote it out has a byte order opposite to
133                    ours, and was running a program using either ss990915
134                    or ss991029 libpcap. */
135                 byte_swapped = TRUE;
136                 modified = TRUE;
137                 wth->tsprecision = WTAP_FILE_TSPREC_USEC;
138                 break;
139
140         case PCAP_NSEC_MAGIC:
141                 /* Host that wrote it has our byte order, and was writing
142                    the file in a format similar to standard libpcap
143                    except that the time stamps have nanosecond resolution. */
144                 byte_swapped = FALSE;
145                 modified = FALSE;
146                 wth->tsprecision = WTAP_FILE_TSPREC_NSEC;
147                 break;
148
149         case PCAP_SWAPPED_NSEC_MAGIC:
150                 /* Host that wrote it out has a byte order opposite to
151                    ours, and was writing the file in a format similar to
152                    standard libpcap except that the time stamps have
153                    nanosecond resolution. */
154                 byte_swapped = TRUE;
155                 modified = FALSE;
156                 wth->tsprecision = WTAP_FILE_TSPREC_NSEC;
157                 break;
158
159         default:
160                 /* Not a "libpcap" type we know about. */
161                 return 0;
162         }
163
164         /* Read the rest of the header. */
165         errno = WTAP_ERR_CANT_READ;
166         bytes_read = file_read(&hdr, sizeof hdr, wth->fh);
167         if (bytes_read != sizeof hdr) {
168                 *err = file_error(wth->fh, err_info);
169                 if (*err != 0)
170                         return -1;
171                 return 0;
172         }
173         wth->data_offset += sizeof hdr;
174
175         if (byte_swapped) {
176                 /* Byte-swap the header fields about which we care. */
177                 hdr.version_major = BSWAP16(hdr.version_major);
178                 hdr.version_minor = BSWAP16(hdr.version_minor);
179                 hdr.snaplen = BSWAP32(hdr.snaplen);
180                 hdr.network = BSWAP32(hdr.network);
181         }
182         if (hdr.version_major < 2) {
183                 /* We only support version 2.0 and later. */
184                 *err = WTAP_ERR_UNSUPPORTED;
185                 *err_info = g_strdup_printf("pcap: major version %u unsupported",
186                     hdr.version_major);
187                 return -1;
188         }
189
190         /*
191          * AIX's non-standard tcpdump uses a minor version number of 2.
192          * Unfortunately, older versions of libpcap might have used
193          * that as well.
194          *
195          * The AIX libpcap uses RFC 1573 ifType values rather than
196          * DLT_ values in the header; the ifType values for LAN devices
197          * are:
198          *
199          *      Ethernet        6
200          *      Token Ring      9
201          *      FDDI            15
202          *
203          * which correspond to DLT_IEEE802 (used for Token Ring),
204          * DLT_PPP, and DLT_SLIP_BSDOS, respectively.  The ifType value
205          * for a loopback interface is 24, which currently isn't
206          * used by any version of libpcap I know about (and, as
207          * tcpdump.org are assigning DLT_ values above 100, and
208          * NetBSD started assigning values starting at 50, and
209          * the values chosen by other libpcaps appear to stop at
210          * 19, it's probably not going to be used by any libpcap
211          * in the future).
212          *
213          * We shall assume that if the minor version number is 2, and
214          * the network type is 6, 9, 15, or 24, that it's AIX libpcap.
215          *
216          * I'm assuming those older versions of libpcap didn't
217          * use DLT_IEEE802 for Token Ring, and didn't use DLT_SLIP_BSDOS
218          * as that came later.  It may have used DLT_PPP, however, in
219          * which case we're out of luck; we assume it's Token Ring
220          * in AIX libpcap rather than PPP in standard libpcap, as
221          * you're probably more likely to be handing an AIX libpcap
222          * token-ring capture than an old (pre-libpcap 0.4) PPP capture
223          * to Wireshark.
224          */
225         aix = FALSE;    /* assume it's not AIX */
226         if (hdr.version_major == 2 && hdr.version_minor == 2) {
227                 switch (hdr.network) {
228
229                 case 6:
230                         hdr.network = 1;        /* DLT_EN10MB, Ethernet */
231                         aix = TRUE;
232                         break;
233
234                 case 9:
235                         hdr.network = 6;        /* DLT_IEEE802, Token Ring */
236                         aix = TRUE;
237                         break;
238
239                 case 15:
240                         hdr.network = 10;       /* DLT_FDDI, FDDI */
241                         aix = TRUE;
242                         break;
243
244                 case 24:
245                         hdr.network = 0;        /* DLT_NULL, loopback */
246                         aix = TRUE;
247                         break;
248                 }
249         }
250
251         file_encap = wtap_pcap_encap_to_wtap_encap(hdr.network);
252         if (file_encap == WTAP_ENCAP_UNKNOWN) {
253                 *err = WTAP_ERR_UNSUPPORTED_ENCAP;
254                 *err_info = g_strdup_printf("pcap: network type %u unknown or unsupported",
255                     hdr.network);
256                 return -1;
257         }
258
259         /* This is a libpcap file */
260         libpcap = (libpcap_t *)g_malloc(sizeof(libpcap_t));;
261         libpcap->byte_swapped = byte_swapped;
262         libpcap->version_major = hdr.version_major;
263         libpcap->version_minor = hdr.version_minor;
264         wth->priv = (void *)libpcap;
265         wth->subtype_read = libpcap_read;
266         wth->subtype_seek_read = libpcap_seek_read;
267         wth->file_encap = file_encap;
268         wth->snapshot_length = hdr.snaplen;
269
270         /* In file format version 2.3, the order of the "incl_len" and
271            "orig_len" fields in the per-packet header was reversed,
272            in order to match the BPF header layout.
273
274            Therefore, in files with versions prior to that, we must swap
275            those two fields.
276
277            Unfortunately, some files were, according to a comment in the
278            "libpcap" source, written with version 2.3 in their headers
279            but without the interchanged fields, so if "incl_len" is
280            greater than "orig_len" - which would make no sense - we
281            assume that we need to swap them in version 2.3 files
282            as well.
283
284            In addition, DG/UX's tcpdump uses version 543.0, and writes
285            the two fields in the pre-2.3 order. */
286         switch (hdr.version_major) {
287
288         case 2:
289                 if (hdr.version_minor < 3)
290                         libpcap->lengths_swapped = SWAPPED;
291                 else if (hdr.version_minor == 3)
292                         libpcap->lengths_swapped = MAYBE_SWAPPED;
293                 else
294                         libpcap->lengths_swapped = NOT_SWAPPED;
295                 break;
296
297         case 543:
298                 libpcap->lengths_swapped = SWAPPED;
299                 break;
300
301         default:
302                 libpcap->lengths_swapped = NOT_SWAPPED;
303                 break;
304         }
305
306         /*
307          * Is this AIX format?
308          */
309         if (aix) {
310                 /*
311                  * Yes.  Skip all the tests for other mutant formats,
312                  * and set the precision to nanosecond precision.
313                  */
314                 wth->file_type = WTAP_FILE_PCAP_AIX;
315                 wth->tsprecision = WTAP_FILE_TSPREC_NSEC;
316                 return 1;
317         }
318
319         /*
320          * No.  Let's look at the header for the first record,
321          * and see if, interpreting it as a standard header (if the
322          * magic number was standard) or a modified header (if the
323          * magic number was modified), the position where it says the
324          * header for the *second* record is contains a corrupted header.
325          *
326          * If so, then:
327          *
328          *      If this file had the standard magic number, it may be
329          *      an ss990417 capture file - in that version of Alexey's
330          *      patch, the packet header format was changed but the
331          *      magic number wasn't, and, alas, Red Hat appear to have
332          *      picked up that version of the patch for RH 6.1, meaning
333          *      RH 6.1 has a tcpdump that writes out files that can't
334          *      be read by any software that expects non-modified headers
335          *      if the magic number isn't the modified magic number (e.g.,
336          *      any normal version of tcpdump, and Wireshark if we don't
337          *      do this gross heuristic).
338          *
339          *      If this file had the modified magic number, it may be
340          *      an ss990915 capture file - in that version of Alexey's
341          *      patch, the magic number was changed, but the record
342          *      header had some extra fields, and, alas, SuSE appear
343          *      to have picked up that version of the patch for SuSE
344          *      6.3, meaning that programs expecting the standard per-
345          *      packet header in captures with the modified magic number
346          *      can't read dumps from its tcpdump.
347          *
348          * Oh, and if it has the standard magic number, it might, instead,
349          * be a Nokia libpcap file, so we may need to try that if
350          * neither normal nor ss990417 headers work.
351          */
352         if (modified) {
353                 /*
354                  * Well, we have the magic number from Alexey's
355                  * later two patches.
356                  *
357                  * Try ss991029, the last of his patches, first.
358                  */
359                 wth->file_type = WTAP_FILE_PCAP_SS991029;
360                 switch (libpcap_try(wth, err)) {
361
362                 case BAD_READ:
363                         /*
364                          * Well, we couldn't even read it.
365                          * Give up.
366                          */
367                         g_free(wth->priv);
368                         return -1;
369
370                 case THIS_FORMAT:
371                         /*
372                          * Well, it looks as if it might be 991029.
373                          * Put the seek pointer back, and return success.
374                          */
375                         if (file_seek(wth->fh, wth->data_offset, SEEK_SET, err) == -1) {
376                                 g_free(wth->priv);
377                                 return -1;
378                         }
379                         return 1;
380
381                 case OTHER_FORMAT:
382                         /*
383                          * Try the next format.
384                          */
385                         break;
386                 }
387
388                 /*
389                  * Well, it's not completely unreadable,
390                  * but it's not ss991029.  Try ss990915;
391                  * there are no other types to try after that,
392                  * so we put the seek pointer back and treat
393                  * it as 990915.
394                  */
395                 wth->file_type = WTAP_FILE_PCAP_SS990915;
396                 if (file_seek(wth->fh, wth->data_offset, SEEK_SET, err) == -1) {
397                         g_free(wth->priv);
398                         return -1;
399                 }
400         } else {
401                 /*
402                  * Well, we have the standard magic number.
403                  *
404                  * Try the standard format first.
405                  */
406                 if(wth->tsprecision == WTAP_FILE_TSPREC_NSEC) {
407                         wth->file_type = WTAP_FILE_PCAP_NSEC;
408                 } else {
409                         wth->file_type = WTAP_FILE_PCAP;
410                 }
411                 switch (libpcap_try(wth, err)) {
412
413                 case BAD_READ:
414                         /*
415                          * Well, we couldn't even read it.
416                          * Give up.
417                          */
418                         g_free(wth->priv);
419                         return -1;
420
421                 case THIS_FORMAT:
422                         /*
423                          * Well, it looks as if it might be a standard
424                          * libpcap file.
425                          * Put the seek pointer back, and return success.
426                          */
427                         if (file_seek(wth->fh, wth->data_offset, SEEK_SET, err) == -1) {
428                                 g_free(wth->priv);
429                                 return -1;
430                         }
431                         return 1;
432
433                 case OTHER_FORMAT:
434                         /*
435                          * Try the next format.
436                          */
437                         break;
438                 }
439
440                 /*
441                  * Well, it's not completely unreadable, but it's not
442                  * a standard file.  Put the seek pointer back and try
443                  * ss990417.
444                  */
445                 wth->file_type = WTAP_FILE_PCAP_SS990417;
446                 if (file_seek(wth->fh, wth->data_offset, SEEK_SET, err) == -1) {
447                         g_free(wth->priv);
448                         return -1;
449                 }
450                 switch (libpcap_try(wth, err)) {
451
452                 case BAD_READ:
453                         /*
454                          * Well, we couldn't even read it.
455                          * Give up.
456                          */
457                         g_free(wth->priv);
458                         return -1;
459
460                 case THIS_FORMAT:
461                         /*
462                          * Well, it looks as if it might be ss990417.
463                          * Put the seek pointer back, and return success.
464                          */
465                         if (file_seek(wth->fh, wth->data_offset, SEEK_SET, err) == -1) {
466                                 g_free(wth->priv);
467                                 return -1;
468                         }
469                         return 1;
470
471                 case OTHER_FORMAT:
472                         /*
473                          * Try the next format.
474                          */
475                         break;
476                 }
477
478                 /*
479                  * Well, it's not completely unreadable,
480                  * but it's not a standard file *nor* is it ss990417.
481                  * Try it as a Nokia file; there are no other types
482                  * to try after that, so we put the seek pointer back
483                  * and treat it as a Nokia file.
484                  */
485                 wth->file_type = WTAP_FILE_PCAP_NOKIA;
486                 if (file_seek(wth->fh, wth->data_offset, SEEK_SET, err) == -1) {
487                         g_free(wth->priv);
488                         return -1;
489                 }
490         }
491
492         /*
493          * We treat a DLT_ value of 13 specially - it appears that in
494          * Nokia libpcap format, it's some form of ATM with what I
495          * suspect is a pseudo-header (even though Nokia's IPSO is
496          * based on FreeBSD, which #defines DLT_SLIP_BSDOS as 13).
497          *
498          * If this is a Nokia capture, treat 13 as WTAP_ENCAP_ATM_PDUS,
499          * rather than as what we normally treat it.
500          */
501         if (wth->file_type == WTAP_FILE_PCAP_NOKIA && hdr.network == 13)
502                 wth->file_encap = WTAP_ENCAP_ATM_PDUS;
503
504         return 1;
505 }
506
507 /* Try to read the first two records of the capture file. */
508 static libpcap_try_t libpcap_try(wtap *wth, int *err)
509 {
510         /*
511          * pcaprec_ss990915_hdr is the largest header type.
512          */
513         struct pcaprec_ss990915_hdr first_rec_hdr, second_rec_hdr;
514
515
516         /*
517          * Attempt to read the first record's header.
518          */
519         if (libpcap_read_header(wth, err, NULL, &first_rec_hdr) == -1) {
520                 if (*err == 0 || *err == WTAP_ERR_SHORT_READ) {
521                         /*
522                          * EOF or short read - assume the file is in this
523                          * format.
524                          * When our client tries to read the first packet
525                          * they will presumably get the same EOF or short
526                          * read.
527                          */
528                         return THIS_FORMAT;
529                 }
530
531                 if (*err == WTAP_ERR_BAD_FILE) {
532                         /*
533                          * The first record is bogus, so this is probably
534                          * a corrupt file.  Assume the file is in this
535                          * format.  When our client tries to read the
536                          * first packet they will presumably get the
537                          * same bogus record.
538                          */
539                         return THIS_FORMAT;
540                 }
541
542                 /*
543                  * Some other error, e.g. an I/O error; just give up.
544                  */
545                 return BAD_READ;
546         }
547
548         /*
549          * Now skip over the first record's data, under the assumption
550          * that the header is sane.
551          */
552         if (file_seek(wth->fh, first_rec_hdr.hdr.incl_len, SEEK_CUR, err) == -1)
553                 return BAD_READ;
554
555         /*
556          * Now attempt to read the second record's header.
557          */
558         if (libpcap_read_header(wth, err, NULL, &second_rec_hdr) == -1) {
559                 if (*err == 0 || *err == WTAP_ERR_SHORT_READ) {
560                         /*
561                          * EOF or short read - assume the file is in this
562                          * format.
563                          * When our client tries to read the second packet
564                          * they will presumably get the same EOF or short
565                          * read.
566                          */
567                         return THIS_FORMAT;
568                 }
569
570                 if (*err == WTAP_ERR_BAD_FILE) {
571                         /*
572                          * The second record is bogus; maybe it's a
573                          * Capture File From Hell, and what looks like
574                          * the "header" of the next packet is actually
575                          * random junk from the middle of a packet.
576                          * Try the next format; if we run out of formats,
577                          * it probably *is* a corrupt file.
578                          */
579                         return OTHER_FORMAT;
580                 }
581
582                 /*
583                  * Some other error, e.g. an I/O error; just give up.
584                  */
585                 return BAD_READ;
586         }
587
588         /*
589          * OK, the first two records look OK; assume this is the
590          * right format.
591          */
592         return THIS_FORMAT;
593 }
594
595 /* Read the next packet */
596 static gboolean libpcap_read(wtap *wth, int *err, gchar **err_info,
597     gint64 *data_offset)
598 {
599         struct pcaprec_ss990915_hdr hdr;
600         guint packet_size;
601         guint orig_size;
602         int bytes_read;
603         guint8 fddi_padding[3];
604         int phdr_len;
605         libpcap_t *libpcap;
606
607         bytes_read = libpcap_read_header(wth, err, err_info, &hdr);
608         if (bytes_read == -1) {
609                 /*
610                  * We failed to read the header.
611                  */
612                 return FALSE;
613         }
614
615         wth->data_offset += bytes_read;
616         packet_size = hdr.hdr.incl_len;
617         orig_size = hdr.hdr.orig_len;
618
619         /*
620          * AIX appears to put 3 bytes of padding in front of FDDI
621          * frames; strip that crap off.
622          */
623         if (wth->file_type == WTAP_FILE_PCAP_AIX &&
624             (wth->file_encap == WTAP_ENCAP_FDDI ||
625              wth->file_encap == WTAP_ENCAP_FDDI_BITSWAPPED)) {
626                 /*
627                  * The packet size is really a record size and includes
628                  * the padding.
629                  */
630                 packet_size -= 3;
631                 orig_size -= 3;
632                 wth->data_offset += 3;
633
634                 /*
635                  * Read the padding.
636                  */
637                 if (!libpcap_read_rec_data(wth->fh, fddi_padding, 3, err,
638                     err_info))
639                         return FALSE;   /* Read error */
640         }
641
642         *data_offset = wth->data_offset;
643
644         libpcap = (libpcap_t *)wth->priv;
645         phdr_len = pcap_process_pseudo_header(wth->fh, wth->file_type,
646             wth->file_encap, packet_size, TRUE, &wth->phdr,
647             &wth->pseudo_header, err, err_info);
648         if (phdr_len < 0)
649                 return FALSE;   /* error */
650
651         /*
652          * Don't count any pseudo-header as part of the packet.
653          */
654         orig_size -= phdr_len;
655         packet_size -= phdr_len;
656         wth->data_offset += phdr_len;
657
658         buffer_assure_space(wth->frame_buffer, packet_size);
659         if (!libpcap_read_rec_data(wth->fh, buffer_start_ptr(wth->frame_buffer),
660             packet_size, err, err_info))
661                 return FALSE;   /* Read error */
662         wth->data_offset += packet_size;
663
664         /* Update the Timestamp, if not already done */
665         if (wth->file_encap != WTAP_ENCAP_ERF) {
666           wth->phdr.ts.secs = hdr.hdr.ts_sec;
667           if(wth->tsprecision == WTAP_FILE_TSPREC_NSEC) {
668             wth->phdr.ts.nsecs = hdr.hdr.ts_usec;
669           } else {
670             wth->phdr.ts.nsecs = hdr.hdr.ts_usec * 1000;
671           }
672         }
673         wth->phdr.caplen = packet_size;
674         wth->phdr.len = orig_size;
675
676         pcap_read_post_process(wth->file_type, wth->file_encap,
677             &wth->pseudo_header, buffer_start_ptr(wth->frame_buffer),
678             wth->phdr.caplen, libpcap->byte_swapped, -1);
679         return TRUE;
680 }
681
682 static gboolean
683 libpcap_seek_read(wtap *wth, gint64 seek_off,
684     union wtap_pseudo_header *pseudo_header, guint8 *pd, int length,
685     int *err, gchar **err_info)
686 {
687         int phdr_len;
688         libpcap_t *libpcap;
689
690         if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
691                 return FALSE;
692
693         libpcap = (libpcap_t *)wth->priv;
694         phdr_len = pcap_process_pseudo_header(wth->random_fh, wth->file_type,
695             wth->file_encap, length, FALSE, NULL, pseudo_header, err, err_info);
696         if (phdr_len < 0)
697                 return FALSE;   /* error */
698
699         /*
700          * Read the packet data.
701          */
702         if (!libpcap_read_rec_data(wth->random_fh, pd, length, err, err_info))
703                 return FALSE;   /* failed */
704
705         pcap_read_post_process(wth->file_type, wth->file_encap,
706             pseudo_header, pd, length, libpcap->byte_swapped, -1);
707         return TRUE;
708 }
709
710 /* Read the header of the next packet.
711
712    Return -1 on an error, or the number of bytes of header read on success. */
713 static int libpcap_read_header(wtap *wth, int *err, gchar **err_info,
714     struct pcaprec_ss990915_hdr *hdr)
715 {
716         int     bytes_to_read, bytes_read;
717
718         /* Read record header. */
719         errno = WTAP_ERR_CANT_READ;
720         switch (wth->file_type) {
721
722         case WTAP_FILE_PCAP:
723         case WTAP_FILE_PCAP_AIX:
724         case WTAP_FILE_PCAP_NSEC:
725                 bytes_to_read = sizeof (struct pcaprec_hdr);
726                 break;
727
728         case WTAP_FILE_PCAP_SS990417:
729         case WTAP_FILE_PCAP_SS991029:
730                 bytes_to_read = sizeof (struct pcaprec_modified_hdr);
731                 break;
732
733         case WTAP_FILE_PCAP_SS990915:
734                 bytes_to_read = sizeof (struct pcaprec_ss990915_hdr);
735                 break;
736
737         case WTAP_FILE_PCAP_NOKIA:
738                 bytes_to_read = sizeof (struct pcaprec_nokia_hdr);
739                 break;
740
741         default:
742                 g_assert_not_reached();
743                 bytes_to_read = 0;
744         }
745         bytes_read = file_read(hdr, bytes_to_read, wth->fh);
746         if (bytes_read != bytes_to_read) {
747                 *err = file_error(wth->fh, err_info);
748                 if (*err == 0 && bytes_read != 0) {
749                         *err = WTAP_ERR_SHORT_READ;
750                 }
751                 return -1;
752         }
753
754         adjust_header(wth, &hdr->hdr);
755
756         if (hdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
757                 /*
758                  * Probably a corrupt capture file; return an error,
759                  * so that our caller doesn't blow up trying to allocate
760                  * space for an immensely-large packet, and so that
761                  * the code to try to guess what type of libpcap file
762                  * this is can tell when it's not the type we're guessing
763                  * it is.
764                  */
765                 *err = WTAP_ERR_BAD_FILE;
766                 if (err_info != NULL) {
767                         *err_info = g_strdup_printf("pcap: File has %u-byte packet, bigger than maximum of %u",
768                             hdr->hdr.incl_len, WTAP_MAX_PACKET_SIZE);
769                 }
770                 return -1;
771         }
772
773         if (hdr->hdr.orig_len > WTAP_MAX_PACKET_SIZE) {
774                 /*
775                  * Probably a corrupt capture file; return an error,
776                  * so that our caller doesn't blow up trying to
777                  * cope with a huge "real" packet length, and so that
778                  * the code to try to guess what type of libpcap file
779                  * this is can tell when it's not the type we're guessing
780                  * it is.
781                  */
782                 *err = WTAP_ERR_BAD_FILE;
783                 if (err_info != NULL) {
784                         *err_info = g_strdup_printf("pcap: File has %u-byte packet, bigger than maximum of %u",
785                             hdr->hdr.orig_len, WTAP_MAX_PACKET_SIZE);
786                 }
787                 return -1;
788         }
789
790         return bytes_read;
791 }
792
793 static void
794 adjust_header(wtap *wth, struct pcaprec_hdr *hdr)
795 {
796         guint32 temp;
797         libpcap_t *libpcap;
798
799         libpcap = (libpcap_t *)wth->priv;
800         if (libpcap->byte_swapped) {
801                 /* Byte-swap the record header fields. */
802                 hdr->ts_sec = BSWAP32(hdr->ts_sec);
803                 hdr->ts_usec = BSWAP32(hdr->ts_usec);
804                 hdr->incl_len = BSWAP32(hdr->incl_len);
805                 hdr->orig_len = BSWAP32(hdr->orig_len);
806         }
807
808         /* Swap the "incl_len" and "orig_len" fields, if necessary. */
809         switch (libpcap->lengths_swapped) {
810
811         case NOT_SWAPPED:
812                 break;
813
814         case MAYBE_SWAPPED:
815                 if (hdr->incl_len <= hdr->orig_len) {
816                         /*
817                          * The captured length is <= the actual length,
818                          * so presumably they weren't swapped.
819                          */
820                         break;
821                 }
822                 /* FALLTHROUGH */
823
824         case SWAPPED:
825                 temp = hdr->orig_len;
826                 hdr->orig_len = hdr->incl_len;
827                 hdr->incl_len = temp;
828                 break;
829         }
830 }
831
832 static gboolean
833 libpcap_read_rec_data(FILE_T fh, guint8 *pd, int length, int *err,
834     gchar **err_info)
835 {
836         int     bytes_read;
837
838         errno = WTAP_ERR_CANT_READ;
839         bytes_read = file_read(pd, length, fh);
840
841         if (bytes_read != length) {
842                 *err = file_error(fh, err_info);
843                 if (*err == 0)
844                         *err = WTAP_ERR_SHORT_READ;
845                 return FALSE;
846         }
847         return TRUE;
848 }
849
850 /* Returns 0 if we could write the specified encapsulation type,
851    an error indication otherwise. */
852 int libpcap_dump_can_write_encap(int encap)
853 {
854         /* Per-packet encapsulations aren't supported. */
855         if (encap == WTAP_ENCAP_PER_PACKET)
856                 return WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
857
858         if (wtap_wtap_encap_to_pcap_encap(encap) == -1)
859                 return WTAP_ERR_UNSUPPORTED_ENCAP;
860
861         return 0;
862 }
863
864 /* Returns TRUE on success, FALSE on failure; sets "*err" to an error code on
865    failure */
866 gboolean libpcap_dump_open(wtap_dumper *wdh, int *err)
867 {
868         guint32 magic;
869         struct pcap_hdr file_hdr;
870
871         /* This is a libpcap file */
872         wdh->subtype_write = libpcap_dump;
873         wdh->subtype_close = NULL;
874
875         /* Write the file header. */
876         switch (wdh->file_type) {
877
878         case WTAP_FILE_PCAP:
879         case WTAP_FILE_PCAP_SS990417:   /* modified, but with the old magic, sigh */
880         case WTAP_FILE_PCAP_NOKIA:      /* Nokia libpcap of some sort */
881                 magic = PCAP_MAGIC;
882                 wdh->tsprecision = WTAP_FILE_TSPREC_USEC;
883                 break;
884
885         case WTAP_FILE_PCAP_SS990915:   /* new magic, extra crap */
886         case WTAP_FILE_PCAP_SS991029:
887                 magic = PCAP_MODIFIED_MAGIC;
888                 wdh->tsprecision = WTAP_FILE_TSPREC_USEC;
889                 break;
890
891         case WTAP_FILE_PCAP_NSEC:               /* same as WTAP_FILE_PCAP, but nsec precision */
892                 magic = PCAP_NSEC_MAGIC;
893                 wdh->tsprecision = WTAP_FILE_TSPREC_NSEC;
894                 break;
895
896         default:
897                 /* We should never get here - our open routine
898                    should only get called for the types above. */
899                 *err = WTAP_ERR_UNSUPPORTED_FILE_TYPE;
900                 return FALSE;
901         }
902
903         if (!wtap_dump_file_write(wdh, &magic, sizeof magic, err))
904                 return FALSE;
905         wdh->bytes_dumped += sizeof magic;
906
907         /* current "libpcap" format is 2.4 */
908         file_hdr.version_major = 2;
909         file_hdr.version_minor = 4;
910         file_hdr.thiszone = 0;  /* XXX - current offset? */
911         file_hdr.sigfigs = 0;   /* unknown, but also apparently unused */
912         /*
913          * Tcpdump cannot handle capture files with a snapshot length of 0,
914          * as BPF filters return either 0 if they fail or the snapshot length
915          * if they succeed, and a snapshot length of 0 means success is
916          * indistinguishable from failure and the filter expression would
917          * reject all packets.
918          *
919          * A snapshot length of 0, inside Wiretap, means "snapshot length
920          * unknown"; if the snapshot length supplied to us is 0, we make
921          * the snapshot length in the header file WTAP_MAX_PACKET_SIZE.
922          */
923         file_hdr.snaplen = (wdh->snaplen != 0) ? wdh->snaplen :
924                                                  WTAP_MAX_PACKET_SIZE;
925         file_hdr.network = wtap_wtap_encap_to_pcap_encap(wdh->encap);
926         if (!wtap_dump_file_write(wdh, &file_hdr, sizeof file_hdr, err))
927                 return FALSE;
928         wdh->bytes_dumped += sizeof file_hdr;
929
930         return TRUE;
931 }
932
933 /* Write a record for a packet to a dump file.
934    Returns TRUE on success, FALSE on failure. */
935 static gboolean libpcap_dump(wtap_dumper *wdh,
936         const struct wtap_pkthdr *phdr,
937         const union wtap_pseudo_header *pseudo_header,
938         const guint8 *pd, int *err)
939 {
940         struct pcaprec_ss990915_hdr rec_hdr;
941         size_t hdr_size;
942         int phdrsize;
943
944         phdrsize = pcap_get_phdr_size(wdh->encap, pseudo_header);
945
946         rec_hdr.hdr.ts_sec = (guint32) phdr->ts.secs;
947         if(wdh->tsprecision == WTAP_FILE_TSPREC_NSEC) {
948                 rec_hdr.hdr.ts_usec = phdr->ts.nsecs;
949         } else {
950                 rec_hdr.hdr.ts_usec = phdr->ts.nsecs / 1000;
951         }
952         rec_hdr.hdr.incl_len = phdr->caplen + phdrsize;
953         rec_hdr.hdr.orig_len = phdr->len + phdrsize;
954
955         if (rec_hdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE || rec_hdr.hdr.orig_len > WTAP_MAX_PACKET_SIZE) {
956                 *err = WTAP_ERR_BAD_FILE;
957                 return FALSE;
958         }
959
960         switch (wdh->file_type) {
961
962         case WTAP_FILE_PCAP:
963         case WTAP_FILE_PCAP_NSEC:
964                 hdr_size = sizeof (struct pcaprec_hdr);
965                 break;
966
967         case WTAP_FILE_PCAP_SS990417:   /* modified, but with the old magic, sigh */
968         case WTAP_FILE_PCAP_SS991029:
969                 /* XXX - what should we supply here?
970
971                    Alexey's "libpcap" looks up the interface in the system's
972                    interface list if "ifindex" is non-zero, and prints
973                    the interface name.  It ignores "protocol", and uses
974                    "pkt_type" to tag the packet as "host", "broadcast",
975                    "multicast", "other host", "outgoing", or "none of the
976                    above", but that's it.
977
978                    If the capture we're writing isn't a modified or
979                    RH 6.1 capture, we'd have to do some work to
980                    generate the packet type and interface index - and
981                    we can't generate the interface index unless we
982                    just did the capture ourselves in any case.
983
984                    I'm inclined to continue to punt; systems other than
985                    those with the older patch can read standard "libpcap"
986                    files, and systems with the older patch, e.g. RH 6.1,
987                    will just have to live with this. */
988                 rec_hdr.ifindex = 0;
989                 rec_hdr.protocol = 0;
990                 rec_hdr.pkt_type = 0;
991                 hdr_size = sizeof (struct pcaprec_modified_hdr);
992                 break;
993
994         case WTAP_FILE_PCAP_SS990915:   /* new magic, extra crap at the end */
995                 rec_hdr.ifindex = 0;
996                 rec_hdr.protocol = 0;
997                 rec_hdr.pkt_type = 0;
998                 rec_hdr.cpu1 = 0;
999                 rec_hdr.cpu2 = 0;
1000                 hdr_size = sizeof (struct pcaprec_ss990915_hdr);
1001                 break;
1002
1003         case WTAP_FILE_PCAP_NOKIA:      /* old 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_nokia_hdr);
1010                 break;
1011
1012         default:
1013                 /* We should never get here - our open routine
1014                    should only get called for the types above. */
1015                 g_assert_not_reached();
1016                 *err = WTAP_ERR_UNSUPPORTED_FILE_TYPE;
1017                 return FALSE;
1018         }
1019
1020         if (!wtap_dump_file_write(wdh, &rec_hdr, hdr_size, err))
1021                 return FALSE;
1022         wdh->bytes_dumped += hdr_size;
1023
1024         if (!pcap_write_phdr(wdh, wdh->encap, pseudo_header, err))
1025                 return FALSE;
1026
1027         if (!wtap_dump_file_write(wdh, pd, phdr->caplen, err))
1028                 return FALSE;
1029         wdh->bytes_dumped += phdr->caplen;
1030         return TRUE;
1031 }