| 1 |
/* |
| 2 |
* ws.cpp |
| 3 |
* Author: Benjamin Sergeant |
| 4 |
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved. |
| 5 |
*/ |
| 6 |
|
| 7 |
// |
| 8 |
// Main driver for websocket utilities |
| 9 |
// |
| 10 |
|
| 11 |
#include "linenoise.hpp" |
| 12 |
#include <CLI11.hpp> |
| 13 |
#include <atomic> |
| 14 |
#include <chrono> |
| 15 |
#include <condition_variable> |
| 16 |
#include <fstream> |
| 17 |
#include <iostream> |
| 18 |
#include <ixwebsocket/IXBench.h> |
| 19 |
#include <ixwebsocket/IXDNSLookup.h> |
| 20 |
#include <ixwebsocket/IXGzipCodec.h> |
| 21 |
#include <ixwebsocket/IXHttpClient.h> |
| 22 |
#include <ixwebsocket/IXHttpServer.h> |
| 23 |
#include <ixwebsocket/IXNetSystem.h> |
| 24 |
#include <ixwebsocket/IXSetThreadName.h> |
| 25 |
#include <ixwebsocket/IXSocket.h> |
| 26 |
#include <ixwebsocket/IXSocketTLSOptions.h> |
| 27 |
#include <ixwebsocket/IXUserAgent.h> |
| 28 |
#include <ixwebsocket/IXUuid.h> |
| 29 |
#include <ixwebsocket/IXWebSocket.h> |
| 30 |
#include <ixwebsocket/IXWebSocketHttpHeaders.h> |
| 31 |
#include <ixwebsocket/IXWebSocketProxyServer.h> |
| 32 |
#include <ixwebsocket/IXWebSocketServer.h> |
| 33 |
#include <msgpack11.hpp> |
| 34 |
#include <mutex> |
| 35 |
#include <queue> |
| 36 |
#include <spdlog/sinks/basic_file_sink.h> |
| 37 |
#include <spdlog/spdlog.h> |
| 38 |
#include <sstream> |
| 39 |
#include <string> |
| 40 |
#include <thread> |
| 41 |
#include <vector> |
| 42 |
|
| 43 |
#ifndef _WIN32 |
| 44 |
#include <signal.h> |
| 45 |
#else |
| 46 |
#include <process.h> |
| 47 |
#define getpid _getpid |
| 48 |
#endif |
| 49 |
|
| 50 |
// for convenience |
| 51 |
using msgpack11::MsgPack; |
| 52 |
|
| 53 |
namespace |
| 54 |
{ |
| 55 |
std::pair<bool, std::vector<uint8_t>> load(const std::string& path) |
| 56 |
{ |
| 57 |
std::vector<uint8_t> memblock; |
| 58 |
std::ifstream file(path); |
| 59 |
|
| 60 |
if (!file.is_open()) return std::make_pair(false, memblock); |
| 61 |
|
| 62 |
file.seekg(0, file.end); |
| 63 |
std::streamoff size = file.tellg(); |
| 64 |
file.seekg(0, file.beg); |
| 65 |
|
| 66 |
memblock.reserve((size_t) size); |
| 67 |
memblock.insert( |
| 68 |
memblock.begin(), std::istream_iterator<char>(file), std::istream_iterator<char>()); |
| 69 |
|
| 70 |
return std::make_pair(true, memblock); |
| 71 |
} |
| 72 |
|
| 73 |
std::pair<bool, std::string> readAsString(const std::string& path) |
| 74 |
{ |
| 75 |
auto res = load(path); |
| 76 |
auto vec = res.second; |
| 77 |
return std::make_pair(res.first, std::string(vec.begin(), vec.end())); |
| 78 |
} |
| 79 |
|
| 80 |
std::string truncate(const std::string& str, size_t n) |
| 81 |
{ |
| 82 |
if (str.size() < n) |
| 83 |
{ |
| 84 |
return str; |
| 85 |
} |
| 86 |
else |
| 87 |
{ |
| 88 |
return str.substr(0, n) + "..."; |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
std::string extractFilename(const std::string& path) |
| 93 |
{ |
| 94 |
std::string::size_type idx; |
| 95 |
|
| 96 |
idx = path.rfind('/'); |
| 97 |
if (idx != std::string::npos) |
| 98 |
{ |
| 99 |
std::string filename = path.substr(idx + 1); |
| 100 |
return filename; |
| 101 |
} |
| 102 |
else |
| 103 |
{ |
| 104 |
return path; |
| 105 |
} |
| 106 |
} |
| 107 |
|
| 108 |
std::string removeExtension(const std::string& path) |
| 109 |
{ |
| 110 |
std::string::size_type idx; |
| 111 |
|
| 112 |
idx = path.rfind('.'); |
| 113 |
if (idx != std::string::npos) |
| 114 |
{ |
| 115 |
std::string filename = path.substr(0, idx); |
| 116 |
return filename; |
| 117 |
} |
| 118 |
else |
| 119 |
{ |
| 120 |
return path; |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
uint64_t djb2Hash(const std::vector<uint8_t>& data) |
| 125 |
{ |
| 126 |
uint64_t hashAddress = 5381; |
| 127 |
|
| 128 |
for (auto&& c : data) |
| 129 |
{ |
| 130 |
hashAddress = ((hashAddress << 5) + hashAddress) + c; |
| 131 |
} |
| 132 |
|
| 133 |
return hashAddress; |
| 134 |
} |
| 135 |
|
| 136 |
uint64_t djb2HashStr(const std::string& data) |
| 137 |
{ |
| 138 |
uint64_t hashAddress = 5381; |
| 139 |
|
| 140 |
for (size_t i = 0; i < data.size(); ++i) |
| 141 |
{ |
| 142 |
hashAddress = ((hashAddress << 5) + hashAddress) + data[i]; |
| 143 |
} |
| 144 |
|
| 145 |
return hashAddress; |
| 146 |
} |
| 147 |
} // namespace |
| 148 |
|
| 149 |
namespace ix |
| 150 |
{ |
| 151 |
// |
| 152 |
// Autobahn test suite |
| 153 |
// |
| 154 |
// 1. First you need to generate a config file in a config folder, |
| 155 |
// which can use a white list of test to execute (with globbing), |
| 156 |
// or a black list of tests to ignore |
| 157 |
// |
| 158 |
// config/fuzzingserver.json |
| 159 |
// { |
| 160 |
// "url": "ws://127.0.0.1:9001", |
| 161 |
// "outdir": "./reports/clients", |
| 162 |
// "cases": ["2.*"], |
| 163 |
// "exclude-cases": [ |
| 164 |
// ], |
| 165 |
// "exclude-agent-cases": {} |
| 166 |
// } |
| 167 |
// |
| 168 |
// |
| 169 |
// 2 Run the test server (using docker) |
| 170 |
// docker run -it --rm -v "${PWD}/config:/config" -v "${PWD}/reports:/reports" -p 9001:9001 |
| 171 |
// --name fuzzingserver crossbario/autobahn-testsuite |
| 172 |
// |
| 173 |
// 3. Run this command |
| 174 |
// ws autobahn -q --url ws://localhost:9001 |
| 175 |
// |
| 176 |
// 4. A HTML report will be generated, you can inspect it to see if you are compliant or not |
| 177 |
// |
| 178 |
|
| 179 |
class AutobahnTestCase |
| 180 |
{ |
| 181 |
public: |
| 182 |
AutobahnTestCase(const std::string& _url, bool quiet); |
| 183 |
void run(); |
| 184 |
|
| 185 |
private: |
| 186 |
void log(const std::string& msg); |
| 187 |
|
| 188 |
std::string _url; |
| 189 |
ix::WebSocket _webSocket; |
| 190 |
|
| 191 |
bool _quiet; |
| 192 |
|
| 193 |
std::mutex _mutex; |
| 194 |
std::condition_variable _condition; |
| 195 |
}; |
| 196 |
|
| 197 |
AutobahnTestCase::AutobahnTestCase(const std::string& url, bool quiet) |
| 198 |
: _url(url) |
| 199 |
, _quiet(quiet) |
| 200 |
{ |
| 201 |
_webSocket.disableAutomaticReconnection(); |
| 202 |
|
| 203 |
// FIXME: this should be on by default |
| 204 |
ix::WebSocketPerMessageDeflateOptions webSocketPerMessageDeflateOptions( |
| 205 |
true, false, false, 15, 15); |
| 206 |
_webSocket.setPerMessageDeflateOptions(webSocketPerMessageDeflateOptions); |
| 207 |
} |
| 208 |
|
| 209 |
void AutobahnTestCase::log(const std::string& msg) |
| 210 |
{ |
| 211 |
if (!_quiet) |
| 212 |
{ |
| 213 |
spdlog::info(msg); |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
void AutobahnTestCase::run() |
| 218 |
{ |
| 219 |
_webSocket.setUrl(_url); |
| 220 |
|
| 221 |
std::stringstream ss; |
| 222 |
log(std::string("Connecting to url: ") + _url); |
| 223 |
|
| 224 |
_webSocket.setOnMessageCallback([this](const ix::WebSocketMessagePtr& msg) { |
| 225 |
std::stringstream ss; |
| 226 |
if (msg->type == ix::WebSocketMessageType::Open) |
| 227 |
{ |
| 228 |
log("autobahn: connected"); |
| 229 |
ss << "Uri: " << msg->openInfo.uri << std::endl; |
| 230 |
ss << "Handshake Headers:" << std::endl; |
| 231 |
for (auto it : msg->openInfo.headers) |
| 232 |
{ |
| 233 |
ss << it.first << ": " << it.second << std::endl; |
| 234 |
} |
| 235 |
} |
| 236 |
else if (msg->type == ix::WebSocketMessageType::Close) |
| 237 |
{ |
| 238 |
ss << "autobahn: connection closed:"; |
| 239 |
ss << " code " << msg->closeInfo.code; |
| 240 |
ss << " reason " << msg->closeInfo.reason << std::endl; |
| 241 |
|
| 242 |
_condition.notify_one(); |
| 243 |
} |
| 244 |
else if (msg->type == ix::WebSocketMessageType::Message) |
| 245 |
{ |
| 246 |
ss << "Received " << msg->wireSize << " bytes" << std::endl; |
| 247 |
|
| 248 |
ss << "autobahn: received message: " << truncate(msg->str, 40) << std::endl; |
| 249 |
|
| 250 |
_webSocket.send(msg->str, msg->binary); |
| 251 |
} |
| 252 |
else if (msg->type == ix::WebSocketMessageType::Error) |
| 253 |
{ |
| 254 |
ss << "Connection error: " << msg->errorInfo.reason << std::endl; |
| 255 |
ss << "#retries: " << msg->errorInfo.retries << std::endl; |
| 256 |
ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl; |
| 257 |
ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl; |
| 258 |
|
| 259 |
// And error can happen, in which case the test-case is marked done |
| 260 |
_condition.notify_one(); |
| 261 |
} |
| 262 |
else if (msg->type == ix::WebSocketMessageType::Fragment) |
| 263 |
{ |
| 264 |
ss << "Received message fragment" << std::endl; |
| 265 |
} |
| 266 |
else if (msg->type == ix::WebSocketMessageType::Ping) |
| 267 |
{ |
| 268 |
ss << "Received ping" << std::endl; |
| 269 |
} |
| 270 |
else if (msg->type == ix::WebSocketMessageType::Pong) |
| 271 |
{ |
| 272 |
ss << "Received pong" << std::endl; |
| 273 |
} |
| 274 |
else |
| 275 |
{ |
| 276 |
ss << "Invalid ix::WebSocketMessageType" << std::endl; |
| 277 |
} |
| 278 |
|
| 279 |
log(ss.str()); |
| 280 |
}); |
| 281 |
|
| 282 |
_webSocket.start(); |
| 283 |
|
| 284 |
log("Waiting for test completion ..."); |
| 285 |
std::unique_lock<std::mutex> lock(_mutex); |
| 286 |
_condition.wait(lock); |
| 287 |
|
| 288 |
_webSocket.stop(); |
| 289 |
} |
| 290 |
|
| 291 |
bool generateReport(const std::string& url) |
| 292 |
{ |
| 293 |
ix::WebSocket webSocket; |
| 294 |
std::string reportUrl(url); |
| 295 |
reportUrl += "/updateReports?agent=ixwebsocket"; |
| 296 |
webSocket.setUrl(reportUrl); |
| 297 |
webSocket.disableAutomaticReconnection(); |
| 298 |
|
| 299 |
std::atomic<bool> success(true); |
| 300 |
std::condition_variable condition; |
| 301 |
|
| 302 |
webSocket.setOnMessageCallback([&condition, &success](const ix::WebSocketMessagePtr& msg) { |
| 303 |
if (msg->type == ix::WebSocketMessageType::Close) |
| 304 |
{ |
| 305 |
spdlog::info("Report generated"); |
| 306 |
condition.notify_one(); |
| 307 |
} |
| 308 |
else if (msg->type == ix::WebSocketMessageType::Error) |
| 309 |
{ |
| 310 |
std::stringstream ss; |
| 311 |
ss << "Connection error: " << msg->errorInfo.reason << std::endl; |
| 312 |
ss << "#retries: " << msg->errorInfo.retries << std::endl; |
| 313 |
ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl; |
| 314 |
ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl; |
| 315 |
spdlog::info(ss.str()); |
| 316 |
|
| 317 |
success = false; |
| 318 |
} |
| 319 |
}); |
| 320 |
|
| 321 |
webSocket.start(); |
| 322 |
std::mutex mutex; |
| 323 |
std::unique_lock<std::mutex> lock(mutex); |
| 324 |
condition.wait(lock); |
| 325 |
webSocket.stop(); |
| 326 |
|
| 327 |
if (!success) |
| 328 |
{ |
| 329 |
spdlog::error("Cannot generate report at url {}", reportUrl); |
| 330 |
} |
| 331 |
|
| 332 |
return success; |
| 333 |
} |
| 334 |
|
| 335 |
int getTestCaseCount(const std::string& url) |
| 336 |
{ |
| 337 |
ix::WebSocket webSocket; |
| 338 |
std::string caseCountUrl(url); |
| 339 |
caseCountUrl += "/getCaseCount"; |
| 340 |
webSocket.setUrl(caseCountUrl); |
| 341 |
webSocket.disableAutomaticReconnection(); |
| 342 |
|
| 343 |
int count = -1; |
| 344 |
std::condition_variable condition; |
| 345 |
|
| 346 |
webSocket.setOnMessageCallback([&condition, &count](const ix::WebSocketMessagePtr& msg) { |
| 347 |
if (msg->type == ix::WebSocketMessageType::Close) |
| 348 |
{ |
| 349 |
condition.notify_one(); |
| 350 |
} |
| 351 |
else if (msg->type == ix::WebSocketMessageType::Error) |
| 352 |
{ |
| 353 |
std::stringstream ss; |
| 354 |
ss << "Connection error: " << msg->errorInfo.reason << std::endl; |
| 355 |
ss << "#retries: " << msg->errorInfo.retries << std::endl; |
| 356 |
ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl; |
| 357 |
ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl; |
| 358 |
spdlog::info(ss.str()); |
| 359 |
|
| 360 |
condition.notify_one(); |
| 361 |
} |
| 362 |
else if (msg->type == ix::WebSocketMessageType::Message) |
| 363 |
{ |
| 364 |
// response is a string |
| 365 |
std::stringstream ss; |
| 366 |
ss << msg->str; |
| 367 |
ss >> count; |
| 368 |
} |
| 369 |
}); |
| 370 |
|
| 371 |
webSocket.start(); |
| 372 |
std::mutex mutex; |
| 373 |
std::unique_lock<std::mutex> lock(mutex); |
| 374 |
condition.wait(lock); |
| 375 |
webSocket.stop(); |
| 376 |
|
| 377 |
if (count == -1) |
| 378 |
{ |
| 379 |
spdlog::error("Cannot retrieve test case count at url {}", caseCountUrl); |
| 380 |
} |
| 381 |
|
| 382 |
return count; |
| 383 |
} |
| 384 |
|
| 385 |
// |
| 386 |
// make && bench ws autobahn --url ws://localhost:9001 |
| 387 |
// |
| 388 |
int ws_autobahn_main(const std::string& url, bool quiet) |
| 389 |
{ |
| 390 |
int testCasesCount = getTestCaseCount(url); |
| 391 |
spdlog::info("Test cases count: {}", testCasesCount); |
| 392 |
|
| 393 |
if (testCasesCount == -1) |
| 394 |
{ |
| 395 |
spdlog::error("Cannot retrieve test case count at url {}", url); |
| 396 |
return 1; |
| 397 |
} |
| 398 |
|
| 399 |
testCasesCount++; |
| 400 |
|
| 401 |
for (int i = 1; i < testCasesCount; ++i) |
| 402 |
{ |
| 403 |
spdlog::info("Execute test case {}", i); |
| 404 |
|
| 405 |
int caseNumber = i; |
| 406 |
|
| 407 |
std::stringstream ss; |
| 408 |
ss << url << "/runCase?case=" << caseNumber << "&agent=ixwebsocket"; |
| 409 |
|
| 410 |
std::string url(ss.str()); |
| 411 |
|
| 412 |
AutobahnTestCase testCase(url, quiet); |
| 413 |
testCase.run(); |
| 414 |
} |
| 415 |
|
| 416 |
return generateReport(url) ? 0 : 1; |
| 417 |
} |
| 418 |
|
| 419 |
/* |
| 420 |
* ws_chat.cpp |
| 421 |
* Author: Benjamin Sergeant |
| 422 |
* Copyright (c) 2017-2019 Machine Zone, Inc. All rights reserved. |
| 423 |
*/ |
| 424 |
|
| 425 |
// |
| 426 |
// Simple chat program that talks to a broadcast server |
| 427 |
// Broadcast server can be ran with `ws broadcast_server` |
| 428 |
// |
| 429 |
|
| 430 |
class WebSocketChat |
| 431 |
{ |
| 432 |
public: |
| 433 |
WebSocketChat(const std::string& url, const std::string& user); |
| 434 |
|
| 435 |
void subscribe(const std::string& channel); |
| 436 |
void start(); |
| 437 |
void stop(); |
| 438 |
bool isReady() const; |
| 439 |
|
| 440 |
void sendMessage(const std::string& text); |
| 441 |
size_t getReceivedMessagesCount() const; |
| 442 |
|
| 443 |
std::string encodeMessage(const std::string& text); |
| 444 |
std::pair<std::string, std::string> decodeMessage(const std::string& str); |
| 445 |
|
| 446 |
private: |
| 447 |
std::string _url; |
| 448 |
std::string _user; |
| 449 |
ix::WebSocket _webSocket; |
| 450 |
std::queue<std::string> _receivedQueue; |
| 451 |
|
| 452 |
void log(const std::string& msg); |
| 453 |
}; |
| 454 |
|
| 455 |
WebSocketChat::WebSocketChat(const std::string& url, const std::string& user) |
| 456 |
: _url(url) |
| 457 |
, _user(user) |
| 458 |
{ |
| 459 |
; |
| 460 |
} |
| 461 |
|
| 462 |
void WebSocketChat::log(const std::string& msg) |
| 463 |
{ |
| 464 |
spdlog::info(msg); |
| 465 |
} |
| 466 |
|
| 467 |
size_t WebSocketChat::getReceivedMessagesCount() const |
| 468 |
{ |
| 469 |
return _receivedQueue.size(); |
| 470 |
} |
| 471 |
|
| 472 |
bool WebSocketChat::isReady() const |
| 473 |
{ |
| 474 |
return _webSocket.getReadyState() == ix::ReadyState::Open; |
| 475 |
} |
| 476 |
|
| 477 |
void WebSocketChat::stop() |
| 478 |
{ |
| 479 |
_webSocket.stop(); |
| 480 |
} |
| 481 |
|
| 482 |
void WebSocketChat::start() |
| 483 |
{ |
| 484 |
_webSocket.setUrl(_url); |
| 485 |
|
| 486 |
std::stringstream ss; |
| 487 |
log(std::string("Connecting to url: ") + _url); |
| 488 |
|
| 489 |
_webSocket.setOnMessageCallback([this](const WebSocketMessagePtr& msg) { |
| 490 |
std::stringstream ss; |
| 491 |
if (msg->type == ix::WebSocketMessageType::Open) |
| 492 |
{ |
| 493 |
log("ws chat: connected"); |
| 494 |
spdlog::info("Uri: {}", msg->openInfo.uri); |
| 495 |
spdlog::info("Headers:"); |
| 496 |
for (auto it : msg->openInfo.headers) |
| 497 |
{ |
| 498 |
spdlog::info("{}: {}", it.first, it.second); |
| 499 |
} |
| 500 |
|
| 501 |
spdlog::info("ws chat: user {} connected !", _user); |
| 502 |
log(ss.str()); |
| 503 |
} |
| 504 |
else if (msg->type == ix::WebSocketMessageType::Close) |
| 505 |
{ |
| 506 |
ss << "ws chat user disconnected: " << _user; |
| 507 |
ss << " code " << msg->closeInfo.code; |
| 508 |
ss << " reason " << msg->closeInfo.reason << std::endl; |
| 509 |
log(ss.str()); |
| 510 |
} |
| 511 |
else if (msg->type == ix::WebSocketMessageType::Message) |
| 512 |
{ |
| 513 |
auto result = decodeMessage(msg->str); |
| 514 |
|
| 515 |
// Our "chat" / "broacast" node.js server does not send us |
| 516 |
// the messages we send, so we don't have to filter it out. |
| 517 |
|
| 518 |
// store text |
| 519 |
_receivedQueue.push(result.second); |
| 520 |
|
| 521 |
ss << std::endl |
| 522 |
<< result.first << "(" << msg->wireSize << " bytes)" |
| 523 |
<< " > " << result.second << std::endl |
| 524 |
<< _user << " > "; |
| 525 |
log(ss.str()); |
| 526 |
} |
| 527 |
else if (msg->type == ix::WebSocketMessageType::Error) |
| 528 |
{ |
| 529 |
ss << "Connection error: " << msg->errorInfo.reason << std::endl; |
| 530 |
ss << "#retries: " << msg->errorInfo.retries << std::endl; |
| 531 |
ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl; |
| 532 |
ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl; |
| 533 |
log(ss.str()); |
| 534 |
} |
| 535 |
else |
| 536 |
{ |
| 537 |
ss << "Invalid ix::WebSocketMessageType"; |
| 538 |
log(ss.str()); |
| 539 |
} |
| 540 |
}); |
| 541 |
|
| 542 |
_webSocket.start(); |
| 543 |
} |
| 544 |
|
| 545 |
std::pair<std::string, std::string> WebSocketChat::decodeMessage(const std::string& str) |
| 546 |
{ |
| 547 |
std::string errMsg; |
| 548 |
MsgPack msg = MsgPack::parse(str, errMsg); |
| 549 |
|
| 550 |
std::string msg_user = msg["user"].string_value(); |
| 551 |
std::string msg_text = msg["text"].string_value(); |
| 552 |
|
| 553 |
return std::pair<std::string, std::string>(msg_user, msg_text); |
| 554 |
} |
| 555 |
|
| 556 |
std::string WebSocketChat::encodeMessage(const std::string& text) |
| 557 |
{ |
| 558 |
std::map<MsgPack, MsgPack> obj; |
| 559 |
obj["user"] = _user; |
| 560 |
obj["text"] = text; |
| 561 |
|
| 562 |
MsgPack msg(obj); |
| 563 |
|
| 564 |
std::string output = msg.dump(); |
| 565 |
return output; |
| 566 |
} |
| 567 |
|
| 568 |
void WebSocketChat::sendMessage(const std::string& text) |
| 569 |
{ |
| 570 |
_webSocket.sendBinary(encodeMessage(text)); |
| 571 |
} |
| 572 |
|
| 573 |
int ws_chat_main(const std::string& url, const std::string& user) |
| 574 |
{ |
| 575 |
spdlog::info("Type Ctrl-D to exit prompt..."); |
| 576 |
WebSocketChat webSocketChat(url, user); |
| 577 |
webSocketChat.start(); |
| 578 |
|
| 579 |
while (true) |
| 580 |
{ |
| 581 |
// Read line |
| 582 |
std::string line; |
| 583 |
std::cout << user << " > " << std::flush; |
| 584 |
std::getline(std::cin, line); |
| 585 |
|
| 586 |
if (!std::cin) |
| 587 |
{ |
| 588 |
break; |
| 589 |
} |
| 590 |
|
| 591 |
webSocketChat.sendMessage(line); |
| 592 |
} |
| 593 |
|
| 594 |
spdlog::info(""); |
| 595 |
webSocketChat.stop(); |
| 596 |
|
| 597 |
return 0; |
| 598 |
} |
| 599 |
|
| 600 |
class WebSocketConnect |
| 601 |
{ |
| 602 |
public: |
| 603 |
WebSocketConnect(const std::string& _url, |
| 604 |
const std::string& headers, |
| 605 |
bool disableAutomaticReconnection, |
| 606 |
bool disablePerMessageDeflate, |
| 607 |
bool binaryMode, |
| 608 |
uint32_t maxWaitBetweenReconnectionRetries, |
| 609 |
const ix::SocketTLSOptions& tlsOptions, |
| 610 |
const std::string& subprotocol, |
| 611 |
int pingIntervalSecs, |
| 612 |
bool decompressGzipMessages); |
| 613 |
|
| 614 |
void subscribe(const std::string& channel); |
| 615 |
void start(); |
| 616 |
void stop(); |
| 617 |
|
| 618 |
int getSentBytes() |
| 619 |
{ |
| 620 |
return _sentBytes; |
| 621 |
} |
| 622 |
int getReceivedBytes() |
| 623 |
{ |
| 624 |
return _receivedBytes; |
| 625 |
} |
| 626 |
|
| 627 |
void sendMessage(const std::string& text); |
| 628 |
|
| 629 |
private: |
| 630 |
std::string _url; |
| 631 |
WebSocketHttpHeaders _headers; |
| 632 |
ix::WebSocket _webSocket; |
| 633 |
bool _disablePerMessageDeflate; |
| 634 |
bool _binaryMode; |
| 635 |
std::atomic<int> _receivedBytes; |
| 636 |
std::atomic<int> _sentBytes; |
| 637 |
bool _decompressGzipMessages; |
| 638 |
|
| 639 |
void log(const std::string& msg); |
| 640 |
WebSocketHttpHeaders parseHeaders(const std::string& data); |
| 641 |
}; |
| 642 |
|
| 643 |
WebSocketConnect::WebSocketConnect(const std::string& url, |
| 644 |
const std::string& headers, |
| 645 |
bool disableAutomaticReconnection, |
| 646 |
bool disablePerMessageDeflate, |
| 647 |
bool binaryMode, |
| 648 |
uint32_t maxWaitBetweenReconnectionRetries, |
| 649 |
const ix::SocketTLSOptions& tlsOptions, |
| 650 |
const std::string& subprotocol, |
| 651 |
int pingIntervalSecs, |
| 652 |
bool decompressGzipMessages) |
| 653 |
: _url(url) |
| 654 |
, _disablePerMessageDeflate(disablePerMessageDeflate) |
| 655 |
, _binaryMode(binaryMode) |
| 656 |
, _receivedBytes(0) |
| 657 |
, _sentBytes(0) |
| 658 |
, _decompressGzipMessages(decompressGzipMessages) |
| 659 |
{ |
| 660 |
if (disableAutomaticReconnection) |
| 661 |
{ |
| 662 |
_webSocket.disableAutomaticReconnection(); |
| 663 |
} |
| 664 |
_webSocket.setMaxWaitBetweenReconnectionRetries(maxWaitBetweenReconnectionRetries); |
| 665 |
_webSocket.setTLSOptions(tlsOptions); |
| 666 |
_webSocket.setPingInterval(pingIntervalSecs); |
| 667 |
|
| 668 |
_headers = parseHeaders(headers); |
| 669 |
|
| 670 |
if (!subprotocol.empty()) |
| 671 |
{ |
| 672 |
_webSocket.addSubProtocol(subprotocol); |
| 673 |
} |
| 674 |
|
| 675 |
WebSocket::setTrafficTrackerCallback([this](int size, bool incoming) { |
| 676 |
if (incoming) |
| 677 |
{ |
| 678 |
_receivedBytes += size; |
| 679 |
} |
| 680 |
else |
| 681 |
{ |
| 682 |
_sentBytes += size; |
| 683 |
} |
| 684 |
}); |
| 685 |
} |
| 686 |
|
| 687 |
void WebSocketConnect::log(const std::string& msg) |
| 688 |
{ |
| 689 |
std::cout << msg << std::endl; |
| 690 |
} |
| 691 |
|
| 692 |
WebSocketHttpHeaders WebSocketConnect::parseHeaders(const std::string& data) |
| 693 |
{ |
| 694 |
WebSocketHttpHeaders headers; |
| 695 |
|
| 696 |
// Split by \n |
| 697 |
std::string token; |
| 698 |
std::stringstream tokenStream(data); |
| 699 |
|
| 700 |
while (std::getline(tokenStream, token)) |
| 701 |
{ |
| 702 |
std::size_t pos = token.rfind(':'); |
| 703 |
|
| 704 |
// Bail out if last '.' is found |
| 705 |
if (pos == std::string::npos) continue; |
| 706 |
|
| 707 |
auto key = token.substr(0, pos); |
| 708 |
auto val = token.substr(pos + 1); |
| 709 |
|
| 710 |
spdlog::info("{}: {}", key, val); |
| 711 |
headers[key] = val; |
| 712 |
} |
| 713 |
|
| 714 |
return headers; |
| 715 |
} |
| 716 |
|
| 717 |
void WebSocketConnect::stop() |
| 718 |
{ |
| 719 |
{ |
| 720 |
Bench bench("ws_connect: stop connection"); |
| 721 |
_webSocket.stop(); |
| 722 |
} |
| 723 |
} |
| 724 |
|
| 725 |
void WebSocketConnect::start() |
| 726 |
{ |
| 727 |
_webSocket.setUrl(_url); |
| 728 |
_webSocket.setExtraHeaders(_headers); |
| 729 |
|
| 730 |
if (_disablePerMessageDeflate) |
| 731 |
{ |
| 732 |
_webSocket.disablePerMessageDeflate(); |
| 733 |
} |
| 734 |
else |
| 735 |
{ |
| 736 |
ix::WebSocketPerMessageDeflateOptions webSocketPerMessageDeflateOptions( |
| 737 |
true, false, false, 15, 15); |
| 738 |
_webSocket.setPerMessageDeflateOptions(webSocketPerMessageDeflateOptions); |
| 739 |
} |
| 740 |
|
| 741 |
std::stringstream ss; |
| 742 |
log(std::string("Connecting to url: ") + _url); |
| 743 |
|
| 744 |
_webSocket.setOnMessageCallback([this](const ix::WebSocketMessagePtr& msg) { |
| 745 |
std::stringstream ss; |
| 746 |
if (msg->type == ix::WebSocketMessageType::Open) |
| 747 |
{ |
| 748 |
spdlog::info("ws_connect: connected"); |
| 749 |
spdlog::info("Uri: {}", msg->openInfo.uri); |
| 750 |
spdlog::info("Headers:"); |
| 751 |
for (auto it : msg->openInfo.headers) |
| 752 |
{ |
| 753 |
spdlog::info("{}: {}", it.first, it.second); |
| 754 |
} |
| 755 |
} |
| 756 |
else if (msg->type == ix::WebSocketMessageType::Close) |
| 757 |
{ |
| 758 |
ss << "ws_connect: connection closed:"; |
| 759 |
ss << " code " << msg->closeInfo.code; |
| 760 |
ss << " reason " << msg->closeInfo.reason << std::endl; |
| 761 |
log(ss.str()); |
| 762 |
} |
| 763 |
else if (msg->type == ix::WebSocketMessageType::Message) |
| 764 |
{ |
| 765 |
spdlog::info("Received {} bytes", msg->wireSize); |
| 766 |
|
| 767 |
std::string payload = msg->str; |
| 768 |
if (_decompressGzipMessages) |
| 769 |
{ |
| 770 |
std::string decompressedBytes; |
| 771 |
if (gzipDecompress(payload, decompressedBytes)) |
| 772 |
{ |
| 773 |
payload = decompressedBytes; |
| 774 |
} |
| 775 |
else |
| 776 |
{ |
| 777 |
spdlog::error("Error decompressing: {}", payload); |
| 778 |
} |
| 779 |
} |
| 780 |
|
| 781 |
ss << "ws_connect: received message: " << payload; |
| 782 |
log(ss.str()); |
| 783 |
} |
| 784 |
else if (msg->type == ix::WebSocketMessageType::Error) |
| 785 |
{ |
| 786 |
ss << "Connection error: " << msg->errorInfo.reason << std::endl; |
| 787 |
ss << "#retries: " << msg->errorInfo.retries << std::endl; |
| 788 |
ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl; |
| 789 |
ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl; |
| 790 |
log(ss.str()); |
| 791 |
} |
| 792 |
else if (msg->type == ix::WebSocketMessageType::Fragment) |
| 793 |
{ |
| 794 |
spdlog::info("Received message fragment"); |
| 795 |
} |
| 796 |
else if (msg->type == ix::WebSocketMessageType::Ping) |
| 797 |
{ |
| 798 |
spdlog::info("Received ping"); |
| 799 |
} |
| 800 |
else if (msg->type == ix::WebSocketMessageType::Pong) |
| 801 |
{ |
| 802 |
spdlog::info("Received pong {}", msg->str); |
| 803 |
} |
| 804 |
else |
| 805 |
{ |
| 806 |
ss << "Invalid ix::WebSocketMessageType"; |
| 807 |
log(ss.str()); |
| 808 |
} |
| 809 |
}); |
| 810 |
|
| 811 |
_webSocket.start(); |
| 812 |
} |
| 813 |
|
| 814 |
void WebSocketConnect::sendMessage(const std::string& text) |
| 815 |
{ |
| 816 |
if (_binaryMode) |
| 817 |
{ |
| 818 |
_webSocket.sendBinary(text); |
| 819 |
} |
| 820 |
else |
| 821 |
{ |
| 822 |
_webSocket.sendText(text); |
| 823 |
} |
| 824 |
} |
| 825 |
|
| 826 |
int ws_connect_main(const std::string& url, |
| 827 |
const std::string& headers, |
| 828 |
bool disableAutomaticReconnection, |
| 829 |
bool disablePerMessageDeflate, |
| 830 |
bool binaryMode, |
| 831 |
uint32_t maxWaitBetweenReconnectionRetries, |
| 832 |
const ix::SocketTLSOptions& tlsOptions, |
| 833 |
const std::string& subprotocol, |
| 834 |
int pingIntervalSecs, |
| 835 |
bool decompressGzipMessages) |
| 836 |
{ |
| 837 |
std::cout << "Type Ctrl-D to exit prompt..." << std::endl; |
| 838 |
WebSocketConnect webSocketChat(url, |
| 839 |
headers, |
| 840 |
disableAutomaticReconnection, |
| 841 |
disablePerMessageDeflate, |
| 842 |
binaryMode, |
| 843 |
maxWaitBetweenReconnectionRetries, |
| 844 |
tlsOptions, |
| 845 |
subprotocol, |
| 846 |
pingIntervalSecs, |
| 847 |
decompressGzipMessages); |
| 848 |
webSocketChat.start(); |
| 849 |
|
| 850 |
while (true) |
| 851 |
{ |
| 852 |
// Read line |
| 853 |
std::string line; |
| 854 |
auto quit = linenoise::Readline("> ", line); |
| 855 |
|
| 856 |
if (quit) |
| 857 |
{ |
| 858 |
break; |
| 859 |
} |
| 860 |
|
| 861 |
if (line == "/stop") |
| 862 |
{ |
| 863 |
spdlog::info("Stopping connection..."); |
| 864 |
webSocketChat.stop(); |
| 865 |
continue; |
| 866 |
} |
| 867 |
|
| 868 |
if (line == "/start") |
| 869 |
{ |
| 870 |
spdlog::info("Starting connection..."); |
| 871 |
webSocketChat.start(); |
| 872 |
continue; |
| 873 |
} |
| 874 |
|
| 875 |
webSocketChat.sendMessage(line); |
| 876 |
|
| 877 |
// Add text to history |
| 878 |
linenoise::AddHistory(line.c_str()); |
| 879 |
} |
| 880 |
|
| 881 |
spdlog::info(""); |
| 882 |
webSocketChat.stop(); |
| 883 |
|
| 884 |
spdlog::info("Received {} bytes", webSocketChat.getReceivedBytes()); |
| 885 |
spdlog::info("Sent {} bytes", webSocketChat.getSentBytes()); |
| 886 |
|
| 887 |
return 0; |
| 888 |
} |
| 889 |
|
| 890 |
int ws_dns_lookup(const std::string& hostname) |
| 891 |
{ |
| 892 |
auto dnsLookup = std::make_shared<DNSLookup>(hostname, 80); |
| 893 |
|
| 894 |
std::string errMsg; |
| 895 |
|
| 896 |
auto res = dnsLookup->resolve(errMsg, [] { return false; }); |
| 897 |
|
| 898 |
auto addr = res->ai_addr; |
| 899 |
|
| 900 |
// FIXME: this display weird addresses / we could steal libuv inet.c |
| 901 |
// code which display correct results |
| 902 |
|
| 903 |
char str[INET_ADDRSTRLEN]; |
| 904 |
ix::inet_ntop(AF_INET, &addr, str, INET_ADDRSTRLEN); |
| 905 |
|
| 906 |
spdlog::info("host: {} ip: {}", hostname, str); |
| 907 |
|
| 908 |
return 0; |
| 909 |
} |
| 910 |
|
| 911 |
int ws_gzip(const std::string& filename, int runCount) |
| 912 |
{ |
| 913 |
auto res = readAsString(filename); |
| 914 |
bool found = res.first; |
| 915 |
if (!found) |
| 916 |
{ |
| 917 |
spdlog::error("Cannot read content of {}", filename); |
| 918 |
return 1; |
| 919 |
} |
| 920 |
|
| 921 |
spdlog::info("gzip input: {} size {} cksum {}", |
| 922 |
filename, |
| 923 |
res.second.size(), |
| 924 |
djb2HashStr(res.second)); |
| 925 |
|
| 926 |
std::string compressedBytes; |
| 927 |
|
| 928 |
spdlog::info("compressing {} times", runCount); |
| 929 |
std::vector<uint64_t> durations; |
| 930 |
{ |
| 931 |
Bench bench("compressing file"); |
| 932 |
bench.setReported(); |
| 933 |
|
| 934 |
for (int i = 0; i < runCount; ++i) |
| 935 |
{ |
| 936 |
bench.reset(); |
| 937 |
compressedBytes = gzipCompress(res.second); |
| 938 |
bench.record(); |
| 939 |
durations.push_back(bench.getDuration()); |
| 940 |
} |
| 941 |
|
| 942 |
size_t medianIdx = durations.size() / 2; |
| 943 |
uint64_t medianRuntime = durations[medianIdx]; |
| 944 |
spdlog::info("median runtime to compress file: {}", medianRuntime); |
| 945 |
} |
| 946 |
|
| 947 |
std::string outputFilename(filename); |
| 948 |
outputFilename += ".gz"; |
| 949 |
|
| 950 |
std::ofstream f; |
| 951 |
f.open(outputFilename); |
| 952 |
f << compressedBytes; |
| 953 |
f.close(); |
| 954 |
|
| 955 |
spdlog::info("gzip output: {} size {} cksum {}", |
| 956 |
outputFilename, |
| 957 |
compressedBytes.size(), |
| 958 |
djb2HashStr(compressedBytes)); |
| 959 |
|
| 960 |
return 0; |
| 961 |
} |
| 962 |
|
| 963 |
int ws_gunzip(const std::string& filename) |
| 964 |
{ |
| 965 |
spdlog::info("filename to gunzip: {}", filename); |
| 966 |
|
| 967 |
auto res = readAsString(filename); |
| 968 |
bool found = res.first; |
| 969 |
if (!found) |
| 970 |
{ |
| 971 |
spdlog::error("Cannot read content of {}", filename); |
| 972 |
return 1; |
| 973 |
} |
| 974 |
|
| 975 |
spdlog::info("gunzip input: {} size {} cksum {}", |
| 976 |
filename, |
| 977 |
res.second.size(), |
| 978 |
djb2HashStr(res.second)); |
| 979 |
|
| 980 |
std::string decompressedBytes; |
| 981 |
|
| 982 |
{ |
| 983 |
Bench bench("decompressing file"); |
| 984 |
if (!gzipDecompress(res.second, decompressedBytes)) |
| 985 |
{ |
| 986 |
spdlog::error("Cannot decompress content of {}", filename); |
| 987 |
return 1; |
| 988 |
} |
| 989 |
} |
| 990 |
|
| 991 |
std::string outputFilename(removeExtension(filename)); |
| 992 |
|
| 993 |
std::ofstream f; |
| 994 |
f.open(outputFilename); |
| 995 |
if (!f.is_open()) |
| 996 |
{ |
| 997 |
spdlog::error("Cannot open {} for writing", outputFilename); |
| 998 |
return 1; |
| 999 |
} |
| 1000 |
f << decompressedBytes; |
| 1001 |
f.close(); |
| 1002 |
|
| 1003 |
spdlog::info("gunzip output: {} size {} cksum {}", |
| 1004 |
outputFilename, |
| 1005 |
decompressedBytes.size(), |
| 1006 |
djb2HashStr(decompressedBytes)); |
| 1007 |
|
| 1008 |
return 0; |
| 1009 |
} |
| 1010 |
|
| 1011 |
int ws_autoroute(const std::string& url, |
| 1012 |
bool disablePerMessageDeflate, |
| 1013 |
const ix::SocketTLSOptions& tlsOptions, |
| 1014 |
const std::string& subprotocol, |
| 1015 |
int pingIntervalSecs, |
| 1016 |
int msgCount) |
| 1017 |
{ |
| 1018 |
Bench bench("ws_autoroute full test"); |
| 1019 |
|
| 1020 |
// Our websocket object |
| 1021 |
ix::WebSocket webSocket; |
| 1022 |
|
| 1023 |
std::string fullUrl(url); |
| 1024 |
fullUrl += "/"; |
| 1025 |
fullUrl += std::to_string(msgCount); |
| 1026 |
|
| 1027 |
webSocket.setUrl(fullUrl); |
| 1028 |
webSocket.setTLSOptions(tlsOptions); |
| 1029 |
webSocket.setPingInterval(pingIntervalSecs); |
| 1030 |
webSocket.disableAutomaticReconnection(); |
| 1031 |
|
| 1032 |
if (disablePerMessageDeflate) |
| 1033 |
{ |
| 1034 |
webSocket.disablePerMessageDeflate(); |
| 1035 |
} |
| 1036 |
|
| 1037 |
if (!subprotocol.empty()) |
| 1038 |
{ |
| 1039 |
webSocket.addSubProtocol(subprotocol); |
| 1040 |
} |
| 1041 |
|
| 1042 |
std::atomic<uint64_t> receivedCountPerSecs(0); |
| 1043 |
std::atomic<uint64_t> target(msgCount); |
| 1044 |
std::mutex conditionVariableMutex; |
| 1045 |
std::condition_variable condition; |
| 1046 |
|
| 1047 |
std::atomic<bool> stop(false); |
| 1048 |
std::chrono::time_point<std::chrono::high_resolution_clock> start; |
| 1049 |
|
| 1050 |
// Setup a callback to be fired |
| 1051 |
// when a message or an event (open, close, ping, pong, error) is received |
| 1052 |
webSocket.setOnMessageCallback( |
| 1053 |
[&receivedCountPerSecs, &target, &stop, &condition, &bench, &start]( |
| 1054 |
const ix::WebSocketMessagePtr& msg) { |
| 1055 |
if (msg->type == ix::WebSocketMessageType::Message) |
| 1056 |
{ |
| 1057 |
receivedCountPerSecs++; |
| 1058 |
|
| 1059 |
target -= 1; |
| 1060 |
if (target == 0) |
| 1061 |
{ |
| 1062 |
stop = true; |
| 1063 |
condition.notify_one(); |
| 1064 |
|
| 1065 |
bench.report(); |
| 1066 |
|
| 1067 |
auto now = std::chrono::high_resolution_clock::now(); |
| 1068 |
auto milliseconds = |
| 1069 |
std::chrono::duration_cast<std::chrono::milliseconds>(now - start); |
| 1070 |
auto duration = milliseconds.count(); |
| 1071 |
|
| 1072 |
spdlog::info("AUTOROUTE IXWebSocket :: {} ms", duration); |
| 1073 |
} |
| 1074 |
} |
| 1075 |
else if (msg->type == ix::WebSocketMessageType::Open) |
| 1076 |
{ |
| 1077 |
bench.reset(); |
| 1078 |
|
| 1079 |
spdlog::info("ws_autoroute: connected"); |
| 1080 |
spdlog::info("Uri: {}", msg->openInfo.uri); |
| 1081 |
spdlog::info("Headers:"); |
| 1082 |
for (auto it : msg->openInfo.headers) |
| 1083 |
{ |
| 1084 |
spdlog::info("{}: {}", it.first, it.second); |
| 1085 |
} |
| 1086 |
|
| 1087 |
start = std::chrono::high_resolution_clock::now(); |
| 1088 |
} |
| 1089 |
else if (msg->type == ix::WebSocketMessageType::Pong) |
| 1090 |
{ |
| 1091 |
spdlog::info("Received pong {}", msg->str); |
| 1092 |
} |
| 1093 |
else if (msg->type == ix::WebSocketMessageType::Close) |
| 1094 |
{ |
| 1095 |
spdlog::info("ws_autoroute: connection closed"); |
| 1096 |
} |
| 1097 |
}); |
| 1098 |
|
| 1099 |
auto timer = [&receivedCountPerSecs, &stop] { |
| 1100 |
setThreadName("Timer"); |
| 1101 |
while (!stop) |
| 1102 |
{ |
| 1103 |
// |
| 1104 |
// We cannot write to sentCount and receivedCount |
| 1105 |
// as those are used externally, so we need to introduce |
| 1106 |
// our own counters |
| 1107 |
// |
| 1108 |
std::stringstream ss; |
| 1109 |
ss << "messages received per second: " << receivedCountPerSecs; |
| 1110 |
|
| 1111 |
spdlog::info(ss.str()); |
| 1112 |
|
| 1113 |
receivedCountPerSecs = 0; |
| 1114 |
|
| 1115 |
auto duration = std::chrono::seconds(1); |
| 1116 |
std::this_thread::sleep_for(duration); |
| 1117 |
} |
| 1118 |
}; |
| 1119 |
|
| 1120 |
std::thread t1(timer); |
| 1121 |
|
| 1122 |
// Now that our callback is setup, we can start our background thread and receive messages |
| 1123 |
std::cout << "Connecting to " << url << "..." << std::endl; |
| 1124 |
webSocket.start(); |
| 1125 |
|
| 1126 |
// Wait for all the messages to be received |
| 1127 |
std::unique_lock<std::mutex> lock(conditionVariableMutex); |
| 1128 |
condition.wait(lock); |
| 1129 |
|
| 1130 |
t1.join(); |
| 1131 |
webSocket.stop(); |
| 1132 |
|
| 1133 |
return 0; |
| 1134 |
} |
| 1135 |
|
| 1136 |
int ws_echo_server_main(int port, |
| 1137 |
bool greetings, |
| 1138 |
const std::string& hostname, |
| 1139 |
const ix::SocketTLSOptions& tlsOptions, |
| 1140 |
bool ipv6, |
| 1141 |
bool disablePerMessageDeflate, |
| 1142 |
bool disablePong, |
| 1143 |
const std::string& httpHeaderAuthorization) |
| 1144 |
{ |
| 1145 |
spdlog::info("Listening on {}:{}", hostname, port); |
| 1146 |
|
| 1147 |
ix::WebSocketServer server(port, |
| 1148 |
hostname, |
| 1149 |
SocketServer::kDefaultTcpBacklog, |
| 1150 |
SocketServer::kDefaultMaxConnections, |
| 1151 |
WebSocketServer::kDefaultHandShakeTimeoutSecs, |
| 1152 |
(ipv6) ? AF_INET6 : AF_INET); |
| 1153 |
|
| 1154 |
server.setTLSOptions(tlsOptions); |
| 1155 |
|
| 1156 |
if (disablePerMessageDeflate) |
| 1157 |
{ |
| 1158 |
spdlog::info("Disable per message deflate"); |
| 1159 |
server.disablePerMessageDeflate(); |
| 1160 |
} |
| 1161 |
|
| 1162 |
if (disablePong) |
| 1163 |
{ |
| 1164 |
spdlog::info("Disable responding to PING messages with PONG"); |
| 1165 |
server.disablePong(); |
| 1166 |
} |
| 1167 |
|
| 1168 |
server.setOnClientMessageCallback( |
| 1169 |
[greetings, httpHeaderAuthorization](std::shared_ptr<ConnectionState> connectionState, |
| 1170 |
WebSocket& webSocket, |
| 1171 |
const WebSocketMessagePtr& msg) { |
| 1172 |
auto remoteIp = connectionState->getRemoteIp(); |
| 1173 |
if (msg->type == ix::WebSocketMessageType::Open) |
| 1174 |
{ |
| 1175 |
spdlog::info("New connection"); |
| 1176 |
spdlog::info("remote ip: {}", remoteIp); |
| 1177 |
spdlog::info("id: {}", connectionState->getId()); |
| 1178 |
spdlog::info("Uri: {}", msg->openInfo.uri); |
| 1179 |
spdlog::info("Headers:"); |
| 1180 |
for (auto it : msg->openInfo.headers) |
| 1181 |
{ |
| 1182 |
spdlog::info("{}: {}", it.first, it.second); |
| 1183 |
} |
| 1184 |
|
| 1185 |
if (!httpHeaderAuthorization.empty()) |
| 1186 |
{ |
| 1187 |
auto authorization = msg->openInfo.headers["Authorization"]; |
| 1188 |
if (authorization != httpHeaderAuthorization) |
| 1189 |
{ |
| 1190 |
webSocket.close(4001, "Permission denied"); |
| 1191 |
} |
| 1192 |
else |
| 1193 |
{ |
| 1194 |
webSocket.sendText("Authorization suceeded!"); |
| 1195 |
} |
| 1196 |
} |
| 1197 |
|
| 1198 |
if (greetings) |
| 1199 |
{ |
| 1200 |
webSocket.sendText("Welcome !"); |
| 1201 |
} |
| 1202 |
} |
| 1203 |
else if (msg->type == ix::WebSocketMessageType::Close) |
| 1204 |
{ |
| 1205 |
spdlog::info("Closed connection: client id {} code {} reason {}", |
| 1206 |
connectionState->getId(), |
| 1207 |
msg->closeInfo.code, |
| 1208 |
msg->closeInfo.reason); |
| 1209 |
} |
| 1210 |
else if (msg->type == ix::WebSocketMessageType::Error) |
| 1211 |
{ |
| 1212 |
spdlog::error("Connection error: {}", msg->errorInfo.reason); |
| 1213 |
spdlog::error("#retries: {}", msg->errorInfo.retries); |
| 1214 |
spdlog::error("Wait time(ms): {}", msg->errorInfo.wait_time); |
| 1215 |
spdlog::error("HTTP Status: {}", msg->errorInfo.http_status); |
| 1216 |
} |
| 1217 |
else if (msg->type == ix::WebSocketMessageType::Message) |
| 1218 |
{ |
| 1219 |
spdlog::info("Received {} bytes", msg->wireSize); |
| 1220 |
webSocket.send(msg->str, msg->binary); |
| 1221 |
} |
| 1222 |
}); |
| 1223 |
|
| 1224 |
auto res = server.listen(); |
| 1225 |
if (!res.first) |
| 1226 |
{ |
| 1227 |
spdlog::error(res.second); |
| 1228 |
return 1; |
| 1229 |
} |
| 1230 |
|
| 1231 |
server.start(); |
| 1232 |
server.wait(); |
| 1233 |
|
| 1234 |
return 0; |
| 1235 |
} |
| 1236 |
|
| 1237 |
WebSocketHttpHeaders parseHeaders(const std::string& data) |
| 1238 |
{ |
| 1239 |
WebSocketHttpHeaders headers; |
| 1240 |
|
| 1241 |
// Split by \n |
| 1242 |
std::string token; |
| 1243 |
std::stringstream tokenStream(data); |
| 1244 |
|
| 1245 |
while (std::getline(tokenStream, token)) |
| 1246 |
{ |
| 1247 |
std::size_t pos = token.rfind(':'); |
| 1248 |
|
| 1249 |
// Bail out if last '.' is found |
| 1250 |
if (pos == std::string::npos) continue; |
| 1251 |
|
| 1252 |
auto key = token.substr(0, pos); |
| 1253 |
auto val = token.substr(pos + 1); |
| 1254 |
|
| 1255 |
spdlog::info("{}: {}", key, val); |
| 1256 |
headers[key] = val; |
| 1257 |
} |
| 1258 |
|
| 1259 |
return headers; |
| 1260 |
} |
| 1261 |
|
| 1262 |
// |
| 1263 |
// Useful endpoint to test HTTP post |
| 1264 |
// https://postman-echo.com/post |
| 1265 |
// |
| 1266 |
HttpParameters parseHttpParameters(const std::string& data) |
| 1267 |
{ |
| 1268 |
HttpParameters httpParameters; |
| 1269 |
|
| 1270 |
// Split by \n |
| 1271 |
std::string token; |
| 1272 |
std::stringstream tokenStream(data); |
| 1273 |
|
| 1274 |
while (std::getline(tokenStream, token)) |
| 1275 |
{ |
| 1276 |
std::size_t pos = token.rfind('='); |
| 1277 |
|
| 1278 |
// Bail out if last '.' is found |
| 1279 |
if (pos == std::string::npos) continue; |
| 1280 |
|
| 1281 |
auto key = token.substr(0, pos); |
| 1282 |
auto val = token.substr(pos + 1); |
| 1283 |
|
| 1284 |
spdlog::info("{}: {}", key, val); |
| 1285 |
httpParameters[key] = val; |
| 1286 |
} |
| 1287 |
|
| 1288 |
return httpParameters; |
| 1289 |
} |
| 1290 |
|
| 1291 |
HttpFormDataParameters parseHttpFormDataParameters(const std::string& data) |
| 1292 |
{ |
| 1293 |
HttpFormDataParameters httpFormDataParameters; |
| 1294 |
|
| 1295 |
// Split by \n |
| 1296 |
std::string token; |
| 1297 |
std::stringstream tokenStream(data); |
| 1298 |
|
| 1299 |
while (std::getline(tokenStream, token)) |
| 1300 |
{ |
| 1301 |
std::size_t pos = token.rfind('='); |
| 1302 |
|
| 1303 |
// Bail out if last '.' is found |
| 1304 |
if (pos == std::string::npos) continue; |
| 1305 |
|
| 1306 |
auto key = token.substr(0, pos); |
| 1307 |
auto val = token.substr(pos + 1); |
| 1308 |
|
| 1309 |
spdlog::info("{}: {}", key, val); |
| 1310 |
|
| 1311 |
if (val[0] == '@') |
| 1312 |
{ |
| 1313 |
std::string filename = token.substr(pos + 2); |
| 1314 |
|
| 1315 |
auto res = readAsString(filename); |
| 1316 |
bool found = res.first; |
| 1317 |
if (!found) |
| 1318 |
{ |
| 1319 |
spdlog::error("Cannot read content of {}", filename); |
| 1320 |
continue; |
| 1321 |
} |
| 1322 |
|
| 1323 |
val = res.second; |
| 1324 |
} |
| 1325 |
|
| 1326 |
httpFormDataParameters[key] = val; |
| 1327 |
} |
| 1328 |
|
| 1329 |
return httpFormDataParameters; |
| 1330 |
} |
| 1331 |
|
| 1332 |
int ws_http_client_main(const std::string& url, |
| 1333 |
const std::string& headersData, |
| 1334 |
const std::string& data, |
| 1335 |
const std::string& formData, |
| 1336 |
const std::string& dataBinary, |
| 1337 |
bool headersOnly, |
| 1338 |
int connectTimeout, |
| 1339 |
int transferTimeout, |
| 1340 |
bool followRedirects, |
| 1341 |
int maxRedirects, |
| 1342 |
bool verbose, |
| 1343 |
bool save, |
| 1344 |
const std::string& output, |
| 1345 |
bool compress, |
| 1346 |
bool compressRequest, |
| 1347 |
const ix::SocketTLSOptions& tlsOptions) |
| 1348 |
{ |
| 1349 |
HttpClient httpClient; |
| 1350 |
httpClient.setTLSOptions(tlsOptions); |
| 1351 |
|
| 1352 |
auto args = httpClient.createRequest(); |
| 1353 |
args->extraHeaders = parseHeaders(headersData); |
| 1354 |
args->connectTimeout = connectTimeout; |
| 1355 |
args->transferTimeout = transferTimeout; |
| 1356 |
args->followRedirects = followRedirects; |
| 1357 |
args->maxRedirects = maxRedirects; |
| 1358 |
args->verbose = verbose; |
| 1359 |
args->compress = compress; |
| 1360 |
args->compressRequest = compressRequest; |
| 1361 |
args->logger = [](const std::string& msg) { spdlog::info(msg); }; |
| 1362 |
args->onProgressCallback = [verbose](int current, int total) -> bool { |
| 1363 |
if (verbose) |
| 1364 |
{ |
| 1365 |
spdlog::info("Downloaded {} bytes out of {}", current, total); |
| 1366 |
} |
| 1367 |
return true; |
| 1368 |
}; |
| 1369 |
|
| 1370 |
HttpParameters httpParameters = parseHttpParameters(data); |
| 1371 |
HttpFormDataParameters httpFormDataParameters = parseHttpFormDataParameters(formData); |
| 1372 |
|
| 1373 |
HttpResponsePtr response; |
| 1374 |
if (headersOnly) |
| 1375 |
{ |
| 1376 |
response = httpClient.head(url, args); |
| 1377 |
} |
| 1378 |
else if (data.empty() && formData.empty() && dataBinary.empty()) |
| 1379 |
{ |
| 1380 |
response = httpClient.get(url, args); |
| 1381 |
} |
| 1382 |
else if (!dataBinary.empty()) |
| 1383 |
{ |
| 1384 |
std::string body = dataBinary; |
| 1385 |
if (compressRequest) |
| 1386 |
{ |
| 1387 |
body = gzipCompress(dataBinary); |
| 1388 |
} |
| 1389 |
response = httpClient.request(url, "POST", body, args, 0); |
| 1390 |
} |
| 1391 |
else |
| 1392 |
{ |
| 1393 |
response = httpClient.post(url, httpParameters, httpFormDataParameters, args); |
| 1394 |
} |
| 1395 |
|
| 1396 |
spdlog::info(""); |
| 1397 |
|
| 1398 |
for (auto it : response->headers) |
| 1399 |
{ |
| 1400 |
spdlog::info("{}: {}", it.first, it.second); |
| 1401 |
} |
| 1402 |
|
| 1403 |
spdlog::info("Upload size: {}", response->uploadSize); |
| 1404 |
spdlog::info("Download size: {}", response->downloadSize); |
| 1405 |
|
| 1406 |
spdlog::info("Status: {}", response->statusCode); |
| 1407 |
if (response->errorCode != HttpErrorCode::Ok) |
| 1408 |
{ |
| 1409 |
spdlog::error("error message: {}", response->errorMsg); |
| 1410 |
} |
| 1411 |
|
| 1412 |
if (!headersOnly && response->errorCode == HttpErrorCode::Ok) |
| 1413 |
{ |
| 1414 |
if (save || !output.empty()) |
| 1415 |
{ |
| 1416 |
// FIMXE we should decode the url first |
| 1417 |
std::string filename = extractFilename(url); |
| 1418 |
if (!output.empty()) |
| 1419 |
{ |
| 1420 |
filename = output; |
| 1421 |
} |
| 1422 |
|
| 1423 |
if (filename.empty()) |
| 1424 |
{ |
| 1425 |
spdlog::error("Cannot save content to disk: No output file supplied, and not " |
| 1426 |
"filename could be extracted from the url {}", |
| 1427 |
url); |
| 1428 |
} |
| 1429 |
else |
| 1430 |
{ |
| 1431 |
spdlog::info("Writing to disk: {}", filename); |
| 1432 |
std::ofstream out(filename); |
| 1433 |
out << response->body; |
| 1434 |
} |
| 1435 |
} |
| 1436 |
else |
| 1437 |
{ |
| 1438 |
if (response->headers["Content-Type"] != "application/octet-stream") |
| 1439 |
{ |
| 1440 |
spdlog::info("body: {}", response->body); |
| 1441 |
} |
| 1442 |
else |
| 1443 |
{ |
| 1444 |
spdlog::info("Binary output can mess up your terminal."); |
| 1445 |
spdlog::info("Use the -O flag to save the file to disk."); |
| 1446 |
spdlog::info("You can also use the --output option to specify a filename."); |
| 1447 |
} |
| 1448 |
} |
| 1449 |
} |
| 1450 |
|
| 1451 |
return 0; |
| 1452 |
} |
| 1453 |
|
| 1454 |
int ws_httpd_main(int port, |
| 1455 |
const std::string& hostname, |
| 1456 |
bool redirect, |
| 1457 |
const std::string& redirectUrl, |
| 1458 |
bool debug, |
| 1459 |
const ix::SocketTLSOptions& tlsOptions) |
| 1460 |
{ |
| 1461 |
spdlog::info("Listening on {}:{}", hostname, port); |
| 1462 |
|
| 1463 |
ix::HttpServer server(port, hostname); |
| 1464 |
server.setTLSOptions(tlsOptions); |
| 1465 |
|
| 1466 |
if (redirect) |
| 1467 |
{ |
| 1468 |
server.makeRedirectServer(redirectUrl); |
| 1469 |
} |
| 1470 |
|
| 1471 |
if (debug) |
| 1472 |
{ |
| 1473 |
server.makeDebugServer(); |
| 1474 |
} |
| 1475 |
|
| 1476 |
auto res = server.listen(); |
| 1477 |
if (!res.first) |
| 1478 |
{ |
| 1479 |
spdlog::error(res.second); |
| 1480 |
return 1; |
| 1481 |
} |
| 1482 |
|
| 1483 |
server.start(); |
| 1484 |
server.wait(); |
| 1485 |
|
| 1486 |
return 0; |
| 1487 |
} |
| 1488 |
|
| 1489 |
class WebSocketPingPong |
| 1490 |
{ |
| 1491 |
public: |
| 1492 |
WebSocketPingPong(const std::string& _url, const ix::SocketTLSOptions& tlsOptions); |
| 1493 |
|
| 1494 |
void subscribe(const std::string& channel); |
| 1495 |
void start(); |
| 1496 |
void stop(); |
| 1497 |
|
| 1498 |
void ping(const std::string& text); |
| 1499 |
void send(const std::string& text); |
| 1500 |
|
| 1501 |
private: |
| 1502 |
std::string _url; |
| 1503 |
ix::WebSocket _webSocket; |
| 1504 |
|
| 1505 |
void log(const std::string& msg); |
| 1506 |
}; |
| 1507 |
|
| 1508 |
WebSocketPingPong::WebSocketPingPong(const std::string& url, |
| 1509 |
const ix::SocketTLSOptions& tlsOptions) |
| 1510 |
: _url(url) |
| 1511 |
{ |
| 1512 |
_webSocket.setTLSOptions(tlsOptions); |
| 1513 |
} |
| 1514 |
|
| 1515 |
void WebSocketPingPong::log(const std::string& msg) |
| 1516 |
{ |
| 1517 |
spdlog::info(msg); |
| 1518 |
} |
| 1519 |
|
| 1520 |
void WebSocketPingPong::stop() |
| 1521 |
{ |
| 1522 |
_webSocket.stop(); |
| 1523 |
} |
| 1524 |
|
| 1525 |
void WebSocketPingPong::start() |
| 1526 |
{ |
| 1527 |
_webSocket.setUrl(_url); |
| 1528 |
|
| 1529 |
std::stringstream ss; |
| 1530 |
log(std::string("Connecting to url: ") + _url); |
| 1531 |
|
| 1532 |
_webSocket.setOnMessageCallback([this](const ix::WebSocketMessagePtr& msg) { |
| 1533 |
spdlog::info("Received {} bytes", msg->wireSize); |
| 1534 |
|
| 1535 |
std::stringstream ss; |
| 1536 |
if (msg->type == ix::WebSocketMessageType::Open) |
| 1537 |
{ |
| 1538 |
log("ping_pong: connected"); |
| 1539 |
|
| 1540 |
spdlog::info("Uri: {}", msg->openInfo.uri); |
| 1541 |
spdlog::info("Headers:"); |
| 1542 |
for (auto it : msg->openInfo.headers) |
| 1543 |
{ |
| 1544 |
spdlog::info("{}: {}", it.first, it.second); |
| 1545 |
} |
| 1546 |
} |
| 1547 |
else if (msg->type == ix::WebSocketMessageType::Close) |
| 1548 |
{ |
| 1549 |
ss << "ping_pong: disconnected:" |
| 1550 |
<< " code " << msg->closeInfo.code << " reason " << msg->closeInfo.reason |
| 1551 |
<< msg->str; |
| 1552 |
log(ss.str()); |
| 1553 |
} |
| 1554 |
else if (msg->type == ix::WebSocketMessageType::Message) |
| 1555 |
{ |
| 1556 |
ss << "ping_pong: received message: " << msg->str; |
| 1557 |
log(ss.str()); |
| 1558 |
} |
| 1559 |
else if (msg->type == ix::WebSocketMessageType::Ping) |
| 1560 |
{ |
| 1561 |
ss << "ping_pong: received ping message: " << msg->str; |
| 1562 |
log(ss.str()); |
| 1563 |
} |
| 1564 |
else if (msg->type == ix::WebSocketMessageType::Pong) |
| 1565 |
{ |
| 1566 |
ss << "ping_pong: received pong message: " << msg->str; |
| 1567 |
log(ss.str()); |
| 1568 |
} |
| 1569 |
else if (msg->type == ix::WebSocketMessageType::Error) |
| 1570 |
{ |
| 1571 |
ss << "Connection error: " << msg->errorInfo.reason << std::endl; |
| 1572 |
ss << "#retries: " << msg->errorInfo.retries << std::endl; |
| 1573 |
ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl; |
| 1574 |
ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl; |
| 1575 |
log(ss.str()); |
| 1576 |
} |
| 1577 |
else |
| 1578 |
{ |
| 1579 |
ss << "Invalid ix::WebSocketMessageType"; |
| 1580 |
log(ss.str()); |
| 1581 |
} |
| 1582 |
}); |
| 1583 |
|
| 1584 |
_webSocket.start(); |
| 1585 |
} |
| 1586 |
|
| 1587 |
void WebSocketPingPong::ping(const std::string& text) |
| 1588 |
{ |
| 1589 |
if (!_webSocket.ping(text).success) |
| 1590 |
{ |
| 1591 |
std::cerr << "Failed to send ping message. Message too long (> 125 bytes) or endpoint " |
| 1592 |
"is disconnected" |
| 1593 |
<< std::endl; |
| 1594 |
} |
| 1595 |
} |
| 1596 |
|
| 1597 |
void WebSocketPingPong::send(const std::string& text) |
| 1598 |
{ |
| 1599 |
_webSocket.send(text); |
| 1600 |
} |
| 1601 |
|
| 1602 |
int ws_ping_pong_main(const std::string& url, const ix::SocketTLSOptions& tlsOptions) |
| 1603 |
{ |
| 1604 |
spdlog::info("Type Ctrl-D to exit prompt..."); |
| 1605 |
WebSocketPingPong webSocketPingPong(url, tlsOptions); |
| 1606 |
webSocketPingPong.start(); |
| 1607 |
|
| 1608 |
while (true) |
| 1609 |
{ |
| 1610 |
std::string text; |
| 1611 |
std::cout << "> " << std::flush; |
| 1612 |
std::getline(std::cin, text); |
| 1613 |
|
| 1614 |
if (!std::cin) |
| 1615 |
{ |
| 1616 |
break; |
| 1617 |
} |
| 1618 |
|
| 1619 |
if (text == "/close") |
| 1620 |
{ |
| 1621 |
webSocketPingPong.send(text); |
| 1622 |
} |
| 1623 |
else |
| 1624 |
{ |
| 1625 |
webSocketPingPong.ping(text); |
| 1626 |
} |
| 1627 |
} |
| 1628 |
|
| 1629 |
std::cout << std::endl; |
| 1630 |
webSocketPingPong.stop(); |
| 1631 |
|
| 1632 |
return 0; |
| 1633 |
} |
| 1634 |
|
| 1635 |
int ws_push_server(int port, |
| 1636 |
const std::string& hostname, |
| 1637 |
const ix::SocketTLSOptions& tlsOptions, |
| 1638 |
bool ipv6, |
| 1639 |
bool disablePerMessageDeflate, |
| 1640 |
bool disablePong, |
| 1641 |
const std::string& sendMsg) |
| 1642 |
{ |
| 1643 |
spdlog::info("Listening on {}:{}", hostname, port); |
| 1644 |
|
| 1645 |
ix::WebSocketServer server(port, |
| 1646 |
hostname, |
| 1647 |
SocketServer::kDefaultTcpBacklog, |
| 1648 |
SocketServer::kDefaultMaxConnections, |
| 1649 |
WebSocketServer::kDefaultHandShakeTimeoutSecs, |
| 1650 |
(ipv6) ? AF_INET6 : AF_INET); |
| 1651 |
|
| 1652 |
server.setTLSOptions(tlsOptions); |
| 1653 |
|
| 1654 |
if (disablePerMessageDeflate) |
| 1655 |
{ |
| 1656 |
spdlog::info("Disable per message deflate"); |
| 1657 |
server.disablePerMessageDeflate(); |
| 1658 |
} |
| 1659 |
|
| 1660 |
if (disablePong) |
| 1661 |
{ |
| 1662 |
spdlog::info("Disable responding to PING messages with PONG"); |
| 1663 |
server.disablePong(); |
| 1664 |
} |
| 1665 |
|
| 1666 |
// push one million messages |
| 1667 |
std::atomic<bool> stop(false); |
| 1668 |
|
| 1669 |
server.setOnClientMessageCallback( |
| 1670 |
[&sendMsg, &stop](std::shared_ptr<ConnectionState> connectionState, |
| 1671 |
WebSocket& webSocket, |
| 1672 |
const WebSocketMessagePtr& msg) { |
| 1673 |
auto remoteIp = connectionState->getRemoteIp(); |
| 1674 |
if (msg->type == ix::WebSocketMessageType::Open) |
| 1675 |
{ |
| 1676 |
spdlog::info("New connection"); |
| 1677 |
spdlog::info("remote ip: {}", remoteIp); |
| 1678 |
spdlog::info("id: {}", connectionState->getId()); |
| 1679 |
spdlog::info("Uri: {}", msg->openInfo.uri); |
| 1680 |
spdlog::info("Headers:"); |
| 1681 |
for (auto it : msg->openInfo.headers) |
| 1682 |
{ |
| 1683 |
spdlog::info("{}: {}", it.first, it.second); |
| 1684 |
} |
| 1685 |
|
| 1686 |
// Parse the msg count from the uri. |
| 1687 |
int msgCount = -1; |
| 1688 |
std::stringstream ss; |
| 1689 |
auto uriSize = msg->openInfo.uri.size(); |
| 1690 |
ss << msg->openInfo.uri.substr(1, uriSize - 1); |
| 1691 |
ss >> msgCount; |
| 1692 |
|
| 1693 |
if (msgCount == -1) |
| 1694 |
{ |
| 1695 |
spdlog::info("Error parsing message count, closing connection"); |
| 1696 |
webSocket.close(); |
| 1697 |
} |
| 1698 |
else |
| 1699 |
{ |
| 1700 |
bool binary = false; |
| 1701 |
for (int i = 0; i < msgCount; ++i) |
| 1702 |
{ |
| 1703 |
auto sendInfo = webSocket.send(sendMsg, binary); |
| 1704 |
if (!sendInfo.success) |
| 1705 |
{ |
| 1706 |
spdlog::info("Error sending message, closing connection"); |
| 1707 |
webSocket.close(); |
| 1708 |
break; |
| 1709 |
} |
| 1710 |
} |
| 1711 |
} |
| 1712 |
} |
| 1713 |
else if (msg->type == ix::WebSocketMessageType::Close) |
| 1714 |
{ |
| 1715 |
spdlog::info("Closed connection: client id {} code {} reason {}", |
| 1716 |
connectionState->getId(), |
| 1717 |
msg->closeInfo.code, |
| 1718 |
msg->closeInfo.reason); |
| 1719 |
stop = true; |
| 1720 |
} |
| 1721 |
else if (msg->type == ix::WebSocketMessageType::Error) |
| 1722 |
{ |
| 1723 |
spdlog::error("Connection error: {}", msg->errorInfo.reason); |
| 1724 |
spdlog::error("#retries: {}", msg->errorInfo.retries); |
| 1725 |
spdlog::error("Wait time(ms): {}", msg->errorInfo.wait_time); |
| 1726 |
spdlog::error("HTTP Status: {}", msg->errorInfo.http_status); |
| 1727 |
} |
| 1728 |
else if (msg->type == ix::WebSocketMessageType::Message) |
| 1729 |
{ |
| 1730 |
spdlog::info("Received {} bytes", msg->wireSize); |
| 1731 |
webSocket.send(msg->str, msg->binary); |
| 1732 |
} |
| 1733 |
}); |
| 1734 |
|
| 1735 |
auto res = server.listen(); |
| 1736 |
if (!res.first) |
| 1737 |
{ |
| 1738 |
spdlog::error(res.second); |
| 1739 |
return 1; |
| 1740 |
} |
| 1741 |
|
| 1742 |
server.start(); |
| 1743 |
|
| 1744 |
while (!stop) |
| 1745 |
{ |
| 1746 |
auto duration = std::chrono::seconds(1); |
| 1747 |
std::this_thread::sleep_for(duration); |
| 1748 |
} |
| 1749 |
|
| 1750 |
server.stop(); |
| 1751 |
|
| 1752 |
return 0; |
| 1753 |
} |
| 1754 |
|
| 1755 |
class WebSocketReceiver |
| 1756 |
{ |
| 1757 |
public: |
| 1758 |
WebSocketReceiver(const std::string& _url, |
| 1759 |
bool enablePerMessageDeflate, |
| 1760 |
int delayMs, |
| 1761 |
const ix::SocketTLSOptions& tlsOptions); |
| 1762 |
|
| 1763 |
void subscribe(const std::string& channel); |
| 1764 |
void start(); |
| 1765 |
void stop(); |
| 1766 |
|
| 1767 |
void waitForConnection(); |
| 1768 |
void waitForMessage(); |
| 1769 |
void handleMessage(const std::string& str); |
| 1770 |
|
| 1771 |
private: |
| 1772 |
std::string _url; |
| 1773 |
std::string _id; |
| 1774 |
ix::WebSocket _webSocket; |
| 1775 |
bool _enablePerMessageDeflate; |
| 1776 |
int _delayMs; |
| 1777 |
int _receivedFragmentCounter; |
| 1778 |
|
| 1779 |
std::mutex _conditionVariableMutex; |
| 1780 |
std::condition_variable _condition; |
| 1781 |
|
| 1782 |
std::string extractFilename(const std::string& path); |
| 1783 |
void handleError(const std::string& errMsg, const std::string& id); |
| 1784 |
void log(const std::string& msg); |
| 1785 |
}; |
| 1786 |
|
| 1787 |
WebSocketReceiver::WebSocketReceiver(const std::string& url, |
| 1788 |
bool enablePerMessageDeflate, |
| 1789 |
int delayMs, |
| 1790 |
const ix::SocketTLSOptions& tlsOptions) |
| 1791 |
: _url(url) |
| 1792 |
, _enablePerMessageDeflate(enablePerMessageDeflate) |
| 1793 |
, _delayMs(delayMs) |
| 1794 |
, _receivedFragmentCounter(0) |
| 1795 |
{ |
| 1796 |
_webSocket.disableAutomaticReconnection(); |
| 1797 |
_webSocket.setTLSOptions(tlsOptions); |
| 1798 |
} |
| 1799 |
|
| 1800 |
void WebSocketReceiver::stop() |
| 1801 |
{ |
| 1802 |
_webSocket.stop(); |
| 1803 |
} |
| 1804 |
|
| 1805 |
void WebSocketReceiver::log(const std::string& msg) |
| 1806 |
{ |
| 1807 |
spdlog::info(msg); |
| 1808 |
} |
| 1809 |
|
| 1810 |
void WebSocketReceiver::waitForConnection() |
| 1811 |
{ |
| 1812 |
spdlog::info("{}: Connecting...", "ws_receive"); |
| 1813 |
|
| 1814 |
std::unique_lock<std::mutex> lock(_conditionVariableMutex); |
| 1815 |
_condition.wait(lock); |
| 1816 |
} |
| 1817 |
|
| 1818 |
void WebSocketReceiver::waitForMessage() |
| 1819 |
{ |
| 1820 |
spdlog::info("{}: Waiting for message...", "ws_receive"); |
| 1821 |
|
| 1822 |
std::unique_lock<std::mutex> lock(_conditionVariableMutex); |
| 1823 |
_condition.wait(lock); |
| 1824 |
} |
| 1825 |
|
| 1826 |
// We should cleanup the file name and full path further to remove .. as well |
| 1827 |
std::string WebSocketReceiver::extractFilename(const std::string& path) |
| 1828 |
{ |
| 1829 |
std::string::size_type idx; |
| 1830 |
|
| 1831 |
idx = path.rfind('/'); |
| 1832 |
if (idx != std::string::npos) |
| 1833 |
{ |
| 1834 |
std::string filename = path.substr(idx + 1); |
| 1835 |
return filename; |
| 1836 |
} |
| 1837 |
else |
| 1838 |
{ |
| 1839 |
return path; |
| 1840 |
} |
| 1841 |
} |
| 1842 |
|
| 1843 |
void WebSocketReceiver::handleError(const std::string& errMsg, const std::string& id) |
| 1844 |
{ |
| 1845 |
std::map<MsgPack, MsgPack> pdu; |
| 1846 |
pdu["kind"] = "error"; |
| 1847 |
pdu["id"] = id; |
| 1848 |
pdu["message"] = errMsg; |
| 1849 |
|
| 1850 |
MsgPack msg(pdu); |
| 1851 |
_webSocket.sendBinary(msg.dump()); |
| 1852 |
} |
| 1853 |
|
| 1854 |
void WebSocketReceiver::handleMessage(const std::string& str) |
| 1855 |
{ |
| 1856 |
spdlog::info("ws_receive: Received message: {}", str.size()); |
| 1857 |
|
| 1858 |
std::string errMsg; |
| 1859 |
MsgPack data = MsgPack::parse(str, errMsg); |
| 1860 |
if (!errMsg.empty()) |
| 1861 |
{ |
| 1862 |
handleError("ws_receive: Invalid MsgPack", std::string()); |
| 1863 |
return; |
| 1864 |
} |
| 1865 |
|
| 1866 |
spdlog::info("id: {}", data["id"].string_value()); |
| 1867 |
|
| 1868 |
std::vector<uint8_t> content = data["content"].binary_items(); |
| 1869 |
spdlog::info("ws_receive: Content size: {}", content.size()); |
| 1870 |
|
| 1871 |
// Validate checksum |
| 1872 |
uint64_t cksum = djb2Hash(content); |
| 1873 |
auto cksumRef = data["djb2_hash"].string_value(); |
| 1874 |
|
| 1875 |
spdlog::info("ws_receive: Computed hash: {}", cksum); |
| 1876 |
spdlog::info("ws_receive: Reference hash: {}", cksumRef); |
| 1877 |
|
| 1878 |
if (std::to_string(cksum) != cksumRef) |
| 1879 |
{ |
| 1880 |
handleError("Hash mismatch.", std::string()); |
| 1881 |
return; |
| 1882 |
} |
| 1883 |
|
| 1884 |
std::string filename = data["filename"].string_value(); |
| 1885 |
filename = extractFilename(filename); |
| 1886 |
|
| 1887 |
std::string filenameTmp = filename + ".tmp"; |
| 1888 |
|
| 1889 |
spdlog::info("ws_receive: Writing to disk: {}", filenameTmp); |
| 1890 |
std::ofstream out(filenameTmp); |
| 1891 |
std::string contentAsString(content.begin(), content.end()); |
| 1892 |
out << contentAsString; |
| 1893 |
out.close(); |
| 1894 |
|
| 1895 |
spdlog::info("ws_receive: Renaming {} to {}", filenameTmp, filename); |
| 1896 |
rename(filenameTmp.c_str(), filename.c_str()); |
| 1897 |
|
| 1898 |
std::map<MsgPack, MsgPack> pdu; |
| 1899 |
pdu["ack"] = true; |
| 1900 |
pdu["id"] = data["id"]; |
| 1901 |
pdu["filename"] = data["filename"]; |
| 1902 |
|
| 1903 |
spdlog::info("Sending ack to sender"); |
| 1904 |
MsgPack msg(pdu); |
| 1905 |
_webSocket.sendBinary(msg.dump()); |
| 1906 |
} |
| 1907 |
|
| 1908 |
void WebSocketReceiver::start() |
| 1909 |
{ |
| 1910 |
_webSocket.setUrl(_url); |
| 1911 |
ix::WebSocketPerMessageDeflateOptions webSocketPerMessageDeflateOptions( |
| 1912 |
_enablePerMessageDeflate, false, false, 15, 15); |
| 1913 |
_webSocket.setPerMessageDeflateOptions(webSocketPerMessageDeflateOptions); |
| 1914 |
|
| 1915 |
std::stringstream ss; |
| 1916 |
log(std::string("ws_receive: Connecting to url: ") + _url); |
| 1917 |
|
| 1918 |
_webSocket.setOnMessageCallback([this](const ix::WebSocketMessagePtr& msg) { |
| 1919 |
std::stringstream ss; |
| 1920 |
if (msg->type == ix::WebSocketMessageType::Open) |
| 1921 |
{ |
| 1922 |
_condition.notify_one(); |
| 1923 |
|
| 1924 |
log("ws_receive: connected"); |
| 1925 |
spdlog::info("Uri: {}", msg->openInfo.uri); |
| 1926 |
spdlog::info("Headers:"); |
| 1927 |
for (auto it : msg->openInfo.headers) |
| 1928 |
{ |
| 1929 |
spdlog::info("{}: {}", it.first, it.second); |
| 1930 |
} |
| 1931 |
} |
| 1932 |
else if (msg->type == ix::WebSocketMessageType::Close) |
| 1933 |
{ |
| 1934 |
ss << "ws_receive: connection closed:"; |
| 1935 |
ss << " code " << msg->closeInfo.code; |
| 1936 |
ss << " reason " << msg->closeInfo.reason << std::endl; |
| 1937 |
log(ss.str()); |
| 1938 |
} |
| 1939 |
else if (msg->type == ix::WebSocketMessageType::Message) |
| 1940 |
{ |
| 1941 |
ss << "ws_receive: transfered " << msg->wireSize << " bytes"; |
| 1942 |
log(ss.str()); |
| 1943 |
handleMessage(msg->str); |
| 1944 |
_condition.notify_one(); |
| 1945 |
} |
| 1946 |
else if (msg->type == ix::WebSocketMessageType::Fragment) |
| 1947 |
{ |
| 1948 |
ss << "ws_receive: received fragment " << _receivedFragmentCounter++; |
| 1949 |
log(ss.str()); |
| 1950 |
|
| 1951 |
if (_delayMs > 0) |
| 1952 |
{ |
| 1953 |
// Introduce an arbitrary delay, to simulate a slow connection |
| 1954 |
std::chrono::duration<double, std::milli> duration(_delayMs); |
| 1955 |
std::this_thread::sleep_for(duration); |
| 1956 |
} |
| 1957 |
} |
| 1958 |
else if (msg->type == ix::WebSocketMessageType::Error) |
| 1959 |
{ |
| 1960 |
ss << "ws_receive "; |
| 1961 |
ss << "Connection error: " << msg->errorInfo.reason << std::endl; |
| 1962 |
ss << "#retries: " << msg->errorInfo.retries << std::endl; |
| 1963 |
ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl; |
| 1964 |
ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl; |
| 1965 |
log(ss.str()); |
| 1966 |
} |
| 1967 |
else if (msg->type == ix::WebSocketMessageType::Ping) |
| 1968 |
{ |
| 1969 |
log("ws_receive: received ping"); |
| 1970 |
} |
| 1971 |
else if (msg->type == ix::WebSocketMessageType::Pong) |
| 1972 |
{ |
| 1973 |
log("ws_receive: received pong"); |
| 1974 |
} |
| 1975 |
else |
| 1976 |
{ |
| 1977 |
ss << "ws_receive: Invalid ix::WebSocketMessageType"; |
| 1978 |
log(ss.str()); |
| 1979 |
} |
| 1980 |
}); |
| 1981 |
|
| 1982 |
_webSocket.start(); |
| 1983 |
} |
| 1984 |
|
| 1985 |
void wsReceive(const std::string& url, |
| 1986 |
bool enablePerMessageDeflate, |
| 1987 |
int delayMs, |
| 1988 |
const ix::SocketTLSOptions& tlsOptions) |
| 1989 |
{ |
| 1990 |
WebSocketReceiver webSocketReceiver(url, enablePerMessageDeflate, delayMs, tlsOptions); |
| 1991 |
webSocketReceiver.start(); |
| 1992 |
|
| 1993 |
webSocketReceiver.waitForConnection(); |
| 1994 |
|
| 1995 |
webSocketReceiver.waitForMessage(); |
| 1996 |
|
| 1997 |
std::chrono::duration<double, std::milli> duration(1000); |
| 1998 |
std::this_thread::sleep_for(duration); |
| 1999 |
|
| 2000 |
spdlog::info("ws_receive: Done !"); |
| 2001 |
webSocketReceiver.stop(); |
| 2002 |
} |
| 2003 |
|
| 2004 |
int ws_receive_main(const std::string& url, |
| 2005 |
bool enablePerMessageDeflate, |
| 2006 |
int delayMs, |
| 2007 |
const ix::SocketTLSOptions& tlsOptions) |
| 2008 |
{ |
| 2009 |
wsReceive(url, enablePerMessageDeflate, delayMs, tlsOptions); |
| 2010 |
return 0; |
| 2011 |
} |
| 2012 |
|
| 2013 |
class WebSocketSender |
| 2014 |
{ |
| 2015 |
public: |
| 2016 |
WebSocketSender(const std::string& _url, |
| 2017 |
bool enablePerMessageDeflate, |
| 2018 |
const ix::SocketTLSOptions& tlsOptions); |
| 2019 |
|
| 2020 |
void subscribe(const std::string& channel); |
| 2021 |
void start(); |
| 2022 |
void stop(); |
| 2023 |
|
| 2024 |
void waitForConnection(); |
| 2025 |
void waitForAck(); |
| 2026 |
|
| 2027 |
bool sendMessage(const std::string& filename, bool throttle); |
| 2028 |
|
| 2029 |
private: |
| 2030 |
std::string _url; |
| 2031 |
std::string _id; |
| 2032 |
ix::WebSocket _webSocket; |
| 2033 |
bool _enablePerMessageDeflate; |
| 2034 |
|
| 2035 |
std::atomic<bool> _connected; |
| 2036 |
|
| 2037 |
std::mutex _conditionVariableMutex; |
| 2038 |
std::condition_variable _condition; |
| 2039 |
|
| 2040 |
void log(const std::string& msg); |
| 2041 |
}; |
| 2042 |
|
| 2043 |
WebSocketSender::WebSocketSender(const std::string& url, |
| 2044 |
bool enablePerMessageDeflate, |
| 2045 |
const ix::SocketTLSOptions& tlsOptions) |
| 2046 |
: _url(url) |
| 2047 |
, _enablePerMessageDeflate(enablePerMessageDeflate) |
| 2048 |
, _connected(false) |
| 2049 |
{ |
| 2050 |
_webSocket.disableAutomaticReconnection(); |
| 2051 |
_webSocket.setTLSOptions(tlsOptions); |
| 2052 |
} |
| 2053 |
|
| 2054 |
void WebSocketSender::stop() |
| 2055 |
{ |
| 2056 |
_webSocket.stop(); |
| 2057 |
} |
| 2058 |
|
| 2059 |
void WebSocketSender::log(const std::string& msg) |
| 2060 |
{ |
| 2061 |
spdlog::info(msg); |
| 2062 |
} |
| 2063 |
|
| 2064 |
void WebSocketSender::waitForConnection() |
| 2065 |
{ |
| 2066 |
spdlog::info("{}: Connecting...", "ws_send"); |
| 2067 |
|
| 2068 |
std::unique_lock<std::mutex> lock(_conditionVariableMutex); |
| 2069 |
_condition.wait(lock); |
| 2070 |
} |
| 2071 |
|
| 2072 |
void WebSocketSender::waitForAck() |
| 2073 |
{ |
| 2074 |
spdlog::info("{}: Waiting for ack...", "ws_send"); |
| 2075 |
|
| 2076 |
std::unique_lock<std::mutex> lock(_conditionVariableMutex); |
| 2077 |
_condition.wait(lock); |
| 2078 |
} |
| 2079 |
|
| 2080 |
void WebSocketSender::start() |
| 2081 |
{ |
| 2082 |
_webSocket.setUrl(_url); |
| 2083 |
|
| 2084 |
ix::WebSocketPerMessageDeflateOptions webSocketPerMessageDeflateOptions( |
| 2085 |
_enablePerMessageDeflate, false, false, 15, 15); |
| 2086 |
_webSocket.setPerMessageDeflateOptions(webSocketPerMessageDeflateOptions); |
| 2087 |
|
| 2088 |
std::stringstream ss; |
| 2089 |
log(std::string("ws_send: Connecting to url: ") + _url); |
| 2090 |
|
| 2091 |
_webSocket.setOnMessageCallback([this](const WebSocketMessagePtr& msg) { |
| 2092 |
std::stringstream ss; |
| 2093 |
if (msg->type == ix::WebSocketMessageType::Open) |
| 2094 |
{ |
| 2095 |
_connected = true; |
| 2096 |
|
| 2097 |
_condition.notify_one(); |
| 2098 |
|
| 2099 |
log("ws_send: connected"); |
| 2100 |
spdlog::info("Uri: {}", msg->openInfo.uri); |
| 2101 |
spdlog::info("Headers:"); |
| 2102 |
for (auto it : msg->openInfo.headers) |
| 2103 |
{ |
| 2104 |
spdlog::info("{}: {}", it.first, it.second); |
| 2105 |
} |
| 2106 |
} |
| 2107 |
else if (msg->type == ix::WebSocketMessageType::Close) |
| 2108 |
{ |
| 2109 |
_connected = false; |
| 2110 |
|
| 2111 |
ss << "ws_send: connection closed:"; |
| 2112 |
ss << " code " << msg->closeInfo.code; |
| 2113 |
ss << " reason " << msg->closeInfo.reason << std::endl; |
| 2114 |
log(ss.str()); |
| 2115 |
} |
| 2116 |
else if (msg->type == ix::WebSocketMessageType::Message) |
| 2117 |
{ |
| 2118 |
_condition.notify_one(); |
| 2119 |
|
| 2120 |
ss << "ws_send: received message (" << msg->wireSize << " bytes)"; |
| 2121 |
log(ss.str()); |
| 2122 |
|
| 2123 |
std::string errMsg; |
| 2124 |
MsgPack data = MsgPack::parse(msg->str, errMsg); |
| 2125 |
if (!errMsg.empty()) |
| 2126 |
{ |
| 2127 |
spdlog::info("Invalid MsgPack response"); |
| 2128 |
return; |
| 2129 |
} |
| 2130 |
|
| 2131 |
std::string id = data["id"].string_value(); |
| 2132 |
if (_id != id) |
| 2133 |
{ |
| 2134 |
spdlog::info("Invalid id"); |
| 2135 |
} |
| 2136 |
} |
| 2137 |
else if (msg->type == ix::WebSocketMessageType::Error) |
| 2138 |
{ |
| 2139 |
ss << "ws_send "; |
| 2140 |
ss << "Connection error: " << msg->errorInfo.reason << std::endl; |
| 2141 |
ss << "#retries: " << msg->errorInfo.retries << std::endl; |
| 2142 |
ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl; |
| 2143 |
ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl; |
| 2144 |
log(ss.str()); |
| 2145 |
} |
| 2146 |
else if (msg->type == ix::WebSocketMessageType::Ping) |
| 2147 |
{ |
| 2148 |
spdlog::info("ws_send: received ping"); |
| 2149 |
} |
| 2150 |
else if (msg->type == ix::WebSocketMessageType::Pong) |
| 2151 |
{ |
| 2152 |
spdlog::info("ws_send: received pong"); |
| 2153 |
} |
| 2154 |
else if (msg->type == ix::WebSocketMessageType::Fragment) |
| 2155 |
{ |
| 2156 |
spdlog::info("ws_send: received fragment"); |
| 2157 |
} |
| 2158 |
else |
| 2159 |
{ |
| 2160 |
ss << "ws_send: Invalid ix::WebSocketMessageType"; |
| 2161 |
log(ss.str()); |
| 2162 |
} |
| 2163 |
}); |
| 2164 |
|
| 2165 |
_webSocket.start(); |
| 2166 |
} |
| 2167 |
|
| 2168 |
bool WebSocketSender::sendMessage(const std::string& filename, bool throttle) |
| 2169 |
{ |
| 2170 |
std::vector<uint8_t> content; |
| 2171 |
{ |
| 2172 |
Bench bench("ws_send: load file from disk"); |
| 2173 |
auto res = load(filename); |
| 2174 |
content = res.second; |
| 2175 |
} |
| 2176 |
|
| 2177 |
_id = uuid4(); |
| 2178 |
|
| 2179 |
std::map<MsgPack, MsgPack> pdu; |
| 2180 |
pdu["kind"] = "send"; |
| 2181 |
pdu["id"] = _id; |
| 2182 |
pdu["content"] = content; |
| 2183 |
auto hash = djb2Hash(content); |
| 2184 |
pdu["djb2_hash"] = std::to_string(hash); |
| 2185 |
pdu["filename"] = filename; |
| 2186 |
|
| 2187 |
MsgPack msg(pdu); |
| 2188 |
|
| 2189 |
auto serializedMsg = msg.dump(); |
| 2190 |
spdlog::info("ws_send: sending {} bytes", serializedMsg.size()); |
| 2191 |
|
| 2192 |
Bench bench("ws_send: Sending file through websocket"); |
| 2193 |
auto result = |
| 2194 |
_webSocket.sendBinary(serializedMsg, [this, throttle](int current, int total) -> bool { |
| 2195 |
spdlog::info("ws_send: Step {} out of {}", current + 1, total); |
| 2196 |
|
| 2197 |
if (throttle) |
| 2198 |
{ |
| 2199 |
std::chrono::duration<double, std::milli> duration(10); |
| 2200 |
std::this_thread::sleep_for(duration); |
| 2201 |
} |
| 2202 |
|
| 2203 |
return _connected; |
| 2204 |
}); |
| 2205 |
|
| 2206 |
if (!result.success) |
| 2207 |
{ |
| 2208 |
spdlog::error("ws_send: Error sending file."); |
| 2209 |
return false; |
| 2210 |
} |
| 2211 |
|
| 2212 |
if (!_connected) |
| 2213 |
{ |
| 2214 |
spdlog::error("ws_send: Got disconnected from the server"); |
| 2215 |
return false; |
| 2216 |
} |
| 2217 |
|
| 2218 |
spdlog::info("ws_send: sent {} bytes", serializedMsg.size()); |
| 2219 |
|
| 2220 |
do |
| 2221 |
{ |
| 2222 |
size_t bufferedAmount = _webSocket.bufferedAmount(); |
| 2223 |
spdlog::info("ws_send: {} bytes left to be sent", bufferedAmount); |
| 2224 |
|
| 2225 |
std::chrono::duration<double, std::milli> duration(500); |
| 2226 |
std::this_thread::sleep_for(duration); |
| 2227 |
} while (_webSocket.bufferedAmount() != 0 && _connected); |
| 2228 |
|
| 2229 |
if (_connected) |
| 2230 |
{ |
| 2231 |
bench.report(); |
| 2232 |
auto duration = bench.getDuration(); |
| 2233 |
auto transferRate = 1000 * content.size() / duration; |
| 2234 |
transferRate /= (1024 * 1024); |
| 2235 |
spdlog::info("ws_send: Send transfer rate: {} MB/s", transferRate); |
| 2236 |
} |
| 2237 |
else |
| 2238 |
{ |
| 2239 |
spdlog::error("ws_send: Got disconnected from the server"); |
| 2240 |
} |
| 2241 |
|
| 2242 |
return _connected; |
| 2243 |
} |
| 2244 |
|
| 2245 |
void wsSend(const std::string& url, |
| 2246 |
const std::string& path, |
| 2247 |
bool enablePerMessageDeflate, |
| 2248 |
bool throttle, |
| 2249 |
const ix::SocketTLSOptions& tlsOptions) |
| 2250 |
{ |
| 2251 |
WebSocketSender webSocketSender(url, enablePerMessageDeflate, tlsOptions); |
| 2252 |
webSocketSender.start(); |
| 2253 |
|
| 2254 |
webSocketSender.waitForConnection(); |
| 2255 |
|
| 2256 |
spdlog::info("ws_send: Sending..."); |
| 2257 |
if (webSocketSender.sendMessage(path, throttle)) |
| 2258 |
{ |
| 2259 |
webSocketSender.waitForAck(); |
| 2260 |
spdlog::info("ws_send: Done !"); |
| 2261 |
} |
| 2262 |
else |
| 2263 |
{ |
| 2264 |
spdlog::error("ws_send: Error sending file."); |
| 2265 |
} |
| 2266 |
|
| 2267 |
webSocketSender.stop(); |
| 2268 |
} |
| 2269 |
|
| 2270 |
int ws_send_main(const std::string& url, |
| 2271 |
const std::string& path, |
| 2272 |
bool disablePerMessageDeflate, |
| 2273 |
const ix::SocketTLSOptions& tlsOptions) |
| 2274 |
{ |
| 2275 |
bool throttle = false; |
| 2276 |
bool enablePerMessageDeflate = !disablePerMessageDeflate; |
| 2277 |
|
| 2278 |
wsSend(url, path, enablePerMessageDeflate, throttle, tlsOptions); |
| 2279 |
return 0; |
| 2280 |
} |
| 2281 |
|
| 2282 |
int ws_transfer_main(int port, |
| 2283 |
const std::string& hostname, |
| 2284 |
const ix::SocketTLSOptions& tlsOptions) |
| 2285 |
{ |
| 2286 |
spdlog::info("Listening on {}:{}", hostname, port); |
| 2287 |
|
| 2288 |
ix::WebSocketServer server(port, hostname); |
| 2289 |
server.setTLSOptions(tlsOptions); |
| 2290 |
|
| 2291 |
server.setOnClientMessageCallback( |
| 2292 |
[&server](std::shared_ptr<ConnectionState> connectionState, |
| 2293 |
WebSocket& webSocket, |
| 2294 |
const WebSocketMessagePtr& msg) { |
| 2295 |
auto remoteIp = connectionState->getRemoteIp(); |
| 2296 |
if (msg->type == ix::WebSocketMessageType::Open) |
| 2297 |
{ |
| 2298 |
spdlog::info("ws_transfer: New connection"); |
| 2299 |
spdlog::info("remote ip: {}", remoteIp); |
| 2300 |
spdlog::info("id: {}", connectionState->getId()); |
| 2301 |
spdlog::info("Uri: {}", msg->openInfo.uri); |
| 2302 |
spdlog::info("Headers:"); |
| 2303 |
for (auto it : msg->openInfo.headers) |
| 2304 |
{ |
| 2305 |
spdlog::info("{}: {}", it.first, it.second); |
| 2306 |
} |
| 2307 |
} |
| 2308 |
else if (msg->type == ix::WebSocketMessageType::Close) |
| 2309 |
{ |
| 2310 |
spdlog::info("ws_transfer: Closed connection: client id {} code {} reason {}", |
| 2311 |
connectionState->getId(), |
| 2312 |
msg->closeInfo.code, |
| 2313 |
msg->closeInfo.reason); |
| 2314 |
auto remaining = server.getClients().size() - 1; |
| 2315 |
spdlog::info("ws_transfer: {} remaining clients", remaining); |
| 2316 |
} |
| 2317 |
else if (msg->type == ix::WebSocketMessageType::Error) |
| 2318 |
{ |
| 2319 |
std::stringstream ss; |
| 2320 |
ss << "ws_transfer: Connection error: " << msg->errorInfo.reason << std::endl; |
| 2321 |
ss << "#retries: " << msg->errorInfo.retries << std::endl; |
| 2322 |
ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl; |
| 2323 |
ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl; |
| 2324 |
spdlog::info(ss.str()); |
| 2325 |
} |
| 2326 |
else if (msg->type == ix::WebSocketMessageType::Fragment) |
| 2327 |
{ |
| 2328 |
spdlog::info("ws_transfer: Received message fragment "); |
| 2329 |
} |
| 2330 |
else if (msg->type == ix::WebSocketMessageType::Message) |
| 2331 |
{ |
| 2332 |
spdlog::info("ws_transfer: Received {} bytes", msg->wireSize); |
| 2333 |
size_t receivers = 0; |
| 2334 |
for (auto&& client : server.getClients()) |
| 2335 |
{ |
| 2336 |
if (client.get() != &webSocket) |
| 2337 |
{ |
| 2338 |
auto readyState = client->getReadyState(); |
| 2339 |
auto id = connectionState->getId(); |
| 2340 |
|
| 2341 |
if (readyState == ReadyState::Open) |
| 2342 |
{ |
| 2343 |
++receivers; |
| 2344 |
client->send( |
| 2345 |
msg->str, msg->binary, [&id](int current, int total) -> bool { |
| 2346 |
spdlog::info("{}: [client {}]: Step {} out of {}", |
| 2347 |
"ws_transfer", |
| 2348 |
id, |
| 2349 |
current, |
| 2350 |
total); |
| 2351 |
return true; |
| 2352 |
}); |
| 2353 |
do |
| 2354 |
{ |
| 2355 |
size_t bufferedAmount = client->bufferedAmount(); |
| 2356 |
|
| 2357 |
spdlog::info("{}: [client {}]: {} bytes left to send", |
| 2358 |
"ws_transfer", |
| 2359 |
id, |
| 2360 |
bufferedAmount); |
| 2361 |
|
| 2362 |
std::this_thread::sleep_for(std::chrono::milliseconds(500)); |
| 2363 |
|
| 2364 |
} while (client->bufferedAmount() != 0 && |
| 2365 |
client->getReadyState() == ReadyState::Open); |
| 2366 |
} |
| 2367 |
else |
| 2368 |
{ |
| 2369 |
std::string readyStateString = |
| 2370 |
readyState == ReadyState::Connecting ? "Connecting" |
| 2371 |
: readyState == ReadyState::Closing ? "Closing" |
| 2372 |
: "Closed"; |
| 2373 |
size_t bufferedAmount = client->bufferedAmount(); |
| 2374 |
|
| 2375 |
spdlog::info( |
| 2376 |
"{}: [client {}]: has readystate {} bytes left to be sent {}", |
| 2377 |
"ws_transfer", |
| 2378 |
id, |
| 2379 |
readyStateString, |
| 2380 |
bufferedAmount); |
| 2381 |
} |
| 2382 |
} |
| 2383 |
} |
| 2384 |
if (!receivers) |
| 2385 |
{ |
| 2386 |
spdlog::info("ws_transfer: no remaining receivers"); |
| 2387 |
} |
| 2388 |
} |
| 2389 |
}); |
| 2390 |
|
| 2391 |
auto res = server.listen(); |
| 2392 |
if (!res.first) |
| 2393 |
{ |
| 2394 |
spdlog::info(res.second); |
| 2395 |
return 1; |
| 2396 |
} |
| 2397 |
|
| 2398 |
server.start(); |
| 2399 |
server.wait(); |
| 2400 |
|
| 2401 |
return 0; |
| 2402 |
} |
| 2403 |
} // namespace ix |
| 2404 |
|
| 2405 |
int main(int argc, char** argv) |
| 2406 |
{ |
| 2407 |
ix::setThreadName("ws main thread"); |
| 2408 |
ix::initNetSystem(); |
| 2409 |
|
| 2410 |
spdlog::set_level(spdlog::level::debug); |
| 2411 |
|
| 2412 |
#ifndef _WIN32 |
| 2413 |
signal(SIGPIPE, SIG_IGN); |
| 2414 |
#endif |
| 2415 |
|
| 2416 |
// Display command. |
| 2417 |
if (getenv("DEBUG")) |
| 2418 |
{ |
| 2419 |
std::stringstream ss; |
| 2420 |
ss << "Command: "; |
| 2421 |
for (int i = 0; i < argc; ++i) |
| 2422 |
{ |
| 2423 |
ss << argv[i] << " "; |
| 2424 |
} |
| 2425 |
spdlog::info(ss.str()); |
| 2426 |
} |
| 2427 |
|
| 2428 |
CLI::App app {"ws is a websocket tool"}; |
| 2429 |
|
| 2430 |
std::string url("ws://127.0.0.1:8008"); |
| 2431 |
std::string path; |
| 2432 |
std::string user; |
| 2433 |
std::string data; |
| 2434 |
std::string formData; |
| 2435 |
std::string binaryData; |
| 2436 |
std::string headers; |
| 2437 |
std::string output; |
| 2438 |
std::string hostname("127.0.0.1"); |
| 2439 |
std::string pidfile; |
| 2440 |
std::string channel; |
| 2441 |
std::string filter; |
| 2442 |
std::string position; |
| 2443 |
std::string message; |
| 2444 |
std::string timer; |
| 2445 |
std::string configPath; |
| 2446 |
std::string subprotocol; |
| 2447 |
std::string remoteHost; |
| 2448 |
std::string logfile; |
| 2449 |
std::string moduleName; |
| 2450 |
std::string republishChannel; |
| 2451 |
std::string publisherRolename; |
| 2452 |
std::string publisherRolesecret; |
| 2453 |
std::string sendMsg("hello world"); |
| 2454 |
std::string filename; |
| 2455 |
std::string httpHeaderAuthorization; |
| 2456 |
ix::SocketTLSOptions tlsOptions; |
| 2457 |
std::string ciphers; |
| 2458 |
std::string redirectUrl; |
| 2459 |
bool headersOnly = false; |
| 2460 |
bool followRedirects = false; |
| 2461 |
bool verbose = false; |
| 2462 |
bool save = false; |
| 2463 |
bool quiet = false; |
| 2464 |
bool compress = false; |
| 2465 |
bool compressRequest = false; |
| 2466 |
bool disableAutomaticReconnection = false; |
| 2467 |
bool disablePerMessageDeflate = false; |
| 2468 |
bool greetings = false; |
| 2469 |
bool ipv6 = false; |
| 2470 |
bool binaryMode = false; |
| 2471 |
bool redirect = false; |
| 2472 |
bool version = false; |
| 2473 |
bool verifyNone = false; |
| 2474 |
bool disablePong = false; |
| 2475 |
bool debug = false; |
| 2476 |
int port = 8008; |
| 2477 |
int connectTimeOut = 60; |
| 2478 |
int transferTimeout = 1800; |
| 2479 |
int maxRedirects = 5; |
| 2480 |
int delayMs = -1; |
| 2481 |
int msgCount = 1000 * 1000; |
| 2482 |
uint32_t maxWaitBetweenReconnectionRetries = 10 * 1000; // 10 seconds |
| 2483 |
int pingIntervalSecs = 30; |
| 2484 |
int runCount = 1; |
| 2485 |
bool decompressGzipMessages = false; |
| 2486 |
|
| 2487 |
auto addGenericOptions = [&pidfile](CLI::App* app) { |
| 2488 |
app->add_option("--pidfile", pidfile, "Pid file"); |
| 2489 |
}; |
| 2490 |
|
| 2491 |
auto addTLSOptions = [&tlsOptions, &verifyNone](CLI::App* app) { |
| 2492 |
app->add_option( |
| 2493 |
"--cert-file", tlsOptions.certFile, "Path to the (PEM format) TLS cert file") |
| 2494 |
->check(CLI::ExistingPath); |
| 2495 |
app->add_option("--key-file", tlsOptions.keyFile, "Path to the (PEM format) TLS key file") |
| 2496 |
->check(CLI::ExistingPath); |
| 2497 |
app->add_option("--ca-file", tlsOptions.caFile, "Path to the (PEM format) ca roots file") |
| 2498 |
->check(CLI::ExistingPath); |
| 2499 |
app->add_option("--ciphers", |
| 2500 |
tlsOptions.ciphers, |
| 2501 |
"A (comma/space/colon) separated list of ciphers to use for TLS"); |
| 2502 |
app->add_flag("--tls", tlsOptions.tls, "Enable TLS (server only)"); |
| 2503 |
app->add_flag("--verify_none", verifyNone, "Disable peer cert verification"); |
| 2504 |
app->add_flag("--disable-hostname-validation", tlsOptions.disable_hostname_validation, "Disable validation of certificates' hostnames"); |
| 2505 |
}; |
| 2506 |
|
| 2507 |
app.add_flag("--version", version, "Print ws version"); |
| 2508 |
app.add_option("--logfile", logfile, "path where all logs will be redirected"); |
| 2509 |
|
| 2510 |
CLI::App* sendApp = app.add_subcommand("send", "Send a file"); |
| 2511 |
sendApp->fallthrough(); |
| 2512 |
sendApp->add_option("url", url, "Connection url")->required(); |
| 2513 |
sendApp->add_option("path", path, "Path to the file to send") |
| 2514 |
->required() |
| 2515 |
->check(CLI::ExistingPath); |
| 2516 |
sendApp->add_flag("-x", disablePerMessageDeflate, "Disable per message deflate"); |
| 2517 |
addGenericOptions(sendApp); |
| 2518 |
addTLSOptions(sendApp); |
| 2519 |
|
| 2520 |
CLI::App* receiveApp = app.add_subcommand("receive", "Receive a file"); |
| 2521 |
receiveApp->fallthrough(); |
| 2522 |
receiveApp->add_option("url", url, "Connection url")->required(); |
| 2523 |
receiveApp->add_option("--delay", |
| 2524 |
delayMs, |
| 2525 |
"Delay (ms) to wait after receiving a fragment" |
| 2526 |
" to artificially slow down the receiver"); |
| 2527 |
receiveApp->add_option("--pidfile", pidfile, "Pid file"); |
| 2528 |
addTLSOptions(receiveApp); |
| 2529 |
|
| 2530 |
CLI::App* transferApp = app.add_subcommand("transfer", "Broadcasting server"); |
| 2531 |
transferApp->fallthrough(); |
| 2532 |
transferApp->add_option("--port", port, "Connection url"); |
| 2533 |
transferApp->add_option("--host", hostname, "Hostname"); |
| 2534 |
transferApp->add_option("--pidfile", pidfile, "Pid file"); |
| 2535 |
addTLSOptions(transferApp); |
| 2536 |
|
| 2537 |
CLI::App* connectApp = app.add_subcommand("connect", "Connect to a remote server"); |
| 2538 |
connectApp->fallthrough(); |
| 2539 |
connectApp->add_option("url", url, "Connection url")->required(); |
| 2540 |
connectApp->add_option("-H", headers, "Header")->join(); |
| 2541 |
connectApp->add_flag("-d", disableAutomaticReconnection, "Disable Automatic Reconnection"); |
| 2542 |
connectApp->add_flag("-x", disablePerMessageDeflate, "Disable per message deflate"); |
| 2543 |
connectApp->add_flag("-b", binaryMode, "Send in binary mode"); |
| 2544 |
connectApp->add_option("--max_wait", |
| 2545 |
maxWaitBetweenReconnectionRetries, |
| 2546 |
"Max Wait Time between reconnection retries"); |
| 2547 |
connectApp->add_option("--ping_interval", pingIntervalSecs, "Interval between sending pings"); |
| 2548 |
connectApp->add_option("--subprotocol", subprotocol, "Subprotocol"); |
| 2549 |
connectApp->add_flag("-g", decompressGzipMessages, "Decompress gziped messages"); |
| 2550 |
addGenericOptions(connectApp); |
| 2551 |
addTLSOptions(connectApp); |
| 2552 |
|
| 2553 |
CLI::App* echoClientApp = app.add_subcommand("autoroute", "Test websocket client performance"); |
| 2554 |
echoClientApp->fallthrough(); |
| 2555 |
echoClientApp->add_option("url", url, "Connection url")->required(); |
| 2556 |
echoClientApp->add_flag("-x", disablePerMessageDeflate, "Disable per message deflate"); |
| 2557 |
echoClientApp->add_option( |
| 2558 |
"--ping_interval", pingIntervalSecs, "Interval between sending pings"); |
| 2559 |
echoClientApp->add_option("--subprotocol", subprotocol, "Subprotocol"); |
| 2560 |
echoClientApp->add_option("--msg_count", msgCount, "Total message count to be sent"); |
| 2561 |
addTLSOptions(echoClientApp); |
| 2562 |
|
| 2563 |
CLI::App* chatApp = app.add_subcommand("chat", "Group chat"); |
| 2564 |
chatApp->fallthrough(); |
| 2565 |
chatApp->add_option("url", url, "Connection url")->required(); |
| 2566 |
chatApp->add_option("user", user, "User name")->required(); |
| 2567 |
|
| 2568 |
CLI::App* echoServerApp = app.add_subcommand("echo_server", "Echo server"); |
| 2569 |
echoServerApp->fallthrough(); |
| 2570 |
echoServerApp->add_option("--port", port, "Port"); |
| 2571 |
echoServerApp->add_option("--host", hostname, "Hostname"); |
| 2572 |
echoServerApp->add_option("--http_authorization_header", httpHeaderAuthorization, "Hostname"); |
| 2573 |
echoServerApp->add_flag("-q", quiet, "Quiet / only display warnings and errors"); |
| 2574 |
echoServerApp->add_flag("-g", greetings, "Greet"); |
| 2575 |
echoServerApp->add_flag("-6", ipv6, "IpV6"); |
| 2576 |
echoServerApp->add_flag("-x", disablePerMessageDeflate, "Disable per message deflate"); |
| 2577 |
echoServerApp->add_flag("-p", disablePong, "Disable sending PONG in response to PING"); |
| 2578 |
addGenericOptions(echoServerApp); |
| 2579 |
addTLSOptions(echoServerApp); |
| 2580 |
|
| 2581 |
CLI::App* pushServerApp = app.add_subcommand("push_server", "Push server"); |
| 2582 |
pushServerApp->fallthrough(); |
| 2583 |
pushServerApp->add_option("--port", port, "Port"); |
| 2584 |
pushServerApp->add_option("--host", hostname, "Hostname"); |
| 2585 |
pushServerApp->add_flag("-q", quiet, "Quiet / only display warnings and errors"); |
| 2586 |
pushServerApp->add_flag("-6", ipv6, "IpV6"); |
| 2587 |
pushServerApp->add_flag("-x", disablePerMessageDeflate, "Disable per message deflate"); |
| 2588 |
pushServerApp->add_flag("-p", disablePong, "Disable sending PONG in response to PING"); |
| 2589 |
pushServerApp->add_option("--send_msg", sendMsg, "Send message"); |
| 2590 |
addTLSOptions(pushServerApp); |
| 2591 |
|
| 2592 |
CLI::App* broadcastServerApp = app.add_subcommand("broadcast_server", "Broadcasting server"); |
| 2593 |
broadcastServerApp->fallthrough(); |
| 2594 |
broadcastServerApp->add_option("--port", port, "Port"); |
| 2595 |
broadcastServerApp->add_option("--host", hostname, "Hostname"); |
| 2596 |
addTLSOptions(broadcastServerApp); |
| 2597 |
|
| 2598 |
CLI::App* pingPongApp = app.add_subcommand("ping", "Ping pong"); |
| 2599 |
pingPongApp->fallthrough(); |
| 2600 |
pingPongApp->add_option("url", url, "Connection url")->required(); |
| 2601 |
addTLSOptions(pingPongApp); |
| 2602 |
|
| 2603 |
CLI::App* httpClientApp = app.add_subcommand("curl", "HTTP Client"); |
| 2604 |
httpClientApp->fallthrough(); |
| 2605 |
httpClientApp->add_option("url", url, "Connection url")->required(); |
| 2606 |
httpClientApp->add_option("-d", data, "Form data")->join(); |
| 2607 |
httpClientApp->add_option("-F", formData, "Form data")->join(); |
| 2608 |
httpClientApp->add_option("--data-binary", binaryData, "Body binary data")->join(); |
| 2609 |
httpClientApp->add_option("-H", headers, "Header")->join(); |
| 2610 |
httpClientApp->add_option("--output", output, "Output file"); |
| 2611 |
httpClientApp->add_flag("-I", headersOnly, "Send a HEAD request"); |
| 2612 |
httpClientApp->add_flag("-L", followRedirects, "Follow redirects"); |
| 2613 |
httpClientApp->add_option("--max-redirects", maxRedirects, "Max Redirects"); |
| 2614 |
httpClientApp->add_flag("-v", verbose, "Verbose"); |
| 2615 |
httpClientApp->add_flag("-O", save, "Save output to disk"); |
| 2616 |
httpClientApp->add_flag("--compressed", compress, "Enable gzip compression"); |
| 2617 |
httpClientApp->add_flag("--compress_request", compressRequest, "Compress request with gzip"); |
| 2618 |
httpClientApp->add_option("--connect-timeout", connectTimeOut, "Connection timeout"); |
| 2619 |
httpClientApp->add_option("--transfer-timeout", transferTimeout, "Transfer timeout"); |
| 2620 |
addTLSOptions(httpClientApp); |
| 2621 |
|
| 2622 |
CLI::App* httpServerApp = app.add_subcommand("httpd", "HTTP server"); |
| 2623 |
httpServerApp->fallthrough(); |
| 2624 |
httpServerApp->add_option("--port", port, "Port"); |
| 2625 |
httpServerApp->add_option("--host", hostname, "Hostname"); |
| 2626 |
httpServerApp->add_flag("-L", redirect, "Redirect all request to redirect_url"); |
| 2627 |
httpServerApp->add_option("--redirect_url", redirectUrl, "Url to redirect to"); |
| 2628 |
httpServerApp->add_flag("-D", debug, "Debug server"); |
| 2629 |
addTLSOptions(httpServerApp); |
| 2630 |
|
| 2631 |
CLI::App* autobahnApp = app.add_subcommand("autobahn", "Test client Autobahn compliance"); |
| 2632 |
autobahnApp->fallthrough(); |
| 2633 |
autobahnApp->add_option("--url", url, "url"); |
| 2634 |
autobahnApp->add_flag("-q", quiet, "Quiet"); |
| 2635 |
|
| 2636 |
CLI::App* proxyServerApp = app.add_subcommand("proxy_server", "Proxy server"); |
| 2637 |
proxyServerApp->fallthrough(); |
| 2638 |
proxyServerApp->add_option("--port", port, "Port"); |
| 2639 |
proxyServerApp->add_option("--host", hostname, "Hostname"); |
| 2640 |
proxyServerApp->add_option("--remote_host", remoteHost, "Remote Hostname"); |
| 2641 |
proxyServerApp->add_flag("-v", verbose, "Verbose"); |
| 2642 |
proxyServerApp->add_option("--config_path", configPath, "Path to config data") |
| 2643 |
->check(CLI::ExistingPath); |
| 2644 |
addGenericOptions(proxyServerApp); |
| 2645 |
addTLSOptions(proxyServerApp); |
| 2646 |
|
| 2647 |
CLI::App* dnsLookupApp = app.add_subcommand("dnslookup", "DNS lookup"); |
| 2648 |
dnsLookupApp->fallthrough(); |
| 2649 |
dnsLookupApp->add_option("host", hostname, "Hostname")->required(); |
| 2650 |
|
| 2651 |
CLI::App* gzipApp = app.add_subcommand("gzip", "Gzip compressor"); |
| 2652 |
gzipApp->fallthrough(); |
| 2653 |
gzipApp->add_option("filename", filename, "Filename")->required(); |
| 2654 |
gzipApp->add_option("--run_count", runCount, "Number of time to run the compression"); |
| 2655 |
|
| 2656 |
CLI::App* gunzipApp = app.add_subcommand("gunzip", "Gzip decompressor"); |
| 2657 |
gunzipApp->fallthrough(); |
| 2658 |
gunzipApp->add_option("filename", filename, "Filename")->required(); |
| 2659 |
|
| 2660 |
CLI11_PARSE(app, argc, argv); |
| 2661 |
|
| 2662 |
// pid file handling |
| 2663 |
if (!pidfile.empty()) |
| 2664 |
{ |
| 2665 |
unlink(pidfile.c_str()); |
| 2666 |
|
| 2667 |
std::ofstream f; |
| 2668 |
f.open(pidfile); |
| 2669 |
f << getpid(); |
| 2670 |
f.close(); |
| 2671 |
} |
| 2672 |
|
| 2673 |
if (verifyNone) |
| 2674 |
{ |
| 2675 |
tlsOptions.caFile = "NONE"; |
| 2676 |
} |
| 2677 |
|
| 2678 |
if (tlsOptions.isUsingSystemDefaults()) |
| 2679 |
{ |
| 2680 |
#if defined(__APPLE__) |
| 2681 |
#if defined(IXWEBSOCKET_USE_MBED_TLS) || defined(IXWEBSOCKET_USE_OPEN_SSL) |
| 2682 |
// We could try to load some system certs as well, but this is easy enough |
| 2683 |
tlsOptions.caFile = "/etc/ssl/cert.pem"; |
| 2684 |
#endif |
| 2685 |
#elif defined(__linux__) |
| 2686 |
#if defined(IXWEBSOCKET_USE_MBED_TLS) |
| 2687 |
std::vector<std::string> caFiles = { |
| 2688 |
"/etc/ssl/certs/ca-bundle.crt", // CentOS |
| 2689 |
"/etc/ssl/certs/ca-certificates.crt", // Alpine |
| 2690 |
}; |
| 2691 |
|
| 2692 |
for (auto&& caFile : caFiles) |
| 2693 |
{ |
| 2694 |
if (fileExists(caFile)) |
| 2695 |
{ |
| 2696 |
tlsOptions.caFile = caFile; |
| 2697 |
break; |
| 2698 |
} |
| 2699 |
} |
| 2700 |
#endif |
| 2701 |
#endif |
| 2702 |
} |
| 2703 |
|
| 2704 |
if (!logfile.empty()) |
| 2705 |
{ |
| 2706 |
try |
| 2707 |
{ |
| 2708 |
auto fileLogger = spdlog::basic_logger_mt("ws", logfile); |
| 2709 |
spdlog::set_default_logger(fileLogger); |
| 2710 |
spdlog::flush_every(std::chrono::seconds(1)); |
| 2711 |
|
| 2712 |
std::cerr << "All logs will be redirected to " << logfile << std::endl; |
| 2713 |
} |
| 2714 |
catch (const spdlog::spdlog_ex& ex) |
| 2715 |
{ |
| 2716 |
std::cerr << "Fatal error, log init failed: " << ex.what() << std::endl; |
| 2717 |
ix::uninitNetSystem(); |
| 2718 |
return 1; |
| 2719 |
} |
| 2720 |
} |
| 2721 |
|
| 2722 |
if (quiet) |
| 2723 |
{ |
| 2724 |
spdlog::set_level(spdlog::level::info); |
| 2725 |
} |
| 2726 |
|
| 2727 |
int ret = 1; |
| 2728 |
if (app.got_subcommand("connect")) |
| 2729 |
{ |
| 2730 |
ret = ix::ws_connect_main(url, |
| 2731 |
headers, |
| 2732 |
disableAutomaticReconnection, |
| 2733 |
disablePerMessageDeflate, |
| 2734 |
binaryMode, |
| 2735 |
maxWaitBetweenReconnectionRetries, |
| 2736 |
tlsOptions, |
| 2737 |
subprotocol, |
| 2738 |
pingIntervalSecs, |
| 2739 |
decompressGzipMessages); |
| 2740 |
} |
| 2741 |
else if (app.got_subcommand("autoroute")) |
| 2742 |
{ |
| 2743 |
ret = ix::ws_autoroute( |
| 2744 |
url, disablePerMessageDeflate, tlsOptions, subprotocol, pingIntervalSecs, msgCount); |
| 2745 |
} |
| 2746 |
else if (app.got_subcommand("echo_server")) |
| 2747 |
{ |
| 2748 |
ret = ix::ws_echo_server_main(port, |
| 2749 |
greetings, |
| 2750 |
hostname, |
| 2751 |
tlsOptions, |
| 2752 |
ipv6, |
| 2753 |
disablePerMessageDeflate, |
| 2754 |
disablePong, |
| 2755 |
httpHeaderAuthorization); |
| 2756 |
} |
| 2757 |
else if (app.got_subcommand("push_server")) |
| 2758 |
{ |
| 2759 |
ret = ix::ws_push_server( |
| 2760 |
port, hostname, tlsOptions, ipv6, disablePerMessageDeflate, disablePong, sendMsg); |
| 2761 |
} |
| 2762 |
else if (app.got_subcommand("transfer") || app.got_subcommand("broadcast_server")) |
| 2763 |
{ |
| 2764 |
ix::WebSocketServer server(port, hostname); |
| 2765 |
server.setTLSOptions(tlsOptions); |
| 2766 |
server.makeBroadcastServer(); |
| 2767 |
if (!server.listenAndStart()) |
| 2768 |
{ |
| 2769 |
spdlog::error("Error while starting the server"); |
| 2770 |
} |
| 2771 |
else |
| 2772 |
{ |
| 2773 |
server.wait(); |
| 2774 |
} |
| 2775 |
} |
| 2776 |
else if (app.got_subcommand("send")) |
| 2777 |
{ |
| 2778 |
ret = ix::ws_send_main(url, path, disablePerMessageDeflate, tlsOptions); |
| 2779 |
} |
| 2780 |
else if (app.got_subcommand("receive")) |
| 2781 |
{ |
| 2782 |
bool enablePerMessageDeflate = false; |
| 2783 |
ret = ix::ws_receive_main(url, enablePerMessageDeflate, delayMs, tlsOptions); |
| 2784 |
} |
| 2785 |
else if (app.got_subcommand("chat")) |
| 2786 |
{ |
| 2787 |
ret = ix::ws_chat_main(url, user); |
| 2788 |
} |
| 2789 |
else if (app.got_subcommand("ping")) |
| 2790 |
{ |
| 2791 |
ret = ix::ws_ping_pong_main(url, tlsOptions); |
| 2792 |
} |
| 2793 |
else if (app.got_subcommand("curl")) |
| 2794 |
{ |
| 2795 |
ret = ix::ws_http_client_main(url, |
| 2796 |
headers, |
| 2797 |
data, |
| 2798 |
formData, |
| 2799 |
binaryData, |
| 2800 |
headersOnly, |
| 2801 |
connectTimeOut, |
| 2802 |
transferTimeout, |
| 2803 |
followRedirects, |
| 2804 |
maxRedirects, |
| 2805 |
verbose, |
| 2806 |
save, |
| 2807 |
output, |
| 2808 |
compress, |
| 2809 |
compressRequest, |
| 2810 |
tlsOptions); |
| 2811 |
} |
| 2812 |
else if (app.got_subcommand("httpd")) |
| 2813 |
{ |
| 2814 |
ret = ix::ws_httpd_main(port, hostname, redirect, redirectUrl, debug, tlsOptions); |
| 2815 |
} |
| 2816 |
else if (app.got_subcommand("autobahn")) |
| 2817 |
{ |
| 2818 |
ret = ix::ws_autobahn_main(url, quiet); |
| 2819 |
} |
| 2820 |
else if (app.got_subcommand("proxy_server")) |
| 2821 |
{ |
| 2822 |
ix::RemoteUrlsMapping remoteUrlsMapping; |
| 2823 |
|
| 2824 |
if (!configPath.empty()) |
| 2825 |
{ |
| 2826 |
auto res = readAsString(configPath); |
| 2827 |
bool found = res.first; |
| 2828 |
if (!found) |
| 2829 |
{ |
| 2830 |
spdlog::error("Cannot read config file {} from disk", configPath); |
| 2831 |
} |
| 2832 |
else |
| 2833 |
{ |
| 2834 |
// Split by \n |
| 2835 |
std::string token; |
| 2836 |
std::stringstream tokenStream(res.second); |
| 2837 |
|
| 2838 |
while (std::getline(tokenStream, token)) |
| 2839 |
{ |
| 2840 |
std::size_t pos = token.rfind(':'); |
| 2841 |
|
| 2842 |
// Bail out if last '.' is found |
| 2843 |
if (pos == std::string::npos) continue; |
| 2844 |
|
| 2845 |
auto key = token.substr(0, pos); |
| 2846 |
auto val = token.substr(pos + 1); |
| 2847 |
|
| 2848 |
spdlog::info("{}: {}", key, val); |
| 2849 |
|
| 2850 |
remoteUrlsMapping[key] = val; |
| 2851 |
} |
| 2852 |
} |
| 2853 |
} |
| 2854 |
|
| 2855 |
ret = ix::websocket_proxy_server_main( |
| 2856 |
port, hostname, tlsOptions, remoteHost, remoteUrlsMapping, verbose); |
| 2857 |
} |
| 2858 |
else if (app.got_subcommand("dnslookup")) |
| 2859 |
{ |
| 2860 |
ret = ix::ws_dns_lookup(hostname); |
| 2861 |
} |
| 2862 |
else if (app.got_subcommand("gzip")) |
| 2863 |
{ |
| 2864 |
ret = ix::ws_gzip(filename, runCount); |
| 2865 |
} |
| 2866 |
else if (app.got_subcommand("gunzip")) |
| 2867 |
{ |
| 2868 |
ret = ix::ws_gunzip(filename); |
| 2869 |
} |
| 2870 |
else if (version) |
| 2871 |
{ |
| 2872 |
std::cout << "ws " << ix::userAgent() << std::endl; |
| 2873 |
} |
| 2874 |
else |
| 2875 |
{ |
| 2876 |
spdlog::error("A subcommand or --version is required"); |
| 2877 |
} |
| 2878 |
|
| 2879 |
ix::uninitNetSystem(); |
| 2880 |
return ret; |
| 2881 |
} |