forked from Telecominfraproject/wlan-cloud-ucentralgw
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathFileUploader.cpp
More file actions
318 lines (267 loc) · 10.3 KB
/
FileUploader.cpp
File metadata and controls
318 lines (267 loc) · 10.3 KB
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
//
// License type: BSD 3-Clause License
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
//
// Created by Stephane Bourque on 2021-03-04.
// Arilia Wireless Inc.
//
#include <iostream>
#include "Poco/CountingStream.h"
#include "Poco/DynamicAny.h"
#include "Poco/Exception.h"
#include "Poco/File.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/Net/MultipartReader.h"
#include "Poco/Net/PartHandler.h"
#include "Poco/StreamCopier.h"
#include "Poco/StringTokenizer.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/ow_constants.h"
#include "framework/utils.h"
#include "FileUploader.h"
#include "StorageService.h"
#include "fmt/format.h"
namespace OpenWifi {
static const std::string URI_BASE{"/v1/upload/"};
int FileUploader::Start() {
poco_notice(Logger(), "Starting.");
Poco::File UploadsDir(MicroServiceConfigPath("openwifi.fileuploader.path", "/tmp"));
Path_ = UploadsDir.path();
if (!UploadsDir.exists()) {
try {
UploadsDir.createDirectory();
} catch (const Poco::Exception &E) {
Logger().log(E);
Path_ = "/tmp";
}
}
for (const auto &Svr : ConfigServersList_) {
if (MicroServiceNoAPISecurity()) {
poco_notice(Logger(), fmt::format("Starting: {}:{}", Svr.Address(), Svr.Port()));
auto Sock{Svr.CreateSocket(Logger())};
auto Params = new Poco::Net::HTTPServerParams;
Params->setMaxThreads(16);
Params->setMaxQueued(100);
Params->setName("ws:upldr");
if (FullName_.empty()) {
std::string TmpName =
MicroServiceConfigGetString("openwifi.fileuploader.uri", "");
if (TmpName.empty()) {
FullName_ =
"https://" + Svr.Name() + ":" + std::to_string(Svr.Port()) + URI_BASE;
} else {
FullName_ = TmpName + URI_BASE;
}
poco_information(Logger(), fmt::format("Uploader URI base is '{}'", FullName_));
}
auto NewServer = std::make_unique<Poco::Net::HTTPServer>(
new FileUpLoaderRequestHandlerFactory(Logger()), Sock, Params);
Params->setName("file-upldr");
NewServer->start();
Servers_.push_back(std::move(NewServer));
} else {
std::string l{"Starting: " + Svr.Address() + ":" + std::to_string(Svr.Port()) +
" key:" + Svr.KeyFile() + " cert:" + Svr.CertFile()};
poco_information(Logger(), l);
auto Sock{Svr.CreateSecureSocket(Logger())};
Svr.LogCert(Logger());
if (!Svr.RootCA().empty())
Svr.LogCas(Logger());
auto Params = new Poco::Net::HTTPServerParams;
Params->setMaxThreads(16);
Params->setMaxQueued(100);
Params->setName("ws:upldr");
if (FullName_.empty()) {
std::string TmpName =
MicroServiceConfigGetString("openwifi.fileuploader.uri", "");
if (TmpName.empty()) {
FullName_ =
"https://" + Svr.Name() + ":" + std::to_string(Svr.Port()) + URI_BASE;
} else {
FullName_ = TmpName + URI_BASE;
}
poco_information(Logger(), fmt::format("Uploader URI base is '{}'", FullName_));
}
auto NewServer = std::make_unique<Poco::Net::HTTPServer>(
new FileUpLoaderRequestHandlerFactory(Logger()), Sock, Params);
NewServer->start();
Servers_.push_back(std::move(NewServer));
}
}
MaxSize_ = 1000 * MicroServiceConfigGetInt("openwifi.fileuploader.maxsize", 10000);
return 0;
}
void FileUploader::reinitialize([[maybe_unused]] Poco::Util::Application &self) {
MicroServiceLoadConfigurationFile();
poco_information(Logger(), "Reinitializing.");
Stop();
Start();
}
const std::string &FileUploader::FullName() { return FullName_; }
// if you pass in an empty UUID, it will just clean the list and not add it.
bool FileUploader::AddUUID(const std::string &UUID, std::chrono::seconds WaitTimeInSeconds,
const std::string &Type) {
std::lock_guard Guard(Mutex_);
uint64_t now = Utils::Now();
auto Func = [now](const UploadId &I) -> bool { return (now > I.Expires); };
OutStandingUploads_.erase(
std::remove_if(OutStandingUploads_.begin(), OutStandingUploads_.end(), Func),
OutStandingUploads_.end());
OutStandingUploads_.emplace_back(UploadId{UUID, now + WaitTimeInSeconds.count(), Type});
return true;
}
bool FileUploader::ValidRequest(const std::string &UUID) {
std::lock_guard Guard(Mutex_);
auto Func = [UUID](const UploadId &P) -> bool { return (P.UUID == UUID); };
return std::find_if(OutStandingUploads_.begin(), OutStandingUploads_.end(), Func) !=
end(OutStandingUploads_);
}
void FileUploader::RemoveRequest(const std::string &UUID) {
std::lock_guard Guard(Mutex_);
auto Func = [UUID](const UploadId &P) -> bool { return (P.UUID == UUID); };
OutStandingUploads_.erase(
std::remove_if(OutStandingUploads_.begin(), OutStandingUploads_.end(), Func),
OutStandingUploads_.end());
}
class FileUploaderPartHandler2 : public Poco::Net::PartHandler {
public:
FileUploaderPartHandler2(std::string Id, Poco::Logger &Logger, std::stringstream &ofs)
: Id_(std::move(Id)), Logger_(Logger), OutputStream_(ofs) {}
void handlePart(const Poco::Net::MessageHeader &Header, std::istream &Stream) {
FileType_ = Header.get(RESTAPI::Protocol::CONTENTTYPE, RESTAPI::Protocol::UNSPECIFIED);
if (Header.has(RESTAPI::Protocol::CONTENTDISPOSITION)) {
std::string Disposition;
Poco::Net::NameValueCollection Parameters;
Poco::Net::MessageHeader::splitParameters(
Header[RESTAPI::Protocol::CONTENTDISPOSITION], Disposition, Parameters);
Name_ = Parameters.get(RESTAPI::Protocol::NAME, RESTAPI::Protocol::UNNAMED);
}
Poco::CountingInputStream InputStream(Stream);
Poco::StreamCopier::copyStream(InputStream, OutputStream_);
Length_ = OutputStream_.str().size();
}
[[nodiscard]] uint64_t Length() const { return Length_; }
[[nodiscard]] std::string &Name() { return Name_; }
[[nodiscard]] std::string &ContentType() { return FileType_; }
private:
uint64_t Length_ = 0;
std::string FileType_;
std::string Name_;
std::string Id_;
Poco::Logger &Logger_;
std::stringstream &OutputStream_;
inline Poco::Logger &Logger() { return Logger_; };
};
class FormRequestHandler : public Poco::Net::HTTPRequestHandler {
public:
explicit FormRequestHandler(std::string UUID, Poco::Logger &L, const std::string &Type)
: UUID_(std::move(UUID)), Logger_(L), Type_(Type) {}
void handleRequest(Poco::Net::HTTPServerRequest &Request,
Poco::Net::HTTPServerResponse &Response) final {
Utils::SetThreadName("FileUploader");
const auto ContentType = Request.getContentType();
const auto Tokens =
Poco::StringTokenizer(ContentType, ";", Poco::StringTokenizer::TOK_TRIM);
poco_debug(Logger(), fmt::format("{}: Preparing to upload a file.", UUID_));
Poco::JSON::Object Answer;
try {
if (Poco::icompare(Tokens[0], "multipart/form-data") == 0 ||
Poco::icompare(Tokens[0], "multipart/mixed") == 0) {
const auto &BoundaryTokens =
Poco::StringTokenizer(Tokens[1], "=", Poco::StringTokenizer::TOK_TRIM);
if (BoundaryTokens[0] == "boundary") {
const std::string &Boundary = BoundaryTokens[1];
Poco::Net::MultipartReader Reader(Request.stream(), Boundary);
bool Done = false;
while (!Done) {
Poco::Net::MessageHeader Hdr;
Reader.nextPart(Hdr);
const auto PartContentType = Hdr.get("Content-Type", "");
if (PartContentType == "application/octet-stream" || PartContentType == "text/plain") {
std::stringstream FileContent;
Poco::StreamCopier::copyStream(Reader.stream(), FileContent);
Answer.set("filename", UUID_);
Answer.set("error", 0);
poco_debug(Logger(), fmt::format("{}: File uploaded.", UUID_));
StorageService()->AttachFileDataToCommand(UUID_, FileContent,
Type_);
std::ostream &ResponseStream = Response.send();
Poco::JSON::Stringifier::stringify(Answer, ResponseStream);
return;
} else {
std::stringstream OO;
Poco::StreamCopier::copyStream(Reader.stream(), OO);
}
if (!Reader.hasNextPart())
Done = true;
}
}
}
} catch (const Poco::Exception &E) {
Logger().log(E);
} catch (...) {
poco_debug(Logger(), "Exception while receiving uploaded file.");
}
poco_debug(Logger(), fmt::format("{}: Failed to upload a file.", UUID_));
std::string Error{"File rejected"};
StorageService()->CancelWaitFile(UUID_, Error);
Answer.set("filename", UUID_);
Answer.set("error", 13);
Answer.set("errorText", "Attached file is too large");
StorageService()->CancelWaitFile(UUID_, Error);
std::ostream &ResponseStream = Response.send();
Poco::JSON::Stringifier::stringify(Answer, ResponseStream);
}
inline Poco::Logger &Logger() { return Logger_; }
private:
std::string UUID_;
Poco::Logger &Logger_;
std::string Type_;
};
Poco::Net::HTTPRequestHandler *FileUpLoaderRequestHandlerFactory::createRequestHandler(
const Poco::Net::HTTPServerRequest &Request) {
poco_debug(Logger(), fmt::format("REQUEST({}): {} {}",
Utils::FormatIPv6(Request.clientAddress().toString()),
Request.getMethod(), Request.getURI()));
if (Request.getMethod() != Poco::Net::HTTPRequest::HTTP_POST ||
Request.getURI().size() < (URI_BASE.size() + 36)) {
poco_warning(Logger(),
fmt::format("ILLEGAL-REQUEST({}): {} {}. Dropped.",
Utils::FormatIPv6(Request.clientAddress().toString()),
Request.getMethod(), Request.getURI()));
return nullptr;
}
// The UUID should be after the /v1/upload/ part...
auto UUIDLocation = Request.getURI().find_first_of(URI_BASE);
if (UUIDLocation != std::string::npos) {
auto UUID = Request.getURI().substr(UUIDLocation + URI_BASE.size());
FileUploader::UploadId E;
if (FileUploader()->Find(UUID, E)) {
FileUploader()->RemoveRequest(UUID);
return new FormRequestHandler(UUID, Logger(), E.Type);
} else {
poco_warning(Logger(), fmt::format("Unknown UUID={}", UUID));
}
}
return nullptr;
}
bool FileUploader::Find(const std::string &UUID, UploadId &V) {
std::lock_guard G(Mutex_);
for (const auto &E : OutStandingUploads_) {
if (E.UUID == UUID) {
V = E;
return true;
}
}
return false;
}
void FileUploader::Stop() {
poco_notice(Logger(), "Stopping...");
for (const auto &svr : Servers_)
svr->stopAll(true);
Servers_.clear();
poco_notice(Logger(), "Stopped...");
}
} // namespace OpenWifi