LATER... ei_kerberos_kdc_session_key ...
[wireshark-sm.git] / ui / stratoshark / stratoshark_main.cpp
blobc378f72d458b50c4a71458890473b4007afb9902
1 /* stratoshark_main.cpp
3 * Stratoshark - System call and event log analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * SPDX-License-Identifier: GPL-2.0-or-later
8 */
10 #include <config.h>
11 #define WS_LOG_DOMAIN LOG_DOMAIN_MAIN
13 #include <locale.h>
15 #ifdef _WIN32
16 #include <windows.h>
17 #include <tchar.h>
18 #include <wchar.h>
19 #include <shellapi.h>
20 #include <wsutil/console_win32.h>
21 #endif
23 #include <ws_exit_codes.h>
24 #include <wsutil/clopts_common.h>
25 #include <wsutil/cmdarg_err.h>
26 #include <ui/urls.h>
27 #include <wsutil/time_util.h>
28 #include <wsutil/filesystem.h>
29 #include <wsutil/privileges.h>
30 #include <wsutil/socket.h>
31 #include <wsutil/wslog.h>
32 #ifdef HAVE_PLUGINS
33 #include <wsutil/plugins.h>
34 #endif
35 #include <wsutil/please_report_bug.h>
36 #include <wsutil/unicode-utils.h>
37 #include <wsutil/version_info.h>
39 #include <epan/addr_resolv.h>
40 #include <epan/ex-opt.h>
41 #include <epan/tap.h>
42 #include <epan/stat_tap_ui.h>
43 #include <epan/column.h>
44 #include <epan/disabled_protos.h>
45 #include <epan/prefs.h>
47 #ifdef HAVE_KERBEROS
48 #include <epan/packet.h>
49 #include <epan/asn1.h>
50 #include <epan/dissectors/packet-kerberos.h>
51 #endif
53 #include <wsutil/codecs.h>
55 #include <extcap.h>
57 /* general (not Qt specific) */
58 #include "file.h"
59 #include "epan/color_filters.h"
61 #include "epan/rtd_table.h"
62 #include "epan/srt_table.h"
64 #include "ui/alert_box.h"
65 #include "ui/iface_lists.h"
66 #include "ui/language.h"
67 #include "ui/persfilepath_opt.h"
68 #include "ui/recent.h"
69 #include "ui/simple_dialog.h"
70 #include "ui/util.h"
71 #include "ui/dissect_opts.h"
72 #include "ui/commandline.h"
73 #include "ui/capture_ui_utils.h"
74 #include "ui/preference_utils.h"
75 #include "ui/software_update.h"
76 #include "ui/taps.h"
78 #include "ui/qt/conversation_dialog.h"
79 #include "ui/qt/utils/color_utils.h"
80 #include "ui/qt/coloring_rules_dialog.h"
81 #include "ui/qt/endpoint_dialog.h"
82 #include "ui/qt/glib_mainloop_on_qeventloop.h"
83 #include "ui/stratoshark/stratoshark_main_window.h"
84 #include "ui/qt/simple_dialog.h"
85 #include "ui/qt/simple_statistics_dialog.h"
86 #include <ui/qt/widgets/splash_overlay.h>
87 #include "ui/stratoshark/stratoshark_application.h"
89 #include "capture/capture-pcap-util.h"
91 #include <QMessageBox>
92 #include <QScreen>
94 #ifdef _WIN32
95 # include "capture/capture-wpcap.h"
96 # include <wsutil/file_util.h>
97 #endif /* _WIN32 */
99 #ifdef HAVE_AIRPCAP
100 # include <capture/airpcap.h>
101 # include <capture/airpcap_loader.h>
102 //# include "airpcap_dlg.h"
103 //# include "airpcap_gui_utils.h"
104 #endif
106 #include "epan/crypt/dot11decrypt_ws.h"
108 /* Handle the addition of View menu items without request */
109 #if defined(Q_OS_MAC)
110 #include <ui/macosx/cocoa_bridge.h>
111 #endif
113 #include <ui/qt/utils/qt_ui_utils.h>
115 //#define DEBUG_STARTUP_TIME 1
117 /* update the main window */
118 void main_window_update(void)
120 StratosharkApplication::processEvents();
123 void exit_application(int status) {
124 if (ssApp) {
125 ssApp->quit();
127 exit(status);
131 * Report an error in command-line arguments.
133 * On Windows, Stratoshark is built for the Windows subsystem, and runs
134 * without a console, so we create a console on Windows to receive the
135 * output.
137 * See create_console(), in ui/win32/console_win32.c, for an example
138 * of code to check whether we need to create a console.
140 * On UN*Xes:
142 * If Stratoshark is run from the command line, its output either goes
143 * to the terminal or to wherever the standard error was redirected.
145 * If Stratoshark is run by executing it as a remote command, e.g. with
146 * ssh, its output either goes to whatever socket was set up for the
147 * remote command's standard error or to wherever the standard error
148 * was redirected.
150 * If Stratoshark was run from the GUI, e.g. by double-clicking on its
151 * icon or on a file that it opens, there are no guarantees as to
152 * where the standard error went. It could be going to /dev/null
153 * (current macOS), or to a socket to systemd for the journal, or
154 * to a log file in the user's home directory, or to the "console
155 * device" ("workstation console"), or....
157 * Part of determining that, at least for locally-run Stratoshark,
158 * is to try to open /dev/tty to determine whether the process
159 * has a controlling terminal. (It fails, at a minimum, for
160 * Stratoshark launched from the GUI under macOS, Ubuntu with GNOME,
161 * and Ubuntu with KDE; in all cases, an attempt to open /dev/tty
162 * fails with ENXIO.) If it does have a controlling terminal,
163 * write to the standard error, otherwise assume that the standard
164 * error might not go anywhere that the user will be able to see.
165 * That doesn't handle the "run by ssh" case, however; that will
166 * not have a controlling terminal. (This means running it by
167 * remote execution, not by remote login.) Perhaps there's an
168 * environment variable to check there.
170 // xxx copied from ../gtk/main.c
171 static void
172 stratoshark_cmdarg_err(const char *fmt, va_list ap)
174 #ifdef _WIN32
175 create_console();
176 #endif
177 fprintf(stderr, "stratoshark: ");
178 vfprintf(stderr, fmt, ap);
179 fprintf(stderr, "\n");
183 * Report additional information for an error in command-line arguments.
184 * Creates a console on Windows.
186 // xxx copied from ../gtk/main.c
187 static void
188 stratoshark_cmdarg_err_cont(const char *fmt, va_list ap)
190 #ifdef _WIN32
191 create_console();
192 #endif
193 vfprintf(stderr, fmt, ap);
194 fprintf(stderr, "\n");
197 void
198 gather_wireshark_qt_compiled_info(feature_list l)
200 #ifdef QT_VERSION
201 with_feature(l, "Qt %s", QT_VERSION_STR);
202 #else
203 with_feature(l, "Qt (version unknown)");
204 #endif
205 gather_caplibs_compile_info(l);
206 epan_gather_compile_info(l);
207 #ifdef QT_MULTIMEDIA_LIB
208 with_feature(l, "QtMultimedia");
209 #else
210 without_feature(l, "QtMultimedia");
211 #endif
213 const char *update_info = software_update_info();
214 if (update_info) {
215 with_feature(l, "automatic updates using %s", update_info);
216 } else {
217 without_feature(l, "automatic updates");
219 #ifdef _WIN32
220 #ifdef HAVE_AIRPCAP
221 gather_airpcap_compile_info(l);
222 #else
223 without_feature(l, "AirPcap");
224 #endif
225 #endif /* _WIN32 */
227 #ifdef HAVE_MINIZIP
228 with_feature(l, "Minizip");
229 #else
230 without_feature(l, "Minizip");
231 #endif
233 #ifdef HAVE_SINSP
234 with_feature(l, "falcosecurity-libs sinsp/scap %d.%d.%d", SINSP_VERSION_MAJOR, SINSP_VERSION_MINOR, SINSP_VERSION_MICRO);
235 #else
236 without_feature(l, "falcosecurity-libs sinsp/scap");
237 #endif
240 void
241 gather_wireshark_runtime_info(feature_list l)
243 with_feature(l, "Qt %s", qVersion());
244 #ifdef HAVE_LIBPCAP
245 gather_caplibs_runtime_info(l);
246 #endif
247 epan_gather_runtime_info(l);
249 #ifdef HAVE_AIRPCAP
250 gather_airpcap_runtime_info(l);
251 #endif
253 if (mainApp) {
254 // Display information
255 const char *display_mode = ColorUtils::themeIsDark() ? "dark" : "light";
256 with_feature(l, "%s display mode", display_mode);
258 int hidpi_count = 0;
259 foreach (QScreen *screen, mainApp->screens()) {
260 if (screen->devicePixelRatio() > 1.0) {
261 hidpi_count++;
264 if (hidpi_count == mainApp->screens().count()) {
265 with_feature(l, "HiDPI");
266 } else if (hidpi_count) {
267 with_feature(l, "mixed DPI");
268 } else {
269 without_feature(l, "HiDPI");
274 static void
275 qt_log_message_handler(QtMsgType type, const QMessageLogContext &, const QString &msg)
277 enum ws_log_level log_level = LOG_LEVEL_DEBUG;
279 switch (type) {
280 case QtInfoMsg:
281 log_level = LOG_LEVEL_INFO;
282 break;
283 // We want qDebug() messages to show up at our default log level.
284 case QtDebugMsg:
285 case QtWarningMsg:
286 log_level = LOG_LEVEL_WARNING;
287 break;
288 case QtCriticalMsg:
289 log_level = LOG_LEVEL_CRITICAL;
290 break;
291 case QtFatalMsg:
292 log_level = LOG_LEVEL_ERROR;
293 break;
294 default:
295 break;
297 ws_log(LOG_DOMAIN_QTUI, log_level, "%s", qUtf8Printable(msg));
300 #ifdef HAVE_LIBPCAP
301 /* Check if there's something important to tell the user during startup.
302 * We want to do this *after* showing the main window so that any windows
303 * we pop up will be above the main window.
305 static void
306 check_and_warn_user_startup()
308 char *cur_user, *cur_group;
310 /* Tell the user not to run as root. */
311 if (running_with_special_privs() && recent.privs_warn_if_elevated) {
312 cur_user = get_cur_username();
313 cur_group = get_cur_groupname();
314 simple_message_box(ESD_TYPE_WARN, &recent.privs_warn_if_elevated,
315 "Running as user \"%s\" and group \"%s\".\n"
316 "This could be dangerous.\n\n"
317 "If you're running Stratoshark this way in order to perform live capture, "
318 "you may want to be aware that there is a better way documented at\n"
319 WS_WIKI_URL("CaptureSetup/CapturePrivileges"), cur_user, cur_group);
320 g_free(cur_user);
321 g_free(cur_group);
324 #endif
326 #ifdef _WIN32
327 // Try to avoid library search path collisions. QCoreApplication will
328 // search QT_INSTALL_PREFIX/plugins for platform DLLs before searching
329 // the application directory. If
331 // - You have Qt version 5.x.y installed in the default location
332 // (C:\Qt\5.x) on your machine.
334 // and
336 // - You install Stratoshark that was built on a machine with Qt version
337 // 5.x.z installed in the default location.
339 // Qt5Core.dll will load qwindows.dll from your local C:\Qt\5.x\...\plugins
340 // directory. This may not be compatible with qwindows.dll from that
341 // same path on the build machine. At any rate, loading DLLs from paths
342 // you don't control is ill-advised. We work around this by removing every
343 // path except our application directory.
345 static inline void
346 win32_reset_library_path(void)
348 QString app_path = QDir(get_progfile_dir()).path();
349 foreach (QString path, QCoreApplication::libraryPaths()) {
350 QCoreApplication::removeLibraryPath(path);
352 QCoreApplication::addLibraryPath(app_path);
354 #endif
356 #ifdef Q_OS_MAC
357 // Try to work around
359 // https://gitlab.com/wireshark/wireshark/-/issues/17075
361 // aka
363 // https://bugreports.qt.io/browse/QTBUG-87014
365 // The fix at
367 // https://codereview.qt-project.org/c/qt/qtbase/+/322228/3/src/plugins/platforms/cocoa/qnsview_drawing.mm
369 // enables layer backing if we're running on Big Sur OR we're running on
370 // Catalina AND we were built with the Catalina SDK. Enable layer backing
371 // here by setting QT_MAC_WANTS_LAYER=1, but only if we're running on Big
372 // Sur and our version of Qt doesn't have a fix for QTBUG-87014.
373 #include <QOperatingSystemVersion>
374 static inline void
375 macos_enable_layer_backing(void)
377 // At the time of this writing, the QTBUG-87014 for layerEnabledByMacOS is...
379 // ...in https://github.com/qt/qtbase/blob/5.15/src/plugins/platforms/cocoa/qnsview_drawing.mm
380 // ...not in https://github.com/qt/qtbase/blob/5.15.2/src/plugins/platforms/cocoa/qnsview_drawing.mm
381 // ...not in https://github.com/qt/qtbase/blob/6.0/src/plugins/platforms/cocoa/qnsview_drawing.mm
382 // ...not in https://github.com/qt/qtbase/blob/6.0.0/src/plugins/platforms/cocoa/qnsview_drawing.mm
384 // We'll assume that it will be fixed in 5.15.3, 6.0.1, and >= 6.1
385 // Note that we only ship LTS versions of Qt with our macOS packages.
386 // Feel free to add other versions if needed.
387 #if \
388 ((QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) && QT_VERSION < QT_VERSION_CHECK(5, 15, 3)) \
389 || (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) && QT_VERSION < QT_VERSION_CHECK(6, 0, 1)) \
391 QOperatingSystemVersion os_ver = QOperatingSystemVersion::current();
392 int major_ver = os_ver.majorVersion();
393 int minor_ver = os_ver.minorVersion();
394 if ( (major_ver == 10 && minor_ver >= 16) || major_ver >= 11 ) {
395 if (qgetenv("QT_MAC_WANTS_LAYER").isEmpty()) {
396 qputenv("QT_MAC_WANTS_LAYER", "1");
399 #endif
401 #endif
403 #ifdef HAVE_LIBPCAP
404 static GList *
405 capture_opts_get_interface_list(int *err _U_, char **err_str _U_)
407 // Stratoshark only wants the IF_EXTCAP interfaces, so there's no point
408 // in spawning dumpcap to retrieve the other types of interfaces.
409 #if 0
410 if (mainApp) {
411 GList *if_list = mainApp->getInterfaceList();
412 if (if_list == NULL) {
413 if_list = capture_interface_list(err, err_str, main_window_update);
414 mainApp->setInterfaceList(if_list);
416 return if_list;
418 return capture_interface_list(err, err_str, main_window_update);
419 #endif
420 return append_extcap_interface_list(NULL);
422 #endif
424 /* And now our feature presentation... [ fade to music ] */
425 int main(int argc, char *qt_argv[])
427 StratosharkMainWindow *main_w;
429 #ifdef _WIN32
430 LPWSTR *wc_argv;
431 int wc_argc;
432 #endif
433 int ret_val = EXIT_SUCCESS;
434 char **argv = qt_argv;
436 char *rf_path;
437 int rf_open_errno;
438 #ifdef HAVE_LIBPCAP
439 char *err_str, *err_str_secondary;
440 #else
441 #ifdef _WIN32
442 #ifdef HAVE_AIRPCAP
443 char *err_str;
444 #endif
445 #endif
446 #endif
447 char *err_msg = NULL;
448 df_error_t *df_err = NULL;
450 QString dfilter, read_filter;
451 #ifdef HAVE_LIBPCAP
452 int caps_queries = 0;
453 #endif
454 /* Start time in microseconds */
455 uint64_t start_time = g_get_monotonic_time();
457 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
459 * See:
461 * issue #16908;
463 * https://doc.qt.io/qt-5/qvector.html#maximum-size-and-out-of-memory-conditions
465 * https://forum.qt.io/topic/114950/qvector-realloc-throwing-sigsegv-when-very-large-surface3d-is-rendered
467 * for why we're doing this; the widget we use for the packet list
468 * uses QVector, so those limitations apply to it.
470 * Apparently, this will be fixed in Qt 6:
472 * https://github.com/qt/qtbase/commit/215ca735341b9487826023a7983382851ce8bf26
474 * https://github.com/qt/qtbase/commit/2a6cdec718934ca2cc7f6f9c616ebe62f6912123#diff-724f419b0bb0487c2629bb16cf534c4b268ddcee89b5177189b607f940cfd83dR192
476 * Hopefully QList won't cause any performance hits relative to
477 * QVector.
479 * We pick 53 million records as a value that should avoid the problem;
480 * see the Wireshark issue for why that value was chosen.
482 cf_set_max_records(53000000);
483 #endif
485 #ifdef Q_OS_MAC
486 macos_enable_layer_backing();
487 #endif
489 cmdarg_err_init(stratoshark_cmdarg_err, stratoshark_cmdarg_err_cont);
491 /* Initialize log handler early so we can have proper logging during startup. */
492 ws_log_init("stratoshark", vcmdarg_err);
493 /* For backward compatibility with GLib logging and Wireshark 3.4. */
494 ws_log_console_writer_set_use_stdout(true);
496 qInstallMessageHandler(qt_log_message_handler);
498 #ifdef _WIN32
499 restore_pipes();
500 #endif
502 #ifdef DEBUG_STARTUP_TIME
503 prefs.gui_console_open = console_open_always;
504 #endif /* DEBUG_STARTUP_TIME */
506 #if defined(Q_OS_MAC)
507 /* Disable automatic addition of tab menu entries in view menu */
508 CocoaBridge::cleanOSGeneratedMenuItems();
509 #endif
512 * Set the C-language locale to the native environment and set the
513 * code page to UTF-8 on Windows.
515 #ifdef _WIN32
516 setlocale(LC_ALL, ".UTF-8");
517 #else
518 setlocale(LC_ALL, "");
519 #endif
521 ws_tzset();
523 #ifdef _WIN32
525 // On Windows, QCoreApplication has its own WinMain(), which gets the
526 // command line using GetCommandLineW(), breaks it into individual
527 // arguments using CommandLineToArgvW(), and then "helpfully"
528 // converts those UTF-16LE arguments into strings in the local code
529 // page.
531 // We don't want that, because not all file names can be represented
532 // in the local code page, so we do the same, but we convert the
533 // strings into UTF-8.
535 wc_argv = CommandLineToArgvW(GetCommandLineW(), &wc_argc);
536 if (wc_argv) {
537 argc = wc_argc;
538 argv = arg_list_utf_16to8(wc_argc, wc_argv);
539 LocalFree(wc_argv);
540 } /* XXX else bail because something is horribly, horribly wrong? */
542 create_app_running_mutex();
543 #endif /* _WIN32 */
545 /* Early logging command-line initialization. */
546 ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
547 ws_noisy("Finished log init and parsing command line log arguments");
550 * Get credential information for later use, and drop privileges
551 * before doing anything else.
552 * Let the user know if anything happened.
554 init_process_policies();
555 relinquish_special_privs_perm();
558 * Attempt to get the pathname of the directory containing the
559 * executable file.
561 /* configuration_init_error = */ configuration_init(argv[0], "Stratoshark");
562 /* ws_log(NULL, LOG_LEVEL_DEBUG, "progfile_dir: %s", get_progfile_dir()); */
564 #ifdef _WIN32
565 ws_init_dll_search_path();
566 /* Load wpcap if possible. Do this before collecting the run-time version information */
567 load_wpcap();
569 #ifdef HAVE_AIRPCAP
570 /* Load the airpcap.dll. This must also be done before collecting
571 * run-time version information. */
572 load_airpcap();
573 #if 0
574 airpcap_dll_ret_val = load_airpcap();
576 switch (airpcap_dll_ret_val) {
577 case AIRPCAP_DLL_OK:
578 /* load the airpcap interfaces */
579 g_airpcap_if_list = get_airpcap_interface_list(&err, &err_str);
581 if (g_airpcap_if_list == NULL || g_list_length(g_airpcap_if_list) == 0) {
582 if (err == CANT_GET_AIRPCAP_INTERFACE_LIST && err_str != NULL) {
583 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", "Failed to open Airpcap Adapters.");
584 g_free(err_str);
586 airpcap_if_active = NULL;
588 } else {
590 /* select the first as default (THIS SHOULD BE CHANGED) */
591 airpcap_if_active = airpcap_get_default_if(airpcap_if_list);
593 break;
595 * XXX - Maybe we need to warn the user if one of the following happens???
597 case AIRPCAP_DLL_OLD:
598 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s","AIRPCAP_DLL_OLD\n");
599 break;
601 case AIRPCAP_DLL_ERROR:
602 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s","AIRPCAP_DLL_ERROR\n");
603 break;
605 case AIRPCAP_DLL_NOT_FOUND:
606 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s","AIRPCAP_DDL_NOT_FOUND\n");
607 break;
609 #endif
610 #endif /* HAVE_AIRPCAP */
611 #endif /* _WIN32 */
613 /* Get the compile-time version information string */
614 ws_init_version_info("Stratoshark", gather_wireshark_qt_compiled_info,
615 gather_wireshark_runtime_info);
617 init_report_alert_box("Stratoshark");
619 /* Create the user profiles directory */
620 if (create_profiles_dir(&rf_path) == -1) {
621 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
622 "Could not create profiles directory\n\"%s\": %s.",
623 rf_path, g_strerror(errno));
624 g_free (rf_path);
627 profile_store_persconffiles(true);
628 recent_init();
630 /* Read the profile independent recent file. We have to do this here so we can */
631 /* set the profile before it can be set from the command line parameter */
632 if (!recent_read_static(&rf_path, &rf_open_errno)) {
633 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
634 "Could not open common recent file\n\"%s\": %s.",
635 rf_path, g_strerror(rf_open_errno));
636 g_free(rf_path);
639 commandline_early_options(argc, argv);
641 #ifdef _WIN32
642 win32_reset_library_path();
643 #endif
645 // Handle DPI scaling on Windows. This causes problems in at least
646 // one case on X11 and we don't yet support Android.
647 // We do the equivalent on macOS by setting NSHighResolutionCapable
648 // in Info.plist.
649 // Note that this enables Windows 8.1-style Per-monitor DPI
650 // awareness but not Windows 10-style Per-monitor v2 awareness.
651 // https://doc.qt.io/qt-5/scalability.html
652 // https://doc.qt.io/qt-5/highdpi.html
653 // https://bugreports.qt.io/browse/QTBUG-53022 - The device pixel ratio is pretty much bogus on Windows.
654 // https://bugreports.qt.io/browse/QTBUG-55510 - Windows have wrong size
655 #if defined(Q_OS_WIN)
656 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
657 #endif
659 // This function must be called before creating the application object.
660 // Qt::HighDpiScaleFactorRoundingPolicy::PassThrough is the default in Qt6,
661 // so this doesn't have any effect (Round is the default in 5.14 & 5.15)
662 #if defined(Q_OS_WIN)
663 QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
664 #endif
666 /* Create The Stratoshark app */
667 StratosharkApplication ss_app(argc, qt_argv);
669 /* initialize the funnel mini-api */
670 // xxx qtshark
671 //initialize_funnel_ops();
673 Dot11DecryptInitContext(&dot11decrypt_ctx);
675 QString cf_name;
676 unsigned int in_file_type = WTAP_TYPE_AUTO;
678 err_msg = ws_init_sockets();
679 if (err_msg != NULL)
681 cmdarg_err("%s", err_msg);
682 g_free(err_msg);
683 cmdarg_err_cont("%s", please_report_bug());
684 ret_val = WS_EXIT_INIT_FAILED;
685 goto clean_exit;
688 /* Read the profile dependent (static part) of the recent file. */
689 /* Only the static part of it will be read, as we don't have the gui now to fill the */
690 /* recent lists which is done in the dynamic part. */
691 /* We have to do this already here, so command line parameters can overwrite these values. */
692 if (!recent_read_profile_static(&rf_path, &rf_open_errno)) {
693 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
694 "Could not open recent file\n\"%s\": %s.",
695 rf_path, g_strerror(rf_open_errno));
696 g_free(rf_path);
698 ssApp->applyCustomColorsFromRecent();
700 // Initialize our language
701 read_language_prefs();
702 ssApp->loadLanguage(language);
704 /* ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_DEBUG, "Translator %s", language); */
706 // Init the main window (and splash)
707 main_w = new(StratosharkMainWindow);
708 main_w->show();
709 // Setup GLib mainloop on Qt event loop to enable GLib and GIO watches
710 GLibMainloopOnQEventLoop::setup(main_w);
711 // We may not need a queued connection here but it would seem to make sense
712 // to force the issue.
713 main_w->connect(&ss_app, SIGNAL(openCaptureFile(QString,QString,unsigned int)),
714 main_w, SLOT(openCaptureFile(QString,QString,unsigned int)));
715 main_w->connect(&ss_app, &StratosharkApplication::openCaptureOptions,
716 main_w, &StratosharkMainWindow::showCaptureOptionsDialog);
719 * If we have a saved "last directory in which a file was opened"
720 * in the recent file, set it as the one for the app.
722 * (do this after the path settings are processed)
724 if (recent.gui_fileopen_remembered_dir &&
725 test_for_directory(recent.gui_fileopen_remembered_dir) == EISDIR) {
726 set_last_open_dir(recent.gui_fileopen_remembered_dir);
729 #ifdef DEBUG_STARTUP_TIME
730 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "set_console_log_handler, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
731 #endif
733 #ifdef HAVE_LIBPCAP
734 /* Set the initial values in the capture options. This might be overwritten
735 by preference settings and then again by the command line parameters. */
736 capture_opts_init(&global_capture_opts, capture_opts_get_interface_list);
737 #endif
740 * Libwiretap must be initialized before libwireshark is, so that
741 * dissection-time handlers for file-type-dependent blocks can
742 * register using the file type/subtype value for the file type.
744 wtap_init(true);
746 splash_update(RA_DISSECTORS, NULL, NULL);
747 #ifdef DEBUG_STARTUP_TIME
748 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling epan init, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
749 #endif
750 /* Register all dissectors; we must do this before checking for the
751 "-G" flag, as the "-G" flag dumps information registered by the
752 dissectors, and we must do it before we read the preferences, in
753 case any dissectors register preferences. */
754 if (!epan_init(splash_update, NULL, true)) {
755 SimpleDialog::displayQueuedMessages(main_w);
756 ret_val = WS_EXIT_INIT_FAILED;
757 goto clean_exit;
759 #ifdef DEBUG_STARTUP_TIME
760 /* epan_init resets the preferences */
761 prefs.gui_console_open = console_open_always;
762 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "epan done, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
763 #endif
765 /* Register all audio codecs. */
766 codecs_init();
768 // Read the dynamic part of the recent file. This determines whether or
769 // not the recent list appears in the main window so the earlier we can
770 // call this the better.
771 if (!recent_read_dynamic(&rf_path, &rf_open_errno)) {
772 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
773 "Could not open recent file\n\"%s\": %s.",
774 rf_path, g_strerror(rf_open_errno));
775 g_free(rf_path);
777 ssApp->refreshRecentCaptures();
779 splash_update(RA_LISTENERS, NULL, NULL);
780 #ifdef DEBUG_STARTUP_TIME
781 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Register all tap listeners, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
782 #endif
783 /* Register all tap listeners; we do this before we parse the arguments,
784 as the "-z" argument can specify a registered tap. */
786 register_all_tap_listeners(tap_reg_listener);
788 conversation_table_set_gui_info(init_conversation_table);
789 endpoint_table_set_gui_info(init_endpoint_table);
790 // srt_table_iterate_tables(register_service_response_tables, NULL);
791 // rtd_table_iterate_tables(register_response_time_delay_tables, NULL);
792 stat_tap_iterate_tables(register_simple_stat_tables, NULL);
794 if (ex_opt_count("read_format") > 0) {
795 in_file_type = open_info_name_to_type(ex_opt_get_next("read_format"));
798 splash_update(RA_PREFERENCES, NULL, NULL);
799 #ifdef DEBUG_STARTUP_TIME
800 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling module preferences, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
801 #endif
803 /* Read the preferences, but don't apply them yet. */
804 global_commandline_info.prefs_p = ss_app.readConfigurationFiles(false);
806 /* Now let's see if any of preferences were overridden at the command
807 * line, and store them. We have to do this before applying the
808 * preferences to the capture options.
810 commandline_override_prefs(argc, argv, true);
812 /* Register the extcap preferences. We do this after seeing if the
813 * capture_no_extcap preference is set in the configuration file
814 * or command line. This will re-read the extcap specific preferences.
816 #ifdef DEBUG_STARTUP_TIME
817 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling extcap_register_preferences, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
818 #endif
819 splash_update(RA_EXTCAP, NULL, NULL);
820 extcap_register_preferences();
822 /* Apply the extcap command line options now that the extcap preferences
823 * are loaded.
825 commandline_options_apply_extcap();
827 /* Some of the preferences affect the capture options. Apply those
828 * before getting the other command line arguments, which can also
829 * affect the capture options. The command line arguments should be
830 * applied last to take precedence (at least until the user saves
831 * preferences, or switches profiles.)
833 prefs_to_capture_opts();
835 /* Now get our remaining args */
836 commandline_other_options(argc, argv, true);
838 /* Convert some command-line parameters to QStrings */
839 if (global_commandline_info.cf_name != NULL)
840 cf_name = QString(global_commandline_info.cf_name);
841 if (global_commandline_info.rfilter != NULL)
842 read_filter = QString(global_commandline_info.rfilter);
843 if (global_commandline_info.dfilter != NULL)
844 dfilter = QString(global_commandline_info.dfilter);
846 timestamp_set_type(recent.gui_time_format);
847 timestamp_set_precision(recent.gui_time_precision);
848 timestamp_set_seconds_type (recent.gui_seconds_format);
850 #ifdef HAVE_LIBPCAP
851 if (global_commandline_info.list_link_layer_types)
852 caps_queries |= CAPS_QUERY_LINK_TYPES;
853 if (global_commandline_info.list_timestamp_types)
854 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
856 if (global_commandline_info.start_capture || caps_queries) {
857 /* We're supposed to do a live capture or get a list of link-layer/timestamp
858 types for a live capture device; if the user didn't specify an
859 interface to use, pick a default. */
860 ret_val = capture_opts_default_iface_if_necessary(&global_capture_opts,
861 ((global_commandline_info.prefs_p->capture_device) && (*global_commandline_info.prefs_p->capture_device != '\0')) ? get_if_name(global_commandline_info.prefs_p->capture_device) : NULL);
862 if (ret_val != 0) {
863 goto clean_exit;
868 * If requested, list the link layer types and/or time stamp types
869 * and exit.
871 if (caps_queries) {
872 unsigned i;
874 #ifdef _WIN32
875 create_console();
876 #endif /* _WIN32 */
877 /* Get the list of link-layer types for the capture devices. */
878 ret_val = EXIT_SUCCESS;
879 GList *if_cap_queries = NULL;
880 if_cap_query_t *if_cap_query;
881 GHashTable *capability_hash;
882 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
883 interface_options *interface_opts;
885 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
886 if_cap_query = g_new(if_cap_query_t, 1);
887 if_cap_query->name = interface_opts->name;
888 if_cap_query->monitor_mode = interface_opts->monitor_mode;
889 if_cap_query->auth_username = NULL;
890 if_cap_query->auth_password = NULL;
891 #ifdef HAVE_PCAP_REMOTE
892 if (interface_opts->auth_type == CAPTURE_AUTH_PWD) {
893 if_cap_query->auth_username = interface_opts->auth_username;
894 if_cap_query->auth_password = interface_opts->auth_password;
896 #endif
897 if_cap_queries = g_list_prepend(if_cap_queries, if_cap_query);
899 if_cap_queries = g_list_reverse(if_cap_queries);
900 capability_hash = capture_get_if_list_capabilities(if_cap_queries, &err_str, &err_str_secondary, NULL);
901 g_list_free_full(if_cap_queries, g_free);
902 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
903 interface_options *interface_opts;
904 if_capabilities_t *caps;
905 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
906 caps = static_cast<if_capabilities_t*>(g_hash_table_lookup(capability_hash, interface_opts->name));
907 if (caps == NULL) {
908 cmdarg_err("%s%s%s", err_str, err_str_secondary ? "\n" : "", err_str_secondary ? err_str_secondary : "");
909 g_free(err_str);
910 g_free(err_str_secondary);
911 ret_val = WS_EXIT_INVALID_CAPABILITY;
912 break;
914 ret_val = capture_opts_print_if_capabilities(caps, interface_opts,
915 caps_queries);
916 if (ret_val != EXIT_SUCCESS) {
917 break;
920 #ifdef _WIN32
921 destroy_console();
922 #endif /* _WIN32 */
923 g_hash_table_destroy(capability_hash);
924 goto clean_exit;
927 #ifdef DEBUG_STARTUP_TIME
928 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling fill_in_local_interfaces, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
929 #endif
930 splash_update(RA_INTERFACES, NULL, NULL);
932 if (!global_commandline_info.cf_name && !prefs.capture_no_interface_load) {
933 /* Allow only extcap interfaces to be found */
934 GList * filter_list = NULL;
935 filter_list = g_list_append(filter_list, GUINT_TO_POINTER((unsigned) IF_EXTCAP));
936 // The below starts the stats; we don't need that since Stratoshark only
937 // supports extcaps.
938 //ssApp->scanLocalInterfaces(filter_list);
939 fill_in_local_interfaces_filtered(filter_list, main_window_update);
940 g_list_free(filter_list);
943 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
944 capture_opts_trim_ring_num_files(&global_capture_opts);
945 #endif /* HAVE_LIBPCAP */
947 /* Notify all registered modules that have had any of their preferences
948 changed either from one of the preferences file or from the command
949 line that their preferences have changed. */
950 #ifdef DEBUG_STARTUP_TIME
951 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling prefs_apply_all, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
952 #endif
953 prefs_apply_all();
954 ColorUtils::setScheme(prefs.gui_color_scheme);
955 ssApp->emitAppSignal(StratosharkApplication::ColorsChanged);
956 ssApp->emitAppSignal(StratosharkApplication::PreferencesChanged);
958 #ifdef HAVE_LIBPCAP
959 if ((global_capture_opts.num_selected == 0) &&
960 (prefs.capture_device != NULL)) {
961 unsigned i;
962 interface_t *device;
963 for (i = 0; i < global_capture_opts.all_ifaces->len; i++) {
964 device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
965 if (!device->hidden && strcmp(device->display_name, prefs.capture_device) == 0) {
966 device->selected = true;
967 global_capture_opts.num_selected++;
968 break;
972 #endif
975 * Enabled and disabled protocols and heuristic dissectors as per
976 * command-line options.
978 if (!setup_enabled_and_disabled_protocols()) {
979 ret_val = WS_EXIT_INVALID_OPTION;
980 goto clean_exit;
983 build_column_format_array(&CaptureFile::globalCapFile()->cinfo, global_commandline_info.prefs_p->num_cols, true);
984 ssApp->emitAppSignal(StratosharkApplication::ColumnsChanged); // We read "recent" widths above.
985 ssApp->emitAppSignal(StratosharkApplication::RecentPreferencesRead); // Must be emitted after PreferencesChanged.
987 ssApp->setMonospaceFont(prefs.gui_font_name);
989 /* For update of WindowTitle (When use gui.window_title preference) */
990 main_w->setWSWindowTitle();
992 if (!color_filters_init(&err_msg, color_filter_add_cb)) {
993 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err_msg);
994 g_free(err_msg);
997 ssApp->allSystemsGo();
998 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Stratoshark is up and ready to go, elapsed time %.3fs", (float) (g_get_monotonic_time() - start_time) / 1000000);
999 SimpleDialog::displayQueuedMessages(main_w);
1001 /* User could specify filename, or display filter, or both */
1002 if (!dfilter.isEmpty())
1003 main_w->filterPackets(dfilter, false);
1004 if (!cf_name.isEmpty()) {
1005 if (main_w->openCaptureFile(cf_name, read_filter, in_file_type)) {
1007 /* Open stat windows; we do so after creating the main window,
1008 to avoid Qt warnings, and after successfully opening the
1009 capture file, so we know we have something to compute stats
1010 on, and after registering all dissectors, so that MATE will
1011 have registered its field array and we can have a tap filter
1012 with one of MATE's late-registered fields as part of the
1013 filter. */
1014 start_requested_stats();
1016 if (global_commandline_info.go_to_packet != 0) {
1017 /* Jump to the specified frame number, kept for backward
1018 compatibility. */
1019 cf_goto_frame(CaptureFile::globalCapFile(), global_commandline_info.go_to_packet, false);
1020 } else if (global_commandline_info.jfilter != NULL) {
1021 dfilter_t *jump_to_filter = NULL;
1022 /* try to compile given filter */
1023 if (!dfilter_compile(global_commandline_info.jfilter, &jump_to_filter, &df_err)) {
1024 // Similar code in MainWindow::mergeCaptureFile().
1025 QMessageBox::warning(main_w, QObject::tr("Invalid Display Filter"),
1026 QObject::tr("The filter expression %1 isn't a valid display filter. (%2).")
1027 .arg(global_commandline_info.jfilter, df_err->msg),
1028 QMessageBox::Ok);
1029 df_error_free(&df_err);
1030 } else {
1031 /* Filter ok, jump to the first packet matching the filter
1032 conditions. Default search direction is forward, but if
1033 option d was given, search backwards */
1034 cf_find_packet_dfilter(CaptureFile::globalCapFile(), jump_to_filter, global_commandline_info.jump_backwards);
1039 #ifdef HAVE_LIBPCAP
1040 else {
1041 if (global_commandline_info.start_capture) {
1042 if (global_capture_opts.save_file != NULL) {
1043 /* Save the directory name for future file dialogs. */
1044 /* (get_dirname overwrites filename) */
1045 char *s = g_strdup(global_capture_opts.save_file);
1046 set_last_open_dir(get_dirname(s));
1047 g_free(s);
1049 /* "-k" was specified; start a capture. */
1050 check_and_warn_user_startup();
1052 /* If no user interfaces were specified on the command line,
1053 copy the list of selected interfaces to the set of interfaces
1054 to use for this capture. */
1055 if (global_capture_opts.ifaces->len == 0)
1056 collect_ifaces(&global_capture_opts);
1057 CaptureFile::globalCapFile()->window = main_w;
1058 if (capture_start(&global_capture_opts, global_commandline_info.capture_comments,
1059 main_w->captureSession(), main_w->captureInfoData(),
1060 main_window_update)) {
1061 /* The capture started. Open stat windows; we do so after creating
1062 the main window, to avoid GTK warnings, and after successfully
1063 opening the capture file, so we know we have something to compute
1064 stats on, and after registering all dissectors, so that MATE will
1065 have registered its field array and we can have a tap filter with
1066 one of MATE's late-registered fields as part of the filter. */
1067 start_requested_stats();
1070 /* if the user didn't supply a capture filter, use the one to filter out remote connections like SSH */
1071 if (!global_commandline_info.start_capture && !global_capture_opts.default_options.cfilter) {
1072 global_capture_opts.default_options.cfilter = g_strdup(get_conn_cfilter());
1075 #endif /* HAVE_LIBPCAP */
1077 // UAT and UI settings files used in configuration profiles which are used
1078 // in Qt dialogs are not registered during startup because they only get
1079 // loaded when the dialog is shown. Register them here.
1080 profile_register_persconffile("io_graphs");
1081 profile_register_persconffile("import_hexdump.json");
1082 profile_register_persconffile("remote_hosts.json");
1084 profile_store_persconffiles(false);
1086 // If the ssApp->exec() event loop exits cleanly, we call
1087 // StratosharkApplication::cleanup().
1088 ret_val = ssApp->exec();
1089 ssApp = NULL;
1091 // Many widgets assume that they always have valid epan data, so this
1092 // must be called before epan_cleanup().
1093 // XXX We need to clean up the Lua GUI here. We currently paper over
1094 // this in FunnelStatistics::~FunnelStatistics, which leaks memory.
1095 delete main_w;
1097 recent_cleanup();
1098 epan_cleanup();
1100 extcap_cleanup();
1102 Dot11DecryptDestroyContext(&dot11decrypt_ctx);
1104 ws_cleanup_sockets();
1106 #ifdef _WIN32
1107 /* For some unknown reason, the "atexit()" call in "create_console()"
1108 doesn't arrange that "destroy_console()" be called when we exit,
1109 so we call it here if a console was created. */
1110 destroy_console();
1111 #endif /* _WIN32 */
1113 clean_exit:
1114 #ifdef HAVE_LIBPCAP
1115 capture_opts_cleanup(&global_capture_opts);
1116 #endif
1117 col_cleanup(&CaptureFile::globalCapFile()->cinfo);
1118 codecs_cleanup();
1119 wtap_cleanup();
1120 free_progdirs();
1121 commandline_options_free();
1122 exit_application(ret_val);