-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimplehttpfileserver.cpp
More file actions
339 lines (282 loc) · 9.96 KB
/
simplehttpfileserver.cpp
File metadata and controls
339 lines (282 loc) · 9.96 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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
#include "simplehttpfileserver.h"
#include <QFile>
#include <QTextStream>
#include <QFileInfo>
#include <QDateTime>
#include <QDebug>
#include<QUrl>
SimpleHttpFileServer::SimpleHttpFileServer(const QString& directory, int port, QObject* parent)
: QObject(parent), m_directory(directory), m_port(port), m_running(false), m_server(nullptr)
{
}
SimpleHttpFileServer::~SimpleHttpFileServer()
{
stop();
}
bool SimpleHttpFileServer::start()
{
if (m_running)
return true;
QDir dir(m_directory);
if (!dir.exists()) {
if (!dir.mkpath(".")) {
emit error("Failed to create directory: " + m_directory);
return false;
}
}
m_server = new QTcpServer(this);
connect(m_server, &QTcpServer::newConnection, this, &SimpleHttpFileServer::onNewConnection);
if (!m_server->listen(QHostAddress::LocalHost, m_port)) {
emit error("Failed to start HTTP server on port " + QString::number(m_port));
m_server->deleteLater();
m_server = nullptr;
return false;
}
m_running = true;
emit started();
return true;
}
void SimpleHttpFileServer::stop()
{
if (m_running && m_server) {
m_server->close();
m_server->deleteLater();
m_server = nullptr;
m_running = false;
emit stopped();
}
}
bool SimpleHttpFileServer::isRunning() const
{
return m_running;
}
QString SimpleHttpFileServer::getDirectory() const
{
return m_directory;
}
int SimpleHttpFileServer::getPort() const
{
return m_port;
}
void SimpleHttpFileServer::onNewConnection()
{
while (m_server->hasPendingConnections()) {
QTcpSocket* socket = m_server->nextPendingConnection();
connect(socket, &QTcpSocket::readyRead, this, &SimpleHttpFileServer::onReadyRead);
connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
}
}
void SimpleHttpFileServer::onReadyRead()
{
QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
if (!socket)
return;
m_buffers[socket].append(socket->readAll());
// Check if we have a full HTTP request (look for double CRLF)
if (!m_buffers[socket].contains("\r\n\r\n"))
return;
handleRequest(socket);
m_buffers.remove(socket);
}
//handlerequest version that protects against spaces in filenames
void SimpleHttpFileServer::handleRequest(QTcpSocket* socket)
{
QByteArray request = m_buffers.value(socket);
QTextStream stream(request);
QString line = stream.readLine();
QString method, path;
QTextStream lineStream(&line);
lineStream >> method >> path;
if (method != "GET") {
sendNotFound(socket);
return;
}
// FIX: URL decode the path before using it!
QString decodedPath = QUrl::fromPercentEncoding(path.toUtf8());
if (decodedPath.contains("..")) {
sendNotFound(socket);
return;
}
// Use the DECODED path to find the file
QString requestedPath = QDir::cleanPath(m_directory + "/" + decodedPath);
QString baseDir = QDir(m_directory).absolutePath();
if (!requestedPath.startsWith(baseDir)) {
sendNotFound(socket);
return;
}
QFileInfo info(requestedPath);
if (info.isDir()) {
sendDirectoryListing(socket, requestedPath);
} else if (info.isFile()) {
sendFile(socket, requestedPath);
} else {
sendNotFound(socket);
}
}
void SimpleHttpFileServer::sendDirectoryListing(QTcpSocket* socket, const QString& dirPath)
{
QDir dir(dirPath);
if (!dir.exists()) {
sendNotFound(socket);
return;
}
QString relativePath = QDir(m_directory).relativeFilePath(dirPath);
if (!relativePath.isEmpty() && !relativePath.endsWith('/')) {
relativePath += '/';
}
QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name);
QString html = "<html><head><title>Shared Files</title></head><body>";
html += "<h1>Available Files</h1><ul>";
for (const QString& file : files) {
QString fileUrl = "/" + relativePath + file; // Correct URL for subdir files
// protect against spaces in urls
QString encodedFileUrl = QUrl::toPercentEncoding(fileUrl, "/");
html += QString("<li><a href=\"%1\">%2</a></li>")
.arg(encodedFileUrl.toHtmlEscaped(), file.toHtmlEscaped());
// .arg(fileUrl.toHtmlEscaped(), file.toHtmlEscaped());
}
html += "</ul></body></html>";
QByteArray response;
response += "HTTP/1.1 200 OK\r\n";
response += "Content-Type: text/html; charset=utf-8\r\n";
response += "Content-Length: " + QByteArray::number(html.toUtf8().size()) + "\r\n";
response += "Connection: close\r\n";
response += "\r\n";
response += html.toUtf8();
socket->write(response);
socket->disconnectFromHost();
}
void SimpleHttpFileServer::sendFile(QTcpSocket* socket, const QString& fullFilePath)
{
QFile file(fullFilePath);
if (!file.exists() || !file.open(QIODevice::ReadOnly)) {
sendNotFound(socket);
return;
}
QByteArray fileData = file.readAll();
file.close();
QString fileName = QFileInfo(file).fileName();
// Basic content type detection
QString contentType = "application/octet-stream";
// ===== Supported File Extensions =====
// Text & Documents
if (fileName.endsWith(".txt"))
contentType = "text/plain";
else if (fileName.endsWith(".html") || fileName.endsWith(".htm"))
contentType = "text/html";
else if (fileName.endsWith(".css"))
contentType = "text/css";
else if (fileName.endsWith(".js"))
contentType = "application/javascript";
else if (fileName.endsWith(".json"))
contentType = "application/json";
else if (fileName.endsWith(".xml"))
contentType = "application/xml";
else if (fileName.endsWith(".csv"))
contentType = "text/csv";
else if (fileName.endsWith(".pdf"))
contentType = "application/pdf";
// Images
else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg"))
contentType = "image/jpeg";
else if (fileName.endsWith(".png"))
contentType = "image/png";
else if (fileName.endsWith(".gif"))
contentType = "image/gif";
else if (fileName.endsWith(".svg"))
contentType = "image/svg+xml";
else if (fileName.endsWith(".webp"))
contentType = "image/webp";
else if (fileName.endsWith(".bmp"))
contentType = "image/bmp";
else if (fileName.endsWith(".ico"))
contentType = "image/x-icon";
// Audio
else if (fileName.endsWith(".mp3"))
contentType = "audio/mpeg";
else if (fileName.endsWith(".wav"))
contentType = "audio/wav";
else if (fileName.endsWith(".ogg"))
contentType = "audio/ogg";
else if (fileName.endsWith(".flac"))
contentType = "audio/flac";
else if (fileName.endsWith(".m4a"))
contentType = "audio/mp4";
// Video
else if (fileName.endsWith(".mp4"))
contentType = "video/mp4";
else if (fileName.endsWith(".webm"))
contentType = "video/webm";
else if (fileName.endsWith(".mkv"))
contentType = "video/x-matroska";
else if (fileName.endsWith(".avi"))
contentType = "video/x-msvideo";
else if (fileName.endsWith(".mov"))
contentType = "video/quicktime";
// Archives
else if (fileName.endsWith(".zip"))
contentType = "application/zip";
else if (fileName.endsWith(".tar"))
contentType = "application/x-tar";
else if (fileName.endsWith(".gz") || fileName.endsWith(".tgz"))
contentType = "application/gzip";
else if (fileName.endsWith(".7z"))
contentType = "application/x-7z-compressed";
else if (fileName.endsWith(".rar"))
contentType = "application/x-rar-compressed";
// Office & Documents
else if (fileName.endsWith(".doc") || fileName.endsWith(".docx"))
contentType = "application/msword";
else if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx"))
contentType = "application/vnd.ms-excel";
else if (fileName.endsWith(".ppt") || fileName.endsWith(".pptx"))
contentType = "application/vnd.ms-powerpoint";
else if (fileName.endsWith(".odt"))
contentType = "application/vnd.oasis.opendocument.text";
else if (fileName.endsWith(".ods"))
contentType = "application/vnd.oasis.opendocument.spreadsheet";
// Executables & Binaries
else if (fileName.endsWith(".exe") || fileName.endsWith(".msi"))
contentType = "application/octet-stream"; // Forces download
else if (fileName.endsWith(".deb"))
contentType = "application/vnd.debian.binary-package";
else if (fileName.endsWith(".rpm"))
contentType = "application/x-rpm";
else if (fileName.endsWith(".apk"))
contentType = "application/vnd.android.package-archive";
// Fonts
else if (fileName.endsWith(".ttf"))
contentType = "font/ttf";
else if (fileName.endsWith(".woff"))
contentType = "font/woff";
else if (fileName.endsWith(".woff2"))
contentType = "font/woff2";
QString disposition = QString("attachment; filename=\"%1\"").arg(fileName);
QByteArray response;
response += "HTTP/1.1 200 OK\r\n";
response += "Content-Type: " + contentType.toUtf8() + "\r\n";
response += "Content-Disposition: " + disposition.toUtf8() + "\r\n";
response += "Content-Length: " + QByteArray::number(fileData.size()) + "\r\n";
response += "Connection: close\r\n";
response += "\r\n";
response += fileData;
socket->write(response);
socket->disconnectFromHost();
}
void SimpleHttpFileServer::sendNotFound(QTcpSocket* socket)
{
QByteArray response;
response += "HTTP/1.1 404 Not Found\r\n";
response += "Content-Type: text/plain\r\n";
response += "Content-Length: 13\r\n";
response += "Connection: close\r\n";
response += "\r\n";
response += "404 Not Found";
socket->write(response);
socket->disconnectFromHost();
}
void SimpleHttpFileServer::restart()
{
stop();
start();
}