tests: add regression tests for Follow TCP Stream
[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  * SPDX-License-Identifier: BSD-3-Clause
10  */
11
12 /*
13  * erf - Endace ERF (Extensible Record Format)
14  *
15  * See
16  *
17  *      http://www.endace.com/support/EndaceRecordFormat.pdf
18  *      (mirror: https://bugs.wireshark.org/bugzilla/attachment.cgi?id=4333) (bug #4484)
19  */
20
21 #include "config.h"
22
23 #include <stdlib.h>
24 #include <string.h>
25
26 #include <glib.h>
27
28 #include <wsutil/crc32.h>
29 #include <wsutil/strtoi.h>
30
31 #include "wtap-int.h"
32 #include "file_wrappers.h"
33 #include "pcap-encap.h"
34 #include "pcapng.h"
35 #include "erf.h"
36
37 struct erf_anchor_mapping {
38   guint64 host_id;
39   guint64 anchor_id;
40   guint64 gen_time;
41   gchar *comment;
42 };
43
44 static const guint erf_header_size = (guint)sizeof(erf_header_t);
45 static const guint erf_mc_header_size = (guint)sizeof(erf_mc_header_t);
46 static const guint erf_eth_hdr_size = (guint)sizeof(erf_eth_header_t);
47
48
49 static gboolean erf_read_header(wtap *wth, FILE_T fh,
50                                 wtap_rec *rec,
51                                 erf_header_t *erf_header,
52                                 int *err,
53                                 gchar **err_info,
54                                 guint32 *bytes_read,
55                                 guint32 *packet_size,
56                                 GPtrArray *anchor_mappings_to_update);
57 static gboolean erf_read(wtap *wth, int *err, gchar **err_info,
58                          gint64 *data_offset);
59 static gboolean erf_seek_read(wtap *wth, gint64 seek_off,
60                               wtap_rec *rec, Buffer *buf,
61                               int *err, gchar **err_info);
62 static void erf_close(wtap *wth);
63
64 static int populate_summary_info(erf_t *erf_priv, wtap *wth, union wtap_pseudo_header *pseudo_header, guint32 packet_size, GPtrArray *anchor_mappings_to_update);
65 static int erf_update_anchors_from_header(erf_t *erf_priv, wtap_rec *rec, union wtap_pseudo_header *pseudo_header, guint64 host_id, GPtrArray *anchor_mappings_to_update);
66
67 typedef struct {
68   gboolean write_next_extra_meta;
69   gboolean last_meta_periodic;
70   guint64 host_id;
71   guint64 implicit_host_id;
72   guint64 prev_frame_ts;
73   guint8 prev_erf_type;
74   guint64 gen_time;
75   time_t first_frame_time_sec;
76   time_t prev_inserted_time_sec;
77   gchar* user_comment_ptr;
78   GPtrArray* periodic_sections;
79   GArray *periodic_extra_ehdrs;
80   GRand *rand;
81 } erf_dump_t;
82
83 erf_dump_t* erf_dump_priv_create(void);
84 static void erf_dump_priv_free(erf_dump_t *dump_priv);
85 static gboolean erf_dump_priv_compare_capture_comment(wtap_dumper *wdh, erf_dump_t *dump_priv,const union wtap_pseudo_header *pseudo_header, const guint8 *pd);
86 static gboolean erf_comment_to_sections(wtap_dumper *wdh, guint16 section_type, guint16 section_id, gchar *comment, GPtrArray *sections);
87 static gboolean erf_wtap_info_to_sections(wtap_dumper *wdh, GPtrArray *sections);
88 static gboolean get_user_comment_string(wtap_dumper *wdh, gchar** user_comment_ptr);
89
90 static gboolean erf_write_meta_record(wtap_dumper *wdh, erf_dump_t *dump_priv, guint64 timestamp, GPtrArray *sections, GArray *extra_ehdrs, int *err);
91
92 static const struct {
93   int erf_encap_value;
94   int wtap_encap_value;
95 } erf_to_wtap_map[] = {
96   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_CHDLC },
97   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_HHDLC },
98   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_CHDLC_WITH_PHDR },
99   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_PPP },
100   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_FRELAY },
101   { ERF_TYPE_HDLC_POS,  WTAP_ENCAP_MTP2 },
102   { ERF_TYPE_ETH,       WTAP_ENCAP_ETHERNET },
103   { 99,       WTAP_ENCAP_ERF }, /*this type added so WTAP_ENCAP_ERF will work and then be treated at ERF->ERF*/
104 };
105
106 #define NUM_ERF_ENCAPS (sizeof erf_to_wtap_map / sizeof erf_to_wtap_map[0])
107
108 #define ERF_META_TAG_HEADERLEN 4
109 #define ERF_META_TAG_TOTAL_ALIGNED_LENGTH(taglength)  ((((guint32)taglength + 0x3U) & ~0x3U) + ERF_META_TAG_HEADERLEN)
110 #define ERF_META_TAG_ALIGNED_LENGTH(taglength)  ((((guint32)taglength + 0x3U) & ~0x3U))
111 #define ERF_PADDING_TO_8(len) ((8 - len % 8) % 8)
112
113 struct erf_if_info {
114   int if_index;
115   gchar *name;
116   gchar *descr;
117   int stream_num;
118   struct {
119     guint filter:1;
120     guint fcs_len:1;
121     guint snaplen:1;
122   } set_flags;
123 };
124
125 struct erf_if_mapping {
126   guint64 host_id;
127   guint8 source_id;
128   struct erf_if_info interfaces[4];
129
130   gchar *module_filter_str;
131   /*here because we could have captures from multiple hosts in the file*/
132   gchar *capture_filter_str;
133   gint8 module_fcs_len;
134   guint32 module_snaplen;
135   int interface_metadata;
136   guint64 interface_gentime;
137   guint64 module_gentime;
138 };
139
140 struct erf_meta_section {
141   guint16 type;
142   guint16 section_id;
143   guint16 section_length;
144   GPtrArray *tags;
145 };
146
147 struct erf_meta_tag {
148   guint16 type;
149   guint16 length;
150   guint8 *value;
151 };
152
153 struct erf_meta_read_state {
154   guint8 *tag_ptr;
155   guint32 remaining_len;
156
157   struct erf_if_mapping *if_map;
158
159   guint16 sectiontype;
160   guint16 sectionid;
161   guint16 parentsectiontype;
162   guint16 parentsectionid;
163
164   guint64 gen_time;
165
166   int interface_metadata;
167 };
168
169 static gboolean erf_wtap_blocks_to_erf_sections(wtap_block_t block, GPtrArray *sections, guint16 section_type, guint16 section_id, wtap_block_foreach_func func);
170
171 static guint32 erf_meta_read_tag(struct erf_meta_tag*, guint8*, guint32);
172
173 static guint erf_anchor_mapping_hash(gconstpointer key) {
174   const struct erf_anchor_mapping *anchor_map = (const struct erf_anchor_mapping*) key;
175
176   return ((guint32)anchor_map->host_id ^ (guint32)anchor_map->anchor_id);
177
178 }
179
180 static gboolean erf_anchor_mapping_equal(gconstpointer a, gconstpointer b) {
181   const struct erf_anchor_mapping *anchor_map_a = (const struct erf_anchor_mapping*) a ;
182   const struct erf_anchor_mapping *anchor_map_b = (const struct erf_anchor_mapping*) b ;
183
184   return (anchor_map_a->host_id) == (anchor_map_b->host_id) &&
185     (anchor_map_a->anchor_id & ERF_EXT_HDR_TYPE_ANCHOR_ID) == (anchor_map_b->anchor_id & ERF_EXT_HDR_TYPE_ANCHOR_ID);
186 }
187
188 static void erf_anchor_mapping_destroy(gpointer key) {
189   struct erf_anchor_mapping *anchor_map = (struct erf_anchor_mapping*) key;
190
191   if(anchor_map->comment != NULL) {
192     g_free(anchor_map->comment);
193     anchor_map->comment = NULL;
194   }
195   g_free(anchor_map);
196   anchor_map = NULL;
197 }
198
199 static gboolean erf_if_mapping_equal(gconstpointer a, gconstpointer b)
200 {
201   const struct erf_if_mapping *if_map_a = (const struct erf_if_mapping*) a;
202   const struct erf_if_mapping *if_map_b = (const struct erf_if_mapping*) b;
203
204   return if_map_a->source_id == if_map_b->source_id && if_map_a->host_id == if_map_b->host_id;
205 }
206
207 static guint erf_if_mapping_hash(gconstpointer key)
208 {
209   const struct erf_if_mapping *if_map = (const struct erf_if_mapping*) key;
210
211   return (((guint) if_map->host_id) << 16) | if_map->source_id;
212 }
213
214 static void erf_if_mapping_destroy(gpointer key)
215 {
216   int i = 0;
217   struct erf_if_mapping *if_map = (struct erf_if_mapping*) key;
218
219   for (i = 0; i < 4; i++) {
220     g_free(if_map->interfaces[i].name);
221     g_free(if_map->interfaces[i].descr);
222   }
223
224   g_free(if_map->module_filter_str);
225   g_free(if_map);
226 }
227
228 static struct erf_if_mapping* erf_if_mapping_create(guint64 host_id, guint8 source_id)
229 {
230   int i = 0;
231   struct erf_if_mapping *if_map = NULL;
232
233   if_map = (struct erf_if_mapping*) g_malloc0(sizeof(struct erf_if_mapping));
234
235   if_map->host_id = host_id;
236   if_map->source_id = source_id;
237
238   for (i = 0; i < 4; i++) {
239     if_map->interfaces[i].if_index = -1;
240     if_map->interfaces[i].stream_num = -1;
241   }
242
243   if_map->module_fcs_len = -1;
244   if_map->module_snaplen = (guint32) -1;
245   /* everything else 0 by g_malloc0*/
246
247   return if_map;
248 }
249
250
251 erf_t *erf_priv_create(void)
252 {
253   erf_t *erf_priv;
254
255   erf_priv = (erf_t*) g_malloc(sizeof(erf_t));
256   erf_priv->anchor_map = g_hash_table_new_full(erf_anchor_mapping_hash, erf_anchor_mapping_equal, erf_anchor_mapping_destroy, NULL);
257   erf_priv->if_map = g_hash_table_new_full(erf_if_mapping_hash, erf_if_mapping_equal, erf_if_mapping_destroy, NULL);
258   erf_priv->implicit_host_id = ERF_META_HOST_ID_IMPLICIT;
259   erf_priv->capture_gentime = 0;
260   erf_priv->host_gentime = 0;
261
262   return erf_priv;
263 }
264
265 erf_t* erf_priv_free(erf_t* erf_priv)
266 {
267   if (erf_priv)
268   {
269     g_hash_table_destroy(erf_priv->anchor_map);
270     g_hash_table_destroy(erf_priv->if_map);
271     g_free(erf_priv);
272   }
273
274   return NULL;
275 }
276
277 static void erf_dump_priv_free(erf_dump_t *dump_priv) {
278   if(dump_priv) {
279     if(dump_priv->periodic_sections) {
280       g_ptr_array_free(dump_priv->periodic_sections, TRUE);
281     }
282     if(dump_priv->periodic_extra_ehdrs) {
283       g_array_free(dump_priv->periodic_extra_ehdrs, TRUE);
284     }
285     if(dump_priv->user_comment_ptr) {
286       g_free(dump_priv->user_comment_ptr);
287     }
288
289     g_free(dump_priv->rand);
290
291     g_free(dump_priv);
292   }
293
294 }
295
296 static void erf_meta_section_free(gpointer data) {
297   struct erf_meta_section *section_ptr = (struct erf_meta_section*) data;
298   if (section_ptr) {
299     g_ptr_array_free(section_ptr->tags, TRUE);
300     section_ptr->tags = NULL;
301   }
302   g_free(section_ptr);
303 }
304
305 static void erf_meta_tag_free(gpointer data) {
306   struct erf_meta_tag *tag_ptr = (struct erf_meta_tag*) data;
307   if (tag_ptr) {
308     g_free(tag_ptr->value);
309     tag_ptr->value = NULL;
310   }
311   g_free(tag_ptr);
312 }
313
314
315 static gboolean erf_dump_finish(struct wtap_dumper *wdh, int *err) {
316   erf_dump_t *dump_priv = (erf_dump_t*)wdh->priv;
317   gboolean ret = TRUE;
318
319   /* Write final metadata record. There are some corner cases where we should
320    * do this (file <1 second, last record was ERF_TYPE_META with an out of date
321    * comment) and there is no harm doing this always if we have already written
322    * some metadata. */
323   if(dump_priv->write_next_extra_meta) {
324     if (!dump_priv->periodic_sections) {
325       dump_priv->periodic_sections = g_ptr_array_new_with_free_func(erf_meta_section_free);
326       if (dump_priv->prev_erf_type == ERF_TYPE_META && dump_priv->last_meta_periodic) {
327         erf_comment_to_sections(wdh, ERF_META_SECTION_CAPTURE, 0, dump_priv->user_comment_ptr, dump_priv->periodic_sections);
328       } else {
329         /* If we get here, metadata record was not found in the first ~1 sec
330          * but we have either a capture comment or a non-ERF file (see
331          * erf_dump_open) */
332         erf_wtap_info_to_sections(wdh, dump_priv->periodic_sections);
333       }
334     }
335
336     if (!erf_write_meta_record(wdh, dump_priv, dump_priv->prev_frame_ts, dump_priv->periodic_sections, dump_priv->periodic_extra_ehdrs, err)) ret = FALSE;
337   }
338
339   /* Clean up */
340   erf_dump_priv_free(dump_priv);
341   /* Avoid double freeing by setting it to NULL*/
342   wdh->priv = NULL;
343
344   return ret;
345
346 }
347
348 static void
349 erf_free_data(gpointer data, gpointer user_data _U_)
350 {
351     g_free(data);
352 }
353
354
355 extern wtap_open_return_val erf_open(wtap *wth, int *err, gchar **err_info)
356 {
357   int              i, n, records_for_erf_check = RECORDS_FOR_ERF_CHECK;
358   int              valid_prev                  = 0;
359   char            *s;
360   erf_timestamp_t  prevts,ts;
361   erf_header_t     header;
362   guint32          mc_hdr;
363   struct erf_eth_hdr eth_hdr;
364   guint32          packet_size;
365   guint16          rlen;
366   guint64          erf_ext_header;
367   guint            erf_ext_header_size = (guint)sizeof(erf_ext_header);
368   guint8           type;
369
370   memset(&prevts, 0, sizeof(prevts));
371
372   /* number of records to scan before deciding if this really is ERF */
373   if ((s = getenv("ERF_RECORDS_TO_CHECK")) != NULL) {
374     if (ws_strtoi32(s, NULL, &n) && n >= 0 && n < 101) {
375       records_for_erf_check = n;
376     }
377   }
378
379   /*
380    * ERF is a little hard because there's no magic number; we look at
381    * the first few records and see if they look enough like ERF
382    * records.
383    */
384
385   for (i = 0; i < records_for_erf_check; i++) {  /* records_for_erf_check */
386
387     if (!wtap_read_bytes_or_eof(wth->fh,&header,erf_header_size,err,err_info)) {
388       if (*err == 0) {
389         /* EOF - all records have been successfully checked, accept the file */
390         break;
391       }
392       if (*err == WTAP_ERR_SHORT_READ) {
393         /* ERF header too short accept the file,
394            only if the very first records have been successfully checked */
395         if (i < MIN_RECORDS_FOR_ERF_CHECK) {
396           return WTAP_OPEN_NOT_MINE;
397         } else {
398           /* BREAK, the last record is too short, and will be ignored */
399           break;
400         }
401       } else {
402         return WTAP_OPEN_ERROR;
403       }
404     }
405
406     rlen=g_ntohs(header.rlen);
407
408     /* fail on invalid record type, invalid rlen, timestamps decreasing, or incrementing too far */
409
410     /* Test valid rlen >= 16 */
411     if (rlen < 16) {
412       return WTAP_OPEN_NOT_MINE;
413     }
414
415     packet_size = rlen - erf_header_size;
416     if (packet_size > WTAP_MAX_PACKET_SIZE_STANDARD) {
417       /*
418        * Probably a corrupt capture file or a file that's not an ERF file
419        * but that passed earlier tests.
420        */
421       return WTAP_OPEN_NOT_MINE;
422     }
423
424     /* Skip PAD records, timestamps may not be set */
425     if ((header.type & 0x7F) == ERF_TYPE_PAD) {
426       if (!wtap_read_bytes(wth->fh, NULL, packet_size, err, err_info)) {
427         if (*err != WTAP_ERR_SHORT_READ) {
428           /* A real error */
429           return WTAP_OPEN_ERROR;
430         }
431         /* ERF record too short, accept the file,
432            only if the very first records have been successfully checked */
433         if (i < MIN_RECORDS_FOR_ERF_CHECK) {
434           return WTAP_OPEN_NOT_MINE;
435         }
436       }
437       continue;
438     }
439
440     /* ERF Type 0 is reserved for ancient legacy records which are not supported, probably not ERF */
441     if ((header.type & 0x7F) == 0) {
442       return WTAP_OPEN_NOT_MINE;
443     }
444
445     /* fail on decreasing timestamps */
446     if ((ts = pletoh64(&header.ts)) < prevts) {
447       /* 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 */
448       if ( ((prevts-ts)>>32) > 1 ) {
449         return WTAP_OPEN_NOT_MINE;
450       }
451     }
452
453     /* Check to see if timestamp increment is > 1 week */
454     if ( (valid_prev) && (ts > prevts) && (((ts-prevts)>>32) > 3600*24*7) ) {
455       return WTAP_OPEN_NOT_MINE;
456     }
457
458     memcpy(&prevts, &ts, sizeof(prevts));
459
460     /* Read over the extension headers */
461     type = header.type;
462     while (type & 0x80){
463       if (!wtap_read_bytes(wth->fh,&erf_ext_header,erf_ext_header_size,err,err_info)) {
464         if (*err == WTAP_ERR_SHORT_READ) {
465           /* Extension header missing, not an ERF file */
466           return WTAP_OPEN_NOT_MINE;
467         }
468         return WTAP_OPEN_ERROR;
469       }
470       if (packet_size < erf_ext_header_size)
471         return WTAP_OPEN_NOT_MINE;
472       packet_size -= erf_ext_header_size;
473       memcpy(&type, &erf_ext_header, sizeof(type));
474     }
475
476
477     /* Read over MC or ETH subheader */
478     switch(header.type & 0x7F) {
479       case ERF_TYPE_MC_HDLC:
480       case ERF_TYPE_MC_RAW:
481       case ERF_TYPE_MC_ATM:
482       case ERF_TYPE_MC_RAW_CHANNEL:
483       case ERF_TYPE_MC_AAL5:
484       case ERF_TYPE_MC_AAL2:
485       case ERF_TYPE_COLOR_MC_HDLC_POS:
486       case ERF_TYPE_AAL2: /* not an MC type but has a similar 'AAL2 ext' header */
487         if (!wtap_read_bytes(wth->fh,&mc_hdr,erf_mc_header_size,err,err_info)) {
488           if (*err == WTAP_ERR_SHORT_READ) {
489             /* Subheader missing, not an ERF file */
490             return WTAP_OPEN_NOT_MINE;
491           }
492           return WTAP_OPEN_ERROR;
493         }
494         if (packet_size < erf_mc_header_size)
495           return WTAP_OPEN_NOT_MINE;
496         packet_size -= erf_mc_header_size;
497         break;
498       case ERF_TYPE_ETH:
499       case ERF_TYPE_COLOR_ETH:
500       case ERF_TYPE_DSM_COLOR_ETH:
501       case ERF_TYPE_COLOR_HASH_ETH:
502         if (!wtap_read_bytes(wth->fh,&eth_hdr,erf_eth_hdr_size,err,err_info)) {
503           if (*err == WTAP_ERR_SHORT_READ) {
504             /* Subheader missing, not an ERF file */
505             return WTAP_OPEN_NOT_MINE;
506           }
507           return WTAP_OPEN_ERROR;
508         }
509         if (packet_size < erf_eth_hdr_size)
510           return WTAP_OPEN_NOT_MINE;
511         packet_size -= erf_eth_hdr_size;
512         break;
513       default:
514         break;
515     }
516
517     if (!wtap_read_bytes(wth->fh, NULL, packet_size, err, err_info)) {
518       if (*err != WTAP_ERR_SHORT_READ) {
519         /* A real error */
520         return WTAP_OPEN_ERROR;
521       }
522       /* ERF record too short, accept the file,
523          only if the very first records have been successfully checked */
524       if (i < MIN_RECORDS_FOR_ERF_CHECK) {
525         return WTAP_OPEN_NOT_MINE;
526       }
527     }
528
529     valid_prev = 1;
530
531   } /* records_for_erf_check */
532
533   if (file_seek(wth->fh, 0L, SEEK_SET, err) == -1) {   /* rewind */
534     return WTAP_OPEN_ERROR;
535   }
536
537   /* This is an ERF file */
538   wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_ERF;
539   wth->snapshot_length = 0;     /* not available in header, only in frame */
540
541   /*
542    * Use the encapsulation for ERF records.
543    */
544   wth->file_encap = WTAP_ENCAP_ERF;
545
546   wth->subtype_read = erf_read;
547   wth->subtype_seek_read = erf_seek_read;
548   wth->subtype_close = erf_close;
549   wth->file_tsprec = WTAP_TSPREC_NSEC;
550
551   wth->priv = erf_priv_create();
552
553   return WTAP_OPEN_MINE;
554 }
555
556 /* Read the next packet */
557 static gboolean erf_read(wtap *wth, int *err, gchar **err_info,
558                          gint64 *data_offset)
559 {
560   erf_header_t erf_header;
561   guint32      packet_size, bytes_read;
562   GPtrArray *anchor_mappings_to_update;
563
564   *data_offset = file_tell(wth->fh);
565
566   anchor_mappings_to_update = g_ptr_array_new_with_free_func(erf_anchor_mapping_destroy);
567
568   do {
569     if (!erf_read_header(wth, wth->fh,
570                          &wth->rec, &erf_header,
571                          err, err_info, &bytes_read, &packet_size,
572                          anchor_mappings_to_update)) {
573       g_ptr_array_free(anchor_mappings_to_update, TRUE);
574       return FALSE;
575     }
576
577     if (!wtap_read_packet_bytes(wth->fh, wth->rec_data, packet_size,
578                                 err, err_info)) {
579       g_ptr_array_free(anchor_mappings_to_update, TRUE);
580       return FALSE;
581     }
582
583     /*
584      * If Provenance metadata record, frame buffer could hold the meta erf tags.
585      * It can also contain per packet comments which can be associated to another
586      * frame.
587      */
588     if ((erf_header.type & 0x7F) == ERF_TYPE_META && packet_size > 0)
589     {
590       populate_summary_info((erf_t*) wth->priv, wth, &wth->rec.rec_header.packet_header.pseudo_header, packet_size, anchor_mappings_to_update);
591     }
592
593   } while ( erf_header.type == ERF_TYPE_PAD );
594
595   g_ptr_array_free(anchor_mappings_to_update, TRUE);
596
597   return TRUE;
598 }
599
600 static gboolean erf_seek_read(wtap *wth, gint64 seek_off,
601                               wtap_rec *rec, Buffer *buf,
602                               int *err, gchar **err_info)
603 {
604   erf_header_t erf_header;
605   guint32      packet_size;
606   GPtrArray *anchor_mappings_to_update;
607
608   if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
609     return FALSE;
610
611   anchor_mappings_to_update = g_ptr_array_new_with_free_func(erf_anchor_mapping_destroy);
612
613   do {
614     if (!erf_read_header(wth, wth->random_fh, rec, &erf_header,
615                          err, err_info, NULL, &packet_size, anchor_mappings_to_update)) {
616       g_ptr_array_free(anchor_mappings_to_update, TRUE);
617       return FALSE;
618     }
619   } while ( erf_header.type == ERF_TYPE_PAD );
620
621   g_ptr_array_free(anchor_mappings_to_update, TRUE);
622
623   return wtap_read_packet_bytes(wth->random_fh, buf, packet_size,
624                                 err, err_info);
625 }
626
627 static struct erf_anchor_mapping* erf_find_anchor_mapping(erf_t *priv,
628     guint64 host_id,
629     guint64 anchor_id)
630 {
631   struct erf_anchor_mapping mapping = {
632     host_id,
633     anchor_id,
634     0,
635     NULL
636   };
637
638   if (!priv) {
639     return NULL;
640   }
641
642   return (struct erf_anchor_mapping*)g_hash_table_lookup(priv->anchor_map, &mapping);
643
644 }
645
646 static gboolean erf_read_header(wtap *wth, FILE_T fh,
647                                 wtap_rec *rec,
648                                 erf_header_t *erf_header,
649                                 int *err,
650                                 gchar **err_info,
651                                 guint32 *bytes_read,
652                                 guint32 *packet_size,
653                                 GPtrArray *anchor_mappings_to_update)
654 {
655   union wtap_pseudo_header *pseudo_header = &rec->rec_header.packet_header.pseudo_header;
656   guint8  erf_exhdr[8];
657   guint64 erf_exhdr_sw;
658   guint8  type    = 0;
659   guint32 mc_hdr;
660   guint32 aal2_hdr;
661   struct wtap_erf_eth_hdr eth_hdr;
662   guint32 skiplen = 0;
663   int     i       = 0;
664   int     max     = sizeof(pseudo_header->erf.ehdr_list)/sizeof(struct erf_ehdr);
665   erf_t *priv = (erf_t*)wth->priv;
666
667   guint64 host_id  = ERF_META_HOST_ID_IMPLICIT;
668   guint8 source_id = 0;
669   guint8 if_num    = 0;
670   gboolean host_id_found = FALSE;
671
672   if (!wtap_read_bytes_or_eof(fh, erf_header, sizeof(*erf_header), err, err_info)) {
673     return FALSE;
674   }
675   if (bytes_read != NULL) {
676     *bytes_read = sizeof(*erf_header);
677   }
678
679   *packet_size =  g_ntohs(erf_header->rlen) - (guint32)sizeof(*erf_header);
680
681   if (*packet_size > WTAP_MAX_PACKET_SIZE_STANDARD) {
682     /*
683      * Probably a corrupt capture file; don't blow up trying
684      * to allocate space for an immensely-large packet.
685      */
686     *err = WTAP_ERR_BAD_FILE;
687     *err_info = g_strdup_printf("erf: File has %u-byte packet, bigger than maximum of %u",
688                                 *packet_size, WTAP_MAX_PACKET_SIZE_STANDARD);
689     return FALSE;
690   }
691
692   if (*packet_size == 0) {
693     /* If this isn't a pad record, it's a corrupt packet; bail out */
694     if ((erf_header->type & 0x7F) != ERF_TYPE_PAD) {
695       *err = WTAP_ERR_BAD_FILE;
696       *err_info = g_strdup("erf: File has 0 byte packet");
697
698       return FALSE;
699     }
700   }
701
702   {
703     guint64 ts = pletoh64(&erf_header->ts);
704
705     /*if ((erf_header->type & 0x7f) != ERF_TYPE_META || wth->file_type_subtype != WTAP_FILE_TYPE_SUBTYPE_ERF) {*/
706       rec->rec_type = REC_TYPE_PACKET;
707     /*
708      * XXX: ERF_TYPE_META records should ideally be FT_SPECIFIC for display
709      * purposes, but currently ft_specific_record_phdr clashes with erf_mc_phdr
710      * and the pcapng dumper assumes it is a pcapng block type. Ideally we
711      * would register a block handler with pcapng and write out the closest
712      * pcapng block, or a custom block/Provenance record.
713      *
714      */
715 #if 0
716     } else {
717       /*
718        * TODO: how to identify, distinguish and timestamp events?
719        * What to do about ENCAP_ERF in pcap/pcapng? Filetype dissector is
720        * chosen by wth->file_type_subtype?
721        */
722       /* For now just treat all Provenance records as reports */
723       rec->rec_type = REC_TYPE_FT_SPECIFIC_REPORT;
724       /* XXX: phdr ft_specific_record_phdr? */
725     }
726 #endif
727     rec->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN|WTAP_HAS_INTERFACE_ID;
728     rec->ts.secs = (long) (ts >> 32);
729     ts  = ((ts & 0xffffffff) * 1000 * 1000 * 1000);
730     ts += (ts & 0x80000000) << 1; /* rounding */
731     rec->ts.nsecs = ((int) (ts >> 32));
732     if (rec->ts.nsecs >= 1000000000) {
733       rec->ts.nsecs -= 1000000000;
734       rec->ts.secs += 1;
735     }
736
737     if_num = erf_header->flags & 0x03;
738   }
739
740   /* Copy the ERF pseudo header */
741   memset(&pseudo_header->erf, 0, sizeof(pseudo_header->erf));
742   pseudo_header->erf.phdr.ts = pletoh64(&erf_header->ts);
743   pseudo_header->erf.phdr.type = erf_header->type;
744   pseudo_header->erf.phdr.flags = erf_header->flags;
745   pseudo_header->erf.phdr.rlen = g_ntohs(erf_header->rlen);
746   pseudo_header->erf.phdr.lctr = g_ntohs(erf_header->lctr);
747   pseudo_header->erf.phdr.wlen = g_ntohs(erf_header->wlen);
748
749   /* Copy the ERF extension header into the pseudo header */
750   type = erf_header->type;
751   while (type & 0x80){
752     if (!wtap_read_bytes(fh, &erf_exhdr, sizeof(erf_exhdr),
753                          err, err_info))
754       return FALSE;
755     if (bytes_read != NULL)
756       *bytes_read += (guint32)sizeof(erf_exhdr);
757     *packet_size -=  (guint32)sizeof(erf_exhdr);
758     skiplen += (guint32)sizeof(erf_exhdr);
759     erf_exhdr_sw = pntoh64(erf_exhdr);
760     if (i < max)
761       memcpy(&pseudo_header->erf.ehdr_list[i].ehdr, &erf_exhdr_sw, sizeof(erf_exhdr_sw));
762     type = erf_exhdr[0];
763
764     /*
765      * XXX: Only want first Source ID and Host ID, and want to preserve HID n SID 0 (see
766      * erf_populate_interface)
767      */
768     switch (type & 0x7FU) {
769       case ERF_EXT_HDR_TYPE_HOST_ID:
770         if (!host_id_found)
771           host_id = erf_exhdr_sw & ERF_EHDR_HOST_ID_MASK;
772
773         host_id_found = TRUE;
774         /* Fall through */
775       case ERF_EXT_HDR_TYPE_FLOW_ID:
776         /* Source ID is present in both Flow ID and Host ID extension headers */
777         if (!source_id)
778           source_id = (erf_exhdr_sw >> 48) & 0xff;
779         break;
780       case ERF_EXT_HDR_TYPE_ANCHOR_ID:
781         /* handled below*/
782         break;
783     }
784     i++;
785   }
786
787   /* XXX: erf_priv pointer needs to change if used as common function for other dissectors! */
788   rec->rec_header.packet_header.interface_id = (guint) erf_populate_interface((erf_t*) wth->priv, wth, pseudo_header, host_id, source_id, if_num);
789
790   /* Try to find comment links using Anchor ID. Done here after we found the first Host ID and have updated the implicit Host ID. */
791   erf_update_anchors_from_header(priv, rec, pseudo_header, host_id, anchor_mappings_to_update);
792
793   switch (erf_header->type & 0x7F) {
794     case ERF_TYPE_IPV4:
795     case ERF_TYPE_IPV6:
796     case ERF_TYPE_RAW_LINK:
797     case ERF_TYPE_INFINIBAND:
798     case ERF_TYPE_INFINIBAND_LINK:
799     case ERF_TYPE_META:
800     case ERF_TYPE_OPA_SNC:
801     case ERF_TYPE_OPA_9B:
802 #if 0
803       {
804         rec->rec_header.packet_header.len =  g_htons(erf_header->wlen);
805         rec->rec_header.packet_header.caplen = g_htons(erf_header->wlen);
806       }
807       return TRUE;
808 #endif
809       break;
810     case ERF_TYPE_PAD:
811     case ERF_TYPE_HDLC_POS:
812     case ERF_TYPE_COLOR_HDLC_POS:
813     case ERF_TYPE_DSM_COLOR_HDLC_POS:
814     case ERF_TYPE_COLOR_HASH_POS:
815     case ERF_TYPE_ATM:
816     case ERF_TYPE_AAL5:
817       break;
818
819     case ERF_TYPE_ETH:
820     case ERF_TYPE_COLOR_ETH:
821     case ERF_TYPE_DSM_COLOR_ETH:
822     case ERF_TYPE_COLOR_HASH_ETH:
823       if (!wtap_read_bytes(fh, &eth_hdr, sizeof(eth_hdr), err, err_info))
824         return FALSE;
825       if (bytes_read != NULL)
826         *bytes_read += (guint32)sizeof(eth_hdr);
827       *packet_size -=  (guint32)sizeof(eth_hdr);
828       skiplen += (guint32)sizeof(eth_hdr);
829       pseudo_header->erf.subhdr.eth_hdr = eth_hdr;
830       break;
831
832     case ERF_TYPE_MC_HDLC:
833     case ERF_TYPE_MC_RAW:
834     case ERF_TYPE_MC_ATM:
835     case ERF_TYPE_MC_RAW_CHANNEL:
836     case ERF_TYPE_MC_AAL5:
837     case ERF_TYPE_MC_AAL2:
838     case ERF_TYPE_COLOR_MC_HDLC_POS:
839       if (!wtap_read_bytes(fh, &mc_hdr, sizeof(mc_hdr), err, err_info))
840         return FALSE;
841       if (bytes_read != NULL)
842         *bytes_read += (guint32)sizeof(mc_hdr);
843       *packet_size -=  (guint32)sizeof(mc_hdr);
844       skiplen += (guint32)sizeof(mc_hdr);
845       pseudo_header->erf.subhdr.mc_hdr = g_ntohl(mc_hdr);
846       break;
847
848     case ERF_TYPE_AAL2:
849       if (!wtap_read_bytes(fh, &aal2_hdr, sizeof(aal2_hdr), err, err_info))
850         return FALSE;
851       if (bytes_read != NULL)
852         *bytes_read += (guint32)sizeof(aal2_hdr);
853       *packet_size -=  (guint32)sizeof(aal2_hdr);
854       skiplen += (guint32)sizeof(aal2_hdr);
855       pseudo_header->erf.subhdr.aal2_hdr = g_ntohl(aal2_hdr);
856       break;
857
858     case ERF_TYPE_IP_COUNTER:
859     case ERF_TYPE_TCP_FLOW_COUNTER:
860       /* unsupported, continue with default: */
861     default:
862       /* let the dissector dissect as unknown record type for forwards compatibility */
863       break;
864   }
865
866   {
867     rec->rec_header.packet_header.len = g_ntohs(erf_header->wlen);
868     rec->rec_header.packet_header.caplen = MIN( g_ntohs(erf_header->wlen),
869                         g_ntohs(erf_header->rlen) - (guint32)sizeof(*erf_header) - skiplen );
870   }
871
872   if (*packet_size > WTAP_MAX_PACKET_SIZE_STANDARD) {
873     /*
874      * Probably a corrupt capture file; don't blow up trying
875      * to allocate space for an immensely-large packet.
876      */
877     *err = WTAP_ERR_BAD_FILE;
878     *err_info = g_strdup_printf("erf: File has %u-byte packet, bigger than maximum of %u",
879                                 *packet_size, WTAP_MAX_PACKET_SIZE_STANDARD);
880     return FALSE;
881   }
882
883   return TRUE;
884 }
885
886 static int wtap_wtap_encap_to_erf_encap(int encap)
887 {
888   unsigned int i;
889   for(i = 0; i < NUM_ERF_ENCAPS; i++){
890     if(erf_to_wtap_map[i].wtap_encap_value == encap)
891       return erf_to_wtap_map[i].erf_encap_value;
892   }
893   return -1;
894 }
895
896 static gboolean erf_write_phdr(wtap_dumper *wdh, int encap, const union wtap_pseudo_header *pseudo_header, int * err)
897 {
898   guint8 erf_hdr[sizeof(struct erf_mc_phdr)];
899   guint8 erf_subhdr[sizeof(union erf_subhdr)];
900   guint8 ehdr[8*MAX_ERF_EHDR];
901   size_t size        = 0;
902   size_t subhdr_size = 0;
903   int    i           = 0;
904   guint8 has_more    = 0;
905
906   switch(encap){
907     case WTAP_ENCAP_ERF:
908       memset(&erf_hdr, 0, sizeof(erf_hdr));
909       phtolell(&erf_hdr[0], pseudo_header->erf.phdr.ts);
910       erf_hdr[8] = pseudo_header->erf.phdr.type;
911       erf_hdr[9] = pseudo_header->erf.phdr.flags;
912       phtons(&erf_hdr[10], pseudo_header->erf.phdr.rlen);
913       phtons(&erf_hdr[12], pseudo_header->erf.phdr.lctr);
914       phtons(&erf_hdr[14], pseudo_header->erf.phdr.wlen);
915       size = sizeof(struct erf_phdr);
916
917       switch(pseudo_header->erf.phdr.type & 0x7F) {
918         case ERF_TYPE_MC_HDLC:
919         case ERF_TYPE_MC_RAW:
920         case ERF_TYPE_MC_ATM:
921         case ERF_TYPE_MC_RAW_CHANNEL:
922         case ERF_TYPE_MC_AAL5:
923         case ERF_TYPE_MC_AAL2:
924         case ERF_TYPE_COLOR_MC_HDLC_POS:
925           phtonl(&erf_subhdr[0], pseudo_header->erf.subhdr.mc_hdr);
926           subhdr_size += (int)sizeof(struct erf_mc_hdr);
927           break;
928         case ERF_TYPE_AAL2:
929           phtonl(&erf_subhdr[0], pseudo_header->erf.subhdr.aal2_hdr);
930           subhdr_size += (int)sizeof(struct erf_aal2_hdr);
931           break;
932         case ERF_TYPE_ETH:
933         case ERF_TYPE_COLOR_ETH:
934         case ERF_TYPE_DSM_COLOR_ETH:
935         case ERF_TYPE_COLOR_HASH_ETH:
936           memcpy(&erf_subhdr[0], &pseudo_header->erf.subhdr.eth_hdr, sizeof pseudo_header->erf.subhdr.eth_hdr);
937           subhdr_size += erf_eth_hdr_size;
938           break;
939         default:
940           break;
941       }
942       break;
943     default:
944       return FALSE;
945
946   }
947   if (!wtap_dump_file_write(wdh, erf_hdr, size, err))
948     return FALSE;
949   wdh->bytes_dumped += size;
950
951   /*write out up to MAX_ERF_EHDR extension headers*/
952   has_more = pseudo_header->erf.phdr.type & 0x80;
953   if(has_more){  /*we have extension headers*/
954     do{
955       phtonll(ehdr+(i*8), pseudo_header->erf.ehdr_list[i].ehdr);
956       if(i == MAX_ERF_EHDR-1) ehdr[i*8] = ehdr[i*8] & 0x7F;
957       has_more = ehdr[i*8] & 0x80;
958       i++;
959     }while(has_more && i < MAX_ERF_EHDR);
960     if (!wtap_dump_file_write(wdh, ehdr, 8*i, err))
961       return FALSE;
962     wdh->bytes_dumped += 8*i;
963   }
964
965   if(!wtap_dump_file_write(wdh, erf_subhdr, subhdr_size, err))
966     return FALSE;
967   wdh->bytes_dumped += subhdr_size;
968
969   return TRUE;
970 }
971
972
973 static void erf_dump_priv_init_gen_time(erf_dump_t *dump_priv) {
974   GTimeVal real_time;
975
976   g_get_current_time(&real_time);
977   /* Convert TimeVal to ERF timestamp */
978   dump_priv->gen_time = ((guint64) real_time.tv_sec << 32) + ((guint64) real_time.tv_usec << 32) / 1000 / 1000;
979 }
980
981
982 static void erf_write_wtap_option_to_capture_tag(wtap_block_t block _U_,
983     guint option_id,
984     wtap_opttype_e option_type _U_,
985     wtap_optval_t *optval,
986     void* user_data) {
987
988   struct erf_meta_section *section_ptr = (struct erf_meta_section*) user_data;
989   struct erf_meta_tag *tag_ptr = NULL;
990
991   tag_ptr = (struct erf_meta_tag*) g_malloc0(sizeof(struct erf_meta_tag));
992
993   switch(option_id) {
994     case OPT_SHB_USERAPPL:
995       tag_ptr->type = ERF_META_TAG_app_name;
996       tag_ptr->value = (guint8*)g_strdup(optval->stringval);
997       tag_ptr->length = (guint16)strlen((char*)tag_ptr->value);
998       break;
999     case OPT_COMMENT:
1000       tag_ptr->type = ERF_META_TAG_comment;
1001       tag_ptr->value = (guint8*)g_strdup(optval->stringval);
1002       tag_ptr->length = (guint16)strlen((char*)tag_ptr->value);
1003       break;
1004     default:
1005       erf_meta_tag_free(tag_ptr);
1006       tag_ptr = NULL;
1007       break;
1008   }
1009
1010   if (tag_ptr)
1011     g_ptr_array_add(section_ptr->tags, tag_ptr);
1012 }
1013
1014 static void erf_write_wtap_option_to_host_tag(wtap_block_t block _U_,
1015     guint option_id,
1016     wtap_opttype_e option_type _U_,
1017     wtap_optval_t *optval,
1018     void* user_data) {
1019
1020   struct erf_meta_section *section_ptr = (struct erf_meta_section*) user_data;
1021   struct erf_meta_tag *tag_ptr = NULL;
1022
1023   tag_ptr = (struct erf_meta_tag*) g_malloc0(sizeof(struct erf_meta_tag));
1024
1025   switch(option_id) {
1026     case OPT_SHB_HARDWARE:
1027       tag_ptr->type = ERF_META_TAG_cpu;
1028       tag_ptr->value = (guint8*)g_strdup(optval->stringval);
1029       tag_ptr->length = (guint16)strlen((char*)tag_ptr->value);
1030       break;
1031     case OPT_SHB_OS:
1032       tag_ptr->type = ERF_META_TAG_os;
1033       tag_ptr->value = (guint8*)g_strdup(optval->stringval);
1034       tag_ptr->length = (guint16)strlen((char*)tag_ptr->value);
1035       break;
1036     default:
1037       erf_meta_tag_free(tag_ptr);
1038       tag_ptr = NULL;
1039       break;
1040   }
1041
1042   if (tag_ptr)
1043     g_ptr_array_add(section_ptr->tags, tag_ptr);
1044 }
1045
1046 static void erf_write_wtap_option_to_interface_tag(wtap_block_t block _U_,
1047     guint option_id,
1048     wtap_opttype_e option_type _U_,
1049     wtap_optval_t *optval,
1050     void* user_data) {
1051
1052   struct erf_meta_section *section_ptr = (struct erf_meta_section*) user_data;
1053   struct erf_meta_tag *tag_ptr = NULL;
1054
1055   tag_ptr = (struct erf_meta_tag*) g_malloc0(sizeof(struct erf_meta_tag));
1056
1057   switch(option_id) {
1058     case OPT_COMMENT:
1059       tag_ptr->type = ERF_META_TAG_comment;
1060       tag_ptr->value = (guint8*)g_strdup(optval->stringval);
1061       tag_ptr->length = (guint16)strlen((char*)tag_ptr->value);
1062       break;
1063     case OPT_IDB_NAME:
1064       tag_ptr->type = ERF_META_TAG_name;
1065       tag_ptr->value = (guint8*)g_strdup(optval->stringval);
1066       tag_ptr->length = (guint16)strlen((char*)tag_ptr->value);
1067       break;
1068     case OPT_IDB_DESCR:
1069       tag_ptr->type = ERF_META_TAG_descr;
1070       tag_ptr->value = (guint8*)g_strdup(optval->stringval);
1071       tag_ptr->length = (guint16)strlen((char*)tag_ptr->value);
1072       break;
1073     case OPT_IDB_OS:
1074       tag_ptr->type = ERF_META_TAG_os;
1075       tag_ptr->value = (guint8*)g_strdup(optval->stringval);
1076       tag_ptr->length = (guint16)strlen((char*)tag_ptr->value);
1077       break;
1078     case OPT_IDB_TSOFFSET:
1079       tag_ptr->type = ERF_META_TAG_ts_offset;
1080       tag_ptr->length = 8;
1081       tag_ptr->value = (guint8*)g_malloc(sizeof(optval->uint64val));
1082       /* convert to relative ERF timestamp */
1083       phtolell(tag_ptr->value, optval->uint64val << 32);
1084       break;
1085     case OPT_IDB_SPEED:
1086       tag_ptr->type = ERF_META_TAG_if_speed;
1087       tag_ptr->length = 8;
1088       tag_ptr->value = (guint8*)g_malloc(sizeof(optval->uint64val));
1089       phtonll(tag_ptr->value, optval->uint64val);
1090       break;
1091     case OPT_IDB_IP4ADDR:
1092       tag_ptr->type = ERF_META_TAG_if_ipv4;
1093       tag_ptr->length = 4;
1094       tag_ptr->value = (guint8*)g_malloc(sizeof(optval->ipv4val));
1095       memcpy(tag_ptr->value, &optval->ipv4val, sizeof(optval->ipv4val));
1096       break;
1097     case OPT_IDB_IP6ADDR:
1098       tag_ptr->type = ERF_META_TAG_if_ipv6;
1099       tag_ptr->length = 16;
1100       tag_ptr->value = (guint8*)g_malloc(sizeof(optval->ipv6val));
1101       memcpy(tag_ptr->value, &optval->ipv6val, sizeof(optval->ipv6val));
1102       break;
1103     case OPT_IDB_FILTER:
1104       {
1105         wtapng_if_descr_filter_t *filter;
1106         tag_ptr->type = 0xF800;
1107         filter = (wtapng_if_descr_filter_t*)&optval->customval;
1108         if(filter->if_filter_str) {
1109           tag_ptr->type = ERF_META_TAG_filter;
1110           tag_ptr->value = (guint8*)g_strdup(filter->if_filter_str);
1111           tag_ptr->length = (guint16)strlen((char*)tag_ptr->value);
1112         }
1113       }
1114       break;
1115     case OPT_IDB_FCSLEN:
1116       tag_ptr->type = ERF_META_TAG_fcs_len;
1117       tag_ptr->length = 4;
1118       tag_ptr->value = (guint8*)g_malloc(tag_ptr->length);
1119       phtonl(tag_ptr->value, (guint32)optval->uint8val);
1120       break;
1121     /* TODO: Don't know what to do with these yet */
1122     case OPT_IDB_EUIADDR:
1123 #if 0
1124       tag_ptr->type = ERF_META_TAG_if_eui;
1125       tag_ptr->length = 8;
1126       tag_ptr->value = (guint8*)g_malloc(sizeof(optval->eui64val));
1127       memcpy(tag_ptr->value, &optval->euival, sizeof(optval->eui64val));
1128       break;
1129 #endif
1130     case OPT_IDB_MACADDR:
1131 #if 0
1132       tag_ptr->type = ERF_META_TAG_if_mac;
1133       tag_ptr->length = 6;
1134       /*value same format as pcapng (6-byte canonical, padded by write
1135        * function automatically to 32-bit boundary)*/
1136       tag_ptr->value = (guint8*)g_malloc(sizeof(optval->macval));
1137       memcpy(tag_ptr->value, &optval->macval, sizeof(optval->macval));
1138       break;
1139 #endif
1140     case OPT_IDB_TSRESOL:
1141     case OPT_IDB_TZONE:
1142     /* Fall through */
1143     default:
1144       erf_meta_tag_free(tag_ptr);
1145       tag_ptr = NULL;
1146       break;
1147   }
1148
1149   if (tag_ptr)
1150     g_ptr_array_add(section_ptr->tags, tag_ptr);
1151
1152 }
1153
1154 static void erf_populate_section_length_by_tags(struct erf_meta_section *section_ptr) {
1155   guint i = 0;
1156   struct erf_meta_tag *tag_ptr;
1157
1158   section_ptr->section_length = 8;
1159
1160   for(;i < section_ptr->tags->len; i++) {
1161     tag_ptr = (struct erf_meta_tag*)g_ptr_array_index(section_ptr->tags, i);
1162     section_ptr->section_length += ERF_META_TAG_TOTAL_ALIGNED_LENGTH(tag_ptr->length);
1163   }
1164 }
1165
1166 /**
1167  * @brief Converts a wtap_block_t block to ERF metadata sections
1168  * @param block a wtap_block_t block
1169  * @param sections pointer to a GPtrArray containing pointers to sections
1170  * @param section_type the pre-specified section_type
1171  * @param section_id Section ID to assign
1172  * @param func a wtap_block_foreach_func call back function to specify
1173  *             what needs to be done on the block
1174  * @return TRUE if success, FALSE if failed
1175  */
1176 static gboolean erf_wtap_blocks_to_erf_sections(wtap_block_t block, GPtrArray *sections, guint16 section_type, guint16 section_id, wtap_block_foreach_func func) {
1177
1178   if(!block || !sections || !func) {
1179     return FALSE;
1180   }
1181
1182   struct erf_meta_section *section_ptr;
1183
1184   section_ptr = (struct erf_meta_section*) g_malloc(sizeof(struct erf_meta_section));
1185   section_ptr->tags = g_ptr_array_new_with_free_func(erf_meta_tag_free);
1186   section_ptr->type = section_type;
1187   section_ptr->section_id = section_id;
1188
1189   wtap_block_foreach_option(block, func, (void*)section_ptr);
1190   erf_populate_section_length_by_tags(section_ptr);
1191   g_ptr_array_add(sections, section_ptr);
1192
1193   return TRUE;
1194 }
1195
1196
1197 static gboolean erf_meta_write_tag(wtap_dumper *wdh, struct erf_meta_tag *tag_ptr, int *err) {
1198
1199   guint16 data[2];
1200   guint pad = 0;
1201   /* we only need to pad up to 32 bits*/
1202   guint32 padbuf = 0;
1203
1204   pad = ERF_META_TAG_ALIGNED_LENGTH(tag_ptr->length) - tag_ptr->length;
1205   data[0] = g_htons(tag_ptr->type);
1206   data[1] = g_htons(tag_ptr->length);
1207
1208   if(!wtap_dump_file_write(wdh, data, sizeof(data), err)) return FALSE;
1209   wdh->bytes_dumped += sizeof(data);
1210
1211   if(!wtap_dump_file_write(wdh, tag_ptr->value, tag_ptr->length, err)) return FALSE;
1212   wdh->bytes_dumped += tag_ptr->length;
1213
1214   if(pad) {
1215     if(!wtap_dump_file_write(wdh, &padbuf, pad, err)) return FALSE;
1216     wdh->bytes_dumped += pad;
1217   }
1218
1219   return TRUE;
1220
1221 }
1222
1223 static gboolean erf_meta_write_section(wtap_dumper *wdh, struct erf_meta_section *section_ptr, int *err) {
1224
1225   struct erf_meta_tag *tag_ptr;
1226   guint i;
1227   guint16 data[4];
1228
1229   data[0] = g_htons(section_ptr->type);
1230   data[1] = g_htons(4); /*section header length*/
1231   data[2] = g_htons(section_ptr->section_id);
1232   data[3] = g_htons(section_ptr->section_length);
1233
1234   if(!wtap_dump_file_write(wdh, data, sizeof(data), err)) return FALSE;
1235   wdh->bytes_dumped += sizeof(data);
1236
1237   for(i = 0; i < section_ptr->tags->len; i++) {
1238     tag_ptr = (struct erf_meta_tag*)g_ptr_array_index(section_ptr->tags, i);
1239     if(!erf_meta_write_tag(wdh, tag_ptr, err)) return FALSE;
1240   }
1241
1242   return TRUE;
1243
1244 }
1245
1246 static gboolean erf_wtap_info_to_sections(wtap_dumper *wdh, GPtrArray *sections) {
1247   wtap_block_t block;
1248   guint i = 0;
1249
1250   block = g_array_index(wdh->shb_hdrs, wtap_block_t, 0);
1251   erf_wtap_blocks_to_erf_sections(block, sections, ERF_META_SECTION_CAPTURE, 0, erf_write_wtap_option_to_capture_tag);
1252
1253   block = g_array_index(wdh->shb_hdrs, wtap_block_t, 0);
1254   erf_wtap_blocks_to_erf_sections(block, sections, ERF_META_SECTION_HOST, 0, erf_write_wtap_option_to_host_tag);
1255
1256   /*TODO: support >4 interfaces by using more Source IDs. Affects more than this
1257    * function as need more metadata records. Just dump them all out for now. */
1258   for(i = 0; i < wdh->interface_data->len; i++) {
1259     block = g_array_index(wdh->interface_data, wtap_block_t, i);
1260     erf_wtap_blocks_to_erf_sections(block, sections, ERF_META_SECTION_INTERFACE, (gint16)i+1, erf_write_wtap_option_to_interface_tag);
1261   }
1262
1263   return TRUE;
1264 }
1265
1266 static gboolean erf_comment_to_sections(wtap_dumper *wdh _U_, guint16 section_type, guint16 section_id, gchar *comment, GPtrArray *sections){
1267   struct erf_meta_section *section_ptr;
1268   struct erf_meta_tag *comment_tag_ptr = NULL;
1269   struct erf_meta_tag *user_tag_ptr = NULL;
1270   const gchar *user = NULL;
1271
1272   /* Generate the section */
1273   section_ptr = (struct erf_meta_section*) g_malloc(sizeof(struct erf_meta_section));
1274   section_ptr->type = section_type;
1275   section_ptr->section_id = section_id;
1276   section_ptr->tags = g_ptr_array_new_with_free_func(erf_meta_tag_free);
1277
1278   /* Generate the comment tag */
1279   comment_tag_ptr = (struct erf_meta_tag*) g_malloc(sizeof(struct erf_meta_tag));
1280   comment_tag_ptr->type = ERF_META_TAG_comment;
1281   /* XXX: if the comment has been cleared write the empty string (which
1282    * conveniently is all a zero length tag which means the value is
1283    * invalidated) */
1284   comment_tag_ptr->value = (guint8*)g_strdup(comment ? comment : "");
1285   comment_tag_ptr->length = (guint16)strlen((char*)comment_tag_ptr->value);
1286   g_ptr_array_add(section_ptr->tags, comment_tag_ptr);
1287
1288   user = g_get_user_name();
1289   if (user) {
1290     /* Generate username tag */
1291     user_tag_ptr = (struct erf_meta_tag*) g_malloc(sizeof(struct erf_meta_tag));
1292     user_tag_ptr->type = ERF_META_TAG_user;
1293     user_tag_ptr->value = (guint8*)g_strdup(user);
1294     user_tag_ptr->length = (guint16)strlen((char*)user_tag_ptr->value);
1295     g_ptr_array_add(section_ptr->tags, user_tag_ptr);
1296   }
1297
1298   erf_populate_section_length_by_tags(section_ptr);
1299
1300   g_ptr_array_add(sections, section_ptr);
1301
1302   return TRUE;
1303 }
1304
1305 static guint64 erf_get_random_anchor_id(erf_dump_t *dump_priv) {
1306   return (((guint64)g_rand_int(dump_priv->rand) << 32) | (guint64)g_rand_int(dump_priv->rand)) >> 16;
1307 }
1308
1309 static guint64 erf_metaid_ext_hdr(guint8 exthdr_type, guint64 id, guint8 srcid_flags) {
1310   guint64 ext_hdr;
1311
1312   ext_hdr = id & ERF_EHDR_HOST_ID_MASK;
1313   ext_hdr |= ((guint64)srcid_flags) << 48;
1314   ext_hdr |= ((guint64)exthdr_type) << 56;
1315
1316   return ext_hdr;
1317 }
1318 #define erf_host_id_ext_hdr(host_id, source_id) erf_metaid_ext_hdr(ERF_EXT_HDR_TYPE_HOST_ID, host_id, source_id)
1319 #define erf_anchor_id_ext_hdr(anchor_id, flags) erf_metaid_ext_hdr(ERF_EXT_HDR_TYPE_ANCHOR_ID, anchor_id, flags)
1320
1321 static inline gboolean erf_add_ext_hdr_to_list(guint64 ext_hdr, guint64 comparison_mask, GArray *extra_ehdrs) {
1322   /* check for existing Host ID in set and add */
1323   guint i = 0;
1324   struct erf_ehdr ehdr_tmp;
1325   struct erf_ehdr *ehdr_ptr = NULL;
1326
1327   if (!extra_ehdrs)
1328     return FALSE;
1329
1330   ext_hdr = ext_hdr & ~ERF_EHDR_MORE_EXTHDR_MASK;
1331   if (comparison_mask == 0)
1332     comparison_mask = G_MAXUINT64;
1333
1334   comparison_mask &= ~ERF_EHDR_MORE_EXTHDR_MASK;
1335
1336   for (i = 0; i < extra_ehdrs->len; i++) {
1337     ehdr_ptr = &g_array_index(extra_ehdrs, struct erf_ehdr, i);
1338     /* Check if we already have this Host ID extension header */
1339     if (ext_hdr == (ehdr_ptr->ehdr & comparison_mask)) {
1340       return TRUE;
1341     }
1342   }
1343
1344   /* set more flag on last extension header */
1345   if (ehdr_ptr) {
1346     ehdr_ptr->ehdr |= ERF_EHDR_MORE_EXTHDR_MASK;
1347   }
1348
1349   ehdr_tmp.ehdr = ext_hdr; /*more flag already cleared above*/
1350   g_array_append_val(extra_ehdrs, ehdr_tmp);
1351
1352   return TRUE;
1353 }
1354
1355 static inline gboolean erf_append_ext_hdr_to_list(guint64 ext_hdr, GArray *extra_ehdrs) {
1356   struct erf_ehdr ehdr_tmp;
1357
1358   if (!extra_ehdrs)
1359     return FALSE;
1360
1361   ehdr_tmp.ehdr = ext_hdr & ~ERF_EHDR_MORE_EXTHDR_MASK;
1362
1363   /* set more flag on last extension header */
1364   if (extra_ehdrs->len) {
1365     g_array_index(extra_ehdrs, struct erf_ehdr, extra_ehdrs->len - 1).ehdr |= ERF_EHDR_MORE_EXTHDR_MASK;
1366   }
1367
1368   g_array_append_val(extra_ehdrs, ehdr_tmp);
1369
1370   return TRUE;
1371 }
1372
1373 static gboolean erf_update_host_id_ext_hdrs_list(erf_dump_t *dump_priv, const union wtap_pseudo_header *pseudo_header, GArray *extra_ehdrs) {
1374   guint8 type;
1375   guint8 erf_type;
1376   int has_more;
1377   guint64 hdr;
1378   int i = 0;
1379   guint8 source_id = 0;
1380   guint64 host_id = 0;
1381   gboolean host_id_found = FALSE;
1382
1383   if (!extra_ehdrs)
1384     return FALSE;
1385
1386   erf_type = pseudo_header->erf.phdr.type & 0x7f;
1387   has_more = pseudo_header->erf.phdr.type & 0x80;
1388
1389   while (has_more && i < MAX_ERF_EHDR) {
1390     hdr = pseudo_header->erf.ehdr_list[i].ehdr;
1391     type = (guint8) (hdr >> 56);
1392
1393     switch (type & 0x7f) {
1394       case ERF_EXT_HDR_TYPE_HOST_ID:
1395         host_id = hdr & ERF_EHDR_HOST_ID_MASK;
1396         source_id = (hdr >> 48) & 0xff;
1397
1398         /* Don't add the wireshark Host ID Source ID 0 twice since we already add it to metadata records */
1399         if (host_id != dump_priv->host_id || source_id != 0)
1400           if (!erf_add_ext_hdr_to_list(hdr, 0, extra_ehdrs)) return FALSE;
1401
1402         if (!host_id_found) {
1403           /* XXX: Take the opportunity to update the implicit Host ID if we
1404            * don't know it yet. Ideally we should pass this through from the
1405            * reader as a custom option or similar. */
1406           if (erf_type == ERF_TYPE_META && ((hdr >> 48) & 0xff) > 0) {
1407             if (dump_priv->implicit_host_id == ERF_META_HOST_ID_IMPLICIT) {
1408               dump_priv->implicit_host_id = host_id;
1409             }
1410           }
1411         }
1412
1413         host_id_found = TRUE;
1414         break;
1415       case ERF_EXT_HDR_TYPE_FLOW_ID:
1416         if (source_id == 0) /* If no Host ID extension header use the first Source ID only */
1417           source_id = (hdr >> 48) & 0xff;
1418         break;
1419     }
1420
1421     has_more = type & 0x80;
1422     i++;
1423   }
1424
1425   /* Add Source ID with implicit Host ID if not found */
1426   if (!host_id_found) {
1427     guint64 implicit_host_id = dump_priv->implicit_host_id == ERF_META_HOST_ID_IMPLICIT ? 0 : dump_priv->implicit_host_id;
1428     /* Don't add the wireshark Host ID Source ID 0 twice since we already add it to metadata records */
1429     if (implicit_host_id != dump_priv->host_id || source_id != 0)
1430       if (!erf_add_ext_hdr_to_list(erf_host_id_ext_hdr(implicit_host_id, source_id), 0, extra_ehdrs)) return FALSE;
1431   }
1432
1433   return TRUE;
1434 }
1435
1436 /**
1437  * Writes a metadata record with a randomly generated Anchor ID with the
1438  * user comment attached to its comment section, also updates the
1439  * modified frame header to include a Host ID extension header and
1440  * a Anchor ID extension header to link the records together.
1441  * @param wdh the wtap_dumper structure
1442  * @param dump_priv private data for the dump stream
1443  * @param rec record metadata from which to get user comment
1444  * @param mutable_hdr pseudo_header to update with Anchor ID for comment record
1445  * @param err the error value
1446  * @return A gboolean value to indicate whether the dump was successful
1447  */
1448 static gboolean erf_write_anchor_meta_update_phdr(wtap_dumper *wdh, erf_dump_t *dump_priv, const wtap_rec *rec, union wtap_pseudo_header *mutable_hdr, int *err) {
1449   GArray *meta_ehdrs;
1450   GPtrArray* sections = NULL;
1451   guint8 has_more;
1452   guint8 i = 0;
1453   guint8 ext_hdr_count = 0;
1454   guint8 j = 0;
1455   guint64 host_id_src_hdr = ERF_META_HOST_ID_IMPLICIT;
1456   guint64 host_id_own_hdr = erf_host_id_ext_hdr(dump_priv->host_id, 0);
1457   guint64 flow_id_hdr = 0;
1458   guint64 anchor_id_hdr = 0;
1459   gboolean found_host_id = FALSE;
1460   gboolean found_own_host_id = FALSE;
1461   gboolean found_flow_id = FALSE;
1462   gint new_ext_hdrs = 0;
1463   guint8 insert_idx = 0;
1464   guint8 source_id = 0;
1465   gboolean ret = FALSE;
1466   guint64 implicit_host_id = dump_priv->implicit_host_id == ERF_META_HOST_ID_IMPLICIT ? 0 : dump_priv->implicit_host_id;
1467
1468
1469   /*
1470    * There are 3 possible scenarios:
1471    * a. The record has a source Host ID but not our Host ID. We need to add our
1472    *    Host ID extension header then our Anchor ID extension header.
1473    * b. The record already has our Host ID extension header on it. We should
1474    *    insert the Anchor ID at the end of the list for that Host ID just
1475    *    before the next Host ID extension header.
1476    * c. The record has no Host ID extension header at all. We need to add the Host ID
1477    *    extension header making the Implicit Host ID explicit before we add our
1478    *    one to avoid claiming the packet was captured by us.
1479    */
1480
1481   /*
1482    * Extract information from the packet extension header stack
1483    * 1. original source Host ID extension header.
1484    * 2. Anchor ID extension header insertion point (see b., above).
1485    * 3. Flow ID extension header so we can add it for reference to the metadata
1486    * record.
1487    * 4. Enough information to generate an explicit Host ID extension header if
1488    *    there wasn't one (see erf_get_source_from_header).
1489    */
1490
1491   has_more = mutable_hdr->erf.phdr.type & 0x80;
1492
1493   while (has_more && (i < MAX_ERF_EHDR)) {
1494     guint64 hdr = mutable_hdr->erf.ehdr_list[i].ehdr;
1495     guint8 type = (guint8) (hdr >> 56);
1496
1497     switch (type & 0x7f) {
1498       case ERF_EXT_HDR_TYPE_HOST_ID:
1499         /* Set insertion point of anchor ID to be at end of Host ID list (i.e.
1500          * just before the next one). */
1501         if (found_own_host_id && !insert_idx)
1502           insert_idx = i;
1503
1504         if ((hdr & ERF_EHDR_HOST_ID_MASK) == dump_priv->host_id){
1505           found_own_host_id = TRUE;
1506         }
1507
1508         if (!found_host_id)
1509           host_id_src_hdr = hdr;
1510
1511         found_host_id = TRUE;
1512         break;
1513
1514       case ERF_EXT_HDR_TYPE_FLOW_ID:
1515         /*XXX: we only use this when making the implicit host id explicit,
1516          * otherwise we'd need to check the one in Host ID header too*/
1517         if (source_id == 0)
1518           source_id = (guint8)(hdr >> 48);
1519
1520         if (!found_flow_id)
1521           flow_id_hdr = hdr;
1522
1523         found_flow_id = TRUE;
1524         break;
1525     }
1526
1527     has_more = type & 0x80;
1528     i += 1;
1529   }
1530
1531   ext_hdr_count = i;
1532
1533   if (!insert_idx)
1534     insert_idx = i;
1535
1536   /* Don't need to add our own Host ID twice if it is the same as the implicit*/
1537   if (!found_host_id && implicit_host_id == dump_priv->host_id) {
1538     found_own_host_id = TRUE;
1539   }
1540
1541   /*
1542    * Update the packet record pseudo_header with Anchor ID and extension header(s)
1543    */
1544   new_ext_hdrs = 1 /*anchor id*/ + (found_own_host_id?0:1) + (found_host_id?0:1);
1545
1546   if(ext_hdr_count + new_ext_hdrs > MAX_ERF_EHDR
1547       || mutable_hdr->erf.phdr.rlen + new_ext_hdrs * 8 > 65535) {
1548     /* Not enough extension header slots to add Anchor ID */
1549     *err = WTAP_ERR_PACKET_TOO_LARGE;
1550     return FALSE;
1551   }
1552
1553   mutable_hdr->erf.phdr.rlen += new_ext_hdrs * 8;
1554
1555   /* Set the more extension headers flag */
1556   mutable_hdr->erf.phdr.type |= 0x80;
1557   if (insert_idx > 0) {
1558     mutable_hdr->erf.ehdr_list[insert_idx-1].ehdr |= ERF_EHDR_MORE_EXTHDR_MASK;
1559   }
1560
1561   /* Generate the Anchor ID extension header */
1562   anchor_id_hdr = erf_anchor_id_ext_hdr(erf_get_random_anchor_id(dump_priv), 0);
1563
1564   /* Either we can insert Anchor ID at the end of the list for our Host ID or we
1565    * need to append the Host ID(s) and Anchor ID */
1566   if (insert_idx < ext_hdr_count) {
1567     /* shuffle up any following extension headers FIRST - we know we have room now */
1568     for (j = ext_hdr_count; j > insert_idx; j--) {
1569       mutable_hdr->erf.ehdr_list[j].ehdr = mutable_hdr->erf.ehdr_list[j-1].ehdr;
1570     }
1571
1572     /* copy more extension headers bit from previous extension header */
1573     anchor_id_hdr |= ERF_EHDR_MORE_EXTHDR_MASK;
1574   }
1575
1576   if(!found_host_id) {
1577     /* No Host ID extension header found and we have an implicit Host ID which
1578      * we want to make explicit */
1579
1580     /* XXX: it is important that we know the implicit Host ID here or we end
1581      * up semi-permentantly associating the packet with Host 0 (unknown), we should
1582      * pass it through from the reader. In theory we should be on the
1583      * original capture machine if we have no Host ID extension headers. */
1584     host_id_src_hdr = erf_host_id_ext_hdr(implicit_host_id, source_id);
1585     mutable_hdr->erf.ehdr_list[insert_idx++].ehdr = ERF_EHDR_SET_MORE_EXTHDR(host_id_src_hdr);
1586   }
1587
1588   if(!found_own_host_id) {
1589     /* Add our Host ID extension header */
1590     mutable_hdr->erf.ehdr_list[insert_idx++].ehdr = ERF_EHDR_SET_MORE_EXTHDR(host_id_own_hdr);
1591   }
1592
1593   /*Add the Anchor ID extension header */
1594   mutable_hdr->erf.ehdr_list[insert_idx].ehdr = anchor_id_hdr;
1595
1596
1597   /*
1598    * Now construct the metadata Anchor record with the same Anchor ID
1599    */
1600
1601   meta_ehdrs = g_array_new(FALSE, FALSE, sizeof(struct erf_ehdr));
1602
1603   /* We need up to 4 extension headers on the Provenance metadata record */
1604   /*Required*/
1605   /* 1. Added by erf_write_meta_record: HostID exthdr to indicate this Anchor
1606    * record was generated by this host. Source ID 0 to avoid changing the
1607    * implicit Host ID. */
1608
1609   /* 2. AnchorID exthdr with 'unique' per-host Anchor ID assigned by this host
1610    * (in this case Wireshark). Anchor defintion flag set to 1 to indicate this
1611    * record contains a defintion of the ID, in this case a comment on a single
1612    * packet. Tied to above extension header by ordering like a list */
1613   erf_append_ext_hdr_to_list(anchor_id_hdr | ERF_EHDR_ANCHOR_ID_DEFINITION_MASK, meta_ehdrs);
1614
1615   /*Helpful for indexing*/
1616   /* 3. HostID exthdr with the original Source (first Host ID extension header) of the packet record */
1617   erf_append_ext_hdr_to_list(host_id_src_hdr, meta_ehdrs);
1618
1619   /* Flow ID extension header from the packet record if we have one */
1620   if (found_flow_id) {
1621     /* 4. FlowID exthdr with Flow ID from the packet so a flow search will find the comment
1622      * record too. Must come here so the (redundant here) Source ID is scoped to the
1623      * correct Host ID. */
1624     /* Clear the stack type just in case something tries to assume we're an IP
1625      * packet without looking at the ERF type. Clear Source ID too just in case
1626      * we're trying to associate with the wrong Host ID. */
1627     erf_append_ext_hdr_to_list(flow_id_hdr & ~(ERF_EHDR_FLOW_ID_STACK_TYPE_MASK|ERF_EHDR_FLOW_ID_SOURCE_ID_MASK), meta_ehdrs);
1628   }
1629
1630   /* Generate the metadata payload with the packet comment */
1631   sections = g_ptr_array_new_with_free_func(erf_meta_section_free);
1632   erf_comment_to_sections(wdh, ERF_META_SECTION_INFO, 0x8000 /*local to record*/, rec->opt_comment, sections);
1633
1634   /* Write the metadata record, but not the packet record as what we do depends
1635    * on the WTAP_ENCAP */
1636   ret = erf_write_meta_record(wdh, dump_priv, mutable_hdr->erf.phdr.ts, sections, meta_ehdrs, err);
1637   g_ptr_array_free(sections, TRUE);
1638   g_array_free(meta_ehdrs, TRUE);
1639
1640   return ret;
1641 }
1642
1643 static gboolean erf_write_meta_record(wtap_dumper *wdh, erf_dump_t *dump_priv, guint64 timestamp, GPtrArray *sections, GArray *extra_ehdrs, int *err) {
1644   union wtap_pseudo_header other_header;
1645   struct erf_meta_tag gen_time_tag;
1646   struct erf_meta_section *section_ptr;
1647   guint total_wlen = 0;
1648   guint total_rlen = 0;
1649   gint64 alignbytes = 0;
1650   guint i;
1651   guint num_extra_ehdrs = 0;
1652
1653   if(!sections || sections->len <= 0)
1654     return FALSE;
1655
1656   for(i = 0; i < sections->len; i++) {
1657     section_ptr = (struct erf_meta_section*)g_ptr_array_index(sections, i);
1658     total_wlen += section_ptr->section_length;
1659   }
1660
1661   gen_time_tag.type = ERF_META_TAG_gen_time;
1662   gen_time_tag.length = 8U;
1663   gen_time_tag.value = (guint8*)&dump_priv->gen_time;
1664   total_wlen += gen_time_tag.length + 4;
1665
1666   total_rlen = total_wlen + 24; /* 24 is the header + extension header length */
1667   if (extra_ehdrs) {
1668     /*
1669      * These will be appended to the first extension header in
1670      * other_header.erf.ehdr_list.  There are a total of MAX_ERF_EHDR
1671      * extension headers in that array, so we can append no more than
1672      * MAX_ERF_EHDR - 1 extension headeers.
1673      */
1674     num_extra_ehdrs = MIN(extra_ehdrs->len, MAX_ERF_EHDR - 1);
1675     total_rlen += num_extra_ehdrs * 8;
1676   }
1677   /*padding to 8 byte alignment*/
1678   total_rlen += ERF_PADDING_TO_8(total_rlen);
1679
1680   if(total_rlen > 65535) {
1681     *err = WTAP_ERR_PACKET_TOO_LARGE;
1682     return FALSE;
1683   }
1684
1685   other_header.erf.phdr.ts = timestamp;
1686   other_header.erf.phdr.type = ERF_TYPE_META | 0x80;
1687   other_header.erf.phdr.flags = 0x04; /* Varying record length */
1688   other_header.erf.phdr.lctr = 0;
1689   other_header.erf.phdr.wlen = (guint16)total_wlen;
1690   other_header.erf.phdr.rlen = (guint16)total_rlen;
1691   /*Add our Host ID in Host ID extension header indicating we generated this
1692    * record. Source ID 0 to avoid affecting implicit Host ID. */
1693   other_header.erf.ehdr_list[0].ehdr = erf_host_id_ext_hdr(dump_priv->host_id, 0);
1694   /*Additional extension headers*/
1695   /*XXX: If we end up cutting the list short, erf_write_phdr will correct the
1696    * unterminated extension header list*/
1697   if (num_extra_ehdrs > 0) {
1698     other_header.erf.ehdr_list[0].ehdr |= ERF_EHDR_MORE_EXTHDR_MASK;
1699     memcpy(&other_header.erf.ehdr_list[1], extra_ehdrs->data, sizeof(struct erf_ehdr) * num_extra_ehdrs);
1700   }
1701
1702   /* Make sure we always write out rlen, regardless of what happens */
1703   alignbytes = wdh->bytes_dumped + other_header.erf.phdr.rlen;
1704
1705   if(!erf_write_phdr(wdh, WTAP_ENCAP_ERF, &other_header, err)) return FALSE;
1706
1707   /* Generation time */
1708   erf_meta_write_tag(wdh, &gen_time_tag, err);
1709
1710   /* Section(s) */
1711   for(i = 0; i < sections->len; i++) {
1712     section_ptr = (struct erf_meta_section*)g_ptr_array_index(sections, i);
1713     erf_meta_write_section(wdh, section_ptr, err);
1714   }
1715
1716   while(wdh->bytes_dumped < alignbytes){
1717     if(!wtap_dump_file_write(wdh, "", 1, err)) return FALSE;
1718     wdh->bytes_dumped++;
1719   }
1720
1721   /* We wrote new packets, reloading is required */
1722   wdh->needs_reload = TRUE;
1723
1724   return TRUE;
1725
1726 }
1727
1728 erf_dump_t *erf_dump_priv_create(void) {
1729   erf_dump_t *dump_priv;
1730
1731   dump_priv = (erf_dump_t*)g_malloc(sizeof(erf_dump_t));
1732   dump_priv->write_next_extra_meta = FALSE;
1733   dump_priv->last_meta_periodic = FALSE;
1734   dump_priv->gen_time = 0;
1735   dump_priv->host_id = ERF_WS_DEFAULT_HOST_ID;
1736   dump_priv->implicit_host_id = ERF_META_HOST_ID_IMPLICIT;
1737   dump_priv->first_frame_time_sec = 0;
1738   dump_priv->prev_inserted_time_sec = 0;
1739   dump_priv->prev_frame_ts = 0;
1740   dump_priv->prev_erf_type = 0;
1741   dump_priv->user_comment_ptr = NULL;
1742   dump_priv->periodic_sections = NULL;
1743   dump_priv->periodic_extra_ehdrs = g_array_new(FALSE, FALSE, sizeof(struct erf_ehdr));
1744   dump_priv->rand = g_rand_new();
1745
1746   return dump_priv;
1747 }
1748
1749 static gboolean erf_dump(
1750     wtap_dumper                    *wdh,
1751     const wtap_rec                 *rec,
1752     const guint8                   *pd,
1753     int                            *err,
1754     gchar                          **err_info _U_)
1755 {
1756   const union wtap_pseudo_header *pseudo_header = &rec->rec_header.packet_header.pseudo_header;
1757   union wtap_pseudo_header other_phdr;
1758   int      encap;
1759   int      erf_type;
1760   gint64   alignbytes   = 0;
1761   guint    padbytes   = 0;
1762   int      round_down   = 0;
1763   gboolean must_add_crc = FALSE;
1764   guint32  crc32        = 0x00000000;
1765   erf_dump_t *dump_priv = (erf_dump_t*)wdh->priv;
1766   /* Host ID extension header with Host ID 0 (unknown). For now use Source ID 1. */
1767   /* TODO: How to know if record was captured by this Wireshark? */
1768   guint64  non_erf_host_id_ehdr = erf_host_id_ext_hdr(0, 1);
1769
1770   /* Don't write anything bigger than we're willing to read. */
1771   if(rec->rec_header.packet_header.caplen > WTAP_MAX_PACKET_SIZE_STANDARD) {
1772     *err = WTAP_ERR_PACKET_TOO_LARGE;
1773     return FALSE;
1774   }
1775
1776   if(wdh->encap == WTAP_ENCAP_PER_PACKET){
1777     encap = rec->rec_header.packet_header.pkt_encap;
1778   }else{
1779     encap = wdh->encap;
1780   }
1781
1782   if(!dump_priv->gen_time) {
1783     erf_dump_priv_init_gen_time(dump_priv);
1784     dump_priv->first_frame_time_sec = rec->ts.secs;
1785   }
1786
1787   if (encap != WTAP_ENCAP_ERF) {
1788     unsigned int total_rlen;;
1789     unsigned int total_wlen;
1790
1791     /*Non-ERF*/
1792
1793     total_rlen = rec->rec_header.packet_header.caplen+16;
1794     total_wlen = rec->rec_header.packet_header.len;
1795
1796     /* We can only convert packet records. */
1797     if (rec->rec_type != REC_TYPE_PACKET) {
1798       *err = WTAP_ERR_UNWRITABLE_REC_TYPE;
1799       return FALSE;
1800     }
1801
1802     if ((erf_type = wtap_wtap_encap_to_erf_encap(encap)) == -1) {
1803       *err = WTAP_ERR_UNWRITABLE_ENCAP;
1804       return FALSE;
1805     }
1806
1807     /* Generate a fake header in other_phdr using data that we know*/
1808     memset(&other_phdr, 0, sizeof(union wtap_pseudo_header));
1809     /* Convert time erf timestamp format*/
1810     other_phdr.erf.phdr.ts = ((guint64) rec->ts.secs << 32) + (((guint64) rec->ts.nsecs <<32) / 1000 / 1000 / 1000);
1811     other_phdr.erf.phdr.type = (guint8)erf_type;
1812     /* Support up to 4 interfaces */
1813     /* TODO: use multiple Source IDs and metadata records to support >4 interfaces */
1814     other_phdr.erf.phdr.flags = rec->rec_header.packet_header.interface_id % ERF_MAX_INTERFACES;
1815     other_phdr.erf.phdr.flags |= 0x4;  /*vlen flag set because we're creating variable length records*/
1816
1817     other_phdr.erf.phdr.lctr = 0;
1818
1819     /*now we work out rlen, accounting for all the different headers and missing fcs(eth)*/
1820     switch(other_phdr.erf.phdr.type & 0x7F){
1821       case ERF_TYPE_ETH:
1822         total_rlen += 2;  /*2 bytes for erf eth_type*/
1823         if (pseudo_header->eth.fcs_len != 4) {
1824           /* Either this packet doesn't include the FCS
1825              (pseudo_header->eth.fcs_len = 0), or we don't
1826              know whether it has an FCS (= -1).  We have to
1827              synthesize an FCS.*/
1828           if(!(rec->rec_header.packet_header.caplen < rec->rec_header.packet_header.len)){ /*don't add FCS if packet has been snapped off*/
1829             crc32 = crc32_ccitt_seed(pd, rec->rec_header.packet_header.caplen, 0xFFFFFFFF);
1830             total_rlen += 4;  /*4 bytes for added checksum*/
1831             total_wlen += 4;
1832             must_add_crc = TRUE;
1833           }
1834         }
1835         break;
1836       case ERF_TYPE_HDLC_POS:
1837         /*we assume that it's missing a FCS checksum, make one up*/
1838         if(!(rec->rec_header.packet_header.caplen < rec->rec_header.packet_header.len)){  /*unless of course, the packet has been snapped off*/
1839           crc32 = crc32_ccitt_seed(pd, rec->rec_header.packet_header.caplen, 0xFFFFFFFF);
1840           total_rlen += 4;  /*4 bytes for added checksum*/
1841           total_wlen += 4;
1842           must_add_crc = TRUE; /* XXX - these never have an FCS? */
1843         }
1844         break;
1845       default:
1846         break;
1847     }
1848
1849     /* Add Host ID extension header with Host ID 0 (unknown). For now use Source ID 1. */
1850     other_phdr.erf.phdr.type |= 0x80;
1851     other_phdr.erf.ehdr_list[0].ehdr = non_erf_host_id_ehdr;
1852     total_rlen += 8;
1853
1854     padbytes = ERF_PADDING_TO_8(total_rlen);  /*calculate how much padding will be required */
1855     if(rec->rec_header.packet_header.caplen < rec->rec_header.packet_header.len){ /*if packet has been snapped, we need to round down what we output*/
1856       round_down = (8 - padbytes) % 8;
1857       total_rlen -= round_down;
1858     }else{
1859       total_rlen += padbytes;
1860     }
1861
1862     if (total_rlen > G_MAXUINT16 || total_wlen > G_MAXUINT16) {
1863       *err = WTAP_ERR_PACKET_TOO_LARGE;
1864       return FALSE;
1865     }
1866
1867     other_phdr.erf.phdr.rlen = (guint16)total_rlen;
1868     other_phdr.erf.phdr.wlen = (guint16)total_wlen;
1869
1870     pseudo_header = &other_phdr;
1871   }
1872
1873   /* We now have a (real or fake) ERF record */
1874   erf_type = pseudo_header->erf.phdr.type & 0x7FU;
1875
1876   /* Accumulate Host ID/Source ID to put in updated periodic metadata */
1877   /* TODO: pass these through from read interface list instead? */
1878   /* Note: this includes the one we made for the fake ERF header */
1879   erf_update_host_id_ext_hdrs_list(dump_priv, pseudo_header, dump_priv->periodic_extra_ehdrs);
1880
1881   /* Insert new metadata record depending on whether the capture comment has
1882    * changed. Write metadata each second at boundaries. If there is metadata
1883    * write at the end of each of metadata records so we update the metadata. */
1884   if (erf_type == ERF_TYPE_META) {
1885     /* Check whether the capture comment string has changed */
1886     /* Updates write_next_extra_meta */
1887     dump_priv->last_meta_periodic = erf_dump_priv_compare_capture_comment(wdh, dump_priv, pseudo_header, pd);
1888   } else { /* don't want to insert a new metadata record while looking at another */
1889     if (dump_priv->prev_erf_type == ERF_TYPE_META && dump_priv->last_meta_periodic) {
1890       /* Last frame was a periodic (non-comment) metadata record (and this frame is not), check if we
1891        * need to insert one to update metdata. */
1892
1893       if(dump_priv->write_next_extra_meta) {
1894         if (!dump_priv->periodic_sections) {
1895           /* If we've seen metadata just insert the capture comment and not the
1896            * rest of the metadata */
1897           dump_priv->periodic_sections = g_ptr_array_new_with_free_func(erf_meta_section_free);
1898           erf_comment_to_sections(wdh, ERF_META_SECTION_CAPTURE, 0, dump_priv->user_comment_ptr, dump_priv->periodic_sections);
1899         }
1900
1901         if (!erf_write_meta_record(wdh, dump_priv, dump_priv->prev_frame_ts, dump_priv->periodic_sections, dump_priv->periodic_extra_ehdrs, err)) return FALSE;
1902         dump_priv->prev_inserted_time_sec = rec->ts.secs;
1903         /*TODO: clear accumulated existing extension headers here?*/
1904       }
1905
1906       /* If we have seen a metadata record in the first ~1 second it
1907        * means that we are dealing with an ERF file with metadata already in them.
1908        * We dont want to write extra metadata if nothing has changed. We can't
1909        * trust the Wireshark representation since we massage the fields on
1910        * read. */
1911       /* restart searching for next meta record to update capture comment at */
1912       dump_priv->write_next_extra_meta = FALSE;
1913     } else if (rec->ts.secs > dump_priv->first_frame_time_sec + 1
1914           && dump_priv->prev_inserted_time_sec != rec->ts.secs) {
1915       /* For compatibility, don't insert metadata for older ERF files with no changed metadata */
1916       if (dump_priv->write_next_extra_meta) {
1917         if (!dump_priv->periodic_sections) {
1918           /* If we get here, metadata record was not found in the first ~1 sec
1919            * but we have either a capture comment or a non-ERF file (see
1920            * erf_dump_open) */
1921           /* Start inserting metadata records from wtap data at second boundaries */
1922           dump_priv->periodic_sections = g_ptr_array_new_with_free_func(erf_meta_section_free);
1923           erf_wtap_info_to_sections(wdh, dump_priv->periodic_sections);
1924         }
1925       }
1926
1927       /* At second boundaries insert either the updated comment (if we've seen some metadata records
1928        * already) or the full metadata */
1929       if (dump_priv->periodic_sections) {
1930         if (!erf_write_meta_record(wdh, dump_priv, (guint64)(rec->ts.secs) << 32, dump_priv->periodic_sections, dump_priv->periodic_extra_ehdrs, err)) return FALSE;
1931         dump_priv->prev_inserted_time_sec = rec->ts.secs;
1932       }
1933     }
1934   }
1935
1936   /* If the packet user comment has changed, we need to
1937    * construct a new header with additional Host ID and Anchor ID
1938    * and insert a metadata record before that frame */
1939   /*XXX: The user may have changed the comment to cleared! */
1940   if(rec->opt_comment || rec->has_comment_changed) {
1941     if (encap == WTAP_ENCAP_ERF) {
1942       /* XXX: What about ERF-in-pcapng with existing comment (that wasn't
1943        * modified)? */
1944       if(rec->has_comment_changed) {
1945         memcpy(&other_phdr, pseudo_header, sizeof(union wtap_pseudo_header));
1946         if(!erf_write_anchor_meta_update_phdr(wdh, dump_priv, rec, &other_phdr, err)) return FALSE;
1947         pseudo_header = &other_phdr;
1948       }
1949     } else {
1950       /* Always write the comment if non-ERF */
1951       if(!erf_write_anchor_meta_update_phdr(wdh, dump_priv, rec, &other_phdr, err)) return FALSE;
1952     }
1953   }
1954
1955   /* Make sure we always write out rlen, regardless of what happens */
1956   alignbytes = wdh->bytes_dumped + pseudo_header->erf.phdr.rlen;
1957
1958   if(!erf_write_phdr(wdh, WTAP_ENCAP_ERF, pseudo_header, err)) return FALSE;
1959
1960   if(!wtap_dump_file_write(wdh, pd, rec->rec_header.packet_header.caplen - round_down, err)) return FALSE;
1961   wdh->bytes_dumped += rec->rec_header.packet_header.caplen - round_down;
1962
1963   /*add the 4 byte CRC if necessary*/
1964   if(must_add_crc){
1965     if(!wtap_dump_file_write(wdh, &crc32, 4, err)) return FALSE;
1966     wdh->bytes_dumped += 4;
1967   }
1968
1969   /*XXX: In the case of ENCAP_ERF, this pads the record to its original length, which is fine in most
1970    * cases. However with >MAX_ERF_EHDR unnecessary padding will be added, and
1971    * if the record was truncated this will be incorrectly treated as payload.
1972    * More than 8 extension headers is unusual though, only the first 8 are
1973    * written out anyway and fixing properly would require major refactor.*/
1974   /*records should be 8byte aligned, so we add padding to our calculated rlen */
1975   while(wdh->bytes_dumped < alignbytes){
1976     if(!wtap_dump_file_write(wdh, "", 1, err)) return FALSE;
1977     wdh->bytes_dumped++;
1978   }
1979
1980   dump_priv->prev_erf_type = pseudo_header->erf.phdr.type & 0x7FU;
1981   dump_priv->prev_frame_ts = pseudo_header->erf.phdr.ts;
1982
1983   return TRUE;
1984 }
1985
1986 int erf_dump_can_write_encap(int encap)
1987 {
1988
1989   if(encap == WTAP_ENCAP_PER_PACKET)
1990     return 0;
1991
1992   if (wtap_wtap_encap_to_erf_encap(encap) == -1)
1993     return WTAP_ERR_UNWRITABLE_ENCAP;
1994
1995   return 0;
1996 }
1997
1998 int erf_dump_open(wtap_dumper *wdh, int *err _U_)
1999 {
2000   erf_dump_t *dump_priv;
2001   gchar *s;
2002   guint64 host_id;
2003
2004   dump_priv = erf_dump_priv_create();
2005
2006   wdh->subtype_write = erf_dump;
2007   wdh->priv = dump_priv;
2008   wdh->subtype_finish = erf_dump_finish;
2009
2010   /* Get the capture comment string */
2011   get_user_comment_string(wdh, &dump_priv->user_comment_ptr);
2012   /* XXX: If we have a capture comment or a non-ERF file assume we need to
2013    * write metadata unless we see existing metadata in the first second. */
2014   if (dump_priv->user_comment_ptr || wdh->encap != WTAP_ENCAP_ERF)
2015     dump_priv->write_next_extra_meta = TRUE;
2016
2017   /* Read Host ID from environment variable */
2018   /* TODO: generate one from MAC address? */
2019   if ((s = getenv("ERF_HOST_ID")) != NULL) {
2020     /* TODO: support both decimal and hex strings (base 0)? */
2021     if (ws_hexstrtou64(s, NULL, &host_id)) {
2022       dump_priv->host_id = host_id & ERF_EHDR_HOST_ID_MASK;
2023     }
2024   }
2025
2026   return TRUE;
2027 }
2028
2029 /*
2030  * TODO: Replace uses in pcapng and pcap with
2031  * erf_read_header() and/or erf_populate_interface_from_header() and delete.
2032  */
2033 int erf_populate_interfaces(wtap *wth)
2034 {
2035   wtap_block_t int_data;
2036   wtapng_if_descr_mandatory_t* int_data_mand;
2037   int i;
2038
2039   if (!wth)
2040     return -1;
2041
2042   /* Preemptively create interface entries for 4 interfaces, since this is the max number in ERF */
2043   for (i=0; i<4; i++) {
2044
2045     int_data = wtap_block_create(WTAP_BLOCK_IF_DESCR);
2046     int_data_mand = (wtapng_if_descr_mandatory_t*)wtap_block_get_mandatory_data(int_data);
2047
2048     int_data_mand->wtap_encap = WTAP_ENCAP_ERF;
2049     /* int_data.time_units_per_second = (1LL<<32);  ERF format resolution is 2^-32, capture resolution is unknown */
2050     int_data_mand->time_units_per_second = 1000000000; /* XXX Since Wireshark only supports down to nanosecond resolution we have to dilute to this */
2051     int_data_mand->snap_len = 65535; /* ERF max length */
2052
2053     /* XXX: if_IPv4addr opt 4  Interface network address and netmask.*/
2054     /* XXX: if_IPv6addr opt 5  Interface network address and prefix length (stored in the last byte).*/
2055     /* XXX: if_MACaddr  opt 6  Interface Hardware MAC address (48 bits).*/
2056     /* XXX: if_EUIaddr  opt 7  Interface Hardware EUI address (64 bits)*/
2057     /* XXX: if_speed    opt 8  Interface speed (in bits per second)*/
2058     /* int_data.if_tsresol = 0xa0;  ERF format resolution is 2^-32 = 0xa0, capture resolution is unknown */
2059     wtap_block_add_uint8_option(int_data, OPT_IDB_TSRESOL, 0x09); /* XXX Since Wireshark only supports down to nanosecond resolution we have to dilute to this */
2060
2061     /* XXX: if_tzone      10  Time zone for GMT support (TODO: specify better). */
2062
2063     /* XXX if_tsoffset; opt 14  A 64 bits integer value that specifies an offset (in seconds)...*/
2064     /* Interface statistics */
2065     int_data_mand->num_stat_entries = 0;
2066     int_data_mand->interface_statistics = NULL;
2067
2068     wtap_block_add_string_option_format(int_data, OPT_IDB_NAME, "Port %c", 'A'+i);
2069     wtap_block_add_string_option_format(int_data, OPT_IDB_DESCR, "ERF Interface Id %d (Port %c)", i, 'A'+i);
2070
2071     g_array_append_val(wth->interface_data, int_data);
2072   }
2073
2074   return 0;
2075 }
2076
2077 int erf_get_source_from_header(union wtap_pseudo_header *pseudo_header, guint64 *host_id, guint8 *source_id)
2078 {
2079   guint8   type;
2080   guint8   has_more;
2081   guint64  hdr;
2082   int      i             = 0;
2083   gboolean host_id_found = FALSE;
2084
2085   if (!pseudo_header || !host_id || !source_id)
2086       return -1;
2087
2088   *host_id = ERF_META_HOST_ID_IMPLICIT;
2089   *source_id = 0;
2090
2091   has_more = pseudo_header->erf.phdr.type & 0x80;
2092
2093   while (has_more && (i < MAX_ERF_EHDR)) {
2094     hdr = pseudo_header->erf.ehdr_list[i].ehdr;
2095     type = (guint8) (hdr >> 56);
2096
2097     /*
2098      * XXX: Only want first Source ID and Host ID, and want to preserve HID n SID 0 (see
2099      * erf_populate_interface)
2100      */
2101     switch (type & 0x7f) {
2102       case ERF_EXT_HDR_TYPE_HOST_ID:
2103         if (!host_id_found)
2104           *host_id = hdr & ERF_EHDR_HOST_ID_MASK;
2105
2106         host_id_found = TRUE;
2107         /* Fall through */
2108       case ERF_EXT_HDR_TYPE_FLOW_ID:
2109         if (*source_id == 0)
2110           *source_id = (hdr >> 48) & 0xff;
2111         break;
2112     }
2113
2114     if (host_id_found)
2115       break;
2116
2117     has_more = type & 0x80;
2118     i += 1;
2119   }
2120
2121   return 0;
2122 }
2123
2124 int erf_populate_interface_from_header(erf_t *erf_priv, wtap *wth, union wtap_pseudo_header *pseudo_header)
2125 {
2126   guint64 host_id;
2127   guint8 source_id;
2128   guint8 if_num;
2129
2130   if (!pseudo_header)
2131     return -1;
2132
2133   if_num = pseudo_header->erf.phdr.flags & 0x03;
2134
2135   erf_get_source_from_header(pseudo_header, &host_id, &source_id);
2136
2137   return erf_populate_interface(erf_priv, wth, pseudo_header, host_id, source_id, if_num);
2138 }
2139
2140 static struct erf_if_mapping* erf_find_interface_mapping(erf_t *erf_priv, guint64 host_id, guint8 source_id)
2141 {
2142   struct erf_if_mapping if_map_lookup;
2143
2144   /* XXX: erf_priv should never be NULL here */
2145   if (!erf_priv)
2146     return NULL;
2147
2148   if_map_lookup.host_id = host_id;
2149   if_map_lookup.source_id = source_id;
2150
2151   return (struct erf_if_mapping*) g_hash_table_lookup(erf_priv->if_map, &if_map_lookup);
2152 }
2153
2154 static void erf_set_interface_descr(wtap_block_t block, guint option_id, guint64 host_id, guint8 source_id, guint8 if_num, const gchar *descr)
2155 {
2156   /* Source XXX,*/
2157   char sourceid_buf[16];
2158   /* Host XXXXXXXXXXXX,*/
2159   char hostid_buf[24];
2160
2161   sourceid_buf[0] = '\0';
2162   hostid_buf[0] = '\0';
2163
2164   /* Implicit Host ID defaults to 0 */
2165   if (host_id == ERF_META_HOST_ID_IMPLICIT) {
2166     host_id = 0;
2167   }
2168
2169   if (host_id > 0) {
2170     g_snprintf(hostid_buf, sizeof(hostid_buf), " Host %012" G_GINT64_MODIFIER "x,", host_id);
2171   }
2172
2173   if (source_id > 0) {
2174     g_snprintf(sourceid_buf, sizeof(sourceid_buf), " Source %u,", source_id);
2175   }
2176
2177   if (descr) {
2178     wtap_block_set_string_option_value_format(block, option_id, "%s (ERF%s%s Interface %d)", descr, hostid_buf, sourceid_buf, if_num);
2179   } else {
2180     wtap_block_set_string_option_value_format(block, option_id, "Port %c (ERF%s%s Interface %d)", 'A'+if_num, hostid_buf, sourceid_buf, if_num);
2181   }
2182 }
2183
2184 static int erf_update_anchors_from_header(erf_t *erf_priv, wtap_rec *rec, union wtap_pseudo_header *pseudo_header, guint64 host_id, GPtrArray *anchor_mappings_to_update)
2185 {
2186   guint8   type;
2187   guint8   has_more;
2188   guint64  hdr;
2189   guint64  comment_gen_time = 0;
2190   guint64  host_id_current;
2191   guint64  anchor_id_current = 0;
2192   int      i             = 0;
2193   gchar   *comment = NULL;
2194
2195   if (!rec || !pseudo_header)
2196     return -1;
2197
2198   /* Start with the first Host ID that was found on the record
2199    * as the Anchor ID isn't required to be the first extension header' */
2200   host_id_current = host_id == ERF_META_HOST_ID_IMPLICIT ? erf_priv->implicit_host_id : host_id;
2201
2202   has_more = pseudo_header->erf.phdr.type & 0x80;
2203
2204   while (has_more && (i < MAX_ERF_EHDR)) {
2205     hdr = pseudo_header->erf.ehdr_list[i].ehdr;
2206     type = (guint8) (hdr >> 56);
2207
2208     switch (type & 0x7f) {
2209       case ERF_EXT_HDR_TYPE_HOST_ID:
2210         host_id_current = hdr & ERF_EHDR_HOST_ID_MASK;
2211         break;
2212
2213       case ERF_EXT_HDR_TYPE_ANCHOR_ID:
2214       {
2215         anchor_id_current = hdr & ERF_EHDR_ANCHOR_ID_MASK;
2216         if (!(ERF_ANCHOR_ID_IS_DEFINITION(hdr))) {
2217           /*
2218             * Anchor definiton flag is 0, attempt to associate a comment with this record
2219             * XXX: currently the comment count may be wrong on the first pass!
2220             */
2221           /* We may not have found the implicit Host ID yet, if so we are unlikely to find anything */
2222           struct erf_anchor_mapping* lookup_result;
2223           lookup_result = erf_find_anchor_mapping(erf_priv, host_id_current, anchor_id_current);
2224           if (lookup_result) {
2225             if (lookup_result->gen_time > comment_gen_time) {
2226               /* XXX: we might have a comment that clears the comment (i.e.
2227                * empty string)! */
2228               if (lookup_result->comment && lookup_result->comment[0] != '\0') {
2229                 comment = lookup_result->comment;
2230               }
2231               comment_gen_time = lookup_result->gen_time;
2232             }
2233           }
2234         }
2235         else {
2236           if (anchor_mappings_to_update && (pseudo_header->erf.phdr.type & 0x7f) == ERF_TYPE_META) {
2237             /*
2238              * Anchor definition flag is 1, put the mapping in an array
2239              * which we will later update when we walk through
2240              * the metadata tags
2241              */
2242             /* Only Provenance record can contain the information we need */
2243             struct erf_anchor_mapping *mapping_ptr =
2244               (struct erf_anchor_mapping*)g_malloc0(sizeof(struct erf_anchor_mapping));
2245             /* May be ERF_META_HOST_ID_IMPLICIT */
2246             mapping_ptr->host_id = host_id_current;
2247             mapping_ptr->anchor_id = anchor_id_current;
2248             g_ptr_array_add(anchor_mappings_to_update, mapping_ptr);
2249           }
2250         }
2251         break;
2252       }
2253     }
2254
2255     has_more = type & 0x80;
2256     i += 1;
2257   }
2258
2259   if (comment) {
2260     rec->opt_comment = g_strdup(comment);
2261     rec->presence_flags |= WTAP_HAS_COMMENTS;
2262   } else {
2263     /* WTAP_HAS_COMMENT has no visible effect?
2264      * Need to set opt_comment to NULL to prevent other packets
2265      * from displaying the same comment
2266      */
2267     /* XXX: We cannot free the old comment because it can be for a different
2268      * frame and still in use, wiretap should be handling this better! */
2269     rec->opt_comment = NULL;
2270   }
2271
2272   return 0;
2273 }
2274
2275 /**
2276  * @brief Update the implicit Host ID and Anchor Mapping information
2277  */
2278 static int erf_update_implicit_host_id(erf_t *erf_priv, wtap *wth, guint64 implicit_host_id)
2279 {
2280   GHashTableIter iter;
2281   gpointer iter_value;
2282   GList* implicit_list = NULL;
2283   GList* item = NULL;
2284   wtap_block_t int_data;
2285   struct erf_if_mapping* if_map = NULL;
2286   struct erf_if_mapping* if_map_other = NULL;
2287   struct erf_if_info* if_info = NULL;
2288   struct erf_anchor_mapping* anchor_mapping = NULL;
2289   struct erf_anchor_mapping* anchor_mapping_other = NULL;
2290   gchar *oldstr = NULL;
2291   char portstr_buf[16];
2292   int i;
2293
2294   if (!erf_priv)
2295     return -1;
2296
2297   erf_priv->implicit_host_id = implicit_host_id;
2298
2299   /*
2300    * We need to update the descriptions of all the interfaces with no Host
2301    * ID to the correct Host ID.
2302    */
2303   g_hash_table_iter_init(&iter, erf_priv->if_map);
2304
2305   /* Remove the implicit mappings from the mapping table */
2306   while (g_hash_table_iter_next(&iter, &iter_value, NULL)) {
2307     if_map = (struct erf_if_mapping*) iter_value;
2308
2309     if (if_map->host_id == ERF_META_HOST_ID_IMPLICIT) {
2310       /* Check we don't have an existing interface that matches */
2311       if_map_other = erf_find_interface_mapping(erf_priv, implicit_host_id, if_map->source_id);
2312
2313       if (!if_map_other) {
2314         /* Pull mapping for update */
2315         /* XXX: Can't add while iterating hash table so use list instead */
2316         g_hash_table_iter_steal(&iter);
2317         implicit_list = g_list_prepend(implicit_list, if_map);
2318       } else {
2319         /*
2320          * XXX: We have duplicate interfaces in this case, but not much else we
2321          * can do since we have already dissected the earlier packets. Expected
2322          * to be unusual as it reqires a mix of explicit and implicit Host ID
2323          * (e.g. FlowID extension header only) packets with the same effective
2324          * Host ID before the first ERF_TYPE_META record.
2325          */
2326
2327         /*
2328          * Update the description of the ERF_META_HOST_ID_IMPLICIT interface(s)
2329          * for the first records in one pass mode. In 2 pass mode (Wireshark
2330          * initial open, TShark in 2 pass mode) we will update the interface
2331          * mapping for the frames on the second pass. Relatively consistent
2332          * with the dissector behaviour.
2333          *
2334          * TODO: Can we delete this interface on the second (or even first)
2335          * pass? Should we try to merge in other metadata?
2336          * Needs a wtap_block_copy() that supports overwriting and/or expose
2337          * custom option copy and do with wtap_block_foreach_option().
2338          */
2339         for (i = 0; i < 4; i++) {
2340           if_info = &if_map->interfaces[i];
2341
2342           if (if_info->if_index >= 0) {
2343             /* XXX: this is a pointer! */
2344             int_data = g_array_index(wth->interface_data, wtap_block_t, if_info->if_index);
2345
2346             g_snprintf(portstr_buf, sizeof(portstr_buf), "Port %c", 'A'+i);
2347
2348             oldstr = if_info->name;
2349             if_info->name = g_strconcat(oldstr ? oldstr : portstr_buf, " [unmatched implicit]", NULL);
2350             g_free(oldstr); /* probably null, but g_free doesn't care */
2351
2352             oldstr = if_info->descr;
2353             if_info->descr = g_strconcat(oldstr ? oldstr : portstr_buf, " [unmatched implicit]", NULL);
2354             g_free(oldstr);
2355
2356             erf_set_interface_descr(int_data, OPT_IDB_NAME, implicit_host_id, if_map->source_id, (guint8) i, if_info->name);
2357             erf_set_interface_descr(int_data, OPT_IDB_DESCR, implicit_host_id, if_map->source_id, (guint8) i, if_info->descr);
2358           }
2359         }
2360       }
2361     }
2362   }
2363
2364   /* Re-add the non-clashing items under the real implicit Host ID */
2365   if (implicit_list) {
2366     item = implicit_list;
2367     do {
2368       if_map = (struct erf_if_mapping*) item->data;
2369
2370       for (i = 0; i < 4; i++) {
2371         if_info = &if_map->interfaces[i];
2372
2373         if (if_info->if_index >= 0) {
2374           /* XXX: this is a pointer! */
2375           int_data = g_array_index(wth->interface_data, wtap_block_t, if_info->if_index);
2376           erf_set_interface_descr(int_data, OPT_IDB_NAME, implicit_host_id, if_map->source_id, (guint8) i, if_info->name);
2377           erf_set_interface_descr(int_data, OPT_IDB_DESCR, implicit_host_id, if_map->source_id, (guint8) i, if_info->descr);
2378         }
2379       }
2380
2381       if_map->host_id = implicit_host_id;
2382       /* g_hash_table_add() only exists since 2.32. */
2383       g_hash_table_replace(erf_priv->if_map, if_map, if_map);
2384     } while ((item = g_list_next(item)));
2385
2386     g_list_free(implicit_list);
2387     implicit_list = NULL;
2388   }
2389
2390   /*
2391    * We also need to update the anchor comment mappings
2392    * to the correct Host ID.
2393    */
2394   g_hash_table_iter_init(&iter, erf_priv->anchor_map);
2395
2396   /* Remove the implicit mappings from the mapping table */
2397   while (g_hash_table_iter_next(&iter, &iter_value, NULL)) {
2398     anchor_mapping = (struct erf_anchor_mapping*) iter_value;
2399
2400     if (anchor_mapping->host_id == ERF_META_HOST_ID_IMPLICIT) {
2401       /* Check we don't have an existing anchor that matches */
2402       anchor_mapping_other = erf_find_anchor_mapping(erf_priv, implicit_host_id,
2403           anchor_mapping->anchor_id);
2404
2405       if (anchor_mapping_other && anchor_mapping_other->gen_time >= anchor_mapping->gen_time) {
2406         /*
2407          * XXX: Duplicate entry of anchor mapping, keep the one with newer
2408          * gen_time.
2409          */
2410           g_hash_table_iter_remove(&iter);
2411       } else {
2412         /* Pull mapping for update */
2413         /* XXX: Can't add while iterating hash table so use list instead */
2414         g_hash_table_iter_steal(&iter);
2415         implicit_list = g_list_prepend(implicit_list, anchor_mapping);
2416         /* existing entry (if any) will be removed by g_hash_table_replace */
2417       }
2418     }
2419   }
2420
2421   /* Re-add the non-clashing items under the real implicit Host ID */
2422   if (implicit_list) {
2423     item = implicit_list;
2424     do {
2425       anchor_mapping = (struct erf_anchor_mapping*) item->data;
2426       anchor_mapping->host_id = implicit_host_id;
2427       g_hash_table_replace(erf_priv->anchor_map, anchor_mapping, anchor_mapping);
2428     } while ((item = g_list_next(item)));
2429
2430     g_list_free(implicit_list);
2431     implicit_list = NULL;
2432   }
2433
2434   return 0;
2435 }
2436
2437 int erf_populate_interface(erf_t *erf_priv, wtap *wth, union wtap_pseudo_header *pseudo_header, guint64 host_id, guint8 source_id, guint8 if_num)
2438 {
2439   wtap_block_t int_data;
2440   wtapng_if_descr_mandatory_t* int_data_mand;
2441   struct erf_if_mapping* if_map = NULL;
2442
2443   if (!wth || !pseudo_header || !erf_priv || if_num > 3)
2444     return -1;
2445
2446   if (host_id == ERF_META_HOST_ID_IMPLICIT) {
2447     /* Defaults to ERF_META_HOST_ID_IMPLICIT so we can update mapping later */
2448     host_id = erf_priv->implicit_host_id;
2449   } else if ((pseudo_header->erf.phdr.type & 0x7f) == ERF_TYPE_META) {
2450     /*
2451      * XXX: We assume there is only one Implicit Host ID. As a special case a first
2452      * Host ID extension header with Source ID 0 on a record does not change
2453      * the implicit Host ID. We respect this even though we support only one
2454      * Implicit Host ID.
2455      */
2456     if (erf_priv->implicit_host_id == ERF_META_HOST_ID_IMPLICIT && source_id > 0) {
2457       erf_update_implicit_host_id(erf_priv, wth, host_id);
2458     }
2459   }
2460
2461   if_map = erf_find_interface_mapping(erf_priv, host_id, source_id);
2462
2463   if (!if_map) {
2464     if_map = erf_if_mapping_create(host_id, source_id);
2465     /* g_hash_table_add() only exists since 2.32. */
2466     g_hash_table_replace(erf_priv->if_map, if_map, if_map);
2467
2468   }
2469
2470   /* Return the existing interface if we have it */
2471   if (if_map->interfaces[if_num].if_index >= 0) {
2472     return if_map->interfaces[if_num].if_index;
2473   }
2474
2475   int_data = wtap_block_create(WTAP_BLOCK_IF_DESCR);
2476   int_data_mand = (wtapng_if_descr_mandatory_t*)wtap_block_get_mandatory_data(int_data);
2477
2478   int_data_mand->wtap_encap = WTAP_ENCAP_ERF;
2479   /* int_data.time_units_per_second = (1LL<<32);  ERF format resolution is 2^-32, capture resolution is unknown */
2480   int_data_mand->time_units_per_second = 1000000000; /* XXX Since Wireshark only supports down to nanosecond resolution we have to dilute to this */
2481   int_data_mand->snap_len = 65535; /* ERF max length */
2482
2483   /* XXX: if_IPv4addr opt 4  Interface network address and netmask.*/
2484   /* XXX: if_IPv6addr opt 5  Interface network address and prefix length (stored in the last byte).*/
2485   /* XXX: if_MACaddr  opt 6  Interface Hardware MAC address (48 bits).*/
2486   /* XXX: if_EUIaddr  opt 7  Interface Hardware EUI address (64 bits)*/
2487   /* XXX: if_speed    opt 8  Interface speed (in bits per second)*/
2488   /* int_data.if_tsresol = 0xa0;  ERF format resolution is 2^-32 = 0xa0, capture resolution is unknown */
2489   wtap_block_add_uint8_option(int_data, OPT_IDB_TSRESOL, 0x09); /* XXX Since Wireshark only supports down to nanosecond resolution we have to dilute to this */
2490   /* XXX: if_tzone      10  Time zone for GMT support (TODO: specify better). */
2491   /* XXX if_tsoffset; opt 14  A 64 bits integer value that specifies an offset (in seconds)...*/
2492   /* Interface statistics */
2493   int_data_mand->num_stat_entries = 0;
2494   int_data_mand->interface_statistics = NULL;
2495
2496   erf_set_interface_descr(int_data, OPT_IDB_NAME, host_id, source_id, if_num, NULL);
2497   erf_set_interface_descr(int_data, OPT_IDB_DESCR, host_id, source_id, if_num, NULL);
2498
2499   if_map->interfaces[if_num].if_index = (int) wth->interface_data->len;
2500   g_array_append_val(wth->interface_data, int_data);
2501
2502   return if_map->interfaces[if_num].if_index;
2503 }
2504
2505 static guint32 erf_meta_read_tag(struct erf_meta_tag* tag, guint8 *tag_ptr, guint32 remaining_len)
2506 {
2507   guint16 tagtype;
2508   guint16 taglength;
2509   guint32 tagtotallength;
2510
2511   if (!tag_ptr || !tag || remaining_len < ERF_META_TAG_HEADERLEN)
2512     return 0;
2513
2514   /* tagtype (2 bytes) */
2515   tagtype = pntoh16(&tag_ptr[0]);
2516
2517   /* length (2 bytes) */
2518   taglength = pntoh16(&tag_ptr[2]);
2519
2520   tagtotallength = ERF_META_TAG_TOTAL_ALIGNED_LENGTH(taglength);
2521
2522   if (remaining_len < tagtotallength) {
2523     return 0;
2524   }
2525
2526   tag->type = tagtype;
2527   tag->length = taglength;
2528   tag->value = &tag_ptr[4];
2529
2530   return tagtotallength;
2531 }
2532
2533 static int populate_capture_host_info(erf_t *erf_priv, wtap *wth, union wtap_pseudo_header *pseudo_header _U_, struct erf_meta_read_state *state)
2534 {
2535   struct erf_meta_tag tag = {0, 0, NULL};
2536
2537   wtap_block_t shb_hdr;
2538   char* tmp;
2539   gchar* app_name    = NULL;
2540   gchar* app_version = NULL;
2541   gchar* model       = NULL;
2542   gchar* descr       = NULL;
2543   gchar* cpu         = NULL;
2544   gchar* modelcpu    = NULL;
2545   guint32 tagtotallength;
2546
2547   if (!wth || !state || !wth->shb_hdrs || (wth->shb_hdrs->len == 0))
2548     return -1;
2549
2550   /* XXX: wth->shb_hdr is already created by different layer, using directly for now. */
2551   /* XXX: Only one section header is supported at this time */
2552   shb_hdr = g_array_index(wth->shb_hdrs, wtap_block_t, 0);
2553
2554   while ((tagtotallength = erf_meta_read_tag(&tag, state->tag_ptr, state->remaining_len)) && !ERF_META_IS_SECTION(tag.type)) {
2555     switch (state->sectiontype) {
2556       case ERF_META_SECTION_CAPTURE:
2557       {
2558         if (erf_priv->capture_gentime > state->gen_time) {
2559           return 0;
2560         }
2561
2562         switch (tag.type) {
2563           case ERF_META_TAG_comment:
2564           {
2565             gchar *existing_comment = NULL;
2566             /*XXX: hack to make changing capture comment work since Wireshark only
2567              * displays one. For now just overwrite the comment as we won't
2568              * pick up all of them yet due to the gen_time check above */
2569             if (wtap_block_get_nth_string_option_value(shb_hdr, OPT_COMMENT, 0, &existing_comment) == WTAP_OPTTYPE_SUCCESS) {
2570               wtap_block_set_nth_string_option_value(shb_hdr, OPT_COMMENT, 0, tag.value, tag.length);
2571             } else {
2572               wtap_block_add_string_option(shb_hdr, OPT_COMMENT, tag.value, tag.length);
2573             }
2574             break;
2575           }
2576         }
2577       }
2578       /* Fall through */
2579       case ERF_META_SECTION_HOST:
2580       {
2581         if (erf_priv->host_gentime > state->gen_time) {
2582           return 0;
2583         }
2584
2585         switch (tag.type) {
2586           case ERF_META_TAG_model:
2587             g_free(model);
2588             model = g_strndup((gchar*) tag.value, tag.length);
2589             break;
2590           case ERF_META_TAG_cpu:
2591             g_free(cpu);
2592             cpu = g_strndup((gchar*) tag.value, tag.length);
2593             break;
2594           case ERF_META_TAG_descr:
2595             g_free(descr);
2596             descr = g_strndup((gchar*) tag.value, tag.length);
2597             break;
2598           case ERF_META_TAG_os:
2599             wtap_block_set_string_option_value(shb_hdr, OPT_SHB_OS, tag.value, tag.length);
2600             break;
2601           case ERF_META_TAG_app_name:
2602             g_free(app_name);
2603             app_name = g_strndup((gchar*) tag.value, tag.length);
2604             break;
2605           case ERF_META_TAG_app_version:
2606             g_free(app_version);
2607             app_version = g_strndup((gchar*) tag.value, tag.length);
2608             break;
2609             /* TODO: dag_version? */
2610             /* TODO: could concatenate comment(s)? */
2611           case ERF_META_TAG_filter:
2612             g_free(state->if_map->capture_filter_str);
2613             state->if_map->capture_filter_str = g_strndup((gchar*) tag.value, tag.length);
2614             break;
2615           default:
2616             break;
2617         }
2618       }
2619       break;
2620     }
2621
2622     state->tag_ptr += tagtotallength;
2623     state->remaining_len -= tagtotallength;
2624   }
2625
2626   /* Post processing */
2627
2628   if (app_name) {
2629     /* If no app_version will just use app_name */
2630
2631     tmp = g_strjoin(" ", app_name, app_version, NULL);
2632     wtap_block_set_string_option_value(shb_hdr, OPT_SHB_USERAPPL, tmp, strlen(tmp));
2633     g_free(tmp);
2634
2635     g_free(app_name);
2636     g_free(app_version);
2637     app_name = NULL;
2638     app_version = NULL;
2639   }
2640
2641   /* For the hardware field show description followed by (model; cpu) */
2642   /* Build "Model; CPU" part */
2643   if (model || cpu) {
2644     /* g_strjoin() would be nice to use here if the API didn't stop on the first NULL... */
2645     if (model && cpu) {
2646       modelcpu = g_strconcat(model, "; ", cpu, NULL);
2647     } else if (cpu) {
2648       modelcpu = cpu;
2649       /* avoid double-free */
2650       cpu = NULL;
2651     } else {
2652       modelcpu = model;
2653       /* avoid double-free */
2654       model = NULL;
2655     }
2656   }
2657
2658   /* Combine into "Description (Model; CPU)" */
2659   if (state->sectiontype == ERF_META_SECTION_HOST && descr) {
2660     if (modelcpu) {
2661       wtap_block_set_string_option_value_format(shb_hdr, OPT_SHB_HARDWARE, "%s (%s)", descr, modelcpu);
2662     } else {
2663       wtap_block_set_string_option_value(shb_hdr, OPT_SHB_HARDWARE, descr, strlen(descr));
2664       /*descr = NULL;*/
2665     }
2666   } else if (modelcpu) {
2667     wtap_block_set_string_option_value(shb_hdr, OPT_SHB_HARDWARE, modelcpu, strlen(modelcpu));
2668     /*modelcpu = NULL;*/
2669   }
2670
2671   /* Free the fields we didn't end up using */
2672   g_free(modelcpu);
2673   g_free(model);
2674   g_free(descr);
2675   g_free(cpu);
2676
2677   if (state->sectiontype == ERF_META_SECTION_CAPTURE) {
2678     erf_priv->capture_gentime = state->gen_time;
2679   } else {
2680     erf_priv->host_gentime = state->gen_time;
2681   }
2682
2683   return 1;
2684 }
2685
2686 static int populate_module_info(erf_t *erf_priv _U_, wtap *wth, union wtap_pseudo_header *pseudo_header _U_, struct erf_meta_read_state *state)
2687 {
2688   struct erf_meta_tag tag = {0, 0, NULL};
2689
2690   guint32 tagtotallength;
2691
2692   if (!wth || !state)
2693     return -1;
2694
2695   if (state->if_map->module_gentime > state->gen_time) {
2696     return 0;
2697   }
2698
2699   while ((tagtotallength = erf_meta_read_tag(&tag, state->tag_ptr, state->remaining_len)) && !ERF_META_IS_SECTION(tag.type)) {
2700     switch (tag.type) {
2701       case ERF_META_TAG_fcs_len:
2702         if (tag.length >= 4) {
2703           state->if_map->module_fcs_len = (gint8) pntoh32(tag.value);
2704         }
2705         break;
2706       case ERF_META_TAG_snaplen:
2707         /* XXX: this is generally per stream */
2708         if (tag.length >= 4) {
2709           state->if_map->module_snaplen = pntoh32(tag.value);
2710         }
2711         break;
2712       case ERF_META_TAG_filter:
2713         g_free(state->if_map->module_filter_str);
2714         state->if_map->module_filter_str = g_strndup((gchar*) tag.value, tag.length);
2715         break;
2716     }
2717
2718     state->tag_ptr += tagtotallength;
2719     state->remaining_len -= tagtotallength;
2720   }
2721
2722   state->if_map->module_gentime = state->gen_time;
2723
2724   return 1;
2725 }
2726
2727 static int populate_interface_info(erf_t *erf_priv, wtap *wth, union wtap_pseudo_header *pseudo_header, struct erf_meta_read_state *state)
2728 {
2729   struct erf_meta_tag tag = {0, 0, NULL};
2730   guint32 tagtotallength;
2731   int interface_index = -1;
2732   wtap_block_t int_data = NULL;
2733   wtapng_if_descr_mandatory_t* int_data_mand = NULL;
2734   wtapng_if_descr_filter_t if_filter;
2735   guint32 if_num = 0;
2736   struct erf_if_info* if_info = NULL;
2737
2738   memset(&if_filter, 0, sizeof(if_filter));
2739
2740   if (!wth || !state || !pseudo_header || !state->if_map)
2741     return -1;
2742
2743   /* Section ID of interface is defined to match ERF interface id. */
2744   if_num = state->sectionid - 1;
2745   /*
2746    * Get or create the interface (there can be multiple interfaces in
2747    * a Provenance record).
2748    */
2749   if (if_num < 4) { /* Note: -1u > 4*/
2750     if_info = &state->if_map->interfaces[if_num];
2751     interface_index = if_info->if_index;
2752
2753     /* Check if the interface information is still uninitialized */
2754     if (interface_index == -1) {
2755       guint8 *tag_ptr_tmp = state->tag_ptr;
2756       guint32 remaining_len_tmp = state->remaining_len;
2757
2758       /* First iterate tags, checking we aren't looking at a timing port */
2759       /*
2760        * XXX: we deliberately only do this logic here rather than the per-packet
2761        * population function so that if somehow we do see packets for an
2762        * 'invalid' port the interface will be created at that time.
2763        */
2764       while ((tagtotallength = erf_meta_read_tag(&tag, tag_ptr_tmp, remaining_len_tmp)) && !ERF_META_IS_SECTION(tag.type)) {
2765         if (tag.type == ERF_META_TAG_if_port_type) {
2766           if (tag.length >= 4 && pntoh32(tag.value) == 2) {
2767             /* This is a timing port, skip it from now on */
2768             /* XXX: should we skip all non-capture ports instead? */
2769
2770             if_info->if_index = -2;
2771             interface_index = -2;
2772           }
2773         } else if (tag.type == ERF_META_TAG_stream_num) {
2774           if (tag.length >= 4) {
2775             if_info->stream_num = (gint32) pntoh32(tag.value);
2776           }
2777         }
2778
2779         tag_ptr_tmp += tagtotallength;
2780         remaining_len_tmp -= tagtotallength;
2781       }
2782
2783       /* If the interface is valid but uninitialized, create it */
2784       if (interface_index == -1) {
2785         interface_index = erf_populate_interface(erf_priv, wth, pseudo_header, state->if_map->host_id, state->if_map->source_id, (guint8) if_num);
2786       }
2787     }
2788
2789     /* Get the wiretap interface metadata */
2790     if (interface_index >= 0) {
2791       int_data = g_array_index(wth->interface_data, wtap_block_t, interface_index);
2792       int_data_mand = (wtapng_if_descr_mandatory_t*)wtap_block_get_mandatory_data(int_data);
2793     } else if (interface_index == -2) {
2794       /* timing/unknown port */
2795       return 0;
2796     } else {
2797       return -1;
2798     }
2799   }
2800
2801   /*
2802    * Bail if already have interface metadata or no interface to associate with.
2803    * We also don't support metadata for >4 interfaces per Host + Source
2804    * as we only use interface ID.
2805    */
2806   if (!int_data)
2807     return 0;
2808
2809   if (state->if_map->interface_gentime > state->gen_time && state->if_map->interface_metadata & (1 << if_num))
2810     return 0;
2811
2812   while ((tagtotallength = erf_meta_read_tag(&tag, state->tag_ptr, state->remaining_len)) && !ERF_META_IS_SECTION(tag.type)) {
2813     switch (tag.type) {
2814       case ERF_META_TAG_name:
2815         /* TODO: fall back to module "dev_name Port N"? */
2816         if (!if_info->name) {
2817           if_info->name = g_strndup((gchar*) tag.value, tag.length);
2818           erf_set_interface_descr(int_data, OPT_IDB_NAME, state->if_map->host_id, state->if_map->source_id, (guint8) if_num, if_info->name);
2819
2820           /* If we have no description, also copy to wtap if_description */
2821           if (!if_info->descr) {
2822             erf_set_interface_descr(int_data, OPT_IDB_DESCR, state->if_map->host_id, state->if_map->source_id, (guint8) if_num, if_info->name);
2823           }
2824         }
2825         break;
2826       case ERF_META_TAG_descr:
2827         if (!if_info->descr) {
2828           if_info->descr = g_strndup((gchar*) tag.value, tag.length);
2829           erf_set_interface_descr(int_data, OPT_IDB_DESCR, state->if_map->host_id, state->if_map->source_id, (guint8) if_num, if_info->descr);
2830
2831           /* If we have no name, also copy to wtap if_name */
2832           if (!if_info->name) {
2833             erf_set_interface_descr(int_data, OPT_IDB_NAME, state->if_map->host_id, state->if_map->source_id, (guint8) if_num, if_info->descr);
2834           }
2835         }
2836         break;
2837       case ERF_META_TAG_if_speed:
2838         if (tag.length >= 8)
2839           wtap_block_add_uint64_option(int_data, OPT_IDB_SPEED, pntoh64(tag.value));
2840         break;
2841       case ERF_META_TAG_if_num:
2842         /*
2843          * XXX: We ignore this as Section ID must match the ERF ifid and
2844          * that is all we care about/have space for at the moment. if_num
2845          * is only really useful with >4 interfaces.
2846          */
2847         /* TODO: might want to put this number in description */
2848         break;
2849       case ERF_META_TAG_fcs_len:
2850         if (tag.length >= 4) {
2851           wtap_block_add_uint8_option(int_data, OPT_IDB_FCSLEN, (guint8) pntoh32(tag.value));
2852           if_info->set_flags.fcs_len = 1;
2853         }
2854         break;
2855       case ERF_META_TAG_snaplen:
2856         /* XXX: this generally per stream */
2857         if (tag.length >= 4) {
2858           int_data_mand->snap_len = pntoh32(tag.value);
2859           if_info->set_flags.snaplen = 1;
2860         }
2861         break;
2862       case ERF_META_TAG_comment:
2863         wtap_block_add_string_option(int_data, OPT_COMMENT, tag.value, tag.length);
2864         break;
2865       case ERF_META_TAG_filter:
2866         if_filter.if_filter_str = g_strndup((gchar*) tag.value, tag.length);
2867         wtap_block_add_custom_option(int_data, OPT_IDB_FILTER, &if_filter, sizeof if_filter);
2868         g_free(if_filter.if_filter_str);
2869         if_info->set_flags.filter = 1;
2870         break;
2871       default:
2872         break;
2873     }
2874
2875     state->tag_ptr += tagtotallength;
2876     state->remaining_len -= tagtotallength;
2877   }
2878
2879   /* Post processing */
2880   /*
2881    * XXX: Assumes module defined first. It is higher in hierarchy so only set
2882    * if not already.
2883    */
2884
2885   /*
2886    * XXX: Missing exposed existence/type-check. No way currently to check if
2887    * been set in the optionblock.
2888    */
2889   if (!if_info->set_flags.filter) {
2890     if (state->if_map->module_filter_str) {
2891       /* Duplicate because might use with multiple interfaces */
2892       if_filter.if_filter_str = state->if_map->module_filter_str;
2893       wtap_block_add_custom_option(int_data, OPT_IDB_FILTER, &if_filter, sizeof if_filter);
2894       /*
2895        * Don't set flag because stream is more specific than module.
2896        */
2897     } else if (state->if_map->capture_filter_str) {
2898       /* TODO: display separately? Note that we could have multiple captures
2899        * from multiple hosts in the file */
2900       if_filter.if_filter_str = state->if_map->capture_filter_str;
2901       wtap_block_add_custom_option(int_data, OPT_IDB_FILTER, &if_filter, sizeof if_filter);
2902     }
2903   }
2904
2905   if (state->if_map->module_fcs_len != -1 && !if_info->set_flags.fcs_len) {
2906     wtap_block_add_uint8_option(int_data, OPT_IDB_FCSLEN, (guint8) state->if_map->module_fcs_len);
2907     if_info->set_flags.fcs_len = 1;
2908   }
2909
2910   if (state->if_map->module_snaplen != (guint32) -1 && !if_info->set_flags.snaplen) {
2911     int_data_mand->snap_len = pntoh32(tag.value);
2912     if_info->set_flags.snaplen = 1;
2913   }
2914
2915   state->interface_metadata |= 1 << if_num;
2916
2917   return 1;
2918 }
2919
2920 static int populate_stream_info(erf_t *erf_priv _U_, wtap *wth, union wtap_pseudo_header *pseudo_header, struct erf_meta_read_state *state)
2921 {
2922   struct erf_meta_tag tag = {0, 0, NULL};
2923   guint32 tagtotallength;
2924   int interface_index = -1;
2925   wtap_block_t int_data = NULL;
2926   wtapng_if_descr_mandatory_t* int_data_mand = NULL;
2927   wtapng_if_descr_filter_t if_filter;
2928   guint32 if_num = 0;
2929   gint32 stream_num = -1;
2930   guint8 *tag_ptr_tmp;
2931   guint32 remaining_len_tmp;
2932   struct erf_if_info* if_info = NULL;
2933
2934   memset(&if_filter, 0, sizeof(if_filter));
2935
2936   if (!wth || !pseudo_header || !state || !state->if_map)
2937     return -1;
2938
2939   tag_ptr_tmp = state->tag_ptr;
2940   remaining_len_tmp = state->remaining_len;
2941
2942   /*
2943    * XXX: We ignore parent section ID because it doesn't represent the
2944    * many-to-many relationship of interfaces and streams very well. The stream is
2945    * associated with all interfaces in the record that don't have a stream_num
2946    * that says otherwise.
2947    */
2948
2949   if (state->sectionid > 0 && state->sectionid != 0x7fff) {
2950     /* Section ID of stream is supposed to match stream_num. */
2951     stream_num = state->sectionid - 1;
2952   } else {
2953     /* First iterate tags, looking for the stream number interfaces might associate with. */
2954     while ((tagtotallength = erf_meta_read_tag(&tag, tag_ptr_tmp, remaining_len_tmp)) && !ERF_META_IS_SECTION(tag.type)) {
2955       if (tag.type == ERF_META_TAG_stream_num) {
2956         if (tag.length >= 4) {
2957           stream_num = (gint32) pntoh32(tag.value);
2958         }
2959       }
2960
2961       tag_ptr_tmp += tagtotallength;
2962       remaining_len_tmp -= tagtotallength;
2963     }
2964   }
2965   /* Otherwise assume the stream applies to all interfaces in the record */
2966
2967   for (if_num = 0; if_num < 4; if_num++) {
2968     tag_ptr_tmp = state->tag_ptr;
2969     remaining_len_tmp = state->remaining_len;
2970     if_info = &state->if_map->interfaces[if_num];
2971
2972     /* Check if we should be handling this interface */
2973     /* XXX: currently skips interfaces that are not in the record. */
2974     if (state->if_map->interface_metadata & (1 << if_num)
2975         || !(state->interface_metadata & (1 << if_num))) {
2976       continue;
2977     }
2978
2979     if (if_info->stream_num != -1
2980         && if_info->stream_num != stream_num) {
2981       continue;
2982     }
2983
2984     interface_index = if_info->if_index;
2985     /* Get the wiretap interface metadata */
2986     if (interface_index >= 0) {
2987         int_data = g_array_index(wth->interface_data, wtap_block_t, interface_index);
2988         int_data_mand = (wtapng_if_descr_mandatory_t*)wtap_block_get_mandatory_data(int_data);
2989     }
2990
2991     if (!int_data) {
2992       continue;
2993     }
2994
2995     while ((tagtotallength = erf_meta_read_tag(&tag, tag_ptr_tmp, remaining_len_tmp)) && !ERF_META_IS_SECTION(tag.type)) {
2996       switch (tag.type) {
2997         case ERF_META_TAG_fcs_len:
2998           if (tag.length >= 4) {
2999             /* Use the largest fcslen of matching streams */
3000             gint8 fcs_len = (gint8) pntoh32(tag.value);
3001             guint8 old_fcs_len = 0;
3002
3003             switch (wtap_block_get_uint8_option_value(int_data, OPT_IDB_FCSLEN, &old_fcs_len)) {
3004
3005               case WTAP_OPTTYPE_SUCCESS:
3006                 /* We already have an FCS length option; update it. */
3007                 if (fcs_len > old_fcs_len || !if_info->set_flags.fcs_len) {
3008                   wtap_block_set_uint8_option_value(int_data, OPT_IDB_FCSLEN, (guint8) pntoh32(tag.value));
3009                   if_info->set_flags.fcs_len = 1;
3010                 }
3011                 break;
3012
3013               case WTAP_OPTTYPE_NOT_FOUND:
3014                 /* We don't have an FCS length option; add it. */
3015                 wtap_block_add_uint8_option(int_data, OPT_IDB_FCSLEN, (guint8) pntoh32(tag.value));
3016                 if_info->set_flags.fcs_len = 1;
3017                 break;
3018
3019               default:
3020                 /* "shouldn't happen" */
3021                 break;
3022             }
3023           }
3024           break;
3025         case ERF_META_TAG_snaplen:
3026           if (tag.length >= 4) {
3027             /* Use the largest snaplen of matching streams */
3028             guint32 snaplen = pntoh32(tag.value);
3029
3030             if (snaplen > int_data_mand->snap_len || !if_info->set_flags.snaplen) {
3031               int_data_mand->snap_len = pntoh32(tag.value);
3032               if_info->set_flags.snaplen = 1;
3033             }
3034           }
3035           break;
3036         case ERF_META_TAG_filter:
3037           /* Override only if not set */
3038           if (!if_info->set_flags.filter) {
3039             if_filter.if_filter_str = g_strndup((gchar*) tag.value, tag.length);
3040             wtap_block_add_custom_option(int_data, OPT_IDB_FILTER, &if_filter, sizeof if_filter);
3041             g_free(if_filter.if_filter_str);
3042             if_info->set_flags.filter = 1;
3043           }
3044           break;
3045         default:
3046           break;
3047       }
3048
3049       tag_ptr_tmp += tagtotallength;
3050       remaining_len_tmp -= tagtotallength;
3051     }
3052   }
3053   state->tag_ptr = tag_ptr_tmp;
3054   state->remaining_len = remaining_len_tmp;
3055
3056   return 1;
3057 }
3058
3059 static int populate_anchor_info(erf_t *erf_priv, wtap *wth, union wtap_pseudo_header *pseudo_header, struct erf_meta_read_state *state, GPtrArray *anchor_mappings_to_update) {
3060   struct erf_meta_tag tag = {0, 0, NULL};
3061   guint32 tagtotallength;
3062   gchar *comment_ptr = NULL;
3063   guint i = 0;
3064
3065   if (!wth || !state || !pseudo_header)
3066     return -1;
3067
3068   if (!anchor_mappings_to_update || anchor_mappings_to_update->len == 0)
3069     return 0;
3070
3071   while ((tagtotallength = erf_meta_read_tag(&tag, state->tag_ptr, state->remaining_len)) && !ERF_META_IS_SECTION(tag.type)) {
3072     /* XXX:Always gets the first comment tag in the section */
3073     switch(tag.type) {
3074       case ERF_META_TAG_comment:
3075         if(!comment_ptr) {
3076           comment_ptr = g_strndup((gchar*)tag.value, tag.length);
3077         }
3078         break;
3079       default:
3080         break;
3081     }
3082
3083     state->tag_ptr += tagtotallength;
3084     state->remaining_len -= tagtotallength;
3085   }
3086
3087   if(comment_ptr) {
3088     for(i = 0; i < anchor_mappings_to_update->len; i++) {
3089       struct erf_anchor_mapping *mapping;
3090       struct erf_anchor_mapping *lookup_result;
3091
3092       mapping = (struct erf_anchor_mapping*)g_ptr_array_index(anchor_mappings_to_update, i);
3093       lookup_result = (struct erf_anchor_mapping*)g_hash_table_lookup(erf_priv->anchor_map, mapping);
3094
3095       /* Use the most recent comment, across all anchors associated with the
3096        * record. */
3097       if(lookup_result) {
3098         if(lookup_result->gen_time < state->gen_time) {
3099           lookup_result->gen_time = state->gen_time;
3100           g_free(lookup_result->comment);
3101           lookup_result->comment = g_strdup(comment_ptr);
3102         }
3103       }
3104       else {
3105         /* !lookup_result */
3106         struct erf_anchor_mapping *new_mapping;
3107         new_mapping = (struct erf_anchor_mapping *)g_malloc0(sizeof(struct erf_anchor_mapping));
3108         new_mapping->anchor_id = mapping->anchor_id;
3109         new_mapping->host_id = mapping->host_id;
3110         new_mapping->gen_time = state->gen_time;
3111         new_mapping->comment = g_strdup(comment_ptr);
3112         g_hash_table_replace(erf_priv->anchor_map, new_mapping, new_mapping);
3113       }
3114     }
3115   }
3116
3117   g_free(comment_ptr);
3118
3119   return 1;
3120 }
3121
3122 /* Populates the capture and interface information for display on the Capture File Properties */
3123 static int populate_summary_info(erf_t *erf_priv, wtap *wth, union wtap_pseudo_header *pseudo_header, guint32 packet_size, GPtrArray *anchor_mappings_to_update)
3124 {
3125   struct erf_meta_read_state state;
3126   struct erf_meta_read_state *state_post = NULL;
3127   guint64 host_id;
3128   guint8 source_id;
3129   GList *post_list = NULL;
3130   GList *item = NULL;
3131
3132   struct erf_meta_tag tag = {0, 0, NULL};
3133   guint32 tagtotallength;
3134
3135   if (!erf_priv || !wth || !pseudo_header)
3136     return -1;
3137
3138   memset(&state, 0, sizeof(struct erf_meta_read_state));
3139
3140   erf_get_source_from_header(pseudo_header, &host_id, &source_id);
3141
3142   if (host_id == 0) {
3143     host_id = erf_priv->implicit_host_id;
3144   }
3145
3146   state.if_map = erf_find_interface_mapping(erf_priv, host_id, source_id);
3147
3148   if (!state.if_map) {
3149     state.if_map = erf_if_mapping_create(host_id, source_id);
3150     /* g_hash_table_add() only exists since 2.32. */
3151     g_hash_table_replace(erf_priv->if_map, state.if_map, state.if_map);
3152
3153   }
3154
3155
3156   state.tag_ptr = wth->rec_data->data;
3157   state.remaining_len = packet_size;
3158
3159   /* Read until see next section tag */
3160   while ((tagtotallength = erf_meta_read_tag(&tag, state.tag_ptr, state.remaining_len))) {
3161     /*
3162      * Obtain the gen_time from the non-section at the beginning of the record
3163      */
3164     if (!ERF_META_IS_SECTION(tag.type)) {
3165       if(state.gen_time == 0U
3166           && tag.type == ERF_META_TAG_gen_time
3167           ) {
3168         memcpy(&state.gen_time, tag.value, sizeof(state.gen_time));
3169
3170         /*
3171          * Since wireshark doesn't have a concept of different summary metadata
3172          * over time, skip the record if metadata is older than what we already have.
3173          */
3174         /* TODO: This doesn't work very well for some tags that wireshark only
3175          * supports one copy of, we'll only end up with the first one.
3176          * wtap_block_set_*_value() currently fails on WTAP_OPTTYPE_NOT_FOUND
3177          * for everything except strings.
3178          * Currently we only particularly care about updating the capture comment
3179          * and a few counters anyway.
3180          */
3181         if ((state.if_map->interface_metadata & 0x03)
3182             && state.gen_time < erf_priv->host_gentime && state.gen_time < erf_priv->capture_gentime
3183             && (!anchor_mappings_to_update || !anchor_mappings_to_update->len)) {
3184           return 0;
3185         }
3186       }
3187       /*
3188        * Skip until we get to the next section tag (which could be the current tag
3189        * after an empty section or successful parsing).
3190        */
3191       /* adjust offset */
3192       state.tag_ptr += tagtotallength;
3193       state.remaining_len -= tagtotallength;
3194       continue;
3195     }
3196
3197     /*
3198      * We are now looking at the next section (and would have exited the loop
3199      * if we reached the end).
3200      */
3201
3202     /* Update parent section. Implicit grouping is by a change in section except Interface and Stream. */
3203     if (tag.type != state.sectiontype) {
3204       if ((tag.type == ERF_META_SECTION_STREAM && state.sectiontype == ERF_META_SECTION_INTERFACE) ||
3205           (tag.type == ERF_META_SECTION_INTERFACE && state.sectiontype == ERF_META_SECTION_STREAM)) {
3206         /* do nothing */
3207       } else {
3208         state.parentsectiontype = state.sectiontype;
3209         state.parentsectionid = state.sectionid;
3210       }
3211     }
3212
3213     /* Update with new sectiontype */
3214     state.sectiontype = tag.type;
3215     if (tag.length >= 4) {
3216       state.sectionid = pntoh16(tag.value);
3217     } else {
3218       state.sectionid = 0;
3219     }
3220
3221     /* Adjust offset to that of first tag in section */
3222     state.tag_ptr += tagtotallength;
3223     state.remaining_len -= tagtotallength;
3224
3225     if ((tagtotallength = erf_meta_read_tag(&tag, state.tag_ptr, state.remaining_len))) {
3226       /*
3227        * Process parent section tag if present (which must be the first tag in
3228        * the section).
3229        */
3230       if (tag.type == ERF_META_TAG_parent_section && tag.length >= 4) {
3231         state.parentsectiontype = pntoh16(tag.value);
3232         state.parentsectionid = pntoh16(&tag.value[2]);
3233       }
3234     }
3235
3236     /* Skip empty sections (includes if above read fails) */
3237     if (ERF_META_IS_SECTION(tag.type)) {
3238       continue;
3239     }
3240
3241     /*
3242      * Skip sections that don't apply to the general set of records
3243      * (extension point for per-packet/event metadata).
3244      * Unless we need to update the anchor info
3245      * in which case, read into it
3246      */
3247     if (state.sectionid & 0x8000) {
3248       if(state.sectiontype & (ERF_META_SECTION_INFO)) {
3249         populate_anchor_info(erf_priv, wth, pseudo_header, &state, anchor_mappings_to_update);
3250       }
3251       continue;
3252     }
3253
3254     /*
3255      * Start at first tag in section, makes loop
3256      * simpler in called functions too. Also makes iterating after failure
3257      * much simpler.
3258      */
3259     switch (state.sectiontype) {
3260       case ERF_META_SECTION_CAPTURE:
3261       case ERF_META_SECTION_HOST:
3262         /* TODO: use return code */
3263         populate_capture_host_info(erf_priv, wth, pseudo_header, &state);
3264         break;
3265       case ERF_META_SECTION_MODULE:
3266         populate_module_info(erf_priv, wth, pseudo_header, &state);
3267         break;
3268       case ERF_META_SECTION_INTERFACE:
3269         populate_interface_info(erf_priv, wth, pseudo_header, &state);
3270         break;
3271       case ERF_META_SECTION_STREAM:
3272         /*
3273          * XXX: Treat streams specially in case the stream information appears
3274          * before the interface information, as we associate them to interface
3275          * data.
3276          */
3277         post_list = g_list_append(post_list, g_memdup(&state, sizeof(struct erf_meta_read_state)));
3278         break;
3279       case ERF_META_SECTION_SOURCE:
3280       case ERF_META_SECTION_DNS:
3281       default:
3282         /* TODO: Not yet implemented */
3283         break;
3284     }
3285   }
3286
3287   /* Process streams last */
3288   if (post_list) {
3289     item = post_list;
3290     do {
3291       state_post = (struct erf_meta_read_state*) item->data;
3292       switch (state_post->sectiontype) {
3293         case ERF_META_SECTION_STREAM:
3294           populate_stream_info(erf_priv, wth, pseudo_header, state_post);
3295           break;
3296       }
3297     } while ((item = g_list_next(item)));
3298     /* g_list_free_full() only exists since 2.28. */
3299     g_list_foreach(post_list, erf_free_data, NULL);
3300     g_list_free(post_list);
3301   }
3302
3303   /*
3304    * Update known metadata so we only examine the first set of metadata. Need to
3305    * do this here so can have interface and stream in same record.
3306    */
3307   if (state.interface_metadata) {
3308     state.if_map->interface_metadata |= state.interface_metadata;
3309     state.if_map->interface_gentime = state.gen_time;
3310   }
3311
3312   return 0;
3313 }
3314
3315 static gboolean get_user_comment_string(wtap_dumper *wdh, gchar** user_comment_ptr) {
3316   wtap_block_t wtap_block;
3317   gboolean ret;
3318
3319   wtap_block = NULL;
3320
3321   if(wdh->shb_hdrs && (wdh->shb_hdrs->len > 0)) {
3322     wtap_block = g_array_index(wdh->shb_hdrs, wtap_block_t, 0);
3323   }
3324
3325   if(wtap_block != NULL) {
3326     ret = wtap_block_get_nth_string_option_value(wtap_block, OPT_COMMENT, 0, user_comment_ptr);
3327     if(ret) {
3328       return FALSE;
3329     }
3330   }
3331
3332   return TRUE;
3333 }
3334
3335 static gboolean erf_dump_priv_compare_capture_comment(wtap_dumper *wdh _U_, erf_dump_t *dump_priv, const union wtap_pseudo_header *pseudo_header, const guint8 *pd){
3336   struct erf_meta_read_state state;
3337   struct erf_meta_tag tag = {0, 0, NULL};
3338   guint32 tagtotallength;
3339   gboolean found_capture_section = FALSE;
3340   gboolean found_normal_section = FALSE;
3341   gchar* comment_ptr = NULL;
3342
3343   memset(&state, 0, sizeof(struct erf_meta_read_state));
3344   state.remaining_len = pseudo_header->erf.phdr.wlen;
3345   memcpy(&(state.tag_ptr), &pd, sizeof(pd));
3346
3347   while((tagtotallength = erf_meta_read_tag(&tag, state.tag_ptr, state.remaining_len))) {
3348     if (ERF_META_IS_SECTION(tag.type)) {
3349       state.sectiontype = tag.type;
3350       if (tag.length >= 4) {
3351         state.sectionid = pntoh16(tag.value);
3352       } else {
3353         state.sectionid = 0;
3354       }
3355
3356       /* Skip sections that don't apply to the general set of records */
3357       if (!(state.sectionid & 0x8000)) {
3358         found_normal_section = TRUE;
3359
3360         if(tag.type == ERF_META_SECTION_CAPTURE) {
3361           /* Found the Capture Section */
3362           found_capture_section = TRUE;
3363         }
3364       }
3365     } else {
3366       if (state.sectiontype == ERF_META_SECTION_CAPTURE && !(state.sectionid & 0x8000)) {
3367         if (tag.type == ERF_META_TAG_comment) {
3368           /* XXX: Only compare the first comment tag */
3369           if(!comment_ptr) {
3370             comment_ptr = g_strndup((char*)tag.value, tag.length);
3371           }
3372           break;
3373         }
3374       }
3375     }
3376
3377     /* Read until we have the Capture section */
3378     state.tag_ptr += tagtotallength;
3379     state.remaining_len -= tagtotallength;
3380   }
3381
3382   if(found_capture_section && (comment_ptr || dump_priv->user_comment_ptr)) {
3383     if(g_strcmp0(comment_ptr, dump_priv->user_comment_ptr)
3384         && !(dump_priv->user_comment_ptr == NULL && comment_ptr && comment_ptr[0] == '\0')) {
3385         /* Also treat "" in ERF as equivalent to NULL as that is how we clear the comment on write. */
3386
3387       /* Comments are different, we should write extra metadata record at the end of the list */
3388       dump_priv->write_next_extra_meta = TRUE;
3389       g_free(comment_ptr);
3390       return TRUE;
3391     } else {
3392       /* We have a capture comment but there is no change, we don't
3393        * need to insert the 'changed' comment. This most likely happened
3394        * because we were looking at list of periodic records and got up to the
3395        * one where the comment was last set. */
3396       dump_priv->write_next_extra_meta = FALSE;
3397     }
3398     /* Otherwise no effect on whether we need to write extra metadata record */
3399   }
3400   /* We didn't find a capture section (e.g. looking at a comment Anchor
3401    * record), or the comment hadn't changed. */
3402
3403   g_free(comment_ptr);
3404   /* Return whether we found any non-local metadata (i.e. whether the record has
3405    * metadata that is more than just packet 'comments') */
3406   return found_normal_section;
3407 }
3408
3409 static void erf_close(wtap *wth)
3410 {
3411   erf_t* erf_priv = (erf_t*)wth->priv;
3412
3413   erf_priv_free(erf_priv);
3414   /* XXX: Prevent double free by wtap_close() */
3415   wth->priv = NULL;
3416 }
3417
3418 /*
3419  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
3420  *
3421  * Local Variables:
3422  * c-basic-offset: 2
3423  * tab-width: 8
3424  * indent-tabs-mode: nil
3425  * End:
3426  *
3427  * vi: set shiftwidth=2 tabstop=8 expandtab:
3428  * :indentSize=2:tabSize=8:noTabs=true:
3429  */