1 /* stats_tree.c
2  * API for a counter tree for Wireshark
3  * 2004, Luis E. G. Ontanon
4  *
5  * Wireshark - Network traffic analyzer
6  * By Gerald Combs <gerald@wireshark.org>
7  * Copyright 1998 Gerald Combs
8  *
9  * SPDX-License-Identifier: GPL-2.0-or-later
10  */
11 
12  /* stats_tree modifications by Deon van der Westhuysen, November 2013
13   * support for
14   *  - sorting by column,
15   *  - calculation of average values
16   *  - calculation of burst rate
17   *  - export to text, CSV or XML file
18   */
19 
20 #include "config.h"
21 
22 #include <glib.h>
23 
24 #include <stdlib.h>
25 
26 #include <epan/stats_tree_priv.h>
27 #include <epan/prefs.h>
28 #include <math.h>
29 #include <string.h>
30 
31 #include "strutil.h"
32 #include "stats_tree.h"
33 #include <wsutil/ws_assert.h>
34 
35 enum _stat_tree_columns {
36     COL_NAME,
37     COL_COUNT,
38     COL_AVERAGE,
39     COL_MIN,
40     COL_MAX,
41     COL_RATE,
42     COL_PERCENT,
43     COL_BURSTRATE,
44     COL_BURSTTIME,
45     N_COLUMNS
46 };
47 
48 /* used to contain the registered stat trees */
49 static GHashTable *registry = NULL;
50 
51 /* a text representation of a node
52 if buffer is NULL returns a newly allocated string */
53 extern gchar*
stats_tree_node_to_str(const stat_node * node,gchar * buffer,guint len)54 stats_tree_node_to_str(const stat_node *node, gchar *buffer, guint len)
55 {
56     if (buffer) {
57         g_snprintf(buffer,len,"%s: %i",node->name, node->counter);
58         return buffer;
59     } else {
60         return g_strdup_printf("%s: %i",node->name, node->counter);
61     }
62 }
63 
64 extern guint
stats_tree_branch_max_namelen(const stat_node * node,guint indent)65 stats_tree_branch_max_namelen(const stat_node *node, guint indent)
66 {
67     stat_node *child;
68     guint maxlen = 0;
69     guint len;
70 
71     indent = indent > INDENT_MAX ? INDENT_MAX : indent;
72 
73     if (node->children) {
74         for (child = node->children; child; child = child->next ) {
75             len = stats_tree_branch_max_namelen(child,indent+1);
76             maxlen = len > maxlen ? len : maxlen;
77         }
78     }
79 
80     if (node->st_flags&ST_FLG_ROOTCHILD) {
81         gchar *display_name = stats_tree_get_displayname(node->name);
82         len = (guint) strlen(display_name) + indent;
83         g_free(display_name);
84     }
85     else {
86     len = (guint) strlen(node->name) + indent;
87     }
88     maxlen = len > maxlen ? len : maxlen;
89 
90     return maxlen;
91 }
92 
93 /* frees the resources allocated by a stat_tree node */
94 static void
free_stat_node(stat_node * node)95 free_stat_node(stat_node *node)
96 {
97     stat_node *child;
98     stat_node *next;
99     burst_bucket *bucket;
100 
101     if (node->children) {
102     for (child = node->children; child; child = next ) {
103         /* child->next will be gone after free_stat_node, so cache it here */
104         next = child->next;
105         free_stat_node(child);
106     }
107     }
108 
109     if (node->hash) g_hash_table_destroy(node->hash);
110 
111     while (node->bh) {
112         bucket = node->bh;
113         node->bh = bucket->next;
114         g_free(bucket);
115     }
116 
117     g_free(node->rng);
118     g_free(node->name);
119     g_free(node);
120 }
121 
122 /* destroys the whole tree instance */
123 extern void
stats_tree_free(stats_tree * st)124 stats_tree_free(stats_tree *st)
125 {
126     stat_node *child;
127     stat_node *next;
128 
129     if (!st) return;
130 
131     g_free(st->filter);
132     g_hash_table_destroy(st->names);
133     g_ptr_array_free(st->parents,TRUE);
134     g_free(st->display_name);
135 
136     for (child = st->root.children; child; child = next ) {
137         /* child->next will be gone after free_stat_node, so cache it here */
138         next = child->next;
139         free_stat_node(child);
140     }
141 
142     if (st->cfg->free_tree_pr)
143         st->cfg->free_tree_pr(st);
144 
145     if (st->cfg->cleanup)
146         st->cfg->cleanup(st);
147 
148     g_free(st);
149 }
150 
151 
152 /* reset a node to its original state */
153 static void
reset_stat_node(stat_node * node)154 reset_stat_node(stat_node *node)
155 {
156     stat_node *child;
157     burst_bucket *bucket;
158 
159     node->counter = 0;
160     switch (node->datatype)
161     {
162     case STAT_DT_INT:
163         node->total.int_total = 0;
164         node->minvalue.int_min = G_MAXINT;
165         node->maxvalue.int_max = G_MININT;
166         break;
167     case STAT_DT_FLOAT:
168         node->total.float_total = 0;
169         node->minvalue.float_min = G_MAXFLOAT;
170         node->maxvalue.float_max = G_MINFLOAT;
171         break;
172     }
173     node->st_flags = 0;
174 
175     while (node->bh) {
176         bucket = node->bh;
177         node->bh = bucket->next;
178         g_free(bucket);
179     }
180     node->bh = g_new0(burst_bucket, 1);
181     node->bt = node->bh;
182     node->bcount = 0;
183     node->max_burst = 0;
184     node->burst_time = -1.0;
185 
186     if (node->children) {
187         for (child = node->children; child; child = child->next )
188             reset_stat_node(child);
189     }
190 }
191 
192 /* reset the whole stats_tree */
193 extern void
stats_tree_reset(void * p)194 stats_tree_reset(void *p)
195 {
196     stats_tree *st = (stats_tree *)p;
197 
198     st->start = -1.0;
199     st->elapsed = 0.0;
200     st->now = - 1.0;
201 
202     reset_stat_node(&st->root);
203 }
204 
205 extern void
stats_tree_reinit(void * p)206 stats_tree_reinit(void *p)
207 {
208     stats_tree *st = (stats_tree *)p;
209     stat_node *child;
210     stat_node *next;
211 
212     for (child = st->root.children; child; child = next) {
213         /* child->next will be gone after free_stat_node, so cache it here */
214         next = child->next;
215         free_stat_node(child);
216     }
217 
218     st->root.children = NULL;
219     st->root.counter = 0;
220     switch (st->root.datatype)
221     {
222     case STAT_DT_INT:
223         st->root.total.int_total = 0;
224         st->root.minvalue.int_min = G_MAXINT;
225         st->root.maxvalue.int_max = G_MININT;
226         break;
227     case STAT_DT_FLOAT:
228         st->root.total.float_total = 0;
229         st->root.minvalue.float_min = G_MAXFLOAT;
230         st->root.maxvalue.float_max = G_MINFLOAT;
231         break;
232     }
233     st->root.st_flags = 0;
234 
235     st->root.bh = g_new0(burst_bucket, 1);
236     st->root.bt = st->root.bh;
237     st->root.bcount = 0;
238     st->root.max_burst = 0;
239     st->root.burst_time = -1.0;
240 
241     /* No more stat_nodes left in tree - clean out hash, array */
242     g_hash_table_remove_all(st->names);
243     if (st->parents->len>1) {
244         g_ptr_array_remove_range(st->parents, 1, st->parents->len-1);
245     }
246 
247     /* Do not update st_flags for the tree (sorting) - leave as was */
248     st->num_columns = N_COLUMNS;
249     g_free(st->display_name);
250     st->display_name = stats_tree_get_displayname(st->cfg->name);
251 
252     if (st->cfg->init) {
253         st->cfg->init(st);
254     }
255 }
256 
257 static void
stats_tree_cfg_free(gpointer p)258 stats_tree_cfg_free(gpointer p)
259 {
260     stats_tree_cfg* cfg = (stats_tree_cfg*)p;
261     g_free(cfg->tapname);
262     g_free(cfg->abbr);
263     g_free(cfg->name);
264     g_free(cfg);
265 }
266 
267 /* register a new stats_tree */
268 extern void
stats_tree_register_with_group(const char * tapname,const char * abbr,const char * name,guint flags,stat_tree_packet_cb packet,stat_tree_init_cb init,stat_tree_cleanup_cb cleanup,register_stat_group_t stat_group)269 stats_tree_register_with_group(const char *tapname, const char *abbr, const char *name,
270             guint flags,
271             stat_tree_packet_cb packet, stat_tree_init_cb init,
272             stat_tree_cleanup_cb cleanup, register_stat_group_t stat_group)
273 {
274     stats_tree_cfg *cfg = g_new0(stats_tree_cfg, 1);
275 
276     /* at the very least the abbrev and the packet function should be given */
277     ws_assert( tapname && abbr && packet );
278 
279     cfg->tapname = g_strdup(tapname);
280     cfg->abbr = g_strdup(abbr);
281     cfg->name = name ? g_strdup(name) : g_strdup(abbr);
282     cfg->stat_group = stat_group;
283 
284     cfg->packet = packet;
285     cfg->init = init;
286     cfg->cleanup = cleanup;
287 
288     cfg->flags = flags&~ST_FLG_MASK;
289     cfg->st_flags = flags&ST_FLG_MASK;
290 
291     if (!registry) registry = g_hash_table_new_full(g_str_hash,g_str_equal,NULL,stats_tree_cfg_free);
292 
293     g_hash_table_insert(registry,cfg->abbr,cfg);
294 }
295 
296 /* register a new stats_tree with default group REGISTER_STAT_GROUP_UNSORTED */
297 extern void
stats_tree_register(const char * tapname,const char * abbr,const char * name,guint flags,stat_tree_packet_cb packet,stat_tree_init_cb init,stat_tree_cleanup_cb cleanup)298 stats_tree_register(const char *tapname, const char *abbr, const char *name,
299             guint flags,
300             stat_tree_packet_cb packet, stat_tree_init_cb init,
301             stat_tree_cleanup_cb cleanup)
302 {
303     stats_tree_register_with_group(tapname, abbr, name,
304             flags,
305             packet, init,
306             cleanup, REGISTER_STAT_GROUP_UNSORTED);
307 }
308 
309 /* register a new stat_tree with default group REGISTER_STAT_GROUP_UNSORTED from a plugin */
310 extern void
stats_tree_register_plugin(const char * tapname,const char * abbr,const char * name,guint flags,stat_tree_packet_cb packet,stat_tree_init_cb init,stat_tree_cleanup_cb cleanup)311 stats_tree_register_plugin(const char *tapname, const char *abbr, const char *name,
312             guint flags,
313             stat_tree_packet_cb packet, stat_tree_init_cb init,
314             stat_tree_cleanup_cb cleanup)
315 {
316     stats_tree_cfg *cfg;
317 
318     stats_tree_register(tapname, abbr, name,
319             flags,
320             packet, init,
321             cleanup);
322     cfg = stats_tree_get_cfg_by_abbr(abbr);
323     cfg->plugin = TRUE;
324 }
325 
326 extern stats_tree*
stats_tree_new(stats_tree_cfg * cfg,tree_pres * pr,const char * filter)327 stats_tree_new(stats_tree_cfg *cfg, tree_pres *pr, const char *filter)
328 {
329     stats_tree *st = g_new0(stats_tree, 1);
330 
331     st->cfg = cfg;
332     st->pr = pr;
333 
334     st->names = g_hash_table_new(g_str_hash,g_str_equal);
335     st->parents = g_ptr_array_new();
336     st->filter = g_strdup(filter);
337 
338     st->start = -1.0;
339     st->elapsed = 0.0;
340 
341     switch (st->root.datatype)
342     {
343     case STAT_DT_INT:
344         st->root.minvalue.int_min = G_MAXINT;
345         st->root.maxvalue.int_max = G_MININT;
346         break;
347     case STAT_DT_FLOAT:
348         st->root.minvalue.float_min = G_MAXFLOAT;
349         st->root.maxvalue.float_max = G_MINFLOAT;
350         break;
351     }
352 
353     st->root.bh = g_new0(burst_bucket, 1);
354     st->root.bt = st->root.bh;
355     st->root.burst_time = -1.0;
356 
357     st->root.name = stats_tree_get_displayname(cfg->name);
358     st->root.st = st;
359 
360     st->st_flags = st->cfg->st_flags;
361 
362     if (!(st->st_flags&ST_FLG_SRTCOL_MASK)) {
363         /* No default sort specified - use preferences */
364         st->st_flags |= prefs.st_sort_defcolflag<<ST_FLG_SRTCOL_SHIFT;
365         if (prefs.st_sort_defdescending) {
366             st->st_flags |= ST_FLG_SORT_DESC;
367         }
368     }
369     st->num_columns = N_COLUMNS;
370     st->display_name = stats_tree_get_displayname(st->cfg->name);
371 
372     g_ptr_array_add(st->parents,&st->root);
373 
374     return st;
375 }
376 
377 /* will be the tap packet cb */
378 extern tap_packet_status
stats_tree_packet(void * p,packet_info * pinfo,epan_dissect_t * edt,const void * pri)379 stats_tree_packet(void *p, packet_info *pinfo, epan_dissect_t *edt, const void *pri)
380 {
381     stats_tree *st = (stats_tree *)p;
382 
383     st->now = nstime_to_msec(&pinfo->rel_ts);
384     if (st->start < 0.0) st->start = st->now;
385 
386     st->elapsed = st->now - st->start;
387 
388     if (st->cfg->packet)
389         return st->cfg->packet(st,pinfo,edt,pri);
390     else
391         return TAP_PACKET_DONT_REDRAW;
392 }
393 
394 extern stats_tree_cfg*
stats_tree_get_cfg_by_abbr(const char * abbr)395 stats_tree_get_cfg_by_abbr(const char *abbr)
396 {
397     if (!abbr) return NULL;
398     return (stats_tree_cfg *)g_hash_table_lookup(registry,abbr);
399 }
400 
401 static gint
compare_stat_menu_item(gconstpointer stat_a,gconstpointer stat_b)402 compare_stat_menu_item(gconstpointer stat_a, gconstpointer stat_b)
403 {
404     const stats_tree_cfg* stat_cfg_a = (const stats_tree_cfg*)stat_a;
405     const stats_tree_cfg* stat_cfg_b = (const stats_tree_cfg*)stat_b;
406 
407     return strcmp(stat_cfg_a->name, stat_cfg_b->name);
408 }
409 
410 extern GList*
stats_tree_get_cfg_list(void)411 stats_tree_get_cfg_list(void)
412 {
413     GList* registry_list = g_hash_table_get_values(registry);
414     /* Now sort the list so they can show up in the
415        menu alphabetically */
416     return g_list_sort(registry_list, compare_stat_menu_item);
417 
418 }
419 
420 struct _stats_tree_pres_cbs {
421     void (*setup_node_pr)(stat_node*);
422     void (*free_tree_pr)(stats_tree*);
423 };
424 
425 static void
setup_tree_presentation(gpointer k _U_,gpointer v,gpointer p)426 setup_tree_presentation(gpointer k _U_, gpointer v, gpointer p)
427 {
428     stats_tree_cfg *cfg = (stats_tree_cfg *)v;
429     struct _stats_tree_pres_cbs *d = (struct _stats_tree_pres_cbs *)p;
430 
431     cfg->setup_node_pr = d->setup_node_pr;
432     cfg->free_tree_pr = d->free_tree_pr;
433 
434 }
435 
436 extern void
stats_tree_presentation(void (* registry_iterator)(gpointer,gpointer,gpointer),void (* setup_node_pr)(stat_node *),void (* free_tree_pr)(stats_tree *),void * data)437 stats_tree_presentation(void (*registry_iterator)(gpointer,gpointer,gpointer),
438             void (*setup_node_pr)(stat_node*),
439             void (*free_tree_pr)(stats_tree*),
440             void *data)
441 {
442     static struct _stats_tree_pres_cbs d;
443 
444     d.setup_node_pr = setup_node_pr;
445     d.free_tree_pr = free_tree_pr;
446 
447     if (registry) g_hash_table_foreach(registry,setup_tree_presentation,&d);
448 
449     if (registry_iterator && registry)
450         g_hash_table_foreach(registry,registry_iterator,data);
451 
452 }
453 
454 
455 /* creates a stat_tree node
456 *    name: the name of the stats_tree node
457 *    parent_name: the name of the ALREADY REGISTERED parent
458 *    with_hash: whether or not it should keep a hash with its children names
459 *    as_named_node: whether or not it has to be registered in the root namespace
460 */
461 static stat_node*
new_stat_node(stats_tree * st,const gchar * name,int parent_id,stat_node_datatype datatype,gboolean with_hash,gboolean as_parent_node)462 new_stat_node(stats_tree *st, const gchar *name, int parent_id, stat_node_datatype datatype,
463           gboolean with_hash, gboolean as_parent_node)
464 {
465 
466     stat_node *node = g_new0(stat_node, 1);
467     stat_node *last_chld = NULL;
468 
469     node->datatype = datatype;
470     switch (datatype)
471     {
472     case STAT_DT_INT:
473         node->minvalue.int_min = G_MAXINT;
474         node->maxvalue.int_max = G_MININT;
475         break;
476     case STAT_DT_FLOAT:
477         node->minvalue.float_min = G_MAXFLOAT;
478         node->maxvalue.float_max = G_MINFLOAT;
479         break;
480     }
481     node->st_flags = parent_id?0:ST_FLG_ROOTCHILD;
482 
483     node->bh = g_new0(burst_bucket, 1);
484     node->bt = node->bh;
485     node->burst_time = -1.0;
486 
487     node->name = g_strdup(name);
488     node->st = st;
489     node->hash = with_hash ? g_hash_table_new(g_str_hash,g_str_equal) : NULL;
490 
491     if (as_parent_node) {
492         g_hash_table_insert(st->names,
493                             node->name,
494                             node);
495 
496         g_ptr_array_add(st->parents,node);
497 
498         node->id = st->parents->len - 1;
499     } else {
500         node->id = -1;
501     }
502 
503     if (parent_id >= 0 && parent_id < (int) st->parents->len ) {
504         node->parent = (stat_node *)g_ptr_array_index(st->parents,parent_id);
505     } else {
506         /* ??? should we set the parent to be root ??? */
507         ws_assert_not_reached();
508     }
509 
510     if (node->parent->children) {
511         /* insert as last child */
512 
513         for (last_chld = node->parent->children;
514              last_chld->next;
515              last_chld = last_chld->next ) ;
516 
517         last_chld->next = node;
518 
519     } else {
520         /* insert as first child */
521         node->parent->children = node;
522     }
523 
524     if(node->parent->hash) {
525         g_hash_table_replace(node->parent->hash,node->name,node);
526     }
527 
528     if (st->cfg->setup_node_pr) {
529         st->cfg->setup_node_pr(node);
530     } else {
531         node->pr = NULL;
532     }
533 
534     return node;
535 }
536 /***/
537 
538 extern int
stats_tree_create_node(stats_tree * st,const gchar * name,int parent_id,stat_node_datatype datatype,gboolean with_hash)539 stats_tree_create_node(stats_tree *st, const gchar *name, int parent_id, stat_node_datatype datatype, gboolean with_hash)
540 {
541     stat_node *node = new_stat_node(st,name,parent_id,datatype,with_hash,TRUE);
542 
543     if (node)
544         return node->id;
545     else
546         return 0;
547 }
548 
549 /* XXX: should this be a macro? */
550 extern int
stats_tree_create_node_by_pname(stats_tree * st,const gchar * name,const gchar * parent_name,stat_node_datatype datatype,gboolean with_children)551 stats_tree_create_node_by_pname(stats_tree *st, const gchar *name,
552                 const gchar *parent_name, stat_node_datatype datatype, gboolean with_children)
553 {
554     return stats_tree_create_node(st,name,stats_tree_parent_id_by_name(st,parent_name),datatype,with_children);
555 }
556 
557 /* Internal function to update the burst calculation data - add entry to bucket */
558 static void
update_burst_calc(stat_node * node,gint value)559 update_burst_calc(stat_node *node, gint value)
560 {
561     double current_bucket;
562     double burstwin;
563 
564     burst_bucket *bn;
565 
566     if (!prefs.st_enable_burstinfo) {
567         return;
568     }
569 
570     /* NB thebucket list should always contain at least one node - even if it is */
571     /* the dummy created at init time. Head and tail should never be NULL!       */
572     current_bucket = floor(node->st->now/prefs.st_burst_resolution);
573     burstwin = prefs.st_burst_windowlen/prefs.st_burst_resolution;
574     if (current_bucket>node->bt->bucket_no) {
575         /* Must add a new bucket at the burst list tail */
576         bn = g_new0(burst_bucket, 1);
577         bn->count = value;
578         bn->bucket_no = current_bucket;
579         bn->start_time = node->st->now;
580         bn->prev = node->bt;
581         node->bt->next = bn;
582         node->bt = bn;
583         /* And add value to the current burst count for node */
584         node->bcount += value;
585         /* Check if bucket list head is now too old and must be removed */
586         while (current_bucket>=(node->bh->bucket_no+burstwin)) {
587             /* off with its head! */
588             bn = node->bh;
589             node->bh = bn->next;
590             node->bh->prev = NULL;
591             node->bcount -= bn->count;
592             g_free(bn);
593         }
594     }
595     else if (current_bucket<node->bh->bucket_no) {
596         /* Packet must be added at head of burst list - check if not too old */
597         if ((current_bucket+burstwin)>node->bt->bucket_no) {
598             /* packet still within the window */
599             bn = g_new0(burst_bucket, 1);
600             bn->count = value;
601             bn->bucket_no = current_bucket;
602             bn->start_time = node->st->now;
603             bn->next = node->bh;
604             node->bh->prev = bn;
605             node->bh = bn;
606             /* And add value to the current burst count for node */
607             node->bcount += value;
608         }
609     }
610     else
611     {
612         /* Somewhere in the middle... */
613         burst_bucket *search = node->bt;
614         while (current_bucket<search->bucket_no) {
615             search = search->prev;
616         }
617         if (current_bucket==search->bucket_no) {
618             /* found existing bucket, increase value */
619             search->count += value;
620             if (search->start_time>node->st->now) {
621                 search->start_time = node->st->now;
622             }
623         }
624         else {
625             /* must add a new bucket after bn. */
626             bn = g_new0(burst_bucket, 1);
627             bn->count = value;
628             bn->bucket_no = current_bucket;
629             bn->start_time = node->st->now;
630             bn->prev = search;
631             bn->next = search->next;
632             search->next = bn;
633             bn->next->prev = bn;
634         }
635         node->bcount += value;
636     }
637     if (node->bcount>node->max_burst) {
638         /* new record burst */
639         node->max_burst = node->bcount;
640         node->burst_time = node->bh->start_time;
641     }
642 }
643 
644 /*
645  * Increases by delta the counter of the node whose name is given
646  * if the node does not exist yet it's created (with counter=1)
647  * using parent_name as parent node.
648  * with_hash=TRUE to indicate that the created node will have a parent
649  */
650 int
stats_tree_manip_node_int(manip_node_mode mode,stats_tree * st,const char * name,int parent_id,gboolean with_hash,gint value)651 stats_tree_manip_node_int(manip_node_mode mode, stats_tree *st, const char *name,
652               int parent_id, gboolean with_hash, gint value)
653 {
654     stat_node *node = NULL;
655     stat_node *parent = NULL;
656 
657     ws_assert( parent_id >= 0 && parent_id < (int) st->parents->len );
658 
659     parent = (stat_node *)g_ptr_array_index(st->parents,parent_id);
660 
661     if( parent->hash ) {
662         node = (stat_node *)g_hash_table_lookup(parent->hash,name);
663     } else {
664         node = (stat_node *)g_hash_table_lookup(st->names,name);
665     }
666 
667     if ( node == NULL )
668         node = new_stat_node(st,name,parent_id,STAT_DT_INT,with_hash,with_hash);
669 
670     switch (mode) {
671         case MN_INCREASE:
672             node->counter += value;
673             update_burst_calc(node, value);
674             break;
675         case MN_SET:
676             node->counter = value;
677             break;
678         case MN_AVERAGE:
679             node->counter++;
680             update_burst_calc(node, 1);
681             /* fall through */ /*to average code */
682         case MN_AVERAGE_NOTICK:
683             node->total.int_total += value;
684             if (node->minvalue.int_min > value) {
685                 node->minvalue.int_min = value;
686             }
687             if (node->maxvalue.int_max < value) {
688                 node->maxvalue.int_max = value;
689             }
690             node->st_flags |= ST_FLG_AVERAGE;
691             break;
692         case MN_SET_FLAGS:
693             node->st_flags |= value;
694             break;
695         case MN_CLEAR_FLAGS:
696             node->st_flags &= ~value;
697             break;
698     }
699 
700     if (node)
701         return node->id;
702     else
703         return -1;
704 }
705 
706 /*
707 * Increases by delta the counter of the node whose name is given
708 * if the node does not exist yet it's created (with counter=1)
709 * using parent_name as parent node.
710 * with_hash=TRUE to indicate that the created node will have a parent
711 */
712 int
stats_tree_manip_node_float(manip_node_mode mode,stats_tree * st,const char * name,int parent_id,gboolean with_hash,gfloat value)713 stats_tree_manip_node_float(manip_node_mode mode, stats_tree *st, const char *name,
714     int parent_id, gboolean with_hash, gfloat value)
715 {
716     stat_node *node = NULL;
717     stat_node *parent = NULL;
718 
719     ws_assert(parent_id >= 0 && parent_id < (int)st->parents->len);
720 
721     parent = (stat_node *)g_ptr_array_index(st->parents, parent_id);
722 
723     if (parent->hash) {
724         node = (stat_node *)g_hash_table_lookup(parent->hash, name);
725     }
726     else {
727         node = (stat_node *)g_hash_table_lookup(st->names, name);
728     }
729 
730     if (node == NULL)
731         node = new_stat_node(st, name, parent_id, STAT_DT_FLOAT, with_hash, with_hash);
732 
733     switch (mode) {
734     case MN_AVERAGE:
735         node->counter++;
736         update_burst_calc(node, 1);
737         /* fall through */ /*to average code */
738     case MN_AVERAGE_NOTICK:
739         node->total.float_total += value;
740         if (node->minvalue.float_min > value) {
741             node->minvalue.float_min = value;
742         }
743         if (node->maxvalue.float_max < value) {
744             node->maxvalue.float_max = value;
745         }
746         node->st_flags |= ST_FLG_AVERAGE;
747         break;
748     default:
749         //only average is currently supported
750         ws_assert_not_reached();
751         break;
752     }
753 
754     if (node)
755         return node->id;
756     else
757         return -1;
758 }
759 
760 extern char*
stats_tree_get_abbr(const char * opt_arg)761 stats_tree_get_abbr(const char *opt_arg)
762 {
763     guint i;
764 
765     /* XXX: this fails when tshark is given any options
766        after the -z */
767     ws_assert(opt_arg != NULL);
768 
769     for (i=0; opt_arg[i] && opt_arg[i] != ','; i++);
770 
771     if (opt_arg[i] == ',') {
772         return g_strndup(opt_arg,i);
773     } else {
774         return NULL;
775     }
776 }
777 
778 
779 /*
780  * This function accepts an input string which should define a long integer range.
781  * The normal result is a struct containing the floor and ceil value of this
782  * range.
783  *
784  * It is allowed to define a range string in the following ways :
785  *
786  * "0-10" -> { 0, 10 }
787  * "-0" -> { G_MININT, 0 }
788  * "0-" -> { 0, G_MAXINT }
789  * "-" -> { G_MININT, G_MAXINT }
790  *
791  * Note that this function is robust to buggy input string. If in some cases it
792  * returns NULL, it but may also return a pair with undefined values.
793  *
794  */
795 static range_pair_t*
get_range(char * rngstr)796 get_range(char *rngstr)
797 {
798     gchar **split;
799     range_pair_t *rng;
800 
801     split = g_strsplit((gchar*)rngstr,"-",2);
802 
803     /* empty string */
804     if (split[0] == NULL) {
805         g_strfreev(split);
806         return NULL;
807     }
808 
809     rng = g_new(range_pair_t, 1);
810 
811     if (split[1] == NULL) {
812         /* means we have a non empty string with no delimiter
813          * so it must be a single number */
814         rng->floor = (gint)strtol(split[0],NULL,10);
815         rng->ceil = rng->floor;
816     } else {
817       /* string == "X-?" */
818         if (*(split[0]) != '\0') {
819             rng->floor = (gint)strtol(split[0],NULL,10);
820         } else {
821             /* string == "-?" */
822             rng->floor = G_MININT;
823         }
824 
825         /* string != "?-" */
826         if (*(split[1]) != '\0') {
827             rng->ceil  = (gint)strtol(split[1],NULL,10);
828         } else {
829             /* string == "?-" */
830             rng->ceil = G_MAXINT;
831         }
832     }
833     g_strfreev(split);
834 
835     return rng;
836 }
837 
838 
839 extern int
stats_tree_create_range_node(stats_tree * st,const gchar * name,int parent_id,...)840 stats_tree_create_range_node(stats_tree *st, const gchar *name, int parent_id, ...)
841 {
842     va_list list;
843     gchar *curr_range;
844     stat_node *rng_root = new_stat_node(st, name, parent_id, STAT_DT_INT, FALSE, TRUE);
845     stat_node *range_node = NULL;
846 
847     va_start( list, parent_id );
848     while (( curr_range = va_arg(list, gchar*) )) {
849         range_node = new_stat_node(st, curr_range, rng_root->id, STAT_DT_INT, FALSE, FALSE);
850         range_node->rng = get_range(curr_range);
851     }
852     va_end( list );
853 
854     return rng_root->id;
855 }
856 
857 extern int
stats_tree_create_range_node_string(stats_tree * st,const gchar * name,int parent_id,int num_str_ranges,gchar ** str_ranges)858 stats_tree_create_range_node_string(stats_tree *st, const gchar *name,
859                     int parent_id, int num_str_ranges,
860                     gchar** str_ranges)
861 {
862     int i;
863     stat_node *rng_root = new_stat_node(st, name, parent_id, STAT_DT_INT, FALSE, TRUE);
864     stat_node *range_node = NULL;
865 
866     for (i = 0; i < num_str_ranges - 1; i++) {
867         range_node = new_stat_node(st, str_ranges[i], rng_root->id, STAT_DT_INT, FALSE, FALSE);
868         range_node->rng = get_range(str_ranges[i]);
869     }
870     range_node = new_stat_node(st, str_ranges[i], rng_root->id, STAT_DT_INT, FALSE, FALSE);
871     range_node->rng = get_range(str_ranges[i]);
872     if (range_node->rng->floor == range_node->rng->ceil) {
873         range_node->rng->ceil = G_MAXINT;
874     }
875 
876     return rng_root->id;
877 }
878 
879 /****/
880 extern int
stats_tree_parent_id_by_name(stats_tree * st,const gchar * parent_name)881 stats_tree_parent_id_by_name(stats_tree *st, const gchar *parent_name)
882 {
883     stat_node *node = (stat_node *)g_hash_table_lookup(st->names,parent_name);
884 
885     if (node)
886         return node->id;
887     else
888         return 0; /* XXX: this is the root shoud we return -1 instead?*/
889 }
890 
891 
892 extern int
stats_tree_range_node_with_pname(stats_tree * st,const gchar * name,const gchar * parent_name,...)893 stats_tree_range_node_with_pname(stats_tree *st, const gchar *name,
894                  const gchar *parent_name, ...)
895 {
896     va_list list;
897     gchar *curr_range;
898     stat_node *range_node = NULL;
899     int parent_id = stats_tree_parent_id_by_name(st,parent_name);
900     stat_node *rng_root = new_stat_node(st, name, parent_id, STAT_DT_INT, FALSE, TRUE);
901 
902     va_start( list, parent_name );
903     while (( curr_range = va_arg(list, gchar*) )) {
904         range_node = new_stat_node(st, curr_range, rng_root->id, STAT_DT_INT, FALSE, FALSE);
905         range_node->rng = get_range(curr_range);
906     }
907     va_end( list );
908 
909     return rng_root->id;
910 }
911 
912 
913 extern int
stats_tree_tick_range(stats_tree * st,const gchar * name,int parent_id,int value_in_range)914 stats_tree_tick_range(stats_tree *st, const gchar *name, int parent_id,
915               int value_in_range)
916 {
917 
918     stat_node *node = NULL;
919     stat_node *parent = NULL;
920     stat_node *child = NULL;
921     gint stat_floor, stat_ceil;
922 
923     if (parent_id >= 0 && parent_id < (int) st->parents->len) {
924         parent = (stat_node *)g_ptr_array_index(st->parents,parent_id);
925     } else {
926         ws_assert_not_reached();
927     }
928 
929     if( parent->hash ) {
930         node = (stat_node *)g_hash_table_lookup(parent->hash,name);
931     } else {
932         node = (stat_node *)g_hash_table_lookup(st->names,name);
933     }
934 
935     if ( node == NULL )
936         ws_assert_not_reached();
937 
938     /* update stats for container node. counter should already be ticked so we only update total and min/max */
939     node->total.int_total += value_in_range;
940     if (node->minvalue.int_min > value_in_range) {
941         node->minvalue.int_min = value_in_range;
942     }
943     if (node->maxvalue.int_max < value_in_range) {
944         node->maxvalue.int_max = value_in_range;
945     }
946     node->st_flags |= ST_FLG_AVERAGE;
947 
948     for ( child = node->children; child; child = child->next) {
949         stat_floor =  child->rng->floor;
950         stat_ceil = child->rng->ceil;
951 
952         if ( value_in_range >= stat_floor && value_in_range <= stat_ceil ) {
953             child->counter++;
954             child->total.int_total += value_in_range;
955             if (child->minvalue.int_min > value_in_range) {
956                 child->minvalue.int_min = value_in_range;
957             }
958             if (child->maxvalue.int_max < value_in_range) {
959                 child->maxvalue.int_max = value_in_range;
960             }
961             child->st_flags |= ST_FLG_AVERAGE;
962             update_burst_calc(child, 1);
963             return node->id;
964         }
965     }
966 
967     return node->id;
968 }
969 
970 extern int
stats_tree_create_pivot(stats_tree * st,const gchar * name,int parent_id)971 stats_tree_create_pivot(stats_tree *st, const gchar *name, int parent_id)
972 {
973     stat_node *node = new_stat_node(st,name,parent_id,STAT_DT_INT,TRUE,TRUE);
974 
975     if (node)
976         return node->id;
977     else
978         return 0;
979 }
980 
981 extern int
stats_tree_create_pivot_by_pname(stats_tree * st,const gchar * name,const gchar * parent_name)982 stats_tree_create_pivot_by_pname(stats_tree *st, const gchar *name,
983                  const gchar *parent_name)
984 {
985     int parent_id = stats_tree_parent_id_by_name(st,parent_name);
986     stat_node *node;
987 
988     node = new_stat_node(st,name,parent_id,STAT_DT_INT,TRUE,TRUE);
989 
990     if (node)
991         return node->id;
992     else
993         return 0;
994 }
995 
996 extern int
stats_tree_tick_pivot(stats_tree * st,int pivot_id,const gchar * pivot_value)997 stats_tree_tick_pivot(stats_tree *st, int pivot_id, const gchar *pivot_value)
998 {
999     stat_node *parent = (stat_node *)g_ptr_array_index(st->parents,pivot_id);
1000 
1001     parent->counter++;
1002     update_burst_calc(parent, 1);
1003     stats_tree_manip_node_int( MN_INCREASE, st, pivot_value, pivot_id, FALSE, 1);
1004 
1005     return pivot_id;
1006 }
1007 
1008 extern gchar*
stats_tree_get_displayname(gchar * fullname)1009 stats_tree_get_displayname (gchar* fullname)
1010 {
1011     gchar *buf = g_strdup(fullname);
1012     gchar *sep;
1013 
1014     if (prefs.st_sort_showfullname) {
1015         return buf; /* unmodifed */
1016     }
1017 
1018     sep = buf;
1019     while ((sep = strchr(sep,'/')) != NULL) {
1020         if (*(++sep)=='/') {  /* escapeded slash - two slash characters after each other */
1021             memmove(sep,sep+1,strlen(sep));
1022         }
1023         else {
1024             /* we got a new path separator */
1025             memmove(buf,sep,strlen(sep)+1);
1026             sep = buf;
1027         }
1028     }
1029 
1030     return buf;
1031 }
1032 
1033 extern gint
stats_tree_get_default_sort_col(stats_tree * st)1034 stats_tree_get_default_sort_col (stats_tree *st)
1035 {
1036     switch ((st->st_flags&ST_FLG_SRTCOL_MASK)>>ST_FLG_SRTCOL_SHIFT) {
1037         case ST_SORT_COL_NAME:
1038             return COL_NAME;
1039         case ST_SORT_COL_COUNT:
1040             return COL_COUNT;
1041         case ST_SORT_COL_AVG:
1042             return COL_AVERAGE;
1043         case ST_SORT_COL_MIN:
1044             return COL_MIN;
1045         case ST_SORT_COL_MAX:
1046             return COL_MAX;
1047         case ST_SORT_COL_BURSTRATE:
1048             return COL_BURSTRATE;
1049     }
1050     return COL_COUNT;   /* nothing specific set */
1051 }
1052 
1053 extern gboolean
stats_tree_is_default_sort_DESC(stats_tree * st)1054 stats_tree_is_default_sort_DESC (stats_tree *st)
1055 {
1056     return st->st_flags&ST_FLG_SORT_DESC;
1057 }
1058 
1059 extern const gchar*
stats_tree_get_column_name(gint col_index)1060 stats_tree_get_column_name (gint col_index)
1061 {
1062     switch (col_index) {
1063         case COL_NAME:
1064             return "Topic / Item";
1065         case COL_COUNT:
1066             return "Count";
1067         case COL_AVERAGE:
1068             return "Average";
1069         case COL_MIN:
1070             return "Min Val";
1071         case COL_MAX:
1072             return "Max Val";
1073         case COL_RATE:
1074             return "Rate (ms)";
1075         case COL_PERCENT:
1076             return "Percent";
1077         case COL_BURSTRATE:
1078             return prefs.st_burst_showcount ? "Burst Count" : "Burst Rate";
1079         case COL_BURSTTIME:
1080             return "Burst Start";
1081         default:
1082             return "(Unknown)";
1083     }
1084 }
1085 
1086 extern gint
stats_tree_get_column_size(gint col_index)1087 stats_tree_get_column_size (gint col_index)
1088 {
1089     if (col_index==COL_NAME) {
1090         return 36;      /* but caller should really call stats_tree_branch_max_namelen() */
1091     }
1092     if (col_index<N_COLUMNS) {
1093         return 12;      /* all numerical values are this size */
1094     }
1095     return 0;           /* invalid column */
1096 }
1097 
1098 extern gchar**
stats_tree_get_values_from_node(const stat_node * node)1099 stats_tree_get_values_from_node (const stat_node* node)
1100 {
1101     gchar **values = (gchar**) g_malloc0(sizeof(gchar*)*(node->st->num_columns));
1102 
1103     values[COL_NAME] = (node->st_flags&ST_FLG_ROOTCHILD)?stats_tree_get_displayname(node->name):g_strdup(node->name);
1104     values[COL_COUNT] = g_strdup_printf("%u",node->counter);
1105     if (((node->st_flags&ST_FLG_AVERAGE) || node->rng)) {
1106         if (node->counter) {
1107             switch (node->datatype)
1108             {
1109             case STAT_DT_INT:
1110                 values[COL_AVERAGE] = g_strdup_printf("%.2f", ((float)node->total.int_total) / node->counter);
1111                 break;
1112             case STAT_DT_FLOAT:
1113                 values[COL_AVERAGE] = g_strdup_printf("%.2f", node->total.float_total / node->counter);
1114                 break;
1115             }
1116         } else {
1117             values[COL_AVERAGE] = g_strdup("-");
1118         }
1119     } else {
1120         values[COL_AVERAGE] = g_strdup("");
1121     }
1122 
1123     if (((node->st_flags&ST_FLG_AVERAGE) || node->rng)) {
1124         if (node->counter) {
1125             switch (node->datatype)
1126             {
1127             case STAT_DT_INT:
1128                 values[COL_MIN] = g_strdup_printf("%d", node->minvalue.int_min);
1129                 break;
1130             case STAT_DT_FLOAT:
1131                 values[COL_MIN] = g_strdup_printf("%f", node->minvalue.float_min);
1132                 break;
1133             }
1134         }
1135         else {
1136             values[COL_MIN] = g_strdup("-");
1137         }
1138     }
1139     else {
1140         values[COL_MIN] = g_strdup("");
1141     }
1142 
1143     if (((node->st_flags&ST_FLG_AVERAGE) || node->rng)) {
1144         if (node->counter) {
1145             switch (node->datatype)
1146             {
1147             case STAT_DT_INT:
1148                 values[COL_MAX] = g_strdup_printf("%d", node->maxvalue.int_max);
1149                 break;
1150             case STAT_DT_FLOAT:
1151                 values[COL_MAX] = g_strdup_printf("%f", node->maxvalue.float_max);
1152                 break;
1153             }
1154         }
1155         else {
1156             values[COL_MAX] = g_strdup("-");
1157         }
1158     }
1159     else {
1160         values[COL_MAX] = g_strdup("");
1161     }
1162 
1163     values[COL_RATE] = (node->st->elapsed)?g_strdup_printf("%.4f",((float)node->counter)/node->st->elapsed):g_strdup("");
1164     values[COL_PERCENT] = ((node->parent)&&(node->parent->counter))?
1165                 g_strdup_printf("%.2f%%",(node->counter*100.0)/node->parent->counter):
1166                 (node->parent==&(node->st->root)?g_strdup("100%"):g_strdup(""));
1167     if (node->st->num_columns>COL_BURSTTIME) {
1168         values[COL_BURSTRATE] = (!prefs.st_enable_burstinfo)?g_strdup(""):
1169                 (node->max_burst?(prefs.st_burst_showcount?
1170                                 g_strdup_printf("%d",node->max_burst):
1171                                 g_strdup_printf("%.4f",((double)node->max_burst)/prefs.st_burst_windowlen)):
1172                 g_strdup("-"));
1173         values[COL_BURSTTIME] = (!prefs.st_enable_burstinfo)?g_strdup(""):
1174                 (node->max_burst?g_strdup_printf("%.3f",(node->burst_time/1000.0)):g_strdup("-"));
1175     }
1176     return values;
1177 }
1178 
1179 extern gint
stats_tree_sort_compare(const stat_node * a,const stat_node * b,gint sort_column,gboolean sort_descending)1180 stats_tree_sort_compare (const stat_node *a, const stat_node *b, gint sort_column,
1181                     gboolean sort_descending)
1182 {
1183     int result = 0;
1184     float avg_a = 0, avg_b = 0;
1185 
1186     if  (prefs.st_sort_rng_nameonly&&(a->rng&&b->rng)) {
1187         /* always sort ranges by range name */
1188         result = a->rng->floor - b->rng->floor;
1189         if (sort_descending&&(!prefs.st_sort_rng_fixorder)) {
1190             result = -result;
1191         }
1192         return result;
1193     }
1194 
1195     switch (sort_column) {
1196         case COL_NAME:
1197             if  (a->rng&&b->rng) {
1198                 result = a->rng->floor - b->rng->floor;
1199             }
1200             else if (prefs.st_sort_casesensitve) {
1201                 result = strcmp(a->name,b->name);
1202             }
1203             else {
1204                 result = g_ascii_strcasecmp(a->name,b->name);
1205             }
1206             break;
1207 
1208         case COL_RATE:
1209         case COL_PERCENT:
1210         case COL_COUNT:
1211             result = a->counter - b->counter;
1212             break;
1213 
1214         case COL_AVERAGE:
1215             switch (a->datatype)
1216             {
1217             case STAT_DT_INT:
1218                 avg_a = a->counter ? ((float)a->total.int_total)/a->counter : 0;
1219                 avg_b = b->counter ? ((float)b->total.int_total)/b->counter : 0;
1220                 break;
1221             case STAT_DT_FLOAT:
1222                 avg_a = a->counter ? ((float)a->total.float_total) / a->counter : 0;
1223                 avg_b = b->counter ? ((float)b->total.float_total) / b->counter : 0;
1224                 break;
1225             }
1226             result = (avg_a>avg_b) ? 1 : ( (avg_a<avg_b) ? -1 : 0);
1227             break;
1228 
1229         case COL_MIN:
1230             switch (a->datatype)
1231             {
1232             case STAT_DT_INT:
1233                 result = a->minvalue.int_min - b->minvalue.int_min;
1234                 break;
1235             case STAT_DT_FLOAT:
1236                 result = (a->minvalue.float_min>b->minvalue.int_min) ? 1 : ((a->minvalue.float_min<b->minvalue.int_min) ? -1 : 0);
1237                 break;
1238             }
1239             break;
1240 
1241         case COL_MAX:
1242             switch (a->datatype)
1243             {
1244             case STAT_DT_INT:
1245                 result = a->maxvalue.int_max - b->maxvalue.int_max;
1246                 break;
1247             case STAT_DT_FLOAT:
1248                 result = (a->maxvalue.float_max>b->maxvalue.float_max) ? 1 : ((a->maxvalue.float_max<b->maxvalue.float_max) ? -1 : 0);
1249                 break;
1250             }
1251             break;
1252 
1253         case COL_BURSTRATE:
1254             result = a->max_burst - b->max_burst;
1255             break;
1256 
1257         case COL_BURSTTIME:
1258             result = (a->burst_time>b->burst_time)?1:((a->burst_time<b->burst_time)?-1:0);
1259             break;
1260 
1261         default:
1262             /* no sort comparison found for column - must update this switch statement */
1263             ws_assert_not_reached();
1264     }
1265 
1266     /* break tie between items with same primary search result */
1267     if (!result) {
1268         if (sort_column==COL_NAME) {
1269             result = a->counter - b->counter;
1270         }
1271         else {
1272             if  (a->rng&&b->rng) {
1273                 result = a->rng->floor - b->rng->floor;
1274             }
1275             else if (prefs.st_sort_casesensitve) {
1276                 result = strcmp(a->name,b->name);
1277             }
1278             else {
1279                 result = g_ascii_strcasecmp(a->name,b->name);
1280             }
1281         }
1282     }
1283 
1284     /* take into account sort order */
1285     if (sort_descending) {
1286         result = -result;
1287     }
1288 
1289     if ((a->st_flags&ST_FLG_SORT_TOP)!=(b->st_flags&ST_FLG_SORT_TOP)) {
1290         /* different sort groups top vs non-top */
1291         result = (a->st_flags&ST_FLG_SORT_TOP)?-1:1;
1292     }
1293     return result;
1294 }
1295 
1296 extern GString*
stats_tree_format_as_str(const stats_tree * st,st_format_type format_type,gint sort_column,gboolean sort_descending)1297 stats_tree_format_as_str(const stats_tree* st, st_format_type format_type,
1298                     gint sort_column, gboolean sort_descending)
1299 {
1300     int maxnamelen = stats_tree_branch_max_namelen(&st->root,0);
1301     stat_node *child;
1302     GString *s;
1303     int count;
1304     gchar *separator = NULL;
1305 
1306     switch(format_type) {
1307         case ST_FORMAT_YAML:
1308             s = g_string_new("---\n");
1309             break;
1310         case ST_FORMAT_XML:
1311             s = g_string_new("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1312             break;
1313         case ST_FORMAT_CSV:
1314             s = g_string_new("\"level\",\"parent\",");
1315             for (count = 0; count<st->num_columns; count++) {
1316                 g_string_append_printf(s,"\"%s\",",stats_tree_get_column_name(count));
1317             }
1318             g_string_append (s,"\n");
1319             break;
1320         case ST_FORMAT_PLAIN:
1321         {
1322             char fmt[16];
1323             int sep_length;
1324 
1325             sep_length = maxnamelen;
1326             for (count = 1; count<st->num_columns; count++) {
1327                 sep_length += stats_tree_get_column_size(count)+2;
1328             }
1329             separator = (gchar *)g_malloc(sep_length+1);
1330             memset (separator, '=', sep_length);
1331             separator[sep_length] = 0;
1332 
1333             s = g_string_new("\n");
1334             g_string_append(s,separator);
1335             g_string_append_printf(s,"\n%s:\n",st->cfg->name);
1336             g_snprintf (fmt,(gulong)sizeof(fmt),"%%-%us",maxnamelen);
1337             g_string_append_printf(s,fmt,stats_tree_get_column_name(0));
1338             for (count = 1; count<st->num_columns; count++) {
1339                 g_snprintf (fmt,(gulong)sizeof(fmt)," %%-%us",stats_tree_get_column_size(count)+1);
1340                 g_string_append_printf(s,fmt,stats_tree_get_column_name(count));
1341             }
1342             memset (separator, '-', sep_length);
1343             g_string_append_printf(s,"\n%s\n",separator);
1344             break;
1345         }
1346         default:
1347             return g_string_new("unknown format for stats_tree\n");
1348     }
1349 
1350     for (child = st->root.children; child; child = child->next ) {
1351         stats_tree_format_node_as_str(child,s,format_type,0,"",maxnamelen,sort_column,sort_descending);
1352 
1353     }
1354 
1355     if (format_type==ST_FORMAT_PLAIN) {
1356         g_string_append_printf(s,"\n%s\n",separator);
1357         g_free(separator);
1358     }
1359 
1360     return s;
1361 }
1362 
1363 typedef struct {
1364     gint sort_column;
1365     gboolean sort_descending;
1366 }   sortinfo;
1367 
1368 /* Function to compare elements for child array sort. a and b are children, user_data
1369 points to a st_flags value */
1370 extern gint
stat_node_array_sortcmp(gconstpointer a,gconstpointer b,gpointer user_data)1371 stat_node_array_sortcmp (gconstpointer a, gconstpointer b, gpointer user_data)
1372 {
1373     /* user_data is *guint value to st_flags */
1374     return stats_tree_sort_compare (*(const stat_node*const*)a,*(const stat_node*const*)b,
1375                     ((sortinfo*)user_data)->sort_column,((sortinfo*)user_data)->sort_descending);
1376 }
1377 
1378 static gchar*
clean_for_xml_tag(gchar * str)1379 clean_for_xml_tag (gchar *str)
1380 {
1381     gchar *s = str;
1382     while ((s=strpbrk(s,"!\"#$%%&'()*+,/;<=>?@[\\]^`{|}~ ")) != NULL) {
1383         *(s++) = '-';
1384     }
1385     return str;
1386 }
1387 
1388 /** helper funcation to add note to formatted stats_tree */
stats_tree_format_node_as_str(const stat_node * node,GString * s,st_format_type format_type,guint indent,const gchar * path,gint maxnamelen,gint sort_column,gboolean sort_descending)1389 WS_DLL_PUBLIC void stats_tree_format_node_as_str(const stat_node *node,
1390                          GString *s,
1391                          st_format_type format_type,
1392                          guint indent,
1393                          const gchar *path,
1394                          gint maxnamelen,
1395                          gint sort_column,
1396                          gboolean sort_descending)
1397 {
1398     int count;
1399     int num_columns = node->st->num_columns;
1400     gchar **values = stats_tree_get_values_from_node(node);
1401     stat_node *child;
1402     sortinfo si;
1403     gchar *full_path;
1404     char fmt[16] = "%s%s%s";
1405 
1406     switch(format_type) {
1407         case ST_FORMAT_YAML:
1408             if (indent) {
1409                 g_snprintf(fmt, (gulong)sizeof(fmt), "%%%ds%%s%%s", indent*4-2);
1410             }
1411             g_string_append_printf(s, fmt, "", indent?"- ":"", "Description");
1412             g_string_append_printf(s, ": \"%s\"\n", values[0]);
1413 
1414             for (count = 1; count<num_columns; count++) {
1415                 if (*values[count]) {
1416                     g_string_append_printf(s, fmt, "", indent?"  ":"",
1417                                             stats_tree_get_column_name(count));
1418                     g_string_append_printf(s, ": %s\n", values[count]);
1419                 }
1420             }
1421             if (node->children) {
1422                 g_string_append_printf(s, fmt, "", indent?"  ":"", "Items:\n");
1423             }
1424             break;
1425         case ST_FORMAT_XML:
1426         {
1427             char *itemname = xml_escape(values[0]);
1428             g_string_append_printf(s,"<stat-node name=\"%s\"%s>\n",itemname,
1429                     node->rng?" isrange=\"true\"":"");
1430             g_free(itemname);
1431             for (count = 1; count<num_columns; count++) {
1432                 gchar *colname = g_strdup(stats_tree_get_column_name(count));
1433                 g_string_append_printf(s,"<%s>",clean_for_xml_tag(colname));
1434                 g_string_append_printf(s,"%s</%s>\n",values[count],colname);
1435                 g_free(colname);
1436             }
1437             break;
1438         }
1439         case ST_FORMAT_CSV:
1440             g_string_append_printf(s,"%d,\"%s\",\"%s\"",indent,path,values[0]);
1441             for (count = 1; count<num_columns; count++) {
1442                 g_string_append_printf(s,",%s",values[count]);
1443             }
1444             g_string_append (s,"\n");
1445             break;
1446         case ST_FORMAT_PLAIN:
1447             g_snprintf (fmt,(gulong)sizeof(fmt),"%%%ds%%-%us",indent,maxnamelen-indent);
1448             g_string_append_printf(s,fmt,"",values[0]);
1449             for (count = 1; count<num_columns; count++) {
1450                 g_snprintf (fmt,(gulong)sizeof(fmt)," %%-%us",stats_tree_get_column_size(count)+1);
1451                 g_string_append_printf(s,fmt,values[count]);
1452             }
1453             g_string_append (s,"\n");
1454             break;
1455     }
1456 
1457     indent++;
1458     indent = indent > INDENT_MAX ? INDENT_MAX : indent;
1459     full_path = g_strdup_printf ("%s/%s",path,values[0]);
1460 
1461     for (count = 0; count<num_columns; count++) {
1462         g_free(values[count]);
1463     }
1464     g_free(values);
1465 
1466     if (node->children) {
1467         GArray *Children = g_array_new(FALSE,FALSE,sizeof(child));
1468         for (child = node->children; child; child = child->next ) {
1469             g_array_append_val(Children,child);
1470         }
1471         si.sort_column = sort_column;
1472         si.sort_descending = sort_descending;
1473         g_array_sort_with_data(Children,stat_node_array_sortcmp,&si);
1474         for (count = 0; count<((int)Children->len); count++) {
1475             stats_tree_format_node_as_str(g_array_index(Children,stat_node*,count), s, format_type,
1476                     indent, full_path, maxnamelen, sort_column, sort_descending);
1477         }
1478         g_array_free(Children, TRUE);
1479     }
1480     g_free(full_path);
1481 
1482     if (format_type==ST_FORMAT_XML) {
1483         g_string_append(s,"</stat-node>\n");
1484     }
1485 }
1486 
stats_tree_cleanup(void)1487 void stats_tree_cleanup(void)
1488 {
1489     g_hash_table_destroy(registry);
1490 }
1491 
1492 /*
1493  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
1494  *
1495  * Local variables:
1496  * c-basic-offset: 4
1497  * tab-width: 8
1498  * indent-tabs-mode: nil
1499  * End:
1500  *
1501  * vi: set shiftwidth=4 tabstop=8 expandtab:
1502  * :indentSize=4:tabSize=8:noTabs=true:
1503  */
1504