aboutsummaryrefslogtreecommitdiff
path: root/src/shared/net/connection.hh
blob: 79146af6251b647a2ff76aac0eebfd514762f367 (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
211
212
#ifndef SHARED_NET_CONNECTION_HH_
#define SHARED_NET_CONNECTION_HH_

#include <algorithm>
#include <optional>
#include <string>

#include "shared/net/net.hh"
#include "shared/net/proto.hh"

namespace shared {
namespace net {

class connection {
private:
    struct sockets {
        int rsock;
        int usock; // connected in constructor, no need to use sendto or revfrom
        std::string address;
        std::string port;

        sockets(const int r, const int u, const std::string& a,
                const std::string& p)
            : rsock(r), usock(u), address(a), port(p) {}
    };
    std::optional<sockets> socks;
    std::optional<std::string> bad_reason;

private:
    struct packet_header {
        std::uint32_t size;
    };

    // Data has a non-serialised header, and variable length serialised
    // protobuf content.
    static std::string packet_to_data(const proto::packet& packet) {

        std::string data;
        packet.SerializeToString(&data);
        shared::compress_string(data);

        packet_header header{.size = htonl(static_cast<std::uint32_t>(
                                 std::size(data) + sizeof(packet_header)))};

        return std::string{reinterpret_cast<char*>(&header),
                           reinterpret_cast<char*>(&header) + sizeof(header)} +
               std::move(data);
    }

    void send_sock_packet(const int sock, const proto::packet& packet) {
        if (!this->good()) {
            return;
        }

        const std::string data = packet_to_data(packet);

        if (send(sock, std::data(data), std::size(data), 0) == -1) {
            this->bad_reason = shared::net::get_errno_error();
        }
    }

public:
    connection(const int rsock) {
        using namespace shared::net;

        const std::string peer_address = get_socket_peer_address(rsock);
        const std::string peer_port = get_socket_peer_port(rsock);

        // Open up a connected usock based on the state of the connected rsock.
        const int usock = [&peer_address, &peer_port, &rsock]() -> int {
            constexpr addrinfo hints = {.ai_flags = AI_PASSIVE,
                                        .ai_family = AF_INET,
                                        .ai_socktype = SOCK_DGRAM};
            const std::string host_address = get_socket_host_address(rsock);
            const std::string host_port = get_socket_host_port(rsock);
            const auto host_info =
                get_addr_info(host_address, host_port, &hints);
            const int usock = make_socket(host_info.get());
            bind_socket(usock, host_info.get());

            const auto peer_info =
                get_addr_info(peer_address, peer_port, &hints);
            connect_socket(usock, peer_info.get());

            return usock;
        }();

        nonblock_socket(usock);
        nonblock_socket(rsock);

        this->socks.emplace(rsock, usock, peer_address, peer_port);
    }

    // We do not want to copy this object!
    // We use std::nullopt to determine if this object has been moved and if we
    // should close its sockets.
    connection(const connection&) = delete;
    connection(connection&& other) noexcept {
        std::swap(this->socks, other.socks);
        std::swap(this->bad_reason, other.bad_reason);
        other.socks.reset();
    }
    connection& operator=(connection&& other) noexcept {
        std::swap(this->socks, other.socks);
        std::swap(this->bad_reason, other.bad_reason);
        other.socks.reset();
        return *this;
    }
    ~connection() noexcept {
        if (this->socks.has_value()) {
            shared::net::close_socket(socks->rsock);
            shared::net::close_socket(socks->usock);
        }
    }

    // Getters.
    bool good() const noexcept { return !bad_reason.has_value(); }
    std::string get_bad_reason() const noexcept {
        return this->bad_reason.value();
    }
    std::string get_address() const noexcept { return this->socks->address; }

public:
    // Send does nothing if good() returns false!
    // Returns whether or not we were able to send our packet.
    void rsend_packet(const proto::packet& packet) noexcept {
        return send_sock_packet(this->socks->rsock, packet);
    }
    void usend_packet(const proto::packet& packet) noexcept {
        return send_sock_packet(this->socks->usock, packet);
    }
    std::optional<proto::packet> rrecv_packet() noexcept {
        const int sock = this->socks->rsock;

        // Get the size of the backlog, early out of there's nothing there yet.
        const auto backlog_size = shared::net::get_backlog_size(sock);
        if (backlog_size < sizeof(packet_header)) {
            return std::nullopt;
        }

        // Read for the packet headers and get the claimed size. Early out if
        // our stream isn't big enough for that yet.
        packet_header header = {};
        recv(sock, &header, sizeof(header), MSG_PEEK);
        const std::uint32_t read_packet_size = ntohl(header.size);
        if (backlog_size < read_packet_size) {
            return std::nullopt;
        }

        // Read the actual packet now, based on our claimed size.
        std::string data;
        data.reserve(read_packet_size);
        if (read(sock, std::data(data), read_packet_size) == -1) {
            this->bad_reason = shared::net::get_errno_error();
            return std::nullopt;
        }

        data = std::string{
            reinterpret_cast<char*>(std::data(data)) + sizeof(packet_header),
            reinterpret_cast<char*>(std::data(data)) + read_packet_size};
        shared::decompress_string(data);

        // Parse the packet, ignoring the header.
        proto::packet packet;
        if (!packet.ParseFromString(data)) {
            return std::nullopt;
        }

        return packet;
    }
    std::optional<proto::packet> urecv_packet() noexcept {
        const int sock = this->socks->usock;

    restart:
        const auto packet_size = shared::net::get_backlog_size(sock);

        if (packet_size == 0) {
            return std::nullopt;
        }

        std::string data;
        data.reserve(packet_size);
        if (recv(sock, std::data(data), packet_size, 0) == -1) {
            this->bad_reason = shared::net::get_errno_error();
            return std::nullopt;
        }

        data = std::string{
            reinterpret_cast<char*>(std::data(data)) + sizeof(packet_header),
            reinterpret_cast<char*>(std::data(data)) + packet_size};
        shared::decompress_string(data);

        proto::packet packet;
        if (!packet.ParseFromString(data)) {
            goto restart;
        }

        return packet;
    }
    // Gets packets from r/u streams, doesn't care which.
    std::optional<proto::packet> recv_packet() noexcept {
        if (const auto ret = urecv_packet(); ret.has_value()) {
            return ret;
        }
        return rrecv_packet();
    }
};

} // namespace net
} // namespace shared

#endif