-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.cpp
More file actions
235 lines (200 loc) · 5.57 KB
/
Socket.cpp
File metadata and controls
235 lines (200 loc) · 5.57 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#include "Socket.h"
#include "warning.h"
#include <stdexcept>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
// Hints struct used in Socket::bind()
// and Socket::connect()
static const addrinfo hints = {
.ai_flags = 0,
.ai_family=AF_UNSPEC,
.ai_socktype=SOCK_STREAM,
.ai_protocol = 0,
.ai_addrlen = 0,
.ai_addr = nullptr,
.ai_canonname = nullptr,
.ai_next = nullptr
};
bool Socket::isValid() const noexcept
{
return (this->socket_fd > 0);
}
void Socket::assertValidity() const
{
if(!isValid())
throw std::runtime_error("Socket is uninitialized");
}
void Socket::assertInvalidity() const
{
if(isValid())
{
throw std::runtime_error("Socket is already initialized");
}
}
std::string Socket::receive() const
{
assertValidity();
constexpr ssize_t MAX_RECEIVE_SIZE = 0x7FFF'FFFF;
uint8_t buffer[256];
// Total message size
ssize_t message_size;
const auto recv_status = recv(this->socket_fd, &message_size, sizeof(message_size), 0);
if(recv_status == 0)
throw Socket::PeerDisconnect("Peer disconnected");
if(recv_status != sizeof(message_size))
throw std::runtime_error("Failed to receive size");
if(message_size > MAX_RECEIVE_SIZE)
throw std::runtime_error("Way too big");
if(message_size < 0)
throw std::runtime_error("Can't send negative number of bytes");
std::string message;
// Where we're currently receiving in buffer
// (we receive in small segments)
ssize_t bytes_received=0;
while(bytes_received<message_size)
{
// Receive some amount of bytes into buffer
const auto length =
recv(socket_fd, buffer, std::min(message_size-bytes_received,
static_cast<ssize_t>(0x100)), 0);
if(length == 0)
throw Socket::PeerDisconnect("Peer disconnected");
if(length < 0)
throw std::runtime_error("Recv returned "+std::to_string(length));
// Add
message += std::string(reinterpret_cast<char*>(buffer), length);
bytes_received += length;
}
if(bytes_received>message_size)
{
throw std::runtime_error("Too many bytes!: "
+std::to_string(bytes_received)+"(actual) vs "
+std::to_string(message_size)+"(expected)"
);
}
return message;
}
void Socket::send(const std::string& message) const
{
assertValidity();
ssize_t bytes_sent;
// Send size as first few bytes
ssize_t size = message.size();
bytes_sent = ::send(this->socket_fd, &size, sizeof(size), 0);
if(bytes_sent != static_cast<ssize_t>(sizeof(size)))
throw std::runtime_error("Size send failed");
// Then send actual message
bytes_sent = ::send(this->socket_fd, message.c_str(), message.size(), 0);
if(bytes_sent != static_cast<ssize_t>(size))
throw std::runtime_error("Send failed");
}
int Socket::accept()
{
assertValidity();
sockaddr_storage client_address;
socklen_t address_size = sizeof(client_address);
const auto new_socket_fd =
::accept(this->socket_fd, (sockaddr*)&client_address, &address_size);
return new_socket_fd;
}
void Socket::listen(int backlog) const
{
assertValidity();
if(::listen(this->socket_fd, backlog) < 0)
{
throw std::runtime_error("Socket failed to listen on TCP port");
}
}
void Socket::bind(int port)
{
assertInvalidity();
int cstatus;// return val of C API functions
addrinfo* server_info_list = nullptr;
if((cstatus = getaddrinfo("0.0.0.0", std::to_string(port).c_str(), &hints, &server_info_list)))
{
throw std::runtime_error(std::string("getaddrinfo failed: ")+std::to_string(cstatus));
}
// bind to whoever will let us
auto server_info = server_info_list;
for ( ; server_info != nullptr; server_info = server_info->ai_next)
{
this->socket_fd =
socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol);
if(! this->isValid())
{
warning(std::string("Failed to create socket: ")+std::to_string(this->socket_fd));
continue;
}
// Prevent annoying "address in use" error
// for setting SO_REUSEADDR to true
int optval = 1;
if((cstatus = setsockopt(this->socket_fd,
SOL_SOCKET,
SO_REUSEADDR,
&optval,
sizeof(optval))))
{
freeaddrinfo(server_info_list);
throw std::runtime_error(std::string("setsockopt failed: ")+std::to_string(cstatus));
}
if(::bind(this->socket_fd, server_info->ai_addr, server_info->ai_addrlen))
{
this->close();
warning(std::string("bind() failed. errno=")+std::to_string(errno));
continue;
}
break;
}
freeaddrinfo(server_info_list);
if(server_info == nullptr)
throw std::runtime_error("Failed to bind() socket");
}
void Socket::connect(const std::string& host, int port)
{
assertInvalidity();
int cstatus;
addrinfo* server_info_list = nullptr;
if((cstatus = getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &server_info_list)))
{
throw std::runtime_error(std::string("getaddrinfo() failed: ")+std::to_string(cstatus));
}
auto server_info = server_info_list;
for ( ; server_info != nullptr; server_info = server_info->ai_next)
{
this->socket_fd =
socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol);
if(!this->isValid())
{
warning(std::string("Failed to create socket: ")+std::to_string(this->socket_fd));
continue;
}
if(::connect(this->socket_fd, server_info->ai_addr, server_info->ai_addrlen))
{
this->close();
continue;
}
break;
}
freeaddrinfo(server_info_list);
if(server_info == nullptr)
throw std::runtime_error("Failed to connect() socket");
}
void Socket::close()
{
assertValidity();
::close(this->socket_fd);
this->socket_fd = 0;
}
Socket::Socket(Socket&& rhs)
{
this->socket_fd = rhs.socket_fd;
rhs.socket_fd = 0;
}
Socket::~Socket()
{
if(this->isValid())
::close(this->socket_fd);
}