logs.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. #if (!defined Q_OS_WIN && !defined _DEBUG) || defined Q_OS_WINRT || defined OS_WIN_STORE || defined OS_MAC_STORE
  304. cForceWorkingDir(psAppDataPath());
  305. #else // (!Q_OS_WIN && !_DEBUG) || Q_OS_WINRT || OS_WIN_STORE || OS_MAC_STORE
  306. cForceWorkingDir(cExeDir());
  307. if (!LogsData->openMain()) {
  308. cForceWorkingDir(psAppDataPath());
  309. }
  310. #endif // (!Q_OS_WIN && !_DEBUG) || Q_OS_WINRT || OS_WIN_STORE || OS_MAC_STORE
  311. }
  312. if (launcher.validateCustomWorkingDir()) {
  313. delete LogsData;
  314. LogsData = new LogsDataFields();
  315. }
  316. // WinRT build requires the working dir to stay the same for plugin loading.
  317. #ifndef Q_OS_WINRT
  318. QDir::setCurrent(cWorkingDir());
  319. #endif // !Q_OS_WINRT
  320. QDir().mkpath(cWorkingDir() + u"tdata"_q);
  321. launcher.workingFolderReady();
  322. CrashReports::StartCatching();
  323. if (!LogsData->openMain()) {
  324. delete LogsData;
  325. LogsData = nullptr;
  326. }
  327. LOG(("Launched version: %1, install beta: %2, alpha: %3, debug mode: %4"
  328. ).arg(AppVersion
  329. ).arg(Logs::b(cInstallBetaVersion())
  330. ).arg(cAlphaVersion()
  331. ).arg(Logs::b(DebugEnabled())));
  332. LOG(("Executable dir: %1, name: %2").arg(cExeDir(), cExeName()));
  333. LOG(("Initial working dir: %1").arg(launcher.initialWorkingDir()));
  334. LOG(("Working dir: %1").arg(cWorkingDir()));
  335. LOG(("Command line: %1").arg(launcher.arguments().join(' ')));
  336. if (!LogsData) {
  337. LOG(("FATAL: Could not open '%1' for writing log!"
  338. ).arg(_logsFilePath(LogDataMain, u"_startXX"_q)));
  339. return;
  340. }
  341. #ifdef Q_OS_WIN
  342. if (cWorkingDir() == psAppDataPath()) { // fix old "Telegram Win (Unofficial)" version
  343. MoveOldDataFiles(psAppDataPathOld());
  344. }
  345. #elif !defined Q_OS_MAC && !defined _DEBUG // fix first version
  346. MoveOldDataFiles(launcher.initialWorkingDir());
  347. #endif
  348. if (LogsInMemory) {
  349. Assert(LogsInMemory != DeletedLogsInMemory);
  350. LogsInMemoryList list = *LogsInMemory;
  351. for (LogsInMemoryList::const_iterator i = list.cbegin(), e = list.cend(); i != e; ++i) {
  352. if (i->first == LogDataMain) {
  353. _logsWrite(i->first, i->second);
  354. }
  355. }
  356. }
  357. LOG(("Logs started"));
  358. }
  359. void finish() {
  360. delete LogsData;
  361. LogsData = 0;
  362. if (LogsInMemory && LogsInMemory != DeletedLogsInMemory) {
  363. delete LogsInMemory;
  364. }
  365. LogsInMemory = DeletedLogsInMemory;
  366. _logsMutex(LogDataMain, true);
  367. CrashReports::FinishCatching();
  368. }
  369. bool started() {
  370. return LogsData != 0;
  371. }
  372. bool instanceChecked() {
  373. if (!LogsData) return false;
  374. if (!LogsData->instanceChecked()) {
  375. LogsBeforeSingleInstanceChecked = Logs::full();
  376. delete LogsData;
  377. LogsData = 0;
  378. LOG(("FATAL: Could not move logging to '%1'!").arg(_logsFilePath(LogDataMain)));
  379. return false;
  380. }
  381. if (LogsInMemory) {
  382. Assert(LogsInMemory != DeletedLogsInMemory);
  383. LogsInMemoryList list = *LogsInMemory;
  384. for (LogsInMemoryList::const_iterator i = list.cbegin(), e = list.cend(); i != e; ++i) {
  385. if (i->first != LogDataMain) {
  386. _logsWrite(i->first, i->second);
  387. }
  388. }
  389. }
  390. if (LogsInMemory) {
  391. Assert(LogsInMemory != DeletedLogsInMemory);
  392. delete LogsInMemory;
  393. }
  394. LogsInMemory = DeletedLogsInMemory;
  395. DEBUG_LOG(("Debug logs started."));
  396. LogsBeforeSingleInstanceChecked.clear();
  397. return true;
  398. }
  399. void multipleInstances() {
  400. if (LogsInMemory) {
  401. Assert(LogsInMemory != DeletedLogsInMemory);
  402. delete LogsInMemory;
  403. }
  404. LogsInMemory = DeletedLogsInMemory;
  405. if (Logs::DebugEnabled()) {
  406. LOG(("WARNING: debug logs are not written in multiple instances mode!"));
  407. }
  408. LogsBeforeSingleInstanceChecked.clear();
  409. }
  410. void closeMain() {
  411. LOG(("Explicitly closing main log and finishing crash handlers."));
  412. if (LogsData) {
  413. LogsData->closeMain();
  414. }
  415. }
  416. void writeMain(const QString &v) {
  417. time_t t = time(NULL);
  418. struct tm tm;
  419. mylocaltime(&tm, &t);
  420. const auto msg = QString("[%1.%2.%3 %4:%5:%6] %7\n"
  421. ).arg(tm.tm_year + 1900
  422. ).arg(tm.tm_mon + 1, 2, 10, QChar('0')
  423. ).arg(tm.tm_mday, 2, 10, QChar('0')
  424. ).arg(tm.tm_hour, 2, 10, QChar('0')
  425. ).arg(tm.tm_min, 2, 10, QChar('0')
  426. ).arg(tm.tm_sec, 2, 10, QChar('0')
  427. ).arg(v);
  428. _logsWrite(LogDataMain, msg);
  429. writeDebug(v);
  430. }
  431. void writeDebug(const QString &v) {
  432. const auto msg = QString("%1 %2\n").arg(_logsEntryStart(), v);
  433. _logsWrite(LogDataDebug, msg);
  434. #ifdef Q_OS_WIN
  435. //OutputDebugString(reinterpret_cast<const wchar_t *>(msg.utf16()));
  436. #elif defined Q_OS_MAC
  437. //objc_outputDebugString(msg);
  438. #elif defined _DEBUG
  439. //std::cout << msg.toUtf8().constData();
  440. #endif
  441. }
  442. void writeTcp(const QString &v) {
  443. const auto msg = QString("%1 %2\n").arg(_logsEntryStart(), v);
  444. _logsWrite(LogDataTcp, msg);
  445. }
  446. void writeMtp(int32 dc, const QString &v) {
  447. const auto expanded = [&] {
  448. const auto bare = MTP::isTemporaryDcId(dc)
  449. ? MTP::getRealIdFromTemporaryDcId(dc)
  450. : MTP::BareDcId(dc);
  451. const auto base = (MTP::isTemporaryDcId(dc) ? "temporary_" : "")
  452. + QString::number(bare);
  453. const auto shift = MTP::GetDcIdShift(dc);
  454. if (shift == 0) {
  455. return base + "_main";
  456. } else if (shift == MTP::kExportDcShift) {
  457. return base + "_export";
  458. } else if (shift == MTP::kExportMediaDcShift) {
  459. return base + "_export_download";
  460. } else if (shift == MTP::kConfigDcShift) {
  461. return base + "_config_enumeration";
  462. } else if (shift == MTP::kLogoutDcShift) {
  463. return base + "_logout_guest";
  464. } else if (shift == MTP::kUpdaterDcShift) {
  465. return base + "_download_update";
  466. } else if (shift == MTP::kGroupCallStreamDcShift) {
  467. return base + "_stream";
  468. } else if (MTP::isDownloadDcId(dc)) {
  469. const auto index = shift - MTP::kBaseDownloadDcShift;
  470. return base + "_download" + QString::number(index);
  471. } else if (MTP::isUploadDcId(dc)) {
  472. const auto index = shift - MTP::kBaseUploadDcShift;
  473. return base + "_upload" + QString::number(index);
  474. } else if (shift >= MTP::kDestroyKeyStartDcShift) {
  475. const auto index = shift - MTP::kDestroyKeyStartDcShift;
  476. return base + "_key_destroyer" + QString::number(index);
  477. }
  478. return base + "_unknown" + QString::number(shift);
  479. }();
  480. const auto msg = _logsEntryStart()
  481. + u" (dc:%1) "_q.arg(expanded)
  482. + v
  483. + '\n';
  484. _logsWrite(LogDataMtp, msg);
  485. }
  486. QString full() {
  487. if (LogsData) {
  488. return LogsData->full();
  489. }
  490. if (!LogsInMemory || LogsInMemory == DeletedLogsInMemory) {
  491. return LogsBeforeSingleInstanceChecked;
  492. }
  493. int32 size = LogsBeforeSingleInstanceChecked.size();
  494. for (LogsInMemoryList::const_iterator i = LogsInMemory->cbegin(), e = LogsInMemory->cend(); i != e; ++i) {
  495. if (i->first == LogDataMain) {
  496. size += i->second.size();
  497. }
  498. }
  499. QString result;
  500. result.reserve(size);
  501. if (!LogsBeforeSingleInstanceChecked.isEmpty()) {
  502. result.append(LogsBeforeSingleInstanceChecked);
  503. }
  504. for (LogsInMemoryList::const_iterator i = LogsInMemory->cbegin(), e = LogsInMemory->cend(); i != e; ++i) {
  505. if (i->first == LogDataMain) {
  506. result += i->second;
  507. }
  508. }
  509. return result;
  510. }
  511. } // namespace Logs