File indexing completed on 2025-01-05 04:37:24

0001 /*
0002     SPDX-FileCopyrightText: 2005 Joris Guisson <joris.guisson@gmail.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 #include "server.h"
0007 #include <QHostAddress>
0008 #include <QStringList>
0009 #include <mse/encryptedpacketsocket.h>
0010 #include <mse/encryptedserverauthenticate.h>
0011 #include <net/portlist.h>
0012 #include <net/socket.h>
0013 #include <peer/accessmanager.h>
0014 #include <peer/authenticationmonitor.h>
0015 #include <peer/peermanager.h>
0016 #include <peer/serverauthenticate.h>
0017 #include <qsocketnotifier.h>
0018 #include <util/functions.h>
0019 #include <util/log.h>
0020 #include <util/sha1hash.h>
0021 
0022 #include "globals.h"
0023 #include "torrent.h"
0024 #include <net/serversocket.h>
0025 
0026 namespace bt
0027 {
0028 typedef QSharedPointer<net::ServerSocket> ServerSocketPtr;
0029 
0030 class Server::Private : public net::ServerSocket::ConnectionHandler
0031 {
0032 public:
0033     Private(Server *p)
0034         : p(p)
0035     {
0036     }
0037 
0038     ~Private() override
0039     {
0040     }
0041 
0042     void reset()
0043     {
0044         sockets.clear();
0045     }
0046 
0047     void newConnection(int fd, const net::Address &addr) override
0048     {
0049         mse::EncryptedPacketSocket::Ptr s(new mse::EncryptedPacketSocket(fd, addr.ipVersion()));
0050         p->newConnection(s);
0051     }
0052 
0053     void add(const QString &ip, bt::Uint16 port)
0054     {
0055         ServerSocketPtr sock(new net::ServerSocket(this));
0056         if (sock->bind(ip, port)) {
0057             sockets.append(sock);
0058         }
0059     }
0060 
0061     Server *p;
0062     QList<ServerSocketPtr> sockets;
0063 };
0064 
0065 Server::Server()
0066     : d(new Private(this))
0067 {
0068 }
0069 
0070 Server::~Server()
0071 {
0072     Globals::instance().getPortList().removePort(port, net::TCP);
0073     delete d;
0074 }
0075 
0076 bool Server::changePort(Uint16 p)
0077 {
0078     if (d->sockets.count() > 0 && p == port)
0079         return true;
0080 
0081     Globals::instance().getPortList().removePort(port, net::TCP);
0082     d->reset();
0083 
0084     const QStringList possible = bindAddresses();
0085     for (const QString &addr : possible) {
0086         d->add(addr, p);
0087     }
0088 
0089     if (d->sockets.count() == 0) {
0090         // Try any addresses if previous binds failed
0091         d->add(QHostAddress(QHostAddress::AnyIPv6).toString(), p);
0092         d->add(QHostAddress(QHostAddress::Any).toString(), p);
0093     }
0094 
0095     if (d->sockets.count()) {
0096         Globals::instance().getPortList().addNewPort(p, net::TCP, true);
0097         return true;
0098     } else
0099         return false;
0100 }
0101 
0102 }
0103 
0104 #include "moc_server.cpp"