logs.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include "logs.h"
  8. #include "platform/platform_specific.h"
  9. #include "core/crash_reports.h"
  10. #include "core/launcher.h"
  11. #include "mtproto/facade.h"
  12. namespace {
  13. std::atomic<int> ThreadCounter/* = 0*/;
  14. thread_local bool WritingEntryFlag/* = false*/;
  15. class WritingEntryScope final {
  16. public:
  17. WritingEntryScope() {
  18. WritingEntryFlag = true;
  19. }
  20. ~WritingEntryScope() {
  21. WritingEntryFlag = false;
  22. }
  23. };
  24. } // namespace
  25. enum LogDataType {
  26. LogDataMain,
  27. LogDataDebug,
  28. LogDataTcp,
  29. LogDataMtp,
  30. LogDataCount
  31. };
  32. QMutex *_logsMutex(LogDataType type, bool clear = false) {
  33. static QMutex *LogsMutexes = 0;
  34. if (clear) {
  35. delete[] LogsMutexes;
  36. LogsMutexes = 0;
  37. } else if (!LogsMutexes) {
  38. LogsMutexes = new QMutex[LogDataCount];
  39. }
  40. return &LogsMutexes[type];
  41. }
  42. QString _logsFilePath(LogDataType type, const QString &postfix = QString()) {
  43. QString path(cWorkingDir());
  44. switch (type) {
  45. case LogDataMain: path += u"log"_q + postfix + u".txt"_q; break;
  46. case LogDataDebug: path += u"DebugLogs/log"_q + postfix + u".txt"_q; break;
  47. case LogDataTcp: path += u"DebugLogs/tcp"_q + postfix + u".txt"_q; break;
  48. case LogDataMtp: path += u"DebugLogs/mtp"_q + postfix + u".txt"_q; break;
  49. }
  50. return path;
  51. }
  52. int32 LogsStartIndexChosen = -1;
  53. QString _logsEntryStart() {
  54. static thread_local auto threadId = ThreadCounter++;
  55. static auto index = 0;
  56. const auto tm = QDateTime::currentDateTime();
  57. return QString("[%1 %2-%3]").arg(tm.toString("hh:mm:ss.zzz"), QString("%1").arg(threadId, 2, 10, QChar('0'))).arg(++index, 7, 10, QChar('0'));
  58. }
  59. class LogsDataFields {
  60. public:
  61. LogsDataFields() {
  62. for (int32 i = 0; i < LogDataCount; ++i) {
  63. files[i].reset(new QFile());
  64. }
  65. }
  66. bool openMain() {
  67. return reopen(LogDataMain, 0, u"start"_q);
  68. }
  69. void closeMain() {
  70. QMutexLocker lock(_logsMutex(LogDataMain));
  71. WritingEntryScope scope;
  72. const auto file = files[LogDataMain].get();
  73. if (file && file->isOpen()) {
  74. file->close();
  75. }
  76. }
  77. bool instanceChecked() {
  78. return reopen(LogDataMain, 0, QString());
  79. }
  80. QString full() {
  81. const auto file = files[LogDataMain].get();
  82. if (!file || !file->isOpen()) {
  83. return QString();
  84. }
  85. QFile out(file->fileName());
  86. if (out.open(QIODevice::ReadOnly)) {
  87. return QString::fromUtf8(out.readAll());
  88. }
  89. return QString();
  90. }
  91. void write(LogDataType type, const QString &msg) {
  92. QMutexLocker lock(_logsMutex(type));
  93. WritingEntryScope scope;
  94. if (type != LogDataMain) {
  95. reopenDebug();
  96. }
  97. const auto file = files[type].get();
  98. if (!file || !file->isOpen()) {
  99. return;
  100. }
  101. file->write(msg.toUtf8());
  102. file->flush();
  103. }
  104. private:
  105. std::unique_ptr<QFile> files[LogDataCount];
  106. int32 part = -1;
  107. bool reopen(LogDataType type, int32 dayIndex, const QString &postfix) {
  108. if (files[type] && files[type]->isOpen()) {
  109. if (type == LogDataMain) {
  110. if (!postfix.isEmpty()) {
  111. return true;
  112. }
  113. } else {
  114. files[type]->close();
  115. }
  116. }
  117. auto mode = QIODevice::WriteOnly | QIODevice::Text;
  118. if (type == LogDataMain) { // we can call LOG() in LogDataMain reopen - mutex not locked
  119. if (postfix.isEmpty()) { // instance checked, need to move to log.txt
  120. Assert(!files[type]->fileName().isEmpty()); // one of log_startXX.txt should've been opened already
  121. auto to = std::make_unique<QFile>(_logsFilePath(type, postfix));
  122. if (to->exists() && !to->remove()) {
  123. LOG(("Could not delete '%1' file to start new logging: %2").arg(to->fileName(), to->errorString()));
  124. return false;
  125. }
  126. if (auto from = QFile(files[type]->fileName()); !from.copy(to->fileName())) { // don't close files[type] yet
  127. LOG(("Could not copy '%1' to '%2' to start new logging: %3").arg(files[type]->fileName(), to->fileName(), from.errorString()));
  128. return false;
  129. }
  130. if (to->open(mode | QIODevice::Append)) {
  131. std::swap(files[type], to);
  132. LOG(("Moved logging from '%1' to '%2'!").arg(to->fileName(), files[type]->fileName()));
  133. to->remove();
  134. LogsStartIndexChosen = -1;
  135. QDir working(cWorkingDir()); // delete all other log_startXX.txt that we can
  136. QStringList oldlogs = working.entryList(QStringList("log_start*.txt"), QDir::Files);
  137. for (QStringList::const_iterator i = oldlogs.cbegin(), e = oldlogs.cend(); i != e; ++i) {
  138. QString oldlog = cWorkingDir() + *i, oldlogend = i->mid(u"log_start"_q.size());
  139. if (oldlogend.size() == 1 + u".txt"_q.size() && oldlogend.at(0).isDigit() && base::StringViewMid(oldlogend, 1) == u".txt"_q) {
  140. bool removed = QFile(oldlog).remove();
  141. LOG(("Old start log '%1' found, deleted: %2").arg(*i, Logs::b(removed)));
  142. }
  143. }
  144. return true;
  145. }
  146. LOG(("Could not open '%1' file to start new logging: %2").arg(to->fileName(), to->errorString()));
  147. return false;
  148. } else {
  149. bool found = false;
  150. int32 oldest = -1; // find not existing log_startX.txt or pick the oldest one (by lastModified)
  151. QDateTime oldestLastModified;
  152. for (int32 i = 0; i < 10; ++i) {
  153. QString trying = _logsFilePath(type, u"_start%1"_q.arg(i));
  154. files[type]->setFileName(trying);
  155. if (!files[type]->exists()) {
  156. LogsStartIndexChosen = i;
  157. found = true;
  158. break;
  159. }
  160. QDateTime lastModified = QFileInfo(trying).lastModified();
  161. if (oldest < 0 || lastModified < oldestLastModified) {
  162. oldestLastModified = lastModified;
  163. oldest = i;
  164. }
  165. }
  166. if (!found) {
  167. files[type]->setFileName(_logsFilePath(type, u"_start%1"_q.arg(oldest)));
  168. LogsStartIndexChosen = oldest;
  169. }
  170. }
  171. } else {
  172. files[type]->setFileName(_logsFilePath(type, postfix));
  173. if (files[type]->exists()) {
  174. if (files[type]->open(QIODevice::ReadOnly | QIODevice::Text)) {
  175. if (QString::fromUtf8(files[type]->readLine()).toInt() == dayIndex) {
  176. mode |= QIODevice::Append;
  177. }
  178. files[type]->close();
  179. }
  180. } else {
  181. QDir().mkdir(cWorkingDir() + u"DebugLogs"_q);
  182. }
  183. }
  184. if (files[type]->open(mode)) {
  185. if (type != LogDataMain) {
  186. files[type]->write(((mode & QIODevice::Append)
  187. ? qsl("\
  188. ----------------------------------------------------------------\n\
  189. NEW LOGGING INSTANCE STARTED!!!\n\
  190. ----------------------------------------------------------------\n")
  191. : qsl("%1\n").arg(dayIndex)).toUtf8());
  192. files[type]->flush();
  193. }
  194. return true;
  195. } else if (type != LogDataMain) {
  196. LOG(("Could not open debug log '%1': %2").arg(files[type]->fileName(), files[type]->errorString()));
  197. }
  198. return false;
  199. }
  200. void reopenDebug() {
  201. time_t t = time(NULL);
  202. struct tm tm;
  203. mylocaltime(&tm, &t);
  204. static const int switchEach = 15; // minutes
  205. int32 newPart = (tm.tm_min + tm.tm_hour * 60) / switchEach;
  206. if (newPart == part) return;
  207. part = newPart;
  208. int32 dayIndex = (tm.tm_year + 1900) * 10000 + (tm.tm_mon + 1) * 100 + tm.tm_mday;
  209. QString postfix = QString("_%4_%5").arg((part * switchEach) / 60, 2, 10, QChar('0')).arg((part * switchEach) % 60, 2, 10, QChar('0'));
  210. reopen(LogDataDebug, dayIndex, postfix);
  211. reopen(LogDataTcp, dayIndex, postfix);
  212. reopen(LogDataMtp, dayIndex, postfix);
  213. }
  214. };
  215. LogsDataFields *LogsData = 0;
  216. using LogsInMemoryList = QList<QPair<LogDataType, QString>>;
  217. LogsInMemoryList *LogsInMemory = 0;
  218. LogsInMemoryList *DeletedLogsInMemory = SharedMemoryLocation<LogsInMemoryList, 0>();
  219. QString LogsBeforeSingleInstanceChecked; // LogsInMemory already dumped in LogsData, but LogsData is about to be deleted
  220. void _logsWrite(LogDataType type, const QString &msg) {
  221. if (LogsData && (type == LogDataMain || LogsStartIndexChosen < 0)) {
  222. if (type == LogDataMain || Logs::DebugEnabled()) {
  223. LogsData->write(type, msg);
  224. }
  225. } else if (LogsInMemory != DeletedLogsInMemory) {
  226. if (!LogsInMemory) {
  227. LogsInMemory = new LogsInMemoryList;
  228. }
  229. LogsInMemory->push_back(qMakePair(type, msg));
  230. } else if (!LogsBeforeSingleInstanceChecked.isEmpty() && type == LogDataMain) {
  231. LogsBeforeSingleInstanceChecked += msg;
  232. }
  233. }
  234. namespace Logs {
  235. namespace {
  236. bool DebugModeEnabled = false;
  237. [[maybe_unused]] void MoveOldDataFiles(const QString &wasDir) {
  238. if (wasDir.isEmpty()) {
  239. return;
  240. }
  241. QFile data(wasDir + "data"), dataConfig(wasDir + "data_config"), tdataConfig(wasDir + "tdata/config");
  242. if (data.exists() && dataConfig.exists() && !QFileInfo::exists(cWorkingDir() + "data") && !QFileInfo::exists(cWorkingDir() + "data_config")) { // move to home dir
  243. LOG(("Copying data to home dir '%1' from '%2'").arg(cWorkingDir(), wasDir));
  244. if (data.copy(cWorkingDir() + "data")) {
  245. LOG(("Copied 'data' to home dir"));
  246. if (dataConfig.copy(cWorkingDir() + "data_config")) {
  247. LOG(("Copied 'data_config' to home dir"));
  248. bool tdataGood = true;
  249. if (tdataConfig.exists()) {
  250. tdataGood = false;
  251. QDir().mkpath(cWorkingDir() + "tdata");
  252. if (tdataConfig.copy(cWorkingDir() + "tdata/config")) {
  253. LOG(("Copied 'tdata/config' to home dir"));
  254. tdataGood = true;
  255. } else {
  256. LOG(("Copied 'data' and 'data_config', but could not copy 'tdata/config'!"));
  257. }
  258. }
  259. if (tdataGood) {
  260. if (data.remove()) {
  261. LOG(("Removed 'data'"));
  262. } else {
  263. LOG(("Could not remove 'data'"));
  264. }
  265. if (dataConfig.remove()) {
  266. LOG(("Removed 'data_config'"));
  267. } else {
  268. LOG(("Could not remove 'data_config'"));
  269. }
  270. if (!tdataConfig.exists() || tdataConfig.remove()) {
  271. LOG(("Removed 'tdata/config'"));
  272. } else {
  273. LOG(("Could not remove 'tdata/config'"));
  274. }
  275. QDir().rmdir(wasDir + "tdata");
  276. }
  277. } else {
  278. LOG(("Copied 'data', but could not copy 'data_config'!!"));
  279. }
  280. } else {
  281. LOG(("Could not copy 'data'!"));
  282. }
  283. }
  284. }
  285. } // namespace
  286. void SetDebugEnabled(bool enabled) {
  287. DebugModeEnabled = enabled;
  288. }
  289. bool DebugEnabled() {
  290. return DebugModeEnabled;
  291. }
  292. bool WritingEntry() {
  293. return WritingEntryFlag;
  294. }
  295. void start() {
  296. Assert(LogsData == nullptr);
  297. auto &launcher = Core::Launcher::Instance();
  298. if (!launcher.checkPortableVersionFolder()) {
  299. return;
  300. }
  301. LogsData = new LogsDataFields();
  302. if (cWorkingDir().isEmpty()) {
  303. cForceWorkingDir(cExeDir());
  304. }
  305. if (launcher.validateCustomWorkingDir()) {
  306. delete LogsData;
  307. LogsData = new LogsDataFields();
  308. }
  309. // WinRT build requires the working dir to stay the same for plugin loading.
  310. #ifndef Q_OS_WINRT
  311. QDir::setCurrent(cWorkingDir());
  312. #endif // !Q_OS_WINRT
  313. QDir().mkpath(cWorkingDir() + u"tdata"_q);
  314. launcher.workingFolderReady();
  315. CrashReports::StartCatching();
  316. if (!LogsData->openMain()) {
  317. delete LogsData;
  318. LogsData = nullptr;
  319. }
  320. LOG(("Launched version: %1, install beta: %2, alpha: %3, debug mode: %4"
  321. ).arg(AppVersion
  322. ).arg(Logs::b(cInstallBetaVersion())
  323. ).arg(cAlphaVersion()
  324. ).arg(Logs::b(DebugEnabled())));
  325. LOG(("Executable dir: %1, name: %2").arg(cExeDir(), cExeName()));
  326. LOG(("Initial working dir: %1").arg(launcher.initialWorkingDir()));
  327. LOG(("Working dir: %1").arg(cWorkingDir()));
  328. LOG(("Command line: %1").arg(launcher.arguments().join(' ')));
  329. if (!LogsData) {
  330. LOG(("FATAL: Could not open '%1' for writing log!"
  331. ).arg(_logsFilePath(LogDataMain, u"_startXX"_q)));
  332. return;
  333. }
  334. if (LogsInMemory) {
  335. Assert(LogsInMemory != DeletedLogsInMemory);
  336. LogsInMemoryList list = *LogsInMemory;
  337. for (LogsInMemoryList::const_iterator i = list.cbegin(), e = list.cend(); i != e; ++i) {
  338. if (i->first == LogDataMain) {
  339. _logsWrite(i->first, i->second);
  340. }
  341. }
  342. }
  343. LOG(("Logs started"));
  344. }
  345. void finish() {
  346. delete LogsData;
  347. LogsData = 0;
  348. if (LogsInMemory && LogsInMemory != DeletedLogsInMemory) {
  349. delete LogsInMemory;
  350. }
  351. LogsInMemory = DeletedLogsInMemory;
  352. _logsMutex(LogDataMain, true);
  353. CrashReports::FinishCatching();
  354. }
  355. bool started() {
  356. return LogsData != 0;
  357. }
  358. bool instanceChecked() {
  359. if (!LogsData) return false;
  360. if (!LogsData->instanceChecked()) {
  361. LogsBeforeSingleInstanceChecked = Logs::full();
  362. delete LogsData;
  363. LogsData = 0;
  364. LOG(("FATAL: Could not move logging to '%1'!").arg(_logsFilePath(LogDataMain)));
  365. return false;
  366. }
  367. if (LogsInMemory) {
  368. Assert(LogsInMemory != DeletedLogsInMemory);
  369. LogsInMemoryList list = *LogsInMemory;
  370. for (LogsInMemoryList::const_iterator i = list.cbegin(), e = list.cend(); i != e; ++i) {
  371. if (i->first != LogDataMain) {
  372. _logsWrite(i->first, i->second);
  373. }
  374. }
  375. }
  376. if (LogsInMemory) {
  377. Assert(LogsInMemory != DeletedLogsInMemory);
  378. delete LogsInMemory;
  379. }
  380. LogsInMemory = DeletedLogsInMemory;
  381. DEBUG_LOG(("Debug logs started."));
  382. LogsBeforeSingleInstanceChecked.clear();
  383. return true;
  384. }
  385. void multipleInstances() {
  386. if (LogsInMemory) {
  387. Assert(LogsInMemory != DeletedLogsInMemory);
  388. delete LogsInMemory;
  389. }
  390. LogsInMemory = DeletedLogsInMemory;
  391. if (Logs::DebugEnabled()) {
  392. LOG(("WARNING: debug logs are not written in multiple instances mode!"));
  393. }
  394. LogsBeforeSingleInstanceChecked.clear();
  395. }
  396. void closeMain() {
  397. LOG(("Explicitly closing main log and finishing crash handlers."));
  398. if (LogsData) {
  399. LogsData->closeMain();
  400. }
  401. }
  402. void writeMain(const QString &v) {
  403. time_t t = time(NULL);
  404. struct tm tm;
  405. mylocaltime(&tm, &t);
  406. const auto msg = QString("[%1.%2.%3 %4:%5:%6] %7\n"
  407. ).arg(tm.tm_year + 1900
  408. ).arg(tm.tm_mon + 1, 2, 10, QChar('0')
  409. ).arg(tm.tm_mday, 2, 10, QChar('0')
  410. ).arg(tm.tm_hour, 2, 10, QChar('0')
  411. ).arg(tm.tm_min, 2, 10, QChar('0')
  412. ).arg(tm.tm_sec, 2, 10, QChar('0')
  413. ).arg(v);
  414. _logsWrite(LogDataMain, msg);
  415. writeDebug(v);
  416. }
  417. void writeDebug(const QString &v) {
  418. const auto msg = QString("%1 %2\n").arg(_logsEntryStart(), v);
  419. _logsWrite(LogDataDebug, msg);
  420. #ifdef Q_OS_WIN
  421. //OutputDebugString(reinterpret_cast<const wchar_t *>(msg.utf16()));
  422. #elif defined Q_OS_MAC
  423. //objc_outputDebugString(msg);
  424. #elif defined _DEBUG
  425. //std::cout << msg.toUtf8().constData();
  426. #endif
  427. }
  428. void writeTcp(const QString &v) {
  429. const auto msg = QString("%1 %2\n").arg(_logsEntryStart(), v);
  430. _logsWrite(LogDataTcp, msg);
  431. }
  432. void writeMtp(int32 dc, const QString &v) {
  433. const auto expanded = [&] {
  434. const auto bare = MTP::isTemporaryDcId(dc)
  435. ? MTP::getRealIdFromTemporaryDcId(dc)
  436. : MTP::BareDcId(dc);
  437. const auto base = (MTP::isTemporaryDcId(dc) ? "temporary_" : "")
  438. + QString::number(bare);
  439. const auto shift = MTP::GetDcIdShift(dc);
  440. if (shift == 0) {
  441. return base + "_main";
  442. } else if (shift == MTP::kExportDcShift) {
  443. return base + "_export";
  444. } else if (shift == MTP::kExportMediaDcShift) {
  445. return base + "_export_download";
  446. } else if (shift == MTP::kConfigDcShift) {
  447. return base + "_config_enumeration";
  448. } else if (shift == MTP::kLogoutDcShift) {
  449. return base + "_logout_guest";
  450. } else if (shift == MTP::kUpdaterDcShift) {
  451. return base + "_download_update";
  452. } else if (shift == MTP::kGroupCallStreamDcShift) {
  453. return base + "_stream";
  454. } else if (MTP::isDownloadDcId(dc)) {
  455. const auto index = shift - MTP::kBaseDownloadDcShift;
  456. return base + "_download" + QString::number(index);
  457. } else if (MTP::isUploadDcId(dc)) {
  458. const auto index = shift - MTP::kBaseUploadDcShift;
  459. return base + "_upload" + QString::number(index);
  460. } else if (shift >= MTP::kDestroyKeyStartDcShift) {
  461. const auto index = shift - MTP::kDestroyKeyStartDcShift;
  462. return base + "_key_destroyer" + QString::number(index);
  463. }
  464. return base + "_unknown" + QString::number(shift);
  465. }();
  466. const auto msg = _logsEntryStart()
  467. + u" (dc:%1) "_q.arg(expanded)
  468. + v
  469. + '\n';
  470. _logsWrite(LogDataMtp, msg);
  471. }
  472. QString full() {
  473. if (LogsData) {
  474. return LogsData->full();
  475. }
  476. if (!LogsInMemory || LogsInMemory == DeletedLogsInMemory) {
  477. return LogsBeforeSingleInstanceChecked;
  478. }
  479. int32 size = LogsBeforeSingleInstanceChecked.size();
  480. for (LogsInMemoryList::const_iterator i = LogsInMemory->cbegin(), e = LogsInMemory->cend(); i != e; ++i) {
  481. if (i->first == LogDataMain) {
  482. size += i->second.size();
  483. }
  484. }
  485. QString result;
  486. result.reserve(size);
  487. if (!LogsBeforeSingleInstanceChecked.isEmpty()) {
  488. result.append(LogsBeforeSingleInstanceChecked);
  489. }
  490. for (LogsInMemoryList::const_iterator i = LogsInMemory->cbegin(), e = LogsInMemory->cend(); i != e; ++i) {
  491. if (i->first == LogDataMain) {
  492. result += i->second;
  493. }
  494. }
  495. return result;
  496. }
  497. } // namespace Logs