attr_dissector_fn_t
[wireshark-sm.git] / sharkd_session.c
blobf5d00eef5e4c67cec05d4b2fa3a15987d2ca3416
1 /* sharkd_session.c
3 * Copyright (C) 2016 Jakub Zawadzki
5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * SPDX-License-Identifier: GPL-2.0-or-later
12 #include <config.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <stdarg.h>
17 #include <string.h>
18 #include <errno.h>
19 #include <inttypes.h>
21 #include <glib.h>
23 #include <wsutil/wsjson.h>
24 #include <wsutil/json_dumper.h>
25 #include <wsutil/ws_assert.h>
26 #include <wsutil/wsgcrypt.h>
28 #include <file.h>
29 #include <epan/epan_dissect.h>
30 #include <epan/exceptions.h>
31 #include <epan/color_filters.h>
32 #include <epan/prefs.h>
33 #include <epan/prefs-int.h>
34 #include <epan/uat-int.h>
35 #include <wiretap/wtap.h>
37 #include <epan/column.h>
38 #include <epan/column-info.h>
40 #include <ui/ssl_key_export.h>
42 #include <ui/io_graph_item.h>
43 #include <epan/stats_tree_priv.h>
44 #include <epan/stat_tap_ui.h>
45 #include <epan/conversation_table.h>
46 #include <epan/sequence_analysis.h>
47 #include <epan/expert.h>
48 #include <epan/export_object.h>
49 #include <epan/follow.h>
50 #include <epan/rtd_table.h>
51 #include <epan/srt_table.h>
52 #include <epan/to_str.h>
54 #include <epan/dissectors/packet-h225.h>
55 #include <epan/rtp_pt.h>
56 #include <ui/voip_calls.h>
57 #include <ui/rtp_stream.h>
58 #include <ui/tap-rtp-common.h>
59 #include <ui/tap-rtp-analysis.h>
60 #include <ui/cli/tap-protohierstat.h>
61 #include <ui/cli/tap-voip.h>
62 #include <wsutil/version_info.h>
63 #include <epan/to_str.h>
65 #include <epan/addr_resolv.h>
66 #include <epan/dissectors/packet-rtp.h>
67 #include <ui/rtp_media.h>
68 #include <ui/mcast_stream.h>
69 #include <speex/speex_resampler.h>
71 #include <epan/maxmind_db.h>
73 #include <wsutil/pint.h>
74 #include <wsutil/strnatcmp.h>
75 #include <wsutil/strtoi.h>
77 #include "globals.h"
79 #include "sharkd.h"
81 struct sharkd_filter_item
83 uint8_t *filtered; /* can be NULL if all frames are matching for given filter. */
86 static GHashTable *filter_table;
88 static int mode;
89 static uint32_t rpcid;
91 static json_dumper dumper;
94 static const char *
95 json_find_attr(const char *buf, const jsmntok_t *tokens, int count, const char *attr)
97 int i;
99 for (i = 0; i < count; i += 2)
101 const char *tok_attr = &buf[tokens[i + 0].start];
102 const char *tok_value = &buf[tokens[i + 1].start];
104 if (!strcmp(tok_attr, attr))
105 return tok_value;
108 return NULL;
111 static void
112 json_print_base64(const uint8_t *data, size_t len)
114 json_dumper_begin_base64(&dumper);
115 json_dumper_write_base64(&dumper, data, len);
116 json_dumper_end_base64(&dumper);
119 static void G_GNUC_PRINTF(2, 3)
120 sharkd_json_value_anyf(const char *key, const char *format, ...)
122 if (key)
123 json_dumper_set_member_name(&dumper, key);
125 va_list ap;
126 va_start(ap, format);
127 json_dumper_value_va_list(&dumper, format, ap);
128 va_end(ap);
131 static void
132 sharkd_json_value_string(const char *key, const char *str)
134 if (key)
135 json_dumper_set_member_name(&dumper, key);
136 json_dumper_value_string(&dumper, str);
139 static void
140 sharkd_json_value_base64(const char *key, const uint8_t *data, size_t len)
142 if (key)
143 json_dumper_set_member_name(&dumper, key);
144 json_print_base64(data, len);
147 static void G_GNUC_PRINTF(2, 3)
148 sharkd_json_value_stringf(const char *key, const char *format, ...)
150 if (key)
151 json_dumper_set_member_name(&dumper, key);
153 va_list ap;
154 va_start(ap, format);
155 char* sformat = ws_strdup_printf("\"%s\"", format);
156 json_dumper_value_va_list(&dumper, sformat, ap);
157 g_free(sformat);
158 va_end(ap);
161 static void
162 sharkd_json_array_open(const char *key)
164 if (key)
165 json_dumper_set_member_name(&dumper, key);
166 json_dumper_begin_array(&dumper);
169 static void
170 sharkd_json_array_close(void)
172 json_dumper_end_array(&dumper);
175 static void
176 sharkd_json_object_open(const char *key)
178 if (key)
179 json_dumper_set_member_name(&dumper, key);
180 json_dumper_begin_object(&dumper);
183 static void
184 sharkd_json_object_close(void)
186 json_dumper_end_object(&dumper);
189 static void
190 sharkd_json_response_open(uint32_t id)
192 json_dumper_begin_object(&dumper); // start the message
193 sharkd_json_value_string("jsonrpc", "2.0");
194 sharkd_json_value_anyf("id", "%d", id);
197 static void
198 sharkd_json_response_close(void)
200 json_dumper_end_object(&dumper); // end the message
202 json_dumper_finish(&dumper);
205 * We do an explicit fflush after every line, because
206 * we want output to be written to the socket as soon
207 * as the line is complete.
209 * The stream is fully-buffered by default, so it's
210 * only flushed when the buffer fills or the FILE *
211 * is closed. On UN*X, we could set it to be line
212 * buffered, but the MSVC standard I/O routines don't
213 * support line buffering - they only support *byte*
214 * buffering, doing a write for every byte written,
215 * which is too inefficient, and full buffering,
216 * which is what you get if you request line buffering.
218 fflush(stdout);
221 static void
222 sharkd_json_result_prologue(uint32_t id)
224 sharkd_json_response_open(id);
225 sharkd_json_object_open("result"); // start the result object
228 static void
229 sharkd_json_result_epilogue(void)
231 json_dumper_end_object(&dumper); // end the result object
232 sharkd_json_response_close();
235 static void
236 sharkd_json_result_array_prologue(uint32_t id)
238 sharkd_json_response_open(id);
239 sharkd_json_array_open("result"); // start the result array
242 static void
243 sharkd_json_result_array_epilogue(void)
245 sharkd_json_array_close(); // end of result array
246 sharkd_json_response_close();
249 static void
250 sharkd_json_simple_ok(uint32_t id)
252 sharkd_json_result_prologue(id);
253 sharkd_json_value_string("status", "OK");
254 sharkd_json_result_epilogue();
257 static void
258 sharkd_json_warning(uint32_t id, char *warning)
260 sharkd_json_result_prologue(id);
261 sharkd_json_value_string("status", "Warning");
262 sharkd_json_value_string("warning", warning);
263 sharkd_json_result_epilogue();
266 static void G_GNUC_PRINTF(4, 5)
267 sharkd_json_error(uint32_t id, int code, char* data, char* format, ...)
269 sharkd_json_response_open(id);
270 sharkd_json_object_open("error");
271 sharkd_json_value_anyf("code", "%d", code);
273 if (format)
275 // format the text message
276 va_list args;
278 va_start(args, format);
279 char *error_msg = ws_strdup_vprintf(format, args);
280 va_end(args);
282 sharkd_json_value_string("message", error_msg);
284 g_free(error_msg);
287 sharkd_json_object_close();
289 if (data)
290 sharkd_json_value_string("data", data);
292 sharkd_json_response_close();
295 static bool
296 is_param_match(const char *param_in, const char *valid_param)
298 char* ptr;
300 if ((ptr = g_strrstr(valid_param, "*")))
302 size_t prefix_len = ptr - valid_param;
303 return !strncmp(param_in, valid_param, prefix_len);
305 else
306 return !strcmp(param_in, valid_param);
310 * json_prep does four things:
312 * 1. check the syntax of the root and parameter members
313 * 2. tokenize the names and values by zero terminating them
314 * 3. unescape the names and values
315 * 4. extracts and saves the rpcid
316 * - we have to do it here as it's needed for the error messages
318 * The objective is to minimise the validation work in the functions
319 * that process each called method.
321 * This gets a little messy as the JSON parser creates a flat list
322 * of all members rather than create a tree.
324 static bool
325 json_prep(char* buf, const jsmntok_t* tokens, int count)
327 int i;
328 const char* method = NULL;
329 char* attr_name = NULL;
330 char* attr_value = NULL;
332 #define SHARKD_JSON_ANY 0
333 #define SHARKD_JSON_STRING 1
334 #define SHARKD_JSON_INTEGER 2
335 #define SHARKD_JSON_UINTEGER 3
336 #define SHARKD_JSON_FLOAT 4
337 #define SHARKD_JSON_OBJECT 5
338 #define SHARKD_JSON_ARRAY 6
339 #define SHARKD_JSON_BOOLEAN 7
340 #define SHARKD_ARRAY_END 99
342 struct member_attribute {
343 const char* parent_ctx;
344 const char* name;
345 int level;
346 jsmntype_t type;
347 int value_type;
348 bool is_mandatory;
351 #define SHARKD_MANDATORY true
352 #define SHARKD_OPTIONAL false
355 * The member attribute structure is key to the syntax checking. The
356 * array contains all of the root level (1) member names, the data
357 * types permissible for the value and a boolean that indicates whether
358 * or not the member is mandatory.
360 * Once we get into the next layer (2) of the json tree, we need to check
361 * params member names and data types dependent in the context of the method
362 * (parent_ctx).
365 struct member_attribute name_array[] = {
366 // Root members
367 {NULL, "jsonrpc", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_MANDATORY},
368 {NULL, "userid", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
369 {NULL, "id", 1, JSMN_PRIMITIVE, SHARKD_JSON_UINTEGER, SHARKD_MANDATORY},
370 {NULL, "method", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_MANDATORY},
371 {NULL, "params", 1, JSMN_OBJECT, SHARKD_JSON_OBJECT, SHARKD_OPTIONAL},
373 // Valid methods
374 {"method", "analyse", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
375 {"method", "bye", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
376 {"method", "check", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
377 {"method", "complete", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
378 {"method", "download", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
379 {"method", "dumpconf", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
380 {"method", "follow", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
381 {"method", "frame", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
382 {"method", "frames", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
383 {"method", "info", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
384 {"method", "intervals", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
385 {"method", "iograph", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
386 {"method", "load", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
387 {"method", "setcomment", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
388 {"method", "setconf", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
389 {"method", "status", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
390 {"method", "tap", 1, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
392 // Parameters and their method context
393 {"check", "field", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
394 {"check", "filter", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
395 {"complete", "field", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
396 {"complete", "pref", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
397 {"download", "token", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
398 {"dumpconf", "pref", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
399 {"follow", "follow", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_MANDATORY},
400 {"follow", "filter", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_MANDATORY},
401 {"follow", "sub_stream", 2, JSMN_PRIMITIVE, SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
402 {"frame", "frame", 2, JSMN_PRIMITIVE, SHARKD_JSON_UINTEGER, SHARKD_MANDATORY},
403 {"frame", "proto", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
404 {"frame", "ref_frame", 2, JSMN_PRIMITIVE, SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
405 {"frame", "prev_frame", 2, JSMN_PRIMITIVE, SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
406 {"frame", "columns", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
407 {"frame", "color", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
408 {"frame", "bytes", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
409 {"frame", "hidden", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
410 {"frames", "column*", 2, JSMN_UNDEFINED, SHARKD_JSON_ANY, SHARKD_OPTIONAL},
411 {"frames", "filter", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
412 {"frames", "skip", 2, JSMN_PRIMITIVE, SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
413 {"frames", "limit", 2, JSMN_PRIMITIVE, SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
414 {"frames", "refs", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
415 {"intervals", "interval", 2, JSMN_PRIMITIVE, SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
416 {"intervals", "filter", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
417 {"iograph", "interval", 2, JSMN_PRIMITIVE, SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
418 {"iograph", "interval_units", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
419 {"iograph", "filter", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
420 {"iograph", "graph0", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_MANDATORY},
421 {"iograph", "graph1", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
422 {"iograph", "graph2", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
423 {"iograph", "graph3", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
424 {"iograph", "graph4", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
425 {"iograph", "graph5", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
426 {"iograph", "graph6", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
427 {"iograph", "graph7", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
428 {"iograph", "graph8", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
429 {"iograph", "graph9", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
430 {"iograph", "filter0", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
431 {"iograph", "filter1", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
432 {"iograph", "filter2", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
433 {"iograph", "filter3", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
434 {"iograph", "filter4", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
435 {"iograph", "filter5", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
436 {"iograph", "filter6", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
437 {"iograph", "filter7", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
438 {"iograph", "filter8", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
439 {"iograph", "filter9", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
440 {"iograph", "aot0", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
441 {"iograph", "aot1", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
442 {"iograph", "aot2", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
443 {"iograph", "aot3", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
444 {"iograph", "aot4", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
445 {"iograph", "aot5", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
446 {"iograph", "aot6", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
447 {"iograph", "aot7", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
448 {"iograph", "aot8", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
449 {"iograph", "aot9", 2, JSMN_PRIMITIVE, SHARKD_JSON_BOOLEAN, SHARKD_OPTIONAL},
450 {"load", "file", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_MANDATORY},
451 {"setcomment", "frame", 2, JSMN_PRIMITIVE, SHARKD_JSON_UINTEGER, SHARKD_MANDATORY},
452 {"setcomment", "comment", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
453 {"setconf", "name", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_MANDATORY},
454 {"setconf", "value", 2, JSMN_UNDEFINED, SHARKD_JSON_ANY, SHARKD_MANDATORY},
455 {"tap", "tap0", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_MANDATORY},
456 {"tap", "tap1", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
457 {"tap", "tap2", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
458 {"tap", "tap3", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
459 {"tap", "tap4", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
460 {"tap", "tap5", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
461 {"tap", "tap6", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
462 {"tap", "tap7", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
463 {"tap", "tap8", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
464 {"tap", "tap9", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
465 {"tap", "tap10", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
466 {"tap", "tap11", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
467 {"tap", "tap12", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
468 {"tap", "tap13", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
469 {"tap", "tap14", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
470 {"tap", "tap15", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
471 {"tap", "filter", 2, JSMN_STRING, SHARKD_JSON_STRING, SHARKD_OPTIONAL},
473 // End of the name_array
474 {NULL, NULL, 0, JSMN_STRING, SHARKD_ARRAY_END, SHARKD_OPTIONAL},
477 rpcid = 0;
479 /* sanity check, and split strings */
480 if (count < 1 || tokens[0].type != JSMN_OBJECT)
482 sharkd_json_error(
483 rpcid, -32600, NULL,
484 "The request must an object"
486 return false;
489 /* don't need [0] token */
490 tokens++;
491 count--;
493 if (count & 1)
495 sharkd_json_error(
496 rpcid, -32600, NULL,
497 "The request must contain name/value pairs"
499 return false;
502 for (i = 0; i < count; i += 2)
504 buf[tokens[i + 0].end] = '\0';
505 buf[tokens[i + 1].end] = '\0';
508 // we must get the id as soon as possible so that it's available in all future error messages
509 attr_value = (char*)json_find_attr(buf, tokens, count, "id");
510 if (attr_value)
512 if (!ws_strtou32(attr_value, NULL, &rpcid))
514 sharkd_json_error(
515 rpcid, -32600, NULL,
516 "The id value must be a positive integer"
518 return false;
522 method = json_find_attr(buf, tokens, count, "method");
524 if (method)
526 bool is_supported = false;
527 i = 0; // name array index
529 // check that the request method is good
530 while (name_array[i].value_type != SHARKD_ARRAY_END)
532 if (name_array[i].parent_ctx)
534 if (!strcmp(method, name_array[i].name) && !strcmp(name_array[i].parent_ctx, "method"))
535 is_supported = true; // the method is valid
538 i++;
541 if (!is_supported)
543 sharkd_json_error(
544 rpcid, -32601, NULL,
545 "The method %s is not supported", method
547 return false;
551 for (i = 0; i < count; i += 2)
553 if (tokens[i].type != JSMN_STRING)
555 sharkd_json_error(
556 rpcid, -32600, NULL,
557 "Member names must be a string - member %d is not string", (i / 2) + 1
559 return false;
562 attr_name = &buf[tokens[i + 0].start];
563 attr_value = &buf[tokens[i + 1].start];
565 if (!strcmp(attr_name, "jsonrpc"))
567 if (strcmp(&buf[tokens[i + 1].start], "2.0"))
569 sharkd_json_error(
570 rpcid, -32600, NULL,
571 "Only JSON %s is supported", "2.0"
573 return false;
577 /* unescape only value, as keys are simple strings */
578 if (tokens[i + 1].type == JSMN_STRING && !json_decode_string_inplace(attr_value))
580 sharkd_json_error(
581 rpcid, -32600, NULL,
582 "Cannot unescape the value string of member %d", (i / 2) + 1
584 return false;
587 /* Confirm that the member is valid */
588 bool match = false;
590 // We need to check root members (level 1) and parameters (level 2), hence the for loop.
592 for (int level = 1; level < 3; level++)
594 size_t j = 0;
596 while (name_array[j].value_type != SHARKD_ARRAY_END) // iterate through the array until we hit the end
598 if (is_param_match(attr_name, name_array[j].name) && name_array[j].level == level)
600 // We need to be sure the match is in the correct context
601 // i.e. is this a match for a root member (level 1) or for a parameter (level 2).
603 if (level == 1)
605 // need to guard against a parameter name matching a method name
606 if (method)
608 if (name_array[j].parent_ctx)
610 j++;
611 continue;
614 if (!strcmp(method, &buf[tokens[i + 0].start]))
616 j++;
617 continue;
621 match = true;
623 else if (method)
625 if (level == 2 && !strcmp(name_array[j].parent_ctx, method))
626 match = true;
627 else
629 j++;
630 continue;
633 else
635 j++;
636 continue;
639 // The match looks good, let's now check the data types
641 if (tokens[i + 1].type != name_array[j].type && name_array[j].type != SHARKD_JSON_ANY)
643 sharkd_json_error(
644 rpcid, -32600, NULL,
645 "The data type for member %s is not valid", attr_name
647 return false;
649 else if (name_array[j].type == JSMN_PRIMITIVE && name_array[j].value_type == SHARKD_JSON_UINTEGER)
651 uint32_t temp;
652 if (!ws_strtou32(attr_value, NULL, &temp) || temp <= 0)
654 sharkd_json_error(
655 rpcid, -32600, NULL,
656 "The value for %s must be a positive integer", name_array[j].name
658 return false;
661 else if (name_array[j].type == JSMN_PRIMITIVE && name_array[j].value_type == SHARKD_JSON_BOOLEAN)
663 if (strcmp(attr_value, "true") && strcmp(attr_value, "false"))
665 sharkd_json_error(
666 rpcid, -32600, NULL,
667 "The value for %s must be a boolean (true or false)", name_array[j].name
669 return false;
673 break; // looks like a valid match
675 j++;
679 if (!match)
681 sharkd_json_error(
682 rpcid, -32600, NULL,
683 "%s is not a valid member name", attr_name
685 return false;
689 /* check for mandatory members */
690 size_t j = 0;
692 while (name_array[j].value_type != SHARKD_ARRAY_END)
694 if (name_array[j].is_mandatory && name_array[j].level == 1)
696 if (!json_find_attr(buf, tokens, count, name_array[j].name))
698 sharkd_json_error(
699 rpcid, -32600, NULL,
700 "Mandatory member %s is missing", name_array[j].name
702 return false;
705 j++;
708 // check that the current request contains the mandatory parameters
709 j = 0;
711 while (name_array[j].value_type != SHARKD_ARRAY_END)
713 if (name_array[j].is_mandatory && name_array[j].level == 2 && !strcmp(method, name_array[j].parent_ctx))
715 if (!json_find_attr(buf, tokens, count, name_array[j].name))
717 sharkd_json_error(
718 rpcid, -32600, NULL,
719 "Mandatory parameter %s is missing", name_array[j].name
721 return false;
724 j++;
728 // check that the parameters for the current request are valid for the method and that the data type for the value is valid
730 return true;
733 static void
734 sharkd_session_filter_free(void *data)
736 struct sharkd_filter_item *l = (struct sharkd_filter_item *) data;
738 g_free(l->filtered);
739 g_free(l);
742 static const struct sharkd_filter_item *
743 sharkd_session_filter_data(const char *filter)
745 struct sharkd_filter_item *l;
747 l = (struct sharkd_filter_item *) g_hash_table_lookup(filter_table, filter);
748 if (!l)
750 uint8_t *filtered = NULL;
752 int ret = sharkd_filter(filter, &filtered);
754 if (ret == -1)
755 return NULL;
757 l = g_new(struct sharkd_filter_item, 1);
758 l->filtered = filtered;
760 g_hash_table_insert(filter_table, g_strdup(filter), l);
763 return l;
766 static bool
767 sharkd_rtp_match_init(rtpstream_id_t *id, const char *init_str)
769 bool ret = false;
770 char **arr;
771 uint32_t tmp_addr_src, tmp_addr_dst;
772 address tmp_src_addr, tmp_dst_addr;
774 memset(id, 0, sizeof(*id));
776 arr = g_strsplit(init_str, "_", 7); /* pass larger value, so we'll catch incorrect input :) */
777 if (g_strv_length(arr) != 5)
778 goto fail;
780 /* TODO, for now only IPv4 */
781 if (!get_host_ipaddr(arr[0], &tmp_addr_src))
782 goto fail;
784 if (!ws_strtou16(arr[1], NULL, &id->src_port))
785 goto fail;
787 if (!get_host_ipaddr(arr[2], &tmp_addr_dst))
788 goto fail;
790 if (!ws_strtou16(arr[3], NULL, &id->dst_port))
791 goto fail;
793 if (!ws_hexstrtou32(arr[4], NULL, &id->ssrc))
794 goto fail;
796 set_address(&tmp_src_addr, AT_IPv4, 4, &tmp_addr_src);
797 copy_address(&id->src_addr, &tmp_src_addr);
798 set_address(&tmp_dst_addr, AT_IPv4, 4, &tmp_addr_dst);
799 copy_address(&id->dst_addr, &tmp_dst_addr);
801 ret = true;
803 fail:
804 g_strfreev(arr);
805 return ret;
808 static bool
809 sharkd_session_process_info_nstat_cb(const void *key, void *value, void *userdata _U_)
811 stat_tap_table_ui *stat_tap = (stat_tap_table_ui *) value;
813 json_dumper_begin_object(&dumper);
814 sharkd_json_value_string("name", stat_tap->title);
815 sharkd_json_value_stringf("tap", "nstat:%s", (const char *) key);
816 json_dumper_end_object(&dumper);
818 return false;
821 static bool
822 sharkd_session_process_info_conv_cb(const void* key, void* value, void* userdata _U_)
824 struct register_ct *table = (struct register_ct *) value;
826 const char *label = (const char *) key;
828 if (get_conversation_packet_func(table))
830 json_dumper_begin_object(&dumper);
831 sharkd_json_value_stringf("name", "Conversation List/%s", label);
832 sharkd_json_value_stringf("tap", "conv:%s", label);
833 json_dumper_end_object(&dumper);
836 if (get_endpoint_packet_func(table))
838 json_dumper_begin_object(&dumper);
839 sharkd_json_value_stringf("name", "Endpoint/%s", label);
840 sharkd_json_value_stringf("tap", "endpt:%s", label);
841 json_dumper_end_object(&dumper);
843 return false;
846 static bool
847 sharkd_session_seq_analysis_cb(const void *key, void *value, void *userdata _U_)
849 register_analysis_t *analysis = (register_analysis_t *) value;
851 json_dumper_begin_object(&dumper);
852 sharkd_json_value_string("name", sequence_analysis_get_ui_name(analysis));
853 sharkd_json_value_stringf("tap", "seqa:%s", (const char *) key);
854 json_dumper_end_object(&dumper);
856 return false;
859 static bool
860 sharkd_export_object_visit_cb(const void *key _U_, void *value, void *user_data _U_)
862 register_eo_t *eo = (register_eo_t *) value;
864 const int proto_id = get_eo_proto_id(eo);
865 const char *filter = proto_get_protocol_filter_name(proto_id);
866 const char *label = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
868 json_dumper_begin_object(&dumper);
869 sharkd_json_value_stringf("name", "Export Object/%s", label);
870 sharkd_json_value_stringf("tap", "eo:%s", filter);
871 json_dumper_end_object(&dumper);
873 return false;
876 static bool
877 sharkd_srt_visit_cb(const void *key _U_, void *value, void *user_data _U_)
879 register_srt_t *srt = (register_srt_t *) value;
881 const int proto_id = get_srt_proto_id(srt);
882 const char *filter = proto_get_protocol_filter_name(proto_id);
883 const char *label = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
885 json_dumper_begin_object(&dumper);
886 sharkd_json_value_stringf("name", "Service Response Time/%s", label);
887 sharkd_json_value_stringf("tap", "srt:%s", filter);
888 json_dumper_end_object(&dumper);
890 return false;
893 static bool
894 sharkd_rtd_visit_cb(const void *key _U_, void *value, void *user_data _U_)
896 register_rtd_t *rtd = (register_rtd_t *) value;
898 const int proto_id = get_rtd_proto_id(rtd);
899 const char *filter = proto_get_protocol_filter_name(proto_id);
900 const char *label = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
902 json_dumper_begin_object(&dumper);
903 sharkd_json_value_stringf("name", "Response Time Delay/%s", label);
904 sharkd_json_value_stringf("tap", "rtd:%s", filter);
905 json_dumper_end_object(&dumper);
907 return false;
910 static bool
911 sharkd_follower_visit_cb(const void *key _U_, void *value, void *user_data _U_)
913 register_follow_t *follower = (register_follow_t *) value;
915 const int proto_id = get_follow_proto_id(follower);
916 const char *label = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
917 const char *filter = label; /* correct: get_follow_by_name() is registered by short name */
919 json_dumper_begin_object(&dumper);
920 sharkd_json_value_stringf("name", "Follow/%s", label);
921 sharkd_json_value_stringf("tap", "follow:%s", filter);
922 json_dumper_end_object(&dumper);
924 return false;
927 static void
928 sharkd_session_print_capture_types(void)
930 unsigned i;
931 GArray *writable_type_subtypes;
932 writable_type_subtypes = wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME);
933 for (i = 0; i < writable_type_subtypes->len; i++) {
934 int ft = g_array_index(writable_type_subtypes, int, i);
935 sharkd_json_object_open(NULL);
936 sharkd_json_value_string("name", wtap_file_type_subtype_name(ft));
937 sharkd_json_value_string("description", wtap_file_type_subtype_description(ft));
938 sharkd_json_object_close();
940 g_array_free(writable_type_subtypes, TRUE);
943 struct encap_type_info
945 const char *name;
946 const char *description;
949 static int
950 encap_type_info_nat_compare(const void *a, const void *b)
952 return ws_ascii_strnatcmp(((const struct encap_type_info *)a)->name,
953 ((const struct encap_type_info *)b)->name);
956 static void
957 encap_type_info_visit(void *data, void *user_data _U_)
959 sharkd_json_object_open(NULL);
960 sharkd_json_value_string("name", ((struct encap_type_info *)data)->name);
961 sharkd_json_value_string("description", ((struct encap_type_info *)data)->description);
962 sharkd_json_object_close();
965 static void
966 sharkd_session_print_encap_types(void)
968 int i;
969 struct encap_type_info *encaps;
970 GSList *list = NULL;
971 encaps = g_new(struct encap_type_info, WTAP_NUM_ENCAP_TYPES);
972 for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
973 encaps[i].name = wtap_encap_name(i);
974 if (encaps[i].name != NULL) {
975 encaps[i].description = wtap_encap_description(i);
976 list = g_slist_insert_sorted(list, &encaps[i], encap_type_info_nat_compare);
979 g_slist_foreach(list, encap_type_info_visit, NULL);
980 g_slist_free(list);
981 g_free(encaps);
985 * sharkd_session_process_info()
987 * Process info request
989 * Output object with attributes:
990 * (m) version - version number
992 * (m) columns - available column formats, array of object with attributes:
993 * 'name' - column name
994 * 'format' - column format-name
996 * (m) stats - available statistics, array of object with attributes:
997 * 'name' - statistic name
998 * 'tap' - sharkd tap-name for statistic
1000 * (m) convs - available conversation list, array of object with attributes:
1001 * 'name' - conversation name
1002 * 'tap' - sharkd tap-name for conversation
1004 * (m) eo - available export object list, array of object with attributes:
1005 * 'name' - export object name
1006 * 'tap' - sharkd tap-name for eo
1008 * (m) srt - available service response time list, array of object with attributes:
1009 * 'name' - service response time name
1010 * 'tap' - sharkd tap-name for srt
1012 * (m) rtd - available response time delay list, array of object with attributes:
1013 * 'name' - response time delay name
1014 * 'tap' - sharkd tap-name for rtd
1016 * (m) seqa - available sequence analysis (flow) list, array of object with attributes:
1017 * 'name' - sequence analysis name
1018 * 'tap' - sharkd tap-name
1020 * (m) taps - available taps, array of object with attributes:
1021 * 'name' - tap name
1022 * 'tap' - sharkd tap-name
1024 * (m) follow - available followers, array of object with attributes:
1025 * 'name' - tap name
1026 * 'tap' - sharkd tap-name
1028 * (m) ftypes - conversation table for FT_ number to string, array of FT_xxx strings.
1030 * (m) nstat - available table-based taps, array of object with attributes:
1031 * 'name' - tap name
1032 * 'tap' - sharkd tap-name
1034 * (m) capture_types - available capture types, array of object with attributes:
1035 * 'name' - capture type name
1036 * 'description' - capture type description
1038 * (m) encap_types - available encapsulation types, array of object with attributes:
1039 * 'name' - encapsulation type name
1040 * 'description' - encapsulation type description
1042 static void
1043 sharkd_session_process_info(void)
1045 int i;
1047 sharkd_json_result_prologue(rpcid);
1049 sharkd_json_array_open("columns");
1050 for (i = 0; i < NUM_COL_FMTS; i++)
1052 const char *col_format = col_format_to_string(i);
1053 const char *col_descr = col_format_desc(i);
1055 json_dumper_begin_object(&dumper);
1056 sharkd_json_value_string("name", col_descr);
1057 sharkd_json_value_string("format", col_format);
1058 json_dumper_end_object(&dumper);
1060 sharkd_json_array_close();
1062 sharkd_json_array_open("stats");
1064 GList *cfg_list = stats_tree_get_cfg_list();
1065 GList *l;
1067 for (l = cfg_list; l; l = l->next)
1069 stats_tree_cfg *cfg = (stats_tree_cfg *) l->data;
1071 json_dumper_begin_object(&dumper);
1072 sharkd_json_value_string("name", cfg->title);
1073 sharkd_json_value_stringf("tap", "stat:%s", cfg->abbr);
1074 json_dumper_end_object(&dumper);
1077 g_list_free(cfg_list);
1079 sharkd_json_array_close();
1081 sharkd_json_array_open("ftypes");
1082 for (i = 0; i < FT_NUM_TYPES; i++)
1083 sharkd_json_value_string(NULL, ftype_name((ftenum_t) i));
1084 sharkd_json_array_close();
1086 sharkd_json_array_open("capture_types");
1087 sharkd_session_print_capture_types();
1088 sharkd_json_array_close();
1090 sharkd_json_array_open("encap_types");
1091 sharkd_session_print_encap_types();
1092 sharkd_json_array_close();
1094 sharkd_json_value_string("version", get_ws_vcs_version_info_short());
1096 sharkd_json_array_open("nstat");
1097 i = 0;
1098 stat_tap_iterate_tables(sharkd_session_process_info_nstat_cb, &i);
1099 sharkd_json_array_close();
1101 sharkd_json_array_open("convs");
1102 i = 0;
1103 conversation_table_iterate_tables(sharkd_session_process_info_conv_cb, &i);
1104 sharkd_json_array_close();
1106 sharkd_json_array_open("seqa");
1107 i = 0;
1108 sequence_analysis_table_iterate_tables(sharkd_session_seq_analysis_cb, &i);
1109 sharkd_json_array_close();
1111 sharkd_json_array_open("taps");
1113 json_dumper_begin_object(&dumper);
1114 sharkd_json_value_string("name", "UDP Multicast Streams");
1115 sharkd_json_value_string("tap", "multicast");
1116 json_dumper_end_object(&dumper);
1118 json_dumper_begin_object(&dumper);
1119 sharkd_json_value_string("name", "RTP streams");
1120 sharkd_json_value_string("tap", "rtp-streams");
1121 json_dumper_end_object(&dumper);
1123 json_dumper_begin_object(&dumper);
1124 sharkd_json_value_string("name", "Protocol Hierarchy Statistics");
1125 sharkd_json_value_string("tap", "phs");
1126 json_dumper_end_object(&dumper);
1128 json_dumper_begin_object(&dumper);
1129 sharkd_json_value_string("name", "VoIP Calls");
1130 sharkd_json_value_string("tap", "voip-calls");
1131 json_dumper_end_object(&dumper);
1133 json_dumper_begin_object(&dumper);
1134 sharkd_json_value_string("name", "VoIP Conversations");
1135 sharkd_json_value_string("tap", "voip-convs");
1136 json_dumper_end_object(&dumper);
1138 json_dumper_begin_object(&dumper);
1139 sharkd_json_value_string("name", "Expert Information");
1140 sharkd_json_value_string("tap", "expert");
1141 json_dumper_end_object(&dumper);
1143 sharkd_json_array_close();
1145 sharkd_json_array_open("eo");
1146 i = 0;
1147 eo_iterate_tables(sharkd_export_object_visit_cb, &i);
1148 sharkd_json_array_close();
1150 sharkd_json_array_open("srt");
1151 i = 0;
1152 srt_table_iterate_tables(sharkd_srt_visit_cb, &i);
1153 sharkd_json_array_close();
1155 sharkd_json_array_open("rtd");
1156 i = 0;
1157 rtd_table_iterate_tables(sharkd_rtd_visit_cb, &i);
1158 sharkd_json_array_close();
1160 sharkd_json_array_open("follow");
1161 i = 0;
1162 follow_iterate_followers(sharkd_follower_visit_cb, &i);
1163 sharkd_json_array_close();
1165 sharkd_json_result_epilogue();
1169 * sharkd_session_process_load()
1171 * Process load request
1173 * Input:
1174 * (m) file - file to be loaded
1176 * Output object with attributes:
1177 * (m) err - error code
1179 static void
1180 sharkd_session_process_load(const char *buf, const jsmntok_t *tokens, int count)
1182 const char *tok_file = json_find_attr(buf, tokens, count, "file");
1183 int err = 0;
1185 if (!tok_file)
1186 return;
1188 fprintf(stderr, "load: filename=%s\n", tok_file);
1190 if (sharkd_cf_open(tok_file, WTAP_TYPE_AUTO, false, &err) != CF_OK)
1192 sharkd_json_error(
1193 rpcid, -2001, NULL,
1194 "Unable to open the file"
1196 return;
1201 err = sharkd_load_cap_file();
1203 CATCH(OutOfMemoryError)
1205 sharkd_json_error(
1206 rpcid, -32603, NULL,
1207 "Load failed, out of memory"
1209 fprintf(stderr, "load: OutOfMemoryError\n");
1210 err = ENOMEM;
1212 ENDTRY;
1214 if (err == 0)
1216 sharkd_json_simple_ok(rpcid);
1218 else
1220 sharkd_json_result_prologue(rpcid);
1221 sharkd_json_value_string("status", wtap_strerror(err));
1222 sharkd_json_value_anyf("err", "%d", err);
1223 sharkd_json_result_epilogue();
1229 * sharkd_session_process_status()
1231 * Process status request
1233 * Output object with attributes:
1234 * (m) frames - count of currently loaded frames
1235 * (m) duration - time difference between time of first frame, and last loaded frame
1236 * (o) filename - capture filename
1237 * (o) filesize - capture filesize
1238 * (o) columns - array of column titles
1239 * (o) column_info - array of column infos, array of object with attributes:
1240 * 'title' - column title
1241 * 'format' - column format (%x or %Cus:<expr>:<occurrence> if COL_CUSTOM)
1242 * 'visible' - true if column is visible
1243 * 'display' - column display format; 'U', 'R' or 'D'
1245 static void
1246 sharkd_session_process_status(void)
1248 sharkd_json_result_prologue(rpcid);
1250 sharkd_json_value_anyf("frames", "%u", cfile.count);
1251 sharkd_json_value_anyf("duration", "%.9f", nstime_to_sec(&cfile.elapsed_time));
1253 if (cfile.filename)
1255 char *name = g_path_get_basename(cfile.filename);
1257 sharkd_json_value_string("filename", name);
1258 g_free(name);
1261 if (cfile.provider.wth)
1263 int64_t file_size = wtap_file_size(cfile.provider.wth, NULL);
1265 if (file_size > 0)
1266 sharkd_json_value_anyf("filesize", "%" PRId64, file_size);
1269 if (cfile.cinfo.num_cols > 0)
1271 sharkd_json_array_open("columns");
1272 for (int i = 0; i < cfile.cinfo.num_cols; ++i)
1274 sharkd_json_value_string(NULL, get_column_title(i));
1276 sharkd_json_array_close();
1278 sharkd_json_array_open("column_info");
1279 for (int i = 0; i < cfile.cinfo.num_cols; ++i)
1281 int fmt = get_column_format(i);
1282 sharkd_json_object_open(NULL);
1283 sharkd_json_value_string("title", get_column_title(i));
1284 if (fmt != COL_CUSTOM)
1286 sharkd_json_value_string("format", col_format_to_string(fmt));
1287 } else {
1288 sharkd_json_value_stringf("format", "%s:%s:%d", col_format_to_string(fmt), get_column_custom_fields(i), get_column_custom_occurrence(i));
1290 sharkd_json_value_anyf("visible", get_column_visible(i) ? "true" : "false");
1291 sharkd_json_value_stringf("display", "%c", get_column_display_format(i));
1292 sharkd_json_object_close();
1294 sharkd_json_array_close();
1297 sharkd_json_result_epilogue();
1300 struct sharkd_analyse_data
1302 GHashTable *protocols_set;
1303 nstime_t *first_time;
1304 nstime_t *last_time;
1307 static void
1308 sharkd_session_process_analyse_cb(epan_dissect_t *edt, proto_tree *tree _U_,
1309 struct epan_column_info *cinfo _U_, const GSList *data_src _U_, void *data)
1311 struct sharkd_analyse_data *analyser = (struct sharkd_analyse_data *) data;
1312 packet_info *pi = &edt->pi;
1313 frame_data *fdata = pi->fd;
1315 if (analyser->first_time == NULL || nstime_cmp(&fdata->abs_ts, analyser->first_time) < 0)
1316 analyser->first_time = &fdata->abs_ts;
1318 if (analyser->last_time == NULL || nstime_cmp(&fdata->abs_ts, analyser->last_time) > 0)
1319 analyser->last_time = &fdata->abs_ts;
1321 if (pi->layers)
1323 wmem_list_frame_t *frame;
1325 for (frame = wmem_list_head(pi->layers); frame; frame = wmem_list_frame_next(frame))
1327 int proto_id = GPOINTER_TO_UINT(wmem_list_frame_data(frame));
1329 if (!g_hash_table_lookup_extended(analyser->protocols_set, GUINT_TO_POINTER(proto_id), NULL, NULL))
1331 g_hash_table_insert(analyser->protocols_set, GUINT_TO_POINTER(proto_id), GUINT_TO_POINTER(proto_id));
1332 sharkd_json_value_string(NULL, proto_get_protocol_filter_name(proto_id));
1340 * sharkd_session_process_status()
1342 * Process analyse request
1344 * Output object with attributes:
1345 * (m) frames - count of currently loaded frames
1346 * (m) protocols - protocol list
1347 * (m) first - earliest frame time
1348 * (m) last - latest frame time
1350 static void
1351 sharkd_session_process_analyse(void)
1353 struct sharkd_analyse_data analyser;
1354 wtap_rec rec; /* Record metadata */
1355 Buffer rec_buf; /* Record data */
1357 analyser.first_time = NULL;
1358 analyser.last_time = NULL;
1359 analyser.protocols_set = g_hash_table_new(NULL /* g_direct_hash() */, NULL /* g_direct_equal */);
1361 sharkd_json_result_prologue(rpcid);
1363 sharkd_json_value_anyf("frames", "%u", cfile.count);
1365 sharkd_json_array_open("protocols");
1367 wtap_rec_init(&rec);
1368 ws_buffer_init(&rec_buf, 1514);
1370 for (uint32_t framenum = 1; framenum <= cfile.count; framenum++)
1372 enum dissect_request_status status;
1373 int err;
1374 char *err_info;
1376 status = sharkd_dissect_request(framenum,
1377 (framenum != 1) ? 1 : 0, framenum - 1,
1378 &rec, &rec_buf, NULL, SHARKD_DISSECT_FLAG_NULL,
1379 &sharkd_session_process_analyse_cb, &analyser,
1380 &err, &err_info);
1381 switch (status) {
1383 case DISSECT_REQUEST_SUCCESS:
1384 break;
1386 case DISSECT_REQUEST_NO_SUCH_FRAME:
1387 /* XXX - report the error. */
1388 break;
1390 case DISSECT_REQUEST_READ_ERROR:
1392 * Free up the error string.
1393 * XXX - report the error.
1395 g_free(err_info);
1396 break;
1400 sharkd_json_array_close();
1402 if (analyser.first_time)
1403 sharkd_json_value_anyf("first", "%.9f", nstime_to_sec(analyser.first_time));
1405 if (analyser.last_time)
1406 sharkd_json_value_anyf("last", "%.9f", nstime_to_sec(analyser.last_time));
1408 sharkd_json_result_epilogue();
1410 wtap_rec_cleanup(&rec);
1411 ws_buffer_free(&rec_buf);
1413 g_hash_table_destroy(analyser.protocols_set);
1416 static column_info *
1417 sharkd_session_create_columns(column_info *cinfo, const char *buf, const jsmntok_t *tokens, int count)
1419 const char *columns_custom[32];
1420 uint16_t columns_fmt[32];
1421 int16_t columns_occur[32];
1423 int i, cols;
1425 for (i = 0; i < 32; i++)
1427 const char *tok_column;
1428 char tok_column_name[64];
1429 char *custom_sepa;
1431 snprintf(tok_column_name, sizeof(tok_column_name), "column%d", i);
1432 tok_column = json_find_attr(buf, tokens, count, tok_column_name);
1433 if (tok_column == NULL)
1434 break;
1436 columns_custom[i] = NULL;
1437 columns_occur[i] = 0;
1439 if ((custom_sepa = strchr(tok_column, ':')))
1441 *custom_sepa = '\0'; /* XXX, C abuse: discarding-const */
1443 columns_fmt[i] = COL_CUSTOM;
1444 columns_custom[i] = tok_column;
1446 if (!ws_strtoi16(custom_sepa + 1, NULL, &columns_occur[i]))
1447 return NULL;
1449 else
1451 if (!ws_strtou16(tok_column, NULL, &columns_fmt[i]))
1452 return NULL;
1454 if (columns_fmt[i] >= NUM_COL_FMTS)
1455 return NULL;
1457 /* if custom, that it shouldn't be just custom number -> error */
1458 if (columns_fmt[i] == COL_CUSTOM)
1459 return NULL;
1463 cols = i;
1465 col_setup(cinfo, cols);
1467 for (i = 0; i < cols; i++)
1469 col_item_t *col_item = &cinfo->columns[i];
1471 col_item->col_fmt = columns_fmt[i];
1472 col_item->col_title = NULL; /* no need for title */
1474 if (col_item->col_fmt == COL_CUSTOM)
1476 col_item->col_custom_fields = g_strdup(columns_custom[i]);
1477 col_item->col_custom_occurrence = columns_occur[i];
1480 col_item->col_fence = 0;
1483 col_finalize(cinfo);
1485 return cinfo;
1488 static void
1489 sharkd_session_process_frames_cb(epan_dissect_t *edt, proto_tree *tree _U_,
1490 struct epan_column_info *cinfo, const GSList *data_src _U_, void *data _U_)
1492 packet_info *pi = &edt->pi;
1493 frame_data *fdata = pi->fd;
1494 wtap_block_t pkt_block = NULL;
1495 unsigned int i;
1496 char *comment = NULL;
1498 json_dumper_begin_object(&dumper);
1500 sharkd_json_array_open("c");
1501 for (int col = 0; col < cinfo->num_cols; ++col)
1503 sharkd_json_value_string(NULL, get_column_text(cinfo, col));
1505 sharkd_json_array_close();
1507 sharkd_json_value_anyf("num", "%u", pi->num);
1510 * Get the block for this record, if it has one.
1512 pkt_block = sharkd_get_packet_block(fdata);
1515 * Does this record have any comments?
1517 if (pkt_block != NULL &&
1518 WTAP_OPTTYPE_SUCCESS == wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT, 0, &comment))
1520 sharkd_json_value_anyf("ct", "true");
1522 sharkd_json_array_open("comments");
1523 for (i = 0; wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT, i, &comment) == WTAP_OPTTYPE_SUCCESS; i++) {
1524 sharkd_json_value_string(NULL, comment);
1526 sharkd_json_array_close();
1529 if (fdata->ignored)
1530 sharkd_json_value_anyf("i", "true");
1532 if (fdata->marked)
1533 sharkd_json_value_anyf("m", "true");
1535 if (fdata->color_filter)
1537 sharkd_json_value_stringf("bg", "%06x", color_t_to_rgb(&fdata->color_filter->bg_color));
1538 sharkd_json_value_stringf("fg", "%06x", color_t_to_rgb(&fdata->color_filter->fg_color));
1541 wtap_block_unref(pkt_block);
1542 json_dumper_end_object(&dumper);
1546 * sharkd_session_process_frames()
1548 * Process frames request
1550 * Input:
1551 * (o) column0...columnXX - requested columns either number in range [0..NUM_COL_FMTS), or custom (syntax <dfilter>:<occurrence>).
1552 * If column0 is not specified default column set will be used.
1553 * (o) filter - filter to be used
1554 * (o) skip=N - skip N frames
1555 * (o) limit=N - show only N frames
1556 * (o) refs - list (comma separated) with sorted time reference frame numbers.
1558 * Output array of frames with attributes:
1559 * (m) c - array of column data
1560 * (m) num - frame number
1561 * (o) i - if frame is ignored
1562 * (o) m - if frame is marked
1563 * (o) ct - if frame is commented
1564 * (o) comments - array of comment strings
1565 * (o) bg - color filter - background color in hex
1566 * (o) fg - color filter - foreground color in hex
1568 static void
1569 sharkd_session_process_frames(const char *buf, const jsmntok_t *tokens, int count)
1571 const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
1572 const char *tok_column = json_find_attr(buf, tokens, count, "column0");
1573 const char *tok_skip = json_find_attr(buf, tokens, count, "skip");
1574 const char *tok_limit = json_find_attr(buf, tokens, count, "limit");
1575 const char *tok_refs = json_find_attr(buf, tokens, count, "refs");
1577 const uint8_t *filter_data = NULL;
1579 uint32_t prev_dis_num = 0;
1580 uint32_t current_ref_frame = 0, next_ref_frame = UINT32_MAX;
1581 uint32_t skip;
1582 uint32_t limit;
1584 wtap_rec rec; /* Record metadata */
1585 Buffer rec_buf; /* Record data */
1586 column_info *cinfo = &cfile.cinfo;
1587 column_info user_cinfo;
1589 if (tok_column)
1591 memset(&user_cinfo, 0, sizeof(user_cinfo));
1592 cinfo = sharkd_session_create_columns(&user_cinfo, buf, tokens, count);
1593 if (!cinfo)
1595 sharkd_json_error(
1596 rpcid, -13001, NULL,
1597 "Column definition invalid - note column 6 requires a custom definition"
1599 return;
1603 if (tok_filter)
1605 const struct sharkd_filter_item *filter_item;
1607 filter_item = sharkd_session_filter_data(tok_filter);
1608 if (!filter_item)
1610 sharkd_json_error(
1611 rpcid, -13002, NULL,
1612 "Filter expression invalid"
1614 return;
1617 filter_data = filter_item->filtered;
1620 skip = 0;
1621 if (tok_skip)
1623 if (!ws_strtou32(tok_skip, NULL, &skip))
1624 return;
1627 limit = 0;
1628 if (tok_limit)
1630 if (!ws_strtou32(tok_limit, NULL, &limit))
1631 return;
1634 if (tok_refs)
1636 if (!ws_strtou32(tok_refs, &tok_refs, &next_ref_frame))
1637 return;
1640 sharkd_json_result_array_prologue(rpcid);
1642 wtap_rec_init(&rec);
1643 ws_buffer_init(&rec_buf, 1514);
1645 for (uint32_t framenum = 1; framenum <= cfile.count; framenum++)
1647 frame_data *fdata;
1648 uint32_t ref_frame = (framenum != 1) ? 1 : 0;
1649 enum dissect_request_status status;
1650 int err;
1651 char *err_info;
1653 if (filter_data && !(filter_data[framenum / 8] & (1 << (framenum % 8))))
1654 continue;
1656 if (skip)
1658 skip--;
1659 prev_dis_num = framenum;
1660 continue;
1663 if (tok_refs)
1665 if (framenum >= next_ref_frame)
1667 current_ref_frame = next_ref_frame;
1669 if (*tok_refs != ',')
1670 next_ref_frame = UINT32_MAX;
1672 while (*tok_refs == ',' && framenum >= next_ref_frame)
1674 current_ref_frame = next_ref_frame;
1676 if (!ws_strtou32(tok_refs + 1, &tok_refs, &next_ref_frame))
1678 fprintf(stderr, "sharkd_session_process_frames() wrong format for refs: %s\n", tok_refs);
1679 break;
1683 if (*tok_refs == '\0' && framenum >= next_ref_frame)
1685 current_ref_frame = next_ref_frame;
1686 next_ref_frame = UINT32_MAX;
1690 if (current_ref_frame)
1691 ref_frame = current_ref_frame;
1694 fdata = sharkd_get_frame(framenum);
1695 status = sharkd_dissect_request(framenum,
1696 ref_frame, prev_dis_num,
1697 &rec, &rec_buf, cinfo,
1698 (fdata->color_filter == NULL) ? SHARKD_DISSECT_FLAG_COLOR : SHARKD_DISSECT_FLAG_NULL,
1699 &sharkd_session_process_frames_cb, NULL,
1700 &err, &err_info);
1701 switch (status) {
1703 case DISSECT_REQUEST_SUCCESS:
1704 break;
1706 case DISSECT_REQUEST_NO_SUCH_FRAME:
1707 /* XXX - report the error. */
1708 break;
1710 case DISSECT_REQUEST_READ_ERROR:
1712 * Free up the error string.
1713 * XXX - report the error.
1715 g_free(err_info);
1716 break;
1719 prev_dis_num = framenum;
1721 if (limit && --limit == 0)
1722 break;
1724 sharkd_json_result_array_epilogue();
1726 if (cinfo != &cfile.cinfo)
1727 col_cleanup(cinfo);
1729 wtap_rec_cleanup(&rec);
1730 ws_buffer_free(&rec_buf);
1733 static void
1734 sharkd_session_process_tap_stats_node_cb(const char *key, const stat_node *n)
1736 stat_node *node;
1738 sharkd_json_array_open(key);
1739 for (node = n->children; node; node = node->next)
1741 json_dumper_begin_object(&dumper);
1743 /* code based on stats_tree_get_values_from_node() */
1744 sharkd_json_value_string("name", node->name);
1745 sharkd_json_value_anyf("count", "%d", node->counter);
1746 if (node->counter && ((node->st_flags & ST_FLG_AVERAGE) || node->rng))
1748 switch(node->datatype)
1750 case STAT_DT_INT:
1751 sharkd_json_value_anyf("avg", "%.2f", ((float)node->total.int_total) / node->counter);
1752 sharkd_json_value_anyf("min", "%d", node->minvalue.int_min);
1753 sharkd_json_value_anyf("max", "%d", node->maxvalue.int_max);
1754 break;
1755 case STAT_DT_FLOAT:
1756 sharkd_json_value_anyf("avg", "%.2f", node->total.float_total / node->counter);
1757 sharkd_json_value_anyf("min", "%f", node->minvalue.float_min);
1758 sharkd_json_value_anyf("max", "%f", node->maxvalue.float_max);
1759 break;
1763 if (node->st->elapsed)
1764 sharkd_json_value_anyf("rate", "%.4f", ((float)node->counter) / node->st->elapsed);
1766 if (node->parent && node->parent->counter)
1767 sharkd_json_value_anyf("perc", "%.2f", (node->counter * 100.0) / node->parent->counter);
1768 else if (node->parent == &(node->st->root))
1769 sharkd_json_value_anyf("perc", "100");
1771 if (prefs.st_enable_burstinfo && node->max_burst)
1773 if (prefs.st_burst_showcount)
1774 sharkd_json_value_anyf("burstcount", "%d", node->max_burst);
1775 else
1776 sharkd_json_value_anyf("burstrate", "%.4f", ((double)node->max_burst) / prefs.st_burst_windowlen);
1778 sharkd_json_value_anyf("bursttime", "%.3f", (node->burst_time / 1000.0));
1781 if (node->children)
1783 sharkd_session_process_tap_stats_node_cb("sub", node);
1785 json_dumper_end_object(&dumper);
1787 sharkd_json_array_close();
1791 * sharkd_session_process_tap_stats_cb()
1793 * Output stats tap:
1795 * (m) tap - tap name
1796 * (m) type:stats - tap output type
1797 * (m) name - stat name
1798 * (m) stats - array of object with attributes:
1799 * (m) name - stat item name
1800 * (m) count - stat item counter
1801 * (o) avg - stat item averange value
1802 * (o) min - stat item min value
1803 * (o) max - stat item max value
1804 * (o) rate - stat item rate value (ms)
1805 * (o) perc - stat item percentage
1806 * (o) burstrate - stat item burst rate
1807 * (o) burstcount - stat item burst count
1808 * (o) burstttme - stat item burst start
1809 * (o) sub - array of object with attributes like in stats node.
1811 static void
1812 sharkd_session_process_tap_stats_cb(void *psp)
1814 stats_tree *st = (stats_tree *) psp;
1816 json_dumper_begin_object(&dumper);
1818 sharkd_json_value_stringf("tap", "stats:%s", st->cfg->abbr);
1819 sharkd_json_value_string("type", "stats");
1820 sharkd_json_value_string("name", st->cfg->path);
1822 sharkd_session_process_tap_stats_node_cb("stats", &st->root);
1824 json_dumper_end_object(&dumper);
1827 static void
1828 sharkd_session_free_tap_stats_cb(void *psp)
1830 stats_tree *st = (stats_tree *) psp;
1832 stats_tree_free(st);
1835 struct sharkd_expert_tap
1837 GSList *details;
1838 GStringChunk *text;
1842 * sharkd_session_process_tap_expert_cb()
1844 * Output expert tap:
1846 * (m) tap - tap name
1847 * (m) type:expert - tap output type
1848 * (m) details - array of object with attributes:
1849 * (m) f - frame number, which generated expert information
1850 * (o) s - severity
1851 * (o) g - group
1852 * (m) m - expert message
1853 * (o) p - protocol
1855 static void
1856 sharkd_session_process_tap_expert_cb(void *tapdata)
1858 struct sharkd_expert_tap *etd = (struct sharkd_expert_tap *) tapdata;
1859 GSList *list;
1861 json_dumper_begin_object(&dumper);
1863 sharkd_json_value_string("tap", "expert");
1864 sharkd_json_value_string("type", "expert");
1866 sharkd_json_array_open("details");
1867 for (list = etd->details; list; list = list->next)
1869 expert_info_t *ei = (expert_info_t *) list->data;
1870 const char *tmp;
1872 json_dumper_begin_object(&dumper);
1874 sharkd_json_value_anyf("f", "%u", ei->packet_num);
1876 tmp = try_val_to_str(ei->severity, expert_severity_vals);
1877 if (tmp)
1878 sharkd_json_value_string("s", tmp);
1880 tmp = try_val_to_str(ei->group, expert_group_vals);
1881 if (tmp)
1882 sharkd_json_value_string("g", tmp);
1884 sharkd_json_value_string("m", ei->summary);
1886 if (ei->protocol)
1887 sharkd_json_value_string("p", ei->protocol);
1889 json_dumper_end_object(&dumper);
1891 sharkd_json_array_close();
1893 json_dumper_end_object(&dumper);
1896 static tap_packet_status
1897 sharkd_session_packet_tap_expert_cb(void *tapdata, packet_info *pinfo _U_, epan_dissect_t *edt _U_, const void *pointer, tap_flags_t flags _U_)
1899 struct sharkd_expert_tap *etd = (struct sharkd_expert_tap *) tapdata;
1900 const expert_info_t *ei = (const expert_info_t *) pointer;
1901 expert_info_t *ei_copy;
1903 if (ei == NULL)
1904 return TAP_PACKET_DONT_REDRAW;
1906 ei_copy = g_new(expert_info_t, 1);
1907 /* Note: this is a shallow copy */
1908 *ei_copy = *ei;
1910 /* ei->protocol, ei->summary might be allocated in packet scope, make a copy. */
1911 ei_copy->protocol = g_string_chunk_insert_const(etd->text, ei_copy->protocol);
1912 ei_copy->summary = g_string_chunk_insert_const(etd->text, ei_copy->summary);
1914 etd->details = g_slist_prepend(etd->details, ei_copy);
1916 return TAP_PACKET_REDRAW;
1919 static void
1920 sharkd_session_free_tap_expert_cb(void *tapdata)
1922 struct sharkd_expert_tap *etd = (struct sharkd_expert_tap *) tapdata;
1924 g_slist_free_full(etd->details, g_free);
1925 g_string_chunk_free(etd->text);
1926 g_free(etd);
1930 * sharkd_session_process_tap_flow_cb()
1932 * Output flow tap:
1933 * (m) tap - tap name
1934 * (m) type:flow - tap output type
1935 * (m) nodes - array of strings with node address
1936 * (m) flows - array of object with attributes:
1937 * (m) t - frame time string
1938 * (m) n - array of two numbers with source node index and destination node index
1939 * (m) pn - array of two numbers with source and destination port
1940 * (o) c - comment
1942 static void
1943 sharkd_session_process_tap_flow_cb(void *tapdata)
1945 seq_analysis_info_t *graph_analysis = (seq_analysis_info_t *) tapdata;
1946 GList *flow_list;
1947 unsigned i;
1949 sequence_analysis_get_nodes(graph_analysis);
1951 json_dumper_begin_object(&dumper);
1952 sharkd_json_value_stringf("tap", "seqa:%s", graph_analysis->name);
1953 sharkd_json_value_string("type", "flow");
1955 sharkd_json_array_open("nodes");
1956 for (i = 0; i < graph_analysis->num_nodes; i++)
1958 char *addr_str;
1960 addr_str = address_to_display(NULL, &(graph_analysis->nodes[i]));
1961 sharkd_json_value_string(NULL, addr_str);
1962 wmem_free(NULL, addr_str);
1964 sharkd_json_array_close();
1966 sharkd_json_array_open("flows");
1967 flow_list = g_queue_peek_nth_link(graph_analysis->items, 0);
1968 while (flow_list)
1970 seq_analysis_item_t *sai = (seq_analysis_item_t *) flow_list->data;
1972 flow_list = g_list_next(flow_list);
1974 if (!sai->display)
1975 continue;
1977 json_dumper_begin_object(&dumper);
1979 sharkd_json_value_string("t", sai->time_str);
1980 sharkd_json_value_anyf("n", "[%u,%u]", sai->src_node, sai->dst_node);
1981 sharkd_json_value_anyf("pn", "[%u,%u]", sai->port_src, sai->port_dst);
1983 if (sai->comment)
1984 sharkd_json_value_string("c", sai->comment);
1986 json_dumper_end_object(&dumper);
1988 sharkd_json_array_close();
1990 json_dumper_end_object(&dumper);
1993 static void
1994 sharkd_session_free_tap_flow_cb(void *tapdata)
1996 seq_analysis_info_t *graph_analysis = (seq_analysis_info_t *) tapdata;
1998 sequence_analysis_info_free(graph_analysis);
2001 struct sharkd_conv_tap_data
2003 const char *type;
2004 conv_hash_t hash;
2005 bool resolve_name;
2006 bool resolve_port;
2009 static bool
2010 sharkd_session_geoip_addr(address *addr, const char *suffix)
2012 const mmdb_lookup_t *lookup = NULL;
2013 bool with_geoip = false;
2014 char json_key[64];
2016 if (addr->type == AT_IPv4)
2018 const ws_in4_addr *ip4 = (const ws_in4_addr *) addr->data;
2020 lookup = maxmind_db_lookup_ipv4(ip4);
2022 else if (addr->type == AT_IPv6)
2024 const ws_in6_addr *ip6 = (const ws_in6_addr *) addr->data;
2026 lookup = maxmind_db_lookup_ipv6(ip6);
2029 if (!lookup || !lookup->found)
2030 return false;
2032 if (lookup->country)
2034 snprintf(json_key, sizeof(json_key), "geoip_country%s", suffix);
2035 sharkd_json_value_string(json_key, lookup->country);
2036 with_geoip = true;
2039 if (lookup->country_iso)
2041 snprintf(json_key, sizeof(json_key), "geoip_country_iso%s", suffix);
2042 sharkd_json_value_string(json_key, lookup->country_iso);
2043 with_geoip = true;
2046 if (lookup->city)
2048 snprintf(json_key, sizeof(json_key), "geoip_city%s", suffix);
2049 sharkd_json_value_string(json_key, lookup->city);
2050 with_geoip = true;
2053 if (lookup->as_org)
2055 snprintf(json_key, sizeof(json_key), "geoip_as_org%s", suffix);
2056 sharkd_json_value_string(json_key, lookup->as_org);
2057 with_geoip = true;
2060 if (lookup->as_number > 0)
2062 snprintf(json_key, sizeof(json_key), "geoip_as%s", suffix);
2063 sharkd_json_value_anyf(json_key, "%u", lookup->as_number);
2064 with_geoip = true;
2067 if (lookup->latitude >= -90.0 && lookup->latitude <= 90.0)
2069 snprintf(json_key, sizeof(json_key), "geoip_lat%s", suffix);
2070 sharkd_json_value_anyf(json_key, "%f", lookup->latitude);
2071 with_geoip = true;
2074 if (lookup->longitude >= -180.0 && lookup->longitude <= 180.0)
2076 snprintf(json_key, sizeof(json_key), "geoip_lon%s", suffix);
2077 sharkd_json_value_anyf(json_key, "%f", lookup->longitude);
2078 with_geoip = true;
2081 return with_geoip;
2084 struct sharkd_analyse_rtp_items
2086 uint32_t frame_num;
2087 uint32_t sequence_num;
2089 double delta;
2090 double jitter;
2091 double skew;
2092 double bandwidth;
2093 bool marker;
2095 double arrive_offset;
2097 /* from tap_rtp_stat_t */
2098 uint32_t flags;
2099 uint16_t pt;
2102 struct sharkd_analyse_rtp
2104 const char *tap_name;
2105 rtpstream_id_t id;
2107 GSList *packets;
2108 double start_time;
2109 tap_rtp_stat_t statinfo;
2112 static void
2113 sharkd_session_process_tap_rtp_free_cb(void *tapdata)
2115 struct sharkd_analyse_rtp *rtp_req = (struct sharkd_analyse_rtp *) tapdata;
2117 g_slist_free_full(rtp_req->packets, g_free);
2118 g_free(rtp_req);
2121 static tap_packet_status
2122 sharkd_session_packet_tap_rtp_analyse_cb(void *tapdata, packet_info *pinfo, epan_dissect_t *edt _U_, const void *pointer, tap_flags_t flags _U_)
2124 struct sharkd_analyse_rtp *rtp_req = (struct sharkd_analyse_rtp *) tapdata;
2125 const struct _rtp_info *rtp_info = (const struct _rtp_info *) pointer;
2127 if (rtpstream_id_equal_pinfo_rtp_info(&rtp_req->id, pinfo, rtp_info))
2129 tap_rtp_stat_t *statinfo = &(rtp_req->statinfo);
2130 struct sharkd_analyse_rtp_items *item;
2132 rtppacket_analyse(statinfo, pinfo, rtp_info);
2134 item = g_new(struct sharkd_analyse_rtp_items, 1);
2136 if (!rtp_req->packets)
2137 rtp_req->start_time = nstime_to_sec(&pinfo->abs_ts);
2139 item->frame_num = pinfo->num;
2140 item->sequence_num = rtp_info->info_seq_num;
2141 item->delta = (statinfo->flags & STAT_FLAG_FIRST) ? 0.0 : statinfo->delta;
2142 item->jitter = (statinfo->flags & STAT_FLAG_FIRST) ? 0.0 : statinfo->jitter;
2143 item->skew = (statinfo->flags & STAT_FLAG_FIRST) ? 0.0 : statinfo->skew;
2144 item->bandwidth = statinfo->bandwidth;
2145 item->marker = rtp_info->info_marker_set ? true : false;
2146 item->arrive_offset= nstime_to_sec(&pinfo->abs_ts) - rtp_req->start_time;
2148 item->flags = statinfo->flags;
2149 item->pt = statinfo->pt;
2151 /* XXX, O(n) optimize */
2152 rtp_req->packets = g_slist_append(rtp_req->packets, item);
2155 return TAP_PACKET_REDRAW;
2159 * sharkd_session_process_tap_rtp_analyse_cb()
2161 * Output rtp analyse tap:
2162 * (m) tap - tap name
2163 * (m) type - tap output type
2164 * (m) ssrc - RTP SSRC
2165 * (m) max_delta - Max delta (ms)
2166 * (m) max_delta_nr - Max delta packet #
2167 * (m) max_jitter - Max jitter (ms)
2168 * (m) mean_jitter - Mean jitter (ms)
2169 * (m) max_skew - Max skew (ms)
2170 * (m) total_nr - Total number of RTP packets
2171 * (m) seq_err - Number of sequence errors
2172 * (m) duration - Duration (ms)
2173 * (m) items - array of object with attributes:
2174 * (m) f - frame number
2175 * (m) o - arrive offset
2176 * (m) sn - sequence number
2177 * (m) d - delta
2178 * (m) j - jitter
2179 * (m) sk - skew
2180 * (m) bw - bandwidth
2181 * (o) s - status string
2182 * (o) t - status type
2183 * (o) mark - rtp mark
2185 static void
2186 sharkd_session_process_tap_rtp_analyse_cb(void *tapdata)
2188 const int RTP_TYPE_CN = 1;
2189 const int RTP_TYPE_ERROR = 2;
2190 const int RTP_TYPE_WARN = 3;
2191 const int RTP_TYPE_PT_EVENT = 4;
2193 const struct sharkd_analyse_rtp *rtp_req = (struct sharkd_analyse_rtp *) tapdata;
2194 const tap_rtp_stat_t *statinfo = &rtp_req->statinfo;
2196 GSList *l;
2198 json_dumper_begin_object(&dumper);
2200 sharkd_json_value_string("tap", rtp_req->tap_name);
2201 sharkd_json_value_string("type", "rtp-analyse");
2202 sharkd_json_value_stringf("ssrc", "0x%x", rtp_req->id.ssrc);
2204 sharkd_json_value_anyf("max_delta", "%f", statinfo->max_delta);
2205 sharkd_json_value_anyf("max_delta_nr", "%u", statinfo->max_nr);
2206 sharkd_json_value_anyf("max_jitter", "%f", statinfo->max_jitter);
2207 sharkd_json_value_anyf("mean_jitter", "%f", statinfo->mean_jitter);
2208 sharkd_json_value_anyf("max_skew", "%f", statinfo->max_skew);
2209 sharkd_json_value_anyf("total_nr", "%u", statinfo->total_nr);
2210 sharkd_json_value_anyf("seq_err", "%u", statinfo->sequence);
2211 sharkd_json_value_anyf("duration", "%f", statinfo->time - statinfo->start_time);
2213 sharkd_json_array_open("items");
2214 for (l = rtp_req->packets; l; l = l->next)
2216 struct sharkd_analyse_rtp_items *item = (struct sharkd_analyse_rtp_items *) l->data;
2218 json_dumper_begin_object(&dumper);
2220 sharkd_json_value_anyf("f", "%u", item->frame_num);
2221 sharkd_json_value_anyf("o", "%.9f", item->arrive_offset);
2222 sharkd_json_value_anyf("sn", "%u", item->sequence_num);
2223 sharkd_json_value_anyf("d", "%.2f", item->delta);
2224 sharkd_json_value_anyf("j", "%.2f", item->jitter);
2225 sharkd_json_value_anyf("sk", "%.2f", item->skew);
2226 sharkd_json_value_anyf("bw", "%.2f", item->bandwidth);
2228 if (item->pt == PT_CN)
2230 sharkd_json_value_string("s", "Comfort noise (PT=13, RFC 3389)");
2231 sharkd_json_value_anyf("t", "%d", RTP_TYPE_CN);
2233 else if (item->pt == PT_CN_OLD)
2235 sharkd_json_value_string("s", "Comfort noise (PT=19, reserved)");
2236 sharkd_json_value_anyf("t", "%d", RTP_TYPE_CN);
2238 else if (item->flags & STAT_FLAG_WRONG_SEQ)
2240 sharkd_json_value_string("s", "Wrong sequence number");
2241 sharkd_json_value_anyf("t", "%d", RTP_TYPE_ERROR);
2243 else if (item->flags & STAT_FLAG_DUP_PKT)
2245 sharkd_json_value_string("s", "Suspected duplicate (MAC address) only delta time calculated");
2246 sharkd_json_value_anyf("t", "%d", RTP_TYPE_WARN);
2248 else if (item->flags & STAT_FLAG_REG_PT_CHANGE)
2250 sharkd_json_value_stringf("s", "Payload changed to PT=%u%s",
2251 item->pt,
2252 (item->flags & STAT_FLAG_PT_T_EVENT) ? " telephone/event" : "");
2253 sharkd_json_value_anyf("t", "%d", RTP_TYPE_WARN);
2255 else if (item->flags & STAT_FLAG_WRONG_TIMESTAMP)
2257 sharkd_json_value_string("s", "Incorrect timestamp");
2258 sharkd_json_value_anyf("t", "%d", RTP_TYPE_WARN);
2260 else if ((item->flags & STAT_FLAG_PT_CHANGE)
2261 && !(item->flags & STAT_FLAG_FIRST)
2262 && !(item->flags & STAT_FLAG_PT_CN)
2263 && (item->flags & STAT_FLAG_FOLLOW_PT_CN)
2264 && !(item->flags & STAT_FLAG_MARKER))
2266 sharkd_json_value_string("s", "Marker missing?");
2267 sharkd_json_value_anyf("t", "%d", RTP_TYPE_WARN);
2269 else if (item->flags & STAT_FLAG_PT_T_EVENT)
2271 sharkd_json_value_stringf("s", "PT=%u telephone/event", item->pt);
2272 sharkd_json_value_anyf("t", "%d", RTP_TYPE_PT_EVENT);
2274 else if (item->flags & STAT_FLAG_MARKER)
2276 sharkd_json_value_anyf("t", "%d", RTP_TYPE_WARN);
2279 if (item->marker)
2280 sharkd_json_value_anyf("mark", "1");
2282 json_dumper_end_object(&dumper);
2284 sharkd_json_array_close();
2286 json_dumper_end_object(&dumper);
2290 * sharkd_session_process_tap_conv_cb()
2292 * Output conv tap:
2293 * (m) tap - tap name
2294 * (m) type - tap output type
2295 * (m) proto - protocol short name
2296 * (o) filter - filter string
2297 * (o) geoip - whether GeoIP information is available, boolean
2299 * (o) convs - array of object with attributes:
2300 * (m) saddr - source address
2301 * (m) daddr - destination address
2302 * (o) sport - source port
2303 * (o) dport - destination port
2304 * (m) txf - TX frame count
2305 * (m) txb - TX bytes
2306 * (m) rxf - RX frame count
2307 * (m) rxb - RX bytes
2308 * (m) start - (relative) first packet time
2309 * (m) stop - (relative) last packet time
2310 * (o) filter - conversation filter
2312 * (o) hosts - array of object with attributes:
2313 * (m) host - host address
2314 * (o) port - host port
2315 * (m) txf - TX frame count
2316 * (m) txb - TX bytes
2317 * (m) rxf - RX frame count
2318 * (m) rxb - RX bytes
2320 static void
2321 sharkd_session_process_tap_conv_cb(void *arg)
2323 conv_hash_t *hash = (conv_hash_t *) arg;
2324 const struct sharkd_conv_tap_data *iu = (struct sharkd_conv_tap_data *) hash->user_data;
2325 const char *proto;
2326 int proto_with_port;
2327 unsigned i;
2329 int with_geoip = 0;
2331 json_dumper_begin_object(&dumper);
2332 sharkd_json_value_string("tap", iu->type);
2334 if (!strncmp(iu->type, "conv:", 5))
2336 sharkd_json_value_string("type", "conv");
2337 sharkd_json_array_open("convs");
2338 proto = iu->type + 5;
2340 else if (!strncmp(iu->type, "endpt:", 6))
2342 sharkd_json_value_string("type", "host");
2343 sharkd_json_array_open("hosts");
2344 proto = iu->type + 6;
2346 else
2348 sharkd_json_value_string("type", "err");
2349 proto = "";
2352 proto_with_port = (!strcmp(proto, "TCP") || !strcmp(proto, "UDP") || !strcmp(proto, "SCTP"));
2354 if (iu->hash.conv_array != NULL && !strncmp(iu->type, "conv:", 5))
2356 for (i = 0; i < iu->hash.conv_array->len; i++)
2358 conv_item_t *iui = &g_array_index(iu->hash.conv_array, conv_item_t, i);
2359 char *src_addr, *dst_addr;
2360 char *src_port, *dst_port;
2361 char *filter_str;
2363 json_dumper_begin_object(&dumper);
2365 sharkd_json_value_string("saddr", (src_addr = get_conversation_address(NULL, &iui->src_address, iu->resolve_name)));
2366 sharkd_json_value_string("daddr", (dst_addr = get_conversation_address(NULL, &iui->dst_address, iu->resolve_name)));
2368 if (proto_with_port)
2370 sharkd_json_value_string("sport", (src_port = get_conversation_port(NULL, iui->src_port, iui->ctype, iu->resolve_port)));
2371 sharkd_json_value_string("dport", (dst_port = get_conversation_port(NULL, iui->dst_port, iui->ctype, iu->resolve_port)));
2373 wmem_free(NULL, src_port);
2374 wmem_free(NULL, dst_port);
2377 sharkd_json_value_anyf("rxf", "%" PRIu64, iui->rx_frames);
2378 sharkd_json_value_anyf("rxb", "%" PRIu64, iui->rx_bytes);
2380 sharkd_json_value_anyf("txf", "%" PRIu64, iui->tx_frames);
2381 sharkd_json_value_anyf("txb", "%" PRIu64, iui->tx_bytes);
2383 sharkd_json_value_anyf("start", "%.9f", nstime_to_sec(&iui->start_time));
2384 sharkd_json_value_anyf("stop", "%.9f", nstime_to_sec(&iui->stop_time));
2386 filter_str = get_conversation_filter(iui, CONV_DIR_A_TO_FROM_B);
2387 if (filter_str)
2389 sharkd_json_value_string("filter", filter_str);
2390 g_free(filter_str);
2393 wmem_free(NULL, src_addr);
2394 wmem_free(NULL, dst_addr);
2396 if (sharkd_session_geoip_addr(&(iui->src_address), "1"))
2397 with_geoip = 1;
2398 if (sharkd_session_geoip_addr(&(iui->dst_address), "2"))
2399 with_geoip = 1;
2401 json_dumper_end_object(&dumper);
2404 else if (iu->hash.conv_array != NULL && !strncmp(iu->type, "endpt:", 6))
2406 for (i = 0; i < iu->hash.conv_array->len; i++)
2408 endpoint_item_t *endpoint = &g_array_index(iu->hash.conv_array, endpoint_item_t, i);
2409 char *host_str, *port_str;
2410 char *filter_str;
2412 json_dumper_begin_object(&dumper);
2414 sharkd_json_value_string("host", (host_str = get_conversation_address(NULL, &endpoint->myaddress, iu->resolve_name)));
2416 if (proto_with_port)
2418 sharkd_json_value_string("port", (port_str = get_endpoint_port(NULL, endpoint, iu->resolve_port)));
2420 wmem_free(NULL, port_str);
2423 sharkd_json_value_anyf("rxf", "%" PRIu64, endpoint->rx_frames);
2424 sharkd_json_value_anyf("rxb", "%" PRIu64, endpoint->rx_bytes);
2426 sharkd_json_value_anyf("txf", "%" PRIu64, endpoint->tx_frames);
2427 sharkd_json_value_anyf("txb", "%" PRIu64, endpoint->tx_bytes);
2429 filter_str = get_endpoint_filter(endpoint);
2430 if (filter_str)
2432 sharkd_json_value_string("filter", filter_str);
2433 g_free(filter_str);
2436 wmem_free(NULL, host_str);
2438 if (sharkd_session_geoip_addr(&(endpoint->myaddress), ""))
2439 with_geoip = 1;
2440 json_dumper_end_object(&dumper);
2443 sharkd_json_array_close();
2445 sharkd_json_value_string("proto", proto);
2446 sharkd_json_value_anyf("geoip", with_geoip ? "true" : "false");
2448 json_dumper_end_object(&dumper);
2451 static void
2452 sharkd_session_free_tap_conv_cb(void *arg)
2454 conv_hash_t *hash = (conv_hash_t *) arg;
2455 struct sharkd_conv_tap_data *iu = (struct sharkd_conv_tap_data *) hash->user_data;
2457 if (!strncmp(iu->type, "conv:", 5))
2459 reset_conversation_table_data(hash);
2461 else if (!strncmp(iu->type, "endpt:", 6))
2463 reset_endpoint_table_data(hash);
2466 g_free(iu);
2470 * sharkd_session_process_tap_nstat_cb()
2472 * Output nstat tap:
2473 * (m) tap - tap name
2474 * (m) type - tap output type
2475 * (m) fields: array of objects with attributes:
2476 * (m) c - name
2478 * (m) tables: array of object with attributes:
2479 * (m) t - table title
2480 * (m) i - array of items
2482 static void
2483 sharkd_session_process_tap_nstat_cb(void *arg)
2485 stat_data_t *stat_data = (stat_data_t *) arg;
2486 unsigned i, j, k;
2488 json_dumper_begin_object(&dumper);
2489 sharkd_json_value_stringf("tap", "nstat:%s", stat_data->stat_tap_data->cli_string);
2490 sharkd_json_value_string("type", "nstat");
2492 sharkd_json_array_open("fields");
2493 for (i = 0; i < stat_data->stat_tap_data->nfields; i++)
2495 stat_tap_table_item *field = &(stat_data->stat_tap_data->fields[i]);
2497 json_dumper_begin_object(&dumper);
2498 sharkd_json_value_string("c", field->column_name);
2499 json_dumper_end_object(&dumper);
2501 sharkd_json_array_close();
2503 sharkd_json_array_open("tables");
2504 for (i = 0; i < stat_data->stat_tap_data->tables->len; i++)
2506 stat_tap_table *table = g_array_index(stat_data->stat_tap_data->tables, stat_tap_table *, i);
2508 json_dumper_begin_object(&dumper);
2510 sharkd_json_value_string("t", table->title);
2512 sharkd_json_array_open("i");
2513 for (j = 0; j < table->num_elements; j++)
2515 stat_tap_table_item_type *field_data;
2517 field_data = stat_tap_get_field_data(table, j, 0);
2518 if (field_data == NULL || field_data->type == TABLE_ITEM_NONE) /* Nothing for us here */
2519 continue;
2521 sharkd_json_array_open(NULL);
2522 for (k = 0; k < table->num_fields; k++)
2524 field_data = stat_tap_get_field_data(table, j, k);
2526 switch (field_data->type)
2528 case TABLE_ITEM_UINT:
2529 sharkd_json_value_anyf(NULL, "%u", field_data->value.uint_value);
2530 break;
2532 case TABLE_ITEM_INT:
2533 sharkd_json_value_anyf(NULL, "%d", field_data->value.int_value);
2534 break;
2536 case TABLE_ITEM_STRING:
2537 sharkd_json_value_string(NULL, field_data->value.string_value);
2538 break;
2540 case TABLE_ITEM_FLOAT:
2541 sharkd_json_value_anyf(NULL, "%f", field_data->value.float_value);
2542 break;
2544 case TABLE_ITEM_ENUM:
2545 sharkd_json_value_anyf(NULL, "%d", field_data->value.enum_value);
2546 break;
2548 case TABLE_ITEM_NONE:
2549 sharkd_json_value_anyf(NULL, "null");
2550 break;
2554 sharkd_json_array_close();
2556 sharkd_json_array_close();
2557 json_dumper_end_object(&dumper);
2559 sharkd_json_array_close();
2561 json_dumper_end_object(&dumper);
2564 static void
2565 sharkd_session_free_tap_nstat_cb(void *arg)
2567 stat_data_t *stat_data = (stat_data_t *) arg;
2569 free_stat_tables(stat_data->stat_tap_data);
2573 * sharkd_session_process_tap_rtd_cb()
2575 * Output rtd tap:
2576 * (m) tap - tap name
2577 * (m) type - tap output type
2578 * (m) stats - statistics rows - array object with attributes:
2579 * (m) type - statistic name
2580 * (m) num - number of messages
2581 * (m) min - minimum SRT time
2582 * (m) max - maximum SRT time
2583 * (m) tot - total SRT time
2584 * (m) min_frame - minimal SRT
2585 * (m) max_frame - maximum SRT
2586 * (o) open_req - Open Requests
2587 * (o) disc_rsp - Discarded Responses
2588 * (o) req_dup - Duplicated Requests
2589 * (o) rsp_dup - Duplicated Responses
2590 * (o) open_req - Open Requests
2591 * (o) disc_rsp - Discarded Responses
2592 * (o) req_dup - Duplicated Requests
2593 * (o) rsp_dup - Duplicated Responses
2595 static void
2596 sharkd_session_process_tap_rtd_cb(void *arg)
2598 rtd_data_t *rtd_data = (rtd_data_t *) arg;
2599 register_rtd_t *rtd = (register_rtd_t *) rtd_data->user_data;
2601 unsigned i, j;
2603 const char *filter = proto_get_protocol_filter_name(get_rtd_proto_id(rtd));
2605 /* XXX, some dissectors are having single table and multiple timestats (mgcp, megaco),
2606 * some multiple table and single timestat (radius, h225)
2607 * and it seems that value_string is used one for timestamp-ID, other one for table-ID
2608 * I wonder how it will gonna work with multiple timestats and multiple tables...
2609 * (for usage grep for: register_rtd_table)
2611 const value_string *vs = get_rtd_value_string(rtd);
2613 json_dumper_begin_object(&dumper);
2614 sharkd_json_value_stringf("tap", "rtd:%s", filter);
2615 sharkd_json_value_string("type", "rtd");
2617 if (rtd_data->stat_table.num_rtds == 1)
2619 const rtd_timestat *ms = &rtd_data->stat_table.time_stats[0];
2621 sharkd_json_value_anyf("open_req", "%u", ms->open_req_num);
2622 sharkd_json_value_anyf("disc_rsp", "%u", ms->disc_rsp_num);
2623 sharkd_json_value_anyf("req_dup", "%u", ms->req_dup_num);
2624 sharkd_json_value_anyf("rsp_dup", "%u", ms->rsp_dup_num);
2627 sharkd_json_array_open("stats");
2628 for (i = 0; i < rtd_data->stat_table.num_rtds; i++)
2630 const rtd_timestat *ms = &rtd_data->stat_table.time_stats[i];
2632 for (j = 0; j < ms->num_timestat; j++)
2634 const char *type_str;
2636 if (ms->rtd[j].num == 0)
2637 continue;
2639 json_dumper_begin_object(&dumper);
2641 if (rtd_data->stat_table.num_rtds == 1)
2642 type_str = val_to_str_const(j, vs, "Other"); /* 1 table - description per row */
2643 else
2644 type_str = val_to_str_const(i, vs, "Other"); /* multiple table - description per table */
2645 sharkd_json_value_string("type", type_str);
2647 sharkd_json_value_anyf("num", "%u", ms->rtd[j].num);
2648 sharkd_json_value_anyf("min", "%.9f", nstime_to_sec(&(ms->rtd[j].min)));
2649 sharkd_json_value_anyf("max", "%.9f", nstime_to_sec(&(ms->rtd[j].max)));
2650 sharkd_json_value_anyf("tot", "%.9f", nstime_to_sec(&(ms->rtd[j].tot)));
2651 sharkd_json_value_anyf("min_frame", "%u", ms->rtd[j].min_num);
2652 sharkd_json_value_anyf("max_frame", "%u", ms->rtd[j].max_num);
2654 if (rtd_data->stat_table.num_rtds != 1)
2656 /* like in tshark, display it on every row */
2657 sharkd_json_value_anyf("open_req", "%u", ms->open_req_num);
2658 sharkd_json_value_anyf("disc_rsp", "%u", ms->disc_rsp_num);
2659 sharkd_json_value_anyf("req_dup", "%u", ms->req_dup_num);
2660 sharkd_json_value_anyf("rsp_dup", "%u", ms->rsp_dup_num);
2663 json_dumper_end_object(&dumper);
2666 sharkd_json_array_close();
2668 json_dumper_end_object(&dumper);
2671 static void
2672 sharkd_session_free_tap_rtd_cb(void *arg)
2674 rtd_data_t *rtd_data = (rtd_data_t *) arg;
2676 free_rtd_table(&rtd_data->stat_table);
2677 g_free(rtd_data);
2681 * sharkd_session_process_tap_srt_cb()
2683 * Output srt tap:
2684 * (m) tap - tap name
2685 * (m) type - tap output type
2687 * (m) tables - array of object with attributes:
2688 * (m) n - table name
2689 * (m) f - table filter
2690 * (o) c - table column name
2691 * (m) r - table rows - array object with attributes:
2692 * (m) n - row name
2693 * (m) idx - procedure index
2694 * (m) num - number of events
2695 * (m) min - minimum SRT time
2696 * (m) max - maximum SRT time
2697 * (m) tot - total SRT time
2699 static void
2700 sharkd_session_process_tap_srt_cb(void *arg)
2702 srt_data_t *srt_data = (srt_data_t *) arg;
2703 register_srt_t *srt = (register_srt_t *) srt_data->user_data;
2705 const char *filter = proto_get_protocol_filter_name(get_srt_proto_id(srt));
2707 unsigned i;
2709 json_dumper_begin_object(&dumper);
2710 sharkd_json_value_stringf("tap", "srt:%s", filter);
2711 sharkd_json_value_string("type", "srt");
2713 sharkd_json_array_open("tables");
2714 for (i = 0; i < srt_data->srt_array->len; i++)
2716 /* SRT table */
2717 srt_stat_table *rst = g_array_index(srt_data->srt_array, srt_stat_table *, i);
2719 int j;
2721 json_dumper_begin_object(&dumper);
2723 if (rst->name)
2724 sharkd_json_value_string("n", rst->name);
2725 else if (rst->short_name)
2726 sharkd_json_value_string("n", rst->short_name);
2727 else
2728 sharkd_json_value_stringf("n", "table%u", i);
2730 if (rst->filter_string)
2731 sharkd_json_value_string("f", rst->filter_string);
2733 if (rst->proc_column_name)
2734 sharkd_json_value_string("c", rst->proc_column_name);
2736 sharkd_json_array_open("r");
2737 for (j = 0; j < rst->num_procs; j++)
2739 /* SRT row */
2740 srt_procedure_t *proc = &rst->procedures[j];
2742 if (proc->stats.num == 0)
2743 continue;
2745 json_dumper_begin_object(&dumper);
2747 sharkd_json_value_string("n", proc->procedure);
2749 if (rst->filter_string)
2750 sharkd_json_value_anyf("idx", "%d", proc->proc_index);
2752 sharkd_json_value_anyf("num", "%u", proc->stats.num);
2754 sharkd_json_value_anyf("min", "%.9f", nstime_to_sec(&proc->stats.min));
2755 sharkd_json_value_anyf("max", "%.9f", nstime_to_sec(&proc->stats.max));
2756 sharkd_json_value_anyf("tot", "%.9f", nstime_to_sec(&proc->stats.tot));
2758 json_dumper_end_object(&dumper);
2760 sharkd_json_array_close();
2762 json_dumper_end_object(&dumper);
2764 sharkd_json_array_close();
2766 json_dumper_end_object(&dumper);
2769 static void
2770 sharkd_session_free_tap_srt_cb(void *arg)
2772 srt_data_t *srt_data = (srt_data_t *) arg;
2773 register_srt_t *srt = (register_srt_t *) srt_data->user_data;
2775 free_srt_table(srt, srt_data->srt_array);
2776 g_array_free(srt_data->srt_array, TRUE);
2777 g_free(srt_data);
2780 static void
2781 sharkd_session_process_tap_phs_cb_aux(phs_t *rs)
2783 for (; rs; rs = rs->sibling) {
2784 if (rs->protocol == -1) {
2785 return;
2787 sharkd_json_object_open(NULL);
2788 sharkd_json_value_string("proto", rs->proto_name);
2789 sharkd_json_value_anyf("frames", "%"PRIu32, rs->frames);
2790 sharkd_json_value_anyf("bytes", "%"PRIu64, rs->bytes);
2791 if (rs->child != NULL && rs->child->protocol != -1) {
2792 sharkd_json_array_open("protos");
2793 sharkd_session_process_tap_phs_cb_aux(rs->child);
2794 sharkd_json_array_close();
2796 sharkd_json_object_close();
2801 * sharkd_session_process_tap_phs_cb()
2803 * Output phs tap:
2804 * (m) tap - tap name
2805 * (m) type - tap output type
2806 * (m) filter - tap filter argument
2807 * (m) protos - array of proto objects
2809 * proto object:
2810 * (m) proto - protocol name
2811 * (m) frames - frame count
2812 * (m) bytes - bytes count
2813 * (o) protos - array of proto objects
2815 static void
2816 sharkd_session_process_tap_phs_cb(void *arg)
2818 phs_t *rs = (phs_t *)arg;
2819 sharkd_json_object_open(NULL);
2820 sharkd_json_value_string("tap", "phs");
2821 sharkd_json_value_string("type", "phs");
2822 sharkd_json_value_string("filter", rs->filter ? rs->filter : "");
2823 sharkd_json_array_open("protos");
2824 sharkd_session_process_tap_phs_cb_aux(rs);
2825 sharkd_json_array_close();
2826 sharkd_json_object_close();
2829 static void
2830 sharkd_session_free_tap_phs_cb(void *arg)
2832 phs_t *rs = (phs_t *)arg;
2833 free_phs(rs);
2836 struct sharkd_export_object_list
2838 struct sharkd_export_object_list *next;
2840 char *type;
2841 const char *proto;
2842 GSList *entries;
2845 static struct sharkd_export_object_list *sharkd_eo_list;
2848 * sharkd_session_process_tap_eo_cb()
2850 * Output eo tap:
2851 * (m) tap - tap name
2852 * (m) type - tap output type
2853 * (m) proto - protocol short name
2854 * (m) objects - array of object with attributes:
2855 * (m) pkt - packet number
2856 * (o) hostname - hostname
2857 * (o) type - content type
2858 * (o) filename - filename
2859 * (m) len - object length
2860 * (m) sha1 - object's sha1 sum
2862 static void
2863 sharkd_session_process_tap_eo_cb(void *tapdata)
2865 export_object_list_t *tap_object = (export_object_list_t *) tapdata;
2866 struct sharkd_export_object_list *object_list = (struct sharkd_export_object_list *) tap_object->gui_data;
2867 GSList *slist;
2868 int i = 0;
2869 char sha1sum_bytes[HASH_SHA1_LENGTH], *sha1sum_str;
2871 json_dumper_begin_object(&dumper);
2872 sharkd_json_value_string("tap", object_list->type);
2873 sharkd_json_value_string("type", "eo");
2875 sharkd_json_value_string("proto", object_list->proto);
2877 sharkd_json_array_open("objects");
2878 for (slist = object_list->entries; slist; slist = slist->next)
2880 const export_object_entry_t *eo_entry = (export_object_entry_t *) slist->data;
2882 json_dumper_begin_object(&dumper);
2884 sharkd_json_value_anyf("pkt", "%u", eo_entry->pkt_num);
2886 if (eo_entry->hostname)
2887 sharkd_json_value_string("hostname", eo_entry->hostname);
2889 if (eo_entry->content_type)
2890 sharkd_json_value_string("type", eo_entry->content_type);
2892 if (eo_entry->filename)
2893 sharkd_json_value_string("filename", eo_entry->filename);
2895 sharkd_json_value_stringf("_download", "%s_%d", object_list->type, i);
2897 sharkd_json_value_anyf("len", "%zu", eo_entry->payload_len);
2899 gcry_md_hash_buffer(GCRY_MD_SHA1, sha1sum_bytes, eo_entry->payload_data, eo_entry->payload_len);
2900 sha1sum_str = bytes_to_str(NULL, sha1sum_bytes, HASH_SHA1_LENGTH);
2901 sharkd_json_value_string("sha1", sha1sum_str);
2902 g_free(sha1sum_str);
2904 json_dumper_end_object(&dumper);
2906 i++;
2908 sharkd_json_array_close();
2910 json_dumper_end_object(&dumper);
2913 static void
2914 sharkd_eo_object_list_add_entry(void *gui_data, export_object_entry_t *entry)
2916 struct sharkd_export_object_list *object_list = (struct sharkd_export_object_list *) gui_data;
2918 object_list->entries = g_slist_append(object_list->entries, entry);
2921 static export_object_entry_t *
2922 sharkd_eo_object_list_get_entry(void *gui_data, int row)
2924 struct sharkd_export_object_list *object_list = (struct sharkd_export_object_list *) gui_data;
2926 return (export_object_entry_t *) g_slist_nth_data(object_list->entries, row);
2929 static struct sharkd_export_object_list *
2930 sharkd_eo_object_list_get_entry_by_type(void *gui_data, const char *tap_type)
2932 struct sharkd_export_object_list *object_list = (struct sharkd_export_object_list *) gui_data;
2933 for (; object_list; object_list = object_list->next)
2935 if (!strcmp(object_list->type, tap_type))
2936 return object_list;
2938 return NULL;
2943 * sharkd_session_process_tap_rtp_cb()
2945 * Output RTP streams tap:
2946 * (m) tap - tap name
2947 * (m) type - tap output type
2948 * (m) streams - array of object with attributes:
2949 * (m) ssrc - RTP synchronization source identifier
2950 * (m) payload - stream payload
2951 * (m) saddr - source address
2952 * (m) sport - source port
2953 * (m) daddr - destination address
2954 * (m) dport - destination port
2955 * (m) pkts - packets count
2956 * (m) max_delta - max delta (ms)
2957 * (m) max_jitter - max jitter (ms)
2958 * (m) mean_jitter - mean jitter (ms)
2959 * (m) expectednr -
2960 * (m) totalnr -
2961 * (m) problem - if analyser found the problem
2962 * (m) ipver - address IP version (4 or 6)
2964 static void
2965 sharkd_session_process_tap_rtp_cb(void *arg)
2967 rtpstream_tapinfo_t *rtp_tapinfo = (rtpstream_tapinfo_t *) arg;
2969 GList *listx;
2971 json_dumper_begin_object(&dumper);
2972 sharkd_json_value_string("tap", "rtp-streams");
2973 sharkd_json_value_string("type", "rtp-streams");
2975 sharkd_json_array_open("streams");
2976 for (listx = g_list_first(rtp_tapinfo->strinfo_list); listx; listx = listx->next)
2978 rtpstream_info_t *streaminfo = (rtpstream_info_t *) listx->data;
2979 rtpstream_info_calc_t calc;
2981 rtpstream_info_calculate(streaminfo, &calc);
2983 json_dumper_begin_object(&dumper);
2985 sharkd_json_value_stringf("ssrc", "0x%x", calc.ssrc);
2986 sharkd_json_value_string("payload", calc.all_payload_type_names);
2988 sharkd_json_value_string("saddr", calc.src_addr_str);
2989 sharkd_json_value_anyf("sport", "%u", calc.src_port);
2990 sharkd_json_value_string("daddr", calc.dst_addr_str);
2991 sharkd_json_value_anyf("dport", "%u", calc.dst_port);
2993 sharkd_json_value_anyf("start_time", "%f", calc.start_time_ms);
2994 sharkd_json_value_anyf("duration", "%f", calc.duration_ms);
2996 sharkd_json_value_anyf("pkts", "%u", calc.packet_count);
2997 sharkd_json_value_anyf("lost", "%u", calc.lost_num);
2998 sharkd_json_value_anyf("lost_percent", "%f", calc.lost_perc);
3000 sharkd_json_value_anyf("max_delta", "%f",calc.max_delta);
3001 sharkd_json_value_anyf("min_delta", "%f",calc.min_delta);
3002 sharkd_json_value_anyf("mean_delta", "%f",calc.mean_delta);
3003 sharkd_json_value_anyf("min_jitter", "%f", calc.min_jitter);
3004 sharkd_json_value_anyf("max_jitter", "%f", calc.max_jitter);
3005 sharkd_json_value_anyf("mean_jitter", "%f", calc.mean_jitter);
3007 sharkd_json_value_anyf("expectednr", "%u", calc.packet_expected);
3008 sharkd_json_value_anyf("totalnr", "%u", calc.total_nr);
3010 sharkd_json_value_anyf("problem", calc.problem ? "true" : "false");
3012 /* for filter */
3013 sharkd_json_value_anyf("ipver", "%d", (streaminfo->id.src_addr.type == AT_IPv6) ? 6 : 4);
3015 rtpstream_info_calc_free(&calc);
3017 json_dumper_end_object(&dumper);
3019 sharkd_json_array_close();
3021 json_dumper_end_object(&dumper);
3025 * sharkd_session_process_tap_multicast_cb()
3027 * Output UDP Multicast streams tap:
3028 * (m) tap - tap name
3029 * (m) type - tap output type
3030 * (m) bufferThresholdBytes - byte count for a stream where a buffer alarm should be reported
3031 * (m) burstIntervalMs - analysis interval in milliseconds
3032 * (m) burstThresholdPackets - count of packets in an interval that should trigger an alarm
3033 * (m) streams - array of streams with metrics:
3034 * (m) saddr - source address
3035 * (m) sport - source port
3036 * (m) daddr - destination address
3037 * (m) dport - destination port
3038 * (m) packets - object group for packet metrics with attributes:
3039 * (m) number - count of packets in the stream
3040 * (m) perSecond - average number of packets per seconds in the stream
3041 * (m) bandwidth - object group for bandwidth metrics with attributes:
3042 * (m) average - average measured bitrate in the stream
3043 * (m) max - max measured bitrate in the stream
3044 * (m) buffer - object group for buffer metrics with attributes:
3045 * (m) alarms - number of times the stream exceeded the buffer threshold
3046 * (m) max - highest stream buffer utilization
3047 * (m) burst - object group for burst metrics with attributes:
3048 * (m) alarms - number of times the stream exceeded the burst threshold
3049 * (m) max - most stream packets measured in a burst interval
3051 static void
3052 sharkd_session_process_tap_multicast_cb(void *arg)
3054 mcaststream_tapinfo_t *tapinfo = (mcaststream_tapinfo_t *)arg;
3055 GList *list_item;
3056 char *addr_str;
3058 json_dumper_begin_object(&dumper);
3060 sharkd_json_value_string("tap", "multicast");
3061 sharkd_json_value_string("type", "multicast");
3063 sharkd_json_value_anyf("bufferThresholdBytes", "%u", mcast_stream_bufferalarm);
3064 sharkd_json_value_anyf("burstIntervalMs", "%u", mcast_stream_burstint);
3065 sharkd_json_value_anyf("burstThresholdPackets", "%u", mcast_stream_trigger);
3067 sharkd_json_array_open("streams");
3068 for (list_item = g_list_first(tapinfo->strinfo_list); list_item; list_item = list_item->next) {
3069 mcast_stream_info_t *stream_info = (mcast_stream_info_t *) list_item->data;
3070 sharkd_json_object_open(NULL);
3072 addr_str = address_to_display(NULL, &stream_info->src_addr);
3073 sharkd_json_value_string("saddr", addr_str);
3074 wmem_free(NULL, addr_str);
3075 sharkd_json_value_anyf("sport", "%u", stream_info->src_port);
3076 addr_str = address_to_display(NULL, &stream_info->dest_addr);
3077 sharkd_json_value_string("daddr", addr_str);
3078 wmem_free(NULL, addr_str);
3079 sharkd_json_value_anyf("dport", "%u", stream_info->dest_port);
3080 sharkd_json_object_open("packets");
3082 sharkd_json_value_anyf("number", "%u", stream_info->npackets);
3083 sharkd_json_value_anyf("perSecond", "%f", stream_info->apackets);
3085 sharkd_json_object_close();
3086 sharkd_json_object_open("bandwidth");
3088 sharkd_json_value_anyf("average", "%f", stream_info->average_bw);
3089 sharkd_json_value_anyf("max", "%f", stream_info->element.maxbw);
3091 sharkd_json_object_close();
3092 sharkd_json_object_open("buffer");
3094 sharkd_json_value_anyf("alarms", "%u", stream_info->element.numbuffalarms);
3095 sharkd_json_value_anyf("max", "%u", stream_info->element.topbuffusage);
3097 sharkd_json_object_close();
3098 sharkd_json_object_open("burst");
3100 sharkd_json_value_anyf("alarms", "%u", stream_info->element.numbursts);
3101 sharkd_json_value_anyf("max", "%u", stream_info->element.topburstsize);
3103 sharkd_json_object_close();
3105 sharkd_json_object_close();
3107 sharkd_json_array_close();
3109 json_dumper_end_object(&dumper);
3112 static void
3113 sharkd_session_process_free_tap_multicast_cb(void *tapdata)
3115 mcaststream_tapinfo_t *tapinfo = (mcaststream_tapinfo_t *)tapdata;
3117 mcaststream_reset(tapinfo);
3119 g_free(tapinfo);
3123 * sharkd_session_process_tap_voip_calls_cb()
3125 * Output VoIP Calls tap:
3126 * (m) tap - tap name
3127 * (m) type - tap output type
3128 * (m) calls - array of objects with attributes:
3129 * (m) call - call number
3130 * (m) start_time - start timestamp
3131 * (m) stop_time - stop timestamp
3132 * (m) initial_speaker - address of initial speaker
3133 * (m) from - from address
3134 * (m) to - to address
3135 * (m) protocol - protocol name
3136 * (m) packets - packet count
3137 * (m) state - state string
3138 * (m) comment - comment string
3140 static void
3141 sharkd_session_process_tap_voip_calls_cb(void *arg)
3143 voip_calls_tapinfo_t *tapinfo = (voip_calls_tapinfo_t *)arg;
3144 char *addr_str;
3145 GList *cur_call = g_queue_peek_nth_link(tapinfo->callsinfos, 0);
3146 sharkd_json_object_open(NULL);
3147 sharkd_json_value_string("tap", "voip-calls");
3148 sharkd_json_value_string("type", "voip-calls");
3149 sharkd_json_array_open("calls");
3150 while (cur_call && cur_call->data) {
3151 voip_calls_info_t *call_info_ = (voip_calls_info_t*) cur_call->data;
3152 sharkd_json_object_open(NULL);
3153 sharkd_json_value_anyf("call", "%hu", call_info_->call_num);
3154 sharkd_json_value_anyf("start_time", "%.6f", nstime_to_sec(&(call_info_->start_rel_ts)));
3155 sharkd_json_value_anyf("stop_time", "%.6f", nstime_to_sec(&(call_info_->stop_rel_ts)));
3156 addr_str = address_to_display(NULL, &(call_info_->initial_speaker));
3157 sharkd_json_value_string("initial_speaker", addr_str);
3158 wmem_free(NULL, addr_str);
3159 sharkd_json_value_string("from", call_info_->from_identity);
3160 sharkd_json_value_string("to", call_info_->to_identity);
3161 sharkd_json_value_string("protocol", ((call_info_->protocol == VOIP_COMMON) && call_info_->protocol_name) ?
3162 call_info_->protocol_name : voip_protocol_name[call_info_->protocol]);
3163 sharkd_json_value_anyf("packets", "%u", call_info_->npackets);
3164 sharkd_json_value_string("state", voip_call_state_name[call_info_->call_state]);
3165 sharkd_json_value_string("comment", call_info_->call_comment);
3166 sharkd_json_object_close();
3167 cur_call = g_list_next(cur_call);
3169 sharkd_json_array_close();
3170 sharkd_json_object_close();
3173 static void
3174 sharkd_session_free_tap_voip_calls_cb(void *tapdata)
3176 voip_calls_tapinfo_t *tapinfo = (voip_calls_tapinfo_t *)tapdata;
3177 voip_calls_remove_all_tap_listeners(tapinfo);
3178 if (tapinfo->callsinfos != NULL) {
3179 g_queue_free(tapinfo->callsinfos);
3181 if (tapinfo->graph_analysis != NULL) {
3182 sequence_analysis_info_free(tapinfo->graph_analysis);
3184 memset(tapinfo, 0, sizeof(*tapinfo));
3188 struct sharkd_voip_convs_req {
3189 voip_calls_tapinfo_t *tapinfo;
3190 const char *tap_name;
3194 * sharkd_session_process_tap_voip_convs_cb()
3196 * Output VoIP Conversations tap:
3197 * (m) tap - tap name
3198 * (m) type - tap output type
3199 * (m) convs - array of objects with attributes:
3200 * (m) frame - frame number
3201 * (m) call - call number
3202 * (m) time - timestamp
3203 * (m) dst_addr - destination address
3204 * (m) dst_port - destination port
3205 * (m) src_addr - source address
3206 * (m) src_port - source port
3207 * (m) label - label string
3208 * (m) comment - comment string
3210 static void
3211 sharkd_session_process_tap_voip_convs_cb(void *arg)
3213 struct sharkd_voip_convs_req *voip_convs_req = (struct sharkd_voip_convs_req *)arg;
3214 voip_calls_tapinfo_t *tapinfo = voip_convs_req->tapinfo;
3215 seq_analysis_info_t *sainfo = tapinfo->graph_analysis;
3216 char *addr_str;
3217 sequence_analysis_list_sort(sainfo);
3218 sharkd_json_object_open(NULL);
3219 sharkd_json_value_string("tap", voip_convs_req->tap_name);
3220 sharkd_json_value_string("type", "voip-convs");
3221 sharkd_json_array_open("convs");
3222 for (GList *cur = g_queue_peek_nth_link(sainfo->items, 0); cur; cur = g_list_next(cur)) {
3223 seq_analysis_item_t *sai = (seq_analysis_item_t *) cur->data;
3224 if ((voip_conv_sel[sai->conv_num / VOIP_CONV_BITS] & (1 << (sai->conv_num % VOIP_CONV_BITS))) == 0)
3225 continue;
3226 sharkd_json_object_open(NULL);
3227 sharkd_json_value_anyf("frame", "%d", sai->frame_number);
3228 sharkd_json_value_anyf("call", "%d", sai->conv_num);
3229 sharkd_json_value_string("time", sai->time_str);
3230 addr_str = address_to_display(NULL, &(sai->dst_addr));
3231 sharkd_json_value_string("dst_addr", addr_str);
3232 wmem_free(NULL, addr_str);
3233 sharkd_json_value_anyf("dst_port", "%d", sai->port_dst);
3234 addr_str = address_to_display(NULL, &(sai->src_addr));
3235 sharkd_json_value_string("src_addr", addr_str);
3236 wmem_free(NULL, addr_str);
3237 sharkd_json_value_anyf("src_port", "%d", sai->port_src);
3238 sharkd_json_value_string("label", sai->frame_label);
3239 sharkd_json_value_string("comment", sai->comment);
3240 sharkd_json_object_close();
3242 sharkd_json_array_close();
3243 sharkd_json_object_close();
3246 static void
3247 sharkd_session_free_tap_voip_convs_cb(void *tapdata)
3249 struct sharkd_voip_convs_req *voip_convs_req = (struct sharkd_voip_convs_req *)tapdata;
3250 voip_calls_tapinfo_t *tapinfo = voip_convs_req->tapinfo;
3251 voip_calls_remove_all_tap_listeners(tapinfo);
3252 if (tapinfo->callsinfos != NULL) {
3253 g_queue_free(tapinfo->callsinfos);
3255 if (tapinfo->graph_analysis != NULL) {
3256 sequence_analysis_info_free(tapinfo->graph_analysis);
3258 memset(tapinfo, 0, sizeof(*tapinfo));
3259 g_free(voip_convs_req);
3262 struct sharkd_hosts_req {
3263 const char *tap_name;
3264 bool dump_v4;
3265 bool dump_v6;
3268 static int
3269 sharkd_session_tap_ipv4_host_compare(const void *a, const void *b)
3271 return ws_ascii_strnatcmp(((const hashipv4_t *)a)->name,
3272 ((const hashipv4_t *)b)->name);
3275 static int
3276 sharkd_session_tap_ipv6_host_compare(const void *a, const void *b)
3278 return ws_ascii_strnatcmp(((const hashipv6_t *)a)->name,
3279 ((const hashipv6_t *)b)->name);
3282 static void
3283 sharkd_session_tap_ipv4_host_print(void *data, void *user_data _U_)
3285 hashipv4_t *ipv4_hash_table_entry = (hashipv4_t *)data;
3286 sharkd_json_object_open(NULL);
3287 sharkd_json_value_string("name", ipv4_hash_table_entry->name);
3288 sharkd_json_value_string("addr", ipv4_hash_table_entry->ip);
3289 sharkd_json_object_close();
3292 static void
3293 sharkd_session_tap_ipv6_host_print(void *data, void *user_data _U_)
3295 hashipv6_t *ipv6_hash_table_entry = (hashipv6_t *)data;
3296 sharkd_json_object_open(NULL);
3297 sharkd_json_value_string("name", ipv6_hash_table_entry->name);
3298 sharkd_json_value_string("addr", ipv6_hash_table_entry->ip6);
3299 sharkd_json_object_close();
3302 static void
3303 sharkd_session_tap_ipv4_host_insert_sorted(void *key _U_, void *value, void *user_data)
3305 hashipv4_t *ipv4_hash_table_entry = (hashipv4_t *)value;
3306 GSList **list = (GSList **)user_data;
3307 if ((ipv4_hash_table_entry->flags & NAME_RESOLVED)) {
3308 *list = g_slist_insert_sorted(*list, ipv4_hash_table_entry, sharkd_session_tap_ipv4_host_compare);
3312 static void
3313 sharkd_session_tap_ipv6_host_insert_sorted(void *key _U_, void *value, void *user_data)
3315 hashipv6_t *ipv6_hash_table_entry = (hashipv6_t *)value;
3316 GSList **list = (GSList **) user_data;
3317 if ((ipv6_hash_table_entry->flags & NAME_RESOLVED)) {
3318 *list = g_slist_insert_sorted(*list, ipv6_hash_table_entry, sharkd_session_tap_ipv6_host_compare);
3322 static void
3323 sharkd_session_tap_ipv4_hosts_print(void)
3325 wmem_map_t *ipv4_hash_table = get_ipv4_hash_table();
3326 if (!ipv4_hash_table)
3327 return;
3328 GSList *list = NULL;
3329 wmem_map_foreach(ipv4_hash_table, sharkd_session_tap_ipv4_host_insert_sorted, &list);
3330 g_slist_foreach(list, sharkd_session_tap_ipv4_host_print, NULL);
3331 g_slist_free(list);
3334 static void
3335 sharkd_session_tap_ipv6_hosts_print(void)
3337 wmem_map_t *ipv6_hash_table = get_ipv6_hash_table();
3338 if (!ipv6_hash_table)
3339 return;
3340 GSList *list = NULL;
3341 wmem_map_foreach(ipv6_hash_table, sharkd_session_tap_ipv6_host_insert_sorted, &list);
3342 g_slist_foreach(list, sharkd_session_tap_ipv6_host_print, NULL);
3343 g_slist_free(list);
3347 * sharkd_session_process_tap_hosts_cb()
3349 * Output Hosts tap:
3350 * (m) tap - tap name
3351 * (m) type - tap output type
3352 * (o) ipv4_hosts - array of objects with attributes:
3353 * (m) addr - ipv4 address
3354 * (m) name - resolved name of address
3355 * (o) ipv6_hosts - array of objects with attributes:
3356 * (m) addr - ipv6 address
3357 * (m) name - resolved name of address
3359 static void
3360 sharkd_session_process_tap_hosts_cb(void *arg)
3362 struct sharkd_hosts_req *hosts_req = (struct sharkd_hosts_req *)arg;
3363 sharkd_json_object_open(NULL);
3364 sharkd_json_value_string("tap", hosts_req->tap_name);
3365 sharkd_json_value_string("type", "hosts");
3366 if (hosts_req->dump_v4) {
3367 sharkd_json_array_open("ipv4_hosts");
3368 sharkd_session_tap_ipv4_hosts_print();
3369 sharkd_json_array_close();
3371 if (hosts_req->dump_v6) {
3372 sharkd_json_array_open("ipv6_hosts");
3373 sharkd_session_tap_ipv6_hosts_print();
3374 sharkd_json_array_close();
3376 sharkd_json_object_close();
3379 static void
3380 sharkd_session_free_tap_hosts_cb(void *tapdata)
3382 struct sharkd_hosts_req *hosts_req = (struct sharkd_hosts_req *)tapdata;
3383 g_free(hosts_req);
3386 static GString*
3387 sharkd_session_eo_register_tap_listener(register_eo_t *eo, const char *tap_type, const char *tap_filter, tap_draw_cb tap_draw, void **ptap_data, GFreeFunc* ptap_free)
3389 export_object_list_t *eo_object;
3390 struct sharkd_export_object_list *object_list;
3392 object_list = sharkd_eo_object_list_get_entry_by_type(sharkd_eo_list, tap_type);
3393 if (object_list)
3395 g_slist_free_full(object_list->entries, (GDestroyNotify) eo_free_entry);
3396 object_list->entries = NULL;
3398 else
3400 object_list = g_new(struct sharkd_export_object_list, 1);
3401 object_list->type = g_strdup(tap_type);
3402 object_list->proto = proto_get_protocol_short_name(find_protocol_by_id(get_eo_proto_id(eo)));
3403 object_list->entries = NULL;
3404 object_list->next = sharkd_eo_list;
3405 sharkd_eo_list = object_list;
3408 eo_object = g_new0(export_object_list_t, 1);
3409 eo_object->add_entry = sharkd_eo_object_list_add_entry;
3410 eo_object->get_entry = sharkd_eo_object_list_get_entry;
3411 eo_object->gui_data = (void *) object_list;
3413 *ptap_data = eo_object;
3414 *ptap_free = g_free; /* need to free only eo_object, object_list need to be kept for potential download */
3416 return register_tap_listener(get_eo_tap_listener_name(eo), eo_object, tap_filter, 0, NULL, get_eo_packet_func(eo), tap_draw, NULL);
3420 * sharkd_session_process_tap()
3422 * Process tap request
3424 * Input:
3425 * (m) tap0 - First tap request
3426 * (o) tap1...tap15 - Other tap requests
3428 * Output object with attributes:
3429 * (m) taps - array of object with attributes:
3430 * (m) tap - tap name
3431 * (m) type - tap output type
3432 * ...
3433 * for type:stats see sharkd_session_process_tap_stats_cb()
3434 * for type:nstat see sharkd_session_process_tap_nstat_cb()
3435 * for type:conv see sharkd_session_process_tap_conv_cb()
3436 * for type:host see sharkd_session_process_tap_conv_cb()
3437 * for type:rtp-streams see sharkd_session_process_tap_rtp_cb()
3438 * for type:rtp-analyse see sharkd_session_process_tap_rtp_analyse_cb()
3439 * for type:eo see sharkd_session_process_tap_eo_cb()
3440 * for type:expert see sharkd_session_process_tap_expert_cb()
3441 * for type:rtd see sharkd_session_process_tap_rtd_cb()
3442 * for type:srt see sharkd_session_process_tap_srt_cb()
3443 * for type:flow see sharkd_session_process_tap_flow_cb()
3445 * (m) err - error code
3447 static void
3448 sharkd_session_process_tap(char *buf, const jsmntok_t *tokens, int count)
3450 void *taps_data[16];
3451 GFreeFunc taps_free[16];
3452 int taps_count = 0;
3453 int i;
3454 const char *tap_filter = json_find_attr(buf, tokens, count, "filter");
3456 rtpstream_tapinfo_t rtp_tapinfo =
3457 { NULL, NULL, NULL, NULL, 0, NULL, NULL, 0, TAP_ANALYSE, NULL, NULL, NULL, false, false};
3459 for (i = 0; i < 16; i++)
3461 char tapbuf[32];
3462 const char *tok_tap;
3464 void *tap_data = NULL;
3465 GFreeFunc tap_free = NULL;
3466 GString *tap_error = NULL;
3468 snprintf(tapbuf, sizeof(tapbuf), "tap%d", i);
3469 tok_tap = json_find_attr(buf, tokens, count, tapbuf);
3470 if (!tok_tap)
3471 break;
3473 if (!strncmp(tok_tap, "stat:", 5))
3475 stats_tree_cfg *cfg = stats_tree_get_cfg_by_abbr(tok_tap + 5);
3476 stats_tree *st;
3478 if (!cfg)
3480 sharkd_json_error(
3481 rpcid, -11001, NULL,
3482 "sharkd_session_process_tap() stat %s not found", tok_tap + 5
3484 return;
3487 st = stats_tree_new(cfg, NULL, tap_filter);
3489 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, NULL);
3491 if (!tap_error && cfg->init)
3492 cfg->init(st);
3494 tap_data = st;
3495 tap_free = sharkd_session_free_tap_stats_cb;
3497 else if (!strcmp(tok_tap, "expert"))
3499 struct sharkd_expert_tap *expert_tap;
3501 expert_tap = g_new0(struct sharkd_expert_tap, 1);
3502 expert_tap->text = g_string_chunk_new(100);
3504 tap_error = register_tap_listener("expert", expert_tap, tap_filter, 0, NULL, sharkd_session_packet_tap_expert_cb, sharkd_session_process_tap_expert_cb, NULL);
3506 tap_data = expert_tap;
3507 tap_free = sharkd_session_free_tap_expert_cb;
3509 else if (!strncmp(tok_tap, "seqa:", 5))
3511 seq_analysis_info_t *graph_analysis;
3512 register_analysis_t *analysis;
3513 const char *tap_name;
3514 tap_packet_cb tap_func;
3515 unsigned tap_flags;
3517 analysis = sequence_analysis_find_by_name(tok_tap + 5);
3518 if (!analysis)
3520 sharkd_json_error(
3521 rpcid, -11002, NULL,
3522 "sharkd_session_process_tap() seq analysis %s not found", tok_tap + 5
3524 return;
3527 graph_analysis = sequence_analysis_info_new();
3528 graph_analysis->name = tok_tap + 5;
3529 /* TODO, make configurable */
3530 graph_analysis->any_addr = false;
3532 tap_name = sequence_analysis_get_tap_listener_name(analysis);
3533 tap_flags = sequence_analysis_get_tap_flags(analysis);
3534 tap_func = sequence_analysis_get_packet_func(analysis);
3536 tap_error = register_tap_listener(tap_name, graph_analysis, tap_filter, tap_flags, NULL, tap_func, sharkd_session_process_tap_flow_cb, NULL);
3538 tap_data = graph_analysis;
3539 tap_free = sharkd_session_free_tap_flow_cb;
3541 else if (!strncmp(tok_tap, "conv:", 5) || !strncmp(tok_tap, "endpt:", 6))
3543 struct register_ct *ct = NULL;
3544 const char *ct_tapname;
3545 struct sharkd_conv_tap_data *ct_data;
3546 tap_packet_cb tap_func = NULL;
3548 if (!strncmp(tok_tap, "conv:", 5))
3550 ct = get_conversation_by_proto_id(proto_get_id_by_short_name(tok_tap + 5));
3552 if (!ct || !(tap_func = get_conversation_packet_func(ct)))
3554 sharkd_json_error(
3555 rpcid, -11003, NULL,
3556 "sharkd_session_process_tap() conv %s not found", tok_tap + 5
3558 return;
3561 else if (!strncmp(tok_tap, "endpt:", 6))
3563 ct = get_conversation_by_proto_id(proto_get_id_by_short_name(tok_tap + 6));
3565 if (!ct || !(tap_func = get_endpoint_packet_func(ct)))
3567 sharkd_json_error(
3568 rpcid, -11004, NULL,
3569 "sharkd_session_process_tap() endpt %s not found", tok_tap + 6
3571 return;
3574 else
3576 sharkd_json_error(
3577 rpcid, -11005, NULL,
3578 "sharkd_session_process_tap() conv/endpt(?): %s not found", tok_tap
3580 return;
3583 ct_tapname = proto_get_protocol_filter_name(get_conversation_proto_id(ct));
3585 ct_data = g_new0(struct sharkd_conv_tap_data, 1);
3586 ct_data->type = tok_tap;
3587 ct_data->hash.user_data = ct_data;
3589 /* XXX: make configurable */
3590 ct_data->resolve_name = true;
3591 ct_data->resolve_port = true;
3593 tap_error = register_tap_listener(ct_tapname, &ct_data->hash, tap_filter, 0, NULL, tap_func, sharkd_session_process_tap_conv_cb, NULL);
3595 tap_data = &ct_data->hash;
3596 tap_free = sharkd_session_free_tap_conv_cb;
3598 else if (!strncmp(tok_tap, "nstat:", 6))
3600 stat_tap_table_ui *stat_tap = stat_tap_by_name(tok_tap + 6);
3601 stat_data_t *stat_data;
3603 if (!stat_tap)
3605 sharkd_json_error(
3606 rpcid, -11006, NULL,
3607 "sharkd_session_process_tap() nstat=%s not found", tok_tap + 6
3609 return;
3612 stat_tap->stat_tap_init_cb(stat_tap);
3614 stat_data = g_new0(stat_data_t, 1);
3615 stat_data->stat_tap_data = stat_tap;
3616 stat_data->user_data = NULL;
3618 tap_error = register_tap_listener(stat_tap->tap_name, stat_data, tap_filter, 0, NULL, stat_tap->packet_func, sharkd_session_process_tap_nstat_cb, NULL);
3620 tap_data = stat_data;
3621 tap_free = sharkd_session_free_tap_nstat_cb;
3623 else if (!strncmp(tok_tap, "rtd:", 4))
3625 register_rtd_t *rtd = get_rtd_table_by_name(tok_tap + 4);
3626 rtd_data_t *rtd_data;
3627 char *err;
3629 if (!rtd)
3631 sharkd_json_error(
3632 rpcid, -11007, NULL,
3633 "sharkd_session_process_tap() rtd=%s not found", tok_tap + 4
3635 return;
3638 rtd_table_get_filter(rtd, "", &tap_filter, &err);
3639 if (err != NULL)
3641 sharkd_json_error(
3642 rpcid, -11008, NULL,
3643 "sharkd_session_process_tap() rtd=%s err=%s", tok_tap + 4, err
3645 g_free(err);
3646 return;
3649 rtd_data = g_new0(rtd_data_t, 1);
3650 rtd_data->user_data = rtd;
3651 rtd_table_dissector_init(rtd, &rtd_data->stat_table, NULL, NULL);
3653 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, NULL);
3655 tap_data = rtd_data;
3656 tap_free = sharkd_session_free_tap_rtd_cb;
3658 else if (!strncmp(tok_tap, "srt:", 4))
3660 register_srt_t *srt = get_srt_table_by_name(tok_tap + 4);
3661 srt_data_t *srt_data;
3662 char *err;
3664 if (!srt)
3666 sharkd_json_error(
3667 rpcid, -11009, NULL,
3668 "sharkd_session_process_tap() srt=%s not found", tok_tap + 4
3670 return;
3673 srt_table_get_filter(srt, "", &tap_filter, &err);
3674 if (err != NULL)
3676 sharkd_json_error(
3677 rpcid, -11010, NULL,
3678 "sharkd_session_process_tap() srt=%s err=%s", tok_tap + 4, err
3680 g_free(err);
3681 return;
3684 srt_data = g_new0(srt_data_t, 1);
3685 srt_data->srt_array = g_array_new(FALSE, TRUE, sizeof(srt_stat_table *));
3686 srt_data->user_data = srt;
3687 srt_table_dissector_init(srt, srt_data->srt_array);
3689 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, NULL);
3691 tap_data = srt_data;
3692 tap_free = sharkd_session_free_tap_srt_cb;
3694 else if (!strncmp(tok_tap, "eo:", 3))
3696 register_eo_t *eo = get_eo_by_name(tok_tap + 3);
3698 if (!eo)
3700 sharkd_json_error(
3701 rpcid, -11011, NULL,
3702 "sharkd_session_process_tap() eo=%s not found", tok_tap + 3
3704 return;
3707 tap_error = sharkd_session_eo_register_tap_listener(eo, tok_tap, tap_filter, sharkd_session_process_tap_eo_cb, &tap_data, &tap_free);
3709 /* tap_data & tap_free assigned by sharkd_session_eo_register_tap_listener */
3711 else if (!strcmp(tok_tap, "rtp-streams"))
3713 tap_error = register_tap_listener("rtp", &rtp_tapinfo, tap_filter, 0, rtpstream_reset_cb, rtpstream_packet_cb, sharkd_session_process_tap_rtp_cb, NULL);
3715 tap_data = &rtp_tapinfo;
3716 tap_free = rtpstream_reset_cb;
3718 else if (!strncmp(tok_tap, "rtp-analyse:", 12))
3720 struct sharkd_analyse_rtp *rtp_req;
3722 rtp_req = (struct sharkd_analyse_rtp *) g_malloc0(sizeof(*rtp_req));
3723 if (!sharkd_rtp_match_init(&rtp_req->id, tok_tap + 12))
3725 rtpstream_id_free(&rtp_req->id);
3726 g_free(rtp_req);
3727 continue;
3730 rtp_req->tap_name = tok_tap;
3731 rtp_req->statinfo.first_packet = true;
3732 rtp_req->statinfo.reg_pt = PT_UNDEFINED;
3734 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, NULL);
3736 tap_data = rtp_req;
3737 tap_free = sharkd_session_process_tap_rtp_free_cb;
3739 else if (!strcmp(tok_tap, "multicast"))
3741 mcaststream_tapinfo_t *mcaststream_tapinfo;
3742 mcaststream_tapinfo = (mcaststream_tapinfo_t *) g_malloc0(sizeof(*mcaststream_tapinfo));
3744 tap_error = register_tap_listener("udp", mcaststream_tapinfo, tap_filter, 0, NULL, mcaststream_packet, sharkd_session_process_tap_multicast_cb, NULL);
3745 tap_data = mcaststream_tapinfo;
3746 tap_free = sharkd_session_process_free_tap_multicast_cb;
3748 else if (!strcmp(tok_tap, "phs"))
3750 phs_t *rs;
3752 pc_proto_id = proto_registrar_get_id_byname("pkt_comment");
3754 rs = new_phs_t(NULL, tap_filter);
3756 tap_error = register_tap_listener("frame", rs, tap_filter,
3757 TL_REQUIRES_PROTO_TREE|TL_REQUIRES_PROTOCOLS,
3758 NULL, protohierstat_packet,
3759 sharkd_session_process_tap_phs_cb, NULL);
3761 tap_data = rs;
3762 tap_free = sharkd_session_free_tap_phs_cb;
3764 else if (!strcmp(tok_tap, "voip-calls"))
3766 voip_stat_init_tapinfo();
3768 tap_error = register_tap_listener("frame", &tapinfo_, tap_filter, 0, NULL, NULL, sharkd_session_process_tap_voip_calls_cb, NULL);
3770 tapinfo_.session = cfile.epan;
3771 voip_calls_init_all_taps(&tapinfo_);
3773 tap_data = &tapinfo_;
3774 tap_free = sharkd_session_free_tap_voip_calls_cb;
3776 else if (!strncmp(tok_tap, "voip-convs:", 11))
3778 int len;
3779 unsigned int min, max;
3780 struct sharkd_voip_convs_req *voip_convs_req;
3781 const char *conv_arg = tok_tap + 11;
3783 // parse tok_tap to get which call we are asking for
3784 if (*conv_arg == 0) {
3785 // set all bits of voip_conv_sel (-1 in binary is all 1's)
3786 memset(voip_conv_sel, -1, sizeof(voip_conv_sel));
3787 } else {
3788 memset(voip_conv_sel, 0, sizeof(voip_conv_sel));
3790 while (*conv_arg != 0) {
3791 if (*conv_arg == ',') {
3792 conv_arg++;
3794 if (sscanf(conv_arg, "%u-%u%n", &min, &max, &len) == 2) {
3795 conv_arg += len;
3796 } else if (sscanf(conv_arg, "%u%n", &min, &len) == 1) {
3797 max = min;
3798 conv_arg += len;
3799 } else {
3800 sharkd_json_error(
3801 rpcid, -11014, NULL,
3802 "sharkd_session_process_tap() voip-convs=%s invalid 'convs' parameter", tok_tap
3804 return;
3806 if (min > max || min >= VOIP_CONV_MAX || max >= VOIP_CONV_MAX) {
3807 sharkd_json_error(
3808 rpcid, -11012, NULL,
3809 "sharkd_session_process_tap() voip-convs=%s invalid 'convs' number range", tok_tap
3811 return;
3813 for(; min <= max; min++) {
3814 voip_conv_sel[min / VOIP_CONV_BITS] |= 1 << (min % VOIP_CONV_BITS);
3819 voip_stat_init_tapinfo();
3821 voip_convs_req = (struct sharkd_voip_convs_req *) g_malloc0(sizeof(*voip_convs_req));
3822 voip_convs_req->tapinfo = &tapinfo_;
3823 voip_convs_req->tap_name = tok_tap;
3825 tap_error = register_tap_listener("frame", voip_convs_req, tap_filter, 0, NULL, NULL, sharkd_session_process_tap_voip_convs_cb, NULL);
3827 tapinfo_.session = cfile.epan;
3828 voip_calls_init_all_taps(&tapinfo_);
3830 tap_data = voip_convs_req;
3831 tap_free = sharkd_session_free_tap_voip_convs_cb;
3833 else if (!strncmp(tok_tap, "hosts:", 6))
3835 bool dump_v4;
3836 bool dump_v6;
3837 struct sharkd_hosts_req *hosts_req;
3838 const char *proto_arg;
3839 char **proto_tokens;
3840 int proto_count;
3842 proto_arg = tok_tap + 6;
3844 if (strlen(proto_arg) == 0) {
3845 dump_v4 = true;
3846 dump_v6 = true;
3847 } else {
3848 dump_v4 = false;
3849 dump_v6 = false;
3851 proto_tokens = g_strsplit(proto_arg, ",", 0);
3852 proto_count = 0;
3853 while (proto_tokens[proto_count]) {
3854 if (!strcmp("ip", proto_tokens[proto_count]) ||
3855 !strcmp("ipv4", proto_tokens[proto_count])) {
3856 dump_v4 = true;
3857 } else if (!strcmp("ipv6", proto_tokens[proto_count])) {
3858 dump_v6 = true;
3859 } else {
3860 g_strfreev(proto_tokens);
3861 sharkd_json_error(
3862 rpcid, -11015, NULL,
3863 "sharkd_session_process_tap() hosts=%s invalid 'protos' parameter", tok_tap
3865 return;
3867 proto_count++;
3869 g_strfreev(proto_tokens);
3872 hosts_req = (struct sharkd_hosts_req *)g_malloc0(sizeof(*hosts_req));
3873 hosts_req->dump_v4 = dump_v4;
3874 hosts_req->dump_v6 = dump_v6;
3875 hosts_req->tap_name = tok_tap;
3877 tap_error = register_tap_listener("frame", hosts_req, tap_filter, TL_REQUIRES_PROTO_TREE, NULL, NULL, sharkd_session_process_tap_hosts_cb, NULL);
3879 tap_data = hosts_req;
3880 tap_free = sharkd_session_free_tap_hosts_cb;
3882 else
3884 sharkd_json_error(
3885 rpcid, -11012, NULL,
3886 "sharkd_session_process_tap() %s not recognized", tok_tap
3888 return;
3891 if (tap_error)
3893 sharkd_json_error(
3894 rpcid, -11013, NULL,
3895 "sharkd_session_process_tap() name=%s error=%s", tok_tap, tap_error->str
3897 g_string_free(tap_error, TRUE);
3898 if (tap_free)
3899 tap_free(tap_data);
3900 return;
3903 taps_data[taps_count] = tap_data;
3904 taps_free[taps_count] = tap_free;
3905 taps_count++;
3908 fprintf(stderr, "sharkd_session_process_tap() count=%d\n", taps_count);
3909 if (taps_count == 0)
3911 sharkd_json_result_prologue(rpcid);
3912 sharkd_json_array_open("taps");
3913 sharkd_json_array_close();
3914 sharkd_json_result_epilogue();
3915 return;
3918 sharkd_json_result_prologue(rpcid);
3919 sharkd_json_array_open("taps");
3920 sharkd_retap();
3921 sharkd_json_array_close();
3922 sharkd_json_result_epilogue();
3924 for (i = 0; i < taps_count; i++)
3926 if (taps_data[i])
3927 remove_tap_listener(taps_data[i]);
3929 if (taps_free[i])
3930 taps_free[i](taps_data[i]);
3935 * sharkd_session_process_follow()
3937 * Process follow request
3939 * Input:
3940 * (m) follow - follow protocol request (e.g. HTTP)
3941 * (m) filter - filter request (e.g. tcp.stream == 1)
3942 * (m) stream - stream index number
3943 * (o) sub_stream - follow sub-stream index number (e.g. for HTTP/2 and QUIC streams)
3945 * Output object with attributes:
3947 * (m) err - error code
3948 * (m) shost - server host
3949 * (m) sport - server port
3950 * (m) sbytes - server send bytes count
3951 * (m) chost - client host
3952 * (m) cport - client port
3953 * (m) cbytes - client send bytes count
3954 * (o) payloads - array of object with attributes:
3955 * (o) s - set if server sent, else client
3956 * (m) n - packet number
3957 * (m) d - data base64 encoded
3959 static void
3960 sharkd_session_process_follow(char *buf, const jsmntok_t *tokens, int count)
3962 const char *tok_follow = json_find_attr(buf, tokens, count, "follow");
3963 const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
3964 const char *tok_sub_stream = json_find_attr(buf, tokens, count, "sub_stream");
3966 register_follow_t *follower;
3967 GString *tap_error;
3969 follow_info_t *follow_info;
3970 const char *host;
3971 char *port;
3973 follower = get_follow_by_name(tok_follow);
3974 if (!follower)
3976 sharkd_json_error(
3977 rpcid, -12001, NULL,
3978 "sharkd_session_process_follow() follower=%s not found", tok_follow
3980 return;
3983 uint64_t substream_id = SUBSTREAM_UNUSED;
3984 if (tok_sub_stream)
3986 ws_strtou64(tok_sub_stream, NULL, &substream_id);
3989 /* follow_reset_stream ? */
3990 follow_info = g_new0(follow_info_t, 1);
3991 follow_info->substream_id = substream_id;
3992 /* gui_data, filter_out_filter not set, but not used by dissector */
3994 tap_error = register_tap_listener(get_follow_tap_string(follower), follow_info, tok_filter, 0, NULL, get_follow_tap_handler(follower), NULL, NULL);
3995 if (tap_error)
3997 sharkd_json_error(
3998 rpcid, -12002, NULL,
3999 "sharkd_session_process_follow() name=%s error=%s", tok_follow, tap_error->str
4001 g_string_free(tap_error, TRUE);
4002 g_free(follow_info);
4003 return;
4006 sharkd_retap();
4008 sharkd_json_result_prologue(rpcid);
4010 /* Server information: hostname, port, bytes sent */
4011 host = address_to_name(&follow_info->server_ip);
4012 sharkd_json_value_string("shost", host);
4014 port = get_follow_port_to_display(follower)(NULL, follow_info->server_port);
4015 sharkd_json_value_string("sport", port);
4016 wmem_free(NULL, port);
4018 sharkd_json_value_anyf("sbytes", "%u", follow_info->bytes_written[0]);
4020 /* Client information: hostname, port, bytes sent */
4021 host = address_to_name(&follow_info->client_ip);
4022 sharkd_json_value_string("chost", host);
4024 port = get_follow_port_to_display(follower)(NULL, follow_info->client_port);
4025 sharkd_json_value_string("cport", port);
4026 wmem_free(NULL, port);
4028 sharkd_json_value_anyf("cbytes", "%u", follow_info->bytes_written[1]);
4030 if (follow_info->payload)
4032 follow_record_t *follow_record;
4033 GList *cur;
4035 sharkd_json_array_open("payloads");
4036 for (cur = g_list_last(follow_info->payload); cur; cur = g_list_previous(cur))
4038 follow_record = (follow_record_t *) cur->data;
4040 json_dumper_begin_object(&dumper);
4042 sharkd_json_value_anyf("n", "%u", follow_record->packet_num);
4043 sharkd_json_value_base64("d", follow_record->data->data, follow_record->data->len);
4045 if (follow_record->is_server)
4046 sharkd_json_value_anyf("s", "%d", 1);
4048 json_dumper_end_object(&dumper);
4050 sharkd_json_array_close();
4053 sharkd_json_result_epilogue();
4055 remove_tap_listener(follow_info);
4056 follow_info_free(follow_info);
4059 static void
4060 sharkd_session_process_frame_cb_tree(const char *key, epan_dissect_t *edt, proto_tree *tree, tvbuff_t **tvbs, bool display_hidden)
4062 proto_node *node;
4064 sharkd_json_array_open(key);
4065 for (node = tree->first_child; node; node = node->next)
4067 field_info *finfo = PNODE_FINFO(node);
4069 if (!finfo)
4070 continue;
4072 if (!display_hidden && FI_GET_FLAG(finfo, FI_HIDDEN))
4073 continue;
4075 json_dumper_begin_object(&dumper);
4077 if (!finfo->rep)
4079 char label_str[ITEM_LABEL_LENGTH];
4081 label_str[0] = '\0';
4082 proto_item_fill_label(finfo, label_str, NULL);
4083 sharkd_json_value_string("l", label_str);
4085 else
4087 sharkd_json_value_string("l", finfo->rep->representation);
4090 if (finfo->ds_tvb && tvbs && tvbs[0] != finfo->ds_tvb)
4092 int idx;
4094 for (idx = 1; tvbs[idx]; idx++)
4096 if (tvbs[idx] == finfo->ds_tvb)
4098 sharkd_json_value_anyf("ds", "%d", idx);
4099 break;
4104 if (finfo->start >= 0 && finfo->length > 0)
4105 sharkd_json_value_anyf("h", "[%d,%d]", finfo->start, finfo->length);
4107 if (finfo->appendix_start >= 0 && finfo->appendix_length > 0)
4108 sharkd_json_value_anyf("i", "[%d,%d]", finfo->appendix_start, finfo->appendix_length);
4111 if (finfo->hfinfo)
4113 char *filter;
4115 if (finfo->hfinfo->type == FT_PROTOCOL)
4117 sharkd_json_value_string("t", "proto");
4119 else if (finfo->hfinfo->type == FT_FRAMENUM)
4121 sharkd_json_value_string("t", "framenum");
4122 sharkd_json_value_anyf("fnum", "%u", fvalue_get_uinteger(finfo->value));
4124 else if (FI_GET_FLAG(finfo, FI_URL) && FT_IS_STRING(finfo->hfinfo->type))
4126 char *url = fvalue_to_string_repr(NULL, finfo->value, FTREPR_DISPLAY, finfo->hfinfo->display);
4128 sharkd_json_value_string("t", "url");
4129 sharkd_json_value_string("url", url);
4130 wmem_free(NULL, url);
4133 filter = proto_construct_match_selected_string(finfo, edt);
4134 if (filter)
4136 sharkd_json_value_string("f", filter);
4137 wmem_free(NULL, filter);
4140 if (finfo->hfinfo->abbrev)
4141 sharkd_json_value_string("fn", finfo->hfinfo->abbrev);
4144 if (FI_GET_FLAG(finfo, FI_GENERATED))
4145 sharkd_json_value_anyf("g", "true");
4147 if (FI_GET_FLAG(finfo, FI_HIDDEN))
4148 sharkd_json_value_anyf("v", "true");
4150 if (FI_GET_FLAG(finfo, PI_SEVERITY_MASK))
4152 const char *severity = try_val_to_str(FI_GET_FLAG(finfo, PI_SEVERITY_MASK), expert_severity_vals);
4154 ws_assert(severity != NULL);
4156 sharkd_json_value_string("s", severity);
4159 if (((proto_tree *) node)->first_child)
4161 if (finfo->tree_type != -1)
4162 sharkd_json_value_anyf("e", "%d", finfo->tree_type);
4164 sharkd_session_process_frame_cb_tree("n", edt, (proto_tree *) node, tvbs, display_hidden);
4167 json_dumper_end_object(&dumper);
4169 sharkd_json_array_close();
4172 static bool
4173 sharkd_follower_visit_layers_cb(const void *key _U_, void *value, void *user_data)
4175 register_follow_t *follower = (register_follow_t *) value;
4176 epan_dissect_t *edt = (epan_dissect_t *) user_data;
4177 packet_info *pi = &edt->pi;
4179 const int proto_id = get_follow_proto_id(follower);
4181 uint32_t ignore_stream;
4182 uint32_t ignore_sub_stream;
4184 if (proto_is_frame_protocol(pi->layers, proto_get_protocol_filter_name(proto_id)))
4186 const char *layer_proto = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
4187 char *follow_filter;
4189 follow_filter = get_follow_conv_func(follower)(edt, pi, &ignore_stream, &ignore_sub_stream);
4191 json_dumper_begin_array(&dumper);
4192 json_dumper_value_string(&dumper, layer_proto);
4193 json_dumper_value_string(&dumper, follow_filter);
4194 json_dumper_end_array(&dumper);
4196 g_free(follow_filter);
4199 return false;
4202 static bool
4203 sharkd_followers_visit_layers_cb(const void *key _U_, void *value, void *user_data)
4205 register_follow_t *follower = (register_follow_t *) value;
4206 epan_dissect_t *edt = (epan_dissect_t *) user_data;
4207 packet_info *pi = &edt->pi;
4209 const int proto_id = get_follow_proto_id(follower);
4211 unsigned stream;
4212 unsigned sub_stream;
4214 if (proto_is_frame_protocol(pi->layers, proto_get_protocol_filter_name(proto_id)))
4216 const char *layer_proto = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
4217 char *follow_filter;
4219 follow_filter = get_follow_conv_func(follower)(edt, pi, &stream, &sub_stream);
4221 sharkd_json_object_open(NULL);
4222 sharkd_json_value_string("protocol", layer_proto);
4223 sharkd_json_value_string("filter", follow_filter);
4224 if (get_follow_stream_count_func(follower) != NULL)
4226 sharkd_json_value_anyf("stream", "%u", stream);
4228 if (get_follow_sub_stream_id_func(follower) != NULL)
4230 sharkd_json_value_anyf("sub_stream", "%u", sub_stream);
4232 sharkd_json_object_close();
4234 g_free(follow_filter);
4237 return false;
4240 struct sharkd_frame_request_data
4242 bool display_hidden;
4245 static void
4246 sharkd_session_process_frame_cb(epan_dissect_t *edt, proto_tree *tree, struct epan_column_info *cinfo, const GSList *data_src, void *data)
4248 packet_info *pi = &edt->pi;
4249 frame_data *fdata = pi->fd;
4250 wtap_block_t pkt_block = NULL;
4252 const struct sharkd_frame_request_data * const req_data = (const struct sharkd_frame_request_data * const) data;
4253 const bool display_hidden = (req_data) ? req_data->display_hidden : false;
4255 sharkd_json_result_prologue(rpcid);
4257 if (fdata->has_modified_block)
4258 pkt_block = sharkd_get_modified_block(fdata);
4259 else
4260 pkt_block = pi->rec->block;
4262 if (pkt_block)
4264 unsigned i;
4265 unsigned n;
4266 char *comment;
4268 n = wtap_block_count_option(pkt_block, OPT_COMMENT);
4270 sharkd_json_array_open("comment");
4271 for (i = 0; i < n; i++) {
4272 if (WTAP_OPTTYPE_SUCCESS == wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT, i, &comment)) {
4273 sharkd_json_value_string(NULL, comment);
4276 sharkd_json_array_close();
4279 if (tree)
4281 tvbuff_t **tvbs = NULL;
4283 /* arrayize data src, to speedup searching for ds_tvb index */
4284 if (data_src && data_src->next /* only needed if there are more than one data source */)
4286 unsigned count = g_slist_length((GSList *) data_src);
4287 unsigned i;
4289 tvbs = (tvbuff_t **) g_malloc0((count + 1) * sizeof(*tvbs));
4291 for (i = 0; i < count; i++)
4293 const struct data_source *src = (const struct data_source *) g_slist_nth_data((GSList *) data_src, i);
4295 tvbs[i] = get_data_source_tvb(src);
4298 tvbs[count] = NULL;
4301 sharkd_session_process_frame_cb_tree("tree", edt, tree, tvbs, display_hidden);
4303 g_free(tvbs);
4306 if (cinfo)
4308 int col;
4310 sharkd_json_array_open("col");
4311 for (col = 0; col < cinfo->num_cols; ++col)
4313 sharkd_json_value_string(NULL, get_column_text(cinfo, col));
4315 sharkd_json_array_close();
4318 if (fdata->ignored)
4319 sharkd_json_value_anyf("i", "true");
4321 if (fdata->marked)
4322 sharkd_json_value_anyf("m", "true");
4324 if (fdata->color_filter)
4326 sharkd_json_value_stringf("bg", "%06x", color_t_to_rgb(&fdata->color_filter->bg_color));
4327 sharkd_json_value_stringf("fg", "%06x", color_t_to_rgb(&fdata->color_filter->fg_color));
4330 if (data_src)
4332 struct data_source *src = (struct data_source *) data_src->data;
4333 bool ds_open = false;
4335 tvbuff_t *tvb;
4336 unsigned length;
4338 tvb = get_data_source_tvb(src);
4339 length = tvb_captured_length(tvb);
4341 if (length != 0)
4343 const unsigned char *cp = tvb_get_ptr(tvb, 0, length);
4345 /* XXX pi.fd->encoding */
4346 sharkd_json_value_base64("bytes", cp, length);
4348 else
4350 sharkd_json_value_base64("bytes", "", 0);
4353 data_src = data_src->next;
4354 if (data_src)
4356 sharkd_json_array_open("ds");
4357 ds_open = true;
4360 while (data_src)
4362 src = (struct data_source *) data_src->data;
4364 json_dumper_begin_object(&dumper);
4367 char *src_name = get_data_source_name(src);
4369 sharkd_json_value_string("name", src_name);
4370 wmem_free(NULL, src_name);
4373 tvb = get_data_source_tvb(src);
4374 length = tvb_captured_length(tvb);
4376 if (length != 0)
4378 const unsigned char *cp = tvb_get_ptr(tvb, 0, length);
4380 /* XXX pi.fd->encoding */
4381 sharkd_json_value_base64("bytes", cp, length);
4383 else
4385 sharkd_json_value_base64("bytes", "", 0);
4388 json_dumper_end_object(&dumper);
4390 data_src = data_src->next;
4393 /* close ds, only if was opened */
4394 if (ds_open)
4395 sharkd_json_array_close();
4398 sharkd_json_array_open("fol");
4399 follow_iterate_followers(sharkd_follower_visit_layers_cb, edt);
4400 sharkd_json_array_close();
4402 sharkd_json_array_open("followers");
4403 follow_iterate_followers(sharkd_followers_visit_layers_cb, edt);
4404 sharkd_json_array_close();
4406 sharkd_json_result_epilogue();
4409 #define SHARKD_IOGRAPH_MAX_ITEMS 1 << 25 /* 33,554,432 limit of items, same as max_io_items_ in ui/qt/io_graph_dialog.h */
4411 struct sharkd_iograph
4413 /* config */
4414 int hf_index;
4415 io_graph_item_unit_t calc_type;
4416 uint32_t interval;
4417 bool aot;
4419 /* result */
4420 int space_items;
4421 int num_items;
4422 io_graph_item_t *items;
4423 GString *error;
4426 static tap_packet_status
4427 sharkd_iograph_packet(void *g, packet_info *pinfo, epan_dissect_t *edt, const void *dummy _U_, tap_flags_t flags _U_)
4429 struct sharkd_iograph *graph = (struct sharkd_iograph *) g;
4430 int idx;
4431 bool update_succeeded;
4433 int64_t tmp_idx = get_io_graph_index(pinfo, graph->interval);
4434 if (tmp_idx < 0 || tmp_idx >= SHARKD_IOGRAPH_MAX_ITEMS)
4435 return TAP_PACKET_DONT_REDRAW;
4437 idx = (int)tmp_idx;
4439 if (idx + 1 > graph->num_items)
4441 if (idx + 1 > graph->space_items)
4443 int new_size = idx + 1024;
4445 graph->items = (io_graph_item_t *) g_realloc(graph->items, sizeof(io_graph_item_t) * new_size);
4446 reset_io_graph_items(&graph->items[graph->space_items], new_size - graph->space_items, graph->hf_index);
4448 graph->space_items = new_size;
4450 else if (graph->items == NULL)
4452 graph->items = g_new(io_graph_item_t, graph->space_items);
4453 reset_io_graph_items(graph->items, graph->space_items, graph->hf_index);
4456 graph->num_items = idx + 1;
4459 update_succeeded = update_io_graph_item(graph->items, idx, pinfo, edt, graph->hf_index, graph->calc_type, graph->interval);
4460 /* XXX - TAP_PACKET_FAILED if the item couldn't be updated, with an error message? */
4461 return update_succeeded ? TAP_PACKET_REDRAW : TAP_PACKET_DONT_REDRAW;
4465 * sharkd_session_process_iograph()
4467 * Process iograph request
4469 * Input:
4470 * (o) interval - interval time, if not specified: 1000
4471 * (o) interval_units - units for interval time, must be 's', 'ms' or 'us', if not specified: ms
4472 * (m) graph0 - First graph request
4473 * (o) graph1...graph9 - Other graph requests
4474 * (o) filter0 - First graph filter
4475 * (o) filter1...filter9 - Other graph filters
4477 * Graph requests can be one of: "packets", "bytes", "bits", "sum:<field>", "frames:<field>", "max:<field>", "min:<field>", "avg:<field>", "load:<field>",
4478 * if you use variant with <field>, you need to pass field name in filter request.
4480 * Output object with attributes:
4481 * (m) iograph - array of graph results with attributes:
4482 * errmsg - graph cannot be constructed
4483 * items - graph values, zeros are skipped, if value is not a number it's next index encoded as hex string
4485 static void
4486 sharkd_session_process_iograph(char *buf, const jsmntok_t *tokens, int count)
4488 const char *tok_interval = json_find_attr(buf, tokens, count, "interval");
4489 const char *tok_interval_units = json_find_attr(buf, tokens, count, "interval_units");
4490 struct sharkd_iograph graphs[10];
4491 bool is_any_ok = false;
4492 int graph_count;
4494 int i;
4496 /* default: 1000ms = one per second */
4497 uint32_t interval = 1000;
4498 const char *interval_units = "ms";
4500 if (tok_interval)
4501 ws_strtou32(tok_interval, NULL, &interval);
4503 if (tok_interval_units)
4505 if (strcmp(tok_interval_units, "us") != 0 &&
4506 strcmp(tok_interval_units, "ms") != 0 &&
4507 strcmp(tok_interval_units, "s") != 0)
4509 sharkd_json_error(
4510 rpcid, -7003, NULL,
4511 "Invalid interval_units parameter: '%s', must be 's', 'ms' or 'us'", tok_interval_units
4513 return;
4515 interval_units = tok_interval_units;
4518 uint32_t interval_us = 0;
4519 if (strcmp(interval_units, "us") == 0)
4521 interval_us = interval;
4523 else if (strcmp(interval_units, "ms") == 0)
4525 interval_us = 1000 * interval;
4527 else if (strcmp(interval_units, "s") == 0)
4529 interval_us = 1000000 * interval;
4532 for (i = graph_count = 0; i < (int) G_N_ELEMENTS(graphs); i++)
4534 struct sharkd_iograph *graph = &graphs[graph_count];
4536 const char *tok_graph;
4537 const char *tok_filter;
4538 char tok_format_buf[32];
4539 const char *field_name;
4540 const char *tok_aot;
4542 snprintf(tok_format_buf, sizeof(tok_format_buf), "graph%d", i);
4543 tok_graph = json_find_attr(buf, tokens, count, tok_format_buf);
4544 if (!tok_graph)
4545 break;
4547 snprintf(tok_format_buf, sizeof(tok_format_buf), "filter%d", i);
4548 tok_filter = json_find_attr(buf, tokens, count, tok_format_buf);
4550 if (!strcmp(tok_graph, "packets"))
4551 graph->calc_type = IOG_ITEM_UNIT_PACKETS;
4552 else if (!strcmp(tok_graph, "bytes"))
4553 graph->calc_type = IOG_ITEM_UNIT_BYTES;
4554 else if (!strcmp(tok_graph, "bits"))
4555 graph->calc_type = IOG_ITEM_UNIT_BITS;
4556 else if (g_str_has_prefix(tok_graph, "sum:"))
4557 graph->calc_type = IOG_ITEM_UNIT_CALC_SUM;
4558 else if (g_str_has_prefix(tok_graph, "frames:"))
4559 graph->calc_type = IOG_ITEM_UNIT_CALC_FRAMES;
4560 else if (g_str_has_prefix(tok_graph, "fields:"))
4561 graph->calc_type = IOG_ITEM_UNIT_CALC_FIELDS;
4562 else if (g_str_has_prefix(tok_graph, "max:"))
4563 graph->calc_type = IOG_ITEM_UNIT_CALC_MAX;
4564 else if (g_str_has_prefix(tok_graph, "min:"))
4565 graph->calc_type = IOG_ITEM_UNIT_CALC_MIN;
4566 else if (g_str_has_prefix(tok_graph, "avg:"))
4567 graph->calc_type = IOG_ITEM_UNIT_CALC_AVERAGE;
4568 else if (g_str_has_prefix(tok_graph, "load:"))
4569 graph->calc_type = IOG_ITEM_UNIT_CALC_LOAD;
4570 else if (g_str_has_prefix(tok_graph, "throughput:"))
4571 graph->calc_type = IOG_ITEM_UNIT_CALC_THROUGHPUT;
4572 else
4573 break;
4575 field_name = strchr(tok_graph, ':');
4576 if (field_name)
4577 field_name = field_name + 1;
4579 /* io_graph_item now supports microseconds (and this parameter
4580 * is expected to be in microseconds.) */
4581 graph->interval = interval_us;
4583 graph->hf_index = -1;
4584 graph->error = check_field_unit(field_name, &graph->hf_index, graph->calc_type);
4586 graph->space_items = 0; /* TODO, can avoid realloc()s in sharkd_iograph_packet() by calculating: capture_time / interval */
4587 graph->num_items = 0;
4588 graph->items = NULL;
4590 snprintf(tok_format_buf, sizeof(tok_format_buf), "aot%d", i);
4591 tok_aot = json_find_attr(buf, tokens, count, tok_format_buf);
4592 if (tok_aot!=NULL) {
4593 graph->aot = (!strcmp(tok_aot, "true")) ? true : false;
4595 else {
4596 graph->aot = false;
4599 if (!graph->error)
4600 graph->error = register_tap_listener("frame", graph, tok_filter, TL_REQUIRES_PROTO_TREE, NULL, sharkd_iograph_packet, NULL, NULL);
4602 graph_count++;
4604 if (graph->error)
4606 sharkd_json_error(
4607 rpcid, -6001, NULL,
4608 "%s", graph->error->str
4610 g_string_free(graph->error, TRUE);
4611 return;
4614 if (graph->error == NULL)
4615 is_any_ok = true;
4618 /* retap only if we have at least one ok */
4619 if (is_any_ok)
4620 sharkd_retap();
4622 sharkd_json_result_prologue(rpcid);
4624 sharkd_json_array_open("iograph");
4625 for (i = 0; i < graph_count; i++)
4627 struct sharkd_iograph *graph = &graphs[i];
4629 json_dumper_begin_object(&dumper);
4631 if (graph->error)
4633 fprintf(stderr, "SNAP 6002 - we should never get to here.\n");
4634 g_string_free(graph->error, TRUE);
4635 exit(-1);
4637 else
4639 int idx;
4640 int next_idx = 0;
4642 sharkd_json_array_open("items");
4643 for (idx = 0; idx < graph->num_items; idx++)
4645 double val;
4647 val = get_io_graph_item(graph->items, graph->calc_type, idx, graph->hf_index, &cfile, graph->interval, graph->num_items, graph->aot);
4649 /* if it's zero, don't display */
4650 if (val == 0.0)
4651 continue;
4653 /* cause zeros are not printed, need to output index */
4654 if (next_idx != idx)
4655 sharkd_json_value_stringf(NULL, "%x", idx);
4657 sharkd_json_value_anyf(NULL, "%f", val);
4658 next_idx = idx + 1;
4660 sharkd_json_array_close();
4662 json_dumper_end_object(&dumper);
4664 remove_tap_listener(graph);
4665 g_free(graph->items);
4667 sharkd_json_array_close();
4669 sharkd_json_result_epilogue();
4673 * sharkd_session_process_intervals()
4675 * Process intervals request - generate basic capture file statistics per requested interval.
4677 * Input:
4678 * (o) interval - interval time in ms, if not specified: 1000ms
4679 * (o) filter - filter for generating interval request
4681 * Output object with attributes:
4682 * (m) intervals - array of intervals, with indexes:
4683 * [0] - index of interval,
4684 * [1] - number of frames during interval,
4685 * [2] - number of bytes during interval.
4687 * (m) last - last interval number.
4688 * (m) frames - total number of frames
4689 * (m) bytes - total number of bytes
4691 * NOTE: If frames are not in order, there might be items with same interval index, or even negative one.
4693 static void
4694 sharkd_session_process_intervals(char *buf, const jsmntok_t *tokens, int count)
4696 const char *tok_interval = json_find_attr(buf, tokens, count, "interval");
4697 const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
4699 const uint8_t *filter_data = NULL;
4701 struct
4703 unsigned int frames;
4704 uint64_t bytes;
4705 } st, st_total;
4707 nstime_t *start_ts;
4709 uint32_t interval_ms = 1000; /* default: one per second */
4711 int64_t idx;
4712 int64_t max_idx = 0;
4714 if (tok_interval)
4715 ws_strtou32(tok_interval, NULL, &interval_ms); // already validated
4717 if (tok_filter)
4719 const struct sharkd_filter_item *filter_item;
4721 filter_item = sharkd_session_filter_data(tok_filter);
4722 if (!filter_item)
4724 sharkd_json_error(
4725 rpcid, -7001, NULL,
4726 "Invalid filter parameter: %s", tok_filter
4728 return;
4730 filter_data = filter_item->filtered;
4733 st_total.frames = 0;
4734 st_total.bytes = 0;
4736 st.frames = 0;
4737 st.bytes = 0;
4739 idx = 0;
4741 sharkd_json_result_prologue(rpcid);
4742 sharkd_json_array_open("intervals");
4744 start_ts = (cfile.count >= 1) ? &(sharkd_get_frame(1)->abs_ts) : NULL;
4746 for (uint32_t framenum = 1; framenum <= cfile.count; framenum++)
4748 frame_data *fdata;
4749 int64_t msec_rel;
4750 int64_t new_idx;
4752 if (filter_data && !(filter_data[framenum / 8] & (1 << (framenum % 8))))
4753 continue;
4755 fdata = sharkd_get_frame(framenum);
4757 msec_rel = (fdata->abs_ts.secs - start_ts->secs) * (int64_t) 1000 + (fdata->abs_ts.nsecs - start_ts->nsecs) / 1000000;
4758 new_idx = msec_rel / interval_ms;
4760 if (idx != new_idx)
4762 if (st.frames != 0)
4764 sharkd_json_value_anyf(NULL, "[%" PRId64 ",%u,%" PRIu64 "]", idx, st.frames, st.bytes);
4767 idx = new_idx;
4768 if (idx > max_idx)
4769 max_idx = idx;
4771 st.frames = 0;
4772 st.bytes = 0;
4775 st.frames += 1;
4776 st.bytes += fdata->pkt_len;
4778 st_total.frames += 1;
4779 st_total.bytes += fdata->pkt_len;
4782 if (st.frames != 0)
4784 sharkd_json_value_anyf(NULL, "[%" PRId64 ",%u,%" PRIu64 "]", idx, st.frames, st.bytes);
4786 sharkd_json_array_close();
4788 sharkd_json_value_anyf("last", "%" PRId64, max_idx);
4789 sharkd_json_value_anyf("frames", "%u", st_total.frames);
4790 sharkd_json_value_anyf("bytes", "%" PRIu64, st_total.bytes);
4792 sharkd_json_result_epilogue();
4796 * sharkd_session_process_frame()
4798 * Process frame request
4800 * Input:
4801 * (m) frame - requested frame number
4802 * (o) ref_frame - time reference frame number
4803 * (o) prev_frame - previously displayed frame number
4804 * (o) proto - set if output frame tree
4805 * (o) columns - set if output frame columns
4806 * (o) color - set if output color-filter bg/fg
4807 * (o) bytes - set if output frame bytes
4808 * (o) hidden - set if output hidden tree fields
4810 * Output object with attributes:
4811 * (m) err - 0 if succeed
4812 * (o) tree - array of frame nodes with attributes:
4813 * l - label
4814 * t: 'proto', 'framenum', 'url' - type of node
4815 * f - filter string
4816 * fn - field name
4817 * s - severity
4818 * e - subtree ett index
4819 * n - array of subtree nodes
4820 * h - two item array: (item start, item length)
4821 * i - two item array: (appendix start, appendix length)
4822 * p - [RESERVED] two item array: (protocol start, protocol length)
4823 * ds- data src index
4824 * url - only for t:'url', url
4825 * fnum - only for t:'framenum', frame number
4826 * g - if field is generated by Wireshark
4827 * v - if field is hidden
4829 * (o) col - array of column data
4830 * (o) bytes - base64 of frame bytes
4831 * (o) ds - array of other data srcs
4832 * (o) comment - frame comment
4833 * (o) fol - array of follow filters:
4834 * [0] - protocol
4835 * [1] - filter string
4836 * (o) followers - array of followers with attributes:
4837 * protocol - protocol string
4838 * filter - filter string
4839 * stream - stream index number
4840 * sub_stream - sub-stream index number (optional, e.g. for HTTP/2 and QUIC streams)
4841 * (o) i - if frame is ignored
4842 * (o) m - if frame is marked
4843 * (o) bg - color filter - background color in hex
4844 * (o) fg - color filter - foreground color in hex
4846 static void
4847 sharkd_session_process_frame(char *buf, const jsmntok_t *tokens, int count)
4849 const char *tok_frame = json_find_attr(buf, tokens, count, "frame");
4850 const char *tok_ref_frame = json_find_attr(buf, tokens, count, "ref_frame");
4851 const char *tok_prev_frame = json_find_attr(buf, tokens, count, "prev_frame");
4852 column_info *cinfo = NULL;
4854 uint32_t framenum, ref_frame_num, prev_dis_num;
4855 uint32_t dissect_flags = SHARKD_DISSECT_FLAG_NULL;
4856 struct sharkd_frame_request_data req_data;
4857 wtap_rec rec; /* Record metadata */
4858 Buffer rec_buf; /* Record data */
4859 enum dissect_request_status status;
4860 int err;
4861 char *err_info;
4863 ws_strtou32(tok_frame, NULL, &framenum); // we have already validated this
4865 ref_frame_num = (framenum != 1) ? 1 : 0;
4866 if (tok_ref_frame)
4868 ws_strtou32(tok_ref_frame, NULL, &ref_frame_num);
4869 if (ref_frame_num > framenum)
4871 sharkd_json_error(
4872 rpcid, -8001, NULL,
4873 "Invalid ref_frame - The ref_frame occurs after the frame specified"
4875 return;
4879 prev_dis_num = framenum - 1;
4880 if (tok_prev_frame)
4882 ws_strtou32(tok_prev_frame, NULL, &prev_dis_num);
4883 if (prev_dis_num >= framenum)
4885 sharkd_json_error(
4886 rpcid, -8002, NULL,
4887 "Invalid prev_frame - The prev_frame occurs on or after the frame specified"
4889 return;
4893 if (json_find_attr(buf, tokens, count, "proto") != NULL)
4894 dissect_flags |= SHARKD_DISSECT_FLAG_PROTO_TREE;
4895 if (json_find_attr(buf, tokens, count, "bytes") != NULL)
4896 dissect_flags |= SHARKD_DISSECT_FLAG_BYTES;
4897 if (json_find_attr(buf, tokens, count, "columns") != NULL) {
4898 dissect_flags |= SHARKD_DISSECT_FLAG_COLUMNS;
4899 cinfo = &cfile.cinfo;
4901 if (json_find_attr(buf, tokens, count, "color") != NULL)
4902 dissect_flags |= SHARKD_DISSECT_FLAG_COLOR;
4904 req_data.display_hidden = (json_find_attr(buf, tokens, count, "v") != NULL);
4906 wtap_rec_init(&rec);
4907 ws_buffer_init(&rec_buf, 1514);
4909 status = sharkd_dissect_request(framenum, ref_frame_num, prev_dis_num,
4910 &rec, &rec_buf, cinfo, dissect_flags,
4911 &sharkd_session_process_frame_cb, &req_data, &err, &err_info);
4912 switch (status) {
4914 case DISSECT_REQUEST_SUCCESS:
4915 /* success */
4916 break;
4918 case DISSECT_REQUEST_NO_SUCH_FRAME:
4919 sharkd_json_error(
4920 rpcid, -8003, NULL,
4921 "Invalid frame - The frame number requested is out of range"
4923 break;
4925 case DISSECT_REQUEST_READ_ERROR:
4926 sharkd_json_error(
4927 rpcid, -8003, NULL,
4928 /* XXX - show the error details */
4929 "Read error - The frame could not be read from the file"
4931 g_free(err_info);
4932 break;
4935 wtap_rec_cleanup(&rec);
4936 ws_buffer_free(&rec_buf);
4940 * sharkd_session_process_check()
4942 * Process check request.
4944 * Input:
4945 * (o) filter - filter to be checked
4946 * (o) field - field to be checked
4948 * Output object with attributes:
4949 * (m) err - always 0
4950 * (o) filter - 'ok', 'warn' or error message
4951 * (o) field - 'ok', or 'notfound'
4953 static int
4954 sharkd_session_process_check(char *buf, const jsmntok_t *tokens, int count)
4956 const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
4957 const char *tok_field = json_find_attr(buf, tokens, count, "field");
4959 if (tok_filter != NULL)
4961 dfilter_t *dfp;
4962 df_error_t *df_err = NULL;
4964 if (dfilter_compile(tok_filter, &dfp, &df_err))
4966 if (dfp && dfilter_deprecated_tokens(dfp))
4967 sharkd_json_warning(rpcid, "Filter contains deprecated tokens");
4968 else
4969 sharkd_json_simple_ok(rpcid);
4971 dfilter_free(dfp);
4972 df_error_free(&df_err);
4973 return 0;
4975 else
4977 sharkd_json_error(
4978 rpcid, -5001, NULL,
4979 "Filter invalid - %s", df_err->msg
4981 df_error_free(&df_err);
4982 return -5001;
4986 if (tok_field != NULL)
4988 header_field_info *hfi = proto_registrar_get_byname(tok_field);
4990 if (!hfi)
4992 sharkd_json_error(
4993 rpcid, -5002, NULL,
4994 "Field %s not found", tok_field
4996 return -5002;
4998 else
5000 sharkd_json_simple_ok(rpcid);
5001 return 0;
5005 sharkd_json_simple_ok(rpcid);
5006 return 0;
5009 struct sharkd_session_process_complete_pref_data
5011 const char *module;
5012 const char *pref;
5015 static unsigned
5016 sharkd_session_process_complete_pref_cb(module_t *module, void *d)
5018 struct sharkd_session_process_complete_pref_data *data = (struct sharkd_session_process_complete_pref_data *) d;
5020 if (strncmp(data->pref, module->name, strlen(data->pref)) != 0)
5021 return 0;
5023 json_dumper_begin_object(&dumper);
5024 sharkd_json_value_string("f", module->name);
5025 sharkd_json_value_string("d", module->title);
5026 json_dumper_end_object(&dumper);
5028 return 0;
5031 static unsigned
5032 sharkd_session_process_complete_pref_option_cb(pref_t *pref, void *d)
5034 struct sharkd_session_process_complete_pref_data *data = (struct sharkd_session_process_complete_pref_data *) d;
5035 const char *pref_name = prefs_get_name(pref);
5036 const char *pref_title = prefs_get_title(pref);
5038 if (strncmp(data->pref, pref_name, strlen(data->pref)) != 0)
5039 return 0;
5041 json_dumper_begin_object(&dumper);
5042 sharkd_json_value_stringf("f", "%s.%s", data->module, pref_name);
5043 sharkd_json_value_string("d", pref_title);
5044 json_dumper_end_object(&dumper);
5046 return 0; /* continue */
5050 * sharkd_session_process_complete()
5052 * Process complete request
5054 * Input:
5055 * (o) field - field to be completed
5056 * (o) pref - preference to be completed
5058 * Output object with attributes:
5059 * (m) err - always 0
5060 * (o) field - array of object with attributes:
5061 * (m) f - field text
5062 * (o) t - field type (FT_ number)
5063 * (o) n - field name
5064 * (o) pref - array of object with attributes:
5065 * (m) f - pref name
5066 * (o) d - pref description
5068 static int
5069 sharkd_session_process_complete(char *buf, const jsmntok_t *tokens, int count)
5071 const char *tok_field = json_find_attr(buf, tokens, count, "field");
5072 const char *tok_pref = json_find_attr(buf, tokens, count, "pref");
5074 sharkd_json_result_prologue(rpcid);
5076 if (tok_field != NULL && tok_field[0])
5078 const size_t filter_length = strlen(tok_field);
5079 const int filter_with_dot = !!strchr(tok_field, '.');
5081 void *proto_cookie;
5082 void *field_cookie;
5083 int proto_id;
5085 sharkd_json_array_open("field");
5087 for (proto_id = proto_get_first_protocol(&proto_cookie); proto_id != -1; proto_id = proto_get_next_protocol(&proto_cookie))
5089 protocol_t *protocol = find_protocol_by_id(proto_id);
5090 const char *protocol_filter;
5091 const char *protocol_name;
5092 header_field_info *hfinfo;
5094 if (!proto_is_protocol_enabled(protocol))
5095 continue;
5097 protocol_name = proto_get_protocol_long_name(protocol);
5098 protocol_filter = proto_get_protocol_filter_name(proto_id);
5100 if (strlen(protocol_filter) >= filter_length && !g_ascii_strncasecmp(tok_field, protocol_filter, filter_length))
5102 json_dumper_begin_object(&dumper);
5104 sharkd_json_value_string("f", protocol_filter);
5105 sharkd_json_value_anyf("t", "%d", FT_PROTOCOL);
5106 sharkd_json_value_string("n", protocol_name);
5108 json_dumper_end_object(&dumper);
5111 if (!filter_with_dot)
5112 continue;
5114 for (hfinfo = proto_get_first_protocol_field(proto_id, &field_cookie); hfinfo != NULL; hfinfo = proto_get_next_protocol_field(proto_id, &field_cookie))
5116 if (hfinfo->same_name_prev_id != -1) /* ignore duplicate names */
5117 continue;
5119 if (strlen(hfinfo->abbrev) >= filter_length && !g_ascii_strncasecmp(tok_field, hfinfo->abbrev, filter_length))
5121 json_dumper_begin_object(&dumper);
5123 sharkd_json_value_string("f", hfinfo->abbrev);
5125 /* XXX, skip displaying name, if there are multiple (to not confuse user) */
5126 if (hfinfo->same_name_next == NULL)
5128 sharkd_json_value_anyf("t", "%d", hfinfo->type);
5129 sharkd_json_value_string("n", hfinfo->name);
5132 json_dumper_end_object(&dumper);
5137 sharkd_json_array_close();
5140 if (tok_pref != NULL && tok_pref[0])
5142 struct sharkd_session_process_complete_pref_data data;
5143 char *dot_sepa;
5145 data.module = tok_pref;
5146 data.pref = tok_pref;
5148 sharkd_json_array_open("pref");
5149 if ((dot_sepa = strchr(tok_pref, '.')))
5151 module_t *pref_mod;
5153 *dot_sepa = '\0'; /* XXX, C abuse: discarding-const */
5154 data.pref = dot_sepa + 1;
5156 pref_mod = prefs_find_module(data.module);
5157 if (pref_mod)
5158 prefs_pref_foreach(pref_mod, sharkd_session_process_complete_pref_option_cb, &data);
5160 *dot_sepa = '.';
5162 else
5164 prefs_modules_foreach(sharkd_session_process_complete_pref_cb, &data);
5166 sharkd_json_array_close();
5169 sharkd_json_result_epilogue();
5171 return 0;
5175 * sharkd_session_process_setcomment()
5177 * Process setcomment request
5179 * Input:
5180 * (m) frame - frame number
5181 * (o) comment - user comment
5183 * Output object with attributes:
5184 * (m) err - error code: 0 succeed
5186 * Note:
5187 * For now, adds comments, doesn't remove or replace them.
5189 static void
5190 sharkd_session_process_setcomment(char *buf, const jsmntok_t *tokens, int count)
5192 const char *tok_frame = json_find_attr(buf, tokens, count, "frame");
5193 const char *tok_comment = json_find_attr(buf, tokens, count, "comment");
5195 uint32_t framenum;
5196 frame_data *fdata;
5197 wtap_opttype_return_val ret;
5198 wtap_block_t pkt_block = NULL;
5200 if (!tok_frame || !ws_strtou32(tok_frame, NULL, &framenum) || framenum == 0)
5202 sharkd_json_error(
5203 rpcid, -3001, NULL,
5204 "Frame number must be a positive integer"
5206 return;
5209 fdata = sharkd_get_frame(framenum); // BUG HERE - If no file loaded you get a crash
5210 if (!fdata)
5212 sharkd_json_error(
5213 rpcid, -3002, NULL,
5214 "Frame number is out of range"
5216 return;
5219 pkt_block = sharkd_get_packet_block(fdata);
5221 ret = wtap_block_add_string_option(pkt_block, OPT_COMMENT, tok_comment, strlen(tok_comment));
5223 if (ret != WTAP_OPTTYPE_SUCCESS)
5225 sharkd_json_error(
5226 rpcid, -3003, NULL,
5227 "Unable to set the comment"
5230 else
5232 sharkd_set_modified_block(fdata, pkt_block);
5233 sharkd_json_simple_ok(rpcid);
5238 * sharkd_session_process_setconf()
5240 * Process setconf request
5242 * Input:
5243 * (m) name - preference name
5244 * (m) value - preference value
5246 * Output object with attributes:
5247 * (m) err - error code: 0 succeed
5249 static void
5250 sharkd_session_process_setconf(char *buf, const jsmntok_t *tokens, int count)
5252 const char *tok_name = json_find_attr(buf, tokens, count, "name");
5253 const char *tok_value = json_find_attr(buf, tokens, count, "value");
5254 char pref[4096];
5255 char *errmsg = NULL;
5257 prefs_set_pref_e ret;
5259 if (!tok_name || tok_name[0] == '\0')
5261 sharkd_json_error(
5262 rpcid, -4001, NULL,
5263 "Preference name missing"
5265 return;
5268 if (!tok_value)
5270 sharkd_json_error(
5271 rpcid, -4002, NULL,
5272 "Preference value missing"
5274 return;
5277 snprintf(pref, sizeof(pref), "%s:%s", tok_name, tok_value);
5279 ret = prefs_set_pref(pref, &errmsg);
5281 switch (ret)
5283 case PREFS_SET_OK:
5284 sharkd_json_simple_ok(rpcid);
5285 break;
5287 case PREFS_SET_OBSOLETE:
5288 sharkd_json_error(
5289 rpcid, -4003, NULL,
5290 "The preference specified is obsolete"
5292 break;
5294 case PREFS_SET_NO_SUCH_PREF:
5295 sharkd_json_error(
5296 rpcid, -4004, NULL,
5297 "No such preference exists"
5299 break;
5301 default:
5302 sharkd_json_error(
5303 rpcid, -4005, NULL,
5304 "Unable to set the preference"
5308 g_free(errmsg);
5311 struct sharkd_session_process_dumpconf_data
5313 module_t *module;
5316 static unsigned
5317 sharkd_session_process_dumpconf_cb(pref_t *pref, void *d)
5319 struct sharkd_session_process_dumpconf_data *data = (struct sharkd_session_process_dumpconf_data *) d;
5320 const char *pref_name = prefs_get_name(pref);
5322 char json_pref_key[512];
5324 snprintf(json_pref_key, sizeof(json_pref_key), "%s.%s", data->module->name, pref_name);
5325 sharkd_json_object_open(json_pref_key);
5327 switch (prefs_get_type(pref))
5329 case PREF_UINT:
5330 sharkd_json_value_anyf("u", "%u", prefs_get_uint_value_real(pref, pref_current));
5331 if (prefs_get_uint_base(pref) != 10)
5332 sharkd_json_value_anyf("ub", "%u", prefs_get_uint_base(pref));
5333 break;
5335 case PREF_BOOL:
5336 sharkd_json_value_anyf("b", prefs_get_bool_value(pref, pref_current) ? "1" : "0");
5337 break;
5339 case PREF_STRING:
5340 case PREF_SAVE_FILENAME:
5341 case PREF_OPEN_FILENAME:
5342 case PREF_DIRNAME:
5343 case PREF_PASSWORD:
5344 case PREF_DISSECTOR:
5345 sharkd_json_value_string("s", prefs_get_string_value(pref, pref_current));
5346 break;
5348 case PREF_ENUM:
5350 const enum_val_t *enums;
5352 sharkd_json_array_open("e");
5353 for (enums = prefs_get_enumvals(pref); enums->name; enums++)
5355 json_dumper_begin_object(&dumper);
5357 sharkd_json_value_anyf("v", "%d", enums->value);
5359 if (enums->value == prefs_get_enum_value(pref, pref_current))
5360 sharkd_json_value_anyf("s", "1");
5362 sharkd_json_value_string("d", enums->description);
5364 json_dumper_end_object(&dumper);
5366 sharkd_json_array_close();
5367 break;
5370 case PREF_RANGE:
5371 case PREF_DECODE_AS_RANGE:
5373 char *range_str = range_convert_range(NULL, prefs_get_range_value_real(pref, pref_current));
5374 sharkd_json_value_string("r", range_str);
5375 wmem_free(NULL, range_str);
5376 break;
5379 case PREF_UAT:
5381 uat_t *uat = prefs_get_uat_value(pref);
5382 unsigned idx;
5384 sharkd_json_array_open("t");
5385 for (idx = 0; idx < uat->raw_data->len; idx++)
5387 void *rec = UAT_INDEX_PTR(uat, idx);
5388 unsigned colnum;
5390 sharkd_json_array_open(NULL);
5391 for (colnum = 0; colnum < uat->ncols; colnum++)
5393 char *str = uat_fld_tostr(rec, &(uat->fields[colnum]));
5395 sharkd_json_value_string(NULL, str);
5396 g_free(str);
5399 sharkd_json_array_close();
5402 sharkd_json_array_close();
5403 break;
5406 case PREF_COLOR:
5407 case PREF_CUSTOM:
5408 case PREF_STATIC_TEXT:
5409 case PREF_OBSOLETE:
5410 /* TODO */
5411 break;
5414 #if 0
5415 sharkd_json_value_string("t", prefs_get_title(pref));
5416 #endif
5418 sharkd_json_object_close();
5420 return 0; /* continue */
5423 static unsigned
5424 sharkd_session_process_dumpconf_mod_cb(module_t *module, void *d)
5426 struct sharkd_session_process_dumpconf_data *data = (struct sharkd_session_process_dumpconf_data *) d;
5428 data->module = module;
5429 prefs_pref_foreach(module, sharkd_session_process_dumpconf_cb, data);
5431 return 0;
5435 * sharkd_session_process_dumpconf()
5437 * Process dumpconf request
5439 * Input:
5440 * (o) pref - module, or preference, NULL for all
5442 * Output object with attributes:
5443 * (o) prefs - object with module preferences
5444 * (m) [KEY] - preference name
5445 * (o) u - preference value (for PREF_UINT)
5446 * (o) ub - preference value suggested base for display (for PREF_UINT) and if different than 10
5447 * (o) b - preference value (only for PREF_BOOL) (1 true, 0 false)
5448 * (o) s - preference value (for PREF_STRING, PREF_SAVE_FILENAME, PREF_OPEN_FILENAME, PREF_DIRNAME, PREF_PASSWORD, PREF_DISSECTOR)
5449 * (o) e - preference possible values (only for PREF_ENUM)
5450 * (o) r - preference value (for PREF_RANGE, PREF_DECODE_AS_RANGE)
5451 * (o) t - preference value (only for PREF_UAT)
5453 static void
5454 sharkd_session_process_dumpconf(char *buf, const jsmntok_t *tokens, int count)
5456 const char *tok_pref = json_find_attr(buf, tokens, count, "pref");
5457 module_t *pref_mod;
5458 char *dot_sepa;
5460 if (!tok_pref)
5462 struct sharkd_session_process_dumpconf_data data;
5464 data.module = NULL;
5466 sharkd_json_result_prologue(rpcid);
5468 sharkd_json_object_open("prefs");
5469 prefs_modules_foreach(sharkd_session_process_dumpconf_mod_cb, &data);
5470 sharkd_json_object_close();
5472 sharkd_json_result_epilogue();
5473 return;
5476 if ((dot_sepa = strchr(tok_pref, '.')))
5478 pref_t *pref = NULL;
5480 *dot_sepa = '\0'; /* XXX, C abuse: discarding-const */
5481 pref_mod = prefs_find_module(tok_pref);
5482 if (pref_mod)
5483 pref = prefs_find_preference(pref_mod, dot_sepa + 1);
5484 *dot_sepa = '.';
5486 if (pref)
5488 struct sharkd_session_process_dumpconf_data data;
5490 data.module = pref_mod;
5492 sharkd_json_result_prologue(rpcid);
5494 sharkd_json_object_open("prefs");
5495 sharkd_session_process_dumpconf_cb(pref, &data);
5496 sharkd_json_object_close();
5498 sharkd_json_result_epilogue();
5499 return;
5501 else
5503 sharkd_json_error(
5504 rpcid, -9001, NULL,
5505 "Invalid pref %s.", tok_pref
5507 return;
5512 pref_mod = prefs_find_module(tok_pref);
5513 if (pref_mod)
5515 struct sharkd_session_process_dumpconf_data data;
5517 data.module = pref_mod;
5519 sharkd_json_result_prologue(rpcid);
5521 sharkd_json_object_open("prefs");
5522 prefs_pref_foreach(pref_mod, sharkd_session_process_dumpconf_cb, &data);
5523 sharkd_json_object_close();
5525 sharkd_json_result_epilogue();
5527 else
5529 sharkd_json_error(
5530 rpcid, -9002, NULL,
5531 "Invalid pref %s.", tok_pref
5536 struct sharkd_download_rtp
5538 rtpstream_id_t id;
5539 GSList *packets;
5540 double start_time;
5543 static void
5544 sharkd_rtp_download_free_items(void *ptr)
5546 rtp_packet_t *rtp_packet = (rtp_packet_t *) ptr;
5548 g_free(rtp_packet->info);
5549 g_free(rtp_packet->payload_data);
5550 g_free(rtp_packet);
5553 static void
5554 sharkd_rtp_download_decode(struct sharkd_download_rtp *req)
5556 /* based on RtpAudioStream::decode() 6e29d874f8b5e6ebc59f661a0bb0dab8e56f122a */
5557 /* TODO, for now only without silence (timing_mode_ = Uninterrupted) */
5559 static const int sample_bytes_ = sizeof(SAMPLE) / sizeof(char);
5561 uint32_t audio_out_rate_ = 0;
5562 struct _GHashTable *decoders_hash_ = rtp_decoder_hash_table_new();
5563 struct SpeexResamplerState_ *audio_resampler_ = NULL;
5565 size_t resample_buff_len = 0x1000;
5566 SAMPLE *resample_buff = (SAMPLE *) g_malloc(resample_buff_len);
5567 spx_uint32_t cur_in_rate = 0;
5568 char *write_buff = NULL;
5569 size_t write_bytes = 0;
5570 unsigned channels = 0;
5571 unsigned sample_rate = 0;
5573 GSList *l;
5575 for (l = req->packets; l; l = l->next)
5577 rtp_packet_t *rtp_packet = (rtp_packet_t *) l->data;
5579 SAMPLE *decode_buff = NULL;
5580 size_t decoded_bytes;
5582 decoded_bytes = decode_rtp_packet(rtp_packet, &decode_buff, decoders_hash_, &channels, &sample_rate);
5583 if (decoded_bytes == 0 || sample_rate == 0)
5585 /* We didn't decode anything. Clean up and prep for the next packet. */
5586 g_free(decode_buff);
5587 continue;
5590 if (audio_out_rate_ == 0)
5592 uint32_t tmp32;
5593 uint16_t tmp16;
5594 char wav_hdr[44];
5596 /* First non-zero wins */
5597 audio_out_rate_ = sample_rate;
5599 RTP_STREAM_DEBUG("Audio sample rate is %u", audio_out_rate_);
5601 /* write WAVE header */
5602 memset(&wav_hdr, 0, sizeof(wav_hdr));
5603 memcpy(&wav_hdr[0], "RIFF", 4);
5604 memcpy(&wav_hdr[4], "\xFF\xFF\xFF\xFF", 4); /* XXX, unknown */
5605 memcpy(&wav_hdr[8], "WAVE", 4);
5607 memcpy(&wav_hdr[12], "fmt ", 4);
5608 memcpy(&wav_hdr[16], "\x10\x00\x00\x00", 4); /* PCM */
5609 memcpy(&wav_hdr[20], "\x01\x00", 2); /* PCM */
5610 /* # channels */
5611 tmp16 = channels;
5612 memcpy(&wav_hdr[22], &tmp16, 2);
5613 /* sample rate */
5614 tmp32 = sample_rate;
5615 memcpy(&wav_hdr[24], &tmp32, 4);
5616 /* byte rate */
5617 tmp32 = sample_rate * channels * sample_bytes_;
5618 memcpy(&wav_hdr[28], &tmp32, 4);
5619 /* block align */
5620 tmp16 = channels * sample_bytes_;
5621 memcpy(&wav_hdr[32], &tmp16, 2);
5622 /* bits per sample */
5623 tmp16 = 8 * sample_bytes_;
5624 memcpy(&wav_hdr[34], &tmp16, 2);
5626 memcpy(&wav_hdr[36], "data", 4);
5627 memcpy(&wav_hdr[40], "\xFF\xFF\xFF\xFF", 4); /* XXX, unknown */
5629 json_dumper_write_base64(&dumper, wav_hdr, sizeof(wav_hdr));
5632 // Write samples to our file.
5633 write_buff = (char *) decode_buff;
5634 write_bytes = decoded_bytes;
5636 if (audio_out_rate_ != sample_rate)
5638 spx_uint32_t in_len, out_len;
5640 /* Resample the audio to match our previous output rate. */
5641 if (!audio_resampler_)
5643 audio_resampler_ = speex_resampler_init(1, sample_rate, audio_out_rate_, 10, NULL);
5644 speex_resampler_skip_zeros(audio_resampler_);
5645 RTP_STREAM_DEBUG("Started resampling from %u to (out) %u Hz.", sample_rate, audio_out_rate_);
5647 else
5649 spx_uint32_t audio_out_rate;
5650 speex_resampler_get_rate(audio_resampler_, &cur_in_rate, &audio_out_rate);
5652 if (sample_rate != cur_in_rate)
5654 speex_resampler_set_rate(audio_resampler_, sample_rate, audio_out_rate);
5655 RTP_STREAM_DEBUG("Changed input rate from %u to %u Hz. Out is %u.", cur_in_rate, sample_rate, audio_out_rate_);
5658 in_len = (spx_uint32_t)rtp_packet->info->info_payload_len;
5659 out_len = (audio_out_rate_ * (spx_uint32_t)rtp_packet->info->info_payload_len / sample_rate) + (audio_out_rate_ % sample_rate != 0);
5660 if (out_len * sample_bytes_ > resample_buff_len)
5662 while ((out_len * sample_bytes_ > resample_buff_len))
5663 resample_buff_len *= 2;
5664 resample_buff = (SAMPLE *) g_realloc(resample_buff, resample_buff_len);
5667 speex_resampler_process_int(audio_resampler_, 0, decode_buff, &in_len, resample_buff, &out_len);
5668 write_buff = (char *) resample_buff;
5669 write_bytes = out_len * sample_bytes_;
5672 /* Write the decoded, possibly-resampled audio */
5673 json_dumper_write_base64(&dumper, write_buff, write_bytes);
5675 g_free(decode_buff);
5678 g_free(resample_buff);
5679 g_hash_table_destroy(decoders_hash_);
5682 static tap_packet_status
5683 sharkd_session_packet_download_tap_rtp_cb(void *tapdata, packet_info *pinfo, epan_dissect_t *edt _U_, const void *data, tap_flags_t flags _U_)
5685 const struct _rtp_info *rtp_info = (const struct _rtp_info *) data;
5686 struct sharkd_download_rtp *req_rtp = (struct sharkd_download_rtp *) tapdata;
5688 /* do not consider RTP packets without a setup frame */
5689 if (rtp_info->info_setup_frame_num == 0)
5690 return TAP_PACKET_DONT_REDRAW;
5692 if (rtpstream_id_equal_pinfo_rtp_info(&req_rtp->id, pinfo, rtp_info))
5694 rtp_packet_t *rtp_packet;
5696 rtp_packet = g_new0(rtp_packet_t, 1);
5697 rtp_packet->info = (struct _rtp_info *) g_memdup2(rtp_info, sizeof(struct _rtp_info));
5699 if (rtp_info->info_all_data_present && rtp_info->info_payload_len != 0)
5700 rtp_packet->payload_data = (uint8_t *) g_memdup2(&(rtp_info->info_data[rtp_info->info_payload_offset]), rtp_info->info_payload_len);
5702 if (!req_rtp->packets)
5703 req_rtp->start_time = nstime_to_sec(&pinfo->abs_ts);
5705 rtp_packet->frame_num = pinfo->num;
5706 rtp_packet->arrive_offset = nstime_to_sec(&pinfo->abs_ts) - req_rtp->start_time;
5708 /* XXX, O(n) optimize */
5709 req_rtp->packets = g_slist_append(req_rtp->packets, rtp_packet);
5712 return TAP_PACKET_DONT_REDRAW;
5715 static bool
5716 sharkd_session_eo_retap_listener(const char *tap_type) {
5717 bool ok = true;
5718 register_eo_t *eo = NULL;
5719 GString *tap_error = NULL;
5720 void *tap_data = NULL;
5721 GFreeFunc tap_free = NULL;
5723 // get <name> from eo:<name>, get_eo_by_name only needs the name (http etc.)
5724 eo = get_eo_by_name(tap_type + 3);
5725 if (!eo)
5727 ok = false;
5728 sharkd_json_error(
5729 rpcid, -11011, NULL,
5730 "sharkd_session_eo_retap_listener() eo=%s not found", tap_type + 3
5734 if (ok)
5736 tap_error = sharkd_session_eo_register_tap_listener(eo, tap_type, NULL, NULL, &tap_data, &tap_free);
5737 if (tap_error)
5739 ok = false;
5740 sharkd_json_error(
5741 rpcid, -10002, NULL,
5742 "sharkd_session_eo_retap_listener() sharkd_session_eo_register_tap_listener error %s",
5743 tap_error->str);
5744 g_string_free(tap_error, TRUE);
5748 if (ok)
5749 sharkd_retap();
5751 if (!tap_error)
5752 remove_tap_listener(tap_data);
5754 if (tap_free)
5755 tap_free(tap_data);
5757 return ok;
5761 * sharkd_session_process_download()
5763 * Process download request
5765 * Input:
5766 * (m) token - token to download
5768 * Output object with attributes:
5769 * (o) file - suggested name of file
5770 * (o) mime - suggested content type
5771 * (o) data - payload base64 encoded
5773 static void
5774 sharkd_session_process_download(char *buf, const jsmntok_t *tokens, int count)
5776 const char *tok_token = json_find_attr(buf, tokens, count, "token");
5778 if (!tok_token)
5780 sharkd_json_error(
5781 rpcid, -10005, NULL,
5782 "missing token"
5784 return;
5787 if (!strncmp(tok_token, "eo:", 3))
5789 // get eo:<name> from eo:<name>_<row>
5790 char *tap_type = g_strdup(tok_token);
5791 char *tmp = strrchr(tap_type, '_');
5792 if (tmp)
5793 *tmp = '\0';
5795 // if eo:<name> not in sharkd_eo_list, retap
5796 if (!sharkd_eo_object_list_get_entry_by_type(sharkd_eo_list, tap_type) &&
5797 !sharkd_session_eo_retap_listener(tap_type))
5799 g_free(tap_type);
5800 // sharkd_json_error called in sharkd_session_eo_retap_listener
5801 return;
5804 g_free(tap_type);
5806 struct sharkd_export_object_list *object_list;
5807 const export_object_entry_t *eo_entry = NULL;
5809 for (object_list = sharkd_eo_list; object_list; object_list = object_list->next)
5811 size_t eo_type_len = strlen(object_list->type);
5813 if (!strncmp(tok_token, object_list->type, eo_type_len) && tok_token[eo_type_len] == '_')
5815 int row;
5817 if (sscanf(&tok_token[eo_type_len + 1], "%d", &row) != 1)
5818 break;
5820 eo_entry = (export_object_entry_t *) g_slist_nth_data(object_list->entries, row);
5821 break;
5825 if (eo_entry)
5827 const char *mime = (eo_entry->content_type) ? eo_entry->content_type : "application/octet-stream";
5828 const char *filename = (eo_entry->filename) ? eo_entry->filename : tok_token;
5830 sharkd_json_result_prologue(rpcid);
5831 sharkd_json_value_string("file", filename);
5832 sharkd_json_value_string("mime", mime);
5833 sharkd_json_value_base64("data", eo_entry->payload_data, eo_entry->payload_len);
5834 sharkd_json_result_epilogue();
5836 else
5838 sharkd_json_result_prologue(rpcid);
5839 sharkd_json_result_epilogue();
5842 else if (!strcmp(tok_token, "ssl-secrets"))
5844 size_t str_len;
5845 char *str = ssl_export_sessions(&str_len);
5847 if (str)
5849 const char *mime = "text/plain";
5850 const char *filename = "keylog.txt";
5852 sharkd_json_result_prologue(rpcid);
5853 sharkd_json_value_string("file", filename);
5854 sharkd_json_value_string("mime", mime);
5855 sharkd_json_value_base64("data", str, str_len);
5856 sharkd_json_result_epilogue();
5858 g_free(str);
5860 else if (!strncmp(tok_token, "rtp:", 4))
5862 struct sharkd_download_rtp rtp_req;
5863 GString *tap_error;
5865 memset(&rtp_req, 0, sizeof(rtp_req));
5866 if (!sharkd_rtp_match_init(&rtp_req.id, tok_token + 4))
5868 sharkd_json_error(
5869 rpcid, -10001, NULL,
5870 "sharkd_session_process_download() rtp tokenizing error %s", tok_token
5872 return;
5875 tap_error = register_tap_listener("rtp", &rtp_req, NULL, 0, NULL, sharkd_session_packet_download_tap_rtp_cb, NULL, NULL);
5876 if (tap_error)
5878 sharkd_json_error(
5879 rpcid, -10002, NULL,
5880 "sharkd_session_process_download() rtp error %s", tap_error->str
5882 g_string_free(tap_error, TRUE);
5883 return;
5886 sharkd_retap();
5887 remove_tap_listener(&rtp_req);
5889 if (rtp_req.packets)
5891 const char *mime = "audio/x-wav";
5892 const char *filename = tok_token;
5894 sharkd_json_result_prologue(rpcid);
5895 sharkd_json_value_string("file", filename);
5896 sharkd_json_value_string("mime", mime);
5898 json_dumper_set_member_name(&dumper, "data");
5899 json_dumper_begin_base64(&dumper);
5900 sharkd_rtp_download_decode(&rtp_req);
5901 json_dumper_end_base64(&dumper);
5903 sharkd_json_result_epilogue();
5905 g_slist_free_full(rtp_req.packets, sharkd_rtp_download_free_items);
5907 else
5909 sharkd_json_error(
5910 rpcid, -10003, NULL,
5911 "no rtp data available"
5915 else
5917 sharkd_json_error(
5918 rpcid, -10004, NULL,
5919 "unrecognized token"
5924 static void
5925 sharkd_session_process(char *buf, const jsmntok_t *tokens, int count)
5927 if (json_prep(buf, tokens, count))
5929 /* don't need [0] token */
5930 tokens++;
5931 count--;
5933 const char* tok_method = json_find_attr(buf, tokens, count, "method");
5935 if (!tok_method) {
5936 sharkd_json_error(
5937 rpcid, -32601, NULL,
5938 "No method found");
5939 return;
5941 if (!strcmp(tok_method, "load"))
5942 sharkd_session_process_load(buf, tokens, count);
5943 else if (!strcmp(tok_method, "status"))
5944 sharkd_session_process_status();
5945 else if (!strcmp(tok_method, "analyse"))
5946 sharkd_session_process_analyse();
5947 else if (!strcmp(tok_method, "info"))
5948 sharkd_session_process_info();
5949 else if (!strcmp(tok_method, "check"))
5950 sharkd_session_process_check(buf, tokens, count);
5951 else if (!strcmp(tok_method, "complete"))
5952 sharkd_session_process_complete(buf, tokens, count);
5953 else if (!strcmp(tok_method, "frames"))
5954 sharkd_session_process_frames(buf, tokens, count);
5955 else if (!strcmp(tok_method, "tap"))
5956 sharkd_session_process_tap(buf, tokens, count);
5957 else if (!strcmp(tok_method, "follow"))
5958 sharkd_session_process_follow(buf, tokens, count);
5959 else if (!strcmp(tok_method, "iograph"))
5960 sharkd_session_process_iograph(buf, tokens, count);
5961 else if (!strcmp(tok_method, "intervals"))
5962 sharkd_session_process_intervals(buf, tokens, count);
5963 else if (!strcmp(tok_method, "frame"))
5964 sharkd_session_process_frame(buf, tokens, count);
5965 else if (!strcmp(tok_method, "setcomment"))
5966 sharkd_session_process_setcomment(buf, tokens, count);
5967 else if (!strcmp(tok_method, "setconf"))
5968 sharkd_session_process_setconf(buf, tokens, count);
5969 else if (!strcmp(tok_method, "dumpconf"))
5970 sharkd_session_process_dumpconf(buf, tokens, count);
5971 else if (!strcmp(tok_method, "download"))
5972 sharkd_session_process_download(buf, tokens, count);
5973 else if (!strcmp(tok_method, "bye"))
5975 sharkd_json_simple_ok(rpcid);
5976 exit(0);
5978 else
5980 sharkd_json_error(
5981 rpcid, -32601, NULL,
5982 "The method \"%s\" is unknown", tok_method
5989 sharkd_session_main(int mode_setting)
5991 char buf[8 * 1024];
5992 jsmntok_t *tokens = NULL;
5993 int tokens_max = -1;
5995 mode = mode_setting;
5997 fprintf(stderr, "Hello in child.\n");
5999 dumper.output_file = stdout;
6001 filter_table = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, sharkd_session_filter_free);
6003 #ifdef HAVE_MAXMINDDB
6004 /* mmdbresolve was stopped before fork(), force starting it */
6005 uat_get_table_by_name("MaxMind Database Paths")->post_update_cb();
6006 #endif
6008 set_resolution_synchrony(true);
6010 while (fgets(buf, sizeof(buf), stdin))
6012 /* every command is line separated JSON */
6013 int ret;
6015 ret = json_parse(buf, NULL, 0);
6016 if (ret <= 0)
6018 sharkd_json_error(
6019 rpcid, -32600, NULL,
6020 "Invalid JSON(1)"
6022 continue;
6025 /* fprintf(stderr, "JSON: %d tokens\n", ret); */
6026 ret += 1;
6028 if (tokens == NULL || tokens_max < ret)
6030 tokens_max = ret;
6031 tokens = (jsmntok_t *) g_realloc(tokens, sizeof(jsmntok_t) * tokens_max);
6034 memset(tokens, 0, ret * sizeof(jsmntok_t));
6036 ret = json_parse(buf, tokens, ret);
6037 if (ret <= 0)
6039 sharkd_json_error(
6040 rpcid, -32600, NULL,
6041 "Invalid JSON(2)"
6043 continue;
6046 host_name_lookup_process();
6048 sharkd_session_process(buf, tokens, ret);
6051 g_hash_table_destroy(filter_table);
6052 g_free(tokens);
6054 return 0;