Refactor Wiretap
[metze/wireshark/wip.git] / wiretap / erf.c
1 /* erf.c
2  * Copyright (c) 2003 Endace Technology Ltd, Hamilton, New Zealand.
3  * All rights reserved.
4  *
5  * This software and documentation has been developed by Endace Technology Ltd.
6  * along with the DAG PCI network capture cards. For further information please
7  * visit http://www.endace.com/.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions are met:
11  *
12  *  1. Redistributions of source code must retain the above copyright notice,
13  *  this list of conditions and the following disclaimer.
14  *
15  *  2. Redistributions in binary form must reproduce the above copyright
16  *  notice, this list of conditions and the following disclaimer in the
17  *  documentation and/or other materials provided with the distribution.
18  *
19  *  3. The name of Endace Technology Ltd may not be used to endorse or promote
20  *  products derived from this software without specific prior written
21  *  permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY ENDACE TECHNOLOGY LTD ``AS IS'' AND ANY EXPRESS
24  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
26  * EVENT SHALL ENDACE TECHNOLOGY LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
29  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
30  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34
35 /*
36  * erf - Endace ERF (Extensible Record Format)
37  *
38  * See
39  *
40  *      http://www.endace.com/support/EndaceRecordFormat.pdf
41  *      (mirror: https://bugs.wireshark.org/bugzilla/attachment.cgi?id=4333) (bug #4484)
42  */
43
44 #include "config.h"
45
46 #include <stdlib.h>
47 #include <string.h>
48
49 #include <glib.h>
50
51 #include <wsutil/crc32.h>
52
53 #include "wftap-int.h"
54 #include "wtap-int.h"
55 #include "file_wrappers.h"
56 #include "buffer.h"
57 #include "pcap-encap.h"
58 #include "atm.h"
59 #include "erf.h"
60
61 static int erf_read_header(FILE_T fh,
62                            struct wtap_pkthdr *phdr,
63                            erf_header_t *erf_header,
64                            int *err,
65                            gchar **err_info,
66                            guint32 *bytes_read,
67                            guint32 *packet_size);
68 static gboolean erf_read(wftap *wfth, int *err, gchar **err_info,
69                          gint64 *data_offset);
70 static gboolean erf_seek_read(wftap *wfth, gint64 seek_off,
71                               void* header, Buffer *buf,
72                               int *err, gchar **err_info);
73
74 static const struct {
75   int erf_encap_value;
76   int wtap_encap_value;
77 } erf_to_wtap_map[] = {
78   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_CHDLC },
79   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_HHDLC },
80   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_CHDLC_WITH_PHDR },
81   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_PPP },
82   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_FRELAY },
83   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_MTP2 },
84   { ERF_TYPE_ETH,       WTAP_ENCAP_ETHERNET },
85   { 99,       WTAP_ENCAP_ERF }, /*this type added so WTAP_ENCAP_ERF will work and then be treated at ERF->ERF*/
86 };
87
88 #define NUM_ERF_ENCAPS (sizeof erf_to_wtap_map / sizeof erf_to_wtap_map[0])
89
90 extern int erf_open(wftap *wfth, int *err, gchar **err_info)
91 {
92   int              i, n, records_for_erf_check = RECORDS_FOR_ERF_CHECK;
93   int              valid_prev                  = 0;
94   char            *s;
95   erf_timestamp_t  prevts,ts;
96   erf_header_t     header;
97   guint32          mc_hdr;
98   guint16          eth_hdr;
99   guint32          packet_size;
100   guint16          rlen;
101   guint64          erf_ext_header;
102   guint8           type;
103   size_t           r;
104   gchar *          buffer;
105   wtap*            wth = (wtap*)wfth->tap_specific_data;
106
107   memset(&prevts, 0, sizeof(prevts));
108
109   /* number of records to scan before deciding if this really is ERF */
110   if ((s = getenv("ERF_RECORDS_TO_CHECK")) != NULL) {
111     if ((n = atoi(s)) > 0 && n < 101) {
112       records_for_erf_check = n;
113     }
114   }
115
116   /*
117    * ERF is a little hard because there's no magic number; we look at
118    * the first few records and see if they look enough like ERF
119    * records.
120    */
121
122   for (i = 0; i < records_for_erf_check; i++) {  /* records_for_erf_check */
123
124     r = file_read(&header,sizeof(header),wfth->fh);
125
126     if (r == 0 ) break;
127     if (r != sizeof(header)) {
128       *err = file_error(wfth->fh, err_info);
129       if (*err != 0 && *err != WTAP_ERR_SHORT_READ) {
130         return -1;
131       } else {
132         /* ERF header too short accept the file,
133            only if the very first records have been successfully checked */
134         if (i < MIN_RECORDS_FOR_ERF_CHECK) {
135           return 0;
136         } else {
137           /* BREAK, the last record is too short, and will be ignored */
138           break;
139         }
140       }
141     }
142
143     rlen=g_ntohs(header.rlen);
144
145     /* fail on invalid record type, invalid rlen, timestamps decreasing, or incrementing too far */
146
147     /* Test valid rlen >= 16 */
148     if (rlen < 16) {
149       return 0;
150     }
151
152     packet_size = rlen - (guint32)sizeof(header);
153     if (packet_size > WTAP_MAX_PACKET_SIZE) {
154       /*
155        * Probably a corrupt capture file or a file that's not an ERF file
156        * but that passed earlier tests.
157        */
158       return 0;
159     }
160
161     /* Skip PAD records, timestamps may not be set */
162     if ((header.type & 0x7F) == ERF_TYPE_PAD) {
163       if (file_seek(wfth->fh, packet_size, SEEK_CUR, err) == -1) {
164         return -1;
165       }
166       continue;
167     }
168
169     /* fail on invalid record type, decreasing timestamps or non-zero pad-bits */
170     /* Not all types within this range are decoded, but it is a first filter */
171     if ((header.type & 0x7F) == 0 || (header.type & 0x7F) > ERF_TYPE_MAX ) {
172       return 0;
173     }
174
175     /* The ERF_TYPE_MAX is the PAD record, but the last used type is ERF_TYPE_INFINIBAND_LINK */
176     if ((header.type & 0x7F) > ERF_TYPE_INFINIBAND_LINK) {
177       return 0;
178     }
179
180     if ((ts = pletoh64(&header.ts)) < prevts) {
181       /* reassembled AALx records may not be in time order, also records are not in strict time order between physical interfaces, so allow 1 sec fudge */
182       if ( ((prevts-ts)>>32) > 1 ) {
183         return 0;
184       }
185     }
186
187     /* Check to see if timestamp increment is > 1 week */
188     if ( (valid_prev) && (ts > prevts) && (((ts-prevts)>>32) > 3600*24*7) ) {
189       return 0;
190     }
191
192     memcpy(&prevts, &ts, sizeof(prevts));
193
194     /* Read over the extension headers */
195     type = header.type;
196     while (type & 0x80){
197       if (file_read(&erf_ext_header, sizeof(erf_ext_header),wfth->fh) != sizeof(erf_ext_header)) {
198         *err = file_error(wfth->fh, err_info);
199         if (*err == 0)
200           *err = WTAP_ERR_SHORT_READ;
201         return -1;
202       }
203       packet_size -= (guint32)sizeof(erf_ext_header);
204       memcpy(&type, &erf_ext_header, sizeof(type));
205     }
206
207
208     /* Read over MC or ETH subheader */
209     switch(header.type & 0x7F) {
210       case ERF_TYPE_MC_HDLC:
211       case ERF_TYPE_MC_RAW:
212       case ERF_TYPE_MC_ATM:
213       case ERF_TYPE_MC_RAW_CHANNEL:
214       case ERF_TYPE_MC_AAL5:
215       case ERF_TYPE_MC_AAL2:
216       case ERF_TYPE_COLOR_MC_HDLC_POS:
217       case ERF_TYPE_AAL2: /* not an MC type but has a similar 'AAL2 ext' header */
218         if (file_read(&mc_hdr,sizeof(mc_hdr),wfth->fh) != sizeof(mc_hdr)) {
219           *err = file_error(wfth->fh, err_info);
220           return -1;
221         }
222         packet_size -= (guint32)sizeof(mc_hdr);
223         break;
224       case ERF_TYPE_ETH:
225       case ERF_TYPE_COLOR_ETH:
226       case ERF_TYPE_DSM_COLOR_ETH:
227         if (file_read(&eth_hdr,sizeof(eth_hdr),wfth->fh) != sizeof(eth_hdr)) {
228           *err = file_error(wfth->fh, err_info);
229           return -1;
230         }
231         packet_size -= (guint32)sizeof(eth_hdr);
232         break;
233       default:
234         break;
235     }
236
237     /* The file_seek function do not return an error if the end of file
238        is reached whereas the record is truncated */
239     if (packet_size > WTAP_MAX_PACKET_SIZE) {
240       /*
241        * Probably a corrupt capture file or a file that's not an ERF file
242        * but that passed earlier tests.
243        */
244       return 0;
245     }
246     buffer=(gchar *)g_malloc(packet_size);
247     r = file_read(buffer, packet_size, wfth->fh);
248     g_free(buffer);
249
250     if (r != packet_size) {
251       /* ERF record too short, accept the file,
252          only if the very first records have been successfully checked */
253       if (i < MIN_RECORDS_FOR_ERF_CHECK) {
254         return 0;
255       }
256     }
257
258     valid_prev = 1;
259
260   } /* records_for_erf_check */
261
262   if (file_seek(wfth->fh, 0L, SEEK_SET, err) == -1) {   /* rewind */
263     return -1;
264   }
265
266   /* This is an ERF file */
267   wfth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_ERF;
268   wfth->snapshot_length = 0;     /* not available in header, only in frame */
269
270   /*
271    * Use the encapsulation for ERF records.
272    */
273   wfth->file_encap = WTAP_ENCAP_ERF;
274
275   wfth->subtype_read = erf_read;
276   wfth->subtype_seek_read = erf_seek_read;
277   wfth->tsprecision = WTAP_FILE_TSPREC_NSEC;
278
279   erf_populate_interfaces(wth);
280
281   return 1;
282 }
283
284 /* Read the next packet */
285 static gboolean erf_read(wftap *wfth, int *err, gchar **err_info,
286                          gint64 *data_offset)
287 {
288   erf_header_t erf_header;
289   guint32      packet_size, bytes_read;
290   wtap*        wth = (wtap*)wfth->tap_specific_data;
291
292   *data_offset = file_tell(wfth->fh);
293
294   do {
295     if (!erf_read_header(wfth->fh,
296                          &wth->phdr, &erf_header,
297                          err, err_info, &bytes_read, &packet_size)) {
298       return FALSE;
299     }
300
301     if (!wtap_read_packet_bytes(wfth->fh, wfth->frame_buffer, packet_size,
302                                 err, err_info))
303       return FALSE;
304
305   } while ( erf_header.type == ERF_TYPE_PAD );
306
307   return TRUE;
308 }
309
310 static gboolean erf_seek_read(wftap *wfth, gint64 seek_off,
311                               void* header, Buffer *buf,
312                               int *err, gchar **err_info)
313 {
314   erf_header_t erf_header;
315   guint32      packet_size;
316   struct wtap_pkthdr *phdr = (struct wtap_pkthdr*)header;
317
318   if (file_seek(wfth->random_fh, seek_off, SEEK_SET, err) == -1)
319     return FALSE;
320
321   do {
322     if (!erf_read_header(wfth->random_fh, phdr, &erf_header,
323                          err, err_info, NULL, &packet_size))
324       return FALSE;
325   } while ( erf_header.type == ERF_TYPE_PAD );
326
327   return wtap_read_packet_bytes(wfth->random_fh, buf, packet_size,
328                                 err, err_info);
329 }
330
331 static int erf_read_header(FILE_T fh,
332                            struct wtap_pkthdr *phdr,
333                            erf_header_t *erf_header,
334                            int *err,
335                            gchar **err_info,
336                            guint32 *bytes_read,
337                            guint32 *packet_size)
338 {
339   union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
340   guint32 mc_hdr;
341   guint8  erf_exhdr[8];
342   guint64 erf_exhdr_sw;
343   guint8  type    = 0;
344   guint16 eth_hdr;
345   guint32 skiplen = 0;
346   int     i       = 0;
347   int     max     = sizeof(pseudo_header->erf.ehdr_list)/sizeof(struct erf_ehdr);
348
349   wtap_file_read_expected_bytes(erf_header, sizeof(*erf_header), fh, err,
350                                 err_info);
351   if (bytes_read != NULL) {
352     *bytes_read = sizeof(*erf_header);
353   }
354
355   *packet_size =  g_ntohs(erf_header->rlen) - (guint32)sizeof(*erf_header);
356
357   if (*packet_size > WTAP_MAX_PACKET_SIZE) {
358     /*
359      * Probably a corrupt capture file; don't blow up trying
360      * to allocate space for an immensely-large packet.
361      */
362     *err = WTAP_ERR_BAD_FILE;
363     *err_info = g_strdup_printf("erf: File has %u-byte packet, bigger than maximum of %u",
364                                 *packet_size, WTAP_MAX_PACKET_SIZE);
365     return FALSE;
366   }
367
368   if (*packet_size == 0) {
369     /* If this isn't a pad record, it's a corrupt packet; bail out */
370     if ((erf_header->type & 0x7F) != ERF_TYPE_PAD) {
371       *err = WTAP_ERR_BAD_FILE;
372       *err_info = g_strdup_printf("erf: File has 0 byte packet");
373
374       return FALSE;
375     }
376   }
377
378   {
379     guint64 ts = pletoh64(&erf_header->ts);
380
381     phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN|WTAP_HAS_INTERFACE_ID;
382     phdr->ts.secs = (long) (ts >> 32);
383     ts  = ((ts & 0xffffffff) * 1000 * 1000 * 1000);
384     ts += (ts & 0x80000000) << 1; /* rounding */
385     phdr->ts.nsecs = ((int) (ts >> 32));
386     if (phdr->ts.nsecs >= 1000000000) {
387       phdr->ts.nsecs -= 1000000000;
388       phdr->ts.secs += 1;
389     }
390     phdr->interface_id = (erf_header->flags & 0x03);
391   }
392
393   /* Copy the ERF pseudo header */
394   memset(&pseudo_header->erf, 0, sizeof(pseudo_header->erf));
395   pseudo_header->erf.phdr.ts = pletoh64(&erf_header->ts);
396   pseudo_header->erf.phdr.type = erf_header->type;
397   pseudo_header->erf.phdr.flags = erf_header->flags;
398   pseudo_header->erf.phdr.rlen = g_ntohs(erf_header->rlen);
399   pseudo_header->erf.phdr.lctr = g_ntohs(erf_header->lctr);
400   pseudo_header->erf.phdr.wlen = g_ntohs(erf_header->wlen);
401
402   /* Copy the ERF extension header into the pseudo header */
403   type = erf_header->type;
404   while (type & 0x80){
405     wtap_file_read_expected_bytes(&erf_exhdr, sizeof(erf_exhdr), fh, err,
406                                   err_info);
407     if (bytes_read != NULL)
408       *bytes_read += (guint32)sizeof(erf_exhdr);
409     *packet_size -=  (guint32)sizeof(erf_exhdr);
410     skiplen += (guint32)sizeof(erf_exhdr);
411     erf_exhdr_sw = pntoh64(erf_exhdr);
412     if (i < max)
413       memcpy(&pseudo_header->erf.ehdr_list[i].ehdr, &erf_exhdr_sw, sizeof(erf_exhdr_sw));
414     type = erf_exhdr[0];
415     i++;
416   }
417
418   switch (erf_header->type & 0x7F) {
419     case ERF_TYPE_IPV4:
420     case ERF_TYPE_IPV6:
421     case ERF_TYPE_RAW_LINK:
422     case ERF_TYPE_INFINIBAND:
423     case ERF_TYPE_INFINIBAND_LINK:
424 #if 0
425       {
426         phdr->len =  g_htons(erf_header->wlen);
427         phdr->caplen = g_htons(erf_header->wlen);
428       }
429       return TRUE;
430 #endif
431       break;
432     case ERF_TYPE_PAD:
433     case ERF_TYPE_HDLC_POS:
434     case ERF_TYPE_COLOR_HDLC_POS:
435     case ERF_TYPE_DSM_COLOR_HDLC_POS:
436     case ERF_TYPE_ATM:
437     case ERF_TYPE_AAL5:
438       break;
439
440     case ERF_TYPE_ETH:
441     case ERF_TYPE_COLOR_ETH:
442     case ERF_TYPE_DSM_COLOR_ETH:
443       wtap_file_read_expected_bytes(&eth_hdr, sizeof(eth_hdr), fh, err,
444                                     err_info);
445       if (bytes_read != NULL)
446         *bytes_read += (guint32)sizeof(eth_hdr);
447       *packet_size -=  (guint32)sizeof(eth_hdr);
448       skiplen += (guint32)sizeof(eth_hdr);
449       pseudo_header->erf.subhdr.eth_hdr = g_htons(eth_hdr);
450       break;
451
452     case ERF_TYPE_MC_HDLC:
453     case ERF_TYPE_MC_RAW:
454     case ERF_TYPE_MC_ATM:
455     case ERF_TYPE_MC_RAW_CHANNEL:
456     case ERF_TYPE_MC_AAL5:
457     case ERF_TYPE_MC_AAL2:
458     case ERF_TYPE_COLOR_MC_HDLC_POS:
459     case ERF_TYPE_AAL2: /* not an MC type but has a similar 'AAL2 ext' header */
460       wtap_file_read_expected_bytes(&mc_hdr, sizeof(mc_hdr), fh, err,
461                                     err_info);
462       if (bytes_read != NULL)
463         *bytes_read += (guint32)sizeof(mc_hdr);
464       *packet_size -=  (guint32)sizeof(mc_hdr);
465       skiplen += (guint32)sizeof(mc_hdr);
466       pseudo_header->erf.subhdr.mc_hdr = g_htonl(mc_hdr);
467       break;
468
469     case ERF_TYPE_IP_COUNTER:
470     case ERF_TYPE_TCP_FLOW_COUNTER:
471       /* unsupported, continue with default: */
472     default:
473       *err = WTAP_ERR_UNSUPPORTED_ENCAP;
474       *err_info = g_strdup_printf("erf: unknown record encapsulation %u",
475                                   erf_header->type);
476       return FALSE;
477   }
478
479   {
480     phdr->len = g_htons(erf_header->wlen);
481     phdr->caplen = MIN( g_htons(erf_header->wlen),
482                         g_htons(erf_header->rlen) - (guint32)sizeof(*erf_header) - skiplen );
483   }
484
485   if (*packet_size > WTAP_MAX_PACKET_SIZE) {
486     /*
487      * Probably a corrupt capture file; don't blow up trying
488      * to allocate space for an immensely-large packet.
489      */
490     *err = WTAP_ERR_BAD_FILE;
491     *err_info = g_strdup_printf("erf: File has %u-byte packet, bigger than maximum of %u",
492                                 *packet_size, WTAP_MAX_PACKET_SIZE);
493     return FALSE;
494   }
495
496   return TRUE;
497 }
498
499 static int wtap_wtap_encap_to_erf_encap(int encap)
500 {
501   unsigned int i;
502   for(i = 0; i < NUM_ERF_ENCAPS; i++){
503     if(erf_to_wtap_map[i].wtap_encap_value == encap)
504       return erf_to_wtap_map[i].erf_encap_value;
505   }
506   return -1;
507 }
508
509 static gboolean erf_write_phdr(wftap_dumper *wdh, int encap, const union wtap_pseudo_header *pseudo_header, int * err)
510 {
511   guint8 erf_hdr[sizeof(struct erf_mc_phdr)];
512   guint8 erf_subhdr[((sizeof(struct erf_mc_hdr) > sizeof(struct erf_eth_hdr))?
513     sizeof(struct erf_mc_hdr) : sizeof(struct erf_eth_hdr))];
514   guint8 ehdr[8*MAX_ERF_EHDR];
515   size_t size        = 0;
516   size_t subhdr_size = 0;
517   int    i           = 0;
518   guint8 has_more    = 0;
519
520   switch(encap){
521     case WTAP_ENCAP_ERF:
522       memset(&erf_hdr, 0, sizeof(erf_hdr));
523       phtolell(&erf_hdr[0], pseudo_header->erf.phdr.ts);
524       erf_hdr[8] = pseudo_header->erf.phdr.type;
525       erf_hdr[9] = pseudo_header->erf.phdr.flags;
526       phtons(&erf_hdr[10], pseudo_header->erf.phdr.rlen);
527       phtons(&erf_hdr[12], pseudo_header->erf.phdr.lctr);
528       phtons(&erf_hdr[14], pseudo_header->erf.phdr.wlen);
529       size = sizeof(struct erf_phdr);
530
531       switch(pseudo_header->erf.phdr.type & 0x7F) {
532         case ERF_TYPE_MC_HDLC:
533         case ERF_TYPE_MC_RAW:
534         case ERF_TYPE_MC_ATM:
535         case ERF_TYPE_MC_RAW_CHANNEL:
536         case ERF_TYPE_MC_AAL5:
537         case ERF_TYPE_MC_AAL2:
538         case ERF_TYPE_COLOR_MC_HDLC_POS:
539           phtonl(&erf_subhdr[0], pseudo_header->erf.subhdr.mc_hdr);
540           subhdr_size += (int)sizeof(struct erf_mc_hdr);
541           break;
542         case ERF_TYPE_ETH:
543         case ERF_TYPE_COLOR_ETH:
544         case ERF_TYPE_DSM_COLOR_ETH:
545           phtons(&erf_subhdr[0], pseudo_header->erf.subhdr.eth_hdr);
546           subhdr_size += (int)sizeof(struct erf_eth_hdr);
547           break;
548         default:
549           break;
550       }
551       break;
552     default:
553       return FALSE;
554
555   }
556   if (!wftap_dump_file_write(wdh, erf_hdr, size, err))
557     return FALSE;
558   wdh->bytes_dumped += size;
559
560   /*write out up to MAX_ERF_EHDR extension headers*/
561   has_more = pseudo_header->erf.phdr.type & 0x80;
562   if(has_more){  /*we have extension headers*/
563     do{
564       phtonll(ehdr+(i*8), pseudo_header->erf.ehdr_list[i].ehdr);
565       if(i == MAX_ERF_EHDR-1) ehdr[i*8] = ehdr[i*8] & 0x7F;
566       has_more = ehdr[i*8] & 0x80;
567       i++;
568     }while(has_more && i < MAX_ERF_EHDR);
569     if (!wftap_dump_file_write(wdh, ehdr, 8*i, err))
570       return FALSE;
571     wdh->bytes_dumped += 8*i;
572   }
573
574   if(!wftap_dump_file_write(wdh, erf_subhdr, subhdr_size, err))
575     return FALSE;
576   wdh->bytes_dumped += subhdr_size;
577
578   return TRUE;
579 }
580
581 static gboolean erf_dump(
582     wftap_dumper                   *wdh,
583     const struct wtap_pkthdr       *phdr,
584     const guint8                   *pd,
585     int                            *err)
586 {
587   const union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
588   union wtap_pseudo_header other_phdr;
589   int      encap;
590   gint64   alignbytes   = 0;
591   int      i;
592   int      round_down   = 0;
593   gboolean must_add_crc = FALSE;
594   guint32  crc32        = 0x00000000;
595
596   /* Don't write anything bigger than we're willing to read. */
597   if(phdr->caplen > WTAP_MAX_PACKET_SIZE) {
598     *err = WTAP_ERR_PACKET_TOO_LARGE;
599     return FALSE;
600   }
601
602   if(wdh->encap == WTAP_ENCAP_PER_PACKET){
603     encap = phdr->pkt_encap;
604   }else{
605     encap = wdh->encap;
606   }
607
608   if(encap == WTAP_ENCAP_ERF){
609     /* We've been handed an ERF record, so there's not much to do here. */
610     alignbytes = wdh->bytes_dumped + pseudo_header->erf.phdr.rlen;
611
612     if(!erf_write_phdr(wdh, encap, pseudo_header, err)) return FALSE;
613
614     if(!wftap_dump_file_write(wdh, pd, phdr->caplen, err)) return FALSE;
615     wdh->bytes_dumped += phdr->caplen;
616
617     /*XXX: this pads the record to its original length, which is fine in most
618      * cases. However with >MAX_ERF_EHDR unnecessary padding will be added, and
619      * if the record was truncated this will be incorrectly treated as payload.
620      * More than 8 extension headers is unusual though, only the first 8 are
621      * written out anyway and fixing properly would require major refactor.*/
622     while(wdh->bytes_dumped < alignbytes){
623       if(!wftap_dump_file_write(wdh, "", 1, err)) return FALSE;
624       wdh->bytes_dumped++;
625     }
626     return TRUE;
627   }
628
629   /*generate a fake header in other_phdr using data that we know*/
630   /*covert time erf timestamp format*/
631   other_phdr.erf.phdr.ts = ((guint64) phdr->ts.secs << 32) + (((guint64) phdr->ts.nsecs <<32) / 1000 / 1000 / 1000);
632   other_phdr.erf.phdr.type = wtap_wtap_encap_to_erf_encap(encap);
633   other_phdr.erf.phdr.flags = 0x4;  /*vlen flag set because we're creating variable length records*/
634   other_phdr.erf.phdr.lctr = 0;
635   /*now we work out rlen, accounting for all the different headers and missing fcs(eth)*/
636   other_phdr.erf.phdr.rlen = phdr->caplen+16;
637   other_phdr.erf.phdr.wlen = phdr->len;
638   switch(other_phdr.erf.phdr.type){
639     case ERF_TYPE_ETH:
640       other_phdr.erf.phdr.rlen += 2;  /*2 bytes for erf eth_type*/
641       if (pseudo_header->eth.fcs_len != 4) {
642         /* Either this packet doesn't include the FCS
643            (pseudo_header->eth.fcs_len = 0), or we don't
644            know whether it has an FCS (= -1).  We have to
645            synthesize an FCS.*/
646          if(!(phdr->caplen < phdr->len)){ /*don't add FCS if packet has been snapped off*/
647           crc32 = crc32_ccitt_seed(pd, phdr->caplen, 0xFFFFFFFF);
648           other_phdr.erf.phdr.rlen += 4;  /*4 bytes for added checksum*/
649           other_phdr.erf.phdr.wlen += 4;
650           must_add_crc = TRUE;
651         }
652       }
653       break;
654     case ERF_TYPE_HDLC_POS:
655       /*we assume that it's missing a FCS checksum, make one up*/
656       if(!(phdr->caplen < phdr->len)){  /*unless of course, the packet has been snapped off*/
657         crc32 = crc32_ccitt_seed(pd, phdr->caplen, 0xFFFFFFFF);
658         other_phdr.erf.phdr.rlen += 4;  /*4 bytes for added checksum*/
659         other_phdr.erf.phdr.wlen += 4;
660         must_add_crc = TRUE; /* XXX - these never have an FCS? */
661       }
662       break;
663     default:
664       break;
665   }
666
667   alignbytes = (8 - (other_phdr.erf.phdr.rlen % 8)) % 8;  /*calculate how much padding will be required */
668   if(phdr->caplen < phdr->len){ /*if packet has been snapped, we need to round down what we output*/
669     round_down = (8 - (guint)alignbytes) % 8;
670     other_phdr.erf.phdr.rlen -= round_down;
671   }else{
672     other_phdr.erf.phdr.rlen += (gint16)alignbytes;
673   }
674
675   if(!erf_write_phdr(wdh, WTAP_ENCAP_ERF, &other_phdr, err)) return FALSE;
676   if(!wftap_dump_file_write(wdh, pd, phdr->caplen - round_down, err)) return FALSE;
677   wdh->bytes_dumped += phdr->caplen - round_down;
678
679   /*add the 4 byte CRC if necessary*/
680   if(must_add_crc){
681     if(!wftap_dump_file_write(wdh, &crc32, 4, err)) return FALSE;
682     wdh->bytes_dumped += 4;
683   }
684   /*records should be 8byte aligned, so we add padding*/
685   if(round_down == 0){
686     for(i = (gint16)alignbytes; i > 0; i--){
687       if(!wftap_dump_file_write(wdh, "", 1, err)) return FALSE;
688       wdh->bytes_dumped++;
689     }
690   }
691
692   return TRUE;
693 }
694
695 int erf_dump_can_write_encap(int encap)
696 {
697
698   if(encap == WTAP_ENCAP_PER_PACKET)
699     return 0;
700
701   if (wtap_wtap_encap_to_erf_encap(encap) == -1)
702     return WTAP_ERR_UNSUPPORTED_ENCAP;
703
704   return 0;
705 }
706
707 int erf_dump_open(wftap_dumper *wdh, int *err)
708 {
709   wdh->subtype_write = erf_dump;
710   wdh->subtype_close = NULL;
711
712   switch(wdh->file_type_subtype){
713     case WTAP_FILE_TYPE_SUBTYPE_ERF:
714       wdh->tsprecision = WTAP_FILE_TSPREC_NSEC;
715       break;
716     default:
717       *err = WTAP_ERR_UNSUPPORTED_FILE_TYPE;
718       return FALSE;
719       break;
720   }
721
722   return TRUE;
723 }
724
725 int erf_populate_interfaces(wtap *wth)
726 {
727   wtapng_if_descr_t int_data;
728   int i;
729
730   if (!wth)
731     return -1;
732
733   if (!wth->interface_data) {
734     wth->interface_data = g_array_new(FALSE, FALSE, sizeof(wtapng_if_descr_t));
735   }
736
737   memset(&int_data, 0, sizeof(int_data)); /* Zero all fields */
738
739   int_data.wtap_encap = WTAP_ENCAP_ERF;
740   /* int_data.time_units_per_second = (1LL<<32);  ERF format resolution is 2^-32, capture resolution is unknown */
741   int_data.time_units_per_second = 1000000000; /* XXX Since Wireshark only supports down to nanosecond resolution we have to dilute to this */
742   int_data.link_type = wtap_wtap_encap_to_pcap_encap(WTAP_ENCAP_ERF);
743   int_data.snap_len = 65535; /* ERF max length */
744   int_data.opt_comment = NULL;
745   /* XXX: if_IPv4addr opt 4  Interface network address and netmask.*/
746   /* XXX: if_IPv6addr opt 5  Interface network address and prefix length (stored in the last byte).*/
747   /* XXX: if_MACaddr  opt 6  Interface Hardware MAC address (48 bits).*/
748   /* XXX: if_EUIaddr  opt 7  Interface Hardware EUI address (64 bits)*/
749   int_data.if_speed = 0; /* Unknown */
750   /* int_data.if_tsresol = 0xa0;  ERF format resolution is 2^-32 = 0xa0, capture resolution is unknown */
751   int_data.if_tsresol = 0x09; /* XXX Since Wireshark only supports down to nanosecond resolution we have to dilute to this */
752   /* XXX: if_tzone      10  Time zone for GMT support (TODO: specify better). */
753   int_data.if_filter_str = NULL;
754   int_data.bpf_filter_len = 0;
755   int_data.if_filter_bpf_bytes = NULL;
756   int_data.if_os = NULL;
757   int_data.if_fcslen = 0; /* unknown! */
758   /* XXX if_tsoffset; opt 14  A 64 bits integer value that specifies an offset (in seconds)...*/
759   /* Interface statistics */
760   int_data.num_stat_entries = 0;
761   int_data.interface_statistics = NULL;
762
763   /* Preemptively create interface entries for 4 interfaces, since this is the max number in ERF */
764   for (i=0; i<4; i++) {
765     int_data.if_name = g_strdup_printf("Port %c", 'A'+i);
766     int_data.if_description = g_strdup_printf("ERF Interface Id %d (Port %c)", i, 'A'+i);
767
768     g_array_append_val(wth->interface_data, int_data);
769     wth->number_of_interfaces++;
770   }
771
772   return 0;
773 }