summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJakub Zawadzki <darkjames-ws@darkjames.pl>2016-10-15 20:48:17 +0200
committerJakub Zawadzki <darkjames-ws@darkjames.pl>2017-01-25 07:19:05 +0000
commite2930f3b78cd47ac4044f3ece059e7dbe83f3f02 (patch)
tree8f64e87b1a44d3ab52509dc92fcc8155a0923c25
parent11574208e7f11d76bb1dbe460577396b8c06e3fb (diff)
downloadwireshark-e2930f3b78cd47ac4044f3ece059e7dbe83f3f02.tar.gz
Add sharkd - daemon variant
sharkd listens on UNIX socket and allows external clients to run commands like: loading file, analysing frames or running TAP(s). Change-Id: I443b2865e4adfd1c11f4f57d09ff7fce6b1e8766 Reviewed-on: https://code.wireshark.org/review/18208 Petri-Dish: Jakub Zawadzki <darkjames-ws@darkjames.pl> Tested-by: Petri Dish Buildbot <buildbot-no-reply@wireshark.org> Reviewed-by: Peter Wu <peter@lekensteyn.nl> Reviewed-by: Jakub Zawadzki <darkjames-ws@darkjames.pl>
-rw-r--r--CMakeLists.txt24
-rw-r--r--Makefile.am31
-rw-r--r--configure.ac14
-rw-r--r--sharkd.c997
-rw-r--r--sharkd.h60
-rw-r--r--sharkd_daemon.c223
-rw-r--r--sharkd_session.c1944
-rw-r--r--wsutil/wsjsmn.c10
-rw-r--r--wsutil/wsjsmn.h4
9 files changed, 3305 insertions, 2 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 7038e7acbc..407012473a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1383,7 +1383,7 @@ if(WIN32)
)
endif()
-# sources common for wireshark, tshark, and rawshark
+# sources common for wireshark, tshark, rawshark and sharkd
set(SHARK_COMMON_SRC
cfile.c
frame_tvbuff.c
@@ -2290,6 +2290,28 @@ if(BUILD_rawshark AND PCAP_FOUND)
install(TARGETS rawshark RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()
+if(BUILD_sharkd)
+ set(sharkd_LIBS
+ ui
+ ${LIBEPAN_LIBS}
+ ${APPLE_CORE_FOUNDATION_LIBRARY}
+ ${APPLE_SYSTEM_CONFIGURATION_LIBRARY}
+ )
+ set(sharkd_FILES
+ capture_opts.c
+ filter_files.c
+ sharkd.c
+ sharkd_daemon.c
+ sharkd_session.c
+ ${SHARK_COMMON_SRC}
+ )
+ add_executable(sharkd ${sharkd_FILES})
+ add_dependencies(sharkd version)
+ set_extra_executable_properties(sharkd "Executables")
+ target_link_libraries(sharkd ${sharkd_LIBS})
+ install(TARGETS sharkd RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
+endif()
+
if(BUILD_dftest)
set(dftest_LIBS
${LIBEPAN_LIBS}
diff --git a/Makefile.am b/Makefile.am
index 2f186f273f..81b7cd4e33 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -45,11 +45,12 @@ bin_PROGRAMS = \
@dumpcap_bin@ \
@reordercap_bin@ \
@rawshark_bin@ \
+ @sharkd_bin@ \
@echld_test_bin@
EXTRA_PROGRAMS = wireshark-gtk wireshark tshark tfshark capinfos captype \
editcap mergecap dftest randpkt text2pcap dumpcap reordercap \
- rawshark echld_test
+ rawshark sharkd echld_test
#
# Wireshark configuration files are put in $(pkgdatadir).
@@ -577,6 +578,34 @@ rawshark_LDADD = \
@SYSTEMCONFIGURATION_FRAMEWORKS@ \
@COREFOUNDATION_FRAMEWORKS@
+sharkd_SOURCES = \
+ $(SHARK_COMMON_SRC) \
+ filter_files.c \
+ sharkd.c \
+ sharkd_daemon.c \
+ sharkd_session.c \
+ ws_version_info.c
+
+sharkd_CPPFLAGS = $(AM_CPPFLAGS) $(GLIB_CFLAGS)
+
+sharkd_LDFLAGS = $(AM_LDFLAGS) $(EXTRALINKFLAGS)
+
+# Libraries and plugin flags with which to link sharkd.
+sharkd_LDADD = \
+ capchild/libcapchild.a \
+ caputils/libcaputils.a \
+ ui/cli/libcliui.a \
+ ui/libui.a \
+ wiretap/libwiretap.la \
+ epan/libwireshark.la \
+ wsutil/libwsutil.la \
+ $(plugin_ldadd) \
+ @GLIB_LIBS@ \
+ @PCAP_LIBS@ \
+ ${EPAN_EXTRA_LIBS} \
+ @SYSTEMCONFIGURATION_FRAMEWORKS@ \
+ @COREFOUNDATION_FRAMEWORKS@
+
text2pcap_SOURCES = \
text2pcap.c \
text2pcap-scanner.l \
diff --git a/configure.ac b/configure.ac
index 6531cf1fad..95d3b6808f 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1888,6 +1888,19 @@ fi
AC_SUBST(rawshark_bin)
AC_SUBST(rawshark_man)
+# Enable/disable sharkd
+AC_ARG_ENABLE(sharkd,
+ AC_HELP_STRING( [--enable-sharkd],
+ [build sharkd @<:@default=yes@:>@]),
+ sharkd=$enableval,enable_sharkd=yes)
+
+if test "x$enable_sharkd" = "xyes" ; then
+ sharkd_bin="sharkd\$(EXEEXT)"
+else
+ sharkd_bin=""
+fi
+AC_SUBST(sharkd_bin)
+
# Enable/disable echld
AC_ARG_ENABLE(echld,
AC_HELP_STRING( [--enable-echld],
@@ -3167,6 +3180,7 @@ echo " Build text2pcap : $enable_text2pcap"
echo " Build randpkt : $enable_randpkt"
echo " Build dftest : $enable_dftest"
echo " Build rawshark : $enable_rawshark"
+echo " Build sharkd : $enable_sharkd"
echo " Build androiddump : $enable_androiddump"
echo " Build sshdump : $enable_sshdump"
echo " Build ciscodump : $enable_ciscodump"
diff --git a/sharkd.c b/sharkd.c
new file mode 100644
index 0000000000..26ac51ed45
--- /dev/null
+++ b/sharkd.c
@@ -0,0 +1,997 @@
+/* sharkd.c
+ *
+ * Daemon variant of Wireshark
+ *
+ * Wireshark - Network traffic analyzer
+ * By Gerald Combs <gerald@wireshark.org>
+ * Copyright 1998 Gerald Combs
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include <config.h>
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <limits.h>
+#include <errno.h>
+#include <signal.h>
+
+#include <glib.h>
+
+#include <epan/exceptions.h>
+#include <epan/epan-int.h>
+#include <epan/epan.h>
+
+#include <wsutil/clopts_common.h>
+#include <wsutil/cmdarg_err.h>
+#include <wsutil/crash_info.h>
+#include <wsutil/filesystem.h>
+#include <wsutil/file_util.h>
+#include <wsutil/privileges.h>
+#include <wsutil/report_err.h>
+#include <ws_version_info.h>
+#include <wiretap/wtap_opttypes.h>
+#include <wiretap/pcapng.h>
+
+#include "globals.h"
+#include <epan/decode_as.h>
+#include <epan/timestamp.h>
+#include <epan/packet.h>
+#include "frame_tvbuff.h"
+#include <epan/disabled_protos.h>
+#include <epan/prefs.h>
+#include <epan/column.h>
+#include <epan/print.h>
+#include <epan/addr_resolv.h>
+#include "ui/util.h"
+#include "ui/ui_util.h"
+#include "ui/decode_as_utils.h"
+#include "ui/tap_export_pdu.h"
+#include "register.h"
+#include "filter_files.h"
+#include <epan/epan_dissect.h>
+#include <epan/tap.h>
+
+#include "log.h"
+
+#include <wsutil/str_util.h>
+#include <wsutil/utf8_entities.h>
+
+#ifdef HAVE_PLUGINS
+#include <wsutil/plugins.h>
+#endif
+
+#include "sharkd.h"
+
+static guint32 cum_bytes;
+static const frame_data *ref;
+static frame_data ref_frame;
+static frame_data *prev_dis;
+static frame_data *prev_cap;
+
+static const char *cf_open_error_message(int err, gchar *err_info,
+ gboolean for_writing, int file_type);
+
+static void open_failure_message(const char *filename, int err,
+ gboolean for_writing);
+static void failure_message(const char *msg_format, va_list ap);
+static void read_failure_message(const char *filename, int err);
+static void write_failure_message(const char *filename, int err);
+static void failure_message_cont(const char *msg_format, va_list ap);
+
+capture_file cfile;
+
+static void
+print_current_user(void) {
+ gchar *cur_user, *cur_group;
+
+ if (started_with_special_privs()) {
+ cur_user = get_cur_username();
+ cur_group = get_cur_groupname();
+ fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
+ cur_user, cur_group);
+ g_free(cur_user);
+ g_free(cur_group);
+ if (running_with_special_privs()) {
+ fprintf(stderr, " This could be dangerous.");
+ }
+ fprintf(stderr, "\n");
+ }
+}
+
+int
+main(int argc, char *argv[])
+{
+ GString *comp_info_str;
+ GString *runtime_info_str;
+ char *init_progfile_dir_error;
+
+ char *gpf_path, *pf_path;
+ char *gdp_path, *dp_path;
+ char *cf_path;
+ char *err_msg = NULL;
+ int gpf_open_errno, gpf_read_errno;
+ int pf_open_errno, pf_read_errno;
+ int gdp_open_errno, gdp_read_errno;
+ int dp_open_errno, dp_read_errno;
+ int cf_open_errno;
+ e_prefs *prefs_p;
+
+ cmdarg_err_init(failure_message, failure_message_cont);
+
+ /*
+ * Get credential information for later use, and drop privileges
+ * before doing anything else.
+ * Let the user know if anything happened.
+ */
+ init_process_policies();
+ relinquish_special_privs_perm();
+ print_current_user();
+
+ /*
+ * Attempt to get the pathname of the executable file.
+ */
+ init_progfile_dir_error = init_progfile_dir(argv[0], main);
+ if (init_progfile_dir_error != NULL) {
+ fprintf(stderr, "sharkd: Can't get pathname of sharkd program: %s.\n",
+ init_progfile_dir_error);
+ }
+
+ /* Get the compile-time version information string */
+ comp_info_str = get_compiled_version_info(NULL, epan_get_compiled_version_info);
+
+ /* Get the run-time version information string */
+ runtime_info_str = get_runtime_version_info(epan_get_runtime_version_info);
+
+ /* Add it to the information to be reported on a crash. */
+ ws_add_crash_info("Sharkd (Wireshark) %s\n"
+ "\n"
+ "%s"
+ "\n"
+ "%s",
+ get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
+ g_string_free(comp_info_str, TRUE);
+ g_string_free(runtime_info_str, TRUE);
+
+ if (sharkd_init(argc, argv) < 0)
+ {
+ printf("cannot initialize sharkd\n");
+ return 1;
+ }
+
+ init_report_err(failure_message, open_failure_message, read_failure_message,
+ write_failure_message);
+
+ timestamp_set_type(TS_RELATIVE);
+ timestamp_set_precision(TS_PREC_AUTO);
+ timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
+
+ wtap_init();
+
+#ifdef HAVE_PLUGINS
+ /* Register all the plugin types we have. */
+ epan_register_plugin_types(); /* Types known to libwireshark */
+
+ /* Scan for plugins. This does *not* call their registration routines;
+ that's done later. */
+ scan_plugins(REPORT_LOAD_FAILURE);
+
+ /* Register all libwiretap plugin modules. */
+ register_all_wiretap_modules();
+#endif
+
+ /* Register all dissectors; we must do this before checking for the
+ "-G" flag, as the "-G" flag dumps information registered by the
+ dissectors, and we must do it before we read the preferences, in
+ case any dissectors register preferences. */
+ if (!epan_init(register_all_protocols, register_all_protocol_handoffs, NULL,
+ NULL))
+ return 2;
+
+ /* load the decode as entries of this profile */
+ load_decode_as_entries();
+
+ prefs_p = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
+ &pf_open_errno, &pf_read_errno, &pf_path);
+ if (gpf_path != NULL) {
+ if (gpf_open_errno != 0) {
+ cmdarg_err("Can't open global preferences file \"%s\": %s.",
+ pf_path, g_strerror(gpf_open_errno));
+ }
+ if (gpf_read_errno != 0) {
+ cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
+ pf_path, g_strerror(gpf_read_errno));
+ }
+ }
+ if (pf_path != NULL) {
+ if (pf_open_errno != 0) {
+ cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
+ g_strerror(pf_open_errno));
+ }
+ if (pf_read_errno != 0) {
+ cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
+ pf_path, g_strerror(pf_read_errno));
+ }
+ g_free(pf_path);
+ pf_path = NULL;
+ }
+
+ read_filter_list(CFILTER_LIST, &cf_path, &cf_open_errno);
+ if (cf_path != NULL) {
+ cmdarg_err("Could not open your capture filter file\n\"%s\": %s.",
+ cf_path, g_strerror(cf_open_errno));
+ g_free(cf_path);
+ }
+
+ if (!color_filters_init(&err_msg, NULL)) {
+ fprintf(stderr, "color_filters_init() failed %s\n", err_msg);
+ g_free(err_msg);
+ }
+
+ /* Read the disabled protocols file. */
+ read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
+ &dp_path, &dp_open_errno, &dp_read_errno);
+ read_disabled_heur_dissector_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
+ &dp_path, &dp_open_errno, &dp_read_errno);
+ if (gdp_path != NULL) {
+ if (gdp_open_errno != 0) {
+ cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
+ gdp_path, g_strerror(gdp_open_errno));
+ }
+ if (gdp_read_errno != 0) {
+ cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
+ gdp_path, g_strerror(gdp_read_errno));
+ }
+ g_free(gdp_path);
+ }
+ if (dp_path != NULL) {
+ if (dp_open_errno != 0) {
+ cmdarg_err(
+ "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
+ g_strerror(dp_open_errno));
+ }
+ if (dp_read_errno != 0) {
+ cmdarg_err(
+ "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
+ g_strerror(dp_read_errno));
+ }
+ g_free(dp_path);
+ }
+
+ cap_file_init(&cfile);
+
+ /* Notify all registered modules that have had any of their preferences
+ changed either from one of the preferences file or from the command
+ line that their preferences have changed. */
+ prefs_apply_all();
+
+ /* disabled protocols as per configuration file */
+ if (gdp_path == NULL && dp_path == NULL) {
+ set_disabled_protos_list();
+ set_disabled_heur_dissector_list();
+ }
+
+ /* Build the column format array */
+ build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
+
+ return sharkd_loop();
+}
+
+static const nstime_t *
+sharkd_get_frame_ts(void *data, guint32 frame_num)
+{
+ capture_file *cf = (capture_file *) data;
+
+ if (ref && ref->num == frame_num)
+ return &ref->abs_ts;
+
+ if (prev_dis && prev_dis->num == frame_num)
+ return &prev_dis->abs_ts;
+
+ if (prev_cap && prev_cap->num == frame_num)
+ return &prev_cap->abs_ts;
+
+ if (cf->frames) {
+ frame_data *fd = frame_data_sequence_find(cf->frames, frame_num);
+
+ return (fd) ? &fd->abs_ts : NULL;
+ }
+
+ return NULL;
+}
+
+static epan_t *
+sharkd_epan_new(capture_file *cf)
+{
+ epan_t *epan = epan_new();
+
+ epan->data = cf;
+ epan->get_frame_ts = sharkd_get_frame_ts;
+ epan->get_interface_name = cap_file_get_interface_name;
+ epan->get_user_comment = NULL;
+
+ return epan;
+}
+
+static gboolean
+process_packet_first_pass(capture_file *cf, epan_dissect_t *edt,
+ gint64 offset, struct wtap_pkthdr *whdr,
+ const guchar *pd)
+{
+ frame_data fdlocal;
+ guint32 framenum;
+ gboolean passed;
+
+ /* The frame number of this packet is one more than the count of
+ frames in this packet. */
+ framenum = cf->count + 1;
+
+ /* If we're not running a display filter and we're not printing any
+ packet information, we don't need to do a dissection. This means
+ that all packets can be marked as 'passed'. */
+ passed = TRUE;
+
+ frame_data_init(&fdlocal, framenum, whdr, offset, cum_bytes);
+
+ /* If we're going to print packet information, or we're going to
+ run a read filter, or display filter, or we're going to process taps, set up to
+ do a dissection and do so. */
+ if (edt) {
+ if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
+ gbl_resolv_flags.transport_name)
+ /* Grab any resolved addresses */
+ host_name_lookup_process();
+
+ /* If we're running a read filter, prime the epan_dissect_t with that
+ filter. */
+ if (cf->rfcode)
+ epan_dissect_prime_dfilter(edt, cf->rfcode);
+
+ if (cf->dfcode)
+ epan_dissect_prime_dfilter(edt, cf->dfcode);
+
+ frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
+ &ref, prev_dis);
+ if (ref == &fdlocal) {
+ ref_frame = fdlocal;
+ ref = &ref_frame;
+ }
+
+ epan_dissect_run(edt, cf->cd_t, whdr, frame_tvbuff_new(&fdlocal, pd), &fdlocal, NULL);
+
+ /* Run the read filter if we have one. */
+ if (cf->rfcode)
+ passed = dfilter_apply_edt(cf->rfcode, edt);
+ }
+
+ if (passed) {
+ frame_data_set_after_dissect(&fdlocal, &cum_bytes);
+ prev_cap = prev_dis = frame_data_sequence_add(cf->frames, &fdlocal);
+
+ /* If we're not doing dissection then there won't be any dependent frames.
+ * More importantly, edt.pi.dependent_frames won't be initialized because
+ * epan hasn't been initialized.
+ * if we *are* doing dissection, then mark the dependent frames, but only
+ * if a display filter was given and it matches this packet.
+ */
+ if (edt && cf->dfcode) {
+ if (dfilter_apply_edt(cf->dfcode, edt)) {
+ g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->frames);
+ }
+ }
+
+ cf->count++;
+ } else {
+ /* if we don't add it to the frame_data_sequence, clean it up right now
+ * to avoid leaks */
+ frame_data_destroy(&fdlocal);
+ }
+
+ if (edt)
+ epan_dissect_reset(edt);
+
+ return passed;
+}
+
+
+static int
+load_cap_file(capture_file *cf, int max_packet_count, gint64 max_byte_count)
+{
+ int err;
+ gchar *err_info = NULL;
+ gint64 data_offset;
+ epan_dissect_t *edt = NULL;
+
+ {
+ /* Allocate a frame_data_sequence for all the frames. */
+ cf->frames = new_frame_data_sequence();
+
+ {
+ gboolean create_proto_tree = FALSE;
+
+ /* If we're going to be applying a filter, we'll need to
+ create a protocol tree against which to apply the filter. */
+ if (cf->rfcode || cf->dfcode)
+ create_proto_tree = TRUE;
+
+ /* We're not going to display the protocol tree on this pass,
+ so it's not going to be "visible". */
+ edt = epan_dissect_new(cf->epan, create_proto_tree, FALSE);
+ }
+
+ while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
+ if (process_packet_first_pass(cf, edt, data_offset, wtap_phdr(cf->wth),
+ wtap_buf_ptr(cf->wth))) {
+ /* Stop reading if we have the maximum number of packets;
+ * When the -c option has not been used, max_packet_count
+ * starts at 0, which practically means, never stop reading.
+ * (unless we roll over max_packet_count ?)
+ */
+ if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
+ err = 0; /* This is not an error */
+ break;
+ }
+ }
+ }
+
+ if (edt) {
+ epan_dissect_free(edt);
+ edt = NULL;
+ }
+
+ /* Close the sequential I/O side, to free up memory it requires. */
+ wtap_sequential_close(cf->wth);
+
+ /* Allow the protocol dissectors to free up memory that they
+ * don't need after the sequential run-through of the packets. */
+ postseq_cleanup_all_protocols();
+
+ prev_dis = NULL;
+ prev_cap = NULL;
+ }
+
+ if (err != 0) {
+ switch (err) {
+
+ case WTAP_ERR_UNSUPPORTED:
+ cmdarg_err("The file \"%s\" contains record data that TShark doesn't support.\n(%s)",
+ cf->filename,
+ err_info != NULL ? err_info : "no information supplied");
+ g_free(err_info);
+ break;
+
+ case WTAP_ERR_SHORT_READ:
+ cmdarg_err("The file \"%s\" appears to have been cut short in the middle of a packet.",
+ cf->filename);
+ break;
+
+ case WTAP_ERR_BAD_FILE:
+ cmdarg_err("The file \"%s\" appears to be damaged or corrupt.\n(%s)",
+ cf->filename,
+ err_info != NULL ? err_info : "no information supplied");
+ g_free(err_info);
+ break;
+
+ case WTAP_ERR_DECOMPRESS:
+ cmdarg_err("The compressed file \"%s\" appears to be damaged or corrupt.\n"
+ "(%s)", cf->filename,
+ err_info != NULL ? err_info : "no information supplied");
+ g_free(err_info);
+ break;
+
+ default:
+ cmdarg_err("An error occurred while reading the file \"%s\": %s.",
+ cf->filename, wtap_strerror(err));
+ break;
+ }
+ }
+
+ return err;
+}
+
+cf_status_t
+cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
+{
+ wtap *wth;
+ gchar *err_info;
+ char err_msg[2048+1];
+
+ wth = wtap_open_offline(fname, type, err, &err_info, TRUE);
+ if (wth == NULL)
+ goto fail;
+
+ /* The open succeeded. Fill in the information for this file. */
+
+ /* Create new epan session for dissection. */
+ epan_free(cf->epan);
+ cf->epan = sharkd_epan_new(cf);
+
+ cf->wth = wth;
+ cf->f_datalen = 0; /* not used, but set it anyway */
+
+ /* Set the file name because we need it to set the follow stream filter.
+ XXX - is that still true? We need it for other reasons, though,
+ in any case. */
+ cf->filename = g_strdup(fname);
+
+ /* Indicate whether it's a permanent or temporary file. */
+ cf->is_tempfile = is_tempfile;
+
+ /* No user changes yet. */
+ cf->unsaved_changes = FALSE;
+
+ cf->cd_t = wtap_file_type_subtype(cf->wth);
+ cf->open_type = type;
+ cf->count = 0;
+ cf->drops_known = FALSE;
+ cf->drops = 0;
+ cf->snap = wtap_snapshot_length(cf->wth);
+ if (cf->snap == 0) {
+ /* Snapshot length not known. */
+ cf->has_snap = FALSE;
+ cf->snap = WTAP_MAX_PACKET_SIZE;
+ } else
+ cf->has_snap = TRUE;
+ nstime_set_zero(&cf->elapsed_time);
+ ref = NULL;
+ prev_dis = NULL;
+ prev_cap = NULL;
+
+ cf->state = FILE_READ_IN_PROGRESS;
+
+ wtap_set_cb_new_ipv4(cf->wth, add_ipv4_name);
+ wtap_set_cb_new_ipv6(cf->wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
+
+ return CF_OK;
+
+fail:
+ g_snprintf(err_msg, sizeof err_msg,
+ cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
+ cmdarg_err("%s", err_msg);
+ return CF_ERROR;
+}
+
+static const char *
+cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
+ int file_type)
+{
+ const char *errmsg;
+ static char errmsg_errno[1024+1];
+
+ if (err < 0) {
+ /* Wiretap error. */
+ switch (err) {
+
+ case WTAP_ERR_NOT_REGULAR_FILE:
+ errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
+ break;
+
+ case WTAP_ERR_RANDOM_OPEN_PIPE:
+ /* Seen only when opening a capture file for reading. */
+ errmsg = "The file \"%s\" is a pipe or FIFO; TShark can't read pipe or FIFO files in two-pass mode.";
+ break;
+
+ case WTAP_ERR_FILE_UNKNOWN_FORMAT:
+ /* Seen only when opening a capture file for reading. */
+ errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
+ break;
+
+ case WTAP_ERR_UNSUPPORTED:
+ /* Seen only when opening a capture file for reading. */
+ g_snprintf(errmsg_errno, sizeof(errmsg_errno),
+ "The file \"%%s\" contains record data that TShark doesn't support.\n"
+ "(%s)",
+ err_info != NULL ? err_info : "no information supplied");
+ g_free(err_info);
+ errmsg = errmsg_errno;
+ break;
+
+ case WTAP_ERR_CANT_WRITE_TO_PIPE:
+ /* Seen only when opening a capture file for writing. */
+ g_snprintf(errmsg_errno, sizeof(errmsg_errno),
+ "The file \"%%s\" is a pipe, and \"%s\" capture files can't be "
+ "written to a pipe.", wtap_file_type_subtype_short_string(file_type));
+ errmsg = errmsg_errno;
+ break;
+
+ case WTAP_ERR_UNWRITABLE_FILE_TYPE:
+ /* Seen only when opening a capture file for writing. */
+ errmsg = "TShark doesn't support writing capture files in that format.";
+ break;
+
+ case WTAP_ERR_UNWRITABLE_ENCAP:
+ /* Seen only when opening a capture file for writing. */
+ g_snprintf(errmsg_errno, sizeof(errmsg_errno),
+ "TShark can't save this capture as a \"%s\" file.",
+ wtap_file_type_subtype_short_string(file_type));
+ errmsg = errmsg_errno;
+ break;
+
+ case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
+ if (for_writing) {
+ g_snprintf(errmsg_errno, sizeof(errmsg_errno),
+ "TShark can't save this capture as a \"%s\" file.",
+ wtap_file_type_subtype_short_string(file_type));
+ errmsg = errmsg_errno;
+ } else
+ errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
+ break;
+
+ case WTAP_ERR_BAD_FILE:
+ /* Seen only when opening a capture file for reading. */
+ g_snprintf(errmsg_errno, sizeof(errmsg_errno),
+ "The file \"%%s\" appears to be damaged or corrupt.\n"
+ "(%s)",
+ err_info != NULL ? err_info : "no information supplied");
+ g_free(err_info);
+ errmsg = errmsg_errno;
+ break;
+
+ case WTAP_ERR_CANT_OPEN:
+ if (for_writing)
+ errmsg = "The file \"%s\" could not be created for some unknown reason.";
+ else
+ errmsg = "The file \"%s\" could not be opened for some unknown reason.";
+ break;
+
+ case WTAP_ERR_SHORT_READ:
+ errmsg = "The file \"%s\" appears to have been cut short"
+ " in the middle of a packet or other data.";
+ break;
+
+ case WTAP_ERR_SHORT_WRITE:
+ errmsg = "A full header couldn't be written to the file \"%s\".";
+ break;
+
+ case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
+ errmsg = "This file type cannot be written as a compressed file.";
+ break;
+
+ case WTAP_ERR_DECOMPRESS:
+ /* Seen only when opening a capture file for reading. */
+ g_snprintf(errmsg_errno, sizeof(errmsg_errno),
+ "The compressed file \"%%s\" appears to be damaged or corrupt.\n"
+ "(%s)",
+ err_info != NULL ? err_info : "no information supplied");
+ g_free(err_info);
+ errmsg = errmsg_errno;
+ break;
+
+ default:
+ g_snprintf(errmsg_errno, sizeof(errmsg_errno),
+ "The file \"%%s\" could not be %s: %s.",
+ for_writing ? "created" : "opened",
+ wtap_strerror(err));
+ errmsg = errmsg_errno;
+ break;
+ }
+ } else
+ errmsg = file_open_error_message(err, for_writing);
+ return errmsg;
+}
+
+/*
+ * Open/create errors are reported with an console message in TShark.
+ */
+static void
+open_failure_message(const char *filename, int err, gboolean for_writing)
+{
+ fprintf(stderr, "sharkd: ");
+ fprintf(stderr, file_open_error_message(err, for_writing), filename);
+ fprintf(stderr, "\n");
+}
+
+/*
+ * General errors are reported with an console message in TShark.
+ */
+static void
+failure_message(const char *msg_format, va_list ap)
+{
+ fprintf(stderr, "sharkd: ");
+ vfprintf(stderr, msg_format, ap);
+ fprintf(stderr, "\n");
+}
+
+/*
+ * Read errors are reported with an console message in TShark.
+ */
+static void
+read_failure_message(const char *filename, int err)
+{
+ cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
+ filename, g_strerror(err));
+}
+
+/*
+ * Write errors are reported with an console message in TShark.
+ */
+static void
+write_failure_message(const char *filename, int err)
+{
+ cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
+ filename, g_strerror(err));
+}
+
+/*
+ * Report additional information for an error in command-line arguments.
+ */
+static void
+failure_message_cont(const char *msg_format, va_list ap)
+{
+ vfprintf(stderr, msg_format, ap);
+ fprintf(stderr, "\n");
+}
+
+cf_status_t
+sharkd_cf_open(const char *fname, unsigned int type, gboolean is_tempfile, int *err)
+{
+ return cf_open(&cfile, fname, type, is_tempfile, err);
+}
+
+int
+sharkd_load_cap_file(void)
+{
+ return load_cap_file(&cfile, 0, 0);
+}
+
+int
+sharkd_dissect_request(unsigned int framenum, void (*cb)(packet_info *, proto_tree *, struct epan_column_info *, const GSList *, void *), int dissect_bytes, int dissect_columns, int dissect_tree, void *data)
+{
+ frame_data *fdata;
+ column_info *cinfo = (dissect_columns) ? &cfile.cinfo : NULL;
+ epan_dissect_t edt;
+ gboolean create_proto_tree;
+ struct wtap_pkthdr phdr; /* Packet header */
+ Buffer buf; /* Packet data */
+
+ int err;
+ char *err_info = NULL;
+
+ fdata = frame_data_sequence_find(cfile.frames, framenum);
+ if (fdata == NULL)
+ return -1;
+
+ wtap_phdr_init(&phdr);
+ ws_buffer_init(&buf, 1500);
+
+ if (!wtap_seek_read(cfile.wth, fdata->file_off, &phdr, &buf, &err, &err_info)) {
+ ws_buffer_free(&buf);
+ return -1; /* error reading the record */
+ }
+
+ create_proto_tree = (dissect_tree) || (cinfo && have_custom_cols(cinfo));
+ epan_dissect_init(&edt, cfile.epan, create_proto_tree, dissect_tree);
+
+ if (cinfo)
+ col_custom_prime_edt(&edt, cinfo);
+
+ /*
+ * XXX - need to catch an OutOfMemoryError exception and
+ * attempt to recover from it.
+ */
+ epan_dissect_run(&edt, cfile.cd_t, &phdr, frame_tvbuff_new_buffer(fdata, &buf), fdata, cinfo);
+
+ if (cinfo) {
+ /* "Stringify" non frame_data vals */
+ epan_dissect_fill_in_columns(&edt, FALSE, TRUE/* fill_fd_columns */);
+ }
+
+ cb(&edt.pi, dissect_tree ? edt.tree : NULL, cinfo, dissect_bytes ? edt.pi.data_src : NULL, data);
+
+ epan_dissect_cleanup(&edt);
+ wtap_phdr_cleanup(&phdr);
+ ws_buffer_free(&buf);
+ return 0;
+}
+
+/* based on packet_list_dissect_and_cache_record */
+int
+sharkd_dissect_columns(int framenum, column_info *cinfo, gboolean dissect_color)
+{
+ frame_data *fdata;
+ epan_dissect_t edt;
+ gboolean create_proto_tree;
+ struct wtap_pkthdr phdr; /* Packet header */
+ Buffer buf; /* Packet data */
+
+ int err;
+ char *err_info = NULL;
+
+ fdata = frame_data_sequence_find(cfile.frames, framenum);
+ if (fdata == NULL) {
+ col_fill_in_error(cinfo, fdata, FALSE, TRUE/* fill_fd_columns */);
+ return -1; /* error reading the record */
+ }
+
+ wtap_phdr_init(&phdr);
+ ws_buffer_init(&buf, 1500);
+
+ if (!wtap_seek_read(cfile.wth, fdata->file_off, &phdr, &buf, &err, &err_info)) {
+ col_fill_in_error(cinfo, fdata, FALSE, FALSE /* fill_fd_columns */);
+ ws_buffer_free(&buf);
+ return -1; /* error reading the record */
+ }
+
+ create_proto_tree = (dissect_color && color_filters_used()) || (cinfo && have_custom_cols(cinfo));
+
+ epan_dissect_init(&edt, cfile.epan, create_proto_tree, FALSE /* proto_tree_visible */);
+
+ if (dissect_color) {
+ color_filters_prime_edt(&edt);
+ fdata->flags.need_colorize = 1;
+ }
+
+ if (cinfo)
+ col_custom_prime_edt(&edt, cinfo);
+
+ /*
+ * XXX - need to catch an OutOfMemoryError exception and
+ * attempt to recover from it.
+ */
+ epan_dissect_run(&edt, cfile.cd_t, &phdr, frame_tvbuff_new_buffer(fdata, &buf), fdata, cinfo);
+
+ if (cinfo) {
+ /* "Stringify" non frame_data vals */
+ epan_dissect_fill_in_columns(&edt, FALSE, TRUE/* fill_fd_columns */);
+ }
+
+ epan_dissect_cleanup(&edt);
+ wtap_phdr_cleanup(&phdr);
+ ws_buffer_free(&buf);
+ return 0;
+}
+
+int
+sharkd_retap(void)
+{
+ guint32 framenum;
+ frame_data *fdata;
+ Buffer buf;
+ struct wtap_pkthdr phdr;
+ int err;
+ char *err_info = NULL;
+
+ gboolean filtering_tap_listeners;
+ guint tap_flags;
+ gboolean construct_protocol_tree;
+ epan_dissect_t edt;
+ column_info *cinfo;
+
+ filtering_tap_listeners = have_filtering_tap_listeners();
+ tap_flags = union_of_tap_listener_flags();
+
+ construct_protocol_tree = filtering_tap_listeners || (tap_flags & TL_REQUIRES_PROTO_TREE);
+ cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cfile.cinfo : NULL;
+
+ wtap_phdr_init(&phdr);
+ ws_buffer_init(&buf, 1500);
+ epan_dissect_init(&edt, cfile.epan, construct_protocol_tree, FALSE);
+
+ reset_tap_listeners();
+
+ for (framenum = 1; framenum <= cfile.count; framenum++) {
+ fdata = frame_data_sequence_find(cfile.frames, framenum);
+
+ if (!wtap_seek_read(cfile.wth, fdata->file_off, &phdr, &buf, &err, &err_info))
+ break;
+
+ epan_dissect_run_with_taps(&edt, cfile.cd_t, &phdr, frame_tvbuff_new(fdata, ws_buffer_start_ptr(&buf)), fdata, cinfo);
+ epan_dissect_reset(&edt);
+ }
+
+ wtap_phdr_cleanup(&phdr);
+ ws_buffer_free(&buf);
+ epan_dissect_cleanup(&edt);
+
+ draw_tap_listeners(TRUE);
+
+ return 0;
+}
+
+int
+sharkd_filter(const char *dftext, guint8 **result)
+{
+ dfilter_t *dfcode = NULL;
+
+ guint32 framenum;
+ guint32 frames_count;
+ Buffer buf;
+ struct wtap_pkthdr phdr;
+ int err;
+ char *err_info = NULL;
+
+ guint8 *result_bits;
+ guint8 passed_bits;
+
+ epan_dissect_t edt;
+
+ if (!dfilter_compile(dftext, &dfcode, &err_info)) {
+ g_free(err_info);
+ return -1;
+ }
+
+ frames_count = cfile.count;
+
+ wtap_phdr_init(&phdr);
+ ws_buffer_init(&buf, 1500);
+ epan_dissect_init(&edt, cfile.epan, TRUE, FALSE);
+
+ passed_bits = 0;
+ result_bits = (guint8 *) g_malloc(2 + (frames_count / 8));
+
+ for (framenum = 1; framenum <= frames_count; framenum++) {
+ frame_data *fdata = frame_data_sequence_find(cfile.frames, framenum);
+
+ if ((framenum & 7) == 0) {
+ result_bits[(framenum / 8) - 1] = passed_bits;
+ passed_bits = 0;
+ }
+
+ if (!wtap_seek_read(cfile.wth, fdata->file_off, &phdr, &buf, &err, &err_info))
+ break;
+
+ /* frame_data_set_before_dissect */
+ epan_dissect_prime_dfilter(&edt, dfcode);
+
+ epan_dissect_run(&edt, cfile.cd_t, &phdr, frame_tvbuff_new_buffer(fdata, &buf), fdata, NULL);
+
+ if (dfilter_apply_edt(dfcode, &edt))
+ passed_bits |= (1 << (framenum % 8));
+
+ /* if passed or ref -> frame_data_set_after_dissect */
+
+ epan_dissect_reset(&edt);
+ }
+
+ if ((framenum & 7) == 0)
+ framenum--;
+ result_bits[framenum / 8] = passed_bits;
+
+ wtap_phdr_cleanup(&phdr);
+ ws_buffer_free(&buf);
+ epan_dissect_cleanup(&edt);
+
+ dfilter_free(dfcode);
+
+ *result = result_bits;
+
+ return framenum;
+}
+
+#include "version.h"
+const char *sharkd_version(void)
+{
+ /* based on get_ws_vcs_version_info(), but shorter */
+#ifdef VCSVERSION
+ return VCSVERSION;
+#else
+ return VERSION;
+#endif
+}
+
+/*
+ * Editor modelines - https://www.wireshark.org/tools/modelines.html
+ *
+ * Local variables:
+ * c-basic-offset: 2
+ * tab-width: 8
+ * indent-tabs-mode: nil
+ * End:
+ *
+ * vi: set shiftwidth=2 tabstop=8 expandtab:
+ * :indentSize=2:tabSize=8:noTabs=true:
+ */
diff --git a/sharkd.h b/sharkd.h
new file mode 100644
index 0000000000..f82aa78f3d
--- /dev/null
+++ b/sharkd.h
@@ -0,0 +1,60 @@
+/* sharkd.h
+ *
+ * Copyright (C) 2016 Jakub Zawadzki
+ *
+ * Wireshark - Network traffic analyzer
+ * By Gerald Combs <gerald@wireshark.org>
+ * Copyright 1998 Gerald Combs
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#ifndef __SHARKD_H
+#define __SHARKD_H
+
+#include <file.h>
+
+/* sharkd.c */
+cf_status_t sharkd_cf_open(const char *fname, unsigned int type, gboolean is_tempfile, int *err);
+int sharkd_load_cap_file(void);
+int sharkd_retap(void);
+int sharkd_filter(const char *dftext, guint8 **result);
+int sharkd_dissect_columns(int framenum, column_info *cinfo, gboolean dissect_color);
+int sharkd_dissect_request(unsigned int framenum, void (*cb)(packet_info *, proto_tree *, struct epan_column_info *, const GSList *, void *), int dissect_bytes, int dissect_columns, int dissect_tree, void *data);
+const char *sharkd_version(void);
+
+extern capture_file cfile;
+
+/* sharkd_daemon.c */
+int sharkd_init(int argc, char **argv);
+int sharkd_loop(void);
+
+/* sharkd_session.c */
+int sharkd_session_main(void);
+
+#endif /* __SHARKD_H */
+
+/*
+ * Editor modelines - http://www.wireshark.org/tools/modelines.html
+ *
+ * Local variables:
+ * c-basic-offset: 8
+ * tab-width: 8
+ * indent-tabs-mode: t
+ * End:
+ *
+ * vi: set shiftwidth=8 tabstop=8 noexpandtab:
+ * :indentSize=8:tabSize=8:noTabs=false:
+ */
diff --git a/sharkd_daemon.c b/sharkd_daemon.c
new file mode 100644
index 0000000000..1f7981b9ed
--- /dev/null
+++ b/sharkd_daemon.c
@@ -0,0 +1,223 @@
+/* sharkd_daemon.c
+ *
+ * Copyright (C) 2016 Jakub Zawadzki
+ *
+ * Wireshark - Network traffic analyzer
+ * By Gerald Combs <gerald@wireshark.org>
+ * Copyright 1998 Gerald Combs
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include <config.h>
+
+#include <glib.h>
+
+#include <stdio.h>
+#include <errno.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <unistd.h>
+
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <arpa/inet.h>
+
+#include <wsutil/strtoi.h>
+
+#include "sharkd.h"
+
+static int _server_fd = -1;
+
+static int
+socket_init(char *path)
+{
+ int fd = -1;
+
+ if (!strncmp(path, "unix:", 5))
+ {
+ struct sockaddr_un s_un;
+ size_t s_un_len;
+
+ path += 5;
+
+ if (strlen(path) + 1 > sizeof(s_un.sun_path))
+ return -1;
+
+ fd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (fd == -1)
+ return -1;
+
+ memset(&s_un, 0, sizeof(s_un));
+ s_un.sun_family = AF_UNIX;
+ g_strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path));
+
+ s_un_len = offsetof(struct sockaddr_un, sun_path) + strlen(s_un.sun_path);
+
+ if (s_un.sun_path[0] == '@')
+ s_un.sun_path[0] = '\0';
+
+ if (bind(fd, (struct sockaddr *) &s_un, s_un_len))
+ {
+ close(fd);
+ return -1;
+ }
+
+ }
+#ifdef SHARKD_TCP_SUPPORT
+ else if (!strncmp(path, "tcp:", 4))
+ {
+ struct sockaddr_in s_in;
+ int one = 1;
+ char *port_sep;
+ guint16 port;
+
+ path += 4;
+
+ port_sep = strchr(path, ':');
+ if (!port_sep)
+ return -1;
+
+ *port_sep = '\0';
+
+ if (ws_strtou16(port_sep + 1, NULL, &port) == FALSE)
+ return -1;
+
+ fd = socket(AF_INET, SOCK_STREAM, 0);
+ if (fd == -1)
+ return -1;
+
+ s_in.sin_family = AF_INET;
+ s_in.sin_addr.s_addr = inet_addr(path);
+ s_in.sin_port = g_htons(port);
+ *port_sep = ':';
+
+ setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
+
+ if (bind(fd, (struct sockaddr *) &s_in, sizeof(struct sockaddr_in)))
+ {
+ close(fd);
+ return -1;
+ }
+ }
+#endif
+ else
+ {
+ return -1;
+ }
+
+ if (listen(fd, SOMAXCONN))
+ {
+ close(fd);
+ return -1;
+ }
+
+ return fd;
+}
+
+int
+sharkd_init(int argc, char **argv)
+{
+ int fd;
+ pid_t pid;
+
+ if (argc != 2)
+ {
+ fprintf(stderr, "Usage: %s <socket>\n", argv[0]);
+ fprintf(stderr, "\n");
+
+ fprintf(stderr, "<socket> examples:\n");
+ fprintf(stderr, " - unix:/tmp/sharkd.sock - listen on unix file /tmp/sharkd.sock\n");
+#ifdef SHARKD_TCP_SUPPORT
+ fprintf(stderr, " - tcp:127.0.0.1:4446 - listen on TCP port 4446\n");
+#endif
+ fprintf(stderr, "\n");
+ return -1;
+ }
+
+ signal(SIGCHLD, SIG_IGN);
+
+ fd = socket_init(argv[1]);
+ if (fd == -1)
+ return -1;
+
+ /* all good - try to daemonize */
+ pid = fork();
+ if (pid == -1)
+ fprintf(stderr, "cannot go to background fork() failed: %s\n", g_strerror(errno));
+
+ if (pid != 0)
+ {
+ /* parent */
+ exit(0);
+ }
+
+ _server_fd = fd;
+ return 0;
+}
+
+int
+sharkd_loop(void)
+{
+ while (1)
+ {
+ int fd;
+ pid_t pid;
+
+ fd = accept(_server_fd, NULL, NULL);
+ if (fd == -1)
+ {
+ fprintf(stderr, "cannot accept(): %s\n", g_strerror(errno));
+ continue;
+ }
+
+ /* wireshark is not ready for handling multiple capture files in single process, so fork(), and handle it in seperate process */
+ pid = fork();
+ if (pid == 0)
+ {
+ /* redirect stdin, stdout to socket */
+ dup2(fd, 0);
+ dup2(fd, 1);
+ close(fd);
+
+ exit(sharkd_session_main());
+ }
+
+ if (pid == -1)
+ {
+ fprintf(stderr, "cannot fork(): %s\n", g_strerror(errno));
+ }
+
+ close(fd);
+ }
+
+ return 0;
+}
+
+/*
+ * Editor modelines - http://www.wireshark.org/tools/modelines.html
+ *
+ * Local variables:
+ * c-basic-offset: 8
+ * tab-width: 8
+ * indent-tabs-mode: t
+ * End:
+ *
+ * vi: set shiftwidth=8 tabstop=8 noexpandtab:
+ * :indentSize=8:tabSize=8:noTabs=false:
+ */
diff --git a/sharkd_session.c b/sharkd_session.c
new file mode 100644
index 0000000000..0b6bb96d4c
--- /dev/null
+++ b/sharkd_session.c
@@ -0,0 +1,1944 @@
+/* sharkd_session.c
+ *
+ * Copyright (C) 2016 Jakub Zawadzki
+ *
+ * Wireshark - Network traffic analyzer
+ * By Gerald Combs <gerald@wireshark.org>
+ * Copyright 1998 Gerald Combs
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include <config.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#include <glib.h>
+
+#include <wsutil/wsjsmn.h>
+
+#include <file.h>
+#include <epan/exceptions.h>
+#include <epan/color_filters.h>
+#include <epan/prefs.h>
+#include <epan/prefs-int.h>
+#include <epan/uat-int.h>
+#include <wiretap/wtap.h>
+
+#include <epan/column.h>
+
+#include <epan/stats_tree_priv.h>
+#include <epan/stat_tap_ui.h>
+#include <epan/conversation_table.h>
+
+#include <epan/dissectors/packet-h225.h>
+#include <epan/rtp_pt.h>
+#include <ui/voip_calls.h>
+#include <ui/rtp_stream.h>
+#include <ui/tap-rtp-common.h>
+#include <epan/to_str.h>
+
+#ifdef HAVE_GEOIP
+# include <GeoIP.h>
+# include <epan/geoip_db.h>
+# include <wsutil/pint.h>
+#endif
+
+#include <wsutil/strtoi.h>
+
+#include "sharkd.h"
+
+static struct register_ct *
+_get_conversation_table_by_name(const char *name)
+{
+ guint count = conversation_table_get_num();
+ guint i;
+
+ /* XXX, wow O(n^2), move to libwireshark */
+ for (i = 0; i < count; i++)
+ {
+ struct register_ct *table = get_conversation_table_by_num(i);
+ const char *label = proto_get_protocol_short_name(find_protocol_by_id(get_conversation_proto_id(table)));
+
+ if (!strcmp(label, name))
+ return table;
+ }
+
+ return NULL;
+}
+
+static void
+json_unescape_str(char *input)
+{
+ char *output = input;
+
+ while (*input)
+ {
+ char ch = *input++;
+
+ if (ch == '\\')
+ {
+ /* TODO, add more escaping rules */
+ ch = *input++;
+ }
+
+ *output = ch;
+ output++;
+ }
+
+ *output = '\0';
+}
+
+static const char *
+json_find_attr(const char *buf, const jsmntok_t *tokens, int count, const char *attr)
+{
+ int i;
+
+ for (i = 0; i < count; i += 2)
+ {
+ const char *tok_attr = &buf[tokens[i + 0].start];
+ const char *tok_value = &buf[tokens[i + 1].start];
+
+ if (!strcmp(tok_attr, attr))
+ return tok_value;
+ }
+
+ return NULL;
+}
+
+static void
+json_puts_string(const char *str)
+{
+ int i;
+
+ if (str == NULL)
+ str = "";
+
+ putchar('"');
+ for (i = 0; str[i]; i++)
+ {
+ switch (str[i])
+ {
+ case '\\':
+ case '"':
+ putchar('\\');
+ putchar(str[i]);
+ break;
+
+ case '\n':
+ putchar('\\');
+ putchar('n');
+ break;
+
+ default:
+ putchar(str[i]);
+ break;
+ }
+ }
+
+ putchar('"');
+}
+
+static void
+json_print_base64(const guint8 *data, int len)
+{
+ int i;
+ int base64_state1 = 0;
+ int base64_state2 = 0;
+ gsize wrote;
+ gchar buf[(1 / 3 + 1) * 4 + 4];
+
+ putchar('"');
+
+ for (i = 0; i < len; i++)
+ {
+ wrote = g_base64_encode_step(&data[i], 1, FALSE, buf, &base64_state1, &base64_state2);
+ if (wrote > 0)
+ fwrite(buf, 1, wrote, stdout);
+ }
+
+ wrote = g_base64_encode_close(FALSE, buf, &base64_state1, &base64_state2);
+ if (wrote > 0)
+ fwrite(buf, 1, wrote, stdout);
+
+ putchar('"');
+}
+
+struct filter_item
+{
+ struct filter_item *next;
+
+ char *filter;
+ guint8 *filtered;
+};
+
+static struct filter_item *filter_list = NULL;
+
+static const guint8 *
+sharkd_session_filter_data(const char *filter)
+{
+ struct filter_item *l;
+
+ for (l = filter_list; l; l = l->next)
+ {
+ if (!strcmp(l->filter, filter))
+ return l->filtered;
+ }
+
+ {
+ guint8 *filtered = NULL;
+
+ int ret = sharkd_filter(filter, &filtered);
+
+ if (ret == -1)
+ return NULL;
+
+ l = (struct filter_item *) g_malloc(sizeof(struct filter_item));
+ l->filter = g_strdup(filter);
+ l->filtered = filtered;
+
+ l->next = filter_list;
+ filter_list = l;
+
+ return filtered;
+ }
+}
+
+static void
+sharkd_session_process_info_conv_cb(gpointer data, gpointer user_data)
+{
+ struct register_ct *table = (struct register_ct *) data;
+ int *pi = (int *) user_data;
+
+ const char *label = proto_get_protocol_short_name(find_protocol_by_id(get_conversation_proto_id(table)));
+
+ if (get_conversation_packet_func(table))
+ {
+ printf("%s{", (*pi) ? "," : "");
+ printf("\"name\":\"Conversation List/%s\"", label);
+ printf(",\"tap\":\"conv:%s\"", label);
+ printf("}");
+
+ *pi = *pi + 1;
+ }
+
+ if (get_hostlist_packet_func(table))
+ {
+ printf("%s{", (*pi) ? "," : "");
+ printf("\"name\":\"Endpoint/%s\"", label);
+ printf(",\"tap\":\"endpt:%s\"", label);
+ printf("}");
+
+ *pi = *pi + 1;
+ }
+}
+
+/**
+ * sharkd_session_process_info()
+ *
+ * Process info request
+ *
+ * Output object with attributes:
+ * (m) columns - available column formats, array of object with attributes:
+ * 'name' - column name
+ * 'format' - column format-name
+ *
+ * (m) stats - available statistics, array of object with attributes:
+ * 'name' - statistic name
+ * 'tap' - sharkd tap-name for statistic
+ *
+ * (m) convs - available conversation list, array of object with attributes:
+ * 'name' - conversation name
+ * 'tap' - sharkd tap-name for conversation
+ *
+ * (m) taps - available taps, array of object with attributes:
+ * 'name' - tap name
+ * 'tap' - sharkd tap-name
+ *
+ * (m) ftypes - conversation table for FT_ number to string
+ */
+static void
+sharkd_session_process_info(void)
+{
+ int i;
+
+ printf("{\"columns\":[");
+ for (i = 0; i < NUM_COL_FMTS; i++)
+ {
+ const char *col_format = col_format_to_string(i);
+ const char *col_descr = col_format_desc(i);
+
+ printf("%s{", (i) ? "," : "");
+ printf("\"name\":\"%s\"", col_descr);
+ printf(",\"format\":\"%s\"", col_format);
+ printf("}");
+ }
+ printf("]");
+
+ printf(",\"stats\":[");
+ {
+ GList *cfg_list = stats_tree_get_cfg_list();
+ GList *l;
+ const char *sepa = "";
+
+ for (l = cfg_list; l; l = l->next)
+ {
+ stats_tree_cfg *cfg = (stats_tree_cfg *) l->data;
+
+ printf("%s{", sepa);
+ printf("\"name\":\"%s\"", cfg->name);
+ printf(",\"tap\":\"stat:%s\"", cfg->abbr);
+ printf("}");
+ sepa = ",";
+ }
+
+ g_list_free(cfg_list);
+ }
+ printf("]");
+
+ printf(",\"ftypes\":[");
+ for (i = 0; i < FT_NUM_TYPES; i++)
+ {
+ if (i)
+ printf(",");
+ json_puts_string(ftype_name((ftenum_t) i));
+ }
+ printf("]");
+
+ printf(",\"version\":");
+ json_puts_string(sharkd_version());
+
+ printf(",\"convs\":[");
+ i = 0;
+ conversation_table_iterate_tables(sharkd_session_process_info_conv_cb, &i);
+ printf("]");
+
+ printf(",\"taps\":[");
+ printf("]");
+
+ printf("}\n");
+}
+
+/**
+ * sharkd_session_process_load()
+ *
+ * Process load request
+ *
+ * Input:
+ * (m) file - file to be loaded
+ *
+ * Output object with attributes:
+ * (m) err - error code
+ */
+static void
+sharkd_session_process_load(const char *buf, const jsmntok_t *tokens, int count)
+{
+ const char *tok_file = json_find_attr(buf, tokens, count, "file");
+ int err = 0;
+
+ fprintf(stderr, "load: filename=%s\n", tok_file);
+
+ if (!tok_file)
+ return;
+
+ if (sharkd_cf_open(tok_file, WTAP_TYPE_AUTO, FALSE, &err) != CF_OK)
+ {
+ printf("{\"err\":%d}\n", err);
+ return;
+ }
+
+ TRY
+ {
+ err = sharkd_load_cap_file();
+ }
+ CATCH(OutOfMemoryError)
+ {
+ fprintf(stderr, "load: OutOfMemoryError\n");
+ err = ENOMEM;
+ }
+ ENDTRY;
+
+ printf("{\"err\":%d}\n", err);
+}
+
+/**
+ * sharkd_session_process_status()
+ *
+ * Process status request
+ *
+ * Output object with attributes:
+ * (m) frames - count of currently loaded frames
+ */
+static void
+sharkd_session_process_status(void)
+{
+ printf("{\"frames\":%d", cfile.count);
+
+ printf("}\n");
+}
+
+struct sharkd_analyse_data
+{
+ GHashTable *protocols_set;
+ nstime_t *first_time;
+ nstime_t *last_time;
+};
+
+static void
+sharkd_session_process_analyse_cb(packet_info *pi, proto_tree *tree, struct epan_column_info *cinfo, const GSList *data_src, void *data)
+{
+ struct sharkd_analyse_data *analyser = (struct sharkd_analyse_data *) data;
+ frame_data *fdata = pi->fd;
+
+ (void) tree;
+ (void) cinfo;
+ (void) data_src;
+
+ if (analyser->first_time == NULL || nstime_cmp(&fdata->abs_ts, analyser->first_time) < 0)
+ analyser->first_time = &fdata->abs_ts;
+
+ if (analyser->last_time == NULL || nstime_cmp(&fdata->abs_ts, analyser->last_time) > 0)
+ analyser->last_time = &fdata->abs_ts;
+
+ if (pi->layers)
+ {
+ wmem_list_frame_t *frame = wmem_list_head(pi->layers);
+
+ for (frame = wmem_list_head(pi->layers); frame; frame = wmem_list_frame_next(frame))
+ {
+ int proto_id = GPOINTER_TO_UINT(wmem_list_frame_data(frame));
+
+ if (!g_hash_table_lookup_extended(analyser->protocols_set, GUINT_TO_POINTER(proto_id), NULL, NULL))
+ {
+ g_hash_table_insert(analyser->protocols_set, GUINT_TO_POINTER(proto_id), GUINT_TO_POINTER(proto_id));
+
+ if (g_hash_table_size(analyser->protocols_set) != 1)
+ printf(",");
+ json_puts_string(proto_get_protocol_filter_name(proto_id));
+ }
+ }
+ }
+
+}
+
+/**
+ * sharkd_session_process_status()
+ *
+ * Process analyse request
+ *
+ * Output object with attributes:
+ * (m) frames - count of currently loaded frames
+ * (m) protocols - protocol list
+ * (m) first - earliest frame time
+ * (m) last - latest frame time
+ */
+static void
+sharkd_session_process_analyse(void)
+{
+ unsigned int framenum;
+ struct sharkd_analyse_data analyser;
+
+ analyser.first_time = NULL;
+ analyser.last_time = NULL;
+ analyser.protocols_set = g_hash_table_new(NULL /* g_direct_hash() */, NULL /* g_direct_equal */);
+
+ printf("{\"frames\":%d", cfile.count);
+
+ printf(",\"protocols\":[");
+ for (framenum = 1; framenum <= cfile.count; framenum++)
+ sharkd_dissect_request(framenum, &sharkd_session_process_analyse_cb, 0, 0, 0, &analyser);
+ printf("]");
+
+ if (analyser.first_time)
+ printf(",\"first\":%.9f", nstime_to_sec(analyser.first_time));
+
+ if (analyser.last_time)
+ printf(",\"last\":%.9f", nstime_to_sec(analyser.last_time));
+
+ printf("}\n");
+
+ g_hash_table_destroy(analyser.protocols_set);
+}
+
+/**
+ * sharkd_session_process_frames()
+ *
+ * Process frames request
+ *
+ * Input:
+ * (o) filter - filter to be used
+ * (o) range - packet range to be used [TODO]
+ *
+ * Output array of frames with attributes:
+ * (m) c - array of column data
+ * (m) num - frame number
+ * (m) i - if frame is ignored
+ * (m) m - if frame is marked
+ * (m) bg - color filter - background color in hex
+ * (m) fg - color filter - foreground color in hex
+ */
+static void
+sharkd_session_process_frames(const char *buf, const jsmntok_t *tokens, int count)
+{
+ const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
+
+ const guint8 *filter_data = NULL;
+
+ const char *frame_sepa = "";
+ unsigned int framenum;
+ int col;
+
+ column_info *cinfo = &cfile.cinfo;
+
+ if (tok_filter)
+ {
+ filter_data = sharkd_session_filter_data(tok_filter);
+ if (!filter_data)
+ return;
+ }
+
+ printf("[");
+ for (framenum = 1; framenum <= cfile.count; framenum++)
+ {
+ frame_data *fdata = frame_data_sequence_find(cfile.frames, framenum);
+
+ if (filter_data && !(filter_data[framenum / 8] & (1 << (framenum % 8))))
+ continue;
+
+ sharkd_dissect_columns(framenum, cinfo, (fdata->color_filter == NULL));
+
+ printf("%s{\"c\":[", frame_sepa);
+ for (col = 0; col < cinfo->num_cols; ++col)
+ {
+ const col_item_t *col_item = &cinfo->columns[col];
+
+ if (col)
+ printf(",");
+
+ json_puts_string(col_item->col_data);
+ }
+ printf("],\"num\":%u", framenum);
+
+ if (fdata->flags.ignored)
+ printf(",\"i\":true");
+
+ if (fdata->flags.marked)
+ printf(",\"m\":true");
+
+ if (fdata->color_filter)
+ {
+ printf(",\"bg\":\"%x\"", color_t_to_rgb(&fdata->color_filter->bg_color));
+ printf(",\"fg\":\"%x\"", color_t_to_rgb(&fdata->color_filter->fg_color));
+ }
+
+ printf("}");
+ frame_sepa = ",";
+ }
+ printf("]\n");
+
+ if (cinfo != &cfile.cinfo)
+ col_cleanup(cinfo);
+}
+
+static void
+sharkd_session_process_tap_stats_node_cb(const stat_node *n)
+{
+ stat_node *node;
+ const char *sepa = "";
+
+ printf("[");
+ for (node = n->children; node; node = node->next)
+ {
+ /* code based on stats_tree_get_values_from_node() */
+ printf("%s{\"name\":\"%s\"", sepa, node->name);
+ printf(",\"count\":%u", node->counter);
+ if (node->counter && ((node->st_flags & ST_FLG_AVERAGE) || node->rng))
+ {
+ printf(",\"avg\":%.2f", ((float)node->total) / node->counter);
+ printf(",\"min\":%u", node->minvalue);
+ printf(",\"max\":%u", node->maxvalue);
+ }
+
+ if (node->st->elapsed)
+ printf(",\"rate\":%.4f",((float)node->counter) / node->st->elapsed);
+
+ if (node->parent && node->parent->counter)
+ printf(",\"perc\":%.2f", (node->counter * 100.0) / node->parent->counter);
+ else if (node->parent == &(node->st->root))
+ printf(",\"perc\":100");
+
+ if (prefs.st_enable_burstinfo && node->max_burst)
+ {
+ if (prefs.st_burst_showcount)
+ printf(",\"burstcount\":%d", node->max_burst);
+ else
+ printf(",\"burstrate\":%.4f", ((double)node->max_burst) / prefs.st_burst_windowlen);
+
+ printf(",\"bursttime\":%.3f", ((double)node->burst_time / 1000.0));
+ }
+
+ if (node->children)
+ {
+ printf(",\"sub\":");
+ sharkd_session_process_tap_stats_node_cb(node);
+ }
+ printf("}");
+ sepa = ",";
+ }
+ printf("]");
+}
+
+/**
+ * sharkd_session_process_tap_stats_cb()
+ *
+ * Output stats tap:
+ *
+ * (m) tap - tap name
+ * (m) type:stats - tap output type
+ * (m) name - stat name
+ * (m) stats - array of object with attributes:
+ * (m) name - stat item name
+ * (m) count - stat item counter
+ * (o) avg - stat item averange value
+ * (o) min - stat item min value
+ * (o) max - stat item max value
+ * (o) rate - stat item rate value (ms)
+ * (o) perc - stat item percentage
+ * (o) burstrate - stat item burst rate
+ * (o) burstcount - stat item burst count
+ * (o) burstttme - stat item burst start
+ * (o) sub - array of object with attributes like in stats node.
+ */
+static void
+sharkd_session_process_tap_stats_cb(void *psp)
+{
+ stats_tree *st = (stats_tree *)psp;
+
+ printf("{\"tap\":\"stats:%s\",\"type\":\"stats\"", st->cfg->abbr);
+
+ printf(",\"name\":\"%s\",\"stats\":", st->cfg->name);
+ sharkd_session_process_tap_stats_node_cb(&st->root);
+ printf("},");
+}
+
+struct sharkd_conv_tap_data
+{
+ const char *type;
+ conv_hash_t hash;
+ gboolean resolve_name;
+ gboolean resolve_port;
+};
+
+static int
+sharkd_session_geoip_addr(address *addr, const char *suffix)
+{
+ int with_geoip = 0;
+
+ (void) addr;
+ (void) suffix;
+
+#ifdef HAVE_GEOIP
+ if (addr->type == AT_IPv4)
+ {
+ uint32_t ip = pntoh32(addr->data);
+
+ guint num_dbs = geoip_db_num_dbs();
+ guint dbnum;
+
+ for (dbnum = 0; dbnum < num_dbs; dbnum++)
+ {
+ const char *geoip_key = NULL;
+ char *geoip_val;
+
+ int db_type = geoip_db_type(dbnum);
+
+ switch (db_type)
+ {
+ case GEOIP_COUNTRY_EDITION:
+ geoip_key = "geoip_country";
+ break;
+
+ case GEOIP_CITY_EDITION_REV0:
+ case GEOIP_CITY_EDITION_REV1:
+ geoip_key = "geoip_city";
+ break;
+
+ case GEOIP_ORG_EDITION:
+ geoip_key = "geoip_org";
+ break;
+
+ case GEOIP_ISP_EDITION:
+ geoip_key = "geoip_isp";
+ break;
+
+ case GEOIP_ASNUM_EDITION:
+ geoip_key = "geoip_as";
+ break;
+
+ case WS_LAT_FAKE_EDITION:
+ geoip_key = "geoip_lat";
+ break;
+
+ case WS_LON_FAKE_EDITION:
+ geoip_key = "geoip_lon";
+ break;
+ }
+
+ if (geoip_key && (geoip_val = geoip_db_lookup_ipv4(dbnum, ip, NULL)))
+ {
+ printf(",\"%s%s\":", geoip_key, suffix);
+ json_puts_string(geoip_val);
+ with_geoip = 1;
+ }
+ }
+ }
+#endif
+#ifdef HAVE_GEOIP_V6
+ if (addr->type == AT_IPv6)
+ {
+ const struct e_in6_addr *ip6 = (const struct e_in6_addr *) addr->data;
+
+ guint num_dbs = geoip_db_num_dbs();
+ guint dbnum;
+
+ for (dbnum = 0; dbnum < num_dbs; dbnum++)
+ {
+ const char *geoip_key = NULL;
+ char *geoip_val;
+
+ int db_type = geoip_db_type(dbnum);
+
+ switch (db_type)
+ {
+ case GEOIP_COUNTRY_EDITION_V6:
+ geoip_key = "geoip_country";
+ break;
+#if NUM_DB_TYPES > 31
+ case GEOIP_CITY_EDITION_REV0_V6:
+ case GEOIP_CITY_EDITION_REV1_V6:
+ geoip_key = "geoip_city";
+ break;
+
+ case GEOIP_ORG_EDITION_V6:
+ geoip_key = "geoip_org";
+ break;
+
+ case GEOIP_ISP_EDITION_V6:
+ geoip_key = "geoip_isp";
+ break;
+
+ case GEOIP_ASNUM_EDITION_V6:
+ geoip_key = "geoip_as";
+ break;
+#endif /* DB_NUM_TYPES */
+ case WS_LAT_FAKE_EDITION:
+ geoip_key = "geoip_lat";
+ break;
+
+ case WS_LON_FAKE_EDITION:
+ geoip_key = "geoip_lon";
+ break;
+ }
+
+ if (geoip_key && (geoip_val = geoip_db_lookup_ipv6(dbnum, *ip6, NULL)))
+ {
+ printf(",\"%s%s\":", geoip_key, suffix);
+ json_puts_string(geoip_val);
+ with_geoip = 1;
+ }
+ }
+ }
+#endif
+
+ return with_geoip;
+}
+
+/**
+ * sharkd_session_process_tap_conv_cb()
+ *
+ * Output conv tap:
+ * (m) tap - tap name
+ * (m) type - tap output type
+ * (m) proto - protocol short name
+ * (o) filter - filter string
+ *
+ * (o) convs - array of object with attributes:
+ * (m) saddr - source address
+ * (m) daddr - destination address
+ * (o) sport - source port
+ * (o) dport - destination port
+ * (m) txf - TX frame count
+ * (m) txb - TX bytes
+ * (m) rxf - RX frame count
+ * (m) rxb - RX bytes
+ * (m) start - (relative) first packet time
+ * (m) stop - (relative) last packet time
+ *
+ * (o) hosts - array of object with attributes:
+ * (m) host - host address
+ * (o) port - host port
+ * (m) txf - TX frame count
+ * (m) txb - TX bytes
+ * (m) rxf - RX frame count
+ * (m) rxb - RX bytes
+ */
+static void
+sharkd_session_process_tap_conv_cb(void *arg)
+{
+ conv_hash_t *hash = (conv_hash_t *) arg;
+ const struct sharkd_conv_tap_data *iu = (struct sharkd_conv_tap_data *) hash->user_data;
+ const char *proto;
+ int proto_with_port;
+ guint i;
+
+ int with_geoip = 0;
+
+ if (!strncmp(iu->type, "conv:", 5))
+ {
+ printf("{\"tap\":\"%s\",\"type\":\"conv\"", iu->type);
+ printf(",\"convs\":[");
+ proto = iu->type + 5;
+ }
+ else if (!strncmp(iu->type, "endpt:", 6))
+ {
+ printf("{\"tap\":\"%s\",\"type\":\"host\"", iu->type);
+ printf(",\"hosts\":[");
+ proto = iu->type + 6;
+ }
+ else
+ {
+ printf("{\"tap\":\"%s\",\"type\":\"err\"", iu->type);
+ proto = "";
+ }
+
+ proto_with_port = (!strcmp(proto, "TCP") || !strcmp(proto, "UDP") || !strcmp(proto, "SCTP"));
+
+ if (iu->hash.conv_array != NULL && !strncmp(iu->type, "conv:", 5))
+ {
+ for (i = 0; i < iu->hash.conv_array->len; i++)
+ {
+ conv_item_t *iui = &g_array_index(iu->hash.conv_array, conv_item_t, i);
+ char *src_addr, *dst_addr;
+ char *src_port, *dst_port;
+ char *filter_str;
+
+ printf("%s{", i ? "," : "");
+
+ printf("\"saddr\":\"%s\"", (src_addr = get_conversation_address(NULL, &iui->src_address, iu->resolve_name)));
+ printf(",\"daddr\":\"%s\"", (dst_addr = get_conversation_address(NULL, &iui->dst_address, iu->resolve_name)));
+
+ if (proto_with_port)
+ {
+ printf(",\"sport\":\"%s\"", (src_port = get_conversation_port(NULL, iui->src_port, iui->ptype, iu->resolve_port)));
+ printf(",\"dport\":\"%s\"", (dst_port = get_conversation_port(NULL, iui->dst_port, iui->ptype, iu->resolve_port)));
+
+ wmem_free(NULL, src_port);
+ wmem_free(NULL, dst_port);
+ }
+
+ printf(",\"rxf\":%" G_GUINT64_FORMAT, iui->rx_frames);
+ printf(",\"rxb\":%" G_GUINT64_FORMAT, iui->rx_bytes);
+
+ printf(",\"txf\":%" G_GUINT64_FORMAT, iui->tx_frames);
+ printf(",\"txb\":%" G_GUINT64_FORMAT, iui->tx_bytes);
+
+ printf(",\"start\":%.9f", nstime_to_sec(&iui->start_time));
+ printf(",\"stop\":%.9f", nstime_to_sec(&iui->stop_time));
+
+ filter_str = get_conversation_filter(iui, CONV_DIR_A_TO_FROM_B);
+ if (filter_str)
+ {
+ printf(",\"filter\":\"%s\"", filter_str);
+ g_free(filter_str);
+ }
+
+ wmem_free(NULL, src_addr);
+ wmem_free(NULL, dst_addr);
+
+ if (sharkd_session_geoip_addr(&(iui->src_address), "1"))
+ with_geoip = 1;
+ if (sharkd_session_geoip_addr(&(iui->dst_address), "2"))
+ with_geoip = 1;
+
+ printf("}");
+ }
+ }
+ else if (iu->hash.conv_array != NULL && !strncmp(iu->type, "endpt:", 6))
+ {
+ for (i = 0; i < iu->hash.conv_array->len; i++)
+ {
+ hostlist_talker_t *host = &g_array_index(iu->hash.conv_array, hostlist_talker_t, i);
+ char *host_str, *port_str;
+ char *filter_str;
+
+ printf("%s{", i ? "," : "");
+
+ printf("\"host\":\"%s\"", (host_str = get_conversation_address(NULL, &host->myaddress, iu->resolve_name)));
+
+ if (proto_with_port)
+ {
+ printf(",\"port\":\"%s\"", (port_str = get_conversation_port(NULL, host->port, host->ptype, iu->resolve_port)));
+
+ wmem_free(NULL, port_str);
+ }
+
+ printf(",\"rxf\":%" G_GUINT64_FORMAT, host->rx_frames);
+ printf(",\"rxb\":%" G_GUINT64_FORMAT, host->rx_bytes);
+
+ printf(",\"txf\":%" G_GUINT64_FORMAT, host->tx_frames);
+ printf(",\"txb\":%" G_GUINT64_FORMAT, host->tx_bytes);
+
+ filter_str = get_hostlist_filter(host);
+ if (filter_str)
+ {
+ printf(",\"filter\":\"%s\"", filter_str);
+ g_free(filter_str);
+ }
+
+ wmem_free(NULL, host_str);
+
+ if (sharkd_session_geoip_addr(&(host->myaddress), ""))
+ with_geoip = 1;
+ printf("}");
+ }
+ }
+
+ printf("],\"proto\":\"%s\",\"geoip\":%s},", proto, with_geoip ? "true" : "false");
+}
+
+/**
+ * sharkd_session_process_tap()
+ *
+ * Process tap request
+ *
+ * Input:
+ * (m) tap0 - First tap request
+ * (o) tap1...tap15 - Other tap requests
+ *
+ * Output object with attributes:
+ * (m) taps - array of object with attributes:
+ * (m) tap - tap name
+ * (m) type - tap output type
+ * ...
+ * for type:stats see sharkd_session_process_tap_stats_cb()
+ * for type:conv see sharkd_session_process_tap_conv_cb()
+ * for type:host see sharkd_session_process_tap_conv_cb()
+ *
+ * (m) err - error code
+ */
+static void
+sharkd_session_process_tap(char *buf, const jsmntok_t *tokens, int count)
+{
+ void *taps_data[16];
+ int taps_count = 0;
+ int i;
+
+ for (i = 0; i < 16; i++)
+ {
+ char tapbuf[32];
+ const char *tok_tap;
+
+ tap_packet_cb tap_func = NULL;
+ void *tap_data = NULL;
+ const char *tap_filter = "";
+ GString *tap_error = NULL;
+
+ taps_data[i] = NULL;
+
+ snprintf(tapbuf, sizeof(tapbuf), "tap%d", i);
+ tok_tap = json_find_attr(buf, tokens, count, tapbuf);
+ if (!tok_tap)
+ break;
+
+ if (!strncmp(tok_tap, "stat:", 5))
+ {
+ stats_tree_cfg *cfg = stats_tree_get_cfg_by_abbr(tok_tap + 5);
+ stats_tree *st;
+
+ if (!cfg)
+ {
+ fprintf(stderr, "sharkd_session_process_tap() stat %s not found\n", tok_tap + 5);
+ continue;
+ }
+
+ st = stats_tree_new(cfg, NULL, tap_filter);
+
+ 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);
+
+ tap_data = st;
+
+ if (!tap_error && cfg->init)
+ cfg->init(st);
+ }
+ else if (!strncmp(tok_tap, "conv:", 5) || !strncmp(tok_tap, "endpt:", 6))
+ {
+ struct register_ct *ct = NULL;
+ const char *ct_tapname;
+ struct sharkd_conv_tap_data *ct_data;
+
+ if (!strncmp(tok_tap, "conv:", 5))
+ {
+ ct = _get_conversation_table_by_name(tok_tap + 5);
+
+ if (!ct || !(tap_func = get_conversation_packet_func(ct)))
+ {
+ fprintf(stderr, "sharkd_session_process_tap() conv %s not found\n", tok_tap + 5);
+ continue;
+ }
+ }
+ else if (!strncmp(tok_tap, "endpt:", 6))
+ {
+ ct = _get_conversation_table_by_name(tok_tap + 6);
+
+ if (!ct || !(tap_func = get_hostlist_packet_func(ct)))
+ {
+ fprintf(stderr, "sharkd_session_process_tap() endpt %s not found\n", tok_tap + 5);
+ continue;
+ }
+ }
+ else
+ {
+ fprintf(stderr, "sharkd_session_process_tap() conv/endpt(?): %s not found\n", tok_tap);
+ continue;
+ }
+
+ ct_tapname = proto_get_protocol_filter_name(get_conversation_proto_id(ct));
+
+ ct_data = (struct sharkd_conv_tap_data *) g_malloc0(sizeof(struct sharkd_conv_tap_data));
+ ct_data->type = tok_tap;
+ ct_data->hash.user_data = ct_data;
+
+ /* XXX: make configurable */
+ ct_data->resolve_name = TRUE;
+ ct_data->resolve_port = TRUE;
+
+ tap_error = register_tap_listener(ct_tapname, &ct_data->hash, tap_filter, 0, NULL, tap_func, sharkd_session_process_tap_conv_cb);
+
+ tap_data = &ct_data->hash;
+ }
+ else
+ {
+ fprintf(stderr, "sharkd_session_process_tap() %s not recognized\n", tok_tap);
+ continue;
+ }
+
+ if (tap_error)
+ {
+ /* XXX, tap data memleaks */
+ fprintf(stderr, "sharkd_session_process_tap() name=%s error=%s", tok_tap, tap_error->str);
+ g_string_free(tap_error, TRUE);
+ continue;
+ }
+
+ taps_data[i] = tap_data;
+ taps_count++;
+ }
+
+ fprintf(stderr, "sharkd_session_process_tap() count=%d\n", taps_count);
+ if (taps_count == 0)
+ return;
+
+ printf("{\"taps\":[");
+ sharkd_retap();
+ printf("null],\"err\":0}\n");
+
+ for (i = 0; i < 16; i++)
+ {
+ if (taps_data[i])
+ remove_tap_listener(taps_data[i]);
+
+ /* XXX, taps data memleaks */
+ }
+}
+
+static void
+sharkd_session_process_frame_cb_tree(proto_tree *tree, tvbuff_t **tvbs)
+{
+ proto_node *node;
+ const char *sepa = "";
+
+ printf("[");
+ for (node = tree->first_child; node; node = node->next)
+ {
+ field_info *finfo = PNODE_FINFO(node);
+
+ if (!finfo)
+ continue;
+
+ /* XXX, for now always skip hidden */
+ if (FI_GET_FLAG(finfo, FI_HIDDEN))
+ continue;
+
+ printf("%s{", sepa);
+
+ printf("\"l\":");
+ if (!finfo->rep)
+ {
+ char label_str[ITEM_LABEL_LENGTH];
+
+ label_str[0] = '\0';
+ proto_item_fill_label(finfo, label_str);
+ json_puts_string(label_str);
+ }
+ else
+ {
+ json_puts_string(finfo->rep->representation);
+ }
+
+ if (finfo->ds_tvb && tvbs && tvbs[0] != finfo->ds_tvb)
+ {
+ int idx;
+
+ for (idx = 1; tvbs[idx]; idx++)
+ {
+ if (tvbs[idx] == finfo->ds_tvb)
+ {
+ printf(",\"ds\":%d", idx);
+ break;
+ }
+ }
+ }
+
+ if (finfo->start >= 0 && finfo->length > 0)
+ printf(",\"h\":[%u,%u]", finfo->start, finfo->length);
+
+ if (finfo->appendix_start >= 0 && finfo->appendix_length > 0)
+ printf(",\"i\":[%u,%u]", finfo->appendix_start, finfo->appendix_length);
+
+ if (finfo->hfinfo && finfo->hfinfo->type == FT_PROTOCOL)
+ printf(",\"t\":\"proto\"");
+
+ if (FI_GET_FLAG(finfo, PI_SEVERITY_MASK))
+ {
+ const char *severity = NULL;
+
+ switch (FI_GET_FLAG(finfo, PI_SEVERITY_MASK))
+ {
+ case PI_COMMENT:
+ severity = "comment";
+ break;
+
+ case PI_CHAT:
+ severity = "chat";
+ break;
+
+ case PI_NOTE:
+ severity = "note";
+ break;
+
+ case PI_WARN:
+ severity = "warn";
+ break;
+
+ case PI_ERROR:
+ severity = "error";
+ break;
+ }
+ g_assert(severity != NULL);
+
+ printf(",\"s\":\"%s\"", severity);
+ }
+
+ if (((proto_tree *) node)->first_child) {
+ if (finfo->tree_type != -1)
+ printf(",\"e\":%d", finfo->tree_type);
+ printf(",\"n\":");
+ sharkd_session_process_frame_cb_tree((proto_tree *) node, tvbs);
+ }
+
+ printf("}");
+ sepa = ",";
+ }
+ printf("]");
+}
+
+static void
+sharkd_session_process_frame_cb(packet_info *pi, proto_tree *tree, struct epan_column_info *cinfo, const GSList *data_src, void *data)
+{
+ (void) pi;
+ (void) data;
+
+ printf("{");
+
+ printf("\"err\":0");
+
+ if (tree)
+ {
+ tvbuff_t **tvbs = NULL;
+
+ printf(",\"tree\":");
+
+ /* arrayize data src, to speedup searching for ds_tvb index */
+ if (data_src && data_src->next /* only needed if there are more than one data source */)
+ {
+ guint count = g_slist_length((GSList *) data_src);
+ guint i;
+
+ tvbs = (tvbuff_t **) g_malloc((count + 1) * sizeof(*tvbs));
+
+ for (i = 0; i < count; i++)
+ {
+ struct data_source *src = (struct data_source *) g_slist_nth_data((GSList *) data_src, i);
+
+ tvbs[i] = get_data_source_tvb(src);
+ }
+
+ tvbs[count] = NULL;
+ }
+
+ sharkd_session_process_frame_cb_tree(tree, tvbs);
+
+ g_free(tvbs);
+ }
+
+ if (cinfo)
+ {
+ int col;
+
+ printf(",\"col\":[");
+ for (col = 0; col < cinfo->num_cols; ++col)
+ {
+ const col_item_t *col_item = &cinfo->columns[col];
+
+ printf("%s\"%s\"", (col) ? "," : "", col_item->col_data);
+ }
+ printf("]");
+ }
+
+ if (data_src)
+ {
+ struct data_source *src = (struct data_source *)data_src->data;
+ const char *ds_sepa = NULL;
+
+ tvbuff_t *tvb;
+ guint length;
+
+ tvb = get_data_source_tvb(src);
+ length = tvb_captured_length(tvb);
+
+ printf(",\"bytes\":");
+ if (length != 0)
+ {
+ const guchar *cp = tvb_get_ptr(tvb, 0, length);
+
+ /* XXX pi.fd->flags.encoding */
+ json_print_base64(cp, length);
+ }
+ else
+ {
+ json_print_base64("", 0);
+ }
+
+ data_src = data_src->next;
+ if (data_src)
+ {
+ printf(",\"ds\":[");
+ ds_sepa = "";
+ }
+
+ while (data_src)
+ {
+ src = (struct data_source *)data_src->data;
+
+ {
+ char *src_name = get_data_source_name(src);
+
+ printf("%s{\"name\":", ds_sepa);
+ json_puts_string(src_name);
+ wmem_free(NULL, src_name);
+ }
+
+ tvb = get_data_source_tvb(src);
+ length = tvb_captured_length(tvb);
+
+ printf(",\"bytes\":");
+ if (length != 0)
+ {
+ const guchar *cp = tvb_get_ptr(tvb, 0, length);
+
+ /* XXX pi.fd->flags.encoding */
+ json_print_base64(cp, length);
+ }
+ else
+ {
+ json_print_base64("", 0);
+ }
+
+ printf("}");
+ ds_sepa = ",";
+
+ data_src = data_src->next;
+ }
+
+ /* close ds, only if was opened */
+ if (ds_sepa != NULL)
+ printf("]");
+ }
+
+ printf("}\n");
+}
+
+/**
+ * sharkd_session_process_intervals()
+ *
+ * Process intervals request - generate basic capture file statistics per requested interval.
+ *
+ * Input:
+ * (o) interval - interval time in ms, if not specified: 1000ms
+ * (o) filter - filter for generating interval request
+ *
+ * Output object with attributes:
+ * (m) intervals - array of intervals, with indexes:
+ * [0] - index of interval,
+ * [1] - number of frames during interval,
+ * [2] - number of bytes during interval.
+ *
+ * (m) last - last interval number.
+ * (m) frames - total number of frames
+ * (m) bytes - total number of bytes
+ *
+ * NOTE: If frames are not in order, there might be items with same interval index, or even negative one.
+ */
+static void
+sharkd_session_process_intervals(char *buf, const jsmntok_t *tokens, int count)
+{
+ const char *tok_interval = json_find_attr(buf, tokens, count, "interval");
+ const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
+
+ const guint8 *filter_data = NULL;
+
+ struct
+ {
+ unsigned int frames;
+ guint64 bytes;
+ } stat, stat_total;
+
+ nstime_t *start_ts = NULL;
+
+ guint32 interval_ms = 1000; /* default: one per second */
+
+ const char *sepa = "";
+ unsigned int framenum;
+ int idx;
+ int max_idx = 0;
+
+ if (tok_interval)
+ (void) ws_strtou32(tok_interval, NULL, &interval_ms);
+
+ if (tok_filter)
+ {
+ filter_data = sharkd_session_filter_data(tok_filter);
+ if (!filter_data)
+ return;
+ }
+
+ stat_total.frames = 0;
+ stat_total.bytes = 0;
+
+ stat.frames = 0;
+ stat.bytes = 0;
+
+ idx = 0;
+
+ printf("{\"intervals\":[");
+
+ for (framenum = 1; framenum <= cfile.count; framenum++)
+ {
+ frame_data *fdata = frame_data_sequence_find(cfile.frames, framenum);
+ int msec_rel;
+ int new_idx;
+
+ if (start_ts == NULL)
+ start_ts = &fdata->abs_ts;
+
+ if (filter_data && !(filter_data[framenum / 8] & (1 << (framenum % 8))))
+ continue;
+
+ /* TODO, make it 64-bit, to avoid msec overflow after 24days */
+ msec_rel = ((fdata->abs_ts.secs - start_ts->secs) * 1000 + (fdata->abs_ts.nsecs - start_ts->nsecs) / 1000000);
+ new_idx = msec_rel / interval_ms;
+
+ if (idx != new_idx)
+ {
+ if (stat.frames != 0)
+ {
+ printf("%s[%d,%u,%" G_GUINT64_FORMAT "]", sepa, idx, stat.frames, stat.bytes);
+ sepa = ",";
+ }
+
+ idx = new_idx;
+ if (idx > max_idx)
+ max_idx = idx;
+
+ stat.frames = 0;
+ stat.bytes = 0;
+ }
+
+ stat.frames += 1;
+ stat.bytes += fdata->pkt_len;
+
+ stat_total.frames += 1;
+ stat_total.bytes += fdata->pkt_len;
+ }
+
+ if (stat.frames != 0)
+ {
+ printf("%s[%d,%u,%" G_GUINT64_FORMAT "]", sepa, idx, stat.frames, stat.bytes);
+ /* sepa = ","; */
+ }
+
+ printf("],\"last\":%d,\"frames\":%u,\"bytes\":%" G_GUINT64_FORMAT "}\n", max_idx, stat_total.frames, stat_total.bytes);
+}
+
+/**
+ * sharkd_session_process_frame()
+ *
+ * Process frame request
+ *
+ * Input:
+ * (m) frame - requested frame number
+ * (o) proto - set if output frame tree
+ * (o) columns - set if output frame columns
+ * (o) bytes - set if output frame bytes
+ *
+ * Output object with attributes:
+ * (m) err - 0 if succeed
+ * (o) tree - array of frame nodes with attributes:
+ * l - label
+ * t: 'proto'
+ * s - severity
+ * e - subtree ett index
+ * n - array of subtree nodes
+ * h - two item array: (item start, item length)
+ * i - two item array: (appendix start, appendix length)
+ * p - [RESERVED] two item array: (protocol start, protocol length)
+ * ds- data src index
+ *
+ * (o) col - array of column data
+ * (o) bytes - base64 of frame bytes
+ * (o) ds - array of other data srcs
+ */
+static void
+sharkd_session_process_frame(char *buf, const jsmntok_t *tokens, int count)
+{
+ const char *tok_frame = json_find_attr(buf, tokens, count, "frame");
+ int tok_proto = (json_find_attr(buf, tokens, count, "proto") != NULL);
+ int tok_bytes = (json_find_attr(buf, tokens, count, "bytes") != NULL);
+ int tok_columns = (json_find_attr(buf, tokens, count, "columns") != NULL);
+
+ guint32 framenum;
+
+ if (!tok_frame || !ws_strtou32(tok_frame, NULL, &framenum) || framenum == 0)
+ return;
+
+ sharkd_dissect_request(framenum, &sharkd_session_process_frame_cb, tok_bytes, tok_columns, tok_proto, NULL);
+}
+
+/**
+ * sharkd_session_process_check()
+ *
+ * Process check request.
+ *
+ * Input:
+ * (o) filter - filter to be checked
+ *
+ * Output object with attributes:
+ * (m) err - always 0
+ * (o) filter - 'ok', 'warn' or error message
+ */
+static int
+sharkd_session_process_check(char *buf, const jsmntok_t *tokens, int count)
+{
+ const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
+
+ printf("{\"err\":0");
+ if (tok_filter != NULL)
+ {
+ char *err_msg = NULL;
+ dfilter_t *dfp;
+
+ if (dfilter_compile(tok_filter, &dfp, &err_msg))
+ {
+ const char *s = "ok";
+
+ if (dfilter_deprecated_tokens(dfp))
+ s = "warn";
+
+ printf(",\"filter\":\"%s\"", s);
+ dfilter_free(dfp);
+ }
+ else
+ {
+ printf(",\"filter\":");
+ json_puts_string(err_msg);
+ g_free(err_msg);
+ }
+ }
+
+ printf("}\n");
+ return 0;
+}
+
+struct sharkd_session_process_complete_pref_data
+{
+ const char *module;
+ const char *pref;
+ const char *sepa;
+};
+
+static guint
+sharkd_session_process_complete_pref_cb(module_t *module, gpointer d)
+{
+ struct sharkd_session_process_complete_pref_data *data = (struct sharkd_session_process_complete_pref_data *) d;
+
+ if (strncmp(data->pref, module->name, strlen(data->pref)) != 0)
+ return 0;
+
+ printf("%s{\"f\":\"%s\",\"d\":\"%s\"}", data->sepa, module->name, module->title);
+ data->sepa = ",";
+
+ return 0;
+}
+
+static guint
+sharkd_session_process_complete_pref_option_cb(pref_t *pref, gpointer d)
+{
+ struct sharkd_session_process_complete_pref_data *data = (struct sharkd_session_process_complete_pref_data *) d;
+ const char *pref_name = prefs_get_name(pref);
+ const char *pref_title = prefs_get_title(pref);
+
+ if (strncmp(data->pref, pref_name, strlen(data->pref)) != 0)
+ return 0;
+
+ printf("%s{\"f\":\"%s.%s\",\"d\":\"%s\"}", data->sepa, data->module, pref_name, pref_title);
+ data->sepa = ",";
+
+ return 0; /* continue */
+}
+
+/**
+ * sharkd_session_process_complete()
+ *
+ * Process complete request
+ *
+ * Input:
+ * (o) field - field to be completed
+ * (o) pref - preference to be completed
+ *
+ * Output object with attributes:
+ * (m) err - always 0
+ * (o) field - array of object with attributes:
+ * (m) f - field text
+ * (o) t - field type (FT_ number)
+ * (o) n - field name
+ * (o) pref - array of object with attributes:
+ * (m) f - pref name
+ * (o) d - pref description
+ */
+static int
+sharkd_session_process_complete(char *buf, const jsmntok_t *tokens, int count)
+{
+ const char *tok_field = json_find_attr(buf, tokens, count, "field");
+ const char *tok_pref = json_find_attr(buf, tokens, count, "pref");
+
+ printf("{\"err\":0");
+ if (tok_field != NULL && tok_field[0])
+ {
+ const size_t filter_length = strlen(tok_field);
+ const int filter_with_dot = !!strchr(tok_field, '.');
+
+ void *proto_cookie;
+ void *field_cookie;
+ int proto_id;
+ const char *sepa = "";
+
+ printf(",\"field\":[");
+
+ for (proto_id = proto_get_first_protocol(&proto_cookie); proto_id != -1; proto_id = proto_get_next_protocol(&proto_cookie))
+ {
+ protocol_t *protocol = find_protocol_by_id(proto_id);
+ const char *protocol_filter;
+ const char *protocol_name;
+ header_field_info *hfinfo;
+
+ if (!proto_is_protocol_enabled(protocol))
+ continue;
+
+ protocol_name = proto_get_protocol_long_name(protocol);
+ protocol_filter = proto_get_protocol_filter_name(proto_id);
+
+ if (strlen(protocol_filter) >= filter_length && !g_ascii_strncasecmp(tok_field, protocol_filter, filter_length))
+ {
+ printf("%s{", sepa);
+ {
+ printf("\"f\":");
+ json_puts_string(protocol_filter);
+ printf(",\"t\":%d", FT_PROTOCOL);
+ printf(",\"n\":");
+ json_puts_string(protocol_name);
+ }
+ printf("}");
+ sepa = ",";
+ }
+
+ if (!filter_with_dot)
+ continue;
+
+ for (hfinfo = proto_get_first_protocol_field(proto_id, &field_cookie); hfinfo != NULL; hfinfo = proto_get_next_protocol_field(proto_id, &field_cookie))
+ {
+ if (hfinfo->same_name_prev_id != -1) /* ignore duplicate names */
+ continue;
+
+ if (strlen(hfinfo->abbrev) >= filter_length && !g_ascii_strncasecmp(tok_field, hfinfo->abbrev, filter_length))
+ {
+ printf("%s{", sepa);
+ {
+ printf("\"f\":");
+ json_puts_string(hfinfo->abbrev);
+
+ /* XXX, skip displaying name, if there are multiple (to not confuse user) */
+ if (hfinfo->same_name_next == NULL)
+ {
+ printf(",\"t\":%d", hfinfo->type);
+ printf(",\"n\":");
+ json_puts_string(hfinfo->name);
+ }
+ }
+ printf("}");
+ sepa = ",";
+ }
+ }
+ }
+
+ printf("]");
+ }
+
+ if (tok_pref != NULL && tok_pref[0])
+ {
+ struct sharkd_session_process_complete_pref_data data;
+ char *dot_sepa;
+
+ data.module = tok_pref;
+ data.pref = tok_pref;
+ data.sepa = "";
+
+ printf(",\"pref\":[");
+
+ if ((dot_sepa = strchr(tok_pref, '.')))
+ {
+ module_t *pref_mod;
+
+ *dot_sepa = '\0'; /* XXX, C abuse: discarding-const */
+ data.pref = dot_sepa + 1;
+
+ pref_mod = prefs_find_module(data.module);
+ if (pref_mod)
+ prefs_pref_foreach(pref_mod, sharkd_session_process_complete_pref_option_cb, &data);
+
+ *dot_sepa = '.';
+ }
+ else
+ {
+ prefs_modules_foreach(sharkd_session_process_complete_pref_cb, &data);
+ }
+
+ printf("]");
+ }
+
+
+ printf("}\n");
+ return 0;
+}
+
+/**
+ * sharkd_session_process_setconf()
+ *
+ * Process setconf request
+ *
+ * Input:
+ * (m) name - preference name
+ * (m) value - preference value
+ *
+ * Output object with attributes:
+ * (m) err - error code: 0 succeed
+ */
+static void
+sharkd_session_process_setconf(char *buf, const jsmntok_t *tokens, int count)
+{
+ const char *tok_name = json_find_attr(buf, tokens, count, "name");
+ const char *tok_value = json_find_attr(buf, tokens, count, "value");
+ char pref[4096];
+
+ prefs_set_pref_e ret;
+
+ if (!tok_name || tok_name[0] == '\0' || !tok_value)
+ return;
+
+ snprintf(pref, sizeof(pref), "%s:%s", tok_name, tok_value);
+
+ ret = prefs_set_pref(pref);
+ printf("{\"err\":%d}\n", ret);
+}
+
+struct sharkd_session_process_dumpconf_data
+{
+ module_t *module;
+ const char *sepa;
+};
+
+static guint
+sharkd_session_process_dumpconf_cb(pref_t *pref, gpointer d)
+{
+ struct sharkd_session_process_dumpconf_data *data = (struct sharkd_session_process_dumpconf_data *) d;
+ const char *pref_name = prefs_get_name(pref);
+
+ printf("%s\"%s.%s\":{}", data->sepa, data->module->name, pref_name);
+
+ data->sepa = ",";
+
+ return 0; /* continue */
+}
+
+static guint
+sharkd_session_process_dumpconf_mod_cb(module_t *module, gpointer d)
+{
+ struct sharkd_session_process_dumpconf_data *data = (struct sharkd_session_process_dumpconf_data *) d;
+
+ data->module = module;
+ prefs_pref_foreach(module, sharkd_session_process_dumpconf_cb, data);
+
+ return 0;
+}
+
+/**
+ * sharkd_session_process_dumpconf()
+ *
+ * Process dumpconf request
+ *
+ * Input:
+ * (o) pref - module, or preference, NULL for all
+ *
+ * Output object with attributes:
+ * (o) prefs - object with module preferences
+ * (m) [KEY] - preference name
+ * (o) u - preference value (only for PREF_UINT)
+ * (o) ub - preference value suggested base for display (only for PREF_UINT) and if different than 10
+ * (o) b - preference value (only for PREF_BOOL) (1 true, 0 false)
+ * (o) s - preference value (only for PREF_STRING)
+ * (o) e - preference possible values (only for PREF_ENUM)
+ * (o) r - preference value (only for PREF_RANGE)
+ * (o) t - preference value (only for PREF_UAT)
+ */
+static void
+sharkd_session_process_dumpconf(char *buf, const jsmntok_t *tokens, int count)
+{
+ const char *tok_pref = json_find_attr(buf, tokens, count, "pref");
+ module_t *pref_mod;
+ char *dot_sepa;
+
+ if (!tok_pref)
+ {
+ struct sharkd_session_process_dumpconf_data data;
+
+ data.module = NULL;
+ data.sepa = "";
+
+ printf("{\"prefs\":{");
+ prefs_modules_foreach(sharkd_session_process_dumpconf_mod_cb, &data);
+ printf("}}\n");
+ return;
+ }
+
+ if ((dot_sepa = strchr(tok_pref, '.')))
+ {
+ pref_t *pref = NULL;
+
+ *dot_sepa = '\0'; /* XXX, C abuse: discarding-const */
+ pref_mod = prefs_find_module(tok_pref);
+ if (pref_mod)
+ pref = prefs_find_preference(pref_mod, dot_sepa + 1);
+ *dot_sepa = '.';
+
+ if (pref)
+ {
+ struct sharkd_session_process_dumpconf_data data;
+
+ data.module = pref_mod;
+ data.sepa = "";
+
+ printf("{\"prefs\":{");
+ sharkd_session_process_dumpconf_cb(pref, &data);
+ printf("}}\n");
+ }
+
+ return;
+ }
+
+ pref_mod = prefs_find_module(tok_pref);
+ if (pref_mod)
+ {
+ struct sharkd_session_process_dumpconf_data data;
+
+ data.module = pref_mod;
+ data.sepa = "";
+
+ printf("{\"prefs\":{");
+ prefs_pref_foreach(pref_mod, sharkd_session_process_dumpconf_cb, &data);
+ printf("}}\n");
+ }
+}
+
+static void
+sharkd_session_process(char *buf, const jsmntok_t *tokens, int count)
+{
+ int i;
+
+ /* sanity check, and split strings */
+ if (count < 1 || tokens[0].type != JSMN_OBJECT)
+ {
+ fprintf(stderr, "sanity check(1): [0] not object\n");
+ return;
+ }
+
+ /* don't need [0] token */
+ tokens++;
+ count--;
+
+ if (count & 1)
+ {
+ fprintf(stderr, "sanity check(2): %d not even\n", count);
+ return;
+ }
+
+ for (i = 0; i < count; i += 2)
+ {
+ if (tokens[i].type != JSMN_STRING)
+ {
+ fprintf(stderr, "sanity check(3): [%d] not string\n", i);
+ return;
+ }
+
+ buf[tokens[i + 0].end] = '\0';
+ buf[tokens[i + 1].end] = '\0';
+
+ json_unescape_str(&buf[tokens[i + 0].start]);
+ json_unescape_str(&buf[tokens[i + 1].start]);
+ }
+
+ {
+ const char *tok_req = json_find_attr(buf, tokens, count, "req");
+
+ if (!tok_req)
+ {
+ fprintf(stderr, "sanity check(4): no \"req\"!\n");
+ return;
+ }
+
+ if (!strcmp(tok_req, "load"))
+ sharkd_session_process_load(buf, tokens, count);
+ else if (!strcmp(tok_req, "status"))
+ sharkd_session_process_status();
+ else if (!strcmp(tok_req, "analyse"))
+ sharkd_session_process_analyse();
+ else if (!strcmp(tok_req, "info"))
+ sharkd_session_process_info();
+ else if (!strcmp(tok_req, "check"))
+ sharkd_session_process_check(buf, tokens, count);
+ else if (!strcmp(tok_req, "complete"))
+ sharkd_session_process_complete(buf, tokens, count);
+ else if (!strcmp(tok_req, "frames"))
+ sharkd_session_process_frames(buf, tokens, count);
+ else if (!strcmp(tok_req, "tap"))
+ sharkd_session_process_tap(buf, tokens, count);
+ else if (!strcmp(tok_req, "intervals"))
+ sharkd_session_process_intervals(buf, tokens, count);
+ else if (!strcmp(tok_req, "frame"))
+ sharkd_session_process_frame(buf, tokens, count);
+ else if (!strcmp(tok_req, "setconf"))
+ sharkd_session_process_setconf(buf, tokens, count);
+ else if (!strcmp(tok_req, "dumpconf"))
+ sharkd_session_process_dumpconf(buf, tokens, count);
+ else if (!strcmp(tok_req, "bye"))
+ _Exit(0);
+ else
+ fprintf(stderr, "::: req = %s\n", tok_req);
+
+ printf("\n");
+ }
+}
+
+int
+sharkd_session_main(void)
+{
+ char buf[16 * 1024];
+ jsmntok_t *tokens = NULL;
+ int tokens_max = -1;
+
+ fprintf(stderr, "Hello in child!\n");
+ setlinebuf(stdout);
+
+ while (fgets(buf, sizeof(buf), stdin))
+ {
+ /* every command is line seperated JSON */
+ int ret;
+
+ ret = wsjsmn_parse(buf, NULL, 0);
+ if (ret < 0)
+ {
+ fprintf(stderr, "invalid JSON -> closing\n");
+ return 1;
+ }
+
+ /* fprintf(stderr, "JSON: %d tokens\n", ret); */
+ ret += 1;
+
+ if (tokens == NULL || tokens_max < ret)
+ {
+ tokens_max = ret;
+ tokens = (jsmntok_t *) g_realloc(tokens, sizeof(jsmntok_t) * tokens_max);
+ }
+
+ memset(tokens, 0, ret * sizeof(jsmntok_t));
+
+ ret = wsjsmn_parse(buf, tokens, ret);
+ if (ret < 0)
+ {
+ fprintf(stderr, "invalid JSON(2) -> closing\n");
+ return 2;
+ }
+
+ sharkd_session_process(buf, tokens, ret);
+ }
+
+ g_free(tokens);
+
+ return 0;
+}
+
+/*
+ * Editor modelines - http://www.wireshark.org/tools/modelines.html
+ *
+ * Local variables:
+ * c-basic-offset: 8
+ * tab-width: 8
+ * indent-tabs-mode: t
+ * End:
+ *
+ * vi: set shiftwidth=8 tabstop=8 noexpandtab:
+ * :indentSize=8:tabSize=8:noTabs=false:
+ */
diff --git a/wsutil/wsjsmn.c b/wsutil/wsjsmn.c
index e18bd45a4e..949b983efc 100644
--- a/wsutil/wsjsmn.c
+++ b/wsutil/wsjsmn.c
@@ -23,6 +23,8 @@
*/
#include "wsjsmn.h"
+
+#include <string.h>
#include <wsutil/jsmn.h>
#include "log.h"
@@ -66,6 +68,14 @@ gboolean jsmn_is_json(const guint8* buf, const size_t len)
return ret;
}
+int wsjsmn_parse(const char *buf, jsmntok_t *tokens, unsigned int max_tokens)
+{
+ jsmn_parser p;
+
+ jsmn_init(&p);
+ return jsmn_parse(&p, buf, strlen(buf), tokens, max_tokens);
+}
+
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
diff --git a/wsutil/wsjsmn.h b/wsutil/wsjsmn.h
index 84e63ebf3c..4b4d9054db 100644
--- a/wsutil/wsjsmn.h
+++ b/wsutil/wsjsmn.h
@@ -28,6 +28,8 @@
#include "ws_symbol_export.h"
#include <glib.h>
+#include "jsmn.h"
+
#ifdef __cplusplus
extern "C" {
#endif
@@ -37,6 +39,8 @@ extern "C" {
*/
WS_DLL_PUBLIC gboolean jsmn_is_json(const guint8* buf, const size_t len);
+WS_DLL_PUBLIC int wsjsmn_parse(const char *buf, jsmntok_t *tokens, unsigned int max_tokens);
+
#ifdef __cplusplus
}
#endif