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