forked from CollaboraOnline/online
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuarantineUtil.cpp
274 lines (226 loc) · 8.72 KB
/
QuarantineUtil.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
* Copyright the Collabora Online contributors.
*
* SPDX-License-Identifier: MPL-2.0
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <config.h>
#include "QuarantineUtil.hpp"
#include <Poco/Path.h>
#include <Poco/URI.h>
#include "ClientSession.hpp"
#include "COOLWSD.hpp"
#include "DocumentBroker.hpp"
#include "FileUtil.hpp"
#include "Util.hpp"
#include <chrono>
#include <common/Common.hpp>
#include <common/StringVector.hpp>
#include <common/Log.hpp>
#include <mutex>
namespace
{
std::size_t getSecondsSinceEpoch()
{
const auto timeNow = std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::seconds>(timeNow.time_since_epoch()).count();
}
} // namespace
std::string Quarantine::QuarantinePath;
std::unordered_map<std::string, std::vector<std::string>> Quarantine::QuarantineMap;
std::mutex Quarantine::Mutex;
Quarantine::Quarantine(DocumentBroker& docBroker, const std::string& docName)
: _docKey(docBroker.getDocKey())
, _docName(Util::encodeURIComponent(docName, std::string(",/?:@&=+$#") + Delimiter))
, _quarantinedFilename(Delimiter + std::to_string(docBroker.getPid()) + Delimiter +
docBroker.getDocKey() + Delimiter + _docName)
, _maxSizeBytes(COOLWSD::getConfigValue<std::size_t>("quarantine_files.limit_dir_size_mb", 0) *
1024 * 1024)
, _maxAgeSecs(COOLWSD::getConfigValue<std::size_t>("quarantine_files.expiry_min", 30) * 60)
, _maxVersions(std::max(
COOLWSD::getConfigValue<std::size_t>("quarantine_files.max_versions_to_maintain", 2),
1UL))
{
LOG_DBG("Quarantine ctor for [" << _docKey << ']');
}
void Quarantine::initialize(const std::string& path)
{
if (!COOLWSD::getConfigValue<bool>("quarantine_files[@enable]", false) ||
!QuarantinePath.empty())
return;
// This function should ever be called once, but for consistency, take the lock.
std::lock_guard<std::mutex> lock(Mutex);
QuarantineMap.clear();
std::vector<std::string> files;
Poco::File(path).list(files);
std::sort(files.begin(), files.end(),
[](const auto& lhs, const auto& rhs)
{
const auto lhsPair = Util::u64FromString(Util::split(lhs, Delimiter).first);
const auto rhsPair = Util::u64FromString(Util::split(rhs, Delimiter).first);
return lhsPair.first && rhsPair.first && lhsPair.second < rhsPair.second;
});
std::vector<StringToken> tokens;
for (const auto& file : files)
{
StringVector::tokenize(file.c_str(), file.size(), Delimiter, tokens);
if (tokens.size() >= 3)
{
const auto docKey = file.substr(tokens[2]._index, tokens[tokens.size() - 1]._index -
tokens[2]._index - 1);
const auto fullpath = path + file;
LOG_TRC("Adding quarantine file [" << fullpath << "] for docKey [" << docKey
<< "] from quarantine directory");
QuarantineMap[docKey].emplace_back(fullpath);
}
tokens.clear();
}
QuarantinePath = path;
}
void Quarantine::removeQuarantine()
{
if (!isQuarantineEnabled())
return;
FileUtil::removeFile(QuarantinePath, true);
}
std::size_t Quarantine::quarantineSize()
{
if (!isQuarantineEnabled())
return 0;
std::vector<std::string> files;
Poco::File(QuarantinePath).list(files);
std::size_t size = 0;
for (const auto& file : files)
{
FileUtil::Stat f(QuarantinePath + file);
size += f.size();
}
return size;
}
void Quarantine::makeQuarantineSpace()
{
if (!isQuarantineEnabled())
return;
LOG_ASSERT_MSG(!Mutex.try_lock(), "Quarantine Mutex must be taken");
std::vector<std::string> files;
Poco::File(QuarantinePath).list(files);
if (files.empty())
return;
std::sort(files.begin(), files.end(),
[](const auto& lhs, const auto& rhs)
{
const auto lhsPair = Util::u64FromString(Util::split(lhs, Delimiter).first);
const auto rhsPair = Util::u64FromString(Util::split(rhs, Delimiter).first);
return lhsPair.first && rhsPair.first && lhsPair.second < rhsPair.second;
});
const std::size_t now = getSecondsSinceEpoch();
std::size_t currentSize = quarantineSize();
auto index = files.begin();
while (index != files.end())
{
bool purge = currentSize >= _maxSizeBytes;
if (!purge)
{
// Parse the timestamp from the quarantined filename (first token).
const auto pair = Util::u64FromString(Util::split(*index, Delimiter).first);
const auto age = (now - pair.first);
if (!pair.second || (now > pair.first && age > _maxAgeSecs))
{
LOG_TRC("Will remove quarantined file [" << *index << "] which is " << age
<< " secs old (max " << _maxAgeSecs
<< " secs)");
purge = true;
}
}
if (purge)
{
FileUtil::Stat file(QuarantinePath + *index);
LOG_TRC("Removing quarantined file ["
<< *index << "] (" << file.size() << " bytes). Current quarantine size: "
<< currentSize << " (max " << _maxSizeBytes << " bytes)");
currentSize -= file.size();
FileUtil::removeFile(QuarantinePath + *index, true);
index = files.erase(index);
}
else
index++;
}
}
void Quarantine::clearOldQuarantineVersions()
{
if (!isQuarantineEnabled())
return;
LOG_ASSERT_MSG(!Mutex.try_lock(), "Quarantine Mutex must be taken");
auto& container = QuarantineMap[_docKey];
if (container.size() > _maxVersions)
{
const std::size_t excess = container.size() - _maxVersions;
LOG_TRC("Removing " << excess << " excess quarantined file versions for [" << _docKey
<< ']');
for (std::size_t i = 0; i < excess; ++i)
{
const std::string& path = container[i];
LOG_TRC("Removing excess quarantined file version #" << (i + 1) << " [" << path
<< "] for [" << _docKey << ']');
FileUtil::removeFile(path);
}
// And remove them from the container.
container.erase(container.begin(), container.begin() + excess);
}
}
bool Quarantine::quarantineFile(const std::string& docPath)
{
if (!isQuarantineEnabled())
return false;
const std::string linkedFilePath =
QuarantinePath + std::to_string(getSecondsSinceEpoch()) + _quarantinedFilename;
std::lock_guard<std::mutex> lock(Mutex);
auto& fileList = QuarantineMap[_docKey];
if (!fileList.empty())
{
FileUtil::Stat sourceStat(docPath);
const auto& lastFile = fileList[fileList.size() - 1];
FileUtil::Stat lastFileStat(lastFile);
if (lastFileStat.isIdenticalTo(sourceStat))
{
LOG_WRN("Quarantining of file ["
<< docPath << "] to [" << linkedFilePath
<< "] is skipped because this file version is already quarantined as: " << lastFile);
return false;
}
}
makeQuarantineSpace();
if (FileUtil::linkOrCopyFile(docPath, linkedFilePath))
{
fileList.emplace_back(linkedFilePath);
clearOldQuarantineVersions();
makeQuarantineSpace();
LOG_WRN("Quarantined [" << docPath << "] to [" << linkedFilePath << ']');
return true;
}
LOG_ERR("Quarantining of file [" << docPath << "] to [" << linkedFilePath << "] failed");
return false;
}
std::string Quarantine::lastQuarantinedFilePath() const
{
if (!isQuarantineEnabled())
return std::string();
std::lock_guard<std::mutex> lock(Mutex);
const auto& fileList = QuarantineMap[_docKey];
return fileList.empty() ? std::string() : fileList[fileList.size() - 1];
}
void Quarantine::removeQuarantinedFiles()
{
std::lock_guard<std::mutex> lock(Mutex);
LOG_DBG("Removing all quarantined files for [" << _docKey << ']');
for (const auto& file : QuarantineMap[_docKey])
{
LOG_TRC("Removing quarantined file [" << file << "] for [" << _docKey << ']');
FileUtil::removeFile(file);
}
QuarantineMap.erase(_docKey);
}