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