From Stephen Donnelly via https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=7266 :
[metze/wireshark/wip.git] / wiretap / erf.c
1 /*
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  * $Id$
35  */
36
37 /*
38  * erf - Endace ERF (Extensible Record Format)
39  *
40  * See
41  *
42  *      http://www.endace.com/support/EndaceRecordFormat.pdf
43  */
44
45 #ifdef HAVE_CONFIG_H
46 #include "config.h"
47 #endif
48
49 #include <stdlib.h>
50 #include <string.h>
51
52 #include <glib.h>
53
54 #include <wsutil/crc32.h>
55
56 #include "wtap-int.h"
57 #include "file_wrappers.h"
58 #include "buffer.h"
59 #include "pcap-encap.h"
60 #include "atm.h"
61 #include "erf.h"
62
63 static int erf_read_header(FILE_T fh,
64                            struct wtap_pkthdr *phdr,
65                            union wtap_pseudo_header *pseudo_header,
66                            erf_header_t *erf_header,
67                            int *err,
68                            gchar **err_info,
69                            guint32 *bytes_read,
70                            guint32 *packet_size);
71 static gboolean erf_read(wtap *wth, int *err, gchar **err_info,
72                          gint64 *data_offset);
73 static gboolean erf_seek_read(wtap *wth, gint64 seek_off,
74                               union wtap_pseudo_header *pseudo_header, guint8 *pd,
75                               int length, int *err, gchar **err_info);
76
77 static const struct {
78   int erf_encap_value;
79   int wtap_encap_value;
80 } erf_to_wtap_map[] = {
81   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_CHDLC },
82   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_HHDLC },
83   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_CHDLC_WITH_PHDR },
84   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_PPP },
85   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_FRELAY },
86   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_MTP2 },
87   { ERF_TYPE_ETH,       WTAP_ENCAP_ETHERNET },
88   { 99,       WTAP_ENCAP_ERF }, /*this type added so WTAP_ENCAP_ERF will work and then be treated at ERF->ERF*/
89 };
90
91 #define NUM_ERF_ENCAPS (sizeof erf_to_wtap_map / sizeof erf_to_wtap_map[0])
92
93 extern int erf_open(wtap *wth, int *err, gchar **err_info)
94 {
95   int              i, n, records_for_erf_check = RECORDS_FOR_ERF_CHECK;
96   int              valid_prev                  = 0;
97   char            *s;
98   erf_timestamp_t  prevts,ts;
99   erf_header_t     header;
100   guint32          mc_hdr;
101   guint16          eth_hdr;
102   guint32          packet_size;
103   guint16          rlen;
104   guint64          erf_ext_header;
105   guint8           type;
106   size_t           r;
107   gchar *          buffer;
108
109   memset(&prevts, 0, sizeof(prevts));
110
111   /* number of records to scan before deciding if this really is ERF */
112   if ((s = getenv("ERF_RECORDS_TO_CHECK")) != NULL) {
113     if ((n = atoi(s)) > 0 && n < 101) {
114       records_for_erf_check = n;
115     }
116   }
117
118   /*
119    * ERF is a little hard because there's no magic number; we look at
120    * the first few records and see if they look enough like ERF
121    * records.
122    */
123
124   for (i = 0; i < records_for_erf_check; i++) {  /* records_for_erf_check */
125
126     r = file_read(&header,sizeof(header),wth->fh);
127
128     if (r == 0 ) break;
129     if (r != sizeof(header)) {
130       if ((*err = file_error(wth->fh, err_info)) != 0) {
131         return -1;
132       } else {
133         /* ERF header too short accept the file,
134            only if the very first records have been successfully checked */
135         if (i < MIN_RECORDS_FOR_ERF_CHECK) {
136           return 0;
137         } else {
138           /* BREAK, the last record is too short, and will be ignored */
139           break;
140         }
141       }
142     }
143
144     rlen=g_ntohs(header.rlen);
145
146     /* fail on invalid record type, invalid rlen, timestamps decreasing, or incrementing too far */
147
148     /* Test valid rlen >= 16 */
149     if (rlen < 16) {
150       return 0;
151     }
152
153     packet_size = rlen - (guint32)sizeof(header);
154     if (packet_size > WTAP_MAX_PACKET_SIZE) {
155       /*
156        * Probably a corrupt capture file or a file that's not an ERF file
157        * but that passed earlier tests; don't blow up trying
158        * to allocate space for an immensely-large packet.
159        */
160       return 0;
161     }
162
163     /* Skip PAD records, timestamps may not be set */
164     if ((header.type & 0x7F) == ERF_TYPE_PAD) {
165       if (file_seek(wth->fh, packet_size, SEEK_CUR, err) == -1) {
166         return -1;
167       }
168       continue;
169     }
170
171     /* fail on invalid record type, decreasing timestamps or non-zero pad-bits */
172     /* Not all types within this range are decoded, but it is a first filter */
173     if ((header.type & 0x7F) == 0 || (header.type & 0x7F) > ERF_TYPE_MAX ) {
174       return 0;
175     }
176
177     /* The ERF_TYPE_MAX is the PAD record, but the last used type is ERF_TYPE_INFINIBAND_LINK */
178     if ((header.type & 0x7F) > ERF_TYPE_INFINIBAND_LINK) {
179       return 0;
180     }
181
182     if ((ts = pletohll(&header.ts)) < prevts) {
183       /* 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 */
184       if ( ((prevts-ts)>>32) > 1 ) {
185         return 0;
186       }
187     }
188
189     /* Check to see if timestamp increment is > 1 week */
190     if ( (valid_prev) && (ts > prevts) && (((ts-prevts)>>32) > 3600*24*7) ) {
191       return 0;
192     }
193
194     memcpy(&prevts, &ts, sizeof(prevts));
195
196     /* Read over the extension headers */
197     type = header.type;
198     while (type & 0x80){
199       if (file_read(&erf_ext_header, sizeof(erf_ext_header),wth->fh) != sizeof(erf_ext_header)) {
200         *err = file_error(wth->fh, err_info);
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),wth->fh) != sizeof(mc_hdr)) {
219           *err = file_error(wth->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),wth->fh) != sizeof(eth_hdr)) {
228           *err = file_error(wth->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; don't blow up trying
242        * to allocate space for an immensely-large packet.
243        */
244       return 0;
245     }
246     buffer=(gchar *)g_malloc(packet_size);
247     r = file_read(buffer, packet_size, wth->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(wth->fh, 0L, SEEK_SET, err) == -1) {   /* rewind */
263     return -1;
264   }
265
266   /* This is an ERF file */
267   wth->file_type = WTAP_FILE_ERF;
268   wth->snapshot_length = 0;     /* not available in header, only in frame */
269
270   /*
271    * Use the encapsulation for ERF records.
272    */
273   wth->file_encap = WTAP_ENCAP_ERF;
274
275   wth->subtype_read = erf_read;
276   wth->subtype_seek_read = erf_seek_read;
277   wth->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(wtap *wth, int *err, gchar **err_info,
286                          gint64 *data_offset)
287 {
288   erf_header_t erf_header;
289   guint32      packet_size, bytes_read;
290
291   *data_offset = file_tell(wth->fh);
292
293   do {
294     if (!erf_read_header(wth->fh,
295                          &wth->phdr, &wth->pseudo_header, &erf_header,
296                          err, err_info, &bytes_read, &packet_size)) {
297       return FALSE;
298     }
299
300     buffer_assure_space(wth->frame_buffer, packet_size);
301
302     wtap_file_read_expected_bytes(buffer_start_ptr(wth->frame_buffer),
303                                   (gint32)(packet_size), wth->fh, err, err_info);
304
305   } while ( erf_header.type == ERF_TYPE_PAD );
306
307   return TRUE;
308 }
309
310 static gboolean erf_seek_read(wtap *wth, gint64 seek_off,
311                               union wtap_pseudo_header *pseudo_header, guint8 *pd,
312                               int length _U_, int *err, gchar **err_info)
313 {
314   erf_header_t erf_header;
315   guint32      packet_size;
316
317   if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
318     return FALSE;
319
320   do {
321     if (!erf_read_header(wth->random_fh, NULL, pseudo_header, &erf_header,
322                          err, err_info, NULL, &packet_size))
323       return FALSE;
324   } while ( erf_header.type == ERF_TYPE_PAD );
325
326   wtap_file_read_expected_bytes(pd, (int)packet_size, wth->random_fh, err,
327                                 err_info);
328
329   return TRUE;
330 }
331
332 static int erf_read_header(FILE_T fh,
333                            struct wtap_pkthdr *phdr,
334                            union wtap_pseudo_header *pseudo_header,
335                            erf_header_t *erf_header,
336                            int *err,
337                            gchar **err_info,
338                            guint32 *bytes_read,
339                            guint32 *packet_size)
340 {
341   guint32 mc_hdr;
342   guint8  erf_exhdr[8];
343   guint64 erf_exhdr_sw;
344   guint8  type    = 0;
345   guint16 eth_hdr;
346   guint32 skiplen = 0;
347   int     i       = 0;
348   int     max     = sizeof(pseudo_header->erf.ehdr_list)/sizeof(struct erf_ehdr);
349
350   wtap_file_read_expected_bytes(erf_header, sizeof(*erf_header), fh, err,
351                                 err_info);
352   if (bytes_read != NULL) {
353     *bytes_read = sizeof(*erf_header);
354   }
355
356   *packet_size =  g_ntohs(erf_header->rlen) - (guint32)sizeof(*erf_header);
357
358   if (*packet_size > WTAP_MAX_PACKET_SIZE) {
359     /*
360      * Probably a corrupt capture file; don't blow up trying
361      * to allocate space for an immensely-large packet.
362      */
363     *err = WTAP_ERR_BAD_FILE;
364     *err_info = g_strdup_printf("erf: File has %u-byte packet, bigger than maximum of %u",
365                                 *packet_size, WTAP_MAX_PACKET_SIZE);
366     return FALSE;
367   }
368
369   if (*packet_size == 0) {
370     /* If this isn't a pad record, it's a corrupt packet; bail out */
371     if ((erf_header->type & 0x7F) != ERF_TYPE_PAD) {
372       *err = WTAP_ERR_BAD_FILE;
373       *err_info = g_strdup_printf("erf: File has 0 byte packet");
374
375       return FALSE;
376     }
377   }
378
379   if (phdr != NULL) {
380     guint64 ts = pletohll(&erf_header->ts);
381
382     phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN|WTAP_HAS_INTERFACE_ID;
383     phdr->ts.secs = (long) (ts >> 32);
384     ts  = ((ts & 0xffffffff) * 1000 * 1000 * 1000);
385     ts += (ts & 0x80000000) << 1; /* rounding */
386     phdr->ts.nsecs = ((int) (ts >> 32));
387     if (phdr->ts.nsecs >= 1000000000) {
388       phdr->ts.nsecs -= 1000000000;
389       phdr->ts.secs += 1;
390     }
391     phdr->interface_id = (erf_header->flags & 0x03);
392   }
393
394   /* Copy the ERF pseudo header */
395   memset(&pseudo_header->erf, 0, sizeof(pseudo_header->erf));
396   pseudo_header->erf.phdr.ts = pletohll(&erf_header->ts);
397   pseudo_header->erf.phdr.type = erf_header->type;
398   pseudo_header->erf.phdr.flags = erf_header->flags;
399   pseudo_header->erf.phdr.rlen = g_ntohs(erf_header->rlen);
400   pseudo_header->erf.phdr.lctr = g_ntohs(erf_header->lctr);
401   pseudo_header->erf.phdr.wlen = g_ntohs(erf_header->wlen);
402
403   /* Copy the ERF extension header into the pseudo header */
404   type = erf_header->type;
405   while (type & 0x80){
406     wtap_file_read_expected_bytes(&erf_exhdr, sizeof(erf_exhdr), fh, err,
407                                   err_info);
408     if (bytes_read != NULL)
409       *bytes_read += (guint32)sizeof(erf_exhdr);
410     *packet_size -=  (guint32)sizeof(erf_exhdr);
411     skiplen += (guint32)sizeof(erf_exhdr);
412     erf_exhdr_sw = pntohll(erf_exhdr);
413     if (i < max)
414       memcpy(&pseudo_header->erf.ehdr_list[i].ehdr, &erf_exhdr_sw, sizeof(erf_exhdr_sw));
415     type = erf_exhdr[0];
416     i++;
417   }
418
419   switch (erf_header->type & 0x7F) {
420     case ERF_TYPE_IPV4:
421     case ERF_TYPE_IPV6:
422     case ERF_TYPE_RAW_LINK:
423     case ERF_TYPE_INFINIBAND:
424     case ERF_TYPE_INFINIBAND_LINK:
425 #if 0
426       if (phdr != NULL) {
427         phdr->len =  g_htons(erf_header->wlen);
428         phdr->caplen = g_htons(erf_header->wlen);
429       }
430       return TRUE;
431 #endif
432       break;
433     case ERF_TYPE_PAD:
434     case ERF_TYPE_HDLC_POS:
435     case ERF_TYPE_COLOR_HDLC_POS:
436     case ERF_TYPE_DSM_COLOR_HDLC_POS:
437     case ERF_TYPE_ATM:
438     case ERF_TYPE_AAL5:
439       break;
440
441     case ERF_TYPE_ETH:
442     case ERF_TYPE_COLOR_ETH:
443     case ERF_TYPE_DSM_COLOR_ETH:
444       wtap_file_read_expected_bytes(&eth_hdr, sizeof(eth_hdr), fh, err,
445                                     err_info);
446       if (bytes_read != NULL)
447         *bytes_read += (guint32)sizeof(eth_hdr);
448       *packet_size -=  (guint32)sizeof(eth_hdr);
449       skiplen += (guint32)sizeof(eth_hdr);
450       pseudo_header->erf.subhdr.eth_hdr = g_htons(eth_hdr);
451       break;
452
453     case ERF_TYPE_MC_HDLC:
454     case ERF_TYPE_MC_RAW:
455     case ERF_TYPE_MC_ATM:
456     case ERF_TYPE_MC_RAW_CHANNEL:
457     case ERF_TYPE_MC_AAL5:
458     case ERF_TYPE_MC_AAL2:
459     case ERF_TYPE_COLOR_MC_HDLC_POS:
460     case ERF_TYPE_AAL2: /* not an MC type but has a similar 'AAL2 ext' header */
461       wtap_file_read_expected_bytes(&mc_hdr, sizeof(mc_hdr), fh, err,
462                                     err_info);
463       if (bytes_read != NULL)
464         *bytes_read += (guint32)sizeof(mc_hdr);
465       *packet_size -=  (guint32)sizeof(mc_hdr);
466       skiplen += (guint32)sizeof(mc_hdr);
467       pseudo_header->erf.subhdr.mc_hdr = g_htonl(mc_hdr);
468       break;
469
470     case ERF_TYPE_IP_COUNTER:
471     case ERF_TYPE_TCP_FLOW_COUNTER:
472       /* unsupported, continue with default: */
473     default:
474       *err = WTAP_ERR_UNSUPPORTED_ENCAP;
475       *err_info = g_strdup_printf("erf: unknown record encapsulation %u",
476                                   erf_header->type);
477       return FALSE;
478   }
479
480   if (phdr != NULL) {
481     phdr->len = g_htons(erf_header->wlen);
482     phdr->caplen = MIN( g_htons(erf_header->wlen),
483                         g_htons(erf_header->rlen) - (guint32)sizeof(*erf_header) - skiplen );
484   }
485
486   if (*packet_size > WTAP_MAX_PACKET_SIZE) {
487     /*
488      * Probably a corrupt capture file; don't blow up trying
489      * to allocate space for an immensely-large packet.
490      */
491     *err = WTAP_ERR_BAD_FILE;
492     *err_info = g_strdup_printf("erf: File has %u-byte packet, bigger than maximum of %u",
493                                 *packet_size, WTAP_MAX_PACKET_SIZE);
494     return FALSE;
495   }
496
497   return TRUE;
498 }
499
500 static int wtap_wtap_encap_to_erf_encap(int encap)
501 {
502   unsigned int i;
503   for(i = 0; i < NUM_ERF_ENCAPS; i++){
504     if(erf_to_wtap_map[i].wtap_encap_value == encap)
505       return erf_to_wtap_map[i].erf_encap_value;
506   }
507   return -1;
508 }
509
510 static gboolean erf_write_phdr(wtap_dumper *wdh, int encap, const union wtap_pseudo_header *pseudo_header, int * err)
511 {
512   guint8 erf_hdr[sizeof(struct erf_mc_phdr)];
513   guint8 erf_subhdr[((sizeof(struct erf_mc_hdr) > sizeof(struct erf_eth_hdr))?
514     sizeof(struct erf_mc_hdr) : sizeof(struct erf_eth_hdr))];
515   guint8 ehdr[8*MAX_ERF_EHDR];
516   size_t size        = 0;
517   size_t subhdr_size = 0;
518   int    i           = 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 (!wtap_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   if((pseudo_header->erf.phdr.type & 0x80) != 0){  /*we have extension headers*/
562     do{
563       phtonll(ehdr+(i*8), pseudo_header->erf.ehdr_list[i].ehdr);
564       if(i == MAX_ERF_EHDR-1) ehdr[i*8] = ehdr[i*8] & 0x7F;
565       i++;
566     }while((ehdr[0] & 0x80) != 0 && i < MAX_ERF_EHDR);
567     if (!wtap_dump_file_write(wdh, ehdr, MAX_ERF_EHDR*i, err))
568       return FALSE;
569     wdh->bytes_dumped += MAX_ERF_EHDR*i;
570   }
571
572   if(!wtap_dump_file_write(wdh, erf_subhdr, subhdr_size, err))
573     return FALSE;
574   wdh->bytes_dumped += subhdr_size;
575
576   return TRUE;
577 }
578
579 static gboolean erf_dump(
580     wtap_dumper                    *wdh,
581     const struct wtap_pkthdr       *phdr,
582     const union wtap_pseudo_header *pseudo_header,
583     const guint8                   *pd,
584     int                            *err)
585 {
586   union wtap_pseudo_header other_phdr;
587   int      encap;
588   gint64   alignbytes   = 0;
589   int      i;
590   int      round_down   = 0;
591   gboolean must_add_crc = FALSE;
592   guint32  crc32        = 0x00000000;
593
594   if(wdh->encap == WTAP_ENCAP_PER_PACKET){
595     encap = phdr->pkt_encap;
596   }else{
597     encap = wdh->encap;
598   }
599
600   switch(encap){
601     case WTAP_ENCAP_ERF:
602       alignbytes = wdh->bytes_dumped + pseudo_header->erf.phdr.rlen;
603
604       if(!erf_write_phdr(wdh, encap, pseudo_header, err)) return FALSE;
605
606       if(!wtap_dump_file_write(wdh, pd, phdr->caplen, err)) return FALSE;
607       wdh->bytes_dumped += phdr->caplen;
608
609       while(wdh->bytes_dumped < alignbytes){
610         if(!wtap_dump_file_write(wdh, "", 1, err)) return FALSE;
611         wdh->bytes_dumped++;
612       }
613       must_add_crc = TRUE; /* XXX - not if this came from an ERF file with an FCS! */
614       break;
615     default:  /*deal with generic wtap format*/
616       /*generate a fake header in other_phdr using data that we know*/
617       /*covert time erf timestamp format*/
618       other_phdr.erf.phdr.ts = ((guint64) phdr->ts.secs << 32) + (((guint64) phdr->ts.nsecs <<32) / 1000 / 1000 / 1000);
619       other_phdr.erf.phdr.type = wtap_wtap_encap_to_erf_encap(encap);
620       other_phdr.erf.phdr.flags = 0x4;  /*vlen flag set because we're creating variable length records*/
621       other_phdr.erf.phdr.lctr = 0;
622       /*now we work out rlen, accounting for all the different headers and missing fcs(eth)*/
623       other_phdr.erf.phdr.rlen = phdr->caplen+16;
624       other_phdr.erf.phdr.wlen = phdr->len;
625       switch(other_phdr.erf.phdr.type){
626         case ERF_TYPE_ETH:
627           other_phdr.erf.phdr.rlen += 2;  /*2 bytes for erf eth_type*/
628           if (pseudo_header->eth.fcs_len != 4) {
629             /* Either this packet doesn't include the FCS
630                (pseudo_header->eth.fcs_len = 0), or we don't
631                know whether it has an FCS (= -1).  We have to
632                synthesize an FCS.*/
633
634             if(!(phdr->caplen < phdr->len)){ /*don't add FCS if packet has been snapped off*/
635               crc32 = crc32_ccitt_seed(pd, phdr->caplen, 0xFFFFFFFF);
636               other_phdr.erf.phdr.rlen += 4;  /*4 bytes for added checksum*/
637               other_phdr.erf.phdr.wlen += 4;
638               must_add_crc = TRUE;
639             }
640           }
641           break;
642         case ERF_TYPE_HDLC_POS:
643           /*we assume that it's missing a FCS checksum, make one up*/
644           if(!(phdr->caplen < phdr->len)){  /*unless of course, the packet has been snapped off*/
645             crc32 = crc32_ccitt_seed(pd, phdr->caplen, 0xFFFFFFFF);
646             other_phdr.erf.phdr.rlen += 4;  /*4 bytes for added checksum*/
647             other_phdr.erf.phdr.wlen += 4;
648             must_add_crc = TRUE; /* XXX - these never have an FCS? */
649           }
650           break;
651         default:
652           break;
653       }
654
655       alignbytes = (8 - (other_phdr.erf.phdr.rlen % 8)) % 8;  /*calculate how much padding will be required */
656       if(phdr->caplen < phdr->len){ /*if packet has been snapped, we need to round down what we output*/
657         round_down = (8 - alignbytes) % 8;
658         other_phdr.erf.phdr.rlen -= round_down;
659       }else{
660         other_phdr.erf.phdr.rlen += (gint16)alignbytes;
661       }
662
663       if(!erf_write_phdr(wdh, WTAP_ENCAP_ERF, &other_phdr, err)) return FALSE;
664       if(!wtap_dump_file_write(wdh, pd, phdr->caplen - round_down, err)) return FALSE;
665       wdh->bytes_dumped += phdr->caplen - round_down;
666
667       /*add the 4 byte CRC if necessary*/
668       if(must_add_crc){
669         if(!wtap_dump_file_write(wdh, &crc32, 4, err)) return FALSE;
670         wdh->bytes_dumped += 4;
671       }
672       /*records should be 8byte aligned, so we add padding*/
673       if(round_down == 0){
674         for(i = (gint16)alignbytes; i > 0; i--){
675           if(!wtap_dump_file_write(wdh, "", 1, err)) return FALSE;
676           wdh->bytes_dumped++;
677         }
678       }
679
680       break;
681   }
682
683   return TRUE;
684 }
685
686 int erf_dump_can_write_encap(int encap)
687 {
688
689   if(encap == WTAP_ENCAP_PER_PACKET)
690     return 0;
691
692   if (wtap_wtap_encap_to_erf_encap(encap) == -1)
693     return WTAP_ERR_UNSUPPORTED_ENCAP;
694
695   return 0;
696 }
697
698 int erf_dump_open(wtap_dumper *wdh, int *err)
699 {
700   wdh->subtype_write = erf_dump;
701   wdh->subtype_close = NULL;
702
703   switch(wdh->file_type){
704     case WTAP_FILE_ERF:
705       wdh->tsprecision = WTAP_FILE_TSPREC_NSEC;
706       break;
707     default:
708       *err = WTAP_ERR_UNSUPPORTED_FILE_TYPE;
709       return FALSE;
710       break;
711   }
712
713   return TRUE;
714 }
715
716 int erf_populate_interfaces(wtap *wth)
717 {
718   wtapng_if_descr_t int_data;
719   int i;
720
721   if (!wth)
722     return -1;
723
724   if (!wth->interface_data) {
725     wth->interface_data = g_array_new(FALSE, FALSE, sizeof(wtapng_if_descr_t));
726   }
727
728   memset(&int_data, 0, sizeof(int_data)); /* Zero all fields */
729
730   int_data.wtap_encap = WTAP_ENCAP_ERF;
731   /* int_data.time_units_per_second = (1LL<<32);  ERF format resolution is 2^-32, capture resolution is unknown */
732   int_data.time_units_per_second = 1000000000; /* XXX Since Wireshark only supports down to nanosecond resolution we have to dilute to this */
733   int_data.link_type = wtap_wtap_encap_to_pcap_encap(WTAP_ENCAP_ERF);
734   int_data.snap_len = 65535; /* ERF max length */
735   int_data.opt_comment = NULL;
736   /* XXX: if_IPv4addr opt 4  Interface network address and netmask.*/
737   /* XXX: if_IPv6addr opt 5  Interface network address and prefix length (stored in the last byte).*/
738   /* XXX: if_MACaddr  opt 6  Interface Hardware MAC address (48 bits).*/
739   /* XXX: if_EUIaddr  opt 7  Interface Hardware EUI address (64 bits)*/
740   int_data.if_speed = 0; /* Unknown */
741   /* int_data.if_tsresol = 0xa0;  ERF format resolution is 2^-32 = 0xa0, capture resolution is unknown */
742   int_data.if_tsresol = 0x09; /* XXX Since Wireshark only supports down to nanosecond resolution we have to dilute to this */
743   /* XXX: if_tzone      10  Time zone for GMT support (TODO: specify better). */
744   int_data.if_filter_str = NULL;
745   int_data.bpf_filter_len = 0;
746   int_data.if_filter_bpf_bytes = NULL;
747   int_data.if_os = NULL;
748   int_data.if_fcslen = 0; /* unknown! */
749   /* XXX if_tsoffset; opt 14  A 64 bits integer value that specifies an offset (in seconds)...*/
750   /* Interface statistics */
751   int_data.num_stat_entries = 0;
752   int_data.interface_statistics = NULL;
753
754   /* Preemptively create interface entries for 4 interfaces, since this is the max number in ERF */
755   for (i=0; i<4; i++) {
756     int_data.if_name = g_strdup_printf("Port %c", 'A'+i);
757     int_data.if_description = g_strdup_printf("ERF Interface Id %d (Port %c)", i, 'A'+i);
758
759     g_array_append_val(wth->interface_data, int_data);
760     wth->number_of_interfaces++;
761   }
762
763   return 0;
764 }