-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqfcgiapp.cpp
389 lines (320 loc) · 12.1 KB
/
qfcgiapp.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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/**
* This file is part of PasswordSender.
*
* PasswordSender is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* PasswordSender is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PasswordSender. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020 Wiebe Cazemier <[email protected]>
*/
#include "qfcgiapp.h"
#include "QTextStream"
#include "QHostAddress"
#include "QTimer"
#include "QThread"
#include <QString>
#include "iostream"
#include <QCommandLineParser>
#include <QDir>
#include <QRegularExpression>
QFcgiApp::QFcgiApp(int argc, char *argv[]) : QCoreApplication(argc, argv)
{
QCoreApplication::setApplicationName("PasswordSender");
QCommandLineParser parser;
parser.setApplicationDescription("FastCGI app for hosting a little webapp to send secrets.");
parser.addHelpOption();
parser.addOption({"listen-port", "The port to listen on. Always localhost. Default 9000.", "port", "9000"});
parser.addOption({"template-dir", "The dir with the templates. Should not be in the docroot of the webserver.", "dir"});
parser.addOption({"from", "E-mail header contents, like 'Chancellor Gowron <[email protected]>'", "from"});
parser.addOption({"subject", "Subject of the e-mail which contains the link", "subject"});
parser.addOption({"license", "Show license info."});
parser.process(*this);
if (parser.isSet("license"))
{
std::cout << "Copyright (C) 2020 Wiebe Cazemier." << std::endl
<< "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>." << std::endl
<< "This is free software: you are free to change and redistribute it." << std::endl
<< "There is NO WARRANTY, to the extent permitted by law." << std::endl
<< std::endl
<< "Written by Wiebe Cazemier <[email protected]>." << std::endl;
return;
}
bool isInt = false;
uint port = parser.value("listen-port").toUInt(&isInt);
if (!isInt)
{
qCritical("Port number is not a number.");
return;
}
templateDir = QDir::cleanPath(parser.value("template-dir"));
QDir dir(templateDir);
if (templateDir.isEmpty())
{
qCritical() << "Template dir is not given.";
return;
}
if (!dir.exists(templateDir) || !dir.isReadable())
{
qCritical() << "Template dir " << templateDir << "not found or not readable.";
return;
}
QRegularExpression r("^.+ <.+@.+>$");
if (!parser.isSet("from") || !r.match(parser.value("from")).hasMatch())
{
qWarning("'From' not in correct format like 'Chancellor Gowron <[email protected]>'");
return;
}
if (!parser.isSet("subject"))
{
qWarning("Subject not set");
return;
}
emailSender.reset(new EmailSender(parser.value("from"), parser.value("subject"), templateDir));
fcgi = new QFCgi(this);
connect(fcgi, &QFCgi::newRequest, this, &QFcgiApp::onNewRequest);
fcgi->configureListen(QHostAddress::Any, port);
this->fcgi->start();
if (!this->fcgi->isStarted())
{
qCritical() << this->fcgi->errorString();
return;
}
cleanupTimer.setInterval(1000*60);
cleanupTimer.setSingleShot(false);
connect(&cleanupTimer, &QTimer::timeout, this, &QFcgiApp::onCleanupTimerElapsed);
cleanupTimer.start();
initialized = true;
}
QFcgiApp::~QFcgiApp()
{
}
void QFcgiApp::renderReponse(const QString &templateFileName, const int httpCode, QIODevice *out, const QHash<QString,QString> &templateVariables)
{
const QString templateFilePath = QDir::cleanPath(templateDir + QDir::separator() + templateFileName);
QFile f(templateFilePath);
if (!f.open(QFile::ReadOnly))
{
QString msg = QString("Can't open template %1").arg(templateFilePath);
throw std::runtime_error(msg.toStdString());
}
QString templateData = QString::fromUtf8(f.readAll());
for (const QString &key : templateVariables.keys())
{
QString val = templateVariables[key];
if (key == "{userenteredlink}" && val.isEmpty())
val = "{removeline}";
templateData.replace(key, val.toHtmlEscaped());
}
QTextStream stream(&templateData);
QString line;
QString final;
while (stream.readLineInto(&line))
{
if (!line.contains("{removeline}"))
{
final.append(line);
final.append("\n");
}
}
QTextStream ts(out);
ts << "Status: " << httpCode << "\r\n"; // Not HTTP header, but FCGI header.
ts << "Content-Type: text/html\r\n";
ts << "Cache-Control: no-store\r\n";
ts << "\r\n";
ts << final;
ts.flush();
}
void QFcgiApp::onNewRequest(QFCgiRequest *request)
{
// request->getOut() is a stream which is used to write back information
// to the webserver.
//QTextStream ts(request->getOut());
//ts << "Content-Type: text/plain\n";
//ts << "\n";
//ts << QString("Hello from %1\n").arg(this->applicationName());
//ts << "This is what I received:\n";
try
{
bool contentLengthAvailable = false;
int contentLength = request->getParam("CONTENT_LENGTH").toInt(&contentLengthAvailable);
if (contentLength > (128 * 1024 * 1024))
throw std::runtime_error("Post-data too large");
QIODevice *in = request->getIn();
QIODevice *out = request->getOut();
connect(in, &QIODevice::readyRead, this, &QFcgiApp::onReadyRead);
RequestDownloader *downloader = new RequestDownloader(in, request, contentLength);
connect(downloader, &RequestDownloader::requestParsed, this, &QFcgiApp::requestParsed);
connect(in, &QIODevice::aboutToClose, this, &QFcgiApp::onConnectionClose);
connect(out, &QIODevice::aboutToClose, this, &QFcgiApp::onConnectionClose);
this->requests[in] = downloader;
downloader->readAvailableData();
}
catch (std::exception &ex)
{
QHash<QString,QString> vars;
vars["{errormsg}"] = ex.what();
renderReponse("errortemplate.html", 500, request->getOut(), vars);
request->endRequest(1);
}
}
void QFcgiApp::onReadyRead()
{
QIODevice *input = static_cast<QIODevice*>(sender());
RequestDownloader *downloader = this->requests[input];
try
{
downloader->readAvailableData();
}
catch (std::exception &ex)
{
QHash<QString,QString> vars;
vars["{errormsg}"] = ex.what();
renderReponse("errortemplate.html", 500, downloader->request->getOut(), vars);
downloader->request->endRequest(1);
}
}
void QFcgiApp::onUploadDone()
{
RequestUploader *uploader = static_cast<RequestUploader*>(sender());
uploader->getFcgiRequest()->endRequest(0);
}
void QFcgiApp::requestParsed(ParsedRequest *parsedRequest)
{
QIODevice *out = parsedRequest->fcgiRequest->getOut();
const auto &submittedSecretsConst = submittedSecrets;
try
{
if (parsedRequest->scriptURL == "/passwordsender/upload")
{
SubmittedSecret_p secret(new SubmittedSecret(parsedRequest));
if (!secret->isValid())
{
throw std::runtime_error("Secret invalid");
}
this->submittedSecrets.insert(secret->uuid, secret);
QString msg = QString("Informatie gestuurd naar %1").arg(secret->recipient);
this->emailSender->SendEmail(*secret);
QHash<QString,QString> vars;
vars["{message}"] = msg;
renderReponse("template.html", 200, out, vars);
parsedRequest->requestDone(0);
}
else if (parsedRequest->scriptURL == "/passwordsender/show")
{
const QString &uuid = parsedRequest->formFields["uuid"].value;
SubmittedSecret_p secret = submittedSecretsConst[uuid];
if (!secret)
{
throw UserError("Dit geheim bestaat niet (meer). Mogelijk is hij verlopen.", 404);
}
else if (!secret->isValid())
{
throw std::runtime_error("Secret invalid");
}
QString fileLink = "{removeline}";
QString fileName = "{removeline}";
if (!secret->secretFiles.empty())
{
std::shared_ptr<SecretFile> file = *secret->secretFiles.begin(); // TODO: multiple files. The first is just for testing.
fileLink = file->getLink();
fileName = file->name;
}
QHash<QString,QString> vars;
vars["{secret}"] = secret->passwordField;
vars["{filelink}"] = fileLink;
vars["{filename}"] = fileName;
vars["{userenteredlink}"] = secret->userEnteredLink;
renderReponse("showsecrettemplate.html", 200, out, vars);
secret->expireSoon();
parsedRequest->requestDone(0);
}
else if (parsedRequest->scriptURL.startsWith("/passwordsender/showlanding/"))
{
const QStringList fields = parsedRequest->scriptURL.split('/');
const QString &uuid = fields[3];
if (uuid.isEmpty())
{
throw UserError("Geen geheim opgegeven. Je zit de boel te flessen.", 500);
}
QHash<QString,QString> vars;
vars["{uuid}"] = uuid;
renderReponse("showlandingtemplate.html", 200, out, vars);
parsedRequest->requestDone(0);
}
else if (parsedRequest->scriptURL.startsWith("/passwordsender/downloadfile/")) // URL like /passwordsender/downloadfile/[uuid-secret]/[uuid-file]
{
const QStringList fields = parsedRequest->scriptURL.split('/');
const QString &secretUuid = fields[3];
const QString &fileUuid = fields[4];
if (secretUuid.isEmpty() || fileUuid.isEmpty())
{
throw UserError("Geen geheim of bestand opgegeven. Je zit de boel te flessen.");
}
SubmittedSecret_p secret = submittedSecretsConst[secretUuid];
if (!secret)
{
throw UserError("Dit geheim bestaat niet (meer). Mogelijk is hij verlopen.");
}
else if (!secret->isValid())
{
throw std::runtime_error("Secret invalid");
}
std::shared_ptr<SecretFile> secretFile = secret->secretFiles[fileUuid];
QIODevice *out = parsedRequest->fcgiRequest->getOut();
RequestUploader *uploader = new RequestUploader(out, secretFile, parsedRequest->fcgiRequest);
connect(uploader, &RequestUploader::uploadDone, this, &QFcgiApp::onUploadDone);
uploader->uploadNextChunk();
}
else
{
throw UserError("Pagina bestaat niet.", 404);
}
}
catch (UserError &ex)
{
qWarning() << ex.what();
QHash<QString,QString> vars;
vars["{errormsg}"] = ex.what();
renderReponse("errortemplate.html", ex.httpCode, out, vars);
parsedRequest->requestDone(1);
}
catch (std::exception &ex)
{
qWarning() << ex.what();
QHash<QString,QString> vars;
vars["{errormsg}"] = "System error";
renderReponse("errortemplate.html", 500, out, vars);
parsedRequest->requestDone(1);
}
}
void QFcgiApp::onConnectionClose()
{
QIODevice *ioDev = dynamic_cast<QIODevice*>(sender());
if (this->requests.contains(ioDev))
{
this->requests.remove(ioDev);
ioDev = nullptr;
}
}
void QFcgiApp::onCleanupTimerElapsed()
{
auto i = submittedSecrets.begin();
while(i != submittedSecrets.end())
{
SubmittedSecret_p p = *i;
if (p && p->hasExpired())
{
i = submittedSecrets.erase(i);
}
else
i++;
}
}