Always use the same limits when parse bencoded data
[qBittorrent.git] / src / app / main.cpp
blob1e95075f4eb07ffc7ad58a5f5d6d5855a01f3fad
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2014 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * In addition, as a special exception, the copyright holders give permission to
21 * link this program with the OpenSSL project's "OpenSSL" library (or with
22 * modified versions of it that use the same license as the "OpenSSL" library),
23 * and distribute the linked executables. You must obey the GNU General Public
24 * License in all respects for all of the code used other than "OpenSSL". If you
25 * modify file(s), you may extend this exception to your version of the file(s),
26 * but you are not obligated to do so. If you do not wish to do so, delete this
27 * exception statement from your version.
30 #include <QtGlobal>
32 #include <chrono>
33 #include <cstdlib>
34 #include <memory>
36 #ifdef Q_OS_UNIX
37 #include <sys/resource.h>
38 #endif
40 #ifndef Q_OS_WIN
41 #ifndef Q_OS_HAIKU
42 #include <unistd.h>
43 #endif // Q_OS_HAIKU
44 #elif defined DISABLE_GUI
45 #include <io.h>
46 #endif
48 #include <QCoreApplication>
49 #include <QDebug>
50 #include <QThread>
52 #ifndef DISABLE_GUI
53 // GUI-only includes
54 #include <QFont>
55 #include <QMessageBox>
56 #include <QPainter>
57 #include <QPen>
58 #include <QPushButton>
59 #include <QSplashScreen>
60 #include <QTimer>
62 #ifdef QBT_STATIC_QT
63 #include <QtPlugin>
64 Q_IMPORT_PLUGIN(QICOPlugin)
65 #endif // QBT_STATIC_QT
67 #else // DISABLE_GUI
68 #include <cstdio>
69 #endif // DISABLE_GUI
71 #include "base/global.h"
72 #include "base/preferences.h"
73 #include "base/profile.h"
74 #include "base/version.h"
75 #include "application.h"
76 #include "cmdoptions.h"
77 #include "signalhandler.h"
78 #include "upgrade.h"
80 #ifndef DISABLE_GUI
81 #include "gui/utils.h"
82 #endif
84 using namespace std::chrono_literals;
86 void displayVersion();
87 bool userAgreesWithLegalNotice();
88 void displayBadArgMessage(const QString &message);
90 #ifndef DISABLE_GUI
91 void showSplashScreen();
92 #endif // DISABLE_GUI
94 #ifdef Q_OS_UNIX
95 void adjustFileDescriptorLimit();
96 #endif
98 // Main
99 int main(int argc, char *argv[])
101 #ifdef Q_OS_UNIX
102 adjustFileDescriptorLimit();
103 #endif
105 // We must save it here because QApplication constructor may change it
106 bool isOneArg = (argc == 2);
108 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && !defined(DISABLE_GUI)
109 // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
110 if (qgetenv("QT_ENABLE_HIGHDPI_SCALING").isEmpty() && qgetenv("QT_AUTO_SCREEN_SCALE_FACTOR").isEmpty())
111 Application::setAttribute(Qt::AA_EnableHighDpiScaling, true);
112 // HighDPI scale factor policy must be set before QGuiApplication is created
113 if (qgetenv("QT_SCALE_FACTOR_ROUNDING_POLICY").isEmpty())
114 Application::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
115 #endif
119 // Create Application
120 auto app = std::make_unique<Application>(argc, argv);
122 #ifdef Q_OS_WIN
123 // QCoreApplication::applicationDirPath() needs an Application object instantiated first
124 // Let's hope that there won't be a crash before this line
125 const char *envName = "_NT_SYMBOL_PATH";
126 const QString envValue = qEnvironmentVariable(envName);
127 if (envValue.isEmpty())
128 qputenv(envName, Application::applicationDirPath().toLocal8Bit());
129 else
130 qputenv(envName, u"%1;%2"_s.arg(envValue, Application::applicationDirPath()).toLocal8Bit());
131 #endif
133 const QBtCommandLineParameters params = app->commandLineArgs();
134 if (!params.unknownParameter.isEmpty())
136 throw CommandLineParameterError(QCoreApplication::translate("Main", "%1 is an unknown command line parameter.",
137 "--random-parameter is an unknown command line parameter.")
138 .arg(params.unknownParameter));
140 #if !defined(Q_OS_WIN) || defined(DISABLE_GUI)
141 if (params.showVersion)
143 if (isOneArg)
145 displayVersion();
146 return EXIT_SUCCESS;
148 throw CommandLineParameterError(QCoreApplication::translate("Main", "%1 must be the single command line parameter.")
149 .arg(u"-v (or --version)"_s));
151 #endif
152 if (params.showHelp)
154 if (isOneArg)
156 displayUsage(QString::fromLocal8Bit(argv[0]));
157 return EXIT_SUCCESS;
159 throw CommandLineParameterError(QCoreApplication::translate("Main", "%1 must be the single command line parameter.")
160 .arg(u"-h (or --help)"_s));
163 const bool firstTimeUser = !Preferences::instance()->getAcceptedLegal();
164 if (firstTimeUser)
166 #ifndef DISABLE_GUI
167 if (!userAgreesWithLegalNotice())
168 return EXIT_SUCCESS;
169 #elif defined(Q_OS_WIN)
170 if (_isatty(_fileno(stdin))
171 && _isatty(_fileno(stdout))
172 && !userAgreesWithLegalNotice())
173 return EXIT_SUCCESS;
174 #else
175 if (!params.shouldDaemonize
176 && isatty(fileno(stdin))
177 && isatty(fileno(stdout))
178 && !userAgreesWithLegalNotice())
179 return EXIT_SUCCESS;
180 #endif
182 setCurrentMigrationVersion();
185 // Check if qBittorrent is already running for this user
186 if (app->isRunning())
188 #if defined(DISABLE_GUI) && !defined(Q_OS_WIN)
189 if (params.shouldDaemonize)
191 throw CommandLineParameterError(QCoreApplication::translate("Main", "You cannot use %1: qBittorrent is already running for this user.")
192 .arg(u"-d (or --daemon)"_s));
194 #endif
196 QThread::msleep(300);
197 app->callMainInstance();
199 return EXIT_SUCCESS;
202 #ifdef Q_OS_WIN
203 // This affects only Windows apparently and Qt5.
204 // When QNetworkAccessManager is instantiated it regularly starts polling
205 // the network interfaces to see what's available and their status.
206 // This polling creates jitter and high ping with wifi interfaces.
207 // So here we disable it for lack of better measure.
208 // It will also spew this message in the console: QObject::startTimer: Timers cannot have negative intervals
209 // For more info see:
210 // 1. https://github.com/qbittorrent/qBittorrent/issues/4209
211 // 2. https://bugreports.qt.io/browse/QTBUG-40332
212 // 3. https://bugreports.qt.io/browse/QTBUG-46015
214 qputenv("QT_BEARER_POLL_TIMEOUT", QByteArray::number(-1));
215 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && !defined(DISABLE_GUI)
216 // this is the default in Qt6
217 app->setAttribute(Qt::AA_DisableWindowContextHelpButton);
218 #endif
219 #endif // Q_OS_WIN
221 #ifdef Q_OS_MACOS
222 // Since Apple made difficult for users to set PATH, we set here for convenience.
223 // Users are supposed to install Homebrew Python for search function.
224 // For more info see issue #5571.
225 QByteArray path = "/usr/local/bin:";
226 path += qgetenv("PATH");
227 qputenv("PATH", path.constData());
229 // On OS X the standard is to not show icons in the menus
230 app->setAttribute(Qt::AA_DontShowIconsInMenus);
231 #else
232 if (!Preferences::instance()->iconsInMenusEnabled())
233 app->setAttribute(Qt::AA_DontShowIconsInMenus);
234 #endif
236 #if defined(DISABLE_GUI) && !defined(Q_OS_WIN)
237 if (params.shouldDaemonize)
239 app.reset(); // Destroy current application
240 if (daemon(1, 0) == 0)
242 app = std::make_unique<Application>(argc, argv);
243 if (app->isRunning())
245 // Another instance had time to start.
246 return EXIT_FAILURE;
249 else
251 qCritical("Something went wrong while daemonizing, exiting...");
252 return EXIT_FAILURE;
255 #elif !defined(DISABLE_GUI)
256 if (!(params.noSplash || Preferences::instance()->isSplashScreenDisabled()))
257 showSplashScreen();
258 #endif
260 registerSignalHandlers();
262 return app->exec();
264 catch (const CommandLineParameterError &er)
266 displayBadArgMessage(er.message());
267 return EXIT_FAILURE;
269 catch (const RuntimeError &er)
271 qDebug() << er.message();
272 return EXIT_FAILURE;
276 #if !defined(DISABLE_GUI)
277 void showSplashScreen()
279 QPixmap splashImg(u":/icons/splash.png"_s);
280 QPainter painter(&splashImg);
281 const auto version = QStringLiteral(QBT_VERSION);
282 painter.setPen(QPen(Qt::white));
283 painter.setFont(QFont(u"Arial"_s, 22, QFont::Black));
284 painter.drawText(224 - painter.fontMetrics().horizontalAdvance(version), 270, version);
285 QSplashScreen *splash = new QSplashScreen(splashImg);
286 splash->show();
287 QTimer::singleShot(1500ms, Qt::CoarseTimer, splash, &QObject::deleteLater);
288 qApp->processEvents();
290 #endif // DISABLE_GUI
292 void displayVersion()
294 printf("%s %s\n", qUtf8Printable(qApp->applicationName()), QBT_VERSION);
297 void displayBadArgMessage(const QString &message)
299 const QString help = QCoreApplication::translate("Main", "Run application with -h option to read about command line parameters.");
300 #if defined(Q_OS_WIN) && !defined(DISABLE_GUI)
301 QMessageBox msgBox(QMessageBox::Critical, QCoreApplication::translate("Main", "Bad command line"),
302 (message + u'\n' + help), QMessageBox::Ok);
303 msgBox.show(); // Need to be shown or to moveToCenter does not work
304 msgBox.move(Utils::Gui::screenCenter(&msgBox));
305 msgBox.exec();
306 #else
307 const QString errMsg = QCoreApplication::translate("Main", "Bad command line: ") + u'\n'
308 + message + u'\n'
309 + help + u'\n';
310 fprintf(stderr, "%s", qUtf8Printable(errMsg));
311 #endif
314 bool userAgreesWithLegalNotice()
316 Preferences *const pref = Preferences::instance();
317 Q_ASSERT(!pref->getAcceptedLegal());
319 #ifdef DISABLE_GUI
320 const QString eula = u"\n*** %1 ***\n"_s.arg(QCoreApplication::translate("Main", "Legal Notice"))
321 + QCoreApplication::translate("Main", "qBittorrent is a file sharing program. When you run a torrent, its data will be made available to others by means of upload. Any content you share is your sole responsibility.") + u"\n\n"
322 + QCoreApplication::translate("Main", "No further notices will be issued.") + u"\n\n"
323 + QCoreApplication::translate("Main", "Press %1 key to accept and continue...").arg(u"'y'"_s) + u'\n';
324 printf("%s", qUtf8Printable(eula));
326 const char ret = getchar(); // Read pressed key
327 if ((ret == 'y') || (ret == 'Y'))
329 // Save the answer
330 pref->setAcceptedLegal(true);
331 return true;
333 #else
334 QMessageBox msgBox;
335 msgBox.setText(QCoreApplication::translate("Main", "qBittorrent is a file sharing program. When you run a torrent, its data will be made available to others by means of upload. Any content you share is your sole responsibility.\n\nNo further notices will be issued."));
336 msgBox.setWindowTitle(QCoreApplication::translate("Main", "Legal notice"));
337 msgBox.addButton(QCoreApplication::translate("Main", "Cancel"), QMessageBox::RejectRole);
338 const QAbstractButton *agreeButton = msgBox.addButton(QCoreApplication::translate("Main", "I Agree"), QMessageBox::AcceptRole);
339 msgBox.show(); // Need to be shown or to moveToCenter does not work
340 msgBox.move(Utils::Gui::screenCenter(&msgBox));
341 msgBox.exec();
342 if (msgBox.clickedButton() == agreeButton)
344 // Save the answer
345 pref->setAcceptedLegal(true);
346 return true;
348 #endif // DISABLE_GUI
350 return false;
353 #ifdef Q_OS_UNIX
354 void adjustFileDescriptorLimit()
356 rlimit limit {};
358 if (getrlimit(RLIMIT_NOFILE, &limit) != 0)
359 return;
361 limit.rlim_cur = limit.rlim_max;
362 setrlimit(RLIMIT_NOFILE, &limit);
364 #endif