1 /*
2  * Bittorrent Client using Qt and libtorrent.
3  * Copyright (C) 2016  sledgehammer999 <hammered999@gmail.com>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18  *
19  * In addition, as a special exception, the copyright holders give permission to
20  * link this program with the OpenSSL project's "OpenSSL" library (or with
21  * modified versions of it that use the same license as the "OpenSSL" library),
22  * and distribute the linked executables. You must obey the GNU General Public
23  * License in all respects for all of the code used other than "OpenSSL".  If you
24  * modify file(s), you may extend this exception to your version of the file(s),
25  * but you are not obligated to do so. If you do not wish to do so, delete this
26  * exception statement from your version.
27  */
28 
29 #include "filelogger.h"
30 
31 #include <chrono>
32 
33 #include <QDateTime>
34 #include <QDir>
35 #include <QTextStream>
36 #include <QVector>
37 
38 #include "base/global.h"
39 #include "base/logger.h"
40 #include "base/utils/fs.h"
41 
42 namespace
43 {
44     const std::chrono::seconds FLUSH_INTERVAL {2};
45 }
46 
FileLogger(const QString & path,const bool backup,const int maxSize,const bool deleteOld,const int age,const FileLogAgeType ageType)47 FileLogger::FileLogger(const QString &path, const bool backup, const int maxSize, const bool deleteOld, const int age, const FileLogAgeType ageType)
48     : m_backup(backup)
49     , m_maxSize(maxSize)
50 {
51     m_flusher.setInterval(FLUSH_INTERVAL);
52     m_flusher.setSingleShot(true);
53     connect(&m_flusher, &QTimer::timeout, this, &FileLogger::flushLog);
54 
55     changePath(path);
56     if (deleteOld)
57         this->deleteOld(age, ageType);
58 
59     const Logger *const logger = Logger::instance();
60     for (const Log::Msg &msg : asConst(logger->getMessages()))
61         addLogMessage(msg);
62 
63     connect(logger, &Logger::newLogMessage, this, &FileLogger::addLogMessage);
64 }
65 
~FileLogger()66 FileLogger::~FileLogger()
67 {
68     closeLogFile();
69 }
70 
changePath(const QString & newPath)71 void FileLogger::changePath(const QString &newPath)
72 {
73     const QDir dir(newPath);
74     dir.mkpath(newPath);
75     const QString tmpPath = dir.absoluteFilePath("qbittorrent.log");
76 
77     if (tmpPath != m_path)
78     {
79         m_path = tmpPath;
80 
81         closeLogFile();
82         m_logFile.setFileName(m_path);
83         openLogFile();
84     }
85 }
86 
deleteOld(const int age,const FileLogAgeType ageType)87 void FileLogger::deleteOld(const int age, const FileLogAgeType ageType)
88 {
89     const QDateTime date = QDateTime::currentDateTime();
90     const QDir dir(Utils::Fs::branchPath(m_path));
91     const QFileInfoList fileList = dir.entryInfoList(QStringList("qbittorrent.log.bak*")
92         , (QDir::Files | QDir::Writable), (QDir::Time | QDir::Reversed));
93 
94     for (const QFileInfo &file : fileList)
95     {
96         QDateTime modificationDate = file.lastModified();
97         switch (ageType)
98         {
99         case DAYS:
100             modificationDate = modificationDate.addDays(age);
101             break;
102         case MONTHS:
103             modificationDate = modificationDate.addMonths(age);
104             break;
105         default:
106             modificationDate = modificationDate.addYears(age);
107         }
108         if (modificationDate > date)
109             break;
110         Utils::Fs::forceRemove(file.absoluteFilePath());
111     }
112 }
113 
setBackup(const bool value)114 void FileLogger::setBackup(const bool value)
115 {
116     m_backup = value;
117 }
118 
setMaxSize(const int value)119 void FileLogger::setMaxSize(const int value)
120 {
121     m_maxSize = value;
122 }
123 
addLogMessage(const Log::Msg & msg)124 void FileLogger::addLogMessage(const Log::Msg &msg)
125 {
126     if (!m_logFile.isOpen()) return;
127 
128     QTextStream stream(&m_logFile);
129     stream.setCodec("UTF-8");
130 
131     switch (msg.type)
132     {
133     case Log::INFO:
134         stream << "(I) ";
135         break;
136     case Log::WARNING:
137         stream << "(W) ";
138         break;
139     case Log::CRITICAL:
140         stream << "(C) ";
141         break;
142     default:
143         stream << "(N) ";
144     }
145 
146     stream << QDateTime::fromMSecsSinceEpoch(msg.timestamp).toString(Qt::ISODate) << " - " << msg.message << '\n';
147 
148     if (m_backup && (m_logFile.size() >= m_maxSize))
149     {
150         closeLogFile();
151         int counter = 0;
152         QString backupLogFilename = m_path + ".bak";
153 
154         while (QFile::exists(backupLogFilename))
155         {
156             ++counter;
157             backupLogFilename = m_path + ".bak" + QString::number(counter);
158         }
159 
160         QFile::rename(m_path, backupLogFilename);
161         openLogFile();
162     }
163     else
164     {
165         if (!m_flusher.isActive())
166             m_flusher.start();
167     }
168 }
169 
flushLog()170 void FileLogger::flushLog()
171 {
172     if (m_logFile.isOpen())
173         m_logFile.flush();
174 }
175 
openLogFile()176 void FileLogger::openLogFile()
177 {
178     if (!m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)
179         || !m_logFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner))
180         {
181         m_logFile.close();
182         LogMsg(tr("An error occurred while trying to open the log file. Logging to file is disabled."), Log::CRITICAL);
183     }
184 }
185 
closeLogFile()186 void FileLogger::closeLogFile()
187 {
188     m_flusher.stop();
189     m_logFile.close();
190 }
191