-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_ws.hpp
421 lines (353 loc) · 16.1 KB
/
client_ws.hpp
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#ifndef CLIENT_WS_HPP
#define CLIENT_WS_HPP
#include "crypto.hpp"
#include <boost/asio.hpp>
#include <unordered_map>
#include <iostream>
#include <random>
namespace SimpleWeb {
template <class socket_type>
class SocketClient;
template <class socket_type>
class SocketClientBase {
public:
class Connection {
friend class SocketClientBase<socket_type>;
friend class SocketClient<socket_type>;
public:
std::unordered_map<std::string, std::string> header;
std::string remote_endpoint_address;
unsigned short remote_endpoint_port;
Connection(socket_type* socket): socket(socket), closed(false) {}
private:
std::unique_ptr<socket_type> socket;
std::atomic<bool> closed;
void read_remote_endpoint_data() {
try {
remote_endpoint_address=socket->lowest_layer().remote_endpoint().address().to_string();
remote_endpoint_port=socket->lowest_layer().remote_endpoint().port();
}
catch(const std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
};
std::unique_ptr<Connection> connection;
class Message {
friend class SocketClientBase<socket_type>;
public:
std::istream data;
size_t length;
unsigned char fin_rsv_opcode;
private:
Message(): data(&data_buffer) {}
boost::asio::streambuf data_buffer;
};
std::function<void(void)> onopen;
std::function<void(std::shared_ptr<Message>)> onmessage;
std::function<void(const boost::system::error_code&)> onerror;
std::function<void(int, const std::string&)> onclose;
void start() {
connect();
asio_io_service.run();
}
void stop() {
asio_io_service.stop();
}
void send(std::iostream& stream, const std::function<void(const boost::system::error_code&)>& callback=nullptr,
unsigned char fin_rsv_opcode=129) {
//Create mask
std::vector<unsigned char> mask;
mask.resize(4);
std::uniform_int_distribution<unsigned char> dist;
std::random_device rd;
for(int c=0;c<4;c++) {
mask[c]=dist(rd);
}
std::shared_ptr<boost::asio::streambuf> write_buffer(new boost::asio::streambuf);
std::ostream response(write_buffer.get());
stream.seekp(0, std::ios::end);
size_t length=stream.tellp();
stream.seekp(0, std::ios::beg);
response.put(fin_rsv_opcode);
//masked (first length byte>=128)
if(length>=126) {
int num_bytes;
if(length>0xffff) {
num_bytes=8;
response.put(127+128);
}
else {
num_bytes=2;
response.put(126+128);
}
for(int c=num_bytes-1;c>=0;c--) {
response.put((length>>(8*c))%256);
}
}
else
response.put(length+128);
for(int c=0;c<4;c++) {
response.put(mask[c]);
}
for(size_t c=0;c<length;c++) {
response.put(stream.get()^mask[c%4]);
}
//Need to copy the callback-function in case its destroyed
boost::asio::async_write(*connection->socket, *write_buffer,
[this, write_buffer, callback](const boost::system::error_code& ec, size_t bytes_transferred) {
if(callback) {
callback(ec);
}
});
}
void send_close(int status, const std::string& reason="") {
//Send close only once (in case close is initiated by client)
if(connection->closed.load()) {
return;
}
connection->closed.store(true);
std::stringstream response;
response.put(status>>8);
response.put(status%256);
response << reason;
//fin_rsv_opcode=136: message close
send(response, [](const boost::system::error_code& ec){}, 136);
}
protected:
const std::string ws_magic_string="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
boost::asio::io_service asio_io_service;
boost::asio::ip::tcp::endpoint asio_endpoint;
boost::asio::ip::tcp::resolver asio_resolver;
std::string host;
unsigned short port;
std::string path;
SocketClientBase(const std::string& host_port_path, unsigned short default_port) :
asio_resolver(asio_io_service) {
size_t host_end=host_port_path.find(':');
size_t host_port_end=host_port_path.find('/');
if(host_end==std::string::npos) {
host_end=host_port_end;
port=default_port;
}
else {
if(host_port_end==std::string::npos)
port=(unsigned short)stoul(host_port_path.substr(host_end+1));
else
port=(unsigned short)stoul(host_port_path.substr(host_end+1, host_port_end-(host_end+1)));
}
if(host_port_end==std::string::npos) {
path="/";
}
else {
path=host_port_path.substr(host_port_end);
}
if(host_end==std::string::npos)
host=host_port_path;
else
host=host_port_path.substr(0, host_end);
}
virtual void connect()=0;
void handshake() {
connection->read_remote_endpoint_data();
std::shared_ptr<boost::asio::streambuf> write_buffer(new boost::asio::streambuf);
std::ostream request(write_buffer.get());
request << "GET " << path << " HTTP/1.1" << "\r\n";
request << "Host: " << host << "\r\n";
request << "Upgrade: websocket\r\n";
request << "Connection: Upgrade\r\n";
//Make random 16-byte nonce
std::string nonce;
nonce.resize(16);
std::uniform_int_distribution<unsigned char> dist;
std::random_device rd;
for(int c=0;c<16;c++)
nonce[c]=dist(rd);
std::string nonce_base64=Crypto::Base64::encode(nonce);
request << "Sec-WebSocket-Key: " << nonce_base64 << "\r\n";
request << "Sec-WebSocket-Version: 13\r\n";
request << "\r\n";
//test this to base64::decode(Sec-WebSocket-Accept)
std::shared_ptr<std::string> accept_sha1(new std::string(Crypto::SHA1(nonce_base64+ws_magic_string)));
boost::asio::async_write(*connection->socket, *write_buffer,
[this, write_buffer, accept_sha1]
(const boost::system::error_code& ec, size_t bytes_transferred) {
if(!ec) {
std::shared_ptr<Message> message(new Message());
boost::asio::async_read_until(*connection->socket, message->data_buffer, "\r\n\r\n",
[this, message, accept_sha1]
(const boost::system::error_code& ec, size_t bytes_transferred) {
if(!ec) {
parse_handshake(message->data);
if(Crypto::Base64::decode(connection->header["Sec-WebSocket-Accept"])==*accept_sha1) {
if(onopen)
onopen();
read_message(message);
}
else
throw std::invalid_argument("WebSocket handshake failed");
}
});
}
else
throw std::invalid_argument("Failed sending handshake");
});
}
void parse_handshake(std::istream& stream) const {
std::string line;
getline(stream, line);
//Not parsing the first line
getline(stream, line);
size_t param_end=line.find(':');
while(param_end!=std::string::npos) {
size_t value_start=param_end+1;
if(line[value_start]==' ')
value_start++;
connection->header[line.substr(0, param_end)]=line.substr(value_start, line.size()-value_start-1);
getline(stream, line);
param_end=line.find(':');
}
}
void read_message(std::shared_ptr<Message> message) {
boost::asio::async_read(*connection->socket, message->data_buffer, boost::asio::transfer_exactly(2),
[this, message](const boost::system::error_code& ec, size_t bytes_transferred) {
if(!ec) {
std::vector<unsigned char> first_bytes;
first_bytes.resize(2);
message->data.read((char*)&first_bytes[0], 2);
message->fin_rsv_opcode=first_bytes[0];
//Close connection if masked message from server (protocol error)
if(first_bytes[1]>=128) {
const std::string reason="message from server masked";
send_close(1002, reason);
if(onclose)
onclose(1002, reason);
return;
}
size_t length=(first_bytes[1]&127);
if(length==126) {
//2 next bytes is the size of content
boost::asio::async_read(*connection->socket, message->data_buffer, boost::asio::transfer_exactly(2),
[this, message]
(const boost::system::error_code& ec, size_t bytes_transferred) {
if(!ec) {
std::vector<unsigned char> length_bytes;
length_bytes.resize(2);
message->data.read((char*)&length_bytes[0], 2);
size_t length=0;
int num_bytes=2;
for(int c=0;c<num_bytes;c++)
length+=length_bytes[c]<<(8*(num_bytes-1-c));
message->length=length;
read_message_content(message);
}
else {
if(onerror)
onerror(ec);
}
});
}
else if(length==127) {
//8 next bytes is the size of content
boost::asio::async_read(*connection->socket, message->data_buffer, boost::asio::transfer_exactly(8),
[this, message]
(const boost::system::error_code& ec, size_t bytes_transferred) {
if(!ec) {
std::vector<unsigned char> length_bytes;
length_bytes.resize(8);
message->data.read((char*)&length_bytes[0], 8);
size_t length=0;
int num_bytes=8;
for(int c=0;c<num_bytes;c++)
length+=length_bytes[c]<<(8*(num_bytes-1-c));
message->length=length;
read_message_content(message);
}
else {
if(onerror)
onerror(ec);
}
});
}
else {
message->length=length;
read_message_content(message);
}
}
else {
if(onerror)
onerror(ec);
}
});
}
void read_message_content(std::shared_ptr<Message> message) {
boost::asio::async_read(*connection->socket, message->data_buffer, boost::asio::transfer_exactly(message->length),
[this, message]
(const boost::system::error_code& ec, size_t bytes_transferred) {
if(!ec) {
//If connection close
if((message->fin_rsv_opcode&0x0f)==8) {
int status=0;
if(message->length>=2) {
unsigned char byte1=message->data.get();
unsigned char byte2=message->data.get();
status=(byte1<<8)+byte2;
}
std::stringstream reason_ss;
reason_ss << message->data.rdbuf();
std::string reason=reason_ss.str();
send_close(status, reason);
if(onclose)
onclose(status, reason);
return;
}
//If ping
else if((message->fin_rsv_opcode&0x0f)==9) {
//send pong
std::stringstream empty_ss;
send(empty_ss, nullptr, message->fin_rsv_opcode+1);
}
else if(onmessage) {
onmessage(message);
}
//Next message
std::shared_ptr<Message> next_message(new Message());
read_message(next_message);
}
else {
if(onerror)
onerror(ec);
}
});
}
};
template<class socket_type>
class SocketClient : public SocketClientBase<socket_type> {};
typedef boost::asio::ip::tcp::socket WS;
template<>
class SocketClient<WS> : public SocketClientBase<WS> {
public:
SocketClient(const std::string& server_port_path) : SocketClientBase<WS>::SocketClientBase(server_port_path, 80) {};
private:
void connect() {
boost::asio::ip::tcp::resolver::query query(host, std::to_string(port));
asio_resolver.async_resolve(query, [this]
(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it){
if(!ec) {
connection=std::unique_ptr<Connection>(new Connection(new WS(asio_io_service)));
boost::asio::async_connect(*connection->socket, it, [this]
(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it){
if(!ec) {
handshake();
}
else
throw std::invalid_argument(ec.message());
});
}
else
throw std::invalid_argument(ec.message());
});
}
};
}
#endif /* CLIENT_WS_HPP */