Revert "TODO epan/dissectors/asn1/kerberos/packet-kerberos-template.c new GSS flags"
[wireshark-sm.git] / ui / qt / main.cpp
blobbe144d26479742e5a457960b571b27c68381a651
1 /* main.cpp
3 * Wireshark - Network traffic 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"
77 #include "ui/profile.h"
79 #include "ui/qt/conversation_dialog.h"
80 #include "ui/qt/utils/color_utils.h"
81 #include "ui/qt/coloring_rules_dialog.h"
82 #include "ui/qt/endpoint_dialog.h"
83 #include "ui/qt/glib_mainloop_on_qeventloop.h"
84 #include "ui/qt/wireshark_main_window.h"
85 #include "ui/qt/response_time_delay_dialog.h"
86 #include "ui/qt/service_response_time_dialog.h"
87 #include "ui/qt/simple_dialog.h"
88 #include "ui/qt/simple_statistics_dialog.h"
89 #include <ui/qt/widgets/splash_overlay.h>
90 #include "ui/qt/wireshark_application.h"
92 #include "capture/capture-pcap-util.h"
94 #include <QMessageBox>
95 #include <QScreen>
97 #ifdef _WIN32
98 # include "capture/capture-wpcap.h"
99 # include <wsutil/file_util.h>
100 #endif /* _WIN32 */
102 #include "epan/crypt/dot11decrypt_ws.h"
104 /* Handle the addition of View menu items without request */
105 #if defined(Q_OS_MAC)
106 #include <ui/macosx/cocoa_bridge.h>
107 #endif
109 #include <ui/qt/utils/qt_ui_utils.h>
111 //#define DEBUG_STARTUP_TIME 1
113 /* update the main window */
114 void main_window_update(void)
116 WiresharkApplication::processEvents();
119 void exit_application(int status) {
120 if (wsApp) {
121 wsApp->quit();
123 exit(status);
127 * Report an error in command-line arguments.
129 * On Windows, Wireshark is built for the Windows subsystem, and runs
130 * without a console, so we create a console on Windows to receive the
131 * output.
133 * See create_console(), in ui/win32/console_win32.c, for an example
134 * of code to check whether we need to create a console.
136 * On UN*Xes:
138 * If Wireshark is run from the command line, its output either goes
139 * to the terminal or to wherever the standard error was redirected.
141 * If Wireshark is run by executing it as a remote command, e.g. with
142 * ssh, its output either goes to whatever socket was set up for the
143 * remote command's standard error or to wherever the standard error
144 * was redirected.
146 * If Wireshark was run from the GUI, e.g. by double-clicking on its
147 * icon or on a file that it opens, there are no guarantees as to
148 * where the standard error went. It could be going to /dev/null
149 * (current macOS), or to a socket to systemd for the journal, or
150 * to a log file in the user's home directory, or to the "console
151 * device" ("workstation console"), or....
153 * Part of determining that, at least for locally-run Wireshark,
154 * is to try to open /dev/tty to determine whether the process
155 * has a controlling terminal. (It fails, at a minimum, for
156 * Wireshark launched from the GUI under macOS, Ubuntu with GNOME,
157 * and Ubuntu with KDE; in all cases, an attempt to open /dev/tty
158 * fails with ENXIO.) If it does have a controlling terminal,
159 * write to the standard error, otherwise assume that the standard
160 * error might not go anywhere that the user will be able to see.
161 * That doesn't handle the "run by ssh" case, however; that will
162 * not have a controlling terminal. (This means running it by
163 * remote execution, not by remote login.) Perhaps there's an
164 * environment variable to check there.
166 // xxx copied from ../gtk/main.c
167 static void
168 wireshark_cmdarg_err(const char *fmt, va_list ap)
170 #ifdef _WIN32
171 create_console();
172 #endif
173 fprintf(stderr, "wireshark: ");
174 vfprintf(stderr, fmt, ap);
175 fprintf(stderr, "\n");
179 * Report additional information for an error in command-line arguments.
180 * Creates a console on Windows.
182 // xxx copied from ../gtk/main.c
183 static void
184 wireshark_cmdarg_err_cont(const char *fmt, va_list ap)
186 #ifdef _WIN32
187 create_console();
188 #endif
189 vfprintf(stderr, fmt, ap);
190 fprintf(stderr, "\n");
193 void
194 gather_wireshark_qt_compiled_info(feature_list l)
196 #ifdef QT_VERSION
197 with_feature(l, "Qt %s", QT_VERSION_STR);
198 #else
199 with_feature(l, "Qt (version unknown)");
200 #endif
201 gather_caplibs_compile_info(l);
202 epan_gather_compile_info(l);
203 #ifdef HAVE_MINIZIPNG
204 with_feature(l, "Minizip-ng %s", MINIZIPNG_VERSION);
205 #else
206 #ifdef HAVE_MINIZIP
207 with_feature(l, "Minizip %s", MINIZIP_VERSION);
208 #else
209 without_feature(l, "Minizip");
210 #endif
211 #endif /* HAVE_MINIZIPNG */
212 #ifdef QT_MULTIMEDIA_LIB
213 with_feature(l, "QtMultimedia");
214 #else
215 without_feature(l, "QtMultimedia");
216 #endif
217 #if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)
218 #ifdef QT_DBUS_LIB
219 with_feature(l, "QtDBus");
220 #else
221 without_feature(l, "QtDBus");
222 #endif
223 #endif /* !Q_OS_WIN && !Q_OS_MAC */
225 const char *update_info = software_update_info();
226 if (update_info) {
227 with_feature(l, "automatic updates");
228 with_feature(l, "%s", update_info);
229 } else {
230 without_feature(l, "automatic updates");
234 void
235 gather_wireshark_runtime_info(feature_list l)
237 with_feature(l, "Qt %s", qVersion());
238 #ifdef HAVE_LIBPCAP
239 gather_caplibs_runtime_info(l);
240 #endif
241 epan_gather_runtime_info(l);
243 if (mainApp) {
244 // Display information
245 const char *display_mode = ColorUtils::themeIsDark() ? "dark" : "light";
246 with_feature(l, "%s display mode", display_mode);
248 int hidpi_count = 0;
249 foreach (QScreen *screen, mainApp->screens()) {
250 if (screen->devicePixelRatio() > 1.0) {
251 hidpi_count++;
254 if (hidpi_count == mainApp->screens().count()) {
255 with_feature(l, "HiDPI");
256 } else if (hidpi_count) {
257 with_feature(l, "mixed DPI");
258 } else {
259 without_feature(l, "HiDPI");
261 QString session = qEnvironmentVariable("XDG_SESSION_TYPE");
262 if (!session.isEmpty()) {
263 if (session == "wayland") {
264 with_feature(l, "Wayland");
265 } else if (session == "x11") {
266 with_feature(l, "Xorg");
267 } else {
268 with_feature(l, "XDG_SESSION_TYPE=%s", qUtf8Printable(session));
271 QString platform = qApp->platformName();
272 if (!platform.isEmpty()) {
273 with_feature(l, "QPA plugin \"%s\"", qUtf8Printable(platform));
278 static void
279 qt_log_message_handler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
281 enum ws_log_level log_level = LOG_LEVEL_NONE;
283 // QMessageLogContext may contain null/zero for release builds.
284 const char *file = context.file;
285 int line = context.line > 0 ? context.line : -1;
286 const char *func = context.function;
288 switch (type) {
289 case QtInfoMsg:
290 log_level = LOG_LEVEL_INFO;
291 // Omit the file/line/function for this level.
292 file = nullptr;
293 line = -1;
294 func = nullptr;
295 break;
296 case QtWarningMsg:
297 log_level = LOG_LEVEL_WARNING;
298 break;
299 case QtCriticalMsg:
300 log_level = LOG_LEVEL_CRITICAL;
301 break;
302 case QtFatalMsg:
303 log_level = LOG_LEVEL_ERROR;
304 break;
305 // We want qDebug() messages to show up always for temporary print-outs.
306 case QtDebugMsg:
307 log_level = LOG_LEVEL_ECHO;
308 break;
311 // Qt gives the full method declaration as the function. Our convention
312 // (following the C/C++ standards) is to display only the function name.
313 // Hack the name into the message as a workaround to avoid formatting
314 // issues.
315 if (func != nullptr) {
316 ws_log_full(LOG_DOMAIN_QTUI, log_level, file, line, nullptr,
317 "%s -- %s", func, qUtf8Printable(msg));
319 else {
320 ws_log_full(LOG_DOMAIN_QTUI, log_level, file, line, nullptr,
321 "%s", qUtf8Printable(msg));
325 #ifdef HAVE_LIBPCAP
326 /* Check if there's something important to tell the user during startup.
327 * We want to do this *after* showing the main window so that any windows
328 * we pop up will be above the main window.
330 static void
331 check_and_warn_user_startup()
333 char *cur_user, *cur_group;
335 /* Tell the user not to run as root. */
336 if (running_with_special_privs() && recent.privs_warn_if_elevated) {
337 cur_user = get_cur_username();
338 cur_group = get_cur_groupname();
339 simple_message_box(ESD_TYPE_WARN, &recent.privs_warn_if_elevated,
340 "Running as user \"%s\" and group \"%s\".\n"
341 "This could be dangerous.\n\n"
342 "If you're running Wireshark this way in order to perform live capture, "
343 "you may want to be aware that there is a better way documented at\n"
344 WS_WIKI_URL("CaptureSetup/CapturePrivileges"), cur_user, cur_group);
345 g_free(cur_user);
346 g_free(cur_group);
349 #endif
351 #if defined(_WIN32) && !defined(__MINGW32__)
352 // Try to avoid library search path collisions. QCoreApplication will
353 // search QT_INSTALL_PREFIX/plugins for platform DLLs before searching
354 // the application directory. If
356 // - You have Qt version 5.x.y installed in the default location
357 // (C:\Qt\5.x) on your machine.
359 // and
361 // - You install Wireshark that was built on a machine with Qt version
362 // 5.x.z installed in the default location.
364 // Qt5Core.dll will load qwindows.dll from your local C:\Qt\5.x\...\plugins
365 // directory. This may not be compatible with qwindows.dll from that
366 // same path on the build machine. At any rate, loading DLLs from paths
367 // you don't control is ill-advised. We work around this by removing every
368 // path except our application directory.
370 // NOTE: This does not apply to MinGW-w64 using MSYS2. In that case we use
371 // the system's Qt plugins with the default search paths.
373 // NOTE 2: When using MinGW-w64 without MSYS2 we also search for the system DLLS,
374 // because our installer might not have deployed them.
376 static inline void
377 win32_reset_library_path(void)
379 QString app_path = QDir(get_progfile_dir()).path();
380 foreach (QString path, QCoreApplication::libraryPaths()) {
381 QCoreApplication::removeLibraryPath(path);
383 QCoreApplication::addLibraryPath(app_path);
385 #endif
387 #ifdef Q_OS_MAC
388 // Try to work around
390 // https://gitlab.com/wireshark/wireshark/-/issues/17075
392 // aka
394 // https://bugreports.qt.io/browse/QTBUG-87014
396 // The fix at
398 // https://codereview.qt-project.org/c/qt/qtbase/+/322228/3/src/plugins/platforms/cocoa/qnsview_drawing.mm
400 // enables layer backing if we're running on Big Sur OR we're running on
401 // Catalina AND we were built with the Catalina SDK. Enable layer backing
402 // here by setting QT_MAC_WANTS_LAYER=1, but only if we're running on Big
403 // Sur and our version of Qt doesn't have a fix for QTBUG-87014.
404 #include <QOperatingSystemVersion>
405 static inline void
406 macos_enable_layer_backing(void)
408 // At the time of this writing, the QTBUG-87014 for layerEnabledByMacOS is...
410 // ...in https://github.com/qt/qtbase/blob/5.15/src/plugins/platforms/cocoa/qnsview_drawing.mm
411 // ...not in https://github.com/qt/qtbase/blob/5.15.2/src/plugins/platforms/cocoa/qnsview_drawing.mm
412 // ...not in https://github.com/qt/qtbase/blob/6.0/src/plugins/platforms/cocoa/qnsview_drawing.mm
413 // ...not in https://github.com/qt/qtbase/blob/6.0.0/src/plugins/platforms/cocoa/qnsview_drawing.mm
415 // We'll assume that it will be fixed in 5.15.3, 6.0.1, and >= 6.1.
416 #if \
417 ((QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) && QT_VERSION < QT_VERSION_CHECK(5, 15, 3)) \
418 || (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) && QT_VERSION < QT_VERSION_CHECK(6, 0, 1)) \
420 QOperatingSystemVersion os_ver = QOperatingSystemVersion::current();
421 int major_ver = os_ver.majorVersion();
422 int minor_ver = os_ver.minorVersion();
423 if ( (major_ver == 10 && minor_ver >= 16) || major_ver >= 11 ) {
424 if (qgetenv("QT_MAC_WANTS_LAYER").isEmpty()) {
425 qputenv("QT_MAC_WANTS_LAYER", "1");
428 #endif
430 #endif
432 #ifdef HAVE_LIBPCAP
433 static GList *
434 capture_opts_get_interface_list(int *err, char **err_str)
436 if (mainApp) {
437 GList *if_list = mainApp->getInterfaceList();
438 if (if_list == NULL) {
439 if_list = capture_interface_list(err, err_str, main_window_update);
440 mainApp->setInterfaceList(if_list);
442 return if_list;
444 return capture_interface_list(err, err_str, main_window_update);
446 #endif
448 /* And now our feature presentation... [ fade to music ] */
449 int main(int argc, char *qt_argv[])
451 WiresharkMainWindow *main_w;
453 #ifdef _WIN32
454 LPWSTR *wc_argv;
455 int wc_argc;
456 #endif
457 int ret_val = EXIT_SUCCESS;
458 char **argv = qt_argv;
460 char *rf_path;
461 int rf_open_errno;
462 #ifdef HAVE_LIBPCAP
463 char *err_str, *err_str_secondary;
464 #endif
465 char *err_msg = NULL;
466 df_error_t *df_err = NULL;
468 QString dfilter, read_filter;
469 #ifdef HAVE_LIBPCAP
470 int caps_queries = 0;
471 #endif
472 /* Start time in microseconds */
473 uint64_t start_time = g_get_monotonic_time();
475 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
477 * See:
479 * issue #16908;
481 * https://doc.qt.io/qt-5/qvector.html#maximum-size-and-out-of-memory-conditions
483 * https://forum.qt.io/topic/114950/qvector-realloc-throwing-sigsegv-when-very-large-surface3d-is-rendered
485 * for why we're doing this; the widget we use for the packet list
486 * uses QVector, so those limitations apply to it.
488 * Apparently, this will be fixed in Qt 6:
490 * https://github.com/qt/qtbase/commit/215ca735341b9487826023a7983382851ce8bf26
492 * https://github.com/qt/qtbase/commit/2a6cdec718934ca2cc7f6f9c616ebe62f6912123#diff-724f419b0bb0487c2629bb16cf534c4b268ddcee89b5177189b607f940cfd83dR192
494 * Hopefully QList won't cause any performance hits relative to
495 * QVector.
497 * We pick 53 million records as a value that should avoid the problem;
498 * see the Wireshark issue for why that value was chosen.
500 cf_set_max_records(53000000);
501 #endif
503 #ifdef Q_OS_MAC
504 macos_enable_layer_backing();
505 #endif
507 cmdarg_err_init(wireshark_cmdarg_err, wireshark_cmdarg_err_cont);
509 /* Initialize log handler early so we can have proper logging during startup. */
510 ws_log_init("wireshark", vcmdarg_err);
511 /* For backward compatibility with GLib logging and Wireshark 3.4. */
512 ws_log_console_writer_set_use_stdout(true);
514 qInstallMessageHandler(qt_log_message_handler);
516 #ifdef _WIN32
517 restore_pipes();
518 #endif
520 #ifdef DEBUG_STARTUP_TIME
521 ws_log_console_open = LOG_CONSOLE_OPEN_ALWAYS;
522 #endif /* DEBUG_STARTUP_TIME */
524 #if defined(Q_OS_MAC)
525 /* Disable automatic addition of tab menu entries in view menu */
526 CocoaBridge::cleanOSGeneratedMenuItems();
527 #endif
530 * Set the C-language locale to the native environment and set the
531 * code page to UTF-8 on Windows.
533 #ifdef _WIN32
534 setlocale(LC_ALL, ".UTF-8");
535 #else
536 setlocale(LC_ALL, "");
537 #endif
539 ws_tzset();
541 #ifdef _WIN32
543 // On Windows, QCoreApplication has its own WinMain(), which gets the
544 // command line using GetCommandLineW(), breaks it into individual
545 // arguments using CommandLineToArgvW(), and then "helpfully"
546 // converts those UTF-16LE arguments into strings in the local code
547 // page.
549 // We don't want that, because not all file names can be represented
550 // in the local code page, so we do the same, but we convert the
551 // strings into UTF-8.
553 wc_argv = CommandLineToArgvW(GetCommandLineW(), &wc_argc);
554 if (wc_argv) {
555 argc = wc_argc;
556 argv = arg_list_utf_16to8(wc_argc, wc_argv);
557 LocalFree(wc_argv);
558 } /* XXX else bail because something is horribly, horribly wrong? */
560 create_app_running_mutex();
561 #endif /* _WIN32 */
563 /* Early logging command-line initialization. */
564 ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
565 ws_noisy("Finished log init and parsing command line log arguments");
568 * Get credential information for later use, and drop privileges
569 * before doing anything else.
570 * Let the user know if anything happened.
572 init_process_policies();
573 relinquish_special_privs_perm();
576 * Attempt to get the pathname of the directory containing the
577 * executable file.
579 /* configuration_init_error = */ configuration_init(argv[0], NULL);
580 /* ws_log(NULL, LOG_LEVEL_DEBUG, "progfile_dir: %s", get_progfile_dir()); */
582 #ifdef _WIN32
583 ws_init_dll_search_path();
584 /* Load wpcap if possible. Do this before collecting the run-time version information */
585 load_wpcap();
587 #endif /* _WIN32 */
589 /* Get the compile-time version information string */
590 ws_init_version_info("Wireshark", gather_wireshark_qt_compiled_info,
591 gather_wireshark_runtime_info);
593 init_report_alert_box("Wireshark");
595 /* Create the user profiles directory */
596 if (create_profiles_dir(&rf_path) == -1) {
597 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
598 "Could not create profiles directory\n\"%s\": %s.",
599 rf_path, g_strerror(errno));
600 g_free (rf_path);
603 profile_store_persconffiles(true);
604 recent_init();
606 /* Read the profile independent recent file. We have to do this here so we can */
607 /* set the profile before it can be set from the command line parameter */
608 if (!recent_read_static(&rf_path, &rf_open_errno)) {
609 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
610 "Could not open common recent file\n\"%s\": %s.",
611 rf_path, g_strerror(rf_open_errno));
612 g_free(rf_path);
615 commandline_early_options(argc, argv);
617 #if defined(_WIN32) && !defined(__MINGW32__)
618 win32_reset_library_path();
619 #endif
621 // Handle DPI scaling on Windows. This causes problems in at least
622 // one case on X11 and we don't yet support Android.
623 // We do the equivalent on macOS by setting NSHighResolutionCapable
624 // in Info.plist.
625 // Note that this enables Windows 8.1-style Per-monitor DPI
626 // awareness but not Windows 10-style Per-monitor v2 awareness.
627 // https://doc.qt.io/qt-5/scalability.html
628 // https://doc.qt.io/qt-5/highdpi.html
629 // https://bugreports.qt.io/browse/QTBUG-53022 - The device pixel ratio is pretty much bogus on Windows.
630 // https://bugreports.qt.io/browse/QTBUG-55510 - Windows have wrong size
632 // Deprecated in Qt6, which is Per-Monitor DPI Aware V2 by default.
633 // warning: 'Qt::AA_EnableHighDpiScaling' is deprecated: High-DPI scaling is always enabled.
634 // This attribute no longer has any effect.
635 #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
636 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
637 #endif
639 // This function must be called before creating the application object.
640 // Qt::HighDpiScaleFactorRoundingPolicy::PassThrough is the default in Qt6,
641 // so this doesn't have any effect (Round is the default in 5.14 & 5.15)
642 #if defined(Q_OS_WIN)
643 QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
644 #endif
646 /* Create The Wireshark app */
647 WiresharkApplication ws_app(argc, qt_argv);
649 // Default value is 400ms = "quickly typing" when searching in Preferences->Protocols
650 // 1000ms allows a more "hunt/peck" typing speed. 2000ms tested - too long.
651 QApplication::setKeyboardInputInterval(1000);
653 /* initialize the funnel mini-api */
654 // xxx qtshark
655 //initialize_funnel_ops();
657 Dot11DecryptInitContext(&dot11decrypt_ctx);
659 QString cf_name;
660 unsigned int in_file_type = WTAP_TYPE_AUTO;
662 err_msg = ws_init_sockets();
663 if (err_msg != NULL)
665 cmdarg_err("%s", err_msg);
666 g_free(err_msg);
667 cmdarg_err_cont("%s", please_report_bug());
668 ret_val = WS_EXIT_INIT_FAILED;
669 goto clean_exit;
672 /* Read the profile dependent (static part) of the recent file. */
673 /* Only the static part of it will be read, as we don't have the gui now to fill the */
674 /* recent lists which is done in the dynamic part. */
675 /* We have to do this already here, so command line parameters can overwrite these values. */
676 if (!recent_read_profile_static(&rf_path, &rf_open_errno)) {
677 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
678 "Could not open recent file\n\"%s\": %s.",
679 rf_path, g_strerror(rf_open_errno));
680 g_free(rf_path);
682 wsApp->applyCustomColorsFromRecent();
684 // Initialize our language
685 read_language_prefs();
686 wsApp->loadLanguage(language);
688 /* ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_DEBUG, "Translator %s", language); */
690 // Init the main window (and splash)
691 main_w = new(WiresharkMainWindow);
692 main_w->show();
693 // Setup GLib mainloop on Qt event loop to enable GLib and GIO watches
694 GLibMainloopOnQEventLoop::setup(main_w);
695 // We may not need a queued connection here but it would seem to make sense
696 // to force the issue.
697 main_w->connect(&ws_app, &WiresharkApplication::openCaptureFile,
698 main_w, [&](QString cf_path, QString display_filter, unsigned int type) {
699 main_w->openCaptureFile(cf_path, display_filter, type);
701 main_w->connect(&ws_app, &WiresharkApplication::openCaptureOptions,
702 main_w, &WiresharkMainWindow::showCaptureOptionsDialog);
705 * If we have a saved "last directory in which a file was opened"
706 * in the recent file, set it as the one for the app.
708 * (do this after the path settings are processed)
710 if (recent.gui_fileopen_remembered_dir &&
711 test_for_directory(recent.gui_fileopen_remembered_dir) == EISDIR) {
712 set_last_open_dir(recent.gui_fileopen_remembered_dir);
715 #ifdef DEBUG_STARTUP_TIME
716 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "set_console_log_handler, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
717 #endif
719 #ifdef HAVE_LIBPCAP
720 /* Set the initial values in the capture options. This might be overwritten
721 by preference settings and then again by the command line parameters. */
722 capture_opts_init(&global_capture_opts, capture_opts_get_interface_list);
723 #endif
726 * Libwiretap must be initialized before libwireshark is, so that
727 * dissection-time handlers for file-type-dependent blocks can
728 * register using the file type/subtype value for the file type.
730 wtap_init(true);
732 splash_update(RA_DISSECTORS, NULL, NULL);
733 #ifdef DEBUG_STARTUP_TIME
734 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling epan init, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
735 #endif
736 /* Register all dissectors; we must do this before checking for the
737 "-G" flag, as the "-G" flag dumps information registered by the
738 dissectors, and we must do it before we read the preferences, in
739 case any dissectors register preferences. */
740 if (!epan_init(splash_update, NULL, true)) {
741 SimpleDialog::displayQueuedMessages(main_w);
742 ret_val = WS_EXIT_INIT_FAILED;
743 goto clean_exit;
745 #ifdef DEBUG_STARTUP_TIME
746 /* epan_init resets the preferences */
747 ws_log_console_open = LOG_CONSOLE_OPEN_ALWAYS;
748 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "epan done, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
749 #endif
751 /* Register all audio codecs. */
752 codecs_init();
754 // Read the dynamic part of the recent file. This determines whether or
755 // not the recent list appears in the main window so the earlier we can
756 // call this the better.
757 if (!recent_read_dynamic(&rf_path, &rf_open_errno)) {
758 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
759 "Could not open recent file\n\"%s\": %s.",
760 rf_path, g_strerror(rf_open_errno));
761 g_free(rf_path);
763 wsApp->refreshRecentCaptures();
765 splash_update(RA_LISTENERS, NULL, NULL);
766 #ifdef DEBUG_STARTUP_TIME
767 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Register all tap listeners, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
768 #endif
769 /* Register all tap listeners; we do this before we parse the arguments,
770 as the "-z" argument can specify a registered tap. */
772 register_all_tap_listeners(tap_reg_listener);
774 conversation_table_set_gui_info(init_conversation_table);
775 endpoint_table_set_gui_info(init_endpoint_table);
776 srt_table_iterate_tables(register_service_response_tables, NULL);
777 rtd_table_iterate_tables(register_response_time_delay_tables, NULL);
778 stat_tap_iterate_tables(register_simple_stat_tables, NULL);
780 if (ex_opt_count("read_format") > 0) {
781 in_file_type = open_info_name_to_type(ex_opt_get_next("read_format"));
784 splash_update(RA_PREFERENCES, NULL, NULL);
785 #ifdef DEBUG_STARTUP_TIME
786 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling module preferences, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
787 #endif
789 /* Read the preferences, but don't apply them yet. */
790 global_commandline_info.prefs_p = ws_app.readConfigurationFiles(false);
792 /* Now let's see if any of preferences were overridden at the command
793 * line, and store them. We have to do this before applying the
794 * preferences to the capture options.
796 commandline_override_prefs(argc, argv, true);
798 /* Register the extcap preferences. We do this after seeing if the
799 * capture_no_extcap preference is set in the configuration file
800 * or command line. This will re-read the extcap specific preferences.
802 #ifdef DEBUG_STARTUP_TIME
803 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling extcap_register_preferences, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
804 #endif
805 splash_update(RA_EXTCAP, NULL, NULL);
806 extcap_register_preferences();
808 /* Apply the extcap command line options now that the extcap preferences
809 * are loaded.
811 commandline_options_apply_extcap();
813 /* Some of the preferences affect the capture options. Apply those
814 * before getting the other command line arguments, which can also
815 * affect the capture options. The command line arguments should be
816 * applied last to take precedence (at least until the user saves
817 * preferences, or switches profiles.)
819 prefs_to_capture_opts();
821 /* Now get our remaining args */
823 /* XXX: Processing interface options on the command line might retrieve
824 * interface list. We don't yet know if we will need to retrieve the
825 * interface capabilities as well (e.g. are we printing capabilities,
826 * or loading the interface list?) until we parse other options, like
827 * whether we have a capture file.
829 * We'd prefer to avoid firing up dumpcap twice (once for the list
830 * without the capabilities and once for capabilities), especially
831 * on Windows where that could mean two UAC prompts. However, getting
832 * the interface capabilities is a bit time-consuming so we don't want
833 * to do it if we don't need to.
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 wsApp->scanLocalInterfaces(nullptr);
936 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
937 capture_opts_trim_ring_num_files(&global_capture_opts);
938 #endif /* HAVE_LIBPCAP */
940 /* Notify all registered modules that have had any of their preferences
941 changed either from one of the preferences file or from the command
942 line that their preferences have changed. */
943 #ifdef DEBUG_STARTUP_TIME
944 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling prefs_apply_all, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
945 #endif
946 splash_update(RA_PREFERENCES_APPLY, NULL, NULL);
947 prefs_apply_all();
948 ColorUtils::setScheme(prefs.gui_color_scheme);
949 wsApp->emitAppSignal(WiresharkApplication::ColorsChanged);
950 wsApp->emitAppSignal(WiresharkApplication::PreferencesChanged);
952 #ifdef HAVE_LIBPCAP
953 if ((global_capture_opts.num_selected == 0) &&
954 (prefs.capture_device != NULL)) {
955 unsigned i;
956 interface_t *device;
957 for (i = 0; i < global_capture_opts.all_ifaces->len; i++) {
958 device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
959 if (!device->hidden && strcmp(device->display_name, prefs.capture_device) == 0) {
960 device->selected = true;
961 global_capture_opts.num_selected++;
962 break;
966 #endif
969 * Enabled and disabled protocols and heuristic dissectors as per
970 * command-line options.
972 if (!setup_enabled_and_disabled_protocols()) {
973 ret_val = WS_EXIT_INVALID_OPTION;
974 goto clean_exit;
977 build_column_format_array(&CaptureFile::globalCapFile()->cinfo, global_commandline_info.prefs_p->num_cols, true);
978 wsApp->emitAppSignal(WiresharkApplication::ColumnsChanged); // We read "recent" widths above.
979 wsApp->emitAppSignal(WiresharkApplication::RecentPreferencesRead); // Must be emitted after PreferencesChanged.
981 wsApp->setMonospaceFont(prefs.gui_font_name);
983 /* For update of WindowTitle (When use gui.window_title preference) */
984 main_w->setWSWindowTitle();
986 if (!color_filters_init(&err_msg, color_filter_add_cb)) {
987 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err_msg);
988 g_free(err_msg);
991 /* allSystemsGo() emits appInitialized(), which signals the WelcomePage to
992 * delete the splash overlay. However, it doesn't get redrawn until
993 * processEvents() is called. If we're opening a capture file that happens
994 * either when we finish reading the file or when the progress bar appears.
995 * It's probably better to leave the splash overlay up until that happens
996 * rather than showing the user the welcome page, so we don't call
997 * processEvents() here.
999 wsApp->allSystemsGo();
1000 ws_info("Wireshark is up and ready to go, elapsed time %.3fs", (float) (g_get_monotonic_time() - start_time) / 1000000);
1001 SimpleDialog::displayQueuedMessages(main_w);
1003 /* User could specify filename, or display filter, or both */
1004 if (!dfilter.isEmpty())
1005 main_w->filterPackets(dfilter, false);
1006 if (!cf_name.isEmpty()) {
1007 if (main_w->openCaptureFile(cf_name, read_filter, in_file_type)) {
1009 /* Open stat windows; we do so after creating the main window,
1010 to avoid Qt warnings, and after successfully opening the
1011 capture file, so we know we have something to compute stats
1012 on, and after registering all dissectors, so that MATE will
1013 have registered its field array and we can have a tap filter
1014 with one of MATE's late-registered fields as part of the
1015 filter. */
1016 start_requested_stats();
1018 if (global_commandline_info.go_to_packet != 0) {
1019 /* Jump to the specified frame number, kept for backward
1020 compatibility. */
1021 cf_goto_frame(CaptureFile::globalCapFile(), global_commandline_info.go_to_packet, false);
1022 } else if (global_commandline_info.jfilter != NULL) {
1023 dfilter_t *jump_to_filter = NULL;
1024 /* try to compile given filter */
1025 if (!dfilter_compile(global_commandline_info.jfilter, &jump_to_filter, &df_err)) {
1026 // Similar code in MainWindow::mergeCaptureFile().
1027 QMessageBox::warning(main_w, QObject::tr("Invalid Display Filter"),
1028 QObject::tr("The filter expression \"%1\" isn't a valid display filter.\n(%2).")
1029 .arg(global_commandline_info.jfilter, df_err->msg),
1030 QMessageBox::Ok);
1031 df_error_free(&df_err);
1032 } else {
1033 /* Filter ok, jump to the first packet matching the filter
1034 conditions. Default search direction is forward, but if
1035 option j was given, search backwards */
1036 cf_find_packet_dfilter(CaptureFile::globalCapFile(), jump_to_filter, global_commandline_info.jump_backwards, false);
1041 #ifdef HAVE_LIBPCAP
1042 else {
1043 if (global_commandline_info.start_capture) {
1044 if (global_capture_opts.save_file != NULL) {
1045 /* Save the directory name for future file dialogs. */
1046 /* (get_dirname overwrites filename) */
1047 char *s = g_strdup(global_capture_opts.save_file);
1048 set_last_open_dir(get_dirname(s));
1049 g_free(s);
1051 /* "-k" was specified; start a capture. */
1052 check_and_warn_user_startup();
1054 /* If no user interfaces were specified on the command line,
1055 copy the list of selected interfaces to the set of interfaces
1056 to use for this capture. */
1057 /* XXX: I don't think this can happen, because if start_capture is
1058 * true then capture_opts_default_iface_if_necessary() was called
1060 if (global_capture_opts.ifaces->len == 0)
1061 collect_ifaces(&global_capture_opts);
1062 CaptureFile::globalCapFile()->window = main_w;
1063 if (capture_start(&global_capture_opts, global_commandline_info.capture_comments,
1064 main_w->captureSession(), main_w->captureInfoData(),
1065 main_window_update)) {
1066 /* The capture started. Open stat windows; we do so after creating
1067 the main window, to avoid GTK warnings, and after successfully
1068 opening the capture file, so we know we have something to compute
1069 stats on, and after registering all dissectors, so that MATE will
1070 have registered its field array and we can have a tap filter with
1071 one of MATE's late-registered fields as part of the filter. */
1072 start_requested_stats();
1075 /* if the user didn't supply a capture filter, use the one to filter out remote connections like SSH */
1076 if (!global_commandline_info.start_capture && !global_capture_opts.default_options.cfilter) {
1077 global_capture_opts.default_options.cfilter = g_strdup(get_conn_cfilter());
1080 #endif /* HAVE_LIBPCAP */
1082 // UAT and UI settings files used in configuration profiles which are used
1083 // in Qt dialogs are not registered during startup because they only get
1084 // loaded when the dialog is shown. Register them here.
1085 profile_register_persconffile("io_graphs");
1086 profile_register_persconffile("import_hexdump.json");
1087 profile_register_persconffile("remote_hosts.json");
1089 profile_store_persconffiles(false);
1090 init_profile_list();
1092 // If the wsApp->exec() event loop exits cleanly, we call
1093 // WiresharkApplication::cleanup().
1094 ret_val = wsApp->exec();
1095 wsApp = NULL;
1097 // Many widgets assume that they always have valid epan data, so this
1098 // must be called before epan_cleanup().
1099 // XXX We need to clean up the Lua GUI here. We currently paper over
1100 // this in FunnelStatistics::~FunnelStatistics, which leaks memory.
1101 delete main_w;
1103 recent_cleanup();
1104 epan_cleanup();
1106 extcap_cleanup();
1108 Dot11DecryptDestroyContext(&dot11decrypt_ctx);
1110 ws_cleanup_sockets();
1112 #ifdef _WIN32
1113 /* For some unknown reason, the "atexit()" call in "create_console()"
1114 doesn't arrange that "destroy_console()" be called when we exit,
1115 so we call it here if a console was created. */
1116 destroy_console();
1117 #endif /* _WIN32 */
1119 clean_exit:
1120 #ifdef HAVE_LIBPCAP
1121 capture_opts_cleanup(&global_capture_opts);
1122 #endif
1123 col_cleanup(&CaptureFile::globalCapFile()->cinfo);
1124 codecs_cleanup();
1125 wtap_cleanup();
1126 free_progdirs();
1127 commandline_options_free();
1128 exit_application(ret_val);