update epan/dissectors/pidl/drsuapi/drsuapi.idl from samba
[wireshark-sm.git] / ui / qt / main.cpp
blob61fbcb14bcad80961c0f3c3ed16d205a5ac5c6e0
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 using %s", update_info);
228 } else {
229 without_feature(l, "automatic updates");
233 void
234 gather_wireshark_runtime_info(feature_list l)
236 with_feature(l, "Qt %s", qVersion());
237 #ifdef HAVE_LIBPCAP
238 gather_caplibs_runtime_info(l);
239 #endif
240 epan_gather_runtime_info(l);
242 if (mainApp) {
243 // Display information
244 const char *display_mode = ColorUtils::themeIsDark() ? "dark" : "light";
245 with_feature(l, "%s display mode", display_mode);
247 int hidpi_count = 0;
248 foreach (QScreen *screen, mainApp->screens()) {
249 if (screen->devicePixelRatio() > 1.0) {
250 hidpi_count++;
253 if (hidpi_count == mainApp->screens().count()) {
254 with_feature(l, "HiDPI");
255 } else if (hidpi_count) {
256 with_feature(l, "mixed DPI");
257 } else {
258 without_feature(l, "HiDPI");
260 QString session = qEnvironmentVariable("XDG_SESSION_TYPE");
261 if (!session.isEmpty()) {
262 if (session == "wayland") {
263 with_feature(l, "Wayland");
264 } else if (session == "x11") {
265 with_feature(l, "Xorg");
266 } else {
267 with_feature(l, "XDG_SESSION_TYPE=%s", qUtf8Printable(session));
270 QString platform = qApp->platformName();
271 if (!platform.isEmpty()) {
272 with_feature(l, "QPA plugin \"%s\"", qUtf8Printable(platform));
277 static void
278 qt_log_message_handler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
280 enum ws_log_level log_level = LOG_LEVEL_NONE;
282 // QMessageLogContext may contain null/zero for release builds.
283 const char *file = context.file;
284 int line = context.line > 0 ? context.line : -1;
285 const char *func = context.function;
287 switch (type) {
288 case QtInfoMsg:
289 log_level = LOG_LEVEL_INFO;
290 // Omit the file/line/function for this level.
291 file = nullptr;
292 line = -1;
293 func = nullptr;
294 break;
295 case QtWarningMsg:
296 log_level = LOG_LEVEL_WARNING;
297 break;
298 case QtCriticalMsg:
299 log_level = LOG_LEVEL_CRITICAL;
300 break;
301 case QtFatalMsg:
302 log_level = LOG_LEVEL_ERROR;
303 break;
304 // We want qDebug() messages to show up always for temporary print-outs.
305 case QtDebugMsg:
306 log_level = LOG_LEVEL_ECHO;
307 break;
310 // Qt gives the full method declaration as the function. Our convention
311 // (following the C/C++ standards) is to display only the function name.
312 // Hack the name into the message as a workaround to avoid formatting
313 // issues.
314 if (func != nullptr) {
315 ws_log_full(LOG_DOMAIN_QTUI, log_level, file, line, nullptr,
316 "%s -- %s", func, qUtf8Printable(msg));
318 else {
319 ws_log_full(LOG_DOMAIN_QTUI, log_level, file, line, nullptr,
320 "%s", qUtf8Printable(msg));
324 #ifdef HAVE_LIBPCAP
325 /* Check if there's something important to tell the user during startup.
326 * We want to do this *after* showing the main window so that any windows
327 * we pop up will be above the main window.
329 static void
330 check_and_warn_user_startup()
332 char *cur_user, *cur_group;
334 /* Tell the user not to run as root. */
335 if (running_with_special_privs() && recent.privs_warn_if_elevated) {
336 cur_user = get_cur_username();
337 cur_group = get_cur_groupname();
338 simple_message_box(ESD_TYPE_WARN, &recent.privs_warn_if_elevated,
339 "Running as user \"%s\" and group \"%s\".\n"
340 "This could be dangerous.\n\n"
341 "If you're running Wireshark this way in order to perform live capture, "
342 "you may want to be aware that there is a better way documented at\n"
343 WS_WIKI_URL("CaptureSetup/CapturePrivileges"), cur_user, cur_group);
344 g_free(cur_user);
345 g_free(cur_group);
348 #endif
350 #if defined(_WIN32) && !defined(__MINGW32__)
351 // Try to avoid library search path collisions. QCoreApplication will
352 // search QT_INSTALL_PREFIX/plugins for platform DLLs before searching
353 // the application directory. If
355 // - You have Qt version 5.x.y installed in the default location
356 // (C:\Qt\5.x) on your machine.
358 // and
360 // - You install Wireshark that was built on a machine with Qt version
361 // 5.x.z installed in the default location.
363 // Qt5Core.dll will load qwindows.dll from your local C:\Qt\5.x\...\plugins
364 // directory. This may not be compatible with qwindows.dll from that
365 // same path on the build machine. At any rate, loading DLLs from paths
366 // you don't control is ill-advised. We work around this by removing every
367 // path except our application directory.
369 // NOTE: This does not apply to MinGW-w64 using MSYS2. In that case we use
370 // the system's Qt plugins with the default search paths.
372 // NOTE 2: When using MinGW-w64 without MSYS2 we also search for the system DLLS,
373 // because our installer might not have deployed them.
375 static inline void
376 win32_reset_library_path(void)
378 QString app_path = QDir(get_progfile_dir()).path();
379 foreach (QString path, QCoreApplication::libraryPaths()) {
380 QCoreApplication::removeLibraryPath(path);
382 QCoreApplication::addLibraryPath(app_path);
384 #endif
386 #ifdef Q_OS_MAC
387 // Try to work around
389 // https://gitlab.com/wireshark/wireshark/-/issues/17075
391 // aka
393 // https://bugreports.qt.io/browse/QTBUG-87014
395 // The fix at
397 // https://codereview.qt-project.org/c/qt/qtbase/+/322228/3/src/plugins/platforms/cocoa/qnsview_drawing.mm
399 // enables layer backing if we're running on Big Sur OR we're running on
400 // Catalina AND we were built with the Catalina SDK. Enable layer backing
401 // here by setting QT_MAC_WANTS_LAYER=1, but only if we're running on Big
402 // Sur and our version of Qt doesn't have a fix for QTBUG-87014.
403 #include <QOperatingSystemVersion>
404 static inline void
405 macos_enable_layer_backing(void)
407 // At the time of this writing, the QTBUG-87014 for layerEnabledByMacOS is...
409 // ...in https://github.com/qt/qtbase/blob/5.15/src/plugins/platforms/cocoa/qnsview_drawing.mm
410 // ...not in https://github.com/qt/qtbase/blob/5.15.2/src/plugins/platforms/cocoa/qnsview_drawing.mm
411 // ...not in https://github.com/qt/qtbase/blob/6.0/src/plugins/platforms/cocoa/qnsview_drawing.mm
412 // ...not in https://github.com/qt/qtbase/blob/6.0.0/src/plugins/platforms/cocoa/qnsview_drawing.mm
414 // We'll assume that it will be fixed in 5.15.3, 6.0.1, and >= 6.1.
415 #if \
416 ((QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) && QT_VERSION < QT_VERSION_CHECK(5, 15, 3)) \
417 || (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) && QT_VERSION < QT_VERSION_CHECK(6, 0, 1)) \
419 QOperatingSystemVersion os_ver = QOperatingSystemVersion::current();
420 int major_ver = os_ver.majorVersion();
421 int minor_ver = os_ver.minorVersion();
422 if ( (major_ver == 10 && minor_ver >= 16) || major_ver >= 11 ) {
423 if (qgetenv("QT_MAC_WANTS_LAYER").isEmpty()) {
424 qputenv("QT_MAC_WANTS_LAYER", "1");
427 #endif
429 #endif
431 #ifdef HAVE_LIBPCAP
432 static GList *
433 capture_opts_get_interface_list(int *err, char **err_str)
435 if (mainApp) {
436 GList *if_list = mainApp->getInterfaceList();
437 if (if_list == NULL) {
438 if_list = capture_interface_list(err, err_str, main_window_update);
439 mainApp->setInterfaceList(if_list);
441 return if_list;
443 return capture_interface_list(err, err_str, main_window_update);
445 #endif
447 /* And now our feature presentation... [ fade to music ] */
448 int main(int argc, char *qt_argv[])
450 WiresharkMainWindow *main_w;
452 #ifdef _WIN32
453 LPWSTR *wc_argv;
454 int wc_argc;
455 #endif
456 int ret_val = EXIT_SUCCESS;
457 char **argv = qt_argv;
459 char *rf_path;
460 int rf_open_errno;
461 #ifdef HAVE_LIBPCAP
462 char *err_str, *err_str_secondary;
463 #endif
464 char *err_msg = NULL;
465 df_error_t *df_err = NULL;
467 QString dfilter, read_filter;
468 #ifdef HAVE_LIBPCAP
469 int caps_queries = 0;
470 #endif
471 /* Start time in microseconds */
472 uint64_t start_time = g_get_monotonic_time();
474 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
476 * See:
478 * issue #16908;
480 * https://doc.qt.io/qt-5/qvector.html#maximum-size-and-out-of-memory-conditions
482 * https://forum.qt.io/topic/114950/qvector-realloc-throwing-sigsegv-when-very-large-surface3d-is-rendered
484 * for why we're doing this; the widget we use for the packet list
485 * uses QVector, so those limitations apply to it.
487 * Apparently, this will be fixed in Qt 6:
489 * https://github.com/qt/qtbase/commit/215ca735341b9487826023a7983382851ce8bf26
491 * https://github.com/qt/qtbase/commit/2a6cdec718934ca2cc7f6f9c616ebe62f6912123#diff-724f419b0bb0487c2629bb16cf534c4b268ddcee89b5177189b607f940cfd83dR192
493 * Hopefully QList won't cause any performance hits relative to
494 * QVector.
496 * We pick 53 million records as a value that should avoid the problem;
497 * see the Wireshark issue for why that value was chosen.
499 cf_set_max_records(53000000);
500 #endif
502 #ifdef Q_OS_MAC
503 macos_enable_layer_backing();
504 #endif
506 cmdarg_err_init(wireshark_cmdarg_err, wireshark_cmdarg_err_cont);
508 /* Initialize log handler early so we can have proper logging during startup. */
509 ws_log_init("wireshark", vcmdarg_err);
510 /* For backward compatibility with GLib logging and Wireshark 3.4. */
511 ws_log_console_writer_set_use_stdout(true);
513 qInstallMessageHandler(qt_log_message_handler);
515 #ifdef _WIN32
516 restore_pipes();
517 #endif
519 #ifdef DEBUG_STARTUP_TIME
520 ws_log_console_open = LOG_CONSOLE_OPEN_ALWAYS;
521 #endif /* DEBUG_STARTUP_TIME */
523 #if defined(Q_OS_MAC)
524 /* Disable automatic addition of tab menu entries in view menu */
525 CocoaBridge::cleanOSGeneratedMenuItems();
526 #endif
529 * Set the C-language locale to the native environment and set the
530 * code page to UTF-8 on Windows.
532 #ifdef _WIN32
533 setlocale(LC_ALL, ".UTF-8");
534 #else
535 setlocale(LC_ALL, "");
536 #endif
538 ws_tzset();
540 #ifdef _WIN32
542 // On Windows, QCoreApplication has its own WinMain(), which gets the
543 // command line using GetCommandLineW(), breaks it into individual
544 // arguments using CommandLineToArgvW(), and then "helpfully"
545 // converts those UTF-16LE arguments into strings in the local code
546 // page.
548 // We don't want that, because not all file names can be represented
549 // in the local code page, so we do the same, but we convert the
550 // strings into UTF-8.
552 wc_argv = CommandLineToArgvW(GetCommandLineW(), &wc_argc);
553 if (wc_argv) {
554 argc = wc_argc;
555 argv = arg_list_utf_16to8(wc_argc, wc_argv);
556 LocalFree(wc_argv);
557 } /* XXX else bail because something is horribly, horribly wrong? */
559 create_app_running_mutex();
560 #endif /* _WIN32 */
562 /* Early logging command-line initialization. */
563 ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
564 ws_noisy("Finished log init and parsing command line log arguments");
567 * Get credential information for later use, and drop privileges
568 * before doing anything else.
569 * Let the user know if anything happened.
571 init_process_policies();
572 relinquish_special_privs_perm();
575 * Attempt to get the pathname of the directory containing the
576 * executable file.
578 /* configuration_init_error = */ configuration_init(argv[0], NULL);
579 /* ws_log(NULL, LOG_LEVEL_DEBUG, "progfile_dir: %s", get_progfile_dir()); */
581 #ifdef _WIN32
582 ws_init_dll_search_path();
583 /* Load wpcap if possible. Do this before collecting the run-time version information */
584 load_wpcap();
586 #endif /* _WIN32 */
588 /* Get the compile-time version information string */
589 ws_init_version_info("Wireshark", gather_wireshark_qt_compiled_info,
590 gather_wireshark_runtime_info);
592 init_report_alert_box("Wireshark");
594 /* Create the user profiles directory */
595 if (create_profiles_dir(&rf_path) == -1) {
596 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
597 "Could not create profiles directory\n\"%s\": %s.",
598 rf_path, g_strerror(errno));
599 g_free (rf_path);
602 profile_store_persconffiles(true);
603 recent_init();
605 /* Read the profile independent recent file. We have to do this here so we can */
606 /* set the profile before it can be set from the command line parameter */
607 if (!recent_read_static(&rf_path, &rf_open_errno)) {
608 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
609 "Could not open common recent file\n\"%s\": %s.",
610 rf_path, g_strerror(rf_open_errno));
611 g_free(rf_path);
614 commandline_early_options(argc, argv);
616 #if defined(_WIN32) && !defined(__MINGW32__)
617 win32_reset_library_path();
618 #endif
620 // Handle DPI scaling on Windows. This causes problems in at least
621 // one case on X11 and we don't yet support Android.
622 // We do the equivalent on macOS by setting NSHighResolutionCapable
623 // in Info.plist.
624 // Note that this enables Windows 8.1-style Per-monitor DPI
625 // awareness but not Windows 10-style Per-monitor v2 awareness.
626 // https://doc.qt.io/qt-5/scalability.html
627 // https://doc.qt.io/qt-5/highdpi.html
628 // https://bugreports.qt.io/browse/QTBUG-53022 - The device pixel ratio is pretty much bogus on Windows.
629 // https://bugreports.qt.io/browse/QTBUG-55510 - Windows have wrong size
631 // Deprecated in Qt6, which is Per-Monitor DPI Aware V2 by default.
632 // warning: 'Qt::AA_EnableHighDpiScaling' is deprecated: High-DPI scaling is always enabled.
633 // This attribute no longer has any effect.
634 #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
635 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
636 #endif
638 // This function must be called before creating the application object.
639 // Qt::HighDpiScaleFactorRoundingPolicy::PassThrough is the default in Qt6,
640 // so this doesn't have any effect (Round is the default in 5.14 & 5.15)
641 #if defined(Q_OS_WIN)
642 QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
643 #endif
645 /* Create The Wireshark app */
646 WiresharkApplication ws_app(argc, qt_argv);
648 // Default value is 400ms = "quickly typing" when searching in Preferences->Protocols
649 // 1000ms allows a more "hunt/peck" typing speed. 2000ms tested - too long.
650 QApplication::setKeyboardInputInterval(1000);
652 /* initialize the funnel mini-api */
653 // xxx qtshark
654 //initialize_funnel_ops();
656 Dot11DecryptInitContext(&dot11decrypt_ctx);
658 QString cf_name;
659 unsigned int in_file_type = WTAP_TYPE_AUTO;
661 err_msg = ws_init_sockets();
662 if (err_msg != NULL)
664 cmdarg_err("%s", err_msg);
665 g_free(err_msg);
666 cmdarg_err_cont("%s", please_report_bug());
667 ret_val = WS_EXIT_INIT_FAILED;
668 goto clean_exit;
671 /* Read the profile dependent (static part) of the recent file. */
672 /* Only the static part of it will be read, as we don't have the gui now to fill the */
673 /* recent lists which is done in the dynamic part. */
674 /* We have to do this already here, so command line parameters can overwrite these values. */
675 if (!recent_read_profile_static(&rf_path, &rf_open_errno)) {
676 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
677 "Could not open recent file\n\"%s\": %s.",
678 rf_path, g_strerror(rf_open_errno));
679 g_free(rf_path);
681 wsApp->applyCustomColorsFromRecent();
683 // Initialize our language
684 read_language_prefs();
685 wsApp->loadLanguage(language);
687 /* ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_DEBUG, "Translator %s", language); */
689 // Init the main window (and splash)
690 main_w = new(WiresharkMainWindow);
691 main_w->show();
692 // Setup GLib mainloop on Qt event loop to enable GLib and GIO watches
693 GLibMainloopOnQEventLoop::setup(main_w);
694 // We may not need a queued connection here but it would seem to make sense
695 // to force the issue.
696 main_w->connect(&ws_app, &WiresharkApplication::openCaptureFile,
697 main_w, [&](QString cf_path, QString display_filter, unsigned int type) {
698 main_w->openCaptureFile(cf_path, display_filter, type);
700 main_w->connect(&ws_app, &WiresharkApplication::openCaptureOptions,
701 main_w, &WiresharkMainWindow::showCaptureOptionsDialog);
704 * If we have a saved "last directory in which a file was opened"
705 * in the recent file, set it as the one for the app.
707 * (do this after the path settings are processed)
709 if (recent.gui_fileopen_remembered_dir &&
710 test_for_directory(recent.gui_fileopen_remembered_dir) == EISDIR) {
711 set_last_open_dir(recent.gui_fileopen_remembered_dir);
714 #ifdef DEBUG_STARTUP_TIME
715 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "set_console_log_handler, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
716 #endif
718 #ifdef HAVE_LIBPCAP
719 /* Set the initial values in the capture options. This might be overwritten
720 by preference settings and then again by the command line parameters. */
721 capture_opts_init(&global_capture_opts, capture_opts_get_interface_list);
722 #endif
725 * Libwiretap must be initialized before libwireshark is, so that
726 * dissection-time handlers for file-type-dependent blocks can
727 * register using the file type/subtype value for the file type.
729 wtap_init(true);
731 splash_update(RA_DISSECTORS, NULL, NULL);
732 #ifdef DEBUG_STARTUP_TIME
733 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling epan init, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
734 #endif
735 /* Register all dissectors; we must do this before checking for the
736 "-G" flag, as the "-G" flag dumps information registered by the
737 dissectors, and we must do it before we read the preferences, in
738 case any dissectors register preferences. */
739 if (!epan_init(splash_update, NULL, true)) {
740 SimpleDialog::displayQueuedMessages(main_w);
741 ret_val = WS_EXIT_INIT_FAILED;
742 goto clean_exit;
744 #ifdef DEBUG_STARTUP_TIME
745 /* epan_init resets the preferences */
746 ws_log_console_open = LOG_CONSOLE_OPEN_ALWAYS;
747 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "epan done, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
748 #endif
750 /* Register all audio codecs. */
751 codecs_init();
753 // Read the dynamic part of the recent file. This determines whether or
754 // not the recent list appears in the main window so the earlier we can
755 // call this the better.
756 if (!recent_read_dynamic(&rf_path, &rf_open_errno)) {
757 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
758 "Could not open recent file\n\"%s\": %s.",
759 rf_path, g_strerror(rf_open_errno));
760 g_free(rf_path);
762 wsApp->refreshRecentCaptures();
764 splash_update(RA_LISTENERS, NULL, NULL);
765 #ifdef DEBUG_STARTUP_TIME
766 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Register all tap listeners, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
767 #endif
768 /* Register all tap listeners; we do this before we parse the arguments,
769 as the "-z" argument can specify a registered tap. */
771 register_all_tap_listeners(tap_reg_listener);
773 conversation_table_set_gui_info(init_conversation_table);
774 endpoint_table_set_gui_info(init_endpoint_table);
775 srt_table_iterate_tables(register_service_response_tables, NULL);
776 rtd_table_iterate_tables(register_response_time_delay_tables, NULL);
777 stat_tap_iterate_tables(register_simple_stat_tables, NULL);
779 if (ex_opt_count("read_format") > 0) {
780 in_file_type = open_info_name_to_type(ex_opt_get_next("read_format"));
783 splash_update(RA_PREFERENCES, NULL, NULL);
784 #ifdef DEBUG_STARTUP_TIME
785 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling module preferences, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
786 #endif
788 /* Read the preferences, but don't apply them yet. */
789 global_commandline_info.prefs_p = ws_app.readConfigurationFiles(false);
791 /* Now let's see if any of preferences were overridden at the command
792 * line, and store them. We have to do this before applying the
793 * preferences to the capture options.
795 commandline_override_prefs(argc, argv, true);
797 /* Register the extcap preferences. We do this after seeing if the
798 * capture_no_extcap preference is set in the configuration file
799 * or command line. This will re-read the extcap specific preferences.
801 #ifdef DEBUG_STARTUP_TIME
802 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling extcap_register_preferences, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
803 #endif
804 splash_update(RA_EXTCAP, NULL, NULL);
805 extcap_register_preferences();
807 /* Apply the extcap command line options now that the extcap preferences
808 * are loaded.
810 commandline_options_apply_extcap();
812 /* Some of the preferences affect the capture options. Apply those
813 * before getting the other command line arguments, which can also
814 * affect the capture options. The command line arguments should be
815 * applied last to take precedence (at least until the user saves
816 * preferences, or switches profiles.)
818 prefs_to_capture_opts();
820 /* Now get our remaining args */
822 /* XXX: Processing interface options on the command line might retrieve
823 * interface list. We don't yet know if we will need to retrieve the
824 * interface capabilities as well (e.g. are we printing capabilities,
825 * or loading the interface list?) until we parse other options, like
826 * whether we have a capture file.
828 * We'd prefer to avoid firing up dumpcap twice (once for the list
829 * without the capabilities and once for capabilities), especially
830 * on Windows where that could mean two UAC prompts. However, getting
831 * the interface capabilities is a bit time-consuming so we don't want
832 * to do it if we don't need to.
835 commandline_other_options(argc, argv, true);
837 /* Convert some command-line parameters to QStrings */
838 if (global_commandline_info.cf_name != NULL)
839 cf_name = QString(global_commandline_info.cf_name);
840 if (global_commandline_info.rfilter != NULL)
841 read_filter = QString(global_commandline_info.rfilter);
842 if (global_commandline_info.dfilter != NULL)
843 dfilter = QString(global_commandline_info.dfilter);
845 timestamp_set_type(recent.gui_time_format);
846 timestamp_set_precision(recent.gui_time_precision);
847 timestamp_set_seconds_type (recent.gui_seconds_format);
849 #ifdef HAVE_LIBPCAP
850 if (global_commandline_info.list_link_layer_types)
851 caps_queries |= CAPS_QUERY_LINK_TYPES;
852 if (global_commandline_info.list_timestamp_types)
853 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
855 if (global_commandline_info.start_capture || caps_queries) {
856 /* We're supposed to do a live capture or get a list of link-layer/timestamp
857 types for a live capture device; if the user didn't specify an
858 interface to use, pick a default. */
859 ret_val = capture_opts_default_iface_if_necessary(&global_capture_opts,
860 ((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);
861 if (ret_val != 0) {
862 goto clean_exit;
867 * If requested, list the link layer types and/or time stamp types
868 * and exit.
870 if (caps_queries) {
871 unsigned i;
873 #ifdef _WIN32
874 create_console();
875 #endif /* _WIN32 */
876 /* Get the list of link-layer types for the capture devices. */
877 ret_val = EXIT_SUCCESS;
878 GList *if_cap_queries = NULL;
879 if_cap_query_t *if_cap_query;
880 GHashTable *capability_hash;
881 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
882 interface_options *interface_opts;
884 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
885 if_cap_query = g_new(if_cap_query_t, 1);
886 if_cap_query->name = interface_opts->name;
887 if_cap_query->monitor_mode = interface_opts->monitor_mode;
888 if_cap_query->auth_username = NULL;
889 if_cap_query->auth_password = NULL;
890 #ifdef HAVE_PCAP_REMOTE
891 if (interface_opts->auth_type == CAPTURE_AUTH_PWD) {
892 if_cap_query->auth_username = interface_opts->auth_username;
893 if_cap_query->auth_password = interface_opts->auth_password;
895 #endif
896 if_cap_queries = g_list_prepend(if_cap_queries, if_cap_query);
898 if_cap_queries = g_list_reverse(if_cap_queries);
899 capability_hash = capture_get_if_list_capabilities(if_cap_queries, &err_str, &err_str_secondary, NULL);
900 g_list_free_full(if_cap_queries, g_free);
901 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
902 interface_options *interface_opts;
903 if_capabilities_t *caps;
904 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
905 caps = static_cast<if_capabilities_t*>(g_hash_table_lookup(capability_hash, interface_opts->name));
906 if (caps == NULL) {
907 cmdarg_err("%s%s%s", err_str, err_str_secondary ? "\n" : "", err_str_secondary ? err_str_secondary : "");
908 g_free(err_str);
909 g_free(err_str_secondary);
910 ret_val = WS_EXIT_INVALID_CAPABILITY;
911 break;
913 ret_val = capture_opts_print_if_capabilities(caps, interface_opts,
914 caps_queries);
915 if (ret_val != EXIT_SUCCESS) {
916 break;
919 #ifdef _WIN32
920 destroy_console();
921 #endif /* _WIN32 */
922 g_hash_table_destroy(capability_hash);
923 goto clean_exit;
926 #ifdef DEBUG_STARTUP_TIME
927 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling fill_in_local_interfaces, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
928 #endif
929 splash_update(RA_INTERFACES, NULL, NULL);
931 if (!global_commandline_info.cf_name && !prefs.capture_no_interface_load) {
932 wsApp->scanLocalInterfaces(nullptr);
935 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
936 capture_opts_trim_ring_num_files(&global_capture_opts);
937 #endif /* HAVE_LIBPCAP */
939 /* Notify all registered modules that have had any of their preferences
940 changed either from one of the preferences file or from the command
941 line that their preferences have changed. */
942 #ifdef DEBUG_STARTUP_TIME
943 ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling prefs_apply_all, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
944 #endif
945 splash_update(RA_PREFERENCES_APPLY, NULL, NULL);
946 prefs_apply_all();
947 ColorUtils::setScheme(prefs.gui_color_scheme);
948 wsApp->emitAppSignal(WiresharkApplication::ColorsChanged);
949 wsApp->emitAppSignal(WiresharkApplication::PreferencesChanged);
951 #ifdef HAVE_LIBPCAP
952 if ((global_capture_opts.num_selected == 0) &&
953 (prefs.capture_device != NULL)) {
954 unsigned i;
955 interface_t *device;
956 for (i = 0; i < global_capture_opts.all_ifaces->len; i++) {
957 device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
958 if (!device->hidden && strcmp(device->display_name, prefs.capture_device) == 0) {
959 device->selected = true;
960 global_capture_opts.num_selected++;
961 break;
965 #endif
968 * Enabled and disabled protocols and heuristic dissectors as per
969 * command-line options.
971 if (!setup_enabled_and_disabled_protocols()) {
972 ret_val = WS_EXIT_INVALID_OPTION;
973 goto clean_exit;
976 build_column_format_array(&CaptureFile::globalCapFile()->cinfo, global_commandline_info.prefs_p->num_cols, true);
977 wsApp->emitAppSignal(WiresharkApplication::ColumnsChanged); // We read "recent" widths above.
978 wsApp->emitAppSignal(WiresharkApplication::RecentPreferencesRead); // Must be emitted after PreferencesChanged.
980 wsApp->setMonospaceFont(prefs.gui_font_name);
982 /* For update of WindowTitle (When use gui.window_title preference) */
983 main_w->setWSWindowTitle();
985 if (!color_filters_init(&err_msg, color_filter_add_cb)) {
986 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err_msg);
987 g_free(err_msg);
990 /* allSystemsGo() emits appInitialized(), which signals the WelcomePage to
991 * delete the splash overlay. However, it doesn't get redrawn until
992 * processEvents() is called. If we're opening a capture file that happens
993 * either when we finish reading the file or when the progress bar appears.
994 * It's probably better to leave the splash overlay up until that happens
995 * rather than showing the user the welcome page, so we don't call
996 * processEvents() here.
998 wsApp->allSystemsGo();
999 ws_info("Wireshark is up and ready to go, elapsed time %.3fs", (float) (g_get_monotonic_time() - start_time) / 1000000);
1000 SimpleDialog::displayQueuedMessages(main_w);
1002 /* User could specify filename, or display filter, or both */
1003 if (!dfilter.isEmpty())
1004 main_w->filterPackets(dfilter, false);
1005 if (!cf_name.isEmpty()) {
1006 if (main_w->openCaptureFile(cf_name, read_filter, in_file_type)) {
1008 /* Open stat windows; we do so after creating the main window,
1009 to avoid Qt warnings, and after successfully opening the
1010 capture file, so we know we have something to compute stats
1011 on, and after registering all dissectors, so that MATE will
1012 have registered its field array and we can have a tap filter
1013 with one of MATE's late-registered fields as part of the
1014 filter. */
1015 start_requested_stats();
1017 if (global_commandline_info.go_to_packet != 0) {
1018 /* Jump to the specified frame number, kept for backward
1019 compatibility. */
1020 cf_goto_frame(CaptureFile::globalCapFile(), global_commandline_info.go_to_packet, false);
1021 } else if (global_commandline_info.jfilter != NULL) {
1022 dfilter_t *jump_to_filter = NULL;
1023 /* try to compile given filter */
1024 if (!dfilter_compile(global_commandline_info.jfilter, &jump_to_filter, &df_err)) {
1025 // Similar code in MainWindow::mergeCaptureFile().
1026 QMessageBox::warning(main_w, QObject::tr("Invalid Display Filter"),
1027 QObject::tr("The filter expression %1 isn't a valid display filter. (%2).")
1028 .arg(global_commandline_info.jfilter, df_err->msg),
1029 QMessageBox::Ok);
1030 df_error_free(&df_err);
1031 } else {
1032 /* Filter ok, jump to the first packet matching the filter
1033 conditions. Default search direction is forward, but if
1034 option d was given, search backwards */
1035 cf_find_packet_dfilter(CaptureFile::globalCapFile(), jump_to_filter, global_commandline_info.jump_backwards);
1040 #ifdef HAVE_LIBPCAP
1041 else {
1042 if (global_commandline_info.start_capture) {
1043 if (global_capture_opts.save_file != NULL) {
1044 /* Save the directory name for future file dialogs. */
1045 /* (get_dirname overwrites filename) */
1046 char *s = g_strdup(global_capture_opts.save_file);
1047 set_last_open_dir(get_dirname(s));
1048 g_free(s);
1050 /* "-k" was specified; start a capture. */
1051 check_and_warn_user_startup();
1053 /* If no user interfaces were specified on the command line,
1054 copy the list of selected interfaces to the set of interfaces
1055 to use for this capture. */
1056 /* XXX: I don't think this can happen, because if start_capture is
1057 * true then capture_opts_default_iface_if_necessary() was called
1059 if (global_capture_opts.ifaces->len == 0)
1060 collect_ifaces(&global_capture_opts);
1061 CaptureFile::globalCapFile()->window = main_w;
1062 if (capture_start(&global_capture_opts, global_commandline_info.capture_comments,
1063 main_w->captureSession(), main_w->captureInfoData(),
1064 main_window_update)) {
1065 /* The capture started. Open stat windows; we do so after creating
1066 the main window, to avoid GTK warnings, and after successfully
1067 opening the capture file, so we know we have something to compute
1068 stats on, and after registering all dissectors, so that MATE will
1069 have registered its field array and we can have a tap filter with
1070 one of MATE's late-registered fields as part of the filter. */
1071 start_requested_stats();
1074 /* if the user didn't supply a capture filter, use the one to filter out remote connections like SSH */
1075 if (!global_commandline_info.start_capture && !global_capture_opts.default_options.cfilter) {
1076 global_capture_opts.default_options.cfilter = g_strdup(get_conn_cfilter());
1079 #endif /* HAVE_LIBPCAP */
1081 // UAT and UI settings files used in configuration profiles which are used
1082 // in Qt dialogs are not registered during startup because they only get
1083 // loaded when the dialog is shown. Register them here.
1084 profile_register_persconffile("io_graphs");
1085 profile_register_persconffile("import_hexdump.json");
1086 profile_register_persconffile("remote_hosts.json");
1088 profile_store_persconffiles(false);
1089 init_profile_list();
1091 // If the wsApp->exec() event loop exits cleanly, we call
1092 // WiresharkApplication::cleanup().
1093 ret_val = wsApp->exec();
1094 wsApp = NULL;
1096 // Many widgets assume that they always have valid epan data, so this
1097 // must be called before epan_cleanup().
1098 // XXX We need to clean up the Lua GUI here. We currently paper over
1099 // this in FunnelStatistics::~FunnelStatistics, which leaks memory.
1100 delete main_w;
1102 recent_cleanup();
1103 epan_cleanup();
1105 extcap_cleanup();
1107 Dot11DecryptDestroyContext(&dot11decrypt_ctx);
1109 ws_cleanup_sockets();
1111 #ifdef _WIN32
1112 /* For some unknown reason, the "atexit()" call in "create_console()"
1113 doesn't arrange that "destroy_console()" be called when we exit,
1114 so we call it here if a console was created. */
1115 destroy_console();
1116 #endif /* _WIN32 */
1118 clean_exit:
1119 #ifdef HAVE_LIBPCAP
1120 capture_opts_cleanup(&global_capture_opts);
1121 #endif
1122 col_cleanup(&CaptureFile::globalCapFile()->cinfo);
1123 codecs_cleanup();
1124 wtap_cleanup();
1125 free_progdirs();
1126 commandline_options_free();
1127 exit_application(ret_val);