93 lines
2.9 KiB
C++
93 lines
2.9 KiB
C++
#ifndef HTTPPROXYSERVER_H
|
||
#define HTTPPROXYSERVER_H
|
||
|
||
#include <QTcpServer>
|
||
#include <QTcpSocket>
|
||
#include <QFile>
|
||
#include <QFileInfo>
|
||
#include <QMimeDatabase>
|
||
#include <QMimeType>
|
||
#include <QDateTime>
|
||
#include <QRegularExpression>
|
||
#include <QDir>
|
||
#include <Qnetworkaccessmanager>
|
||
|
||
// Proxy server старается найти запрашиваемый файл, если его нет то он пытается запросить его на сервере
|
||
|
||
class HttpProxyServer : public QTcpServer
|
||
{
|
||
Q_OBJECT
|
||
private:
|
||
QString defaultPath;
|
||
QString projectPath = "/models";
|
||
QString enginePath;
|
||
QString m_targetHost = "192.168.0.169";
|
||
quint16 m_targetPort = 1234;
|
||
quint16 localPort;
|
||
QString usesPass = "admin:secret";
|
||
|
||
|
||
public:
|
||
const QString& getDefaultPath() { return defaultPath; };
|
||
void setProjectPath(const QString&path) { projectPath = path; }
|
||
static HttpProxyServer* Instance;
|
||
HttpProxyServer(quint16 port, QObject* parent = nullptr);
|
||
quint16 getLocalProt() const {return localPort; } ;
|
||
|
||
void setTargetHost(const QString& targetHost) {
|
||
m_targetHost = targetHost;
|
||
}
|
||
|
||
void setTargetPort(quint16 targetPort) {
|
||
m_targetPort = targetPort;
|
||
}
|
||
|
||
private slots:
|
||
|
||
void handleNewConnection()
|
||
{
|
||
while (hasPendingConnections()) {
|
||
QTcpSocket *socket = nextPendingConnection();
|
||
connect(socket, &QTcpSocket::readyRead, this, [this, socket]() {
|
||
handleRequest(socket);
|
||
});
|
||
connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
|
||
}
|
||
}
|
||
|
||
void handleRequest(QTcpSocket *socket);
|
||
|
||
private:
|
||
void copyHeaders(const QByteArray& request, QNetworkRequest& networkRequest);
|
||
|
||
int serveFile(QTcpSocket *socket, const QString &pathArg);
|
||
|
||
int serveFileWithRange(QTcpSocket *socket, const QString &path, const QString &rangeHeader);
|
||
|
||
void sendDirectoryListing(QTcpSocket *socket, const QString &path);
|
||
|
||
void sendError(QTcpSocket *socket, int code, const QString &message);
|
||
|
||
QString extractPathFromRequest(const QByteArray& request);
|
||
|
||
void sendProxyHeaders(QTcpSocket* clientSocket, QNetworkReply* reply);
|
||
|
||
void proxyRequest(QTcpSocket* clientSocket, const QString& path, const QByteArray& originalRequest);
|
||
void proxyRequestGet(QTcpSocket* clientSocket, const QString& path);
|
||
void sendErrorResponse(QTcpSocket* socket, int code, const QString& message)
|
||
{
|
||
QString response = QString("HTTP/1.1 %1 %2\r\n"
|
||
"Content-Type: text/plain\r\n"
|
||
"Connection: close\r\n"
|
||
"\r\n"
|
||
"%3")
|
||
.arg(code)
|
||
.arg(message)
|
||
.arg(message);
|
||
socket->write(response.toUtf8());
|
||
socket->disconnectFromHost();
|
||
}
|
||
};
|
||
|
||
#endif // HTTPPROXYSERVER_H
|