sharkd: add more information about currently loaded file.
[metze/wireshark/wip.git] / sharkd_session.c
1 /* sharkd_session.c
2  *
3  * Copyright (C) 2016 Jakub Zawadzki
4  *
5  * Wireshark - Network traffic analyzer
6  * By Gerald Combs <gerald@wireshark.org>
7  * Copyright 1998 Gerald Combs
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version 2
12  * of the License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23
24 #include <config.h>
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.h>
30
31 #include <glib.h>
32
33 #include <wsutil/wsjsmn.h>
34 #include <wsutil/ws_printf.h>
35
36 #include <file.h>
37 #include <epan/exceptions.h>
38 #include <epan/color_filters.h>
39 #include <epan/prefs.h>
40 #include <epan/prefs-int.h>
41 #include <epan/uat-int.h>
42 #include <wiretap/wtap.h>
43
44 #include <epan/column.h>
45
46 #include <ui/ssl_key_export.h>
47
48 #include <epan/stats_tree_priv.h>
49 #include <epan/stat_tap_ui.h>
50 #include <epan/conversation_table.h>
51 #include <epan/expert.h>
52 #include <epan/export_object.h>
53 #include <epan/follow.h>
54 #include <epan/rtd_table.h>
55 #include <epan/srt_table.h>
56
57 #include <epan/dissectors/packet-h225.h>
58 #include <epan/rtp_pt.h>
59 #include <ui/voip_calls.h>
60 #include <ui/rtp_stream.h>
61 #include <ui/tap-rtp-common.h>
62 #include <epan/to_str.h>
63
64 #include <epan/addr_resolv.h>
65 #include <epan/dissectors/packet-rtp.h>
66 #include <ui/rtp_media.h>
67 #include <codecs/speex/speex_resampler.h>
68
69 #ifdef HAVE_GEOIP
70 # include <GeoIP.h>
71 # include <epan/geoip_db.h>
72 # include <wsutil/pint.h>
73 #endif
74
75 #include <wsutil/glib-compat.h>
76 #include <wsutil/strtoi.h>
77
78 #include "sharkd.h"
79
80 static void
81 json_unescape_str(char *input)
82 {
83         char *output = input;
84
85         while (*input)
86         {
87                 char ch = *input++;
88
89                 if (ch == '\\')
90                 {
91                         /* TODO, add more escaping rules */
92                         ch = *input++;
93                 }
94
95                 *output = ch;
96                 output++;
97         }
98
99         *output = '\0';
100 }
101
102 static const char *
103 json_find_attr(const char *buf, const jsmntok_t *tokens, int count, const char *attr)
104 {
105         int i;
106
107         for (i = 0; i < count; i += 2)
108         {
109                 const char *tok_attr  = &buf[tokens[i + 0].start];
110                 const char *tok_value = &buf[tokens[i + 1].start];
111
112                 if (!strcmp(tok_attr, attr))
113                         return tok_value;
114         }
115
116         return NULL;
117 }
118
119 static void
120 json_puts_string(const char *str)
121 {
122         int i;
123
124         if (str == NULL)
125                 str = "";
126
127         putchar('"');
128         for (i = 0; str[i]; i++)
129         {
130                 switch (str[i])
131                 {
132                         case '\\':
133                         case '"':
134                                 putchar('\\');
135                                 putchar(str[i]);
136                                 break;
137
138                         case '\n':
139                                 putchar('\\');
140                                 putchar('n');
141                                 break;
142
143                         default:
144                                 putchar(str[i]);
145                                 break;
146                 }
147         }
148
149         putchar('"');
150 }
151
152 static void
153 json_print_base64_step(const guint8 *data, int *state1, int *state2)
154 {
155         gchar buf[(1 / 3 + 1) * 4 + 4 + 1];
156         gsize wrote;
157
158         if (data)
159                 wrote = g_base64_encode_step(data, 1, FALSE, buf, state1, state2);
160         else
161                 wrote = g_base64_encode_close(FALSE, buf, state1, state2);
162
163         if (wrote > 0)
164         {
165                 buf[wrote] = '\0';
166                 printf("%s", buf);
167         }
168 }
169
170 static void
171 json_print_base64(const guint8 *data, size_t len)
172 {
173         size_t i;
174         int base64_state1 = 0;
175         int base64_state2 = 0;
176
177         putchar('"');
178
179         for (i = 0; i < len; i++)
180                 json_print_base64_step(&data[i], &base64_state1, &base64_state2);
181
182         json_print_base64_step(NULL, &base64_state1, &base64_state2);
183
184         putchar('"');
185 }
186
187 struct filter_item
188 {
189         struct filter_item *next;
190
191         char *filter;
192         guint8 *filtered;
193 };
194
195 static struct filter_item *filter_list = NULL;
196
197 static const guint8 *
198 sharkd_session_filter_data(const char *filter)
199 {
200         struct filter_item *l;
201
202         for (l = filter_list; l; l = l->next)
203         {
204                 if (!strcmp(l->filter, filter))
205                         return l->filtered;
206         }
207
208         {
209                 guint8 *filtered = NULL;
210
211                 int ret = sharkd_filter(filter, &filtered);
212
213                 if (ret == -1)
214                         return NULL;
215
216                 l = (struct filter_item *) g_malloc(sizeof(struct filter_item));
217                 l->filter = g_strdup(filter);
218                 l->filtered = filtered;
219
220                 l->next = filter_list;
221                 filter_list = l;
222
223                 return filtered;
224         }
225 }
226
227 struct sharkd_rtp_match
228 {
229         guint32 addr_src, addr_dst;
230         address src_addr;
231         address dst_addr;
232         guint16 src_port;
233         guint16 dst_port;
234         guint32 ssrc;
235 };
236
237 static gboolean
238 sharkd_rtp_match_init(struct sharkd_rtp_match *req, const char *init_str)
239 {
240         gboolean ret = FALSE;
241         char **arr;
242
243         arr = g_strsplit(init_str, "_", 7); /* pass larger value, so we'll catch incorrect input :) */
244         if (g_strv_length(arr) != 5)
245                 goto fail;
246
247         /* TODO, for now only IPv4 */
248         if (!get_host_ipaddr(arr[0], &req->addr_src))
249                 goto fail;
250
251         if (!ws_strtou16(arr[1], NULL, &req->src_port))
252                 goto fail;
253
254         if (!get_host_ipaddr(arr[2], &req->addr_dst))
255                 goto fail;
256
257         if (!ws_strtou16(arr[3], NULL, &req->dst_port))
258                 goto fail;
259
260         if (!ws_hexstrtou32(arr[4], NULL, &req->ssrc))
261                 goto fail;
262
263         set_address(&req->src_addr, AT_IPv4, 4, &req->addr_src);
264         set_address(&req->dst_addr, AT_IPv4, 4, &req->addr_dst);
265         ret = TRUE;
266
267 fail:
268         g_strfreev(arr);
269         return ret;
270 }
271
272 static gboolean
273 sharkd_rtp_match_check(const struct sharkd_rtp_match *req, const packet_info *pinfo, const struct _rtp_info *rtp_info)
274 {
275         if (rtp_info->info_sync_src == req->ssrc &&
276                 pinfo->srcport == req->src_port &&
277                 pinfo->destport == req->dst_port &&
278                 addresses_equal(&pinfo->src, &req->src_addr) &&
279                 addresses_equal(&pinfo->dst, &req->dst_addr))
280         {
281                 return TRUE;
282         }
283
284         return FALSE;
285 }
286
287 static gboolean
288 sharkd_session_process_info_nstat_cb(const void *key, void *value, void *userdata)
289 {
290         stat_tap_table_ui *new_stat_tap = (stat_tap_table_ui *) value;
291         int *pi = (int *) userdata;
292
293         printf("%s{", (*pi) ? "," : "");
294                 printf("\"name\":\"%s\"", new_stat_tap->title);
295                 printf(",\"tap\":\"nstat:%s\"", (const char *) key);
296         printf("}");
297
298         *pi = *pi + 1;
299         return FALSE;
300 }
301
302 static gboolean
303 sharkd_session_process_info_conv_cb(const void* key, void* value, void* userdata)
304 {
305         struct register_ct *table = (struct register_ct *) value;
306         int *pi = (int *) userdata;
307
308         const char *label = (const char*)key;
309
310         if (get_conversation_packet_func(table))
311         {
312                 printf("%s{", (*pi) ? "," : "");
313                         printf("\"name\":\"Conversation List/%s\"", label);
314                         printf(",\"tap\":\"conv:%s\"", label);
315                 printf("}");
316
317                 *pi = *pi + 1;
318         }
319
320         if (get_hostlist_packet_func(table))
321         {
322                 printf("%s{", (*pi) ? "," : "");
323                         printf("\"name\":\"Endpoint/%s\"", label);
324                         printf(",\"tap\":\"endpt:%s\"", label);
325                 printf("}");
326
327                 *pi = *pi + 1;
328         }
329         return FALSE;
330 }
331
332 static gboolean
333 sharkd_export_object_visit_cb(const void *key _U_, void *value, void *user_data)
334 {
335         register_eo_t *eo = (register_eo_t*)value;
336         int *pi = (int *) user_data;
337
338         const int proto_id = get_eo_proto_id(eo);
339         const char *filter = proto_get_protocol_filter_name(proto_id);
340         const char *label  = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
341
342         printf("%s{", (*pi) ? "," : "");
343                 printf("\"name\":\"Export Object/%s\"", label);
344                 printf(",\"tap\":\"eo:%s\"", filter);
345         printf("}");
346
347         *pi = *pi + 1;
348         return FALSE;
349 }
350
351 static gboolean
352 sharkd_srt_visit_cb(const void *key _U_, void *value, void *user_data)
353 {
354         register_srt_t *srt = (register_srt_t *) value;
355         int *pi = (int *) user_data;
356
357         const int proto_id = get_srt_proto_id(srt);
358         const char *filter = proto_get_protocol_filter_name(proto_id);
359         const char *label  = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
360
361         printf("%s{", (*pi) ? "," : "");
362                 printf("\"name\":\"Service Response Time/%s\"", label);
363                 printf(",\"tap\":\"srt:%s\"", filter);
364         printf("}");
365
366         *pi = *pi + 1;
367         return FALSE;
368 }
369
370 static gboolean
371 sharkd_rtd_visit_cb(const void *key _U_, void *value, void *user_data)
372 {
373         register_rtd_t *rtd = (register_rtd_t *) value;
374         int *pi = (int *) user_data;
375
376         const int proto_id = get_rtd_proto_id(rtd);
377         const char *filter = proto_get_protocol_filter_name(proto_id);
378         const char *label  = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
379
380         printf("%s{", (*pi) ? "," : "");
381                 printf("\"name\":\"Response Time Delay/%s\"", label);
382                 printf(",\"tap\":\"rtd:%s\"", filter);
383         printf("}");
384
385         *pi = *pi + 1;
386         return FALSE;
387 }
388
389 static gboolean
390 sharkd_follower_visit_cb(const void *key _U_, void *value, void *user_data)
391 {
392         register_follow_t *follower = (register_follow_t*) value;
393         int *pi = (int *) user_data;
394
395         const int proto_id = get_follow_proto_id(follower);
396         const char *label  = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
397         const char *filter = label; /* correct: get_follow_by_name() is registered by short name */
398
399         printf("%s{", (*pi) ? "," : "");
400                 printf("\"name\":\"Follow/%s\"", label);
401                 printf(",\"tap\":\"follow:%s\"", filter);
402         printf("}");
403
404         *pi = *pi + 1;
405         return FALSE;
406 }
407
408 /**
409  * sharkd_session_process_info()
410  *
411  * Process info request
412  *
413  * Output object with attributes:
414  *   (m) columns - available column formats, array of object with attributes:
415  *                  'name'   - column name
416  *                  'format' - column format-name
417  *
418  *   (m) stats   - available statistics, array of object with attributes:
419  *                  'name' - statistic name
420  *                  'tap'  - sharkd tap-name for statistic
421  *
422  *   (m) convs   - available conversation list, array of object with attributes:
423  *                  'name' - conversation name
424  *                  'tap'  - sharkd tap-name for conversation
425  *
426  *   (m) eo      - available export object list, array of object with attributes:
427  *                  'name' - export object name
428  *                  'tap'  - sharkd tap-name for eo
429  *
430  *   (m) srt     - available service response time list, array of object with attributes:
431  *                  'name' - service response time name
432  *                  'tap'  - sharkd tap-name for srt
433  *
434  *   (m) rtd     - available response time delay list, array of object with attributes:
435  *                  'name' - response time delay name
436  *                  'tap'  - sharkd tap-name for rtd
437  *
438  *   (m) taps - available taps, array of object with attributes:
439  *                  'name' - tap name
440  *                  'tap'  - sharkd tap-name
441  *
442  *   (m) follow - available followers, array of object with attributes:
443  *                  'name' - tap name
444  *                  'tap'  - sharkd tap-name
445  *
446  *   (m) ftypes   - conversation table for FT_ number to string
447  */
448 static void
449 sharkd_session_process_info(void)
450 {
451         int i;
452
453         printf("{\"columns\":[");
454         for (i = 0; i < NUM_COL_FMTS; i++)
455         {
456                 const char *col_format = col_format_to_string(i);
457                 const char *col_descr  = col_format_desc(i);
458
459                 printf("%s{", (i) ? "," : "");
460                         printf("\"name\":\"%s\"", col_descr);
461                         printf(",\"format\":\"%s\"", col_format);
462                 printf("}");
463         }
464         printf("]");
465
466         printf(",\"stats\":[");
467         {
468                 GList *cfg_list = stats_tree_get_cfg_list();
469                 GList *l;
470                 const char *sepa = "";
471
472                 for (l = cfg_list; l; l = l->next)
473                 {
474                         stats_tree_cfg *cfg = (stats_tree_cfg *) l->data;
475
476                         printf("%s{", sepa);
477                                 printf("\"name\":\"%s\"", cfg->name);
478                                 printf(",\"tap\":\"stat:%s\"", cfg->abbr);
479                         printf("}");
480                         sepa = ",";
481                 }
482
483                 g_list_free(cfg_list);
484         }
485         printf("]");
486
487         printf(",\"ftypes\":[");
488         for (i = 0; i < FT_NUM_TYPES; i++)
489         {
490                 if (i)
491                         printf(",");
492                 json_puts_string(ftype_name((ftenum_t) i));
493         }
494         printf("]");
495
496         printf(",\"version\":");
497         json_puts_string(sharkd_version());
498
499         printf(",\"nstat\":[");
500         i = 0;
501         new_stat_tap_iterate_tables(sharkd_session_process_info_nstat_cb, &i);
502         printf("]");
503
504         printf(",\"convs\":[");
505         i = 0;
506         conversation_table_iterate_tables(sharkd_session_process_info_conv_cb, &i);
507         printf("]");
508
509         printf(",\"taps\":[");
510         {
511                 printf("{\"name\":\"%s\",\"tap\":\"%s\"}", "RTP streams", "rtp-streams");
512                 printf(",{\"name\":\"%s\",\"tap\":\"%s\"}", "Expert Information", "expert");
513         }
514         printf("]");
515
516         printf(",\"eo\":[");
517         i = 0;
518         eo_iterate_tables(sharkd_export_object_visit_cb, &i);
519         printf("]");
520
521         printf(",\"srt\":[");
522         i = 0;
523         srt_table_iterate_tables(sharkd_srt_visit_cb, &i);
524         printf("]");
525
526         printf(",\"rtd\":[");
527         i = 0;
528         rtd_table_iterate_tables(sharkd_rtd_visit_cb, &i);
529         printf("]");
530
531         printf(",\"follow\":[");
532         i = 0;
533         follow_iterate_followers(sharkd_follower_visit_cb, &i);
534         printf("]");
535
536         printf("}\n");
537 }
538
539 /**
540  * sharkd_session_process_load()
541  *
542  * Process load request
543  *
544  * Input:
545  *   (m) file - file to be loaded
546  *
547  * Output object with attributes:
548  *   (m) err - error code
549  */
550 static void
551 sharkd_session_process_load(const char *buf, const jsmntok_t *tokens, int count)
552 {
553         const char *tok_file = json_find_attr(buf, tokens, count, "file");
554         int err = 0;
555
556         fprintf(stderr, "load: filename=%s\n", tok_file);
557
558         if (!tok_file)
559                 return;
560
561         if (sharkd_cf_open(tok_file, WTAP_TYPE_AUTO, FALSE, &err) != CF_OK)
562         {
563                 printf("{\"err\":%d}\n", err);
564                 return;
565         }
566
567         TRY
568         {
569                 err = sharkd_load_cap_file();
570         }
571         CATCH(OutOfMemoryError)
572         {
573                 fprintf(stderr, "load: OutOfMemoryError\n");
574                 err = ENOMEM;
575         }
576         ENDTRY;
577
578         printf("{\"err\":%d}\n", err);
579 }
580
581 /**
582  * sharkd_session_process_status()
583  *
584  * Process status request
585  *
586  * Output object with attributes:
587  *   (m) frames   - count of currently loaded frames
588  *   (m) duration - time difference between time of first frame, and last loaded frame
589  *   (o) filename - capture filename
590  *   (o) filesize - capture filesize
591  */
592 static void
593 sharkd_session_process_status(void)
594 {
595         printf("{\"frames\":%u", cfile.count);
596
597         printf(",\"duration\":%.9f", nstime_to_sec(&cfile.elapsed_time));
598
599         if (cfile.filename)
600         {
601                 char *name = g_path_get_basename(cfile.filename);
602
603                 printf(",\"filename\":");
604                 json_puts_string(name);
605                 g_free(name);
606         }
607
608         if (cfile.wth)
609         {
610                 gint64 file_size = wtap_file_size(cfile.wth, NULL);
611
612                 if (file_size > 0)
613                         printf(",\"filesize\":%" G_GINT64_FORMAT, file_size);
614         }
615
616         printf("}\n");
617 }
618
619 struct sharkd_analyse_data
620 {
621         GHashTable *protocols_set;
622         nstime_t *first_time;
623         nstime_t *last_time;
624 };
625
626 static void
627 sharkd_session_process_analyse_cb(packet_info *pi, proto_tree *tree, struct epan_column_info *cinfo, const GSList *data_src, void *data)
628 {
629         struct sharkd_analyse_data *analyser = (struct sharkd_analyse_data *) data;
630         frame_data *fdata = pi->fd;
631
632         (void) tree;
633         (void) cinfo;
634         (void) data_src;
635
636         if (analyser->first_time == NULL || nstime_cmp(&fdata->abs_ts, analyser->first_time) < 0)
637                 analyser->first_time = &fdata->abs_ts;
638
639         if (analyser->last_time == NULL || nstime_cmp(&fdata->abs_ts, analyser->last_time) > 0)
640                 analyser->last_time = &fdata->abs_ts;
641
642         if (pi->layers)
643         {
644                 wmem_list_frame_t *frame;
645
646                 for (frame = wmem_list_head(pi->layers); frame; frame = wmem_list_frame_next(frame))
647                 {
648                         int proto_id = GPOINTER_TO_UINT(wmem_list_frame_data(frame));
649
650                         if (!g_hash_table_lookup_extended(analyser->protocols_set, GUINT_TO_POINTER(proto_id), NULL, NULL))
651                         {
652                                 g_hash_table_insert(analyser->protocols_set, GUINT_TO_POINTER(proto_id), GUINT_TO_POINTER(proto_id));
653
654                                 if (g_hash_table_size(analyser->protocols_set) != 1)
655                                         printf(",");
656                                 json_puts_string(proto_get_protocol_filter_name(proto_id));
657                         }
658                 }
659         }
660
661 }
662
663 /**
664  * sharkd_session_process_status()
665  *
666  * Process analyse request
667  *
668  * Output object with attributes:
669  *   (m) frames  - count of currently loaded frames
670  *   (m) protocols - protocol list
671  *   (m) first     - earliest frame time
672  *   (m) last      - latest frame time
673  */
674 static void
675 sharkd_session_process_analyse(void)
676 {
677         unsigned int framenum;
678         struct sharkd_analyse_data analyser;
679
680         analyser.first_time = NULL;
681         analyser.last_time  = NULL;
682         analyser.protocols_set = g_hash_table_new(NULL /* g_direct_hash() */, NULL /* g_direct_equal */);
683
684         printf("{\"frames\":%u", cfile.count);
685
686         printf(",\"protocols\":[");
687         for (framenum = 1; framenum <= cfile.count; framenum++)
688                 sharkd_dissect_request(framenum, &sharkd_session_process_analyse_cb, 0, 0, 0, &analyser);
689         printf("]");
690
691         if (analyser.first_time)
692                 printf(",\"first\":%.9f", nstime_to_sec(analyser.first_time));
693
694         if (analyser.last_time)
695                 printf(",\"last\":%.9f", nstime_to_sec(analyser.last_time));
696
697         printf("}\n");
698
699         g_hash_table_destroy(analyser.protocols_set);
700 }
701
702 /**
703  * sharkd_session_process_frames()
704  *
705  * Process frames request
706  *
707  * Input:
708  *   (o) filter - filter to be used
709  *   (o) skip=N   - skip N frames
710  *   (o) limit=N  - show only N frames
711  *
712  * Output array of frames with attributes:
713  *   (m) c   - array of column data
714  *   (m) num - frame number
715  *   (m) i   - if frame is ignored
716  *   (m) m   - if frame is marked
717  *   (m) bg  - color filter - background color in hex
718  *   (m) fg  - color filter - foreground color in hex
719  */
720 static void
721 sharkd_session_process_frames(const char *buf, const jsmntok_t *tokens, int count)
722 {
723         const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
724         const char *tok_skip   = json_find_attr(buf, tokens, count, "skip");
725         const char *tok_limit  = json_find_attr(buf, tokens, count, "limit");
726
727         const guint8 *filter_data = NULL;
728
729         const char *frame_sepa = "";
730         int col;
731
732         guint32 framenum;
733         guint32 skip;
734         guint32 limit;
735
736         column_info *cinfo = &cfile.cinfo;
737
738         if (tok_filter)
739         {
740                 filter_data = sharkd_session_filter_data(tok_filter);
741                 if (!filter_data)
742                         return;
743         }
744
745         skip = 0;
746         if (tok_skip)
747         {
748                 if (!ws_strtou32(tok_skip, NULL, &skip))
749                         return;
750         }
751
752         limit = 0;
753         if (tok_limit)
754         {
755                 if (!ws_strtou32(tok_limit, NULL, &limit))
756                         return;
757         }
758
759         printf("[");
760         for (framenum = 1; framenum <= cfile.count; framenum++)
761         {
762                 frame_data *fdata = frame_data_sequence_find(cfile.frames, framenum);
763
764                 if (filter_data && !(filter_data[framenum / 8] & (1 << (framenum % 8))))
765                         continue;
766
767                 if (skip)
768                 {
769                         skip--;
770                         continue;
771                 }
772
773                 sharkd_dissect_columns(framenum, cinfo, (fdata->color_filter == NULL));
774
775                 printf("%s{\"c\":[", frame_sepa);
776                 for (col = 0; col < cinfo->num_cols; ++col)
777                 {
778                         const col_item_t *col_item = &cinfo->columns[col];
779
780                         if (col)
781                                 printf(",");
782
783                         json_puts_string(col_item->col_data);
784                 }
785                 printf("],\"num\":%u", framenum);
786
787                 if (fdata->flags.ignored)
788                         printf(",\"i\":true");
789
790                 if (fdata->flags.marked)
791                         printf(",\"m\":true");
792
793                 if (fdata->color_filter)
794                 {
795                         printf(",\"bg\":\"%x\"", color_t_to_rgb(&fdata->color_filter->bg_color));
796                         printf(",\"fg\":\"%x\"", color_t_to_rgb(&fdata->color_filter->fg_color));
797                 }
798
799                 printf("}");
800                 frame_sepa = ",";
801
802                 if (limit && --limit == 0)
803                         break;
804         }
805         printf("]\n");
806
807         if (cinfo != &cfile.cinfo)
808                 col_cleanup(cinfo);
809 }
810
811 static void
812 sharkd_session_process_tap_stats_node_cb(const stat_node *n)
813 {
814         stat_node *node;
815         const char *sepa = "";
816
817         printf("[");
818         for (node = n->children; node; node = node->next)
819         {
820                 /* code based on stats_tree_get_values_from_node() */
821                 printf("%s{\"name\":\"%s\"", sepa, node->name);
822                 printf(",\"count\":%d", node->counter);
823                 if (node->counter && ((node->st_flags & ST_FLG_AVERAGE) || node->rng))
824                 {
825                         printf(",\"avg\":%.2f", ((float)node->total) / node->counter);
826                         printf(",\"min\":%d", node->minvalue);
827                         printf(",\"max\":%d", node->maxvalue);
828                 }
829
830                 if (node->st->elapsed)
831                         printf(",\"rate\":%.4f",((float)node->counter) / node->st->elapsed);
832
833                 if (node->parent && node->parent->counter)
834                         printf(",\"perc\":%.2f", (node->counter * 100.0) / node->parent->counter);
835                 else if (node->parent == &(node->st->root))
836                         printf(",\"perc\":100");
837
838                 if (prefs.st_enable_burstinfo && node->max_burst)
839                 {
840                         if (prefs.st_burst_showcount)
841                                 printf(",\"burstcount\":%d", node->max_burst);
842                         else
843                                 printf(",\"burstrate\":%.4f", ((double)node->max_burst) / prefs.st_burst_windowlen);
844
845                         printf(",\"bursttime\":%.3f", ((double)node->burst_time / 1000.0));
846                 }
847
848                 if (node->children)
849                 {
850                         printf(",\"sub\":");
851                         sharkd_session_process_tap_stats_node_cb(node);
852                 }
853                 printf("}");
854                 sepa = ",";
855         }
856         printf("]");
857 }
858
859 /**
860  * sharkd_session_process_tap_stats_cb()
861  *
862  * Output stats tap:
863  *
864  *   (m) tap        - tap name
865  *   (m) type:stats - tap output type
866  *   (m) name       - stat name
867  *   (m) stats      - array of object with attributes:
868  *                  (m) name       - stat item name
869  *                  (m) count      - stat item counter
870  *                  (o) avg        - stat item averange value
871  *                  (o) min        - stat item min value
872  *                  (o) max        - stat item max value
873  *                  (o) rate       - stat item rate value (ms)
874  *                  (o) perc       - stat item percentage
875  *                  (o) burstrate  - stat item burst rate
876  *                  (o) burstcount - stat item burst count
877  *                  (o) burstttme  - stat item burst start
878  *                  (o) sub        - array of object with attributes like in stats node.
879  */
880 static void
881 sharkd_session_process_tap_stats_cb(void *psp)
882 {
883         stats_tree *st = (stats_tree *) psp;
884
885         printf("{\"tap\":\"stats:%s\",\"type\":\"stats\"", st->cfg->abbr);
886
887         printf(",\"name\":\"%s\",\"stats\":", st->cfg->name);
888         sharkd_session_process_tap_stats_node_cb(&st->root);
889         printf("},");
890 }
891
892 static void
893 sharkd_session_free_tap_stats_cb(void *psp)
894 {
895         stats_tree *st = (stats_tree *) psp;
896
897         stats_tree_free(st);
898 }
899
900 struct sharkd_expert_tap
901 {
902         GSList *details;
903         GStringChunk *text;
904 };
905
906 /**
907  * sharkd_session_process_tap_expert_cb()
908  *
909  * Output expert tap:
910  *
911  *   (m) tap         - tap name
912  *   (m) type:expert - tap output type
913  *   (m) details     - array of object with attributes:
914  *                  (m) f - frame number, which generated expert information
915  *                  (o) s - severity
916  *                  (o) g - group
917  *                  (m) m - expert message
918  *                  (o) p - protocol
919  */
920 static void
921 sharkd_session_process_tap_expert_cb(void *tapdata)
922 {
923         struct sharkd_expert_tap *etd = (struct sharkd_expert_tap *) tapdata;
924         GSList *list;
925         const char *sepa = "";
926
927         printf("{\"tap\":\"%s\",\"type\":\"%s\"", "expert", "expert");
928
929         printf(",\"details\":[");
930         for (list = etd->details; list; list = list->next)
931         {
932                 expert_info_t *ei = (expert_info_t *) list->data;
933                 const char *tmp;
934
935                 printf("%s{", sepa);
936
937                 printf("\"f\":%u,", ei->packet_num);
938
939                 tmp = try_val_to_str(ei->severity, expert_severity_vals);
940                 if (tmp)
941                         printf("\"s\":\"%s\",", tmp);
942
943                 tmp = try_val_to_str(ei->group, expert_group_vals);
944                 if (tmp)
945                         printf("\"g\":\"%s\",", tmp);
946
947                 printf("\"m\":");
948                 json_puts_string(ei->summary);
949                 printf(",");
950
951                 if (ei->protocol)
952                 {
953                         printf("\"p\":");
954                         json_puts_string(ei->protocol);
955                 }
956
957                 printf("}");
958                 sepa = ",";
959         }
960         printf("]");
961
962         printf("},");
963 }
964
965 static gboolean
966 sharkd_session_packet_tap_expert_cb(void *tapdata, packet_info *pinfo _U_, epan_dissect_t *edt _U_, const void *pointer)
967 {
968         struct sharkd_expert_tap *etd = (struct sharkd_expert_tap *) tapdata;
969         expert_info_t *ei             = (expert_info_t *) pointer;
970
971         ei = (expert_info_t *) g_memdup(ei, sizeof(*ei));
972         ei->protocol = g_string_chunk_insert_const(etd->text, ei->protocol);
973         ei->summary  = g_string_chunk_insert_const(etd->text, ei->summary);
974
975         etd->details = g_slist_prepend(etd->details, ei);
976
977         return TRUE;
978 }
979
980 static void
981 sharkd_session_free_tap_expert_cb(void *tapdata)
982 {
983         struct sharkd_expert_tap *etd = (struct sharkd_expert_tap *) tapdata;
984
985         g_slist_free_full(etd->details, g_free);
986         g_string_chunk_free(etd->text);
987         g_free(etd);
988 }
989
990 struct sharkd_conv_tap_data
991 {
992         const char *type;
993         conv_hash_t hash;
994         gboolean resolve_name;
995         gboolean resolve_port;
996 };
997
998 static int
999 sharkd_session_geoip_addr(address *addr, const char *suffix)
1000 {
1001         int with_geoip = 0;
1002
1003         (void) addr;
1004         (void) suffix;
1005
1006 #ifdef HAVE_GEOIP
1007         if (addr->type == AT_IPv4)
1008         {
1009                 guint32 ip = pntoh32(addr->data);
1010
1011                 guint num_dbs = geoip_db_num_dbs();
1012                 guint dbnum;
1013
1014                 for (dbnum = 0; dbnum < num_dbs; dbnum++)
1015                 {
1016                         const char *geoip_key = NULL;
1017                         char *geoip_val;
1018
1019                         int db_type = geoip_db_type(dbnum);
1020
1021                         switch (db_type)
1022                         {
1023                                 case GEOIP_COUNTRY_EDITION:
1024                                         geoip_key = "geoip_country";
1025                                         break;
1026
1027                                 case GEOIP_CITY_EDITION_REV0:
1028                                 case GEOIP_CITY_EDITION_REV1:
1029                                         geoip_key = "geoip_city";
1030                                         break;
1031
1032                                 case GEOIP_ORG_EDITION:
1033                                         geoip_key = "geoip_org";
1034                                         break;
1035
1036                                 case GEOIP_ISP_EDITION:
1037                                         geoip_key = "geoip_isp";
1038                                         break;
1039
1040                                 case GEOIP_ASNUM_EDITION:
1041                                         geoip_key = "geoip_as";
1042                                         break;
1043
1044                                 case WS_LAT_FAKE_EDITION:
1045                                         geoip_key = "geoip_lat";
1046                                         break;
1047
1048                                 case WS_LON_FAKE_EDITION:
1049                                         geoip_key = "geoip_lon";
1050                                         break;
1051                         }
1052
1053                         if (geoip_key && (geoip_val = geoip_db_lookup_ipv4(dbnum, ip, NULL)))
1054                         {
1055                                 printf(",\"%s%s\":", geoip_key, suffix);
1056                                 json_puts_string(geoip_val);
1057                                 with_geoip = 1;
1058                         }
1059                 }
1060         }
1061 #ifdef HAVE_GEOIP_V6
1062         if (addr->type == AT_IPv6)
1063         {
1064                 const struct e_in6_addr *ip6 = (const struct e_in6_addr *) addr->data;
1065
1066                 guint num_dbs = geoip_db_num_dbs();
1067                 guint dbnum;
1068
1069                 for (dbnum = 0; dbnum < num_dbs; dbnum++)
1070                 {
1071                         const char *geoip_key = NULL;
1072                         char *geoip_val;
1073
1074                         int db_type = geoip_db_type(dbnum);
1075
1076                         switch (db_type)
1077                         {
1078                                 case GEOIP_COUNTRY_EDITION_V6:
1079                                         geoip_key = "geoip_country";
1080                                         break;
1081 #if NUM_DB_TYPES > 31
1082                                 case GEOIP_CITY_EDITION_REV0_V6:
1083                                 case GEOIP_CITY_EDITION_REV1_V6:
1084                                         geoip_key = "geoip_city";
1085                                         break;
1086
1087                                 case GEOIP_ORG_EDITION_V6:
1088                                         geoip_key = "geoip_org";
1089                                         break;
1090
1091                                 case GEOIP_ISP_EDITION_V6:
1092                                         geoip_key = "geoip_isp";
1093                                         break;
1094
1095                                 case GEOIP_ASNUM_EDITION_V6:
1096                                         geoip_key = "geoip_as";
1097                                         break;
1098 #endif /* DB_NUM_TYPES */
1099                                 case WS_LAT_FAKE_EDITION:
1100                                         geoip_key = "geoip_lat";
1101                                         break;
1102
1103                                 case WS_LON_FAKE_EDITION:
1104                                         geoip_key = "geoip_lon";
1105                                         break;
1106                         }
1107
1108                         if (geoip_key && (geoip_val = geoip_db_lookup_ipv6(dbnum, *ip6, NULL)))
1109                         {
1110                                 printf(",\"%s%s\":", geoip_key, suffix);
1111                                 json_puts_string(geoip_val);
1112                                 with_geoip = 1;
1113                         }
1114                 }
1115         }
1116 #endif /* HAVE_GEOIP_V6 */
1117 #endif /* HAVE_GEOIP */
1118
1119         return with_geoip;
1120 }
1121
1122 struct sharkd_analyse_rtp_items
1123 {
1124         guint32 frame_num;
1125         guint32 sequence_num;
1126
1127         double delta;
1128         double jitter;
1129         double skew;
1130         double bandwidth;
1131         gboolean marker;
1132
1133         double arrive_offset;
1134
1135         /* from tap_rtp_stat_t */
1136         guint32 flags;
1137         guint16 pt;
1138 };
1139
1140 struct sharkd_analyse_rtp
1141 {
1142         const char *tap_name;
1143         struct sharkd_rtp_match rtp;
1144
1145         GSList *packets;
1146         double start_time;
1147         tap_rtp_stat_t statinfo;
1148 };
1149
1150 static void
1151 sharkd_session_process_tap_rtp_free_cb(void *tapdata)
1152 {
1153         struct sharkd_analyse_rtp *rtp_req = (struct sharkd_analyse_rtp *) tapdata;
1154
1155         g_slist_free_full(rtp_req->packets, g_free);
1156         g_free(rtp_req);
1157 }
1158
1159 static gboolean
1160 sharkd_session_packet_tap_rtp_analyse_cb(void *tapdata, packet_info *pinfo, epan_dissect_t *edt _U_, const void *pointer)
1161 {
1162         struct sharkd_analyse_rtp *rtp_req = (struct sharkd_analyse_rtp *) tapdata;
1163         const struct _rtp_info *rtpinfo = (const struct _rtp_info *) pointer;
1164
1165         if (sharkd_rtp_match_check(&rtp_req->rtp, pinfo, rtpinfo))
1166         {
1167                 tap_rtp_stat_t *statinfo = &(rtp_req->statinfo);
1168                 struct sharkd_analyse_rtp_items *item;
1169
1170                 rtp_packet_analyse(statinfo, pinfo, rtpinfo);
1171
1172                 item = (struct sharkd_analyse_rtp_items *) g_malloc(sizeof(struct sharkd_analyse_rtp_items));
1173
1174                 if (!rtp_req->packets)
1175                         rtp_req->start_time = nstime_to_sec(&pinfo->abs_ts);
1176
1177                 item->frame_num    = pinfo->num;
1178                 item->sequence_num = rtpinfo->info_seq_num;
1179                 item->delta        = (statinfo->flags & STAT_FLAG_FIRST) ? 0.0 : statinfo->delta;
1180                 item->jitter       = (statinfo->flags & STAT_FLAG_FIRST) ? 0.0 : statinfo->jitter;
1181                 item->skew         = (statinfo->flags & STAT_FLAG_FIRST) ? 0.0 : statinfo->skew;
1182                 item->bandwidth    = statinfo->bandwidth;
1183                 item->marker       = rtpinfo->info_marker_set ? TRUE : FALSE;
1184                 item->arrive_offset= nstime_to_sec(&pinfo->abs_ts) - rtp_req->start_time;
1185
1186                 item->flags = statinfo->flags;
1187                 item->pt    = statinfo->pt;
1188
1189                 /* XXX, O(n) optimize */
1190                 rtp_req->packets = g_slist_append(rtp_req->packets, item);
1191         }
1192
1193         return TRUE;
1194 }
1195
1196 /**
1197  * sharkd_session_process_tap_rtp_analyse_cb()
1198  *
1199  * Output rtp analyse tap:
1200  *   (m) tap   - tap name
1201  *   (m) type  - tap output type
1202  *   (m) ssrc         - RTP SSRC
1203  *   (m) max_delta    - Max delta (ms)
1204  *   (m) max_delta_nr - Max delta packet #
1205  *   (m) max_jitter   - Max jitter (ms)
1206  *   (m) mean_jitter  - Mean jitter (ms)
1207  *   (m) max_skew     - Max skew (ms)
1208  *   (m) total_nr     - Total number of RTP packets
1209  *   (m) seq_err      - Number of sequence errors
1210  *   (m) duration     - Duration (ms)
1211  *   (m) items      - array of object with attributes:
1212  *                  (m) f    - frame number
1213  *                  (m) o    - arrive offset
1214  *                  (m) sn   - sequence number
1215  *                  (m) d    - delta
1216  *                  (m) j    - jitter
1217  *                  (m) sk   - skew
1218  *                  (m) bw   - bandwidth
1219  *                  (o) s    - status string
1220  *                  (o) t    - status type
1221  *                  (o) mark - rtp mark
1222  */
1223 static void
1224 sharkd_session_process_tap_rtp_analyse_cb(void *tapdata)
1225 {
1226         const int RTP_TYPE_CN       = 1;
1227         const int RTP_TYPE_ERROR    = 2;
1228         const int RTP_TYPE_WARN     = 3;
1229         const int RTP_TYPE_PT_EVENT = 4;
1230
1231         const struct sharkd_analyse_rtp *rtp_req = (struct sharkd_analyse_rtp *) tapdata;
1232         const tap_rtp_stat_t *statinfo = &rtp_req->statinfo;
1233
1234         const char *sepa = "";
1235         GSList *l;
1236
1237         printf("{\"tap\":\"%s\",\"type\":\"rtp-analyse\"", rtp_req->tap_name);
1238
1239         printf(",\"ssrc\":%u", rtp_req->rtp.ssrc);
1240
1241         printf(",\"max_delta\":%f", statinfo->max_delta);
1242         printf(",\"max_delta_nr\":%u", statinfo->max_nr);
1243         printf(",\"max_jitter\":%f", statinfo->max_jitter);
1244         printf(",\"mean_jitter\":%f", statinfo->mean_jitter);
1245         printf(",\"max_skew\":%f", statinfo->max_skew);
1246         printf(",\"total_nr\":%u", statinfo->total_nr);
1247         printf(",\"seq_err\":%u", statinfo->sequence);
1248         printf(",\"duration\":%f", statinfo->time - statinfo->start_time);
1249
1250         printf(",\"items\":[");
1251         for (l = rtp_req->packets; l; l = l->next)
1252         {
1253                 struct sharkd_analyse_rtp_items *item = (struct sharkd_analyse_rtp_items *) l->data;
1254
1255                 printf("%s{", sepa);
1256
1257                 printf("\"f\":%u", item->frame_num);
1258                 printf(",\"o\":%.9f", item->arrive_offset);
1259                 printf(",\"sn\":%u", item->sequence_num);
1260                 printf(",\"d\":%.2f", item->delta);
1261                 printf(",\"j\":%.2f", item->jitter);
1262                 printf(",\"sk\":%.2f", item->skew);
1263                 printf(",\"bw\":%.2f", item->bandwidth);
1264
1265                 if (item->pt == PT_CN)
1266                         printf(",\"s\":\"%s\",\"t\":%d", "Comfort noise (PT=13, RFC 3389)", RTP_TYPE_CN);
1267                 else if (item->pt == PT_CN_OLD)
1268                         printf(",\"s\":\"%s\",\"t\":%d", "Comfort noise (PT=19, reserved)", RTP_TYPE_CN);
1269                 else if (item->flags & STAT_FLAG_WRONG_SEQ)
1270                         printf(",\"s\":\"%s\",\"t\":%d", "Wrong sequence number", RTP_TYPE_ERROR);
1271                 else if (item->flags & STAT_FLAG_DUP_PKT)
1272                         printf(",\"s\":\"%s\",\"t\":%d", "Suspected duplicate (MAC address) only delta time calculated", RTP_TYPE_WARN);
1273                 else if (item->flags & STAT_FLAG_REG_PT_CHANGE)
1274                         printf(",\"s\":\"Payload changed to PT=%u%s\",\"t\":%d",
1275                                 item->pt,
1276                                 (item->flags & STAT_FLAG_PT_T_EVENT) ? " telephone/event" : "",
1277                                 RTP_TYPE_WARN);
1278                 else if (item->flags & STAT_FLAG_WRONG_TIMESTAMP)
1279                         printf(",\"s\":\"%s\",\"t\":%d", "Incorrect timestamp", RTP_TYPE_WARN);
1280                 else if ((item->flags & STAT_FLAG_PT_CHANGE)
1281                         &&  !(item->flags & STAT_FLAG_FIRST)
1282                         &&  !(item->flags & STAT_FLAG_PT_CN)
1283                         &&  (item->flags & STAT_FLAG_FOLLOW_PT_CN)
1284                         &&  !(item->flags & STAT_FLAG_MARKER))
1285                 {
1286                         printf(",\"s\":\"%s\",\"t\":%d", "Marker missing?", RTP_TYPE_WARN);
1287                 }
1288                 else if (item->flags & STAT_FLAG_PT_T_EVENT)
1289                         printf(",\"s\":\"PT=%u telephone/event\",\"t\":%d", item->pt, RTP_TYPE_PT_EVENT);
1290                 else if (item->flags & STAT_FLAG_MARKER)
1291                         printf(",\"t\":%d", RTP_TYPE_WARN);
1292
1293                 if (item->marker)
1294                         printf(",\"mark\":1");
1295
1296                 printf("}");
1297                 sepa = ",";
1298         }
1299         printf("]");
1300
1301         printf("},");
1302 }
1303
1304 /**
1305  * sharkd_session_process_tap_conv_cb()
1306  *
1307  * Output conv tap:
1308  *   (m) tap        - tap name
1309  *   (m) type       - tap output type
1310  *   (m) proto      - protocol short name
1311  *   (o) filter     - filter string
1312  *
1313  *   (o) convs      - array of object with attributes:
1314  *                  (m) saddr - source address
1315  *                  (m) daddr - destination address
1316  *                  (o) sport - source port
1317  *                  (o) dport - destination port
1318  *                  (m) txf   - TX frame count
1319  *                  (m) txb   - TX bytes
1320  *                  (m) rxf   - RX frame count
1321  *                  (m) rxb   - RX bytes
1322  *                  (m) start - (relative) first packet time
1323  *                  (m) stop  - (relative) last packet time
1324  *
1325  *   (o) hosts      - array of object with attributes:
1326  *                  (m) host - host address
1327  *                  (o) port - host port
1328  *                  (m) txf  - TX frame count
1329  *                  (m) txb  - TX bytes
1330  *                  (m) rxf  - RX frame count
1331  *                  (m) rxb  - RX bytes
1332  */
1333 static void
1334 sharkd_session_process_tap_conv_cb(void *arg)
1335 {
1336         conv_hash_t *hash = (conv_hash_t *) arg;
1337         const struct sharkd_conv_tap_data *iu = (struct sharkd_conv_tap_data *) hash->user_data;
1338         const char *proto;
1339         int proto_with_port;
1340         guint i;
1341
1342         int with_geoip = 0;
1343
1344         if (!strncmp(iu->type, "conv:", 5))
1345         {
1346                 printf("{\"tap\":\"%s\",\"type\":\"conv\"", iu->type);
1347                 printf(",\"convs\":[");
1348                 proto = iu->type + 5;
1349         }
1350         else if (!strncmp(iu->type, "endpt:", 6))
1351         {
1352                 printf("{\"tap\":\"%s\",\"type\":\"host\"", iu->type);
1353                 printf(",\"hosts\":[");
1354                 proto = iu->type + 6;
1355         }
1356         else
1357         {
1358                 printf("{\"tap\":\"%s\",\"type\":\"err\"", iu->type);
1359                 proto = "";
1360         }
1361
1362         proto_with_port = (!strcmp(proto, "TCP") || !strcmp(proto, "UDP") || !strcmp(proto, "SCTP"));
1363
1364         if (iu->hash.conv_array != NULL && !strncmp(iu->type, "conv:", 5))
1365         {
1366                 for (i = 0; i < iu->hash.conv_array->len; i++)
1367                 {
1368                         conv_item_t *iui = &g_array_index(iu->hash.conv_array, conv_item_t, i);
1369                         char *src_addr, *dst_addr;
1370                         char *src_port, *dst_port;
1371                         char *filter_str;
1372
1373                         printf("%s{", i ? "," : "");
1374
1375                         printf("\"saddr\":\"%s\"",  (src_addr = get_conversation_address(NULL, &iui->src_address, iu->resolve_name)));
1376                         printf(",\"daddr\":\"%s\"", (dst_addr = get_conversation_address(NULL, &iui->dst_address, iu->resolve_name)));
1377
1378                         if (proto_with_port)
1379                         {
1380                                 printf(",\"sport\":\"%s\"", (src_port = get_conversation_port(NULL, iui->src_port, iui->ptype, iu->resolve_port)));
1381                                 printf(",\"dport\":\"%s\"", (dst_port = get_conversation_port(NULL, iui->dst_port, iui->ptype, iu->resolve_port)));
1382
1383                                 wmem_free(NULL, src_port);
1384                                 wmem_free(NULL, dst_port);
1385                         }
1386
1387                         printf(",\"rxf\":%" G_GUINT64_FORMAT, iui->rx_frames);
1388                         printf(",\"rxb\":%" G_GUINT64_FORMAT, iui->rx_bytes);
1389
1390                         printf(",\"txf\":%" G_GUINT64_FORMAT, iui->tx_frames);
1391                         printf(",\"txb\":%" G_GUINT64_FORMAT, iui->tx_bytes);
1392
1393                         printf(",\"start\":%.9f", nstime_to_sec(&iui->start_time));
1394                         printf(",\"stop\":%.9f", nstime_to_sec(&iui->stop_time));
1395
1396                         filter_str = get_conversation_filter(iui, CONV_DIR_A_TO_FROM_B);
1397                         if (filter_str)
1398                         {
1399                                 printf(",\"filter\":\"%s\"", filter_str);
1400                                 g_free(filter_str);
1401                         }
1402
1403                         wmem_free(NULL, src_addr);
1404                         wmem_free(NULL, dst_addr);
1405
1406                         if (sharkd_session_geoip_addr(&(iui->src_address), "1"))
1407                                 with_geoip = 1;
1408                         if (sharkd_session_geoip_addr(&(iui->dst_address), "2"))
1409                                 with_geoip = 1;
1410
1411                         printf("}");
1412                 }
1413         }
1414         else if (iu->hash.conv_array != NULL && !strncmp(iu->type, "endpt:", 6))
1415         {
1416                 for (i = 0; i < iu->hash.conv_array->len; i++)
1417                 {
1418                         hostlist_talker_t *host = &g_array_index(iu->hash.conv_array, hostlist_talker_t, i);
1419                         char *host_str, *port_str;
1420                         char *filter_str;
1421
1422                         printf("%s{", i ? "," : "");
1423
1424                         printf("\"host\":\"%s\"", (host_str = get_conversation_address(NULL, &host->myaddress, iu->resolve_name)));
1425
1426                         if (proto_with_port)
1427                         {
1428                                 printf(",\"port\":\"%s\"", (port_str = get_conversation_port(NULL, host->port, host->ptype, iu->resolve_port)));
1429
1430                                 wmem_free(NULL, port_str);
1431                         }
1432
1433                         printf(",\"rxf\":%" G_GUINT64_FORMAT, host->rx_frames);
1434                         printf(",\"rxb\":%" G_GUINT64_FORMAT, host->rx_bytes);
1435
1436                         printf(",\"txf\":%" G_GUINT64_FORMAT, host->tx_frames);
1437                         printf(",\"txb\":%" G_GUINT64_FORMAT, host->tx_bytes);
1438
1439                         filter_str = get_hostlist_filter(host);
1440                         if (filter_str)
1441                         {
1442                                 printf(",\"filter\":\"%s\"", filter_str);
1443                                 g_free(filter_str);
1444                         }
1445
1446                         wmem_free(NULL, host_str);
1447
1448                         if (sharkd_session_geoip_addr(&(host->myaddress), ""))
1449                                 with_geoip = 1;
1450                         printf("}");
1451                 }
1452         }
1453
1454         printf("],\"proto\":\"%s\",\"geoip\":%s},", proto, with_geoip ? "true" : "false");
1455 }
1456
1457 static void
1458 sharkd_session_free_tap_conv_cb(void *arg)
1459 {
1460         conv_hash_t *hash = (conv_hash_t *) arg;
1461         struct sharkd_conv_tap_data *iu = (struct sharkd_conv_tap_data *) hash->user_data;
1462
1463         if (!strncmp(iu->type, "conv:", 5))
1464         {
1465                 reset_conversation_table_data(hash);
1466         }
1467         else if (!strncmp(iu->type, "endpt:", 6))
1468         {
1469                 reset_hostlist_table_data(hash);
1470         }
1471
1472         g_free(iu);
1473 }
1474
1475 /**
1476  * sharkd_session_process_tap_nstat_cb()
1477  *
1478  * Output nstat tap:
1479  *   (m) tap        - tap name
1480  *   (m) type       - tap output type
1481  *   (m) fields: array of objects with attributes:
1482  *                  (m) c - name
1483  *
1484  *   (m) tables: array of object with attributes:
1485  *                  (m) t - table title
1486  *                  (m) i - array of items
1487  */
1488 static void
1489 sharkd_session_process_tap_nstat_cb(void *arg)
1490 {
1491         new_stat_data_t *stat_data = (new_stat_data_t *) arg;
1492         guint i, j, k;
1493
1494         printf("{\"tap\":\"nstat:%s\",\"type\":\"nstat\"", stat_data->stat_tap_data->cli_string);
1495
1496         printf(",\"fields\":[");
1497         for (i = 0; i < stat_data->stat_tap_data->nfields; i++)
1498         {
1499                 stat_tap_table_item *field = &(stat_data->stat_tap_data->fields[i]);
1500
1501                 if (i)
1502                         printf(",");
1503
1504                 printf("{");
1505
1506                 printf("\"c\":");
1507                 json_puts_string(field->column_name);
1508
1509                 printf("}");
1510         }
1511         printf("]");
1512
1513         printf(",\"tables\":[");
1514         for (i = 0; i < stat_data->stat_tap_data->tables->len; i++)
1515         {
1516                 stat_tap_table *table = g_array_index(stat_data->stat_tap_data->tables, stat_tap_table *, i);
1517                 const char *sepa = "";
1518
1519                 if (i)
1520                         printf(",");
1521
1522                 printf("{");
1523
1524                 printf("\"t\":");
1525                 printf("\"%s\"", table->title);
1526
1527                 printf(",\"i\":[");
1528                 for (j = 0; j < table->num_elements; j++)
1529                 {
1530                         stat_tap_table_item_type *field_data;
1531
1532                         field_data = new_stat_tap_get_field_data(table, j, 0);
1533                         if (field_data == NULL || field_data->type == TABLE_ITEM_NONE) /* Nothing for us here */
1534                                 continue;
1535
1536                         printf("%s[", sepa);
1537                         for (k = 0; k < table->num_fields; k++)
1538                         {
1539                                 field_data = new_stat_tap_get_field_data(table, j, k);
1540
1541                                 if (k)
1542                                         printf(",");
1543
1544                                 switch (field_data->type)
1545                                 {
1546                                         case TABLE_ITEM_UINT:
1547                                                 printf("%u", field_data->value.uint_value);
1548                                                 break;
1549
1550                                         case TABLE_ITEM_INT:
1551                                                 printf("%d", field_data->value.uint_value);
1552                                                 break;
1553
1554                                         case TABLE_ITEM_STRING:
1555                                                 json_puts_string(field_data->value.string_value);
1556                                                 break;
1557
1558                                         case TABLE_ITEM_FLOAT:
1559                                                 printf("%f", field_data->value.float_value);
1560                                                 break;
1561
1562                                         case TABLE_ITEM_ENUM:
1563                                                 printf("%d", field_data->value.enum_value);
1564                                                 break;
1565
1566                                         case TABLE_ITEM_NONE:
1567                                                 printf("null");
1568                                                 break;
1569                                 }
1570                         }
1571
1572                         printf("]");
1573                         sepa = ",";
1574                 }
1575                 printf("]");
1576                 printf("}");
1577         }
1578
1579         printf("]},");
1580 }
1581
1582 static void
1583 sharkd_session_free_tap_nstat_cb(void *arg)
1584 {
1585         new_stat_data_t *stat_data = (new_stat_data_t *) arg;
1586
1587         free_stat_tables(stat_data->stat_tap_data, NULL, NULL);
1588 }
1589
1590 /**
1591  * sharkd_session_process_tap_rtd_cb()
1592  *
1593  * Output rtd tap:
1594  *   (m) tap        - tap name
1595  *   (m) type       - tap output type
1596  *   (m) stats - statistics rows - array object with attributes:
1597  *                  (m) type - statistic name
1598  *                  (m) num - number of messages
1599  *                  (m) min - minimum SRT time
1600  *                  (m) max - maximum SRT time
1601  *                  (m) tot - total SRT time
1602  *                  (m) min_frame - minimal SRT
1603  *                  (m) max_frame - maximum SRT
1604  *                  (o) open_req - Open Requests
1605  *                  (o) disc_rsp - Discarded Responses
1606  *                  (o) req_dup  - Duplicated Requests
1607  *                  (o) rsp_dup  - Duplicated Responses
1608  *   (o) open_req   - Open Requests
1609  *   (o) disc_rsp   - Discarded Responses
1610  *   (o) req_dup    - Duplicated Requests
1611  *   (o) rsp_dup    - Duplicated Responses
1612  */
1613 static void
1614 sharkd_session_process_tap_rtd_cb(void *arg)
1615 {
1616         rtd_data_t *rtd_data = (rtd_data_t *) arg;
1617         register_rtd_t *rtd  = (register_rtd_t *) rtd_data->user_data;
1618
1619         guint i, j;
1620
1621         const char *filter = proto_get_protocol_filter_name(get_rtd_proto_id(rtd));
1622
1623         /* XXX, some dissectors are having single table and multiple timestats (mgcp, megaco),
1624          *      some multiple table and single timestat (radius, h225)
1625          *      and it seems that value_string is used one for timestamp-ID, other one for table-ID
1626          *      I wonder how it will gonna work with multiple timestats and multiple timestat...
1627          * (for usage grep for: register_rtd_table)
1628          */
1629         const value_string *vs = get_rtd_value_string(rtd);
1630         const char *sepa = "";
1631
1632         printf("{\"tap\":\"rtd:%s\",\"type\":\"rtd\"", filter);
1633
1634         if (rtd_data->stat_table.num_rtds == 1)
1635         {
1636                 const rtd_timestat *ms = &rtd_data->stat_table.time_stats[0];
1637
1638                 printf(",\"open_req\":%u", ms->open_req_num);
1639                 printf(",\"disc_rsp\":%u", ms->disc_rsp_num);
1640                 printf(",\"req_dup\":%u", ms->req_dup_num);
1641                 printf(",\"rsp_dup\":%u", ms->rsp_dup_num);
1642         }
1643
1644         printf(",\"stats\":[");
1645         for (i = 0; i < rtd_data->stat_table.num_rtds; i++)
1646         {
1647                 const rtd_timestat *ms = &rtd_data->stat_table.time_stats[i];
1648
1649                 for (j = 0; j < ms->num_timestat; j++)
1650                 {
1651                         const char *type_str;
1652
1653                         if (ms->rtd[j].num == 0)
1654                                 continue;
1655
1656                         printf("%s{", sepa);
1657
1658                         if (rtd_data->stat_table.num_rtds == 1)
1659                                 type_str = val_to_str_const(j, vs, "Other"); /* 1 table - description per row */
1660                         else
1661                                 type_str = val_to_str_const(i, vs, "Other"); /* multiple table - description per table */
1662                         printf("\"type\":");
1663                         json_puts_string(type_str);
1664
1665                         printf(",\"num\":%u", ms->rtd[j].num);
1666                         printf(",\"min\":%.9f", nstime_to_sec(&(ms->rtd[j].min)));
1667                         printf(",\"max\":%.9f", nstime_to_sec(&(ms->rtd[j].max)));
1668                         printf(",\"tot\":%.9f", nstime_to_sec(&(ms->rtd[j].tot)));
1669                         printf(",\"min_frame\":%u", ms->rtd[j].min_num);
1670                         printf(",\"max_frame\":%u", ms->rtd[j].max_num);
1671
1672                         if (rtd_data->stat_table.num_rtds != 1)
1673                         {
1674                                 /* like in tshark, display it on every row */
1675                                 printf(",\"open_req\":%u", ms->open_req_num);
1676                                 printf(",\"disc_rsp\":%u", ms->disc_rsp_num);
1677                                 printf(",\"req_dup\":%u", ms->req_dup_num);
1678                                 printf(",\"rsp_dup\":%u", ms->rsp_dup_num);
1679                         }
1680
1681                         printf("}");
1682                         sepa = ",";
1683                 }
1684         }
1685         printf("]},");
1686 }
1687
1688 static void
1689 sharkd_session_free_tap_rtd_cb(void *arg)
1690 {
1691         rtd_data_t *rtd_data = (rtd_data_t *) arg;
1692
1693         free_rtd_table(&rtd_data->stat_table, NULL, NULL);
1694         g_free(rtd_data);
1695 }
1696
1697 /**
1698  * sharkd_session_process_tap_srt_cb()
1699  *
1700  * Output srt tap:
1701  *   (m) tap        - tap name
1702  *   (m) type       - tap output type
1703  *
1704  *   (m) tables - array of object with attributes:
1705  *                  (m) n - table name
1706  *                  (m) f - table filter
1707  *                  (o) c - table column name
1708  *                  (m) r - table rows - array object with attributes:
1709  *                            (m) n   - row name
1710  *                            (m) idx - procedure index
1711  *                            (m) num - number of events
1712  *                            (m) min - minimum SRT time
1713  *                            (m) max - maximum SRT time
1714  *                            (m) tot - total SRT time
1715  */
1716 static void
1717 sharkd_session_process_tap_srt_cb(void *arg)
1718 {
1719         srt_data_t *srt_data = (srt_data_t *) arg;
1720         register_srt_t *srt = (register_srt_t *) srt_data->user_data;
1721
1722         const char *filter = proto_get_protocol_filter_name(get_srt_proto_id(srt));
1723
1724         guint i;
1725
1726         printf("{\"tap\":\"srt:%s\",\"type\":\"srt\"", filter);
1727
1728         printf(",\"tables\":[");
1729         for (i = 0; i < srt_data->srt_array->len; i++)
1730         {
1731                 /* SRT table */
1732                 srt_stat_table *rst = g_array_index(srt_data->srt_array, srt_stat_table *, i);
1733                 const char *sepa = "";
1734
1735                 int j;
1736
1737                 if (i)
1738                         printf(",");
1739                 printf("{");
1740
1741                 printf("\"n\":");
1742                 if (rst->name)
1743                         json_puts_string(rst->name);
1744                 else if (rst->short_name)
1745                         json_puts_string(rst->short_name);
1746                 else
1747                         printf("\"table%u\"", i);
1748
1749                 if (rst->filter_string)
1750                 {
1751                         printf(",\"f\":");
1752                         json_puts_string(rst->filter_string);
1753                 }
1754
1755                 if (rst->proc_column_name)
1756                 {
1757                         printf(",\"c\":");
1758                         json_puts_string(rst->proc_column_name);
1759                 }
1760
1761                 printf(",\"r\":[");
1762                 for (j = 0; j < rst->num_procs; j++)
1763                 {
1764                         /* SRT row */
1765                         srt_procedure_t *proc = &rst->procedures[j];
1766
1767                         if (proc->stats.num == 0)
1768                                 continue;
1769
1770                         printf("%s{", sepa);
1771
1772                         printf("\"n\":");
1773                         json_puts_string(proc->procedure);
1774
1775                         if (rst->filter_string)
1776                                 printf(",\"idx\":%d", proc->proc_index);
1777
1778                         printf(",\"num\":%u", proc->stats.num);
1779
1780                         printf(",\"min\":%.9f", nstime_to_sec(&proc->stats.min));
1781                         printf(",\"max\":%.9f", nstime_to_sec(&proc->stats.max));
1782                         printf(",\"tot\":%.9f", nstime_to_sec(&proc->stats.tot));
1783
1784                         printf("}");
1785                         sepa = ",";
1786                 }
1787                 printf("]}");
1788         }
1789
1790         printf("]},");
1791 }
1792
1793 static void
1794 sharkd_session_free_tap_srt_cb(void *arg)
1795 {
1796         srt_data_t *srt_data = (srt_data_t *) arg;
1797         register_srt_t *srt = (register_srt_t *) srt_data->user_data;
1798
1799         free_srt_table(srt, srt_data->srt_array, NULL, NULL);
1800         g_array_free(srt_data->srt_array, TRUE);
1801         g_free(srt_data);
1802 }
1803
1804 struct sharkd_export_object_list
1805 {
1806         struct sharkd_export_object_list *next;
1807
1808         char *type;
1809         const char *proto;
1810         GSList *entries;
1811 };
1812
1813 static struct sharkd_export_object_list *sharkd_eo_list;
1814
1815 /**
1816  * sharkd_session_process_tap_eo_cb()
1817  *
1818  * Output eo tap:
1819  *   (m) tap        - tap name
1820  *   (m) type       - tap output type
1821  *   (m) proto      - protocol short name
1822  *   (m) objects    - array of object with attributes:
1823  *                  (m) pkt - packet number
1824  *                  (o) hostname - hostname
1825  *                  (o) type - content type
1826  *                  (o) filename - filename
1827  *                  (m) len - object length
1828  */
1829 static void
1830 sharkd_session_process_tap_eo_cb(void *tapdata)
1831 {
1832         export_object_list_t *tap_object = (export_object_list_t *) tapdata;
1833         struct sharkd_export_object_list *object_list = (struct sharkd_export_object_list*) tap_object->gui_data;
1834         GSList *slist;
1835         int i = 0;
1836
1837         printf("{\"tap\":\"%s\",\"type\":\"eo\"", object_list->type);
1838         printf(",\"proto\":\"%s\"", object_list->proto);
1839         printf(",\"objects\":[");
1840
1841         for (slist = object_list->entries; slist; slist = slist->next)
1842         {
1843                 const export_object_entry_t *eo_entry = (export_object_entry_t *) slist->data;
1844
1845                 printf("%s{", i ? "," : "");
1846
1847                 printf("\"pkt\":%u", eo_entry->pkt_num);
1848
1849                 if (eo_entry->hostname)
1850                 {
1851                         printf(",\"hostname\":");
1852                         json_puts_string(eo_entry->hostname);
1853                 }
1854
1855                 if (eo_entry->content_type)
1856                 {
1857                         printf(",\"type\":");
1858                         json_puts_string(eo_entry->content_type);
1859                 }
1860
1861                 if (eo_entry->filename)
1862                 {
1863                         printf(",\"filename\":");
1864                         json_puts_string(eo_entry->filename);
1865                 }
1866
1867                 printf(",\"_download\":\"%s_%d\"", object_list->type, i);
1868
1869                 printf(",\"len\":%" G_GINT64_FORMAT, eo_entry->payload_len);
1870
1871                 printf("}");
1872
1873                 i++;
1874         }
1875
1876         printf("]},");
1877 }
1878
1879 static void
1880 sharkd_eo_object_list_add_entry(void *gui_data, export_object_entry_t *entry)
1881 {
1882         struct sharkd_export_object_list *object_list = (struct sharkd_export_object_list *) gui_data;
1883
1884         object_list->entries = g_slist_append(object_list->entries, entry);
1885 }
1886
1887 static export_object_entry_t *
1888 sharkd_eo_object_list_get_entry(void *gui_data, int row)
1889 {
1890         struct sharkd_export_object_list *object_list = (struct sharkd_export_object_list *) gui_data;
1891
1892         return (export_object_entry_t *) g_slist_nth_data(object_list->entries, row);
1893 }
1894
1895 /**
1896  * sharkd_session_process_tap_rtp_cb()
1897  *
1898  * Output RTP streams tap:
1899  *   (m) tap        - tap name
1900  *   (m) type       - tap output type
1901  *   (m) streams    - array of object with attributes:
1902  *                  (m) ssrc        - RTP synchronization source identifier
1903  *                  (m) payload     - stream payload
1904  *                  (m) saddr       - source address
1905  *                  (m) sport       - source port
1906  *                  (m) daddr       - destination address
1907  *                  (m) dport       - destination port
1908  *                  (m) pkts        - packets count
1909  *                  (m) max_delta   - max delta (ms)
1910  *                  (m) max_jitter  - max jitter (ms)
1911  *                  (m) mean_jitter - mean jitter (ms)
1912  *                  (m) expectednr  -
1913  *                  (m) totalnr     -
1914  *                  (m) problem     - if analyser found the problem
1915  *                  (m) ipver       - address IP version (4 or 6)
1916  */
1917 static void
1918 sharkd_session_process_tap_rtp_cb(void *arg)
1919 {
1920         rtpstream_tapinfo_t *rtp_tapinfo = (rtpstream_tapinfo_t *) arg;
1921
1922         GList *listx;
1923         const char *sepa = "";
1924
1925         printf("{\"tap\":\"%s\",\"type\":\"%s\"", "rtp-streams", "rtp-streams");
1926
1927         printf(",\"streams\":[");
1928         for (listx = g_list_first(rtp_tapinfo->strinfo_list); listx; listx = listx->next)
1929         {
1930                 rtp_stream_info_t *streaminfo = (rtp_stream_info_t *) listx->data;
1931
1932                 char *src_addr, *dst_addr;
1933                 char *payload;
1934                 guint32 expected;
1935
1936                 src_addr = address_to_display(NULL, &(streaminfo->src_addr));
1937                 dst_addr = address_to_display(NULL, &(streaminfo->dest_addr));
1938
1939                 if (streaminfo->payload_type_name != NULL)
1940                         payload = wmem_strdup(NULL, streaminfo->payload_type_name);
1941                 else
1942                         payload = val_to_str_ext_wmem(NULL, streaminfo->payload_type, &rtp_payload_type_short_vals_ext, "Unknown (%u)");
1943
1944                 printf("%s{\"ssrc\":%u", sepa, streaminfo->ssrc);
1945                 printf(",\"payload\":\"%s\"", payload);
1946
1947                 printf(",\"saddr\":\"%s\"", src_addr);
1948                 printf(",\"sport\":%u", streaminfo->src_port);
1949
1950                 printf(",\"daddr\":\"%s\"", dst_addr);
1951                 printf(",\"dport\":%u", streaminfo->dest_port);
1952
1953                 printf(",\"pkts\":%u", streaminfo->packet_count);
1954
1955                 printf(",\"max_delta\":%f", streaminfo->rtp_stats.max_delta);
1956                 printf(",\"max_jitter\":%f", streaminfo->rtp_stats.max_jitter);
1957                 printf(",\"mean_jitter\":%f", streaminfo->rtp_stats.mean_jitter);
1958
1959                 expected = (streaminfo->rtp_stats.stop_seq_nr + streaminfo->rtp_stats.cycles * 65536) - streaminfo->rtp_stats.start_seq_nr + 1;
1960                 printf(",\"expectednr\":%u", expected);
1961                 printf(",\"totalnr\":%u", streaminfo->rtp_stats.total_nr);
1962
1963                 printf(",\"problem\":%s", streaminfo->problem ? "true" : "false");
1964
1965                 /* for filter */
1966                 printf(",\"ipver\":%d", (streaminfo->src_addr.type == AT_IPv6) ? 6 : 4);
1967
1968                 wmem_free(NULL, src_addr);
1969                 wmem_free(NULL, dst_addr);
1970                 wmem_free(NULL, payload);
1971
1972                 printf("}");
1973                 sepa = ",";
1974         }
1975         printf("]},");
1976 }
1977
1978 /**
1979  * sharkd_session_process_tap()
1980  *
1981  * Process tap request
1982  *
1983  * Input:
1984  *   (m) tap0         - First tap request
1985  *   (o) tap1...tap15 - Other tap requests
1986  *
1987  * Output object with attributes:
1988  *   (m) taps  - array of object with attributes:
1989  *                  (m) tap  - tap name
1990  *                  (m) type - tap output type
1991  *                  ...
1992  *                  for type:stats see sharkd_session_process_tap_stats_cb()
1993  *                  for type:nstat see sharkd_session_process_tap_nstat_cb()
1994  *                  for type:conv see sharkd_session_process_tap_conv_cb()
1995  *                  for type:host see sharkd_session_process_tap_conv_cb()
1996  *                  for type:rtp-streams see sharkd_session_process_tap_rtp_cb()
1997  *                  for type:rtp-analyse see sharkd_session_process_tap_rtp_analyse_cb()
1998  *                  for type:eo see sharkd_session_process_tap_eo_cb()
1999  *                  for type:expert see sharkd_session_process_tap_expert_cb()
2000  *                  for type:rtd see sharkd_session_process_tap_rtd_cb()
2001  *                  for type:srt see sharkd_session_process_tap_srt_cb()
2002  *
2003  *   (m) err   - error code
2004  */
2005 static void
2006 sharkd_session_process_tap(char *buf, const jsmntok_t *tokens, int count)
2007 {
2008         void *taps_data[16];
2009         GFreeFunc taps_free[16];
2010         int taps_count = 0;
2011         int i;
2012
2013         rtpstream_tapinfo_t rtp_tapinfo =
2014                 {NULL, NULL, NULL, NULL, 0, NULL, 0, TAP_ANALYSE, NULL, NULL, NULL, FALSE};
2015
2016         for (i = 0; i < 16; i++)
2017         {
2018                 char tapbuf[32];
2019                 const char *tok_tap;
2020
2021                 void *tap_data = NULL;
2022                 GFreeFunc tap_free = NULL;
2023                 const char *tap_filter = "";
2024                 GString *tap_error = NULL;
2025
2026                 ws_snprintf(tapbuf, sizeof(tapbuf), "tap%d", i);
2027                 tok_tap = json_find_attr(buf, tokens, count, tapbuf);
2028                 if (!tok_tap)
2029                         break;
2030
2031                 if (!strncmp(tok_tap, "stat:", 5))
2032                 {
2033                         stats_tree_cfg *cfg = stats_tree_get_cfg_by_abbr(tok_tap + 5);
2034                         stats_tree *st;
2035
2036                         if (!cfg)
2037                         {
2038                                 fprintf(stderr, "sharkd_session_process_tap() stat %s not found\n", tok_tap + 5);
2039                                 continue;
2040                         }
2041
2042                         st = stats_tree_new(cfg, NULL, tap_filter);
2043
2044                         tap_error = register_tap_listener(st->cfg->tapname, st, st->filter, st->cfg->flags, stats_tree_reset, stats_tree_packet, sharkd_session_process_tap_stats_cb);
2045
2046                         if (!tap_error && cfg->init)
2047                                 cfg->init(st);
2048
2049                         tap_data = st;
2050                         tap_free = sharkd_session_free_tap_stats_cb;
2051                 }
2052                 else if (!strcmp(tok_tap, "expert"))
2053                 {
2054                         struct sharkd_expert_tap *expert_tap;
2055
2056                         expert_tap = g_new0(struct sharkd_expert_tap, 1);
2057                         expert_tap->text = g_string_chunk_new(100);
2058
2059                         tap_error = register_tap_listener("expert", expert_tap, NULL, 0, NULL, sharkd_session_packet_tap_expert_cb, sharkd_session_process_tap_expert_cb);
2060
2061                         tap_data = expert_tap;
2062                         tap_free = sharkd_session_free_tap_expert_cb;
2063                 }
2064                 else if (!strncmp(tok_tap, "conv:", 5) || !strncmp(tok_tap, "endpt:", 6))
2065                 {
2066                         struct register_ct *ct = NULL;
2067                         const char *ct_tapname;
2068                         struct sharkd_conv_tap_data *ct_data;
2069                         tap_packet_cb tap_func = NULL;
2070
2071                         if (!strncmp(tok_tap, "conv:", 5))
2072                         {
2073                                 ct = get_conversation_by_proto_id(proto_get_id_by_short_name(tok_tap + 5));
2074
2075                                 if (!ct || !(tap_func = get_conversation_packet_func(ct)))
2076                                 {
2077                                         fprintf(stderr, "sharkd_session_process_tap() conv %s not found\n", tok_tap + 5);
2078                                         continue;
2079                                 }
2080                         }
2081                         else if (!strncmp(tok_tap, "endpt:", 6))
2082                         {
2083                                 ct = get_conversation_by_proto_id(proto_get_id_by_short_name(tok_tap + 6));
2084
2085                                 if (!ct || !(tap_func = get_hostlist_packet_func(ct)))
2086                                 {
2087                                         fprintf(stderr, "sharkd_session_process_tap() endpt %s not found\n", tok_tap + 6);
2088                                         continue;
2089                                 }
2090                         }
2091                         else
2092                         {
2093                                 fprintf(stderr, "sharkd_session_process_tap() conv/endpt(?): %s not found\n", tok_tap);
2094                                 continue;
2095                         }
2096
2097                         ct_tapname = proto_get_protocol_filter_name(get_conversation_proto_id(ct));
2098
2099                         ct_data = (struct sharkd_conv_tap_data *) g_malloc0(sizeof(struct sharkd_conv_tap_data));
2100                         ct_data->type = tok_tap;
2101                         ct_data->hash.user_data = ct_data;
2102
2103                         /* XXX: make configurable */
2104                         ct_data->resolve_name = TRUE;
2105                         ct_data->resolve_port = TRUE;
2106
2107                         tap_error = register_tap_listener(ct_tapname, &ct_data->hash, tap_filter, 0, NULL, tap_func, sharkd_session_process_tap_conv_cb);
2108
2109                         tap_data = &ct_data->hash;
2110                         tap_free = sharkd_session_free_tap_conv_cb;
2111                 }
2112                 else if (!strncmp(tok_tap, "nstat:", 6))
2113                 {
2114                         stat_tap_table_ui *stat = new_stat_tap_by_name(tok_tap + 6);
2115                         new_stat_data_t *stat_data;
2116
2117                         if (!stat)
2118                         {
2119                                 fprintf(stderr, "sharkd_session_process_tap() nstat=%s not found\n", tok_tap + 6);
2120                                 continue;
2121                         }
2122
2123                         stat->stat_tap_init_cb(stat, NULL, NULL);
2124
2125                         stat_data = g_new0(new_stat_data_t, 1);
2126                         stat_data->stat_tap_data = stat;
2127                         stat_data->user_data = NULL;
2128
2129                         tap_error = register_tap_listener(stat->tap_name, stat_data, tap_filter, 0, NULL, stat->packet_func, sharkd_session_process_tap_nstat_cb);
2130
2131                         tap_data = stat_data;
2132                         tap_free = sharkd_session_free_tap_nstat_cb;
2133                 }
2134                 else if (!strncmp(tok_tap, "rtd:", 4))
2135                 {
2136                         register_rtd_t *rtd = get_rtd_table_by_name(tok_tap + 4);
2137                         rtd_data_t *rtd_data;
2138                         char *err;
2139
2140                         if (!rtd)
2141                         {
2142                                 fprintf(stderr, "sharkd_session_process_tap() rtd=%s not found\n", tok_tap + 4);
2143                                 continue;
2144                         }
2145
2146                         rtd_table_get_filter(rtd, "", &tap_filter, &err);
2147                         if (err != NULL)
2148                         {
2149                                 fprintf(stderr, "sharkd_session_process_tap() rtd=%s err=%s\n", tok_tap + 4, err);
2150                                 g_free(err);
2151                                 continue;
2152                         }
2153
2154                         rtd_data = g_new0(rtd_data_t, 1);
2155                         rtd_data->user_data = rtd;
2156                         rtd_table_dissector_init(rtd, &rtd_data->stat_table, NULL, NULL);
2157
2158                         tap_error = register_tap_listener(get_rtd_tap_listener_name(rtd), rtd_data, tap_filter, 0, NULL, get_rtd_packet_func(rtd), sharkd_session_process_tap_rtd_cb);
2159
2160                         tap_data = rtd_data;
2161                         tap_free = sharkd_session_free_tap_rtd_cb;
2162                 }
2163                 else if (!strncmp(tok_tap, "srt:", 4))
2164                 {
2165                         register_srt_t *srt = get_srt_table_by_name(tok_tap + 4);
2166                         srt_data_t *srt_data;
2167                         char *err;
2168
2169                         if (!srt)
2170                         {
2171                                 fprintf(stderr, "sharkd_session_process_tap() srt=%s not found\n", tok_tap + 4);
2172                                 continue;
2173                         }
2174
2175                         srt_table_get_filter(srt, "", &tap_filter, &err);
2176                         if (err != NULL)
2177                         {
2178                                 fprintf(stderr, "sharkd_session_process_tap() srt=%s err=%s\n", tok_tap + 4, err);
2179                                 g_free(err);
2180                                 continue;
2181                         }
2182
2183                         srt_data = g_new0(srt_data_t, 1);
2184                         srt_data->srt_array = g_array_new(FALSE, TRUE, sizeof(srt_stat_table *));
2185                         srt_data->user_data = srt;
2186                         srt_table_dissector_init(srt, srt_data->srt_array, NULL, NULL);
2187
2188                         tap_error = register_tap_listener(get_srt_tap_listener_name(srt), srt_data, tap_filter, 0, NULL, get_srt_packet_func(srt), sharkd_session_process_tap_srt_cb);
2189
2190                         tap_data = srt_data;
2191                         tap_free = sharkd_session_free_tap_srt_cb;
2192                 }
2193                 else if (!strncmp(tok_tap, "eo:", 3))
2194                 {
2195                         register_eo_t *eo = get_eo_by_name(tok_tap + 3);
2196                         export_object_list_t *eo_object;
2197                         struct sharkd_export_object_list *object_list;
2198
2199                         if (!eo)
2200                         {
2201                                 fprintf(stderr, "sharkd_session_process_tap() eo=%s not found\n", tok_tap + 3);
2202                                 continue;
2203                         }
2204
2205                         for (object_list = sharkd_eo_list; object_list; object_list = object_list->next)
2206                         {
2207                                 if (!strcmp(object_list->type, tok_tap))
2208                                 {
2209                                         g_slist_free_full(object_list->entries, (GDestroyNotify) eo_free_entry);
2210                                         object_list->entries = NULL;
2211                                         break;
2212                                 }
2213                         }
2214
2215                         if (!object_list)
2216                         {
2217                                 object_list = g_new(struct sharkd_export_object_list, 1);
2218                                 object_list->type = g_strdup(tok_tap);
2219                                 object_list->proto = proto_get_protocol_short_name(find_protocol_by_id(get_eo_proto_id(eo)));
2220                                 object_list->entries = NULL;
2221                                 object_list->next = sharkd_eo_list;
2222                                 sharkd_eo_list = object_list;
2223                         }
2224
2225                         eo_object  = g_new0(export_object_list_t, 1);
2226                         eo_object->add_entry = sharkd_eo_object_list_add_entry;
2227                         eo_object->get_entry = sharkd_eo_object_list_get_entry;
2228                         eo_object->gui_data = (void *) object_list;
2229
2230                         tap_error = register_tap_listener(get_eo_tap_listener_name(eo), eo_object, NULL, 0, NULL, get_eo_packet_func(eo), sharkd_session_process_tap_eo_cb);
2231
2232                         tap_data = eo_object;
2233                         tap_free = g_free; /* need to free only eo_object, object_list need to be kept for potential download */
2234                 }
2235                 else if (!strcmp(tok_tap, "rtp-streams"))
2236                 {
2237                         tap_error = register_tap_listener("rtp", &rtp_tapinfo, tap_filter, 0, rtpstream_reset_cb, rtpstream_packet, sharkd_session_process_tap_rtp_cb);
2238
2239                         tap_data = &rtp_tapinfo;
2240                         tap_free = rtpstream_reset_cb;
2241                 }
2242                 else if (!strncmp(tok_tap, "rtp-analyse:", 12))
2243                 {
2244                         struct sharkd_analyse_rtp *rtp_req;
2245
2246                         rtp_req = (struct sharkd_analyse_rtp *) g_malloc0(sizeof(*rtp_req));
2247                         if (!sharkd_rtp_match_init(&rtp_req->rtp, tok_tap + 12))
2248                         {
2249                                 g_free(rtp_req);
2250                                 continue;
2251                         }
2252
2253                         rtp_req->tap_name = tok_tap;
2254                         rtp_req->statinfo.first_packet = TRUE;
2255                         rtp_req->statinfo.reg_pt = PT_UNDEFINED;
2256
2257                         tap_error = register_tap_listener("rtp", rtp_req, tap_filter, 0, NULL, sharkd_session_packet_tap_rtp_analyse_cb, sharkd_session_process_tap_rtp_analyse_cb);
2258
2259                         tap_data = rtp_req;
2260                         tap_free = sharkd_session_process_tap_rtp_free_cb;
2261                 }
2262                 else
2263                 {
2264                         fprintf(stderr, "sharkd_session_process_tap() %s not recognized\n", tok_tap);
2265                         continue;
2266                 }
2267
2268                 if (tap_error)
2269                 {
2270                         fprintf(stderr, "sharkd_session_process_tap() name=%s error=%s", tok_tap, tap_error->str);
2271                         g_string_free(tap_error, TRUE);
2272                         if (tap_free)
2273                                 tap_free(tap_data);
2274                         continue;
2275                 }
2276
2277                 taps_data[taps_count] = tap_data;
2278                 taps_free[taps_count] = tap_free;
2279                 taps_count++;
2280         }
2281
2282         fprintf(stderr, "sharkd_session_process_tap() count=%d\n", taps_count);
2283         if (taps_count == 0)
2284                 return;
2285
2286         printf("{\"taps\":[");
2287         sharkd_retap();
2288         printf("null],\"err\":0}\n");
2289
2290         for (i = 0; i < taps_count; i++)
2291         {
2292                 if (taps_data[i])
2293                         remove_tap_listener(taps_data[i]);
2294
2295                 if (taps_free[i])
2296                         taps_free[i](taps_data[i]);
2297         }
2298 }
2299
2300 /**
2301  * sharkd_session_process_follow()
2302  *
2303  * Process follow request
2304  *
2305  * Input:
2306  *   (m) follow  - follow protocol request (e.g. HTTP)
2307  *   (m) filter  - filter request (e.g. tcp.stream == 1)
2308  *
2309  * Output object with attributes:
2310  *
2311  *   (m) err    - error code
2312  *   (m) shost  - server host
2313  *   (m) sport  - server port
2314  *   (m) sbytes - server send bytes count
2315  *   (m) chost  - client host
2316  *   (m) cport  - client port
2317  *   (m) cbytes - client send bytes count
2318  *   (o) payloads - array of object with attributes:
2319  *                  (o) s - set if server sent, else client
2320  *                  (m) n - packet number
2321  *                  (m) d - data base64 encoded
2322  */
2323 static void
2324 sharkd_session_process_follow(char *buf, const jsmntok_t *tokens, int count)
2325 {
2326         const char *tok_follow = json_find_attr(buf, tokens, count, "follow");
2327         const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
2328
2329         register_follow_t *follower;
2330         GString *tap_error;
2331
2332         follow_info_t *follow_info;
2333         const char *host;
2334         char *port;
2335
2336         if (!tok_follow || !tok_filter)
2337                 return;
2338
2339         follower = get_follow_by_name(tok_follow);
2340         if (!follower)
2341         {
2342                 fprintf(stderr, "sharkd_session_process_follow() follower=%s not found\n", tok_follow);
2343                 return;
2344         }
2345
2346         /* follow_reset_stream ? */
2347         follow_info = g_new0(follow_info_t, 1);
2348         /* gui_data, filter_out_filter not set, but not used by dissector */
2349
2350         tap_error = register_tap_listener(get_follow_tap_string(follower), follow_info, tok_filter, 0, NULL, get_follow_tap_handler(follower), NULL);
2351         if (tap_error)
2352         {
2353                 fprintf(stderr, "sharkd_session_process_follow() name=%s error=%s", tok_follow, tap_error->str);
2354                 g_string_free(tap_error, TRUE);
2355                 g_free(follow_info);
2356                 return;
2357         }
2358
2359         sharkd_retap();
2360
2361         printf("{");
2362
2363         printf("\"err\":0");
2364
2365         /* Server information: hostname, port, bytes sent */
2366         host = address_to_name(&follow_info->server_ip);
2367         printf(",\"shost\":");
2368         json_puts_string(host);
2369
2370         port = get_follow_port_to_display(follower)(NULL, follow_info->server_port);
2371         printf(",\"sport\":");
2372         json_puts_string(port);
2373         wmem_free(NULL, port);
2374
2375         printf(",\"sbytes\":%u", follow_info->bytes_written[0]);
2376
2377         /* Client information: hostname, port, bytes sent */
2378         host = address_to_name(&follow_info->client_ip);
2379         printf(",\"chost\":");
2380         json_puts_string(host);
2381
2382         port = get_follow_port_to_display(follower)(NULL, follow_info->client_port);
2383         printf(",\"cport\":");
2384         json_puts_string(port);
2385         wmem_free(NULL, port);
2386
2387         printf(",\"cbytes\":%u", follow_info->bytes_written[1]);
2388
2389         if (follow_info->payload)
2390         {
2391                 follow_record_t *follow_record;
2392                 GList *cur;
2393                 const char *sepa = "";
2394
2395                 printf(",\"payloads\":[");
2396
2397                 for (cur = follow_info->payload; cur; cur = g_list_next(cur))
2398                 {
2399                         follow_record = (follow_record_t *) cur->data;
2400
2401                         printf("%s{", sepa);
2402
2403                         printf("\"n\":%u", follow_record->packet_num);
2404
2405                         printf(",\"d\":");
2406                         json_print_base64(follow_record->data->data, follow_record->data->len);
2407
2408                         if (follow_record->is_server)
2409                                 printf(",\"s\":%d", 1);
2410
2411                         printf("}");
2412                         sepa = ",";
2413                 }
2414
2415                 printf("]");
2416         }
2417
2418         printf("}\n");
2419
2420         remove_tap_listener(follow_info);
2421         follow_info_free(follow_info);
2422 }
2423
2424 static void
2425 sharkd_session_process_frame_cb_tree(proto_tree *tree, tvbuff_t **tvbs)
2426 {
2427         proto_node *node;
2428         const char *sepa = "";
2429
2430         printf("[");
2431         for (node = tree->first_child; node; node = node->next)
2432         {
2433                 field_info *finfo = PNODE_FINFO(node);
2434
2435                 if (!finfo)
2436                         continue;
2437
2438                 /* XXX, for now always skip hidden */
2439                 if (FI_GET_FLAG(finfo, FI_HIDDEN))
2440                         continue;
2441
2442                 printf("%s{", sepa);
2443
2444                 printf("\"l\":");
2445                 if (!finfo->rep)
2446                 {
2447                         char label_str[ITEM_LABEL_LENGTH];
2448
2449                         label_str[0] = '\0';
2450                         proto_item_fill_label(finfo, label_str);
2451                         json_puts_string(label_str);
2452                 }
2453                 else
2454                 {
2455                         json_puts_string(finfo->rep->representation);
2456                 }
2457
2458                 if (finfo->ds_tvb && tvbs && tvbs[0] != finfo->ds_tvb)
2459                 {
2460                         int idx;
2461
2462                         for (idx = 1; tvbs[idx]; idx++)
2463                         {
2464                                 if (tvbs[idx] == finfo->ds_tvb)
2465                                 {
2466                                         printf(",\"ds\":%d", idx);
2467                                         break;
2468                                 }
2469                         }
2470                 }
2471
2472                 if (finfo->start >= 0 && finfo->length > 0)
2473                         printf(",\"h\":[%d,%d]", finfo->start, finfo->length);
2474
2475                 if (finfo->appendix_start >= 0 && finfo->appendix_length > 0)
2476                         printf(",\"i\":[%d,%d]", finfo->appendix_start, finfo->appendix_length);
2477
2478
2479                 if (finfo->hfinfo)
2480                 {
2481                         if (finfo->hfinfo->type == FT_PROTOCOL)
2482                         {
2483                                 printf(",\"t\":\"proto\"");
2484                         }
2485                         else if (finfo->hfinfo->type == FT_FRAMENUM)
2486                         {
2487                                 printf(",\"t\":\"framenum\",\"fnum\":%u", finfo->value.value.uinteger);
2488                         }
2489                         else if (FI_GET_FLAG(finfo, FI_URL) && IS_FT_STRING(finfo->hfinfo->type))
2490                         {
2491                                 char *url = fvalue_to_string_repr(NULL, &finfo->value, FTREPR_DISPLAY, finfo->hfinfo->display);
2492
2493                                 printf(",\"t\":\"url\",\"url\":");
2494                                 json_puts_string(url);
2495                                 wmem_free(NULL, url);
2496                         }
2497                 }
2498
2499                 if (FI_GET_FLAG(finfo, PI_SEVERITY_MASK))
2500                 {
2501                         const char *severity = try_val_to_str(FI_GET_FLAG(finfo, PI_SEVERITY_MASK), expert_severity_vals);
2502
2503                         g_assert(severity != NULL);
2504
2505                         printf(",\"s\":\"%s\"", severity);
2506                 }
2507
2508                 if (((proto_tree *) node)->first_child) {
2509                         if (finfo->tree_type != -1)
2510                                 printf(",\"e\":%d", finfo->tree_type);
2511                         printf(",\"n\":");
2512                         sharkd_session_process_frame_cb_tree((proto_tree *) node, tvbs);
2513                 }
2514
2515                 printf("}");
2516                 sepa = ",";
2517         }
2518         printf("]");
2519 }
2520
2521 static gboolean
2522 sharkd_follower_visit_layers_cb(const void *key _U_, void *value, void *user_data)
2523 {
2524         register_follow_t *follower = (register_follow_t *) value;
2525         packet_info *pi = (packet_info *) user_data;
2526
2527         const int proto_id = get_follow_proto_id(follower);
2528
2529         guint32 ignore_stream;
2530
2531         if (proto_is_frame_protocol(pi->layers, proto_get_protocol_filter_name(proto_id)))
2532         {
2533                 const char *layer_proto = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
2534                 char *follow_filter;
2535
2536                 follow_filter = get_follow_conv_func(follower)(pi, &ignore_stream);
2537
2538                 printf(",[\"%s\",", layer_proto);
2539                 json_puts_string(follow_filter);
2540                 printf("]");
2541
2542                 g_free(follow_filter);
2543         }
2544
2545         return FALSE;
2546 }
2547
2548 static void
2549 sharkd_session_process_frame_cb(packet_info *pi, proto_tree *tree, struct epan_column_info *cinfo, const GSList *data_src, void *data)
2550 {
2551         (void) pi;
2552         (void) data;
2553
2554         printf("{");
2555
2556         printf("\"err\":0");
2557
2558         if (tree)
2559         {
2560                 tvbuff_t **tvbs = NULL;
2561
2562                 printf(",\"tree\":");
2563
2564                 /* arrayize data src, to speedup searching for ds_tvb index */
2565                 if (data_src && data_src->next /* only needed if there are more than one data source */)
2566                 {
2567                         guint count = g_slist_length((GSList *) data_src);
2568                         guint i;
2569
2570                         tvbs = (tvbuff_t **) g_malloc((count + 1) * sizeof(*tvbs));
2571
2572                         for (i = 0; i < count; i++)
2573                         {
2574                                 struct data_source *src = (struct data_source *) g_slist_nth_data((GSList *) data_src, i);
2575
2576                                 tvbs[i] = get_data_source_tvb(src);
2577                         }
2578
2579                         tvbs[count] = NULL;
2580                 }
2581
2582                 sharkd_session_process_frame_cb_tree(tree, tvbs);
2583
2584                 g_free(tvbs);
2585         }
2586
2587         if (cinfo)
2588         {
2589                 int col;
2590
2591                 printf(",\"col\":[");
2592                 for (col = 0; col < cinfo->num_cols; ++col)
2593                 {
2594                         const col_item_t *col_item = &cinfo->columns[col];
2595
2596                         printf("%s\"%s\"", (col) ? "," : "", col_item->col_data);
2597                 }
2598                 printf("]");
2599         }
2600
2601         if (data_src)
2602         {
2603                 struct data_source *src = (struct data_source *)data_src->data;
2604                 const char *ds_sepa = NULL;
2605
2606                 tvbuff_t *tvb;
2607                 guint length;
2608
2609                 tvb = get_data_source_tvb(src);
2610                 length = tvb_captured_length(tvb);
2611
2612                 printf(",\"bytes\":");
2613                 if (length != 0)
2614                 {
2615                         const guchar *cp = tvb_get_ptr(tvb, 0, length);
2616
2617                         /* XXX pi.fd->flags.encoding */
2618                         json_print_base64(cp, length);
2619                 }
2620                 else
2621                 {
2622                         json_print_base64("", 0);
2623                 }
2624
2625                 data_src = data_src->next;
2626                 if (data_src)
2627                 {
2628                         printf(",\"ds\":[");
2629                         ds_sepa = "";
2630                 }
2631
2632                 while (data_src)
2633                 {
2634                         src = (struct data_source *)data_src->data;
2635
2636                         {
2637                                 char *src_name = get_data_source_name(src);
2638
2639                                 printf("%s{\"name\":", ds_sepa);
2640                                 json_puts_string(src_name);
2641                                 wmem_free(NULL, src_name);
2642                         }
2643
2644                         tvb = get_data_source_tvb(src);
2645                         length = tvb_captured_length(tvb);
2646
2647                         printf(",\"bytes\":");
2648                         if (length != 0)
2649                         {
2650                                 const guchar *cp = tvb_get_ptr(tvb, 0, length);
2651
2652                                 /* XXX pi.fd->flags.encoding */
2653                                 json_print_base64(cp, length);
2654                         }
2655                         else
2656                         {
2657                                 json_print_base64("", 0);
2658                         }
2659
2660                         printf("}");
2661                         ds_sepa = ",";
2662
2663                         data_src = data_src->next;
2664                 }
2665
2666                 /* close ds, only if was opened */
2667                 if (ds_sepa != NULL)
2668                         printf("]");
2669         }
2670
2671         printf(",\"fol\":[0");
2672         follow_iterate_followers(sharkd_follower_visit_layers_cb, pi);
2673         printf("]");
2674
2675         printf("}\n");
2676 }
2677
2678 /**
2679  * sharkd_session_process_intervals()
2680  *
2681  * Process intervals request - generate basic capture file statistics per requested interval.
2682  *
2683  * Input:
2684  *   (o) interval - interval time in ms, if not specified: 1000ms
2685  *   (o) filter   - filter for generating interval request
2686  *
2687  * Output object with attributes:
2688  *   (m) intervals - array of intervals, with indexes:
2689  *             [0] - index of interval,
2690  *             [1] - number of frames during interval,
2691  *             [2] - number of bytes during interval.
2692  *
2693  *   (m) last   - last interval number.
2694  *   (m) frames - total number of frames
2695  *   (m) bytes  - total number of bytes
2696  *
2697  * NOTE: If frames are not in order, there might be items with same interval index, or even negative one.
2698  */
2699 static void
2700 sharkd_session_process_intervals(char *buf, const jsmntok_t *tokens, int count)
2701 {
2702         const char *tok_interval = json_find_attr(buf, tokens, count, "interval");
2703         const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
2704
2705         const guint8 *filter_data = NULL;
2706
2707         struct
2708         {
2709                 unsigned int frames;
2710                 guint64 bytes;
2711         } st, st_total;
2712
2713         nstime_t *start_ts = NULL;
2714
2715         guint32 interval_ms = 1000; /* default: one per second */
2716
2717         const char *sepa = "";
2718         unsigned int framenum;
2719         gint64 idx;
2720         gint64 max_idx = 0;
2721
2722         if (tok_interval) {
2723                 if (!ws_strtou32(tok_interval, NULL, &interval_ms) || interval_ms == 0) {
2724                         fprintf(stderr, "Invalid interval parameter: %s.\n", tok_interval);
2725                         return;
2726                 }
2727         }
2728
2729         if (tok_filter)
2730         {
2731                 filter_data = sharkd_session_filter_data(tok_filter);
2732                 if (!filter_data)
2733                         return;
2734         }
2735
2736         st_total.frames = 0;
2737         st_total.bytes  = 0;
2738
2739         st.frames = 0;
2740         st.bytes  = 0;
2741
2742         idx = 0;
2743
2744         printf("{\"intervals\":[");
2745
2746         for (framenum = 1; framenum <= cfile.count; framenum++)
2747         {
2748                 frame_data *fdata = frame_data_sequence_find(cfile.frames, framenum);
2749                 gint64 msec_rel;
2750                 gint64 new_idx;
2751
2752                 if (start_ts == NULL)
2753                         start_ts = &fdata->abs_ts;
2754
2755                 if (filter_data && !(filter_data[framenum / 8] & (1 << (framenum % 8))))
2756                         continue;
2757
2758                 msec_rel = (fdata->abs_ts.secs - start_ts->secs) * (gint64) 1000 + (fdata->abs_ts.nsecs - start_ts->nsecs) / 1000000;
2759                 new_idx  = msec_rel / interval_ms;
2760
2761                 if (idx != new_idx)
2762                 {
2763                         if (st.frames != 0)
2764                         {
2765                                 printf("%s[%" G_GINT64_FORMAT ",%u,%" G_GUINT64_FORMAT "]", sepa, idx, st.frames, st.bytes);
2766                                 sepa = ",";
2767                         }
2768
2769                         idx = new_idx;
2770                         if (idx > max_idx)
2771                                 max_idx = idx;
2772
2773                         st.frames = 0;
2774                         st.bytes  = 0;
2775                 }
2776
2777                 st.frames += 1;
2778                 st.bytes  += fdata->pkt_len;
2779
2780                 st_total.frames += 1;
2781                 st_total.bytes  += fdata->pkt_len;
2782         }
2783
2784         if (st.frames != 0)
2785         {
2786                 printf("%s[%" G_GINT64_FORMAT ",%u,%" G_GUINT64_FORMAT "]", sepa, idx, st.frames, st.bytes);
2787                 /* sepa = ","; */
2788         }
2789
2790         printf("],\"last\":%" G_GINT64_FORMAT ",\"frames\":%u,\"bytes\":%" G_GUINT64_FORMAT "}\n", max_idx, st_total.frames, st_total.bytes);
2791 }
2792
2793 /**
2794  * sharkd_session_process_frame()
2795  *
2796  * Process frame request
2797  *
2798  * Input:
2799  *   (m) frame - requested frame number
2800  *   (o) proto - set if output frame tree
2801  *   (o) columns - set if output frame columns
2802  *   (o) bytes - set if output frame bytes
2803  *
2804  * Output object with attributes:
2805  *   (m) err   - 0 if succeed
2806  *   (o) tree  - array of frame nodes with attributes:
2807  *                  l - label
2808  *                  t: 'proto', 'framenum', 'url' - type of node
2809  *                  s - severity
2810  *                  e - subtree ett index
2811  *                  n - array of subtree nodes
2812  *                  h - two item array: (item start, item length)
2813  *                  i - two item array: (appendix start, appendix length)
2814  *                  p - [RESERVED] two item array: (protocol start, protocol length)
2815  *                  ds- data src index
2816  *                  url  - only for t:'url', url
2817  *                  fnum - only for t:'framenum', frame number
2818  *
2819  *   (o) col   - array of column data
2820  *   (o) bytes - base64 of frame bytes
2821  *   (o) ds    - array of other data srcs
2822  *   (o) fol   - array of follow filters:
2823  *                  [0] - protocol
2824  *                  [1] - filter string
2825  */
2826 static void
2827 sharkd_session_process_frame(char *buf, const jsmntok_t *tokens, int count)
2828 {
2829         const char *tok_frame = json_find_attr(buf, tokens, count, "frame");
2830         int tok_proto   = (json_find_attr(buf, tokens, count, "proto") != NULL);
2831         int tok_bytes   = (json_find_attr(buf, tokens, count, "bytes") != NULL);
2832         int tok_columns = (json_find_attr(buf, tokens, count, "columns") != NULL);
2833
2834         guint32 framenum;
2835
2836         if (!tok_frame || !ws_strtou32(tok_frame, NULL, &framenum) || framenum == 0)
2837                 return;
2838
2839         sharkd_dissect_request(framenum, &sharkd_session_process_frame_cb, tok_bytes, tok_columns, tok_proto, NULL);
2840 }
2841
2842 /**
2843  * sharkd_session_process_check()
2844  *
2845  * Process check request.
2846  *
2847  * Input:
2848  *   (o) filter - filter to be checked
2849  *
2850  * Output object with attributes:
2851  *   (m) err - always 0
2852  *   (o) filter - 'ok', 'warn' or error message
2853  */
2854 static int
2855 sharkd_session_process_check(char *buf, const jsmntok_t *tokens, int count)
2856 {
2857         const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
2858
2859         printf("{\"err\":0");
2860         if (tok_filter != NULL)
2861         {
2862                 char *err_msg = NULL;
2863                 dfilter_t *dfp;
2864
2865                 if (dfilter_compile(tok_filter, &dfp, &err_msg))
2866                 {
2867                         const char *s = "ok";
2868
2869                         if (dfilter_deprecated_tokens(dfp))
2870                                 s = "warn";
2871
2872                         printf(",\"filter\":\"%s\"", s);
2873                         dfilter_free(dfp);
2874                 }
2875                 else
2876                 {
2877                         printf(",\"filter\":");
2878                         json_puts_string(err_msg);
2879                         g_free(err_msg);
2880                 }
2881         }
2882
2883         printf("}\n");
2884         return 0;
2885 }
2886
2887 struct sharkd_session_process_complete_pref_data
2888 {
2889         const char *module;
2890         const char *pref;
2891         const char *sepa;
2892 };
2893
2894 static guint
2895 sharkd_session_process_complete_pref_cb(module_t *module, gpointer d)
2896 {
2897         struct sharkd_session_process_complete_pref_data *data = (struct sharkd_session_process_complete_pref_data *) d;
2898
2899         if (strncmp(data->pref, module->name, strlen(data->pref)) != 0)
2900                 return 0;
2901
2902         printf("%s{\"f\":\"%s\",\"d\":\"%s\"}", data->sepa, module->name, module->title);
2903         data->sepa = ",";
2904
2905         return 0;
2906 }
2907
2908 static guint
2909 sharkd_session_process_complete_pref_option_cb(pref_t *pref, gpointer d)
2910 {
2911         struct sharkd_session_process_complete_pref_data *data = (struct sharkd_session_process_complete_pref_data *) d;
2912         const char *pref_name = prefs_get_name(pref);
2913         const char *pref_title = prefs_get_title(pref);
2914
2915         if (strncmp(data->pref, pref_name, strlen(data->pref)) != 0)
2916                 return 0;
2917
2918         printf("%s{\"f\":\"%s.%s\",\"d\":\"%s\"}", data->sepa, data->module, pref_name, pref_title);
2919         data->sepa = ",";
2920
2921         return 0; /* continue */
2922 }
2923
2924 /**
2925  * sharkd_session_process_complete()
2926  *
2927  * Process complete request
2928  *
2929  * Input:
2930  *   (o) field - field to be completed
2931  *   (o) pref  - preference to be completed
2932  *
2933  * Output object with attributes:
2934  *   (m) err - always 0
2935  *   (o) field - array of object with attributes:
2936  *                  (m) f - field text
2937  *                  (o) t - field type (FT_ number)
2938  *                  (o) n - field name
2939  *   (o) pref  - array of object with attributes:
2940  *                  (m) f - pref name
2941  *                  (o) d - pref description
2942  */
2943 static int
2944 sharkd_session_process_complete(char *buf, const jsmntok_t *tokens, int count)
2945 {
2946         const char *tok_field = json_find_attr(buf, tokens, count, "field");
2947         const char *tok_pref  = json_find_attr(buf, tokens, count, "pref");
2948
2949         printf("{\"err\":0");
2950         if (tok_field != NULL && tok_field[0])
2951         {
2952                 const size_t filter_length = strlen(tok_field);
2953                 const int filter_with_dot = !!strchr(tok_field, '.');
2954
2955                 void *proto_cookie;
2956                 void *field_cookie;
2957                 int proto_id;
2958                 const char *sepa = "";
2959
2960                 printf(",\"field\":[");
2961
2962                 for (proto_id = proto_get_first_protocol(&proto_cookie); proto_id != -1; proto_id = proto_get_next_protocol(&proto_cookie))
2963                 {
2964                         protocol_t *protocol = find_protocol_by_id(proto_id);
2965                         const char *protocol_filter;
2966                         const char *protocol_name;
2967                         header_field_info *hfinfo;
2968
2969                         if (!proto_is_protocol_enabled(protocol))
2970                                 continue;
2971
2972                         protocol_name   = proto_get_protocol_long_name(protocol);
2973                         protocol_filter = proto_get_protocol_filter_name(proto_id);
2974
2975                         if (strlen(protocol_filter) >= filter_length && !g_ascii_strncasecmp(tok_field, protocol_filter, filter_length))
2976                         {
2977                                 printf("%s{", sepa);
2978                                 {
2979                                         printf("\"f\":");
2980                                         json_puts_string(protocol_filter);
2981                                         printf(",\"t\":%d", FT_PROTOCOL);
2982                                         printf(",\"n\":");
2983                                         json_puts_string(protocol_name);
2984                                 }
2985                                 printf("}");
2986                                 sepa = ",";
2987                         }
2988
2989                         if (!filter_with_dot)
2990                                 continue;
2991
2992                         for (hfinfo = proto_get_first_protocol_field(proto_id, &field_cookie); hfinfo != NULL; hfinfo = proto_get_next_protocol_field(proto_id, &field_cookie))
2993                         {
2994                                 if (hfinfo->same_name_prev_id != -1) /* ignore duplicate names */
2995                                         continue;
2996
2997                                 if (strlen(hfinfo->abbrev) >= filter_length && !g_ascii_strncasecmp(tok_field, hfinfo->abbrev, filter_length))
2998                                 {
2999                                         printf("%s{", sepa);
3000                                         {
3001                                                 printf("\"f\":");
3002                                                 json_puts_string(hfinfo->abbrev);
3003
3004                                                 /* XXX, skip displaying name, if there are multiple (to not confuse user) */
3005                                                 if (hfinfo->same_name_next == NULL)
3006                                                 {
3007                                                         printf(",\"t\":%d", hfinfo->type);
3008                                                         printf(",\"n\":");
3009                                                         json_puts_string(hfinfo->name);
3010                                                 }
3011                                         }
3012                                         printf("}");
3013                                         sepa = ",";
3014                                 }
3015                         }
3016                 }
3017
3018                 printf("]");
3019         }
3020
3021         if (tok_pref != NULL && tok_pref[0])
3022         {
3023                 struct sharkd_session_process_complete_pref_data data;
3024                 char *dot_sepa;
3025
3026                 data.module = tok_pref;
3027                 data.pref = tok_pref;
3028                 data.sepa = "";
3029
3030                 printf(",\"pref\":[");
3031
3032                 if ((dot_sepa = strchr(tok_pref, '.')))
3033                 {
3034                         module_t *pref_mod;
3035
3036                         *dot_sepa = '\0'; /* XXX, C abuse: discarding-const */
3037                         data.pref = dot_sepa + 1;
3038
3039                         pref_mod = prefs_find_module(data.module);
3040                         if (pref_mod)
3041                                 prefs_pref_foreach(pref_mod, sharkd_session_process_complete_pref_option_cb, &data);
3042
3043                         *dot_sepa = '.';
3044                 }
3045                 else
3046                 {
3047                         prefs_modules_foreach(sharkd_session_process_complete_pref_cb, &data);
3048                 }
3049
3050                 printf("]");
3051         }
3052
3053
3054         printf("}\n");
3055         return 0;
3056 }
3057
3058 /**
3059  * sharkd_session_process_setconf()
3060  *
3061  * Process setconf request
3062  *
3063  * Input:
3064  *   (m) name  - preference name
3065  *   (m) value - preference value
3066  *
3067  * Output object with attributes:
3068  *   (m) err   - error code: 0 succeed
3069  */
3070 static void
3071 sharkd_session_process_setconf(char *buf, const jsmntok_t *tokens, int count)
3072 {
3073         const char *tok_name = json_find_attr(buf, tokens, count, "name");
3074         const char *tok_value = json_find_attr(buf, tokens, count, "value");
3075         char pref[4096];
3076
3077         prefs_set_pref_e ret;
3078
3079         if (!tok_name || tok_name[0] == '\0' || !tok_value)
3080                 return;
3081
3082         ws_snprintf(pref, sizeof(pref), "%s:%s", tok_name, tok_value);
3083
3084         ret = prefs_set_pref(pref);
3085         printf("{\"err\":%d}\n", ret);
3086 }
3087
3088 struct sharkd_session_process_dumpconf_data
3089 {
3090         module_t *module;
3091         const char *sepa;
3092 };
3093
3094 static guint
3095 sharkd_session_process_dumpconf_cb(pref_t *pref, gpointer d)
3096 {
3097         struct sharkd_session_process_dumpconf_data *data = (struct sharkd_session_process_dumpconf_data *) d;
3098         const char *pref_name = prefs_get_name(pref);
3099
3100         printf("%s\"%s.%s\":{", data->sepa, data->module->name, pref_name);
3101
3102         switch (prefs_get_type(pref))
3103         {
3104                 case PREF_UINT:
3105                 case PREF_DECODE_AS_UINT:
3106                         printf("\"u\":%u", prefs_get_uint_value_real(pref, pref_current));
3107                         if (prefs_get_uint_base(pref) != 10)
3108                                 printf(",\"ub\":%u", prefs_get_uint_base(pref));
3109                         break;
3110
3111                 case PREF_BOOL:
3112                         printf("\"b\":%s", prefs_get_bool_value(pref, pref_current) ? "1" : "0");
3113                         break;
3114
3115                 case PREF_STRING:
3116                         printf("\"s\":");
3117                         json_puts_string(prefs_get_string_value(pref, pref_current));
3118                         break;
3119
3120                 case PREF_ENUM:
3121                 {
3122                         const enum_val_t *enums;
3123                         const char *enum_sepa = "";
3124
3125                         printf("\"e\":[");
3126                         for (enums = prefs_get_enumvals(pref); enums->name; enums++)
3127                         {
3128                                 printf("%s{\"v\":%d", enum_sepa, enums->value);
3129
3130                                 if (enums->value == prefs_get_enum_value(pref, pref_current))
3131                                         printf(",\"s\":1");
3132
3133                                 printf(",\"d\":");
3134                                 json_puts_string(enums->description);
3135
3136                                 printf("}");
3137                                 enum_sepa = ",";
3138                         }
3139                         printf("]");
3140                         break;
3141                 }
3142
3143                 case PREF_RANGE:
3144                 case PREF_DECODE_AS_RANGE:
3145                 {
3146                         char *range_str = range_convert_range(NULL, prefs_get_range_value_real(pref, pref_current));
3147                         printf("\"r\":\"%s\"", range_str);
3148                         wmem_free(NULL, range_str);
3149                         break;
3150                 }
3151
3152                 case PREF_UAT:
3153                 {
3154                         uat_t *uat = prefs_get_uat_value(pref);
3155                         guint idx;
3156
3157                         printf("\"t\":[");
3158                         for (idx = 0; idx < uat->raw_data->len; idx++)
3159                         {
3160                                 void *rec = UAT_INDEX_PTR(uat, idx);
3161                                 guint colnum;
3162
3163                                 if (idx)
3164                                         printf(",");
3165
3166                                 printf("[");
3167                                 for (colnum = 0; colnum < uat->ncols; colnum++)
3168                                 {
3169                                         char *str = uat_fld_tostr(rec, &(uat->fields[colnum]));
3170
3171                                         if (colnum)
3172                                                 printf(",");
3173
3174                                         json_puts_string(str);
3175                                         g_free(str);
3176                                 }
3177
3178                                 printf("]");
3179                         }
3180
3181                         printf("]");
3182                         break;
3183                 }
3184
3185                 case PREF_COLOR:
3186                 case PREF_CUSTOM:
3187                 case PREF_STATIC_TEXT:
3188                 case PREF_OBSOLETE:
3189                         /* TODO */
3190                         break;
3191         }
3192
3193 #if 0
3194         printf(",\"t\":");
3195         json_puts_string(prefs_get_title(pref));
3196 #endif
3197
3198         printf("}");
3199         data->sepa = ",";
3200
3201         return 0; /* continue */
3202 }
3203
3204 static guint
3205 sharkd_session_process_dumpconf_mod_cb(module_t *module, gpointer d)
3206 {
3207         struct sharkd_session_process_dumpconf_data *data = (struct sharkd_session_process_dumpconf_data *) d;
3208
3209         data->module = module;
3210         prefs_pref_foreach(module, sharkd_session_process_dumpconf_cb, data);
3211
3212         return 0;
3213 }
3214
3215 /**
3216  * sharkd_session_process_dumpconf()
3217  *
3218  * Process dumpconf request
3219  *
3220  * Input:
3221  *   (o) pref - module, or preference, NULL for all
3222  *
3223  * Output object with attributes:
3224  *   (o) prefs   - object with module preferences
3225  *                  (m) [KEY] - preference name
3226  *                  (o) u - preference value (only for PREF_UINT)
3227  *                  (o) ub - preference value suggested base for display (only for PREF_UINT) and if different than 10
3228  *                  (o) b - preference value (only for PREF_BOOL) (1 true, 0 false)
3229  *                  (o) s - preference value (only for PREF_STRING)
3230  *                  (o) e - preference possible values (only for PREF_ENUM)
3231  *                  (o) r - preference value (only for PREF_RANGE)
3232  *                  (o) t - preference value (only for PREF_UAT)
3233  */
3234 static void
3235 sharkd_session_process_dumpconf(char *buf, const jsmntok_t *tokens, int count)
3236 {
3237         const char *tok_pref = json_find_attr(buf, tokens, count, "pref");
3238         module_t *pref_mod;
3239         char *dot_sepa;
3240
3241         if (!tok_pref)
3242         {
3243                 struct sharkd_session_process_dumpconf_data data;
3244
3245                 data.module = NULL;
3246                 data.sepa = "";
3247
3248                 printf("{\"prefs\":{");
3249                 prefs_modules_foreach(sharkd_session_process_dumpconf_mod_cb, &data);
3250                 printf("}}\n");
3251                 return;
3252         }
3253
3254         if ((dot_sepa = strchr(tok_pref, '.')))
3255         {
3256                 pref_t *pref = NULL;
3257
3258                 *dot_sepa = '\0'; /* XXX, C abuse: discarding-const */
3259                 pref_mod = prefs_find_module(tok_pref);
3260                 if (pref_mod)
3261                         pref = prefs_find_preference(pref_mod, dot_sepa + 1);
3262                 *dot_sepa = '.';
3263
3264                 if (pref)
3265                 {
3266                         struct sharkd_session_process_dumpconf_data data;
3267
3268                         data.module = pref_mod;
3269                         data.sepa = "";
3270
3271                         printf("{\"prefs\":{");
3272                         sharkd_session_process_dumpconf_cb(pref, &data);
3273                         printf("}}\n");
3274                 }
3275
3276                 return;
3277         }
3278
3279         pref_mod = prefs_find_module(tok_pref);
3280         if (pref_mod)
3281         {
3282                 struct sharkd_session_process_dumpconf_data data;
3283
3284                 data.module = pref_mod;
3285                 data.sepa = "";
3286
3287                 printf("{\"prefs\":{");
3288                 prefs_pref_foreach(pref_mod, sharkd_session_process_dumpconf_cb, &data);
3289                 printf("}}\n");
3290     }
3291 }
3292
3293 struct sharkd_download_rtp
3294 {
3295         struct sharkd_rtp_match rtp;
3296         GSList *packets;
3297         double start_time;
3298 };
3299
3300 static void
3301 sharkd_rtp_download_free_items(void *ptr)
3302 {
3303         rtp_packet_t *rtp_packet = (rtp_packet_t *) ptr;
3304
3305         g_free(rtp_packet->info);
3306         g_free(rtp_packet->payload_data);
3307         g_free(rtp_packet);
3308 }
3309
3310 static void
3311 sharkd_rtp_download_decode(struct sharkd_download_rtp *req)
3312 {
3313         /* based on RtpAudioStream::decode() 6e29d874f8b5e6ebc59f661a0bb0dab8e56f122a */
3314         /* TODO, for now only without silence (timing_mode_ = Uninterrupted) */
3315
3316         static const int sample_bytes_ = sizeof(SAMPLE) / sizeof(char);
3317
3318         guint32 audio_out_rate_ = 0;
3319         struct _GHashTable *decoders_hash_ = rtp_decoder_hash_table_new();
3320         struct SpeexResamplerState_ *audio_resampler_ = NULL;
3321
3322         gsize resample_buff_len = 0x1000;
3323         SAMPLE *resample_buff = (SAMPLE *) g_malloc(resample_buff_len);
3324         spx_uint32_t cur_in_rate = 0;
3325         char *write_buff = NULL;
3326         gint64 write_bytes = 0;
3327         unsigned channels = 0;
3328         unsigned sample_rate = 0;
3329
3330         int i;
3331         int base64_state1 = 0;
3332         int base64_state2 = 0;
3333
3334         GSList *l;
3335
3336         for (l = req->packets; l; l = l->next)
3337         {
3338                 rtp_packet_t *rtp_packet = (rtp_packet_t *) l->data;
3339
3340                 SAMPLE *decode_buff = NULL;
3341                 size_t decoded_bytes;
3342
3343                 decoded_bytes = decode_rtp_packet(rtp_packet, &decode_buff, decoders_hash_, &channels, &sample_rate);
3344                 if (decoded_bytes == 0 || sample_rate == 0)
3345                 {
3346                         /* We didn't decode anything. Clean up and prep for the next packet. */
3347                         g_free(decode_buff);
3348                         continue;
3349                 }
3350
3351                 if (audio_out_rate_ == 0)
3352                 {
3353                         guint32 tmp32;
3354                         guint16 tmp16;
3355                         char wav_hdr[44];
3356
3357                         /* First non-zero wins */
3358                         audio_out_rate_ = sample_rate;
3359
3360                         RTP_STREAM_DEBUG("Audio sample rate is %u", audio_out_rate_);
3361
3362                         /* write WAVE header */
3363                         memset(&wav_hdr, 0, sizeof(wav_hdr));
3364                         memcpy(&wav_hdr[0], "RIFF", 4);
3365                         memcpy(&wav_hdr[4], "\xFF\xFF\xFF\xFF", 4); /* XXX, unknown */
3366                         memcpy(&wav_hdr[8], "WAVE", 4);
3367
3368                         memcpy(&wav_hdr[12], "fmt ", 4);
3369                         memcpy(&wav_hdr[16], "\x10\x00\x00\x00", 4); /* PCM */
3370                         memcpy(&wav_hdr[20], "\x01\x00", 2);         /* PCM */
3371                         /* # channels */
3372                         tmp16 = channels;
3373                         memcpy(&wav_hdr[22], &tmp16, 2);
3374                         /* sample rate */
3375                         tmp32 = sample_rate;
3376                         memcpy(&wav_hdr[24], &tmp32, 4);
3377                         /* byte rate */
3378                         tmp32 = sample_rate * channels * sample_bytes_;
3379                         memcpy(&wav_hdr[28], &tmp32, 4);
3380                         /* block align */
3381                         tmp16 = channels * sample_bytes_;
3382                         memcpy(&wav_hdr[32], &tmp16, 2);
3383                         /* bits per sample */
3384                         tmp16 = 8 * sample_bytes_;
3385                         memcpy(&wav_hdr[34], &tmp16, 2);
3386
3387                         memcpy(&wav_hdr[36], "data", 4);
3388                         memcpy(&wav_hdr[40], "\xFF\xFF\xFF\xFF", 4); /* XXX, unknown */
3389
3390                         for (i = 0; i < (int) sizeof(wav_hdr); i++)
3391                                 json_print_base64_step(&wav_hdr[i], &base64_state1, &base64_state2);
3392                 }
3393
3394                 // Write samples to our file.
3395                 write_buff = (char *) decode_buff;
3396                 write_bytes = decoded_bytes;
3397
3398                 if (audio_out_rate_ != sample_rate)
3399                 {
3400                         spx_uint32_t in_len, out_len;
3401
3402                         /* Resample the audio to match our previous output rate. */
3403                         if (!audio_resampler_)
3404                         {
3405                                 audio_resampler_ = speex_resampler_init(1, sample_rate, audio_out_rate_, 10, NULL);
3406                                 speex_resampler_skip_zeros(audio_resampler_);
3407                                 RTP_STREAM_DEBUG("Started resampling from %u to (out) %u Hz.", sample_rate, audio_out_rate_);
3408                         }
3409                         else
3410                         {
3411                                 spx_uint32_t audio_out_rate;
3412                                 speex_resampler_get_rate(audio_resampler_, &cur_in_rate, &audio_out_rate);
3413
3414                                 if (sample_rate != cur_in_rate)
3415                                 {
3416                                         speex_resampler_set_rate(audio_resampler_, sample_rate, audio_out_rate);
3417                                         RTP_STREAM_DEBUG("Changed input rate from %u to %u Hz. Out is %u.", cur_in_rate, sample_rate, audio_out_rate_);
3418                                 }
3419                         }
3420                         in_len = (spx_uint32_t)rtp_packet->info->info_payload_len;
3421                         out_len = (audio_out_rate_ * (spx_uint32_t)rtp_packet->info->info_payload_len / sample_rate) + (audio_out_rate_ % sample_rate != 0);
3422                         if (out_len * sample_bytes_ > resample_buff_len)
3423                         {
3424                                 while ((out_len * sample_bytes_ > resample_buff_len))
3425                                         resample_buff_len *= 2;
3426                                 resample_buff = (SAMPLE *) g_realloc(resample_buff, resample_buff_len);
3427                         }
3428
3429                         speex_resampler_process_int(audio_resampler_, 0, decode_buff, &in_len, resample_buff, &out_len);
3430                         write_buff = (char *) resample_buff;
3431                         write_bytes = out_len * sample_bytes_;
3432                 }
3433
3434                 /* Write the decoded, possibly-resampled audio */
3435                 for (i = 0; i < write_bytes; i++)
3436                         json_print_base64_step(&write_buff[i], &base64_state1, &base64_state2);
3437
3438                 g_free(decode_buff);
3439         }
3440
3441         json_print_base64_step(NULL, &base64_state1, &base64_state2);
3442
3443         g_free(resample_buff);
3444         g_hash_table_destroy(decoders_hash_);
3445 }
3446
3447 static gboolean
3448 sharkd_session_packet_download_tap_rtp_cb(void *tapdata, packet_info *pinfo, epan_dissect_t *edt _U_, const void *data)
3449 {
3450         const struct _rtp_info *rtp_info = (const struct _rtp_info *) data;
3451         struct sharkd_download_rtp *req_rtp = (struct sharkd_download_rtp *) tapdata;
3452
3453         /* do not consider RTP packets without a setup frame */
3454         if (rtp_info->info_setup_frame_num == 0)
3455                 return FALSE;
3456
3457         if (sharkd_rtp_match_check(&req_rtp->rtp, pinfo, rtp_info))
3458         {
3459                 rtp_packet_t *rtp_packet;
3460
3461                 rtp_packet = g_new0(rtp_packet_t, 1);
3462                 rtp_packet->info = (struct _rtp_info *) g_memdup(rtp_info, sizeof(struct _rtp_info));
3463
3464                 if (rtp_info->info_all_data_present && rtp_info->info_payload_len != 0)
3465                         rtp_packet->payload_data = (guint8 *) g_memdup(&(rtp_info->info_data[rtp_info->info_payload_offset]), rtp_info->info_payload_len);
3466
3467                 if (!req_rtp->packets)
3468                         req_rtp->start_time = nstime_to_sec(&pinfo->abs_ts);
3469
3470                 rtp_packet->frame_num = pinfo->num;
3471                 rtp_packet->arrive_offset = nstime_to_sec(&pinfo->abs_ts) - req_rtp->start_time;
3472
3473                 /* XXX, O(n) optimize */
3474                 req_rtp->packets = g_slist_append(req_rtp->packets, rtp_packet);
3475         }
3476
3477         return FALSE;
3478 }
3479
3480 /**
3481  * sharkd_session_process_download()
3482  *
3483  * Process download request
3484  *
3485  * Input:
3486  *   (m) token  - token to download
3487  *
3488  * Output object with attributes:
3489  *   (o) file - suggested name of file
3490  *   (o) mime - suggested content type
3491  *   (o) data - payload base64 encoded
3492  */
3493 static void
3494 sharkd_session_process_download(char *buf, const jsmntok_t *tokens, int count)
3495 {
3496         const char *tok_token      = json_find_attr(buf, tokens, count, "token");
3497
3498         if (!tok_token)
3499                 return;
3500
3501         if (!strncmp(tok_token, "eo:", 3))
3502         {
3503                 struct sharkd_export_object_list *object_list;
3504                 const export_object_entry_t *eo_entry = NULL;
3505
3506                 for (object_list = sharkd_eo_list; object_list; object_list = object_list->next)
3507                 {
3508                         size_t eo_type_len = strlen(object_list->type);
3509
3510                         if (!strncmp(tok_token, object_list->type, eo_type_len) && tok_token[eo_type_len] == '_')
3511                         {
3512                                 int row;
3513
3514                                 if (sscanf(&tok_token[eo_type_len + 1], "%d", &row) != 1)
3515                                         break;
3516
3517                                 eo_entry = (export_object_entry_t *) g_slist_nth_data(object_list->entries, row);
3518                                 break;
3519                         }
3520                 }
3521
3522                 if (eo_entry)
3523                 {
3524                         const char *mime     = (eo_entry->content_type) ? eo_entry->content_type : "application/octet-stream";
3525                         const char *filename = (eo_entry->filename) ? eo_entry->filename : tok_token;
3526
3527                         printf("{\"file\":");
3528                         json_puts_string(filename);
3529                         printf(",\"mime\":");
3530                         json_puts_string(mime);
3531                         printf(",\"data\":");
3532                         json_print_base64(eo_entry->payload_data, (int) eo_entry->payload_len); /* XXX, export object will be truncated if >= 2^31 */
3533                         printf("}\n");
3534                 }
3535         }
3536         else if (!strcmp(tok_token, "ssl-secrets"))
3537         {
3538                 char *str = ssl_export_sessions();
3539
3540                 if (str)
3541                 {
3542                         const char *mime     = "text/plain";
3543                         const char *filename = "keylog.txt";
3544
3545                         printf("{\"file\":");
3546                         json_puts_string(filename);
3547                         printf(",\"mime\":");
3548                         json_puts_string(mime);
3549                         printf(",\"data\":");
3550                         json_print_base64(str, strlen(str));
3551                         printf("}\n");
3552                 }
3553                 g_free(str);
3554         }
3555         else if (!strncmp(tok_token, "rtp:", 4))
3556         {
3557                 struct sharkd_download_rtp rtp_req;
3558                 GString *tap_error;
3559
3560                 memset(&rtp_req, 0, sizeof(rtp_req));
3561                 if (!sharkd_rtp_match_init(&rtp_req.rtp, tok_token + 4))
3562                 {
3563                         fprintf(stderr, "sharkd_session_process_download() rtp tokenizing error %s\n", tok_token);
3564                         return;
3565                 }
3566
3567                 tap_error = register_tap_listener("rtp", &rtp_req, NULL, 0, NULL, sharkd_session_packet_download_tap_rtp_cb, NULL);
3568                 if (tap_error)
3569                 {
3570                         fprintf(stderr, "sharkd_session_process_download() rtp error=%s", tap_error->str);
3571                         g_string_free(tap_error, TRUE);
3572                         return;
3573                 }
3574
3575                 sharkd_retap();
3576                 remove_tap_listener(&rtp_req);
3577
3578                 if (rtp_req.packets)
3579                 {
3580                         const char *mime     = "audio/x-wav";
3581                         const char *filename = tok_token;
3582
3583                         printf("{\"file\":");
3584                         json_puts_string(filename);
3585                         printf(",\"mime\":");
3586                         json_puts_string(mime);
3587
3588                         printf(",\"data\":");
3589                         putchar('"');
3590                         sharkd_rtp_download_decode(&rtp_req);
3591                         putchar('"');
3592
3593                         printf("}\n");
3594
3595                         g_slist_free_full(rtp_req.packets, sharkd_rtp_download_free_items);
3596                 }
3597         }
3598 }
3599
3600 static void
3601 sharkd_session_process(char *buf, const jsmntok_t *tokens, int count)
3602 {
3603         int i;
3604
3605         /* sanity check, and split strings */
3606         if (count < 1 || tokens[0].type != JSMN_OBJECT)
3607         {
3608                 fprintf(stderr, "sanity check(1): [0] not object\n");
3609                 return;
3610         }
3611
3612         /* don't need [0] token */
3613         tokens++;
3614         count--;
3615
3616         if (count & 1)
3617         {
3618                 fprintf(stderr, "sanity check(2): %d not even\n", count);
3619                 return;
3620         }
3621
3622         for (i = 0; i < count; i += 2)
3623         {
3624                 if (tokens[i].type != JSMN_STRING)
3625                 {
3626                         fprintf(stderr, "sanity check(3): [%d] not string\n", i);
3627                         return;
3628                 }
3629
3630                 buf[tokens[i + 0].end] = '\0';
3631                 buf[tokens[i + 1].end] = '\0';
3632
3633                 json_unescape_str(&buf[tokens[i + 0].start]);
3634                 json_unescape_str(&buf[tokens[i + 1].start]);
3635         }
3636
3637         {
3638                 const char *tok_req = json_find_attr(buf, tokens, count, "req");
3639
3640                 if (!tok_req)
3641                 {
3642                         fprintf(stderr, "sanity check(4): no \"req\".\n");
3643                         return;
3644                 }
3645
3646                 if (!strcmp(tok_req, "load"))
3647                         sharkd_session_process_load(buf, tokens, count);
3648                 else if (!strcmp(tok_req, "status"))
3649                         sharkd_session_process_status();
3650                 else if (!strcmp(tok_req, "analyse"))
3651                         sharkd_session_process_analyse();
3652                 else if (!strcmp(tok_req, "info"))
3653                         sharkd_session_process_info();
3654                 else if (!strcmp(tok_req, "check"))
3655                         sharkd_session_process_check(buf, tokens, count);
3656                 else if (!strcmp(tok_req, "complete"))
3657                         sharkd_session_process_complete(buf, tokens, count);
3658                 else if (!strcmp(tok_req, "frames"))
3659                         sharkd_session_process_frames(buf, tokens, count);
3660                 else if (!strcmp(tok_req, "tap"))
3661                         sharkd_session_process_tap(buf, tokens, count);
3662                 else if (!strcmp(tok_req, "follow"))
3663                         sharkd_session_process_follow(buf, tokens, count);
3664                 else if (!strcmp(tok_req, "intervals"))
3665                         sharkd_session_process_intervals(buf, tokens, count);
3666                 else if (!strcmp(tok_req, "frame"))
3667                         sharkd_session_process_frame(buf, tokens, count);
3668                 else if (!strcmp(tok_req, "setconf"))
3669                         sharkd_session_process_setconf(buf, tokens, count);
3670                 else if (!strcmp(tok_req, "dumpconf"))
3671                         sharkd_session_process_dumpconf(buf, tokens, count);
3672                 else if (!strcmp(tok_req, "download"))
3673                         sharkd_session_process_download(buf, tokens, count);
3674                 else if (!strcmp(tok_req, "bye"))
3675                         exit(0);
3676                 else
3677                         fprintf(stderr, "::: req = %s\n", tok_req);
3678
3679                 /* reply for every command are 0+ lines of JSON reply (outputed above), finished by empty new line */
3680                 printf("\n");
3681
3682                 /*
3683                  * We do an explicit fflush after every line, because
3684                  * we want output to be written to the socket as soon
3685                  * as the line is complete.
3686                  *
3687                  * The stream is fully-buffered by default, so it's
3688                  * only flushed when the buffer fills or the FILE *
3689                  * is closed.  On UN*X, we could set it to be line
3690                  * buffered, but the MSVC standard I/O routines don't
3691                  * support line buffering - they only support *byte*
3692                  * buffering, doing a write for every byte written,
3693                  * which is too inefficient, and full buffering,
3694                  * which is what you get if you request line buffering.
3695                  */
3696                 fflush(stdout);
3697         }
3698 }
3699
3700 int
3701 sharkd_session_main(void)
3702 {
3703         char buf[2 * 1024];
3704         jsmntok_t *tokens = NULL;
3705         int tokens_max = -1;
3706
3707         fprintf(stderr, "Hello in child.\n");
3708
3709         while (fgets(buf, sizeof(buf), stdin))
3710         {
3711                 /* every command is line seperated JSON */
3712                 int ret;
3713
3714                 ret = wsjsmn_parse(buf, NULL, 0);
3715                 if (ret < 0)
3716                 {
3717                         fprintf(stderr, "invalid JSON -> closing\n");
3718                         return 1;
3719                 }
3720
3721                 /* fprintf(stderr, "JSON: %d tokens\n", ret); */
3722                 ret += 1;
3723
3724                 if (tokens == NULL || tokens_max < ret)
3725                 {
3726                         tokens_max = ret;
3727                         tokens = (jsmntok_t *) g_realloc(tokens, sizeof(jsmntok_t) * tokens_max);
3728                 }
3729
3730                 memset(tokens, 0, ret * sizeof(jsmntok_t));
3731
3732                 ret = wsjsmn_parse(buf, tokens, ret);
3733                 if (ret < 0)
3734                 {
3735                         fprintf(stderr, "invalid JSON(2) -> closing\n");
3736                         return 2;
3737                 }
3738
3739                 sharkd_session_process(buf, tokens, ret);
3740         }
3741
3742         g_free(tokens);
3743
3744         return 0;
3745 }
3746
3747 /*
3748  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
3749  *
3750  * Local variables:
3751  * c-basic-offset: 8
3752  * tab-width: 8
3753  * indent-tabs-mode: t
3754  * End:
3755  *
3756  * vi: set shiftwidth=8 tabstop=8 noexpandtab:
3757  * :indentSize=8:tabSize=8:noTabs=false:
3758  */