proxylight/src/main.cpp

104 lines
3.7 KiB
C++

#include "proxyserver.h"
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTextStream>
#include <QFile>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
app.setApplicationName("proxylight");
app.setApplicationVersion("0.2");
QCommandLineParser commandLineParser;
commandLineParser.addHelpOption();
commandLineParser.addVersionOption();
commandLineParser.addPositionalArgument("config", "Configuration file.");
commandLineParser.process(app);
const QStringList args = commandLineParser.positionalArguments();
if (args.count() != 1) {
QTextStream(stderr) << "Configuration file not defined!" << Qt::endl;
return 1;
}
const QString configFile = args.at(0);
if (!QFile::exists(configFile)) {
QTextStream(stderr) << "Configuration file " << configFile << " not found!" << Qt::endl;
return 1;
}
QFile configFileIO(configFile);
if (!configFileIO.open(QIODevice::ReadOnly)) {
QTextStream(stderr) << "Configuration file " << configFile << " can't be read!" << Qt::endl;
return 1;
}
else {
QTextStream(stderr) << "Configuration file " << configFile << " found!" << Qt::endl;
}
const QByteArray configData = configFileIO.readAll();
const QJsonDocument jsonDocument = QJsonDocument::fromJson(configData);
const QJsonObject jsonObject = jsonDocument.object();
for (auto it = jsonObject.constBegin(); it != jsonObject.constEnd(); it++) {
const QJsonValue value = it.value();
if (!value.isObject())
break;
const QString serverName = it.key();
int localPort = -1;
int remotePort = -1;
QString serverBind, remoteHost;
const QJsonObject object = value.toObject();
for (auto it = object.constBegin(); it != object.constEnd(); it++) {
const QString key = it.key();
if (key == "Bind") {
const QJsonValue value = it.value();
if (value.isString()) {
serverBind = value.toString();
}
}
if (key == "LocalPort") {
const QJsonValue value = it.value();
if (value.isDouble()) {
localPort = value.toInt();
}
else if (value.isString()) {
bool ok;
localPort = value.toString().toInt(&ok);
}
}
if (key == "RemotePort") {
const QJsonValue value = it.value();
if (value.isDouble()) {
remotePort = value.toInt();
}
else if (value.isString()) {
bool ok;
remotePort = value.toString().toInt(&ok);
}
}
if (key == "RemoteHost") {
const QJsonValue value = it.value();
if (value.isString()) {
remoteHost = value.toString();
}
}
}
if (localPort == -1 || remotePort == -1 || remoteHost.isEmpty()) {
QTextStream(stderr) << serverName << ": Loading failed!" << Qt::endl;
break;
}
ProxyServer *proxyServer = new ProxyServer(localPort, remotePort, remoteHost, serverName, serverBind);
if (!proxyServer->isListening()) {
QTextStream(stderr) << serverName << ": Binding failed!" << Qt::endl;
proxyServer->deleteLater();
break;
}
QTextStream(stderr) << serverName << ": Proxy started!" << Qt::endl;
}
return app.exec();
}