aboutsummaryrefslogtreecommitdiff
path: root/src/DirectConnection.cpp
blob: 6e3ddccd6c8dd663f40a9d97197ddaae075fb07a (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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#include "../include/sibs/DirectConnection.hpp"
#include "../include/Log.hpp"
#include <cstdio>
#include <cstring>

#ifndef WIN32
   #include <arpa/inet.h>
   #include <netdb.h>
#else
   #include <winsock2.h>
   #include <ws2tcpip.h>
#endif
#include <udt/udt.h>

namespace sibs
{
    // Max received data size allowed when receiving regular data, receive data as file to receive more data
    const int MAX_RECEIVED_DATA_SIZE = 1024 * 1024 * 1; // 1Mb
    
    Ipv4::Ipv4(const char *ip, u16 port)
    {        
        struct addrinfo hints = {};
        hints.ai_flags = AI_PASSIVE;
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        
        char portStr[6];
        sprintf(portStr, "%d", port);
        int addrInfoResult = getaddrinfo(ip, portStr, &hints, &address);
        if(addrInfoResult != 0)
        {
            std::string errMsg = "Ip ";
            errMsg += ip;
            errMsg += " is not a valid ip";
            throw InvalidAddressException(errMsg);
        }
    }
    
    Ipv4::~Ipv4()
    {
        freeaddrinfo(address);
    }
    
    DirectConnections::DirectConnections(u16 _port) : 
        port(_port),
        alive(true)
    {
        UDT::startup();
        eid = UDT::epoll_create();
        receiveDataThread = std::thread(&DirectConnections::receiveData, this);
    }
    
    DirectConnections::~DirectConnections()
    {
        alive = false;
        receiveDataThread.join();
        
        for(auto &peer : peers)
        {
            UDT::close(peer.first);
        }
        UDT::epoll_release(eid);
        UDT::cleanup();
    }
    
    std::shared_ptr<DirectConnectionPeer> DirectConnections::connect(const Ipv4 &address, PubSubReceiveDataCallback receiveDataCallbackFunc)
    {
        UDTSOCKET socket = UDT::socket(AI_PASSIVE, AF_INET, SOCK_STREAM);
        if(socket == UDT::INVALID_SOCK)
        {
            std::string errMsg = "UDT: Failed to create socket, error: ";
            errMsg += UDT::getlasterror_desc();
            throw ConnectionException(errMsg);
        }
        
        bool rendezvous = true;
        UDT::setsockopt(socket, 0, UDT_RENDEZVOUS, &rendezvous, sizeof(bool));
        bool reuseAddr = true;
        UDT::setsockopt(socket, 0, UDT_REUSEADDR, &reuseAddr, sizeof(bool));
        
        // Windows UDP issue
        // For better performance, modify HKLM\System\CurrentControlSet\Services\Afd\Parameters\FastSendDatagramThreshold
        #ifdef WIN32
        int mss = 1052;
        UDT::setsockopt(socket, 0, UDT_MSS, &mss, sizeof(mss));
        #endif
        
        sockaddr_in myAddr = {};
        myAddr.sin_family = AF_INET;
        myAddr.sin_port = htons(port);
        myAddr.sin_addr.s_addr = INADDR_ANY;
        memset(&myAddr.sin_zero, '\0', 8);

        if(UDT::bind(socket, (sockaddr*)&myAddr, sizeof(myAddr)) == UDT::ERROR)
        {
            std::string errMsg = "UDT: Failed to bind, error: ";
            errMsg += UDT::getlasterror_desc();
            throw ConnectionException(errMsg);
        }
        
        if(UDT::connect(socket, address.address->ai_addr, address.address->ai_addrlen) == UDT::ERROR)
        {
            std::string errMsg = "UDT: Failed to connect, error: ";
            errMsg += UDT::getlasterror_desc();
            throw ConnectionException(errMsg);
        }
        
        UDT::epoll_add_usock(eid, socket);
        std::shared_ptr<DirectConnectionPeer> peer = std::make_shared<DirectConnectionPeer>();
        peer->socket = socket;
        peer->receiveDataCallbackFunc = receiveDataCallbackFunc;
        peersMutex.lock();
        peers[socket] = peer;
        peersMutex.unlock();
        return peer;
    }
    
    void DirectConnections::send(const std::shared_ptr<DirectConnectionPeer> &peer, const void *data, const usize size)
    {
        usize sentSizeTotal = 0;
        while(sentSizeTotal < size)
        {
            int sentSize = UDT::send(peer->socket, (char*)data + sentSizeTotal, size - sentSizeTotal, 0);
            if(sentSize == UDT::ERROR)
            {
                std::string errMsg = "UDT: Failed to send data, error: ";
                errMsg += UDT::getlasterror_desc();
                throw SendException(errMsg);
            }
            sentSizeTotal += sentSize;
        }
    }
    
    void DirectConnections::receiveData()
    {
        std::vector<char> data;
        data.reserve(MAX_RECEIVED_DATA_SIZE);
        
        std::set<UDTSOCKET> readfds;
        while(alive)
        {
            int numfsReady = UDT::epoll_wait(eid, &readfds, nullptr, 250);
            if(numfsReady == 0)
                continue;
            else if(numfsReady == -1)
            {
                if(UDT::getlasterror_code() == UDT::ERRORINFO::ETIMEOUT)
                    continue;
                else
                {
                    Log::error("UDT: Stop receiving data, got error: %s", UDT::getlasterror_desc());
                    return;
                }
            }
            
            for(UDTSOCKET receivedDataFromPeer : readfds)
            {
                bool receivedData = receiveDataFromPeer(receivedDataFromPeer, data.data());
                if(receivedData)
                {
                    peersMutex.lock();
                    auto peer = peers[receivedDataFromPeer];
                    peersMutex.unlock();
                    try
                    {
                        if(peer->receiveDataCallbackFunc)
                            peer->receiveDataCallbackFunc(data.data(), data.size());
                    }
                    catch(std::exception &e)
                    {
                        Log::error("UDT: Receive callback function threw exception: %s, ignoring...", e.what());
                    }
                }
            }
            readfds.clear();
        }
    }
    
    bool DirectConnections::receiveDataFromPeer(const int socket, char *output)
    {
        usize receivedTotalSize = 0;
        while(receivedTotalSize < MAX_RECEIVED_DATA_SIZE)
        {
            usize dataAvailableSize;
            int receiveSizeDataTypeSize = sizeof(dataAvailableSize);
            if(UDT::getsockopt(socket, 0, UDT_RCVDATA, &dataAvailableSize, &receiveSizeDataTypeSize) == UDT::ERROR)
            {
                Log::error("UDT: Failed to receive data available size, error: %s", UDT::getlasterror_desc());
                return false;
            }
            
            int receivedSize = UDT::recv(socket, &output[receivedTotalSize], MAX_RECEIVED_DATA_SIZE - receivedTotalSize, 0);
            if(receivedSize == UDT::ERROR)
            {
                Log::error("UDT: Failed to receive data, error: %s", UDT::getlasterror_desc());
                return false;
            }
            
            if(receivedSize == 0)
            {
                return true;
            }
            
            receivedTotalSize += dataAvailableSize;
        }
        
        Log::error("UDT: Received too much data, ignoring...");
        return false;
    }
}