458 lines
15 KiB
C++
458 lines
15 KiB
C++
#include "httpproxyserver.h"
|
||
|
||
#include "HttpProxyServer.h"
|
||
#include <QStandardPaths>
|
||
#include <QNetworkReply>
|
||
#include <thread>
|
||
#include <qeventloop.h>
|
||
#include <qtimer.h>
|
||
#include "settingsrepository.h"
|
||
#include "QCoreApplication"
|
||
|
||
HttpProxyServer* HttpProxyServer::Instance = 0;
|
||
// extern const char* PotreeViewer;
|
||
|
||
HttpProxyServer::HttpProxyServer(quint16 port, QObject* parent) : QTcpServer(parent), localPort(port)
|
||
{
|
||
QString defaultDataPath = "data";
|
||
QDir appDir = QDir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation));
|
||
defaultPath = SettingsRepository::instance().defaultProjectDirectory();
|
||
listen(QHostAddress::Any, port);
|
||
connect(this, &HttpProxyServer::newConnection, this, &HttpProxyServer::handleNewConnection);
|
||
qDebug() << "Serving at port" << port;
|
||
}
|
||
|
||
void HttpProxyServer::handleRequest(QTcpSocket *socket)
|
||
{
|
||
QByteArray request = socket->readAll();
|
||
QList<QByteArray> lines = request.split('\n');
|
||
|
||
if (lines.isEmpty()) return;
|
||
|
||
QList<QByteArray> requestLine = lines[0].trimmed().split(' ');
|
||
if (requestLine.size() < 2) return;
|
||
|
||
QString method = requestLine[0];
|
||
QString path = requestLine[1];
|
||
|
||
if (path.startsWith("/")) {
|
||
path = path.mid(1);
|
||
}
|
||
|
||
if (path.isEmpty()) {
|
||
path = ".";
|
||
}
|
||
|
||
if (path == "."){
|
||
bool isUpgrade = false;
|
||
for (int i = 1; i < lines.size(); ++i) {
|
||
QByteArray line = lines[i].trimmed();
|
||
|
||
if (line.startsWith("Upgrade:") || line.startsWith("upgrade:")) {
|
||
// Например: "Upgrade: websocket"
|
||
isUpgrade = true;
|
||
break;
|
||
}
|
||
|
||
if (line.startsWith("Connection:") || line.startsWith("connection:")) {
|
||
// Например: "Connection: Upgrade"
|
||
if (line.contains("pgrade")) {
|
||
isUpgrade = true;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (isUpgrade == false) {
|
||
projectPath = "";
|
||
}
|
||
}
|
||
|
||
// Parse headers
|
||
QMap<QString, QString> headers;
|
||
for (int i = 1; i < lines.size(); ++i) {
|
||
QByteArray line = lines[i].trimmed();
|
||
if (line.isEmpty()) break;
|
||
|
||
int colonPos = line.indexOf(':');
|
||
if (colonPos > 0) {
|
||
QString key = line.left(colonPos).trimmed();
|
||
QString value = line.mid(colonPos + 1).trimmed();
|
||
headers[key] = value;
|
||
}
|
||
}
|
||
|
||
int ret_code;
|
||
if (path.contains("metadata")) {
|
||
int _d = 0;
|
||
}
|
||
// Handle range request
|
||
if (headers.contains("Range")) {
|
||
ret_code = serveFileWithRange(socket, path, headers["Range"]);
|
||
if (ret_code) {
|
||
proxyRequest(socket, path, request);
|
||
}
|
||
} else {
|
||
if (path == "/") {
|
||
|
||
}
|
||
ret_code = serveFile(socket, path);
|
||
if (ret_code) {
|
||
proxyRequest(socket, path, request);
|
||
}
|
||
}
|
||
}
|
||
|
||
int HttpProxyServer::serveFileWithRange(QTcpSocket *socket, const QString &pathArg, const QString &rangeHeader)
|
||
{
|
||
QString path = defaultPath + projectPath + "/" + pathArg;
|
||
|
||
QFileInfo fileInfo(path);
|
||
|
||
qDebug() << "Try serve file: " << path;
|
||
if (!fileInfo.exists() || !fileInfo.isFile()) {
|
||
return 1;
|
||
}
|
||
|
||
QFile file(path);
|
||
if (!file.open(QIODevice::ReadOnly)) {
|
||
return 2;
|
||
}
|
||
|
||
qint64 fileSize = file.size();
|
||
QMimeDatabase mimeDb;
|
||
QMimeType mimeType = mimeDb.mimeTypeForFile(path);
|
||
|
||
// Parse range header: bytes=start-end
|
||
QRegularExpression regex("bytes=(\\d+)-(\\d*)");
|
||
QRegularExpressionMatch match = regex.match(rangeHeader);
|
||
|
||
if (!match.hasMatch()) {
|
||
// Malformed range header - serve full content
|
||
serveFile(socket, path);
|
||
return 3;
|
||
}
|
||
|
||
qint64 start = match.captured(1).toLongLong();
|
||
QString endStr = match.captured(2);
|
||
qint64 end = endStr.isEmpty() ? fileSize - 1 : endStr.toLongLong();
|
||
|
||
if (start >= fileSize) {
|
||
sendError(socket, 416, "Requested Range Not Satisfiable");
|
||
return 4;
|
||
}
|
||
|
||
if (end >= fileSize) {
|
||
end = fileSize - 1;
|
||
}
|
||
|
||
qint64 length = end - start + 1;
|
||
|
||
if (!file.seek(start)) {
|
||
sendError(socket, 500, "Internal Server Error");
|
||
return 5;
|
||
}
|
||
|
||
QByteArray response = "HTTP/1.1 206 Partial Content\r\n";
|
||
response += "Content-Type: " + mimeType.name().toUtf8() + "\r\n";
|
||
response += "Content-Range: bytes " + QByteArray::number(start) + "-" +
|
||
QByteArray::number(end) + "/" + QByteArray::number(fileSize) + "\r\n";
|
||
response += "Content-Length: " + QByteArray::number(length) + "\r\n";
|
||
response += "Connection: close\r\n\r\n";
|
||
|
||
socket->write(response);
|
||
|
||
// Send the file in chunks to avoid loading large files into memory
|
||
const qint64 chunkSize = 64 * 1024; // 64KB chunks
|
||
qint64 remaining = length;
|
||
|
||
while (remaining > 0 && socket->state() == QAbstractSocket::ConnectedState) {
|
||
QByteArray chunk = file.read(qMin(remaining, chunkSize));
|
||
if (chunk.isEmpty()) break;
|
||
|
||
socket->write(chunk);
|
||
socket->waitForBytesWritten();
|
||
remaining -= chunk.size();
|
||
}
|
||
|
||
file.close();
|
||
socket->disconnectFromHost();
|
||
|
||
return 0;
|
||
}
|
||
|
||
QString HttpProxyServer::extractPathFromRequest(const QByteArray& request)
|
||
{
|
||
int start = request.indexOf(' ') + 1;
|
||
int end = request.indexOf(' ', start);
|
||
return QString::fromUtf8(request.mid(start, end - start)).split('?').first();
|
||
}
|
||
|
||
void HttpProxyServer::sendProxyHeaders(QTcpSocket *clientSocket, QNetworkReply *reply)
|
||
{
|
||
clientSocket->write("HTTP/1.1 200 OK\r\n");
|
||
foreach(const QByteArray & header, reply->rawHeaderList()) {
|
||
clientSocket->write(header + ": " + reply->rawHeader(header) + "\r\n");
|
||
}
|
||
clientSocket->write("\r\n");
|
||
clientSocket->setProperty("headersSent", true);
|
||
}
|
||
|
||
void HttpProxyServer::copyHeaders(const QByteArray& request, QNetworkRequest& networkRequest)
|
||
{
|
||
QList<QByteArray> headers = request.split('\n');
|
||
for (const QByteArray& header : headers) {
|
||
int colonPos = header.indexOf(':');
|
||
if (colonPos > 0) {
|
||
QByteArray name = header.left(colonPos).trimmed();
|
||
QByteArray value = header.mid(colonPos + 1).trimmed();
|
||
if (!name.isEmpty() && !value.isEmpty()) {
|
||
networkRequest.setRawHeader(name, value);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
int HttpProxyServer::serveFile(QTcpSocket *socket, const QString &pathArg)
|
||
{
|
||
QString path = defaultPath + projectPath + "/" + pathArg;
|
||
|
||
QFileInfo fileInfo(path);
|
||
QMimeDatabase mimeDb;
|
||
QMimeType mimeType;
|
||
QByteArray content = "";
|
||
if (pathArg.startsWith("src/pages/PotreeViewer.tsx?t")) {
|
||
static QDir dir(QCoreApplication::applicationDirPath());
|
||
QString filePath = dir.absoluteFilePath("QtQuckApp\\PotreeViewer.js");
|
||
|
||
QFile file(filePath);
|
||
if (!file.open(QIODevice::ReadOnly)) {
|
||
return 2;
|
||
}
|
||
|
||
content = file.readAll();
|
||
file.close();
|
||
mimeType = mimeDb.mimeTypeForFile(filePath);//"application/octet-stream";
|
||
// content = PotreeViewer;
|
||
} else if (pathArg.startsWith("src/pages/PotreeViewer.tsx")) {
|
||
|
||
static QDir dir(QCoreApplication::applicationDirPath());
|
||
|
||
QString filePath = dir.absoluteFilePath("QtQuckApp\\PotreeViewerV.js");
|
||
|
||
QFile file(filePath);
|
||
if (!file.open(QIODevice::ReadOnly)) {
|
||
return 2;
|
||
}
|
||
|
||
content = file.readAll();
|
||
file.close();
|
||
mimeType = mimeDb.mimeTypeForFile(filePath);//"application/octet-stream";
|
||
// content = PotreeViewer;
|
||
} else {
|
||
if (fileInfo.isDir()) {
|
||
sendDirectoryListing(socket, path);
|
||
return 0;
|
||
}
|
||
|
||
if (!fileInfo.exists() || !fileInfo.isFile()) {
|
||
//sendError(socket, 404, "File not found");
|
||
return 1;
|
||
}
|
||
|
||
QFile file(path);
|
||
if (!file.open(QIODevice::ReadOnly)) {
|
||
//sendError(socket, 403, "Forbidden");
|
||
return 2;
|
||
}
|
||
content = file.readAll();
|
||
file.close();
|
||
mimeType = mimeDb.mimeTypeForFile(path);
|
||
}
|
||
|
||
|
||
|
||
|
||
QByteArray response = "HTTP/1.1 200 OK\r\n";
|
||
response += "Content-Type: " + mimeType.name().toUtf8() + "\r\n";
|
||
response += "Content-Length: " + QByteArray::number(content.size()) + "\r\n";
|
||
response += "Connection: close\r\n\r\n";
|
||
|
||
socket->write(response);
|
||
socket->write(content);
|
||
socket->disconnectFromHost();
|
||
return 0;
|
||
}
|
||
|
||
void HttpProxyServer::proxyRequest(QTcpSocket* clientSocket, const QString& path, const QByteArray& originalRequest)
|
||
{
|
||
// Читаем все данные от клиента
|
||
QByteArray requestData = originalRequest;
|
||
|
||
if (requestData.isEmpty()) {
|
||
qWarning() << "Empty request from client";
|
||
clientSocket->close();
|
||
return;
|
||
}
|
||
|
||
// Логируем входящий запрос
|
||
qDebug() << "Received request:\n" << requestData;
|
||
|
||
// Создаем соединение с целевым сервером
|
||
QTcpSocket* serverSocket = new QTcpSocket(this);
|
||
serverSocket->connectToHost(m_targetHost, m_targetPort);
|
||
|
||
if (!serverSocket->waitForConnected(5000)) {
|
||
qWarning() << "Failed to connect to target server:" << serverSocket->errorString();
|
||
serverSocket->deleteLater();
|
||
sendErrorResponse(clientSocket, 502, "Bad Gateway");
|
||
return;
|
||
}
|
||
|
||
// Отправляем запрос на целевой сервер
|
||
serverSocket->write(requestData);
|
||
serverSocket->flush();
|
||
|
||
// Устанавливаем соединение между клиентом и сервером
|
||
connect(serverSocket, &QTcpSocket::readyRead, [clientSocket, serverSocket]() {
|
||
QByteArray response = serverSocket->readAll();
|
||
clientSocket->write(response);
|
||
clientSocket->flush();
|
||
qDebug() << "Forwarded response of size:" << response.size();
|
||
});
|
||
|
||
connect(serverSocket, &QTcpSocket::disconnected, [clientSocket, serverSocket]() {
|
||
serverSocket->deleteLater();
|
||
clientSocket->disconnectFromHost();
|
||
});
|
||
|
||
connect(clientSocket, &QTcpSocket::disconnected, [serverSocket]() {
|
||
serverSocket->disconnectFromHost();
|
||
});
|
||
}
|
||
|
||
void HttpProxyServer::proxyRequestGet(QTcpSocket* clientSocket, const QString& path)
|
||
{
|
||
// Читаем все данные от клиента
|
||
|
||
// Создаем соединение с целевым сервером
|
||
QTcpSocket* serverSocket = new QTcpSocket(this);
|
||
serverSocket->connectToHost(m_targetHost, m_targetPort);
|
||
|
||
|
||
if (!serverSocket->waitForConnected(5000)) {
|
||
qWarning() << "Failed to connect to target server:" << serverSocket->errorString();
|
||
serverSocket->deleteLater();
|
||
sendErrorResponse(clientSocket, 502, "Bad Gateway");
|
||
return;
|
||
}
|
||
|
||
// Отправляем запрос на целевой сервер
|
||
QByteArray getRequest = "GET " + path.toUtf8() + " HTTP/1.1\r\n";
|
||
|
||
getRequest += "Host: " + m_targetHost.toUtf8();
|
||
if (m_targetPort != 80 && m_targetPort != 443) { // Если нестандартный порт, добавляем
|
||
getRequest += ":" + QByteArray::number(m_targetPort);
|
||
}
|
||
|
||
getRequest += "\r\n";
|
||
|
||
if (usesPass != "") {
|
||
QByteArray encodedUserPass = usesPass.toUtf8().toBase64();
|
||
getRequest += "Authorization: Basic " + encodedUserPass + "\r\n";
|
||
}
|
||
|
||
getRequest += "Connection: close\r\n"; // Закрываем соединение после ответа
|
||
getRequest += "\r\n"; // Завершаем заголовки
|
||
|
||
// Отправляем GET-запрос на целевой сервер
|
||
serverSocket->write(getRequest);
|
||
serverSocket->flush();
|
||
|
||
// Устанавливаем соединение между клиентом и сервером
|
||
connect(serverSocket, &QTcpSocket::readyRead, [clientSocket, serverSocket]() {
|
||
QByteArray response = serverSocket->readAll();
|
||
clientSocket->write(response);
|
||
clientSocket->flush();
|
||
qDebug() << "Forwarded response of size:" << response.size();
|
||
});
|
||
|
||
connect(serverSocket, &QTcpSocket::disconnected, [clientSocket, serverSocket]() {
|
||
serverSocket->deleteLater();
|
||
clientSocket->disconnectFromHost();
|
||
});
|
||
|
||
connect(clientSocket, &QTcpSocket::disconnected, [serverSocket]() {
|
||
serverSocket->disconnectFromHost();
|
||
});
|
||
}
|
||
|
||
// QString getPage(QString metaFilePath);
|
||
|
||
void HttpProxyServer::sendDirectoryListing(QTcpSocket *socket, const QString &path)
|
||
{
|
||
QDir dir(path);
|
||
if (!dir.exists()) {
|
||
sendError(socket, 404, "Directory not found");
|
||
return;
|
||
}
|
||
QString html;
|
||
|
||
QString pathMathDataCheck = dir.absoluteFilePath("metadata.json");
|
||
|
||
QFileInfo metadataFile(pathMathDataCheck);
|
||
if (metadataFile.exists()) {
|
||
projectPath = path.mid(defaultPath.length());
|
||
|
||
QByteArray response = "HTTP/1.1 302 Found\r\n";
|
||
response += "Location: /viewer\r\n";
|
||
response += "Content-Type: text/html\r\n";
|
||
response += "Content-Length: 0\r\n"; // Тело ответа отсутствует
|
||
response += "Connection: close\r\n\r\n";
|
||
socket->write(response);
|
||
socket->disconnectFromHost();
|
||
return;
|
||
}
|
||
else {
|
||
|
||
QStringList entries = dir.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
|
||
|
||
html = "<html><head><title>Directory listing for /" + path + "</title></head><body>";
|
||
html += "<h1>Directory listing for /" + path + "</h1><hr><ul>";
|
||
|
||
for (const QString& entry : entries) {
|
||
QString fullPath = path + "/" + entry;
|
||
QFileInfo info(fullPath);
|
||
// если директория добавляем слэш
|
||
QString postFix = info.isDir() ? "/" : "";//? "-" : QString::number(info.size());
|
||
html += QString("<li><a href=\"%1\">%1</a></li>").arg(entry + postFix);
|
||
}
|
||
|
||
html += "</ul><hr></body></html>";
|
||
}
|
||
QByteArray response = "HTTP/1.1 200 OK\r\n";
|
||
response += "Content-Type: text/html\r\n";
|
||
response += "Content-Length: " + QByteArray::number(html.toUtf8().size()) + "\r\n";
|
||
response += "Connection: close\r\n\r\n";
|
||
response += html.toUtf8();
|
||
|
||
socket->write(response);
|
||
socket->disconnectFromHost();
|
||
}
|
||
|
||
void HttpProxyServer::sendError(QTcpSocket *socket, int code, const QString &message)
|
||
{
|
||
QString responseText = QString("HTTP/1.1 %1 %2\r\n"
|
||
"Content-Type: text/plain\r\n"
|
||
"Connection: close\r\n\r\n"
|
||
"%1 %2").arg(code).arg(message);
|
||
|
||
socket->write(responseText.toUtf8());
|
||
socket->disconnectFromHost();
|
||
}
|
||
|
||
#include <QString>
|
||
#include <qcoreapplication.h>
|
||
|
||
|