code cleaning

This commit is contained in:
csoler 2021-12-19 18:40:44 +01:00
parent 37d4e4f3df
commit 9684b2ed94
20 changed files with 14 additions and 297 deletions

View File

@ -737,8 +737,7 @@ HEADERS += tor/AddOnionCommand.h \
tor/TorControlCommand.h \
tor/TorControlSocket.h \
tor/TorManager.h \
tor/TorProcess.h \
tor/Useful.h
tor/TorProcess.h
SOURCES += tor/AddOnionCommand.cpp \
tor/AuthenticateCommand.cpp \

View File

@ -41,9 +41,6 @@ class HiddenService;
class AddOnionCommand : public TorControlCommand
{
// Q_PROPERTY(std::string errorMessage READ errorMessage CONSTANT)
// Q_PROPERTY(bool successful READ isSuccessful CONSTANT)
public:
AddOnionCommand(HiddenService *service);
@ -52,7 +49,6 @@ public:
std::string errorMessage() const { return m_errorMessage; }
bool isSuccessful() const;
// signals:
void set_succeeded_callback(const std::function<void(void)>& f) { mSucceeded=f;}
void set_failed_callback(const std::function<void(int)>& f) { mFailed=f;}

View File

@ -33,7 +33,6 @@
#include <iostream>
#include "CryptoKey.h"
#include "Useful.h"
#include <openssl/bn.h>
#include <openssl/bio.h>

View File

@ -30,8 +30,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GETCONFCOMMAND_H
#define GETCONFCOMMAND_H
#pragma once
#include <map>
#include "TorControlCommand.h"
@ -41,8 +40,6 @@ namespace Tor
class GetConfCommand : public TorControlCommand
{
// Q_PROPERTY(QVariantMap results READ results CONSTANT)
public:
enum Type {
GetConf,
@ -69,5 +66,3 @@ private:
};
}
#endif // GETCONFCOMMAND_H

View File

@ -33,7 +33,6 @@
#include "HiddenService.h"
#include "TorControl.h"
#include "CryptoKey.h"
#include "Useful.h"
#include "util/rsdir.h"
#include <fstream>
@ -102,7 +101,7 @@ void HiddenService::setServiceId(const ByteArray& sid)
void HiddenService::setPrivateKey(const CryptoKey &key)
{
if (m_privateKey.isLoaded()) {
BUG() << "Cannot change the private key on an existing HiddenService";
RsErr() << "Cannot change the private key on an existing HiddenService";
return;
}

View File

@ -86,7 +86,6 @@ public:
void addTarget(const Target &target);
void addTarget(uint16_t servicePort, std::string targetAddress, uint16_t targetPort);
//private slots:
void servicePublished();
private:

View File

@ -49,11 +49,6 @@
*/
class PendingOperation
{
// Q_PROPERTY(bool isFinished READ isFinished NOTIFY finished FINAL)
// Q_PROPERTY(bool isSuccess READ isSuccess NOTIFY success FINAL)
// Q_PROPERTY(bool isError READ isError NOTIFY error FINAL)
// Q_PROPERTY(std::string errorMessage READ errorMessage NOTIFY finished FINAL)
public:
PendingOperation();
@ -62,15 +57,6 @@ public:
bool isError() const;
std::string errorMessage() const;
// signals:
// // Always emitted once when finished, regardless of status
// void finished();
//
// // One of error() or success() is emitted once
// void error(const std::string &errorMessage);
// void success();
//protected slots:
void finishWithError(const std::string &errorMessage);
void finishWithSuccess();

View File

@ -52,8 +52,6 @@ public:
};
typedef uint8_t AuthMethod;
// RS_REGISTER_FLAGS_TYPE(AuthMethod); // not usable here because we're inside a class (and worse, inside a namespace)
ProtocolInfoCommand(TorControl *manager);
ByteArray build();

View File

@ -55,25 +55,6 @@ ByteArray SetConfCommand::build(const std::string &key, const std::string &value
return build(std::list<std::pair<std::string, std::string> > { std::make_pair(key, value) } );
}
// ByteArray SetConfCommand::build(const std::list<std::pair<ByteArray,ByteArray> > &data)
// {
// QList<QPair<QByteArray, QByteArray> > out;
//
// for (QVariantMap::ConstIterator it = data.begin(); it != data.end(); it++) {
// QByteArray key = it.key().toLatin1();
//
// if (static_cast<QMetaType::Type>(it.value().type()) == QMetaType::QVariantList) {
// QVariantList values = it.value().value<QVariantList>();
// foreach (const QVariant &value, values)
// out.append(qMakePair(key, value.toString().toLatin1()));
// } else {
// out.append(qMakePair(key, it.value().toString().toLatin1()));
// }
// }
//
// return build(out);
// }
ByteArray SetConfCommand::build(const std::list<std::pair<std::string, std::string> >& data)
{
ByteArray out(m_resetMode ? "RESETCONF" : "SETCONF");

View File

@ -40,9 +40,6 @@ namespace Tor
class SetConfCommand : public TorControlCommand
{
//Q_PROPERTY(QString errorMessage READ errorMessage CONSTANT)
//Q_PROPERTY(bool successful READ isSuccessful CONSTANT)
public:
SetConfCommand();
@ -54,7 +51,6 @@ public:
std::string errorMessage() const { return m_errorMessage; }
bool isSuccessful() const;
//signals:
void set_ConfSucceeded_callback(const std::function<void(void)>& f) { mConfSucceeded=f; }
void set_ConfFailed_callback (const std::function<void(int code)>& f){ mConfFailed=f; }

View File

@ -62,78 +62,13 @@ static std::ostream& torctrldebug()
#define torCtrlDebug torctrldebug
using namespace Tor;
namespace Tor {
// class TorControlPrivate : public QObject
// {
// Q_OBJECT
//
// public:
// TorControl *q;
//
// TorControlSocket *socket;
// std::string torAddress;
// std::string errorMessage;
// std::string torVersion;
// ByteArray authPassword;
// std::string socksAddress;
// QList<HiddenService*> services;
// uint16_t controlPort, socksPort;
// TorControl::Status status;
// TorControl::TorStatus torStatus;
// std::map<std::string,std::string> bootstrapStatus;
// bool hasOwnership;
//
// TorControlPrivate(TorControl *parent);
//
// void setStatus(TorControl::Status status);
// void setTorStatus(TorControl::TorStatus status);
//
// void getTorInfo();
// void publishServices();
//
// public slots:
// void socketConnected();
// void socketDisconnected();
// void socketError();
//
// void authenticateReply();
// void protocolInfoReply();
// void getTorInfoReply();
// void setError(const std::string &message);
//
// void statusEvent(int code, const ByteArray &data);
// void updateBootstrap(const std::list<ByteArray> &data);
// };
}
TorControl::TorControl()
{
mSocket = new TorControlSocket(this);
}
// TorControlPrivate::TorControlPrivate(TorControl *parent)
// : QObject(parent), q(parent), controlPort(0), socksPort(0),
// status(TorControl::NotConnected), torStatus(TorControl::TorUnknown),
// hasOwnership(false)
// {
// socket = new TorControlSocket();
//
// // QObject::connect(socket, SIGNAL(connected()), this, SLOT(socketConnected()));
// // QObject::connect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
// // QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError()));
// // QObject::connect(socket, SIGNAL(error(QString)), this, SLOT(setError(QString)));
// }
// QNetworkProxy TorControl::connectionProxy()
// {
// return QNetworkProxy(QNetworkProxy::Socks5Proxy, d->socksAddress.toString(), d->socksPort);
// }
static RsTorConnectivityStatus torConnectivityStatus(Tor::TorControl::Status t)
{
switch(t)
@ -179,11 +114,6 @@ void TorControl::setStatus(TorControl::Status n)
rsEvents->sendEvent(ev);
}
mStatusChanged_callback(mStatus, old);
// if (mStatus == TorControl::Connected && old < TorControl::Connected)
// socketConnected();//mConnected_callback();
// else if (mStatus < TorControl::Connected && old >= TorControl::Connected)
// socketDisconnected();//mDisconnected_callback();
}
void TorControl::setTorStatus(TorControl::TorStatus n)
@ -274,10 +204,8 @@ void TorControl::connect(const std::string &address, uint16_t port)
mControlPort = port;
setTorStatus(TorUnknown);
//bool b = d->socket->blockSignals(true);
if(mSocket->isRunning())
mSocket->fullstop();
//d->socket->blockSignals(b);
setStatus(Connecting);
@ -340,7 +268,7 @@ void TorControl::authenticate()
command->set_finished_callback( [this](TorControlCommand *sender) { protocolInfoReply(sender); });
command->set_replyLine_callback([this](int code, const ByteArray &data) { statusEvent(code,data); });
//connect(command, &TorControlCommand::finished, this, &protocolInfoReply);
mSocket->sendCommand(command, command->build());
}
@ -372,7 +300,7 @@ void TorControl::protocolInfoReply(TorControlCommand *sender)
if (mStatus == TorControl::Authenticating)
{
AuthenticateCommand *auth = new AuthenticateCommand;
//connect(auth, &TorControlCommand::finished, this, &TorControl::authenticateReply);
auth->set_finished_callback( [this](TorControlCommand *sender) { authenticateReply(sender); });
ByteArray data;
@ -456,28 +384,7 @@ void TorControl::getTorInfo()
std::list<std::string> keys{ "status/circuit-established","status/bootstrap-phase" };
#ifdef TODO
/* If these are set in the config, they override the automatic behavior. */
SettingsObject settings("tor");
QHostAddress forceAddress(settings.read("socksAddress").toString());
uint16_t port = (uint16_t)settings.read("socksPort").toInt();
if (!forceAddress.isNull() && port) {
torCtrlDebug() << "torctrl: Using manually specified SOCKS connection settings";
socksAddress = forceAddress;
socksPort = port;
if(rsEvents)
{
auto ev = std::make_shared<RsTorManagerEvent>();
ev->mTorManagerEventType = RsTorManagerEventCode::TOR_CONNECTIVITY_CHANGED;
rsEvents->sendEvent(ev);
}
}
else
#endif
keys .push_back("net/listeners/socks");
keys.push_back("net/listeners/socks");
mSocket->sendCommand(command, command->build(keys));
}
@ -485,7 +392,7 @@ void TorControl::getTorInfo()
void TorControl::getTorInfoReply(TorControlCommand *sender)
{
GetConfCommand *command = dynamic_cast<GetConfCommand*>(sender);
if (!command)// || !isConnected())
if (!command)
return;
std::list<ByteArray> listenAddresses = splitQuotedStrings(command->get("net/listeners/socks").front(), ' ');
@ -557,20 +464,6 @@ void TorControl::publishServices()
}
std::cerr << std::endl;
#ifdef TODO
SettingsObject settings("tor");
if (settings.read("neverPublishServices").toBool())
{
torCtrlDebug() << "torctrl: Skipping service publication because neverPublishService is enabled" << std::endl;
/* Call servicePublished under the assumption that they're published externally. */
for (QList<HiddenService*>::Iterator it = services.begin(); it != services.end(); ++it)
(*it)->servicePublished();
return;
}
#endif
if (torVersionAsNewAs("0.2.7")) {
for(HiddenService *service: mServices)
{
@ -697,8 +590,6 @@ void TorControl::updateBootstrap(const std::list<ByteArray> &data)
mBootstrapStatus[key.toLower().toString()] = value.toString();
}
//torCtrlDebug() << bootstrapStatus << std::endl;
if(rsEvents)
{
auto ev = std::make_shared<RsTorManagerEvent>();
@ -716,7 +607,6 @@ TorControlCommand *TorControl::getConfiguration(const std::string& options)
command->set_replyLine_callback([this](int code, const ByteArray &data) { statusEvent(code,data); });
mSocket->sendCommand(command, command->build(options));
//QQmlEngine::setObjectOwnership(command, QQmlEngine::CppOwnership);
return command;
}
@ -726,7 +616,6 @@ TorControlCommand *TorControl::setConfiguration(const std::list<std::pair<std::s
command->setResetMode(true);
mSocket->sendCommand(command, command->build(options));
//QQmlEngine::setObjectOwnership(command, QQmlEngine::CppOwnership);
return command;
}
@ -744,7 +633,6 @@ public:
{
assert(!command);
command = new GetConfCommand(GetConfCommand::GetInfo);
//QObject::connect(command, &TorControlCommand::finished, this, &SaveConfigOperation::configTextReply);
command->set_finished_callback([this](TorControlCommand *sender){ configTextReply(sender); });
socket->sendCommand(command, command->build(std::list<std::string> { "config-text" , "config-file" } ));
@ -832,11 +720,9 @@ PendingOperation *TorControl::saveConfiguration()
SaveConfigOperation *operation = new SaveConfigOperation();
//QObject::connect(operation, &PendingOperation::finished, operation, &QObject::deleteLater);
operation->set_finished_callback( [operation]() { delete operation; });
operation->start(mSocket);
//QQmlEngine::setObjectOwnership(operation, QQmlEngine::CppOwnership);
return operation;
}

View File

@ -48,19 +48,6 @@ class TorControlCommand;
class TorControl : public TorControlSocketClient
{
// Q_ENUMS(Status TorStatus)
//
// // Status of the control connection
// Q_PROPERTY(Status status READ status NOTIFY statusChanged)
// // Status of Tor (and whether it believes it can connect)
// Q_PROPERTY(TorStatus torStatus READ torStatus NOTIFY torStatusChanged)
// // Whether it's possible to make a SOCKS connection and connect
// Q_PROPERTY(bool hasConnectivity READ hasConnectivity NOTIFY connectivityChanged)
// Q_PROPERTY(QString torVersion READ torVersion NOTIFY connected)
// Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY statusChanged)
// Q_PROPERTY(QVariantMap bootstrapStatus READ bootstrapStatus NOTIFY bootstrapStatusChanged)
// Q_PROPERTY(bool hasOwnership READ hasOwnership NOTIFY hasOwnershipChanged)
public:
enum Status
{
@ -111,18 +98,9 @@ public:
void addHiddenService(HiddenService *service);
std::map<std::string, std::string> bootstrapStatus() const;
/*Q_INVOKABLE*/ TorControlCommand *getConfiguration(const std::string &options);
/*Q_INVOKABLE*/ TorControlCommand *setConfiguration(const std::list<std::pair<std::string, std::string> > &options);
/*Q_INVOKABLE*/ PendingOperation *saveConfiguration();
//signals:
// void statusChanged(int newStatus, int oldStatus);
// void torStatusChanged(int newStatus, int oldStatus);
// void connected();
// void disconnected();
// void connectivityChanged();
// void bootstrapStatusChanged();
// void hasOwnershipChanged();
TorControlCommand *getConfiguration(const std::string &options);
TorControlCommand *setConfiguration(const std::list<std::pair<std::string, std::string> > &options);
PendingOperation *saveConfiguration();
void set_statusChanged_callback(const std::function<void(int,int)>& f) { mStatusChanged_callback = f ;}
void set_connected_callback(const std::function<void(void)>& f) { mConnected_callback = f ;}
@ -130,7 +108,6 @@ public:
virtual void socketError(const std::string &s) override;
//public slots:
/* Instruct Tor to shutdown */
void shutdown();
/* Call shutdown(), and wait synchronously for the command to be written */

View File

@ -43,14 +43,12 @@ TorControlCommand::TorControlCommand()
void TorControlCommand::onReply(int statusCode, const ByteArray &data)
{
//emit replyLine(statusCode, data);
mReplyLine(statusCode, data);
}
void TorControlCommand::onFinished(int statusCode)
{
m_finalStatus = statusCode;
//emit finished();
mFinished(this);
}

View File

@ -50,7 +50,6 @@ public:
int statusCode() const { return m_finalStatus; }
//signals:
void set_replyLine_callback( const std::function<void(int statusCode, const ByteArray &data)>& f) { mReplyLine=f ; }
void set_finished_callback( const std::function<void(TorControlCommand *sender)>& f) { mFinished=f; };

View File

@ -40,8 +40,6 @@ using namespace Tor;
TorControlSocket::TorControlSocket(TorControlSocketClient *client)
: RsThreadedTcpSocket(),currentCommand(0), inDataReply(false),mClient(client)
{
//connect(this, SIGNAL(readyRead()), this, SLOT(process()));
//connect(this, SIGNAL(disconnected()), this, SLOT(clear()));
}
TorControlSocket::~TorControlSocket()
@ -84,8 +82,6 @@ void TorControlSocket::registerEvent(const ByteArray &event, TorControlCommand *
ByteArray data("SETEVENTS");
for(auto it:eventCommands)
{
//const ByteArray &key, eventCommands.keys()) {
//data += key;
data += ' ';
data += it.first;
}

View File

@ -67,12 +67,9 @@ public:
virtual int tick() override;
std::string peerAddress() const;
//signals:
// void error(const std::string& message);
const std::string& errorString() const { return m_errorMessage ;}
//private slots:
void process();
void clear();

View File

@ -101,7 +101,6 @@ TorManagerPrivate::TorManagerPrivate(TorManager *parent)
, configNeeded(false)
, hiddenService(NULL)
{
//connect(control, SIGNAL(statusChanged(int,int)), SLOT(controlStatusChanged(int)));
control->set_statusChanged_callback([this](int new_status,int /*old_status*/) { controlStatusChanged(new_status); });
}
@ -150,9 +149,6 @@ void TorManager::setHiddenServiceDirectory(const std::string &path)
static bool test_listening_port(const std::string& /*address*/,uint16_t port)
{
// sockaddr_storage addr;
// sockaddr_storage_fromString(address,addr);
//
int sockfd;
struct sockaddr_in serv_addr ;
@ -227,9 +223,6 @@ bool TorManager::setupHiddenService()
d->hiddenService = new Tor::HiddenService(this,legacyDir);
RsDbg() << "Creating new hidden service." << std::endl;
// connect(d->hiddenService, SIGNAL(privateKeyChanged()), this, SLOT(hiddenServicePrivateKeyChanged())) ;
// connect(d->hiddenService, SIGNAL(hostnameChanged()), this, SLOT(hiddenServiceHostnameChanged())) ;
}
assert(d->hiddenService);

View File

@ -49,16 +49,6 @@ class TorManagerPrivate;
class TorManager : public HiddenServiceClient, public RsThread, public RsTor
{
// Q_OBJECT
// Q_PROPERTY(bool configurationNeeded READ configurationNeeded NOTIFY configurationNeededChanged)
// Q_PROPERTY(QStringList logMessages READ logMessages CONSTANT)
// Q_PROPERTY(Tor::TorProcess* process READ process CONSTANT)
// Q_PROPERTY(Tor::TorControl* control READ control CONSTANT)
// Q_PROPERTY(bool hasError READ hasError NOTIFY errorChanged)
// Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorChanged)
// Q_PROPERTY(QString torDataDirectory READ torDataDirectory WRITE setTorDataDirectory)
public:
static TorManager *instance();
@ -85,10 +75,8 @@ public:
bool getHiddenServiceInfo(std::string& service_id,std::string& service_onion_address,uint16_t& service_port, std::string& service_target_address,uint16_t& target_port);
bool getProxyServerInfo(std::string &proxy_server_adress, uint16_t& proxy_server_port);
//public slots:
bool startTorManager();
//private slots:
virtual void hiddenServiceOnline() override {} // do nothing here.
virtual void hiddenServicePrivateKeyChanged() override;
virtual void hiddenServiceHostnameChanged() override;

View File

@ -271,7 +271,6 @@ void TorProcess::start()
return; // stop the control thread
}
int flags ;
unix_fcntl_nonblock(fd[STDOUT_FILENO]);
unix_fcntl_nonblock(fd[STDERR_FILENO]);
@ -309,8 +308,6 @@ void TorProcess::tick()
}
else if(mControlPortReadNbTries > 10)
{
//errorMessageChanged(errorMessage);
//stateChanged(state);
mState = Failed;
m_client->processStateChanged(mState);// stateChanged(mState);
}
@ -394,20 +391,18 @@ bool TorProcess::ensureFilesExist()
std::string TorProcess::torrcPath() const
{
//return QDir::toNativeSeparators(dataDir) + QDir::separator() + QStringLiteral("torrc");
return RsDirUtil::makePath(mDataDir,"torrc");
}
std::string TorProcess::controlPortFilePath() const
{
//return QDir::toNativeSeparators(dataDir) + QDir::separator() + QStringLiteral("control-port");
return RsDirUtil::makePath(mDataDir,"control-port");
}
bool TorProcess::tryReadControlPort()
{
FILE *file = RsDirUtil::rs_fopen(controlPortFilePath().c_str(),"r");
std::cerr << "Trying to read control port" << std::endl;
RsDbg() << "Trying to read control port" ;
if(file)
{
@ -425,72 +420,10 @@ bool TorProcess::tryReadControlPort()
if (!mControlHost.empty() && mControlPort > 0)
{
std::cerr << "Got control host/port = " << mControlHost << ":" << mControlPort << std::endl;
RsDbg() << "Got control host/port = " << mControlHost << ":" << mControlPort ;
return true;
}
}
}
return false;
}
#ifdef TO_REMOVE
void TorProcessPrivate::processStarted()
{
state = TorProcess::Connecting;
/*emit*/ q->stateChanged(state);
/*emit*/ q->stateChanged(state);
controlPortAttempts = 0;
controlPortTimer.start();
}
void TorProcessPrivate::processFinished()
{
if (state < TorProcess::Starting)
return;
controlPortTimer.stop();
errorMessage = process.errorString().toStdString();
if (errorMessage.empty())
errorMessage = "Process exited unexpectedly (code " + RsUtil::NumberToString(process.exitCode()) + ")";
state = TorProcess::Failed;
/*emit*/ q->errorMessageChanged(errorMessage);
/*emit*/ q->stateChanged(state);
}
void TorProcessPrivate::processError(QProcess::ProcessError error)
{
if (error == QProcess::FailedToStart || error == QProcess::Crashed)
processFinished();
}
void TorProcessPrivate::processReadable()
{
while (process.bytesAvailable() > 0)
{
ByteArray line = process.readLine(2048).trimmed();
if (!line.empty())
/*emit*/ q->logMessage(line.toString()));
}
}
TorProcessPrivate::TorProcessPrivate(TorProcess *q)
: q(q), state(TorProcess::NotStarted), controlPort(0), controlPortAttempts(0)
{
connect(&process, &QProcess::started, this, &TorProcessPrivate::processStarted);
connect(&process, (void (QProcess::*)(int, QProcess::ExitStatus))&QProcess::finished,
this, &TorProcessPrivate::processFinished);
connect(&process, (void (QProcess::*)(QProcess::ProcessError))&QProcess::error,
this, &TorProcessPrivate::processError);
connect(&process, &QProcess::readyRead, this, &TorProcessPrivate::processReadable);
controlPortTimer.setInterval(500);
connect(&controlPortTimer, &QTimer::timeout, this, &TorProcessPrivate::tryReadControlPort);
}
#endif

View File

@ -11,6 +11,8 @@
#include "util/rsprint.h"
#include "util/rsdebug.h"
// This class re-implements QByteArray from Qt library.
class ByteArray: public std::vector<unsigned char>
{
public: