Bug Summary

File:builds/wireshark/wireshark/ui/qt/main_application.cpp
Warning:line 475, column 5
Potential memory leak

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name main_application.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -fno-delete-null-pointer-checks -mframe-pointer=all -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -ffloat16-excess-precision=fast -fbfloat16-excess-precision=fast -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/builds/wireshark/wireshark/build -fcoverage-compilation-dir=/builds/wireshark/wireshark/build -resource-dir /usr/lib/llvm-22/lib/clang/22 -isystem /usr/include/glib-2.0 -isystem /usr/lib/x86_64-linux-gnu/glib-2.0/include -isystem /builds/wireshark/wireshark/build/ui/qt -isystem /builds/wireshark/wireshark/ui/qt -isystem /builds/wireshark/wireshark/ui/qt/lua_debugger -isystem /usr/include/x86_64-linux-gnu/qt6/QtConcurrent -isystem /usr/include/x86_64-linux-gnu/qt6 -isystem /usr/include/x86_64-linux-gnu/qt6/QtCore -isystem /usr/lib/x86_64-linux-gnu/qt6/mkspecs/linux-g++ -isystem /usr/include/x86_64-linux-gnu/qt6/QtNetwork -isystem /usr/include/x86_64-linux-gnu/qt6/QtPrintSupport -isystem /usr/include/x86_64-linux-gnu/qt6/QtGui -isystem /usr/include/x86_64-linux-gnu/qt6/QtWidgets -isystem /usr/include/x86_64-linux-gnu/qt6/QtSvg -isystem /usr/include/x86_64-linux-gnu/qt6/QtMultimedia -isystem /usr/include/x86_64-linux-gnu/qt6/QtDBus -D CARES_NO_DEPRECATED -D G_DISABLE_DEPRECATED -D G_DISABLE_SINGLE_INCLUDES -D QT_CONCURRENT_LIB -D QT_CORE_LIB -D QT_DBUS_LIB -D QT_GUI_LIB -D QT_MULTIMEDIA_LIB -D QT_NETWORK_LIB -D QT_PRINTSUPPORT_LIB -D QT_SVG_LIB -D QT_WIDGETS_LIB -D WS_DEBUG -D WS_DEBUG_UTF_8 -I /builds/wireshark/wireshark/build/ui/qt/qtui_autogen/include -I /builds/wireshark/wireshark/build -I /builds/wireshark/wireshark -I /builds/wireshark/wireshark/include -D _GLIBCXX_ASSERTIONS -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/x86_64-linux-gnu/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16/backward -internal-isystem /usr/lib/llvm-22/lib/clang/22/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/builds/wireshark/wireshark/= -fmacro-prefix-map=/builds/wireshark/wireshark/build/= -fmacro-prefix-map=../= -Wno-format-nonliteral -std=c++17 -fdeprecated-macro -ferror-limit 19 -fwrapv -fwrapv-pointer -fstrict-flex-arrays=3 -stack-protector 2 -fstack-clash-protection -fcf-protection=full -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fcxx-exceptions -fexceptions -fcolor-diagnostics -analyzer-output=html -faddrsig -fdwarf2-cfi-asm -o /builds/wireshark/wireshark/sbout/2026-10-27-101140-3661-1 -x c++ /builds/wireshark/wireshark/ui/qt/main_application.cpp
1/* main_application.cpp
2 *
3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
6 *
7 * SPDX-License-Identifier: GPL-2.0-or-later
8 */
9
10// warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data
11#ifdef _MSC_VER
12#pragma warning(push)
13#pragma warning(disable : 4267)
14#endif
15
16#define WS_LOG_DOMAIN"Main" LOG_DOMAIN_MAIN"Main"
17
18#include "main_application.h"
19
20#include <algorithm>
21#include <errno(*__errno_location ()).h>
22
23#include "wsutil/filesystem.h"
24#include "app/application_flavor.h"
25
26#include "epan/addr_resolv.h"
27#include "epan/prefs.h"
28#include "epan/proto.h"
29#include "epan/tap.h"
30#include "epan/timestamp.h"
31#include "epan/dfilter/dfilter-macro.h"
32
33#include "ui/commandline.h"
34#include "ui/preference_utils.h"
35#include "ui/language.h"
36#include "ui/recent.h"
37#include "ui/simple_dialog.h"
38#include "ui/util.h"
39
40#include <ui/qt/utils/qt_ui_utils.h>
41#include <ui/qt/utils/color_utils.h>
42#include <ui/qt/utils/font_manager.h>
43#include <ui/qt/utils/software_update.h>
44#include <ui/qt/utils/theme_manager.h>
45
46#include "epan/color_filters.h"
47#include "epan/tag_rules.h"
48
49#include "extcap.h"
50#ifdef HAVE_LIBPCAP1
51#include <capture/iface_monitor.h>
52#endif
53
54#include "ui/capture_globals.h"
55#include "ui/recent_utils.h"
56
57#include "wsutil/utf8_entities.h"
58
59#ifdef _WIN32
60# include "wsutil/file_util.h"
61# include <QMessageBox>
62# include <QSettings>
63#endif /* _WIN32 */
64
65#include <ui/qt/capture_file.h>
66
67#include <ui/qt/main_window.h>
68#include <ui/qt/manager/interface_list_manager.h>
69#include <ui/qt/main_status_bar.h>
70#include <ui/qt/utils/workspace_state.h>
71#include <ui/qt/utils/theme_styler.h>
72
73#include <QAction>
74#include <QApplication>
75#include <QColorDialog>
76#include <QDesktopServices>
77#include <QDir>
78#include <QEvent>
79#include <QFileOpenEvent>
80#include <QFontInfo>
81#include <QFontMetrics>
82#include <QLibraryInfo>
83#include <QLocale>
84#include <QMainWindow>
85#include <QMutableListIterator>
86#include <QProxyStyle>
87#include <QSocketNotifier>
88#include <QThreadPool>
89#include <QUrl>
90#include <qmath.h>
91
92#include <QMimeDatabase>
93
94#include <QStyleHints>
95
96#if QT_VERSION((6<<16)|(10<<8)|(2)) >= QT_VERSION_CHECK(6, 5, 0)((6<<16)|(5<<8)|(0)) && defined(Q_OS_WIN)
97#include <QStyleFactory>
98#endif
99
100#ifdef _MSC_VER
101#pragma warning(pop)
102#endif
103
104MainApplication *mainApp;
105
106// XXX - Copied from ui/gtk/file_dlg.c
107
108static QHash<int, QList<QAction *> > dynamic_menu_groups_;
109static QHash<int, QList<QAction *> > added_menu_groups_;
110static QHash<int, QList<QAction *> > removed_menu_groups_;
111
112QString MainApplication::window_title_separator_ = QString::fromUtf8(" " UTF8_MIDDLE_DOT"\u00b7" " ");
113
114// QMimeDatabase parses a large-ish XML file and can be slow to initialize.
115// Do so in a worker thread as early as possible.
116// https://github.com/lxde/pcmanfm-qt/issues/415
117class MimeDatabaseInitThread : public QRunnable
118{
119private:
120 void run() override
121 {
122 QMimeDatabase mime_db;
123 mime_db.mimeTypeForData(QByteArray());
124 }
125};
126
127void
128topic_action(topic_action_e action)
129{
130 if (mainApp) mainApp->helpTopicAction(action);
131}
132
133/* write all capture filenames of the menu to the user's recent file */
134extern "C" void menu_recent_file_write_all(FILE *rf) {
135
136 const QList<RecentFileInfo>& recentFiles = WorkspaceState::instance()->recentCaptureFiles();
137 int rFSize = static_cast<int>(recentFiles.size());
138 for (int i = 0; i < rFSize; i++) {
139 const RecentFileInfo& rfi = recentFiles.at(i);
140
141 QString cf_name = rfi.filename;
142 if (!cf_name.isNull()) {
143 fprintf (rf, RECENT_KEY_CAPTURE_FILE"recent.capture_file" ": %s\n", qUtf8Printable(cf_name)QtPrivate::asString(cf_name).toUtf8().constData());
144 }
145 }
146}
147
148void MainApplication::refreshPacketData()
149{
150 if (host_name_lookup_process()) {
151 emit addressResolutionChanged();
152 } else if (col_data_changed()) {
153 emit columnDataChanged();
154 }
155}
156
157void MainApplication::updateTaps()
158{
159 draw_tap_listeners(false);
160}
161
162QDir MainApplication::openDialogInitialDir() {
163 return QDir(get_open_dialog_initial_dir());
164}
165
166void MainApplication::setLastOpenDirFromFilename(const QString file_name)
167{
168 /* XXX - Use canonicalPath() instead of absolutePath()? */
169 QString directory = QDir::toNativeSeparators(QFileInfo(file_name).absolutePath());
170 /* XXX - printable? */
171 set_last_open_dir(qUtf8Printable(directory)QtPrivate::asString(directory).toUtf8().constData());
172}
173
174void MainApplication::helpTopicAction(topic_action_e action)
175{
176 QString url = gchar_free_to_qstring(topic_action_url(action));
177
178 if (!url.isEmpty()) {
179 QDesktopServices::openUrl(QUrl(QDir::fromNativeSeparators(url)));
180 }
181}
182
183void MainApplication::setConfigurationProfile(const char *profile_name, bool write_recent_file)
184{
185 char *rf_path;
186 int rf_open_errno;
187 char *err_msg = NULL__null;
188 const char* env_prefix = application_configuration_environment_prefix();
189
190 /* First check if profile exists */
191 if (!profile_exists(env_prefix, profile_name, false)) {
192 if (profile_exists(env_prefix, profile_name, true)) {
193 char *pf_dir_path, *pf_dir_path2, *pf_filename;
194 /* Copy from global profile */
195 if (create_persconffile_profile(env_prefix, profile_name, &pf_dir_path) == -1) {
196 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK0x01,
197 "Can't create directory\n\"%s\":\n%s.",
198 pf_dir_path, g_strerror(errno(*__errno_location ())));
199
200 g_free(pf_dir_path)(__builtin_object_size ((pf_dir_path), 0) != ((size_t) - 1)) ?
g_free_sized (pf_dir_path, __builtin_object_size ((pf_dir_path
), 0)) : (g_free) (pf_dir_path)
;
201 }
202
203 if (copy_persconffile_profile(env_prefix, profile_name, profile_name, true, &pf_filename,
204 &pf_dir_path, &pf_dir_path2) == -1) {
205 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK0x01,
206 "Can't copy file \"%s\" in directory\n\"%s\" to\n\"%s\":\n%s.",
207 pf_filename, pf_dir_path2, pf_dir_path, g_strerror(errno(*__errno_location ())));
208
209 g_free(pf_filename)(__builtin_object_size ((pf_filename), 0) != ((size_t) - 1)) ?
g_free_sized (pf_filename, __builtin_object_size ((pf_filename
), 0)) : (g_free) (pf_filename)
;
210 g_free(pf_dir_path)(__builtin_object_size ((pf_dir_path), 0) != ((size_t) - 1)) ?
g_free_sized (pf_dir_path, __builtin_object_size ((pf_dir_path
), 0)) : (g_free) (pf_dir_path)
;
211 g_free(pf_dir_path2)(__builtin_object_size ((pf_dir_path2), 0) != ((size_t) - 1))
? g_free_sized (pf_dir_path2, __builtin_object_size ((pf_dir_path2
), 0)) : (g_free) (pf_dir_path2)
;
212 }
213 } else {
214 /* No personal and no global profile exists */
215 return;
216 }
217 }
218
219 /* Then check if changing to another profile */
220 if (profile_name && strcmp (profile_name, get_profile_name()) == 0) {
221 return;
222 }
223
224 /* Get the current geometry, before writing it to disk */
225 emit profileChanging();
226
227 if (write_recent_file && profile_exists(env_prefix, get_profile_name(), false))
228 {
229 /* Write recent file for profile we are leaving, if it still exists */
230 write_profile_recent();
231 }
232
233 // Freeze the packet list early to avoid updating column data before doing a
234 // full redissection. The packet list will be thawed when redissection is done.
235 emit freezePacketList(true);
236
237 /* Set profile name and update the status bar */
238 set_profile_name (profile_name);
239 emit profileNameChanged(profile_name);
240
241 /* Apply new preferences */
242 readConfigurationFiles(true);
243
244 /* Reading the new profile's preferences reset every registered preference,
245 * including the ones that are shared by all of our profiles. Those aren't
246 * part of the profile we're leaving, so read them back in. */
247 extcap_read_preferences();
248
249 /* Apply command-line preferences */
250 commandline_options_reapply();
251 extcap_register_preferences(NULL__null, NULL__null);
252
253 /* Switching profile requires reloading the macro list. */
254 reloadDisplayFilterMacros();
255
256 if (!recent_read_profile_static(&rf_path, &rf_open_errno)) {
257 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK0x01,
258 "Could not open common recent file\n\"%s\": %s.",
259 rf_path, g_strerror(rf_open_errno));
260 g_free(rf_path)(__builtin_object_size ((rf_path), 0) != ((size_t) - 1)) ? g_free_sized
(rf_path, __builtin_object_size ((rf_path), 0)) : (g_free) (
rf_path)
;
261 }
262 FontManager::instance()->restoreZoomLevel();
263 if (recent.gui_fileopen_remembered_dir &&
264 test_for_directory(recent.gui_fileopen_remembered_dir) == EISDIR21) {
265 set_last_open_dir(recent.gui_fileopen_remembered_dir);
266 }
267 timestamp_set_type(recent.gui_time_format);
268 timestamp_set_precision(recent.gui_time_precision);
269 timestamp_set_seconds_type (recent.gui_seconds_format);
270
271 prefs_to_capture_opts(&global_capture_opts);
272 prefs_apply_all();
273#ifdef HAVE_LIBPCAP1
274 /* Re-apply interface display attributes from the new profile's prefs before
275 the preferencesChanged() emit below, so its listeners see fresh data. The
276 manager owns interface enumeration/attributes now. */
277 if (MainWindow *mw = mainWindow())
278 if (InterfaceListManager *mgr = mw->interfaceListManager())
279 mgr->reapplyInterfacePreferences();
280#endif
281
282 emit columnsChanged();
283 emit preferencesChanged();
284 emit recentPreferencesRead();
285 emit filterExpressionsChanged();
286 emit checkDisplayFilter();
287 emit captureFilterListChanged();
288 emit displayFilterListChanged();
289
290 /* Reload color filters */
291 if (!color_filters_reload(&err_msg, color_filter_add_cb, application_configuration_environment_prefix())) {
292 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK0x01, "%s", err_msg);
293 g_free(err_msg)(__builtin_object_size ((err_msg), 0) != ((size_t) - 1)) ? g_free_sized
(err_msg, __builtin_object_size ((err_msg), 0)) : (g_free) (
err_msg)
;
294 }
295
296 /* Reload tag rules (profile-specific file changes; global file stays the same) */
297 tag_rules_reload();
298
299 /* Capture-interface prefs are now watched by InterfaceListManager, which
300 rescans when capture_no_interface_load / capture_no_extcap flips. A profile
301 switch can also change interface display attributes, so notify subscribers
302 (the manager owns the interface-list-changed signal now). */
303 MainWindow *mw = mainWindow();
304 if (mw && mw->interfaceListManager())
305 mw->interfaceListManager()->notifyListChanged();
306 emit packetDissectionChanged();
307
308 /* Write recent_common file to ensure last used profile setting is stored. */
309 write_recent();
310}
311
312void MainApplication::reloadLuaPluginsDelayed()
313{
314 QTimer::singleShot(0, this, [this]() {
315 /* Clear the reloading flag so the re-triggered reload
316 * is not blocked by the isReloadingLua() guard. */
317 setReloadingLua(false);
318 emit reloadLuaPlugins();
319 });
320}
321
322const QIcon &MainApplication::normalIcon()
323{
324 if (normal_icon_.isNull()) {
325 initializeIcons();
326 }
327 return normal_icon_;
328}
329
330const QIcon &MainApplication::captureIcon()
331{
332 if (capture_icon_.isNull()) {
333 initializeIcons();
334 }
335 return capture_icon_;
336}
337
338const QString MainApplication::windowTitleString(QStringList title_parts)
339{
340 QMutableStringListIterator tii(title_parts);
341 while (tii.hasNext()) {
342 QString ti = tii.next();
343 if (ti.isEmpty()) tii.remove();
344 }
345 title_parts.prepend(applicationName());
346 return title_parts.join(window_title_separator_);
347}
348
349void MainApplication::applyCustomColorsFromRecent()
350{
351 int i = 0;
352 bool ok;
353 for (GList *custom_color = recent.custom_colors; custom_color; custom_color = custom_color->next) {
354 QRgb rgb = QString((const char *)custom_color->data).toUInt(&ok, 16);
355 if (ok) {
356 QColorDialog::setCustomColor(i++, QColor(rgb));
357 }
358 }
359}
360
361// Return the first top-level MainWindow.
362MainWindow *MainApplication::mainWindow()
363{
364 foreach (QWidget *tlw, topLevelWidgets())for (auto _container_364 = QtPrivate::qMakeForeachContainer(topLevelWidgets
()); _container_364.i != _container_364.e; ++_container_364.i
) if (QWidget *tlw = *_container_364.i; false) {} else
{
365 MainWindow *tlmw = qobject_cast<MainWindow *>(tlw);
366 if (tlmw && tlmw->isVisible()) {
367 return tlmw;
368 }
369 }
370 return nullptr;
371}
372
373void MainApplication::storeCustomColorsInRecent()
374{
375 if (QColorDialog::customCount()) {
376 prefs_clear_string_list(recent.custom_colors);
377 recent.custom_colors = NULL__null;
378 for (int i = 0; i < QColorDialog::customCount(); i++) {
379 QRgb rgb = QColorDialog::customColor(i).rgb();
380 recent.custom_colors = g_list_append(recent.custom_colors, ws_strdup_printf("%08x", rgb)wmem_strdup_printf(__null, "%08x", rgb));
381 }
382 }
383}
384
385bool MainApplication::event(QEvent *event)
386{
387 QString display_filter = NULL__null;
388 if (event->type() == QEvent::FileOpen) {
389 QFileOpenEvent *foe = static_cast<QFileOpenEvent *>(event);
390 if (foe && foe->file().length() > 0) {
391 QString cf_path(foe->file());
392 if (initialized_) {
393 emit openCaptureFile(cf_path, display_filter, WTAP_TYPE_AUTO0);
394 } else {
395 pending_open_files_.append(cf_path);
396 }
397 }
398 return true;
399 }
400 return QApplication::event(event);
401}
402
403void MainApplication::cleanup()
404{
405 SoftwareUpdate::instance()->cleanup();
406 storeCustomColorsInRecent();
407 // Write the user's recent file(s) to disk.
408 write_profile_recent();
409 write_recent();
410
411 // We might end up here via exit_application.
412 QThreadPool::globalInstance()->waitForDone();
413}
414
415MainApplication::MainApplication(int &argc, char **argv) :
416 QApplication(argc, argv),
417 initialized_(false),
418 is_reloading_lua_(false),
419 if_notifier_(NULL__null),
420 active_captures_(0)
421#if defined(Q_OS_MACOS) || defined(Q_OS_WIN)
422 , normal_icon_(windowIcon())
423#endif
424{
425 mainApp = this;
426
427 MimeDatabaseInitThread *mime_db_init_thread = new(MimeDatabaseInitThread);
428 QThreadPool::globalInstance()->start(mime_db_init_thread);
429
430 Q_INIT_RESOURCE(about)do { extern int qInitResources_about (); qInitResources_about
(); } while (false)
;
1
Loop condition is false. Exiting loop
431 Q_INIT_RESOURCE(i18n)do { extern int qInitResources_i18n (); qInitResources_i18n (
); } while (false)
;
2
Loop condition is false. Exiting loop
432 Q_INIT_RESOURCE(languages)do { extern int qInitResources_languages (); qInitResources_languages
(); } while (false)
;
3
Loop condition is false. Exiting loop
433
434 // Initialize the ThemeManager as early as possible so that any
435 // widget constructed afterwards can resolve themed stylesheets and
436 // color tokens. This must run after QApplication's base ctor (so
437 // that the palette is queryable for light/dark detection) but
438 // before any UI is built. recent_common has already been read in
439 // main()/stratoshark_main() prior to constructing this application
440 // object, so we can read any configured themes as well.
441 // Theme selection is persisted in recent_common (recent.gui_theme_name),
442 // not in the preferences file — so it survives profile switches and
443 // stays global to the install. Empty / missing value, or the legacy
444 // "default" sentinel, get resolved by ThemeManager itself to the
445 // current flavor's preferred default (wireshark / stratoshark).
446 ThemeManager::init(ThemeManager::resolveThemeName(
447 QString::fromUtf8(recent.gui_theme_name)));
448
449#ifdef Q_OS_WIN
450 /* RichEd20.DLL is needed for native file dialog filter entries. */
451 ws_load_library("riched20.dll");
452#endif // Q_OS_WIN
453
454 // We use a lot of style sheets that base their colors on the main
455 // application palette, so this works better.
456 setAttribute(Qt::AA_UseStyleSheetPropagationInWidgetStyles, true);
457
458 // Throw various settings at the wall with the hope that one of them will
459 // enable context menu shortcuts QTBUG-69452, QTBUG-109590
460 setAttribute(Qt::AA_DontShowShortcutsInContextMenus, false);
461 styleHints()->setShowShortcutsInContextMenus(true);
462
463 packet_data_timer_.setParent(this);
464 connect(&packet_data_timer_, &QTimer::timeout, this, &MainApplication::refreshPacketData);
465 packet_data_timer_.start(1000);
466
467 tap_update_timer_.setParent(this);
468 // tap_update_timer interval is set when preferences are set before init
469 connect(this, &MainApplication::appInitialized, &tap_update_timer_, [&]() { tap_update_timer_.start(); });
470 connect(&tap_update_timer_, &QTimer::timeout, this, &MainApplication::updateTaps);
471
472 setStyle(new ThemeStyler);
4
Memory is allocated
473 // setStyle() rebuilds Qt's per-class font table from the platform theme,
474 // dropping the zoomed or overridden class fonts pushed by ThemeManager.
475 FontManager::instance()->reapplyApplicationFonts();
5
Potential memory leak
476
477 connect(qApp(static_cast<QApplication *>(QCoreApplication::instance
()))
, &QApplication::aboutToQuit, this, &MainApplication::cleanup);
478}
479
480MainApplication::~MainApplication()
481{
482 mainApp = NULL__null;
483 clearDynamicMenuGroupItems();
484}
485
486void MainApplication::emitAppSignal(AppSignal signal)
487{
488 switch (signal) {
489 case ColumnsChanged:
490 emit columnsChanged();
491 break;
492 case CaptureFilterListChanged:
493 emit captureFilterListChanged();
494 break;
495 case DisplayFilterListChanged:
496 emit displayFilterListChanged();
497 break;
498 case FilterExpressionsChanged:
499 emit filterExpressionsChanged();
500 break;
501 case NameResolutionChanged:
502 emit addressResolutionChanged();
503 break;
504 case PreferencesChanged:
505 tap_update_timer_.setInterval(prefs.tap_update_interval);
506 emit preferencesChanged();
507 break;
508 case PacketDissectionChanged:
509 emit packetDissectionChanged();
510 break;
511 case RecentPreferencesRead:
512 emit recentPreferencesRead();
513 break;
514 case FieldsChanged:
515 emit fieldsChanged();
516 break;
517 case FreezePacketList:
518 emit freezePacketList(false);
519 break;
520 case AggregationChanged:
521 emit aggregationChanged();
522 break;
523 default:
524 break;
525 }
526}
527
528// Flush any collected app signals.
529//
530// On macOS emitting PacketDissectionChanged from a dialog can
531// render the application unusable:
532// https://gitlab.com/wireshark/wireshark/-/issues/11361
533// https://gitlab.com/wireshark/wireshark/-/issues/11448
534// Work around the problem by queueing up app signals and emitting them
535// after the dialog is closed.
536//
537// The following bugs might be related although they don't describe the
538// exact behavior we're working around here:
539// https://bugreports.qt.io/browse/QTBUG-38512
540// https://bugreports.qt.io/browse/QTBUG-38600
541void MainApplication::flushAppSignals()
542{
543 while (!app_signals_.isEmpty()) {
544 mainApp->emitAppSignal(app_signals_.takeFirst());
545 }
546}
547
548void MainApplication::emitStatCommandSignal(const QString &menu_path, const char *arg, void *userdata)
549{
550 emit openStatCommandDialog(menu_path, arg, userdata);
551}
552
553void MainApplication::emitTapParameterSignal(const QString cfg_abbr, const QString arg, void *userdata)
554{
555 emit openTapParameterDialog(cfg_abbr, arg, userdata);
556}
557
558// XXX Combine statistics and funnel routines into addGroupItem + groupItems?
559void MainApplication::addDynamicMenuGroupItem(int group, QAction *sg_action)
560{
561 if (!dynamic_menu_groups_.contains(group)) {
562 dynamic_menu_groups_[group] = QList<QAction *>();
563 }
564 dynamic_menu_groups_[group] << sg_action;
565}
566
567void MainApplication::appendDynamicMenuGroupItem(int group, QAction *sg_action)
568{
569 if (!added_menu_groups_.contains(group)) {
570 added_menu_groups_[group] = QList<QAction *>();
571 }
572 added_menu_groups_[group] << sg_action;
573 addDynamicMenuGroupItem(group, sg_action);
574}
575
576void MainApplication::removeDynamicMenuGroupItem(int group, QAction *sg_action)
577{
578 if (!removed_menu_groups_.contains(group)) {
579 removed_menu_groups_[group] = QList<QAction *>();
580 }
581 removed_menu_groups_[group] << sg_action;
582 dynamic_menu_groups_[group].removeAll(sg_action);
583}
584
585void MainApplication::clearDynamicMenuGroupItems()
586{
587 foreach (int group, dynamic_menu_groups_.keys())for (auto _container_587 = QtPrivate::qMakeForeachContainer(dynamic_menu_groups_
.keys()); _container_587.i != _container_587.e; ++_container_587
.i) if (int group = *_container_587.i; false) {} else
{
588 dynamic_menu_groups_[group].clear();
589 }
590}
591
592QList<QAction *> MainApplication::dynamicMenuGroupItems(int group)
593{
594 if (!dynamic_menu_groups_.contains(group)) {
595 return QList<QAction *>();
596 }
597
598 QList<QAction *> sgi_list = dynamic_menu_groups_[group];
599 std::sort(sgi_list.begin(), sgi_list.end(), qActionLessThan);
600 return sgi_list;
601}
602
603QList<QAction *> MainApplication::addedMenuGroupItems(int group)
604{
605 if (!added_menu_groups_.contains(group)) {
606 return QList<QAction *>();
607 }
608
609 QList<QAction *> sgi_list = added_menu_groups_[group];
610 std::sort(sgi_list.begin(), sgi_list.end(), qActionLessThan);
611 return sgi_list;
612}
613
614QList<QAction *> MainApplication::removedMenuGroupItems(int group)
615{
616 if (!removed_menu_groups_.contains(group)) {
617 return QList<QAction *>();
618 }
619
620 QList<QAction *> sgi_list = removed_menu_groups_[group];
621 std::sort(sgi_list.begin(), sgi_list.end(), qActionLessThan);
622 return sgi_list;
623}
624
625void MainApplication::clearAddedMenuGroupItems()
626{
627 foreach (int group, added_menu_groups_.keys())for (auto _container_627 = QtPrivate::qMakeForeachContainer(added_menu_groups_
.keys()); _container_627.i != _container_627.e; ++_container_627
.i) if (int group = *_container_627.i; false) {} else
{
628 added_menu_groups_[group].clear();
629 }
630}
631
632void MainApplication::clearRemovedMenuGroupItems()
633{
634 foreach (int group, removed_menu_groups_.keys())for (auto _container_634 = QtPrivate::qMakeForeachContainer(removed_menu_groups_
.keys()); _container_634.i != _container_634.e; ++_container_634
.i) if (int group = *_container_634.i; false) {} else
{
635 foreach (QAction *action, removed_menu_groups_[group])for (auto _container_635 = QtPrivate::qMakeForeachContainer(removed_menu_groups_
[group]); _container_635.i != _container_635.e; ++_container_635
.i) if (QAction *action = *_container_635.i; false) {} else
{
636 delete action;
637 }
638 removed_menu_groups_[group].clear();
639 }
640}
641
642#ifdef HAVE_LIBPCAP1
643
644static void
645iface_mon_event_cb(const char *iface, int added, int up)
646{
647 int present = 0;
648 unsigned ifs, j;
649 interface_t *device;
650 interface_options *interface_opts;
651
652 for (ifs = 0; ifs < global_capture_opts.all_ifaces->len; ifs++) {
653 device = &g_array_index(global_capture_opts.all_ifaces, interface_t, ifs)(((interface_t*) (void *) (global_capture_opts.all_ifaces)->
data) [(ifs)])
;
654 if (strcmp(device->name, iface) == 0) {
655 present = 1;
656 if (!up) {
657 /*
658 * Interface went down or disappeared; remove all instances
659 * of it from the current list of interfaces selected
660 * for capturing.
661 */
662 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
663 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j)(((interface_options*) (void *) (global_capture_opts.ifaces)->
data) [(j)])
;
664 if (strcmp(interface_opts->name, device->name) == 0) {
665 capture_opts_del_iface(&global_capture_opts, j);
666 }
667 }
668 }
669 }
670 }
671
672 mainApp->emitLocalInterfaceEvent(iface, added, up);
673 if (present != up) {
674 /*
675 * We've been told that there's a new interface or that an old
676 * interface is gone; reload the local interface list.
677 *
678 * XXX: We also want to reload the local interface list if [what
679 * we can retrieve about] the capabilities of the device have changed.
680 * Ideally we'd update the capabilities of just the one device in
681 * the cache and signal that the list has been updated, instead of
682 * freeing the entire cache and scanning again - but some extcaps
683 * depend on other interfaces being up; e.g. by default androiddump
684 * tries to connect to the loopback interface to look for adb running,
685 * so if the loopback interface changes so does the status of
686 * androiddump.
687 *
688 * On Linux, at least, you can't get the capabilities from a down
689 * interface, but it's still present in all_ifaces - dumpcap returns
690 * it in the list, and we show it so the user can get a status / error
691 * message when trying to capture on it instead of it vanishing.
692 * So if both present and up are true, then we still want to refresh
693 * to update the capabilities and restart the stats.
694 *
695 * We also store the address in all_ifaces and show them to the user,
696 * so we probably should monitor those events as well and update
697 * the interface list appropriately when those change.
698 */
699 MainWindow *mainWindow = mainApp->mainWindow();
700 if (mainWindow && mainWindow->interfaceListManager())
701 mainWindow->interfaceListManager()->requestRefresh();
702 }
703}
704
705#endif
706
707void MainApplication::ifChangeEventsAvailable()
708{
709#ifdef HAVE_LIBPCAP1
710 /*
711 * Something's readable from the descriptor for interface
712 * monitoring.
713 *
714 * Have the interface-monitoring code Read whatever interface-change
715 * events are available, and call the callback for them.
716 */
717 iface_mon_event();
718#endif
719}
720
721void MainApplication::emitLocalInterfaceEvent(const char *ifname, int added, int up)
722{
723 emit localInterfaceEvent(ifname, added, up);
724}
725
726void MainApplication::whenInitializedDispatch(const QObject *context, std::function<void()> fn)
727{
728 // POLICY DECISION (your input shapes behavior here):
729 //
730 // We get here only when a caller registers via whenInitialized() *after*
731 // appInitialized() has already fired. The not-yet-initialized path runs the
732 // callback later, from the event loop, once construction is long finished.
733 // How should the already-initialized path behave?
734 //
735 // A) Synchronous: fn(); right now. Simplest. But the callback runs while
736 // the caller's constructor is still on the stack -- the object may be
737 // only partly built, and any code after the whenInitialized() call in
738 // that constructor runs *after* the callback. Timing differs from the
739 // deferred path.
740 //
741 // B) Deferred to the event loop (e.g. QTimer::singleShot(0, context, fn)
742 // or QMetaObject::invokeMethod(..., Qt::QueuedConnection)): callback
743 // always runs after the current call returns, matching the signal path
744 // exactly, so callers see one consistent ordering. Costs one event-loop
745 // turn and needs the context-still-alive guarantee.
746 //
747 // Option A (current behavior) is intentional for now: it exactly reproduces
748 // the old open-coded `if (isInitialized()) doThing();` -- a synchronous call
749 // on the caller's stack -- so routing those sites through whenInitialized()
750 // is a pure no-op refactor. Option B is the intended end state, but it
751 // shifts the already-initialized callback by one event-loop turn and so
752 // changes ordering for every converted site at once; switch to it only
753 // behind broader ordering/lifetime tests (dialogs opened mid-session,
754 // welcome/interface frames at cold start, context destroyed same-turn).
755 //
756 // To switch, delete the fn() below and enable the deferred dispatch:
757 //
758 // QTimer::singleShot(0, const_cast<QObject *>(context), std::move(fn));
759 //
760 // (context is the receiver, so the call is dropped if it dies first, and
761 // runs on context's thread -- matching the connect() branch.)
762 Q_UNUSED(context)(void)context; // option A ignores context; option B uses it.
763 fn(); // option A: synchronous, matches legacy behavior.
764}
765
766void MainApplication::allSystemsGo()
767{
768 QString display_filter = NULL__null;
769 initialized_ = true;
770 emit appInitialized();
771 while (pending_open_files_.length() > 0) {
772 emit openCaptureFile(pending_open_files_.front(), display_filter, WTAP_TYPE_AUTO0);
773 pending_open_files_.pop_front();
774 }
775
776 bool sideBarVisible = recent.gui_welcome_page_sidebar_tips_visible ||
777 recent.gui_welcome_page_sidebar_learn_visible;
778 SoftwareUpdate::instance()->init(!sideBarVisible);
779
780#ifdef HAVE_LIBPCAP1
781 int err;
782 err = iface_mon_start(&iface_mon_event_cb);
783 if (err == 0) {
784 if_notifier_ = new QSocketNotifier(iface_mon_get_sock(),
785 QSocketNotifier::Read, this);
786 connect(if_notifier_, &QSocketNotifier::activated, this, &MainApplication::ifChangeEventsAvailable);
787 }
788#endif
789}
790
791_e_prefs *MainApplication::readConfigurationFiles(bool reset)
792{
793 e_prefs *prefs_p;
794
795 if (reset) {
796 //
797 // Reset current preferences and enabled/disabled protocols and
798 // heuristic dissectors before reading.
799 // (Needed except when this is called at startup.)
800 //
801 prefs_reset(application_configuration_environment_prefix(), application_columns(), application_num_columns());
802 proto_reenable_all();
803 }
804
805 /* Load libwireshark settings from the current profile. */
806 prefs_p = epan_load_settings();
807
808 return prefs_p;
809}
810
811static void switchTranslator(QTranslator& myTranslator, const QLocale &locale, const QString& filename, const QStringList &searchPath)
812{
813 mainApp->removeTranslator(&myTranslator);
814 for (const QString &path : searchPath) {
815 if (myTranslator.load(locale, filename, QStringLiteral("_")(QString(QtPrivate::qMakeStringPrivate(u"" "_"))), path)) {
816 mainApp->installTranslator(&myTranslator);
817 return;
818 }
819 }
820 if (locale.language() != QLocale::C) {
821 /* Don't compare the locale itself, see:
822 * https://doc.qt.io/qt-6/qlocale.html#operator-eq-eq
823 *
824 * Note that the ordered list of languages that were tried is that of
825 * locale.uiLanguages(); the first language in that list is not
826 * necessarily locale.language(), especially on Windows (See #17221.)
827 */
828 qWarningQMessageLogger(static_cast<const char *>("ui/qt/main_application.cpp"
), 828, static_cast<const char *>(__PRETTY_FUNCTION__))
.warning
() << "Couldn't load" << filename << "translations." << "Searched:" << searchPath;
829 }
830}
831
832QStringList MainApplication::getTranslationsPaths() const
833{
834 const char* env_prefix = application_configuration_environment_prefix();
835
836 // Search path list ordered by priority. Prefer personal configuration
837 // to global datadir to embedded resources to Qt global directory.
838 QStringList searchPath;
839 searchPath.emplaceBack(gchar_free_to_qstring(get_persconffile_path("languages", false, env_prefix)));
840 searchPath.emplaceBack(QStringLiteral("%1/languages")(QString(QtPrivate::qMakeStringPrivate(u"" "%1/languages"))).arg(get_datafile_dir(env_prefix)));
841 searchPath.emplaceBack(QStringLiteral(":/i18n/")(QString(QtPrivate::qMakeStringPrivate(u"" ":/i18n/"))));
842
843#if QT_VERSION((6<<16)|(10<<8)|(2)) >= QT_VERSION_CHECK(6, 8, 0)((6<<16)|(8<<8)|(0))
844 searchPath.append(QLibraryInfo::paths(QLibraryInfo::TranslationsPath));
845#else
846 searchPath.emplaceBack(QLibraryInfo::path(QLibraryInfo::TranslationsPath));
847#endif
848
849 return searchPath;
850}
851
852void MainApplication::loadLanguage(const QString newLanguage)
853{
854 QLocale locale;
855
856 if (newLanguage.isEmpty() || newLanguage == USE_SYSTEM_LANGUAGE"system") {
857 locale = QLocale::system();
858 } else {
859 locale = QLocale(newLanguage);
860 }
861
862 QLocale::setDefault(locale);
863
864 QStringList searchPath = getTranslationsPaths();
865
866 // Translations are searched for in the reverse order in which they were
867 // installed, so install the Qt generic translator first and ours last.
868 switchTranslator(mainApp->translatorQt, locale, QStringLiteral("qt")(QString(QtPrivate::qMakeStringPrivate(u"" "qt"))), searchPath);
869
870 // XXX - Yes, the translation files are also wireshark_%1.qm for Stratoshark.
871 // There is a stratoshark_en.[ts|qm] file too (for plurals?) though I'm
872 // not sure if it's used properly.
873 switchTranslator(mainApp->translator, locale, QStringLiteral("wireshark")(QString(QtPrivate::qMakeStringPrivate(u"" "wireshark"))), searchPath);
874}
875
876QString MainApplication::translateSystemLocale(const char *context, const char *sourceText, const char *disambiguation, int n) const
877{
878 // If we called this a lot, we could store the system QTranslators as
879 // member variables, but we only call this when constructing the
880 // language preference QComboBox.
881 QTranslator systemTranslator;
882 QString translated;
883 QStringList searchPath = getTranslationsPaths();
884
885 // Search in our translations first
886 for (const QString &path : searchPath) {
887 if (systemTranslator.load(QLocale::system(), QStringLiteral("wireshark")(QString(QtPrivate::qMakeStringPrivate(u"" "wireshark"))), QStringLiteral("_")(QString(QtPrivate::qMakeStringPrivate(u"" "_"))), path)) {
888 translated = systemTranslator.translate(context, sourceText, disambiguation, n);
889 if (!translated.isEmpty()) {
890 return translated;
891 }
892 }
893 }
894
895 // Try the generic Qt translations
896 for (const QString &path : searchPath) {
897 if (systemTranslator.load(QLocale::system(), QStringLiteral("qt")(QString(QtPrivate::qMakeStringPrivate(u"" "qt"))), QStringLiteral("_")(QString(QtPrivate::qMakeStringPrivate(u"" "_"))), path)) {
898 translated = systemTranslator.translate(context, sourceText, disambiguation, n);
899 if (!translated.isEmpty()) {
900 return translated;
901 }
902 }
903 }
904
905 return QString::fromUtf8(sourceText);
906}
907
908void MainApplication::doTriggerMenuItem(MainMenuItem menuItem)
909{
910 switch (menuItem)
911 {
912 case FileOpenDialog:
913 emit openCaptureFile(QString(), QString(), WTAP_TYPE_AUTO0);
914 break;
915 case CaptureOptionsDialog:
916 emit openCaptureOptions();
917 break;
918 }
919}
920
921void MainApplication::captureEventHandler(CaptureEvent ev)
922{
923 switch(ev.captureContext())
924 {
925#ifdef HAVE_LIBPCAP1
926 case CaptureEvent::Update:
927 case CaptureEvent::Fixed:
928 switch (ev.eventType())
929 {
930 case CaptureEvent::Prepared:
931 iface_mon_enable(true);
932 break;
933 case CaptureEvent::Started:
934 active_captures_++;
935 emit captureActive(active_captures_);
936 break;
937 case CaptureEvent::Finished:
938 active_captures_--;
939 emit captureActive(active_captures_);
940 // A refresh requested during the capture was deferred by
941 // InterfaceListManager (capture-active guard) and is serviced now via
942 // the captureActive signal above; no explicit re-trigger needed.
943 break;
944 default:
945 break;
946 }
947 break;
948#endif
949 case CaptureEvent::File:
950 case CaptureEvent::Reload:
951 case CaptureEvent::Rescan:
952 switch (ev.eventType())
953 {
954 case CaptureEvent::Started:
955 QTimer::singleShot(TAP_UPDATE_DEFAULT_INTERVAL3000 / 5, this, SLOT(updateTaps())qFlagLocation("1" "updateTaps()" "\0" "ui/qt/main_application.cpp"
":" "955")
);
956 QTimer::singleShot(TAP_UPDATE_DEFAULT_INTERVAL3000 / 2, this, SLOT(updateTaps())qFlagLocation("1" "updateTaps()" "\0" "ui/qt/main_application.cpp"
":" "956")
);
957 break;
958 case CaptureEvent::Finished:
959 updateTaps();
960 break;
961 default:
962 break;
963 }
964 break;
965 default:
966 break;
967 }
968}
969
970void MainApplication::pushStatus(StatusInfo status, const QString &message, const QString &messagetip)
971{
972 MainWindow * mw = mainWindow();
973 if (! mw) {
974 return;
975 }
976
977 MainStatusBar * bar = mw->statusBar();
978 if (! bar) {
979 return;
980 }
981
982 switch(status)
983 {
984 case FilterSyntax:
985 bar->pushGenericStatus(MainStatusBar::STATUS_CTX_FILTER, message);
986 break;
987 case FieldStatus:
988 bar->pushGenericStatus(MainStatusBar::STATUS_CTX_FIELD, message);
989 break;
990 case FileStatus:
991 bar->pushGenericStatus(MainStatusBar::STATUS_CTX_FILE, message, messagetip);
992 break;
993 case ByteStatus:
994 bar->pushGenericStatus(MainStatusBar::STATUS_CTX_BYTE, message);
995 break;
996 case BusyStatus:
997 bar->pushGenericStatus(MainStatusBar::STATUS_CTX_PROGRESS, message, messagetip);
998 break;
999 case TemporaryStatus:
1000 bar->pushGenericStatus(MainStatusBar::STATUS_CTX_TEMPORARY, message);
1001 break;
1002 }
1003}
1004
1005void MainApplication::popStatus(StatusInfo status)
1006{
1007 MainWindow * mw = mainWindow();
1008 if (! mw) {
1009 return;
1010 }
1011
1012 MainStatusBar * bar = mw->statusBar();
1013 if (! bar) {
1014 return;
1015 }
1016
1017 switch(status)
1018 {
1019 case FilterSyntax:
1020 bar->popGenericStatus(MainStatusBar::STATUS_CTX_FILTER);
1021 break;
1022 case FieldStatus:
1023 bar->popGenericStatus(MainStatusBar::STATUS_CTX_FIELD);
1024 break;
1025 case FileStatus:
1026 bar->popGenericStatus(MainStatusBar::STATUS_CTX_FILE);
1027 break;
1028 case ByteStatus:
1029 bar->popGenericStatus(MainStatusBar::STATUS_CTX_BYTE);
1030 break;
1031 case BusyStatus:
1032 bar->popGenericStatus(MainStatusBar::STATUS_CTX_PROGRESS);
1033 break;
1034 case TemporaryStatus:
1035 bar->popGenericStatus(MainStatusBar::STATUS_CTX_TEMPORARY);
1036 break;
1037 }
1038}
1039
1040void MainApplication::gotoFrame(int frame)
1041{
1042 MainWindow * mw = mainWindow();
1043 if (! mw) {
1044 return;
1045 }
1046
1047 mw->gotoFrame(frame);
1048}
1049
1050void MainApplication::reloadDisplayFilterMacros()
1051{
1052 dfilter_macro_reload(application_configuration_environment_prefix());
1053 // The signal is needed when the display filter grammar changes for
1054 // any reason (not just "fields".)
1055 mainApp->emitAppSignal(MainApplication::FieldsChanged);
1056}