aboutsummaryrefslogtreecommitdiff
path: root/src/BootstrapNode.cpp
blob: 5c62e6459c0f0d8be0b434ec8a159a35d255f14a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#include "../include/sibs/BootstrapNode.hpp"
#include "../include/Log.hpp"
#ifndef WIN32
   #include <arpa/inet.h>
   #include <netdb.h>
#else
   #include <winsock2.h>
   #include <ws2tcpip.h>
#endif
#include <udt/udt.h>
#include <sibs/SafeSerializer.hpp>
#include <sibs/SafeDeserializer.hpp>

namespace sibs
{
    BootstrapNode::BootstrapNode(const Ipv4 &address) : 
        connections(address.getPort()),
        socket(connections.createSocket(address, false, true))
    {
        if(connections.port != address.getPort())
        {
            throw SocketCreateException("BootstrapNode: Failed to bind port " + std::to_string(address.getPort()));
        }

        connections.onRemoveDisconnectedPeer([this](std::shared_ptr<DirectConnectionPeer> peer)
        {
            std::lock_guard<std::mutex> lock(subscribedPeersMutex);
            for(auto &topicUsers : subscribedPeers)
            {
                for(auto it = topicUsers.second.begin(); it != topicUsers.second.end(); )
                {
                    if(peer->address == (*it)->address)
                        it = topicUsers.second.erase(it);
                    else
                        ++it;
                }
            }
        });

        if(UDT::listen(socket->udtSocket, 10) == UDT::ERROR)
        {
            std::string errMsg = "UDT: Failed to listen, error: ";
            errMsg += UDT::getlasterror_desc();
            throw BootstrapException(errMsg);
        }
        acceptConnectionsThread = std::thread(&BootstrapNode::acceptConnections, this);
    }
    
    BootstrapNode::~BootstrapNode()
    {
        std::lock_guard<std::mutex> lock(connections.peersMutex);
        connections.alive = false;
        socket.reset();
        acceptConnectionsThread.join();
    }
    
    void BootstrapNode::acceptConnections()
    {
        sockaddr_storage clientAddr;
        int addrLen = sizeof(clientAddr);

        while(connections.alive)
        {
            UDTSOCKET clientUdtSocket = UDT::accept(socket->udtSocket, (sockaddr*)&clientAddr, &addrLen);
            if(clientUdtSocket == UDT::INVALID_SOCK)
            {
                // Connection was killed because bootstrap node was taken down
                if(!connections.alive)
                    return;
                Log::error("UDT: Failed to accept connection, error: %s", UDT::getlasterror_desc());
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
                continue;
            }
            auto clientSocket = std::make_unique<Socket>(clientUdtSocket);

            char clientHost[NI_MAXHOST];
            char clientService[NI_MAXSERV];
            getnameinfo((sockaddr *)&clientAddr, addrLen, clientHost, sizeof(clientHost), clientService, sizeof(clientService), NI_NUMERICHOST | NI_NUMERICSERV);
            Log::debug("UDT: New connection: %s:%s (socket: %d)", clientHost, clientService, clientUdtSocket);
            
            std::lock_guard<std::mutex> lock(connections.peersMutex);
            UDT::epoll_add_usock(connections.eid, clientUdtSocket);
            clientSocket->eid = connections.eid;
            std::shared_ptr<DirectConnectionPeer> peer = std::make_shared<DirectConnectionPeer>();
            peer->socket = std::move(clientSocket);
            sockaddr_in *clientAddrSock = (sockaddr_in*)&clientAddr;
            memcpy(&peer->address.address, clientAddrSock, sizeof(peer->address.address));
            peer->receiveDataCallbackFunc = std::bind(&BootstrapNode::messageFromClient, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
            connections.peers[clientUdtSocket] = peer;
        }
    }

    void BootstrapNode::messageFromClient(std::shared_ptr<DirectConnectionPeer> peer, MessageType messageType, const void *data, const usize size)
    {
        sibs::SafeDeserializer deserializer((const u8*)data, size);
        PubsubKey pubsubKey;
        deserializer.extract(pubsubKey.data.data(), PUBSUB_KEY_LENGTH);

        if(messageType == MessageType::SUBSCRIBE)
        {
            Log::debug("BootstrapNode: Received peer subscribe from (ip: %s, port: %d)", peer->address.getAddress().c_str(), peer->address.getPort());
            std::lock_guard<std::mutex> lock(subscribedPeersMutex);
            auto &peers = subscribedPeers[pubsubKey];
            for(auto &existingPeer : peers)
            {
                if(existingPeer->address == peer->address)
                    return;
            }
            
            sibs::SafeSerializer serializer;
            serializer.add((u32)peer->address.address.sin_family);
            serializer.add((u32)peer->address.address.sin_addr.s_addr);
            serializer.add((u16)peer->address.address.sin_port);
            auto newPeerMessage = std::make_shared<Message>(MessageType::SUBSCRIBE);
            newPeerMessage->append(pubsubKey.data.data(), pubsubKey.data.size());
            newPeerMessage->append(serializer.getBuffer().data(), serializer.getBuffer().size());
            auto sendCallbackFunc = [](PubSubResult result, const std::string &resultStr)
            {
                Log::debug("BootstrapNode::peerSubscribe send result: %d, result string: %s", result, resultStr.c_str());
            };
            for(auto &existingPeer : peers)
            {
                connections.send(existingPeer, newPeerMessage, sendCallbackFunc);
            }
            
            sibs::SafeSerializer newPeerSerializer;
            for(auto &existingPeer : peers)
            {
                newPeerSerializer.add((u32)existingPeer->address.address.sin_family);
                newPeerSerializer.add((u32)existingPeer->address.address.sin_addr.s_addr);
                newPeerSerializer.add((u16)existingPeer->address.address.sin_port);
            }
            peers.push_back(peer);

            auto existingPeerMessage = std::make_shared<Message>(MessageType::SUBSCRIBE);
            existingPeerMessage->append(pubsubKey.data.data(), pubsubKey.data.size());
            existingPeerMessage->append(newPeerSerializer.getBuffer().data(), newPeerSerializer.getBuffer().size());
            connections.send(peer, existingPeerMessage, sendCallbackFunc);
        }
        else if(messageType == MessageType::UNSUBSCRIBE)
        {
            Log::debug("BootstrapNode: Received peer unsubscribe from (ip: %s, port: %d)", peer->address.getAddress().c_str(), peer->address.getPort());
            std::lock_guard<std::mutex> lock(subscribedPeersMutex);
            auto &peers = subscribedPeers[pubsubKey];
            for(auto it = peers.begin(); it != peers.end(); ++it)
            {
                auto existingPeer = *it;
                if(existingPeer->address == peer->address)
                {
                    peers.erase(it);
                    break;
                }
            }
        }
        else
        {
            Log::warn("BootstrapNode: received message from client that was not subscribe or unsubscribe");
        }
    }
}