Bug Summary

File:builds/wireshark/wireshark/ui/qt/main_application.cpp
Warning:line 461, 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-11-19-100337-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 <[email protected]>
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, bool reload)
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 /* Copy from global profile */
194 char *err = NULL__null;
195 if (!copy_global_profile(env_prefix, profile_name, &err)) {
196 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK0x01, "%s", err);
197 g_free(err)(__builtin_object_size ((err), 0) != ((size_t) - 1)) ? g_free_sized
(err, __builtin_object_size ((err), 0)) : (g_free) (err)
;
198 }
199 } else {
200 /* No personal and no global profile exists */
201 return;
202 }
203 }
204
205 /* Then check if changing to another profile */
206 if (!reload && profile_name && strcmp (profile_name, get_profile_name()) == 0) {
207 return;
208 }
209
210 /* Get the current geometry, before writing it to disk */
211 emit profileChanging();
212
213 if (write_recent_file && profile_exists(env_prefix, get_profile_name(), false))
214 {
215 /* Write recent file for profile we are leaving, if it still exists */
216 write_profile_recent();
217 }
218
219 // Freeze the packet list early to avoid updating column data before doing a
220 // full redissection. The packet list will be thawed when redissection is done.
221 emit freezePacketList(true);
222
223 /* Set profile name and update the status bar */
224 set_profile_name (profile_name);
225 emit profileNameChanged(profile_name);
226
227 /* Apply new preferences */
228 readConfigurationFiles(true);
229
230 /* Reading the new profile's preferences reset every registered preference,
231 * including the ones that are shared by all of our profiles. Those aren't
232 * part of the profile we're leaving, so read them back in. */
233 extcap_read_preferences();
234
235 /* Apply command-line preferences */
236 commandline_options_reapply();
237 extcap_register_preferences(NULL__null, NULL__null);
238
239 /* Switching profile requires reloading the macro list. */
240 reloadDisplayFilterMacros();
241
242 if (!recent_read_profile_static(&rf_path, &rf_open_errno)) {
243 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK0x01,
244 "Could not open common recent file\n\"%s\": %s.",
245 rf_path, g_strerror(rf_open_errno));
246 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)
;
247 }
248 FontManager::instance()->restoreZoomLevel();
249 if (recent.gui_fileopen_remembered_dir &&
250 test_for_directory(recent.gui_fileopen_remembered_dir) == EISDIR21) {
251 set_last_open_dir(recent.gui_fileopen_remembered_dir);
252 }
253 timestamp_set_type(recent.gui_time_format);
254 timestamp_set_precision(recent.gui_time_precision);
255 timestamp_set_seconds_type (recent.gui_seconds_format);
256
257 prefs_to_capture_opts(&global_capture_opts);
258 prefs_apply_all();
259#ifdef HAVE_LIBPCAP1
260 /* Re-apply interface display attributes from the new profile's prefs before
261 the preferencesChanged() emit below, so its listeners see fresh data. The
262 manager owns interface enumeration/attributes now. */
263 if (MainWindow *mw = mainWindow())
264 if (InterfaceListManager *mgr = mw->interfaceListManager())
265 mgr->reapplyInterfacePreferences();
266#endif
267
268 emit columnsChanged();
269 emit preferencesChanged();
270 emit recentPreferencesRead();
271 emit filterExpressionsChanged();
272 emit checkDisplayFilter();
273 emit captureFilterListChanged();
274 emit displayFilterListChanged();
275
276 /* Reload color filters */
277 if (!color_filters_reload(&err_msg, color_filter_add_cb, application_configuration_environment_prefix())) {
278 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK0x01, "%s", err_msg);
279 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)
;
280 }
281
282 /* Reload tag rules (profile-specific file changes; global file stays the same) */
283 tag_rules_reload();
284
285 /* Capture-interface prefs are now watched by InterfaceListManager, which
286 rescans when capture_no_interface_load / capture_no_extcap flips. A profile
287 switch can also change interface display attributes, so notify subscribers
288 (the manager owns the interface-list-changed signal now). */
289 MainWindow *mw = mainWindow();
290 if (mw && mw->interfaceListManager())
291 mw->interfaceListManager()->notifyListChanged();
292 emit packetDissectionChanged();
293
294 /* Write recent_common file to ensure last used profile setting is stored. */
295 write_recent();
296}
297
298void MainApplication::reloadLuaPluginsDelayed()
299{
300 QTimer::singleShot(0, this, [this]() {
301 /* Clear the reloading flag so the re-triggered reload
302 * is not blocked by the isReloadingLua() guard. */
303 setReloadingLua(false);
304 emit reloadLuaPlugins();
305 });
306}
307
308const QIcon &MainApplication::normalIcon()
309{
310 if (normal_icon_.isNull()) {
311 initializeIcons();
312 }
313 return normal_icon_;
314}
315
316const QIcon &MainApplication::captureIcon()
317{
318 if (capture_icon_.isNull()) {
319 initializeIcons();
320 }
321 return capture_icon_;
322}
323
324const QString MainApplication::windowTitleString(QStringList title_parts)
325{
326 QMutableStringListIterator tii(title_parts);
327 while (tii.hasNext()) {
328 QString ti = tii.next();
329 if (ti.isEmpty()) tii.remove();
330 }
331 title_parts.prepend(applicationName());
332 return title_parts.join(window_title_separator_);
333}
334
335void MainApplication::applyCustomColorsFromRecent()
336{
337 int i = 0;
338 bool ok;
339 for (GList *custom_color = recent.custom_colors; custom_color; custom_color = custom_color->next) {
340 QRgb rgb = QString((const char *)custom_color->data).toUInt(&ok, 16);
341 if (ok) {
342 QColorDialog::setCustomColor(i++, QColor(rgb));
343 }
344 }
345}
346
347// Return the first top-level MainWindow.
348MainWindow *MainApplication::mainWindow()
349{
350 foreach (QWidget *tlw, topLevelWidgets())for (auto _container_350 = QtPrivate::qMakeForeachContainer(topLevelWidgets
()); _container_350.i != _container_350.e; ++_container_350.i
) if (QWidget *tlw = *_container_350.i; false) {} else
{
351 MainWindow *tlmw = qobject_cast<MainWindow *>(tlw);
352 if (tlmw && tlmw->isVisible()) {
353 return tlmw;
354 }
355 }
356 return nullptr;
357}
358
359void MainApplication::storeCustomColorsInRecent()
360{
361 if (QColorDialog::customCount()) {
362 prefs_clear_string_list(recent.custom_colors);
363 recent.custom_colors = NULL__null;
364 for (int i = 0; i < QColorDialog::customCount(); i++) {
365 QRgb rgb = QColorDialog::customColor(i).rgb();
366 recent.custom_colors = g_list_append(recent.custom_colors, ws_strdup_printf("%08x", rgb)wmem_strdup_printf(__null, "%08x", rgb));
367 }
368 }
369}
370
371bool MainApplication::event(QEvent *event)
372{
373 QString display_filter = NULL__null;
374 if (event->type() == QEvent::FileOpen) {
375 QFileOpenEvent *foe = static_cast<QFileOpenEvent *>(event);
376 if (foe && foe->file().length() > 0) {
377 QString cf_path(foe->file());
378 if (initialized_) {
379 emit openCaptureFile(cf_path, display_filter, WTAP_TYPE_AUTO0);
380 } else {
381 pending_open_files_.append(cf_path);
382 }
383 }
384 return true;
385 }
386 return QApplication::event(event);
387}
388
389void MainApplication::cleanup()
390{
391 SoftwareUpdate::instance()->cleanup();
392 storeCustomColorsInRecent();
393 // Write the user's recent file(s) to disk.
394 write_profile_recent();
395 write_recent();
396
397 // We might end up here via exit_application.
398 QThreadPool::globalInstance()->waitForDone();
399}
400
401MainApplication::MainApplication(int &argc, char **argv) :
402 QApplication(argc, argv),
403 initialized_(false),
404 is_reloading_lua_(false),
405 if_notifier_(NULL__null),
406 active_captures_(0)
407#if defined(Q_OS_MACOS) || defined(Q_OS_WIN)
408 , normal_icon_(windowIcon())
409#endif
410{
411 mainApp = this;
412
413 MimeDatabaseInitThread *mime_db_init_thread = new(MimeDatabaseInitThread);
414 QThreadPool::globalInstance()->start(mime_db_init_thread);
415
416 Q_INIT_RESOURCE(about)do { extern int qInitResources_about (); qInitResources_about
(); } while (false)
;
1
Loop condition is false. Exiting loop
417 Q_INIT_RESOURCE(i18n)do { extern int qInitResources_i18n (); qInitResources_i18n (
); } while (false)
;
2
Loop condition is false. Exiting loop
418 Q_INIT_RESOURCE(languages)do { extern int qInitResources_languages (); qInitResources_languages
(); } while (false)
;
3
Loop condition is false. Exiting loop
419
420 // Initialize the ThemeManager as early as possible so that any
421 // widget constructed afterwards can resolve themed stylesheets and
422 // color tokens. This must run after QApplication's base ctor (so
423 // that the palette is queryable for light/dark detection) but
424 // before any UI is built. recent_common has already been read in
425 // main()/stratoshark_main() prior to constructing this application
426 // object, so we can read any configured themes as well.
427 // Theme selection is persisted in recent_common (recent.gui_theme_name),
428 // not in the preferences file — so it survives profile switches and
429 // stays global to the install. Empty / missing value, or the legacy
430 // "default" sentinel, get resolved by ThemeManager itself to the
431 // current flavor's preferred default (wireshark / stratoshark).
432 ThemeManager::init(ThemeManager::resolveThemeName(
433 QString::fromUtf8(recent.gui_theme_name)));
434
435#ifdef Q_OS_WIN
436 /* RichEd20.DLL is needed for native file dialog filter entries. */
437 ws_load_library("riched20.dll");
438#endif // Q_OS_WIN
439
440 // We use a lot of style sheets that base their colors on the main
441 // application palette, so this works better.
442 setAttribute(Qt::AA_UseStyleSheetPropagationInWidgetStyles, true);
443
444 // Throw various settings at the wall with the hope that one of them will
445 // enable context menu shortcuts QTBUG-69452, QTBUG-109590
446 setAttribute(Qt::AA_DontShowShortcutsInContextMenus, false);
447 styleHints()->setShowShortcutsInContextMenus(true);
448
449 packet_data_timer_.setParent(this);
450 connect(&packet_data_timer_, &QTimer::timeout, this, &MainApplication::refreshPacketData);
451 packet_data_timer_.start(1000);
452
453 tap_update_timer_.setParent(this);
454 // tap_update_timer interval is set when preferences are set before init
455 connect(this, &MainApplication::appInitialized, &tap_update_timer_, [&]() { tap_update_timer_.start(); });
456 connect(&tap_update_timer_, &QTimer::timeout, this, &MainApplication::updateTaps);
457
458 setStyle(new ThemeStyler);
4
Memory is allocated
459 // setStyle() rebuilds Qt's per-class font table from the platform theme,
460 // dropping the zoomed or overridden class fonts pushed by ThemeManager.
461 FontManager::instance()->reapplyApplicationFonts();
5
Potential memory leak
462
463 connect(qApp(static_cast<QApplication *>(QCoreApplication::instance
()))
, &QApplication::aboutToQuit, this, &MainApplication::cleanup);
464}
465
466MainApplication::~MainApplication()
467{
468 mainApp = NULL__null;
469 clearDynamicMenuGroupItems();
470}
471
472void MainApplication::emitAppSignal(AppSignal signal)
473{
474 switch (signal) {
475 case ColumnsChanged:
476 emit columnsChanged();
477 break;
478 case CaptureFilterListChanged:
479 emit captureFilterListChanged();
480 break;
481 case DisplayFilterListChanged:
482 emit displayFilterListChanged();
483 break;
484 case FilterExpressionsChanged:
485 emit filterExpressionsChanged();
486 break;
487 case NameResolutionChanged:
488 emit addressResolutionChanged();
489 break;
490 case PreferencesChanged:
491 tap_update_timer_.setInterval(prefs.tap_update_interval);
492 emit preferencesChanged();
493 break;
494 case PacketDissectionChanged:
495 emit packetDissectionChanged();
496 break;
497 case RecentPreferencesRead:
498 emit recentPreferencesRead();
499 break;
500 case FieldsChanged:
501 emit fieldsChanged();
502 break;
503 case FreezePacketList:
504 emit freezePacketList(false);
505 break;
506 case AggregationChanged:
507 emit aggregationChanged();
508 break;
509 default:
510 break;
511 }
512}
513
514// Flush any collected app signals.
515//
516// On macOS emitting PacketDissectionChanged from a dialog can
517// render the application unusable:
518// https://gitlab.com/wireshark/wireshark/-/issues/11361
519// https://gitlab.com/wireshark/wireshark/-/issues/11448
520// Work around the problem by queueing up app signals and emitting them
521// after the dialog is closed.
522//
523// The following bugs might be related although they don't describe the
524// exact behavior we're working around here:
525// https://bugreports.qt.io/browse/QTBUG-38512
526// https://bugreports.qt.io/browse/QTBUG-38600
527void MainApplication::flushAppSignals()
528{
529 while (!app_signals_.isEmpty()) {
530 mainApp->emitAppSignal(app_signals_.takeFirst());
531 }
532}
533
534void MainApplication::emitStatCommandSignal(const QString &menu_path, const char *arg, void *userdata)
535{
536 emit openStatCommandDialog(menu_path, arg, userdata);
537}
538
539void MainApplication::emitTapParameterSignal(const QString cfg_abbr, const QString arg, void *userdata)
540{
541 emit openTapParameterDialog(cfg_abbr, arg, userdata);
542}
543
544// XXX Combine statistics and funnel routines into addGroupItem + groupItems?
545void MainApplication::addDynamicMenuGroupItem(int group, QAction *sg_action)
546{
547 if (!dynamic_menu_groups_.contains(group)) {
548 dynamic_menu_groups_[group] = QList<QAction *>();
549 }
550 dynamic_menu_groups_[group] << sg_action;
551}
552
553void MainApplication::appendDynamicMenuGroupItem(int group, QAction *sg_action)
554{
555 if (!added_menu_groups_.contains(group)) {
556 added_menu_groups_[group] = QList<QAction *>();
557 }
558 added_menu_groups_[group] << sg_action;
559 addDynamicMenuGroupItem(group, sg_action);
560}
561
562void MainApplication::removeDynamicMenuGroupItem(int group, QAction *sg_action)
563{
564 if (!removed_menu_groups_.contains(group)) {
565 removed_menu_groups_[group] = QList<QAction *>();
566 }
567 removed_menu_groups_[group] << sg_action;
568 dynamic_menu_groups_[group].removeAll(sg_action);
569}
570
571void MainApplication::clearDynamicMenuGroupItems()
572{
573 foreach (int group, dynamic_menu_groups_.keys())for (auto _container_573 = QtPrivate::qMakeForeachContainer(dynamic_menu_groups_
.keys()); _container_573.i != _container_573.e; ++_container_573
.i) if (int group = *_container_573.i; false) {} else
{
574 dynamic_menu_groups_[group].clear();
575 }
576}
577
578QList<QAction *> MainApplication::dynamicMenuGroupItems(int group)
579{
580 if (!dynamic_menu_groups_.contains(group)) {
581 return QList<QAction *>();
582 }
583
584 QList<QAction *> sgi_list = dynamic_menu_groups_[group];
585 std::sort(sgi_list.begin(), sgi_list.end(), qActionLessThan);
586 return sgi_list;
587}
588
589QList<QAction *> MainApplication::addedMenuGroupItems(int group)
590{
591 if (!added_menu_groups_.contains(group)) {
592 return QList<QAction *>();
593 }
594
595 QList<QAction *> sgi_list = added_menu_groups_[group];
596 std::sort(sgi_list.begin(), sgi_list.end(), qActionLessThan);
597 return sgi_list;
598}
599
600QList<QAction *> MainApplication::removedMenuGroupItems(int group)
601{
602 if (!removed_menu_groups_.contains(group)) {
603 return QList<QAction *>();
604 }
605
606 QList<QAction *> sgi_list = removed_menu_groups_[group];
607 std::sort(sgi_list.begin(), sgi_list.end(), qActionLessThan);
608 return sgi_list;
609}
610
611void MainApplication::clearAddedMenuGroupItems()
612{
613 foreach (int group, added_menu_groups_.keys())for (auto _container_613 = QtPrivate::qMakeForeachContainer(added_menu_groups_
.keys()); _container_613.i != _container_613.e; ++_container_613
.i) if (int group = *_container_613.i; false) {} else
{
614 added_menu_groups_[group].clear();
615 }
616}
617
618void MainApplication::clearRemovedMenuGroupItems()
619{
620 foreach (int group, removed_menu_groups_.keys())for (auto _container_620 = QtPrivate::qMakeForeachContainer(removed_menu_groups_
.keys()); _container_620.i != _container_620.e; ++_container_620
.i) if (int group = *_container_620.i; false) {} else
{
621 foreach (QAction *action, removed_menu_groups_[group])for (auto _container_621 = QtPrivate::qMakeForeachContainer(removed_menu_groups_
[group]); _container_621.i != _container_621.e; ++_container_621
.i) if (QAction *action = *_container_621.i; false) {} else
{
622 delete action;
623 }
624 removed_menu_groups_[group].clear();
625 }
626}
627
628#ifdef HAVE_LIBPCAP1
629
630static void
631iface_mon_event_cb(const char *iface, int added, int up)
632{
633 int present = 0;
634 unsigned ifs, j;
635 interface_t *device;
636 interface_options *interface_opts;
637
638 for (ifs = 0; ifs < global_capture_opts.all_ifaces->len; ifs++) {
639 device = &g_array_index(global_capture_opts.all_ifaces, interface_t, ifs)(((interface_t*) (void *) (global_capture_opts.all_ifaces)->
data) [(ifs)])
;
640 if (strcmp(device->name, iface) == 0) {
641 present = 1;
642 if (!up) {
643 /*
644 * Interface went down or disappeared; remove all instances
645 * of it from the current list of interfaces selected
646 * for capturing.
647 */
648 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
649 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j)(((interface_options*) (void *) (global_capture_opts.ifaces)->
data) [(j)])
;
650 if (strcmp(interface_opts->name, device->name) == 0) {
651 capture_opts_del_iface(&global_capture_opts, j);
652 }
653 }
654 }
655 }
656 }
657
658 mainApp->emitLocalInterfaceEvent(iface, added, up);
659 if (present != up) {
660 /*
661 * We've been told that there's a new interface or that an old
662 * interface is gone; reload the local interface list.
663 *
664 * XXX: We also want to reload the local interface list if [what
665 * we can retrieve about] the capabilities of the device have changed.
666 * Ideally we'd update the capabilities of just the one device in
667 * the cache and signal that the list has been updated, instead of
668 * freeing the entire cache and scanning again - but some extcaps
669 * depend on other interfaces being up; e.g. by default androiddump
670 * tries to connect to the loopback interface to look for adb running,
671 * so if the loopback interface changes so does the status of
672 * androiddump.
673 *
674 * On Linux, at least, you can't get the capabilities from a down
675 * interface, but it's still present in all_ifaces - dumpcap returns
676 * it in the list, and we show it so the user can get a status / error
677 * message when trying to capture on it instead of it vanishing.
678 * So if both present and up are true, then we still want to refresh
679 * to update the capabilities and restart the stats.
680 *
681 * We also store the address in all_ifaces and show them to the user,
682 * so we probably should monitor those events as well and update
683 * the interface list appropriately when those change.
684 */
685 MainWindow *mainWindow = mainApp->mainWindow();
686 if (mainWindow && mainWindow->interfaceListManager())
687 mainWindow->interfaceListManager()->requestRefresh();
688 }
689}
690
691#endif
692
693void MainApplication::ifChangeEventsAvailable()
694{
695#ifdef HAVE_LIBPCAP1
696 /*
697 * Something's readable from the descriptor for interface
698 * monitoring.
699 *
700 * Have the interface-monitoring code Read whatever interface-change
701 * events are available, and call the callback for them.
702 */
703 iface_mon_event();
704#endif
705}
706
707void MainApplication::emitLocalInterfaceEvent(const char *ifname, int added, int up)
708{
709 emit localInterfaceEvent(ifname, added, up);
710}
711
712void MainApplication::whenInitializedDispatch(const QObject *context, std::function<void()> fn)
713{
714 // POLICY DECISION (your input shapes behavior here):
715 //
716 // We get here only when a caller registers via whenInitialized() *after*
717 // appInitialized() has already fired. The not-yet-initialized path runs the
718 // callback later, from the event loop, once construction is long finished.
719 // How should the already-initialized path behave?
720 //
721 // A) Synchronous: fn(); right now. Simplest. But the callback runs while
722 // the caller's constructor is still on the stack -- the object may be
723 // only partly built, and any code after the whenInitialized() call in
724 // that constructor runs *after* the callback. Timing differs from the
725 // deferred path.
726 //
727 // B) Deferred to the event loop (e.g. QTimer::singleShot(0, context, fn)
728 // or QMetaObject::invokeMethod(..., Qt::QueuedConnection)): callback
729 // always runs after the current call returns, matching the signal path
730 // exactly, so callers see one consistent ordering. Costs one event-loop
731 // turn and needs the context-still-alive guarantee.
732 //
733 // Option A (current behavior) is intentional for now: it exactly reproduces
734 // the old open-coded `if (isInitialized()) doThing();` -- a synchronous call
735 // on the caller's stack -- so routing those sites through whenInitialized()
736 // is a pure no-op refactor. Option B is the intended end state, but it
737 // shifts the already-initialized callback by one event-loop turn and so
738 // changes ordering for every converted site at once; switch to it only
739 // behind broader ordering/lifetime tests (dialogs opened mid-session,
740 // welcome/interface frames at cold start, context destroyed same-turn).
741 //
742 // To switch, delete the fn() below and enable the deferred dispatch:
743 //
744 // QTimer::singleShot(0, const_cast<QObject *>(context), std::move(fn));
745 //
746 // (context is the receiver, so the call is dropped if it dies first, and
747 // runs on context's thread -- matching the connect() branch.)
748 Q_UNUSED(context)(void)context; // option A ignores context; option B uses it.
749 fn(); // option A: synchronous, matches legacy behavior.
750}
751
752void MainApplication::allSystemsGo()
753{
754 QString display_filter = NULL__null;
755 initialized_ = true;
756 emit appInitialized();
757 while (pending_open_files_.length() > 0) {
758 emit openCaptureFile(pending_open_files_.front(), display_filter, WTAP_TYPE_AUTO0);
759 pending_open_files_.pop_front();
760 }
761
762 bool sideBarVisible = recent.gui_welcome_page_sidebar_tips_visible ||
763 recent.gui_welcome_page_sidebar_learn_visible;
764 SoftwareUpdate::instance()->init(!sideBarVisible);
765
766#ifdef HAVE_LIBPCAP1
767 int err;
768 err = iface_mon_start(&iface_mon_event_cb);
769 if (err == 0) {
770 if_notifier_ = new QSocketNotifier(iface_mon_get_sock(),
771 QSocketNotifier::Read, this);
772 connect(if_notifier_, &QSocketNotifier::activated, this, &MainApplication::ifChangeEventsAvailable);
773 }
774#endif
775}
776
777_e_prefs *MainApplication::readConfigurationFiles(bool reset)
778{
779 e_prefs *prefs_p;
780
781 if (reset) {
782 //
783 // Reset current preferences and enabled/disabled protocols and
784 // heuristic dissectors before reading.
785 // (Needed except when this is called at startup.)
786 //
787 prefs_reset(application_configuration_environment_prefix(), application_columns(), application_num_columns());
788 proto_reenable_all();
789 }
790
791 /* Load libwireshark settings from the current profile. */
792 prefs_p = epan_load_settings();
793
794 return prefs_p;
795}
796
797static void switchTranslator(QTranslator& myTranslator, const QLocale &locale, const QString& filename, const QStringList &searchPath)
798{
799 mainApp->removeTranslator(&myTranslator);
800 for (const QString &path : searchPath) {
801 if (myTranslator.load(locale, filename, QStringLiteral("_")(QString(QtPrivate::qMakeStringPrivate(u"" "_"))), path)) {
802 mainApp->installTranslator(&myTranslator);
803 return;
804 }
805 }
806 if (locale.language() != QLocale::C) {
807 /* Don't compare the locale itself, see:
808 * https://doc.qt.io/qt-6/qlocale.html#operator-eq-eq
809 *
810 * Note that the ordered list of languages that were tried is that of
811 * locale.uiLanguages(); the first language in that list is not
812 * necessarily locale.language(), especially on Windows (See #17221.)
813 */
814 qWarningQMessageLogger(static_cast<const char *>("ui/qt/main_application.cpp"
), 814, static_cast<const char *>(__PRETTY_FUNCTION__))
.warning
() << "Couldn't load" << filename << "translations." << "Searched:" << searchPath;
815 }
816}
817
818QStringList MainApplication::getTranslationsPaths() const
819{
820 const char* env_prefix = application_configuration_environment_prefix();
821
822 // Search path list ordered by priority. Prefer personal configuration
823 // to global datadir to embedded resources to Qt global directory.
824 QStringList searchPath;
825 searchPath.emplaceBack(gchar_free_to_qstring(get_persconffile_path("languages", false, env_prefix)));
826 searchPath.emplaceBack(QStringLiteral("%1/languages")(QString(QtPrivate::qMakeStringPrivate(u"" "%1/languages"))).arg(get_datafile_dir(env_prefix)));
827 searchPath.emplaceBack(QStringLiteral(":/i18n/")(QString(QtPrivate::qMakeStringPrivate(u"" ":/i18n/"))));
828
829#if QT_VERSION((6<<16)|(10<<8)|(2)) >= QT_VERSION_CHECK(6, 8, 0)((6<<16)|(8<<8)|(0))
830 searchPath.append(QLibraryInfo::paths(QLibraryInfo::TranslationsPath));
831#else
832 searchPath.emplaceBack(QLibraryInfo::path(QLibraryInfo::TranslationsPath));
833#endif
834
835 return searchPath;
836}
837
838void MainApplication::loadLanguage(const QString newLanguage)
839{
840 QLocale locale;
841
842 if (newLanguage.isEmpty() || newLanguage == USE_SYSTEM_LANGUAGE"system") {
843 locale = QLocale::system();
844 } else {
845 locale = QLocale(newLanguage);
846 }
847
848 QLocale::setDefault(locale);
849
850 QStringList searchPath = getTranslationsPaths();
851
852 // Translations are searched for in the reverse order in which they were
853 // installed, so install the Qt generic translator first and ours last.
854 switchTranslator(mainApp->translatorQt, locale, QStringLiteral("qt")(QString(QtPrivate::qMakeStringPrivate(u"" "qt"))), searchPath);
855
856 // XXX - Yes, the translation files are also wireshark_%1.qm for Stratoshark.
857 // There is a stratoshark_en.[ts|qm] file too (for plurals?) though I'm
858 // not sure if it's used properly.
859 switchTranslator(mainApp->translator, locale, QStringLiteral("wireshark")(QString(QtPrivate::qMakeStringPrivate(u"" "wireshark"))), searchPath);
860}
861
862QString MainApplication::translateSystemLocale(const char *context, const char *sourceText, const char *disambiguation, int n) const
863{
864 // If we called this a lot, we could store the system QTranslators as
865 // member variables, but we only call this when constructing the
866 // language preference QComboBox.
867 QTranslator systemTranslator;
868 QString translated;
869 QStringList searchPath = getTranslationsPaths();
870
871 // Search in our translations first
872 for (const QString &path : searchPath) {
873 if (systemTranslator.load(QLocale::system(), QStringLiteral("wireshark")(QString(QtPrivate::qMakeStringPrivate(u"" "wireshark"))), QStringLiteral("_")(QString(QtPrivate::qMakeStringPrivate(u"" "_"))), path)) {
874 translated = systemTranslator.translate(context, sourceText, disambiguation, n);
875 if (!translated.isEmpty()) {
876 return translated;
877 }
878 }
879 }
880
881 // Try the generic Qt translations
882 for (const QString &path : searchPath) {
883 if (systemTranslator.load(QLocale::system(), QStringLiteral("qt")(QString(QtPrivate::qMakeStringPrivate(u"" "qt"))), QStringLiteral("_")(QString(QtPrivate::qMakeStringPrivate(u"" "_"))), path)) {
884 translated = systemTranslator.translate(context, sourceText, disambiguation, n);
885 if (!translated.isEmpty()) {
886 return translated;
887 }
888 }
889 }
890
891 return QString::fromUtf8(sourceText);
892}
893
894void MainApplication::doTriggerMenuItem(MainMenuItem menuItem)
895{
896 switch (menuItem)
897 {
898 case FileOpenDialog:
899 emit openCaptureFile(QString(), QString(), WTAP_TYPE_AUTO0);
900 break;
901 case CaptureOptionsDialog:
902 emit openCaptureOptions();
903 break;
904 }
905}
906
907void MainApplication::captureEventHandler(CaptureEvent ev)
908{
909 switch(ev.captureContext())
910 {
911#ifdef HAVE_LIBPCAP1
912 case CaptureEvent::Update:
913 case CaptureEvent::Fixed:
914 switch (ev.eventType())
915 {
916 case CaptureEvent::Prepared:
917 iface_mon_enable(true);
918 break;
919 case CaptureEvent::Started:
920 active_captures_++;
921 emit captureActive(active_captures_);
922 break;
923 case CaptureEvent::Finished:
924 active_captures_--;
925 emit captureActive(active_captures_);
926 // A refresh requested during the capture was deferred by
927 // InterfaceListManager (capture-active guard) and is serviced now via
928 // the captureActive signal above; no explicit re-trigger needed.
929 break;
930 default:
931 break;
932 }
933 break;
934#endif
935 case CaptureEvent::File:
936 case CaptureEvent::Reload:
937 case CaptureEvent::Rescan:
938 switch (ev.eventType())
939 {
940 case CaptureEvent::Started:
941 QTimer::singleShot(TAP_UPDATE_DEFAULT_INTERVAL3000 / 5, this, SLOT(updateTaps())qFlagLocation("1" "updateTaps()" "\0" "ui/qt/main_application.cpp"
":" "941")
);
942 QTimer::singleShot(TAP_UPDATE_DEFAULT_INTERVAL3000 / 2, this, SLOT(updateTaps())qFlagLocation("1" "updateTaps()" "\0" "ui/qt/main_application.cpp"
":" "942")
);
943 break;
944 case CaptureEvent::Finished:
945 updateTaps();
946 break;
947 default:
948 break;
949 }
950 break;
951 default:
952 break;
953 }
954}
955
956void MainApplication::pushStatus(StatusInfo status, const QString &message, const QString &messagetip)
957{
958 MainWindow * mw = mainWindow();
959 if (! mw) {
960 return;
961 }
962
963 MainStatusBar * bar = mw->statusBar();
964 if (! bar) {
965 return;
966 }
967
968 switch(status)
969 {
970 case FilterSyntax:
971 bar->pushGenericStatus(MainStatusBar::STATUS_CTX_FILTER, message);
972 break;
973 case FieldStatus:
974 bar->pushGenericStatus(MainStatusBar::STATUS_CTX_FIELD, message);
975 break;
976 case FileStatus:
977 bar->pushGenericStatus(MainStatusBar::STATUS_CTX_FILE, message, messagetip);
978 break;
979 case ByteStatus:
980 bar->pushGenericStatus(MainStatusBar::STATUS_CTX_BYTE, message);
981 break;
982 case BusyStatus:
983 bar->pushGenericStatus(MainStatusBar::STATUS_CTX_PROGRESS, message, messagetip);
984 break;
985 case TemporaryStatus:
986 bar->pushGenericStatus(MainStatusBar::STATUS_CTX_TEMPORARY, message);
987 break;
988 }
989}
990
991void MainApplication::popStatus(StatusInfo status)
992{
993 MainWindow * mw = mainWindow();
994 if (! mw) {
995 return;
996 }
997
998 MainStatusBar * bar = mw->statusBar();
999 if (! bar) {
1000 return;
1001 }
1002
1003 switch(status)
1004 {
1005 case FilterSyntax:
1006 bar->popGenericStatus(MainStatusBar::STATUS_CTX_FILTER);
1007 break;
1008 case FieldStatus:
1009 bar->popGenericStatus(MainStatusBar::STATUS_CTX_FIELD);
1010 break;
1011 case FileStatus:
1012 bar->popGenericStatus(MainStatusBar::STATUS_CTX_FILE);
1013 break;
1014 case ByteStatus:
1015 bar->popGenericStatus(MainStatusBar::STATUS_CTX_BYTE);
1016 break;
1017 case BusyStatus:
1018 bar->popGenericStatus(MainStatusBar::STATUS_CTX_PROGRESS);
1019 break;
1020 case TemporaryStatus:
1021 bar->popGenericStatus(MainStatusBar::STATUS_CTX_TEMPORARY);
1022 break;
1023 }
1024}
1025
1026void MainApplication::gotoFrame(int frame)
1027{
1028 MainWindow * mw = mainWindow();
1029 if (! mw) {
1030 return;
1031 }
1032
1033 mw->gotoFrame(frame);
1034}
1035
1036void MainApplication::reloadDisplayFilterMacros()
1037{
1038 dfilter_macro_reload(application_configuration_environment_prefix());
1039 // The signal is needed when the display filter grammar changes for
1040 // any reason (not just "fields".)
1041 mainApp->emitAppSignal(MainApplication::FieldsChanged);
1042}