Bug Summary

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