Rename buffer_ routines to ws_buffer_ to avoid name collisions.
[metze/wireshark/wip.git] / wiretap / visual.c
1 /* visual.c
2  * File read and write routines for Visual Networks cap files.
3  * Copyright (c) 2001, Tom Nisbet  tnisbet@visualnetworks.com
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include "config.h"
24 #include <errno.h>
25 #include <string.h>
26 #include "wtap-int.h"
27 #include "file_wrappers.h"
28 #include <wsutil/buffer.h>
29 #include "visual.h"
30
31 /*
32  * A Visual Networks traffic capture file contains three sections. The
33  * first is a 192 octet file header.  This is followed by the captured
34  * packet header, and for ATM captures, there is an additional atm packet header.
35  * The data follows the packet header. The last section is the packet index block.
36  * The index block contains one 4 octet pointer for each captured packet.
37  * The first packet index is (4 * num_pkts) octets from the end of the file
38  * and the last index is in the last four octets of the file.
39  *
40  * All integer and time values are stored in little-endian format, except for
41  *  the ATM Packet Header, which is stored in network byte order.
42  *
43  * [ File Header ]
44  *
45  *
46  * [ Packet Header 1 ] [(opt) ATM Packet Header] [ Data ]
47  * ...
48  * [ Packet Header n ] [(opt) ATM Packet Header] [ Data ]
49  *
50  *
51  * [ Index Block 1 ] ... [ Index Block n ]
52  */
53
54 /* Capture file header, INCLUDING the magic number, is 192 bytes. */
55 #define CAPTUREFILE_HEADER_SIZE 192
56
57 /* Magic number for Visual Networks traffic capture files. */
58 static const char visual_magic[] = {
59     5, 'V', 'N', 'F'
60 };
61
62
63 /* Visual File Header (minus magic number). */
64 /* This structure is used to extract information */
65 struct visual_file_hdr
66 {
67     guint32 num_pkts;           /* Number of packets in the file */
68     guint32 start_time;         /* Capture start time in PC format */
69     guint16 media_type;         /* IANA ifType of packet source */
70     guint16 max_length;         /* Max allowable stored packet length */
71     guint16 file_flags;         /* File type flags */
72                                 /*   Bit 0 indicates indexes present */
73     guint16 file_version;       /* Version number of this file format */
74     guint32 media_speed;        /* ifSpeed of packet source in bits/sec. */
75     guint16 media_param;        /* Media-specific extra parameter. */
76     char    RESERVED_[102];     /* MUST BE ALL ZEROS FOR FUTURE COMPATABILITY */
77     char    description[64];    /* File description (null terminated) */
78 };
79
80
81 /* Packet status bits */
82 #define PS_LONG             0x01
83 #define PS_SHORT            0x02
84 #define PS_ERRORED          0x04
85 #define PS_1ST_AFTER_DROP   0x08
86 #define PS_APPROX_ORDER     0x10
87 #define PS_SENT             0x40
88 #define PS_ABORTED          0x80
89
90 /* Visual Packet Header */
91 /* This structure is used to extract information */
92 struct visual_pkt_hdr
93 {
94     guint32 ts_delta;           /* Time stamp - msecs since start of capture */
95     guint16 orig_len;           /* Actual length of packet */
96     guint16 incl_len;           /* Number of octets captured in file */
97     guint32 status;             /* Packet status flags (media specific) */
98     guint8  encap_hint;         /* Encapsulation type hint */
99     guint8  encap_skip;         /* Number of bytes to skip before decoding */
100     char    RESERVED_[6];       /* RESERVED - must be zero */
101 };
102
103 /* Optional Visual ATM Packet Header */
104 /* This structure is used to extract information */
105 struct visual_atm_hdr
106 {
107    guint16 vpi;           /* 4 bits of zeros; 12 bits of ATM VPI */
108    guint16 vci;           /* ATM VCI */
109    guint8  info;          /* 4 bits version; 3 bits unused-zero; 1 bit direction */
110    guint8  category;      /* indicates type of traffic. 4 bits of status + 4 bits of type */
111    guint16 cell_count;    /* number of cells that make up this pdu */
112    guint32 data_length;   /* PDU data length for AAL-5 PDUs, all others - cellcount * 48 */
113    guint32 ts_secs;       /* seonds value of sysUpTime when the last cell of this PDU was captured */
114    guint32 ts_nsec;       /* nanoseonds value of sysUpTime when the last cell of this PDU was captured */
115
116 };
117
118 /* visual_atm_hdr info bit definitions */
119 #define FROM_NETWORK       0x01
120 #define ATM_VER_MASK       0xf0  /* Not currently displayed */
121
122 /* visual_atm_hdr category definitions */
123 /* High nibble - not currently displayed */
124 #define VN_INCOMPLETE      0x40
125 #define VN_BAD_CRC         0x80
126 #define VN_CAT_STAT_MASK   0xf0
127 /* Low nibble */
128 #define VN_UNKNOWN         0x00
129 #define VN_AAL1            0x01
130 #define VN_AAL2            0x02
131 #define VN_AAL34           0x03
132 #define VN_O191            0x04
133 #define VN_AAL5            0x05
134 #define VN_OAM             0x0a
135 #define VN_RM              0x0b
136 #define VN_IDLE            0x0c
137 #define VN_CAT_TYPE_MASK   0x0f
138
139
140 /* Additional information for reading Visual files */
141 struct visual_read_info
142 {
143     guint32 num_pkts;           /* Number of pkts in the file */
144     guint32 current_pkt;        /* Next packet to be read */
145     double  start_time;         /* Capture start time in microseconds */
146 };
147
148
149 /* Additional information for writing Visual files */
150 struct visual_write_info
151 {
152     guint start_time;        /* Capture start time in seconds */
153     int     index_table_index;  /* Index of the next index entry */
154     int     index_table_size;   /* Allocated size of the index table */
155     guint32 * index_table;      /* File offsets for the packets */
156     guint32 next_offset;        /* Offset of next packet */
157 };
158
159
160 /* Local functions to handle file reads and writes */
161 static gboolean visual_read(wtap *wth, int *err, gchar **err_info,
162     gint64 *data_offset);
163 static gboolean visual_seek_read(wtap *wth, gint64 seek_off,
164     struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info);
165 static gboolean visual_read_packet(wtap *wth, FILE_T fh,
166     struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info);
167 static gboolean visual_dump(wtap_dumper *wdh, const struct wtap_pkthdr *phdr,
168     const guint8 *pd, int *err);
169 static gboolean visual_dump_close(wtap_dumper *wdh, int *err);
170 static void visual_dump_free(wtap_dumper *wdh);
171
172
173 /* Open a file for reading */
174 int visual_open(wtap *wth, int *err, gchar **err_info)
175 {
176     int bytes_read;
177     char magic[sizeof visual_magic];
178     struct visual_file_hdr vfile_hdr;
179     struct visual_read_info * visual;
180     int encap;
181
182     /* Check the magic string at the start of the file */
183     errno = WTAP_ERR_CANT_READ;
184     bytes_read = file_read(magic, sizeof magic, wth->fh);
185     if (bytes_read != sizeof magic)
186     {
187         *err = file_error(wth->fh, err_info);
188         if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
189             return -1;
190         return 0;
191     }
192     if (memcmp(magic, visual_magic, sizeof visual_magic) != 0)
193     {
194         return 0;
195     }
196
197     /* Read the rest of the file header. */
198     errno = WTAP_ERR_CANT_READ;
199     bytes_read = file_read(&vfile_hdr, sizeof vfile_hdr, wth->fh);
200     if (bytes_read != sizeof vfile_hdr)
201     {
202         *err = file_error(wth->fh, err_info);
203         if (*err == 0)
204             *err = WTAP_ERR_SHORT_READ;
205         return -1;
206     }
207
208     /* Verify the file version is known */
209     vfile_hdr.file_version = pletoh16(&vfile_hdr.file_version);
210     if (vfile_hdr.file_version != 1)
211     {
212         *err = WTAP_ERR_UNSUPPORTED;
213         *err_info = g_strdup_printf("visual: file version %u unsupported", vfile_hdr.file_version);
214         return -1;
215     }
216
217     /* Translate the encapsulation type; these values are SNMP ifType
218        values, as found in http://www.iana.org/assignments/smi-numbers.
219
220        Note that a file with media type 22 ("propPointToPointSerial") may
221        contain Cisco HDLC or PPP over HDLC.  This will get sorted out after
222        the first packet is read.
223
224        XXX - should we use WTAP_ENCAP_PER_PACKET for that? */
225     switch (pletoh16(&vfile_hdr.media_type))
226     {
227     case  6:    /* ethernet-csmacd */
228         encap = WTAP_ENCAP_ETHERNET;
229         break;
230
231     case  9:    /* IEEE802.5 */
232         encap = WTAP_ENCAP_TOKEN_RING;
233         break;
234
235     case 16:    /* lapb */
236         encap = WTAP_ENCAP_LAPB;
237         break;
238
239     case 22:    /* propPointToPointSerial */
240     case 118:   /* HDLC */
241         encap = WTAP_ENCAP_CHDLC_WITH_PHDR;
242         break;
243
244     case 32:    /* frame-relay */
245         encap = WTAP_ENCAP_FRELAY_WITH_PHDR;
246         break;
247
248     case 37:    /* ATM */
249        encap = WTAP_ENCAP_ATM_PDUS;
250        break;
251
252     default:
253         *err = WTAP_ERR_UNSUPPORTED_ENCAP;
254         *err_info = g_strdup_printf("visual: network type %u unknown or unsupported",
255                                      vfile_hdr.media_type);
256         return -1;
257     }
258
259     /* Fill in the wiretap struct with data from the file header */
260     wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_VISUAL_NETWORKS;
261     wth->file_encap = encap;
262     wth->snapshot_length = pletoh16(&vfile_hdr.max_length);
263
264     /* Set up the pointers to the handlers for this file type */
265     wth->subtype_read = visual_read;
266     wth->subtype_seek_read = visual_seek_read;
267     wth->tsprecision = WTAP_FILE_TSPREC_USEC;
268
269     /* Add Visual-specific information to the wiretap struct for later use. */
270     visual = (struct visual_read_info *)g_malloc(sizeof(struct visual_read_info));
271     wth->priv = (void *)visual;
272     visual->num_pkts = pletoh32(&vfile_hdr.num_pkts);
273     visual->start_time = ((double) pletoh32(&vfile_hdr.start_time)) * 1000000;
274     visual->current_pkt = 1;
275
276     return 1;
277 }
278
279
280 /* Read the next available packet from the file.  This is called
281    in a loop to sequentially read the entire file one time.  After
282    the file has been read once, any Future access to the packets is
283    done through seek_read. */
284 static gboolean visual_read(wtap *wth, int *err, gchar **err_info,
285     gint64 *data_offset)
286 {
287     struct visual_read_info *visual = (struct visual_read_info *)wth->priv;
288
289     /* Check for the end of the packet data.  Note that a check for file EOF
290        will not work because there are index values stored after the last
291        packet's data. */
292     if (visual->current_pkt > visual->num_pkts)
293     {
294         *err = 0;   /* it's just an EOF, not an error */
295         return FALSE;
296     }
297     visual->current_pkt++;
298
299     *data_offset = file_tell(wth->fh);
300
301     return visual_read_packet(wth, wth->fh, &wth->phdr, wth->frame_buffer,
302             err, err_info);
303 }
304
305 /* Read packet header and data for random access. */
306 static gboolean visual_seek_read(wtap *wth, gint64 seek_off,
307     struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info)
308 {
309     /* Seek to the packet header */
310     if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
311         return FALSE;
312
313     /* Read the packet. */
314     if (!visual_read_packet(wth, wth->random_fh, phdr, buf, err, err_info)) {
315         if (*err == 0)
316             *err = WTAP_ERR_SHORT_READ;
317         return FALSE;
318     }
319     return TRUE;
320 }
321
322 static gboolean
323 visual_read_packet(wtap *wth, FILE_T fh, struct wtap_pkthdr *phdr,
324         Buffer *buf, int *err, gchar **err_info)
325 {
326     struct visual_read_info *visual = (struct visual_read_info *)wth->priv;
327     struct visual_pkt_hdr vpkt_hdr;
328     int bytes_read;
329     guint32 packet_size;
330     struct visual_atm_hdr vatm_hdr;
331     double  t;
332     time_t  secs;
333     guint32 usecs;
334     guint32 packet_status;
335     guint8 *pd;
336
337     /* Read the packet header. */
338     errno = WTAP_ERR_CANT_READ;
339     bytes_read = file_read(&vpkt_hdr, (unsigned int)sizeof vpkt_hdr, fh);
340     if (bytes_read < 0 || (size_t)bytes_read != sizeof vpkt_hdr)
341     {
342         *err = file_error(fh, err_info);
343         if (*err == 0 && bytes_read != 0)
344         {
345             *err = WTAP_ERR_SHORT_READ;
346         }
347         return FALSE;
348     }
349
350     /* Get the included length of data. This includes extra headers + payload */
351     packet_size = pletoh16(&vpkt_hdr.incl_len);
352
353     phdr->rec_type = REC_TYPE_PACKET;
354     phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
355
356     /* Set the packet time and length. */
357     t = visual->start_time;
358     t += ((double)pletoh32(&vpkt_hdr.ts_delta))*1000;
359     secs = (time_t)(t/1000000);
360     usecs = (guint32)(t - secs*1000000);
361     phdr->ts.secs = secs;
362     phdr->ts.nsecs = usecs * 1000;
363
364     phdr->len = pletoh16(&vpkt_hdr.orig_len);
365
366     packet_status = pletoh32(&vpkt_hdr.status);
367
368     /* Do encapsulation-specific processing.
369
370        Most Visual capture types include the FCS in the original length
371        value, but don't include the FCS as part of the payload or captured
372        length.  This is different from the model used in most other capture
373        file formats, including pcap and pcap-ng in cases where the FCS isn't
374        captured (which are the typical cases), and causes the RTP audio
375        payload save to fail since then captured len != orig len.
376
377        We adjust the original length to remove the FCS bytes we counted based
378        on the file encapsualtion type.  The only downside to this fix is
379        throughput calculations will be slightly lower as it won't include
380        the FCS bytes.  However, as noted, that problem also exists with
381        other capture formats.
382
383        We also set status flags.  The only status currently supported for
384        all encapsulations is direction.  This either goes in the p2p or the
385        X.25 pseudo header.  It would probably be better to move this up
386        into the phdr. */
387     switch (wth->file_encap)
388     {
389     case WTAP_ENCAP_ETHERNET:
390         /* Ethernet has a 4-byte FCS. */
391         if (phdr->len < 4)
392         {
393             *err = WTAP_ERR_BAD_FILE;
394             *err_info = g_strdup_printf("visual: Ethernet packet has %u-byte original packet, less than the FCS length",
395                         phdr->len);
396             return FALSE;
397         }
398         phdr->len -= 4;
399
400         /* XXX - the above implies that there's never an FCS; should this
401            set the FCS length to 0? */
402         phdr->pseudo_header.eth.fcs_len = -1;
403         break;
404
405     case WTAP_ENCAP_CHDLC_WITH_PHDR:
406         /* This has a 2-byte FCS. */
407         if (phdr->len < 2)
408         {
409             *err = WTAP_ERR_BAD_FILE;
410             *err_info = g_strdup_printf("visual: Cisco HDLC packet has %u-byte original packet, less than the FCS length",
411                         phdr->len);
412             return FALSE;
413         }
414         phdr->len -= 2;
415
416         phdr->pseudo_header.p2p.sent = (packet_status & PS_SENT) ? TRUE : FALSE;
417         break;
418
419     case WTAP_ENCAP_PPP_WITH_PHDR:
420         /* No FCS.
421            XXX - true?  Note that PPP can negotiate no FCS, a 2-byte FCS,
422            or a 4-byte FCS. */
423         phdr->pseudo_header.p2p.sent = (packet_status & PS_SENT) ? TRUE : FALSE;
424         break;
425
426     case WTAP_ENCAP_FRELAY_WITH_PHDR:
427         /* This has a 2-byte FCS. */
428         if (phdr->len < 2)
429         {
430             *err = WTAP_ERR_BAD_FILE;
431             *err_info = g_strdup_printf("visual: Frame Relay packet has %u-byte original packet, less than the FCS length",
432                         phdr->len);
433             return FALSE;
434         }
435         phdr->len -= 2;
436
437         phdr->pseudo_header.x25.flags =
438             (packet_status & PS_SENT) ? 0x00 : FROM_DCE;
439         break;
440
441     case WTAP_ENCAP_LAPB:
442         /* This has a 2-byte FCS. */
443         if (phdr->len < 2)
444         {
445             *err = WTAP_ERR_BAD_FILE;
446             *err_info = g_strdup_printf("visual: Frame Relay packet has %u-byte original packet, less than the FCS length",
447                         phdr->len);
448             return FALSE;
449         }
450         phdr->len -= 2;
451
452         phdr->pseudo_header.x25.flags =
453             (packet_status & PS_SENT) ? 0x00 : FROM_DCE;
454         break;
455
456     case WTAP_ENCAP_ATM_PDUS:
457         /* ATM original length doesn't include any FCS. Do nothing to
458            the packet length.
459
460            ATM packets have an additional packet header; read and
461            process it. */
462         errno = WTAP_ERR_CANT_READ;
463         bytes_read = file_read(&vatm_hdr, (unsigned int)sizeof vatm_hdr, fh);
464         if (bytes_read < 0 || (size_t)bytes_read != sizeof vatm_hdr)
465         {
466             *err = file_error(fh, err_info);
467             if (*err == 0)
468             {
469                 *err = WTAP_ERR_SHORT_READ;
470             }
471             return FALSE;
472         }
473
474         /* Remove ATM header from length of included bytes in capture, as
475            this header was appended by the processor doing the packet
476            reassembly, and was not transmitted across the wire */
477         packet_size -= (guint32)sizeof vatm_hdr;
478
479         /* Set defaults */
480         phdr->pseudo_header.atm.type = TRAF_UNKNOWN;
481         phdr->pseudo_header.atm.subtype = TRAF_ST_UNKNOWN;
482         phdr->pseudo_header.atm.aal5t_len = 0;
483
484         /* Next two items not supported. Defaulting to zero */
485         phdr->pseudo_header.atm.aal5t_u2u = 0;
486         phdr->pseudo_header.atm.aal5t_chksum = 0;
487
488         /* Flags appear only to convey that packet is a raw cell. Set to 0 */
489         phdr->pseudo_header.atm.flags = 0;
490
491         /* Not supported. Defaulting to zero */
492         phdr->pseudo_header.atm.aal2_cid = 0;
493
494         switch(vatm_hdr.category & VN_CAT_TYPE_MASK )
495         {
496         case VN_AAL1:
497             phdr->pseudo_header.atm.aal = AAL_1;
498             break;
499
500         case VN_AAL2:
501             phdr->pseudo_header.atm.aal = AAL_2;
502             break;
503
504         case VN_AAL34:
505             phdr->pseudo_header.atm.aal = AAL_3_4;
506             break;
507
508         case VN_AAL5:
509             phdr->pseudo_header.atm.aal = AAL_5;
510             phdr->pseudo_header.atm.type = TRAF_LLCMX;
511             phdr->pseudo_header.atm.aal5t_len = pntoh32(&vatm_hdr.data_length);
512             break;
513
514         case VN_OAM:
515         /* Marking next 3 as OAM versus unknown */
516         case VN_O191:
517         case VN_IDLE:
518         case VN_RM:
519             phdr->pseudo_header.atm.aal = AAL_OAMCELL;
520             break;
521
522         case VN_UNKNOWN:
523         default:
524             phdr->pseudo_header.atm.aal = AAL_UNKNOWN;
525             break;
526         }
527         phdr->pseudo_header.atm.vpi = pntoh16(&vatm_hdr.vpi) & 0x0FFF;
528         phdr->pseudo_header.atm.vci = pntoh16(&vatm_hdr.vci);
529         phdr->pseudo_header.atm.cells = pntoh16(&vatm_hdr.cell_count);
530
531         /* Using bit value of 1 (DCE -> DTE) to indicate From Network */
532         phdr->pseudo_header.atm.channel = vatm_hdr.info & FROM_NETWORK;
533         break;
534
535     /* Not sure about token ring. Just leaving alone for now. */
536     case WTAP_ENCAP_TOKEN_RING:
537     default:
538         break;
539     }
540
541     phdr->caplen = packet_size;
542
543     /* Check for too-large packet. */
544     if (packet_size > WTAP_MAX_PACKET_SIZE)
545     {
546         /* Probably a corrupt capture file; don't blow up trying
547           to allocate space for an immensely-large packet. */
548         *err = WTAP_ERR_BAD_FILE;
549         *err_info = g_strdup_printf("visual: File has %u-byte packet, bigger than maximum of %u",
550             packet_size, WTAP_MAX_PACKET_SIZE);
551         return FALSE;
552     }
553
554     /* Read the packet data */
555     if (!wtap_read_packet_bytes(fh, buf, packet_size, err, err_info))
556         return FALSE;
557
558     if (wth->file_encap == WTAP_ENCAP_CHDLC_WITH_PHDR)
559     {
560         /* Fill in the encapsulation.  Visual files have a media type in the
561            file header and an encapsulation type in each packet header.  Files
562            with a media type of HDLC can be either Cisco EtherType or PPP.
563
564            The encapsulation hint values we've seen are:
565
566              2 - seen in an Ethernet capture
567              13 - seen in a PPP capture; possibly also seen in Cisco HDLC
568                   captures
569              14 - seen in a PPP capture; probably seen only for PPP.
570
571            According to bug 2005, the collection probe can be configured
572            for PPP, in which case the encapsulation hint is 14, or can
573            be configured for auto-detect, in which case the encapsulation
574            hint is 13, and the encapsulation must be guessed from the
575            packet contents.  Auto-detect is the default. */
576         pd = ws_buffer_start_ptr(buf);
577
578         /* If PPP is specified in the encap hint, then use that */
579         if (vpkt_hdr.encap_hint == 14)
580         {
581             /* But first we need to examine the first three octets to
582                try to determine the proper encapsulation, see RFC 2364. */
583             if (packet_size >= 3 &&
584                 (0xfe == pd[0]) && (0xfe == pd[1]) && (0x03 == pd[2]))
585             {
586                 /* It is actually LLC encapsulated PPP */
587                 phdr->pkt_encap = WTAP_ENCAP_ATM_RFC1483;
588             }
589             else
590             {
591                 /* It is actually PPP */
592                 phdr->pkt_encap = WTAP_ENCAP_PPP_WITH_PHDR;
593             }
594         }
595         else
596         {
597             /* Otherwise, we need to examine the first two octets to
598                try to determine the encapsulation. */
599             if (packet_size >= 2 && (0xff == pd[0]) && (0x03 == pd[1]))
600             {
601                 /* It is actually PPP */
602                 phdr->pkt_encap = WTAP_ENCAP_PPP_WITH_PHDR;
603             }
604         }
605     }
606
607     return TRUE;
608 }
609
610 /* Check for media types that may be written in Visual file format.
611    Returns 0 if the specified encapsulation type is supported,
612    an error indication otherwise. */
613 int visual_dump_can_write_encap(int encap)
614 {
615     /* Per-packet encapsulations aren't supported. */
616     if (encap == WTAP_ENCAP_PER_PACKET)
617         return WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
618
619     /* Check for supported encapsulation types */
620     switch (encap)
621     {
622     case WTAP_ENCAP_ETHERNET:
623     case WTAP_ENCAP_TOKEN_RING:
624     case WTAP_ENCAP_LAPB:
625     case WTAP_ENCAP_CHDLC_WITH_PHDR:
626     case WTAP_ENCAP_FRELAY_WITH_PHDR:
627     case WTAP_ENCAP_PPP:
628     case WTAP_ENCAP_PPP_WITH_PHDR:
629         return 0;
630     }
631
632     return WTAP_ERR_UNSUPPORTED_ENCAP;
633 }
634
635
636 /* Open a file for writing.
637    Returns TRUE on success, FALSE on failure; sets "*err" to an
638    error code on failure */
639 gboolean visual_dump_open(wtap_dumper *wdh, int *err)
640 {
641     struct visual_write_info *visual;
642
643     /* Set the write routines for a visual file. */
644     wdh->subtype_write = visual_dump;
645     wdh->subtype_close = visual_dump_close;
646
647     /* Create a struct to hold file information for the duration
648        of the write */
649     visual = (struct visual_write_info *)g_malloc(sizeof(struct visual_write_info));
650     wdh->priv = (void *)visual;
651     visual->index_table_index = 0;
652     visual->index_table_size = 1024;
653     visual->index_table = 0;
654     visual->next_offset = CAPTUREFILE_HEADER_SIZE;
655
656     /* All of the fields in the file header aren't known yet so
657        just skip over it for now.  It will be created after all
658        of the packets have been written. */
659     if (wtap_dump_file_seek(wdh, CAPTUREFILE_HEADER_SIZE, SEEK_SET, err) == -1)
660         return FALSE;
661
662     return TRUE;
663 }
664
665
666 /* Write a packet to a Visual dump file.
667    Returns TRUE on success, FALSE on failure. */
668 static gboolean visual_dump(wtap_dumper *wdh, const struct wtap_pkthdr *phdr,
669     const guint8 *pd, int *err)
670 {
671     const union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
672     struct visual_write_info * visual = (struct visual_write_info *)wdh->priv;
673     struct visual_pkt_hdr vpkt_hdr;
674     size_t hdr_size = sizeof vpkt_hdr;
675     guint delta_msec;
676     guint32 packet_status;
677
678     /* We can only write packet records. */
679     if (phdr->rec_type != REC_TYPE_PACKET) {
680         *err = WTAP_ERR_REC_TYPE_UNSUPPORTED;
681         return FALSE;
682     }
683
684     /* Don't write anything we're not willing to read. */
685     if (phdr->caplen > WTAP_MAX_PACKET_SIZE) {
686         *err = WTAP_ERR_PACKET_TOO_LARGE;
687         return FALSE;
688     }
689
690     /* If the visual structure was never allocated then nothing useful
691        can be done. */
692     if (visual == 0)
693         return FALSE;
694
695     /* Zero out unused and reserved fields in the packet header. */
696     memset(&vpkt_hdr, 0, hdr_size);
697
698     /* Visual UpTime capture files have a capture start time in the
699        file header.  Each packet has a capture time (in msec) relative
700        to the file start time.  Use the time of the first packet as the
701        file start time. */
702     if (visual->index_table_index == 0)
703     {
704         /* This is the first packet.  Save its start time as the file time. */
705         visual->start_time = (guint32) phdr->ts.secs;
706
707         /* Initialize the index table */
708         visual->index_table = (guint32 *)g_malloc(1024 * sizeof *visual->index_table);
709         visual->index_table_size = 1024;
710     }
711
712     /* Calculate milliseconds since capture start. */
713     delta_msec = phdr->ts.nsecs / 1000000;
714     delta_msec += ( (guint32) phdr->ts.secs - visual->start_time) * 1000;
715     vpkt_hdr.ts_delta = GUINT32_TO_LE(delta_msec);
716
717     /* Fill in the length fields. */
718     vpkt_hdr.orig_len = GUINT16_TO_LE(phdr->len);
719     vpkt_hdr.incl_len = GUINT16_TO_LE(phdr->caplen);
720
721     /* Fill in the encapsulation hint for the file's media type. */
722     switch (wdh->encap)
723     {
724     case WTAP_ENCAP_ETHERNET:   /* Ethernet */
725         vpkt_hdr.encap_hint = 2;
726         break;
727     case WTAP_ENCAP_TOKEN_RING: /* Token Ring */
728         vpkt_hdr.encap_hint = 3;
729         break;
730     case WTAP_ENCAP_PPP:        /* PPP */
731     case WTAP_ENCAP_PPP_WITH_PHDR:
732         vpkt_hdr.encap_hint = 14;
733         break;
734     case WTAP_ENCAP_CHDLC_WITH_PHDR:      /* HDLC Router */
735         vpkt_hdr.encap_hint = 13;
736         break;
737     case WTAP_ENCAP_FRELAY_WITH_PHDR:     /* Frame Relay Auto-detect */
738         vpkt_hdr.encap_hint = 12;
739         break;
740     case WTAP_ENCAP_LAPB:       /* Unknown */
741     default:
742         vpkt_hdr.encap_hint = 1;
743         break;
744     }
745
746     /* Set status flags.  The only status currently supported for all
747        encapsulations is direction.  This either goes in the p2p or the
748        X.25 pseudo header.  It would probably be better to move this up
749        into the phdr. */
750     packet_status = 0;
751     switch (wdh->encap)
752     {
753     case WTAP_ENCAP_CHDLC_WITH_PHDR:
754         packet_status |= (pseudo_header->p2p.sent ? PS_SENT : 0x00);
755         break;
756
757     case WTAP_ENCAP_FRELAY_WITH_PHDR:
758     case WTAP_ENCAP_LAPB:
759         packet_status |=
760             ((pseudo_header->x25.flags & FROM_DCE) ? 0x00 : PS_SENT);
761         break;
762     }
763     vpkt_hdr.status = GUINT32_TO_LE(packet_status);
764
765     /* Write the packet header. */
766     if (!wtap_dump_file_write(wdh, &vpkt_hdr, hdr_size, err))
767         return FALSE;
768
769     /* Write the packet data */
770     if (!wtap_dump_file_write(wdh, pd, phdr->caplen, err))
771         return FALSE;
772
773     /* Store the frame offset in the index table. */
774     if (visual->index_table_index >= visual->index_table_size)
775     {
776         /* End of table reached.  Reallocate with a larger size */
777         visual->index_table_size *= 2;
778         visual->index_table = (guint32 *)g_realloc(visual->index_table,
779             visual->index_table_size * sizeof *visual->index_table);
780     }
781     visual->index_table[visual->index_table_index] = GUINT32_TO_LE(visual->next_offset);
782
783     /* Update the table index and offset for the next frame. */
784     visual->index_table_index++;
785     visual->next_offset += (guint32) hdr_size + phdr->caplen;
786
787     return TRUE;
788 }
789
790
791 /* Finish writing to a dump file.
792    Returns TRUE on success, FALSE on failure. */
793 static gboolean visual_dump_close(wtap_dumper *wdh, int *err)
794 {
795     struct visual_write_info * visual = (struct visual_write_info *)wdh->priv;
796     size_t n_to_write;
797     struct visual_file_hdr vfile_hdr;
798     const char *magicp;
799     size_t magic_size;
800
801     /* If the visual structure was never allocated then nothing useful
802        can be done. */
803     if (visual == 0)
804         return FALSE;
805
806     /* Write out the frame table at the end of the file. */
807     if (visual->index_table)
808     {
809         /* Write the index table to the file. */
810         n_to_write = visual->index_table_index * sizeof *visual->index_table;
811         if (!wtap_dump_file_write(wdh, visual->index_table, n_to_write, err))
812         {
813             visual_dump_free(wdh);
814             return FALSE;
815         }
816     }
817
818     /* Write the magic number at the start of the file. */
819     if (wtap_dump_file_seek(wdh, 0, SEEK_SET, err) == -1)
820         return FALSE;
821     magicp = visual_magic;
822     magic_size = sizeof visual_magic;
823     if (!wtap_dump_file_write(wdh, magicp, magic_size, err))
824     {
825         visual_dump_free(wdh);
826         return FALSE;
827     }
828
829     /* Initialize the file header with zeroes for the reserved fields. */
830     memset(&vfile_hdr, '\0', sizeof vfile_hdr);
831     vfile_hdr.num_pkts = GUINT32_TO_LE(visual->index_table_index);
832     vfile_hdr.start_time = GUINT32_TO_LE(visual->start_time);
833     vfile_hdr.max_length = GUINT16_TO_LE(65535);
834     vfile_hdr.file_flags = GUINT16_TO_LE(1);  /* indexes are present */
835     vfile_hdr.file_version = GUINT16_TO_LE(1);
836     g_strlcpy(vfile_hdr.description, "Wireshark file", 64);
837
838     /* Translate the encapsulation type */
839     switch (wdh->encap)
840     {
841     case WTAP_ENCAP_ETHERNET:
842         vfile_hdr.media_type = GUINT16_TO_LE(6);
843         break;
844
845     case WTAP_ENCAP_TOKEN_RING:
846         vfile_hdr.media_type = GUINT16_TO_LE(9);
847         break;
848
849     case WTAP_ENCAP_LAPB:
850         vfile_hdr.media_type = GUINT16_TO_LE(16);
851         break;
852
853     case WTAP_ENCAP_PPP:        /* PPP is differentiated from CHDLC in PktHdr */
854     case WTAP_ENCAP_PPP_WITH_PHDR:
855     case WTAP_ENCAP_CHDLC_WITH_PHDR:
856         vfile_hdr.media_type = GUINT16_TO_LE(22);
857         break;
858
859     case WTAP_ENCAP_FRELAY_WITH_PHDR:
860         vfile_hdr.media_type = GUINT16_TO_LE(32);
861         break;
862     }
863
864     /* Write the file header following the magic bytes. */
865     if (!wtap_dump_file_write(wdh, &vfile_hdr, sizeof vfile_hdr, err))
866     {
867         visual_dump_free(wdh);
868         return FALSE;
869     }
870
871     /* Deallocate the file write data */
872     visual_dump_free(wdh);
873     return TRUE;
874 }
875
876
877 /* Free the memory allocated by a visual file writer. */
878 static void visual_dump_free(wtap_dumper *wdh)
879 {
880     struct visual_write_info * visual = (struct visual_write_info *)wdh->priv;
881
882     if (visual)
883     {
884         /* Free the index table memory. */
885         if (visual->index_table)
886             g_free(visual->index_table);
887     }
888 }