Repository navigation
Expand file tree
/
Copy pathwebserver_plugin.cpp
More file actions
1332 lines (1180 loc) · 68.2 KB
/
Copy pathwebserver_plugin.cpp
File metadata and controls
1332 lines (1180 loc) · 68.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <graphene/plugins/webserver/webserver_plugin.hpp>
#include <graphene/plugins/webserver/ip_counter_cache.hpp>
#include <graphene/plugins/chain/plugin.hpp>
#include <graphene/plugins/snapshot/plugin.hpp>
#include <graphene/protocol/block.hpp>
#include <fc/network/ip.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/io/json.hpp>
#include <fc/network/resolve.hpp>
#include <fc/crypto/sha256.hpp>
#include <fc/compat/asio_compat.hpp>
#include <boost/asio.hpp>
#include <boost/filesystem.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <functional>
#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/config/asio.hpp>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/client.hpp>
#include <websocketpp/logger/stub.hpp>
#ifndef _WIN32
#include <websocketpp/logger/syslog.hpp>
#endif
#include <thread>
#include <memory>
#include <iostream>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <mutex>
#include <atomic>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cctype>
#include <ctime>
#include <chrono>
#include <algorithm>
#include <graphene/plugins/json_rpc/plugin.hpp>
namespace graphene {
namespace plugins {
namespace webserver {
namespace asio = boost::asio;
using std::map;
using std::string;
using boost::asio::ip::tcp;
using std::shared_ptr;
using websocketpp::connection_hdl;
typedef uint32_t thread_pool_size_t;
struct asio_with_stub_log : public websocketpp::config::asio {
typedef asio_with_stub_log type;
typedef asio base;
typedef base::concurrency_type concurrency_type;
typedef base::request_type request_type;
typedef base::response_type response_type;
typedef base::message_type message_type;
typedef base::con_msg_manager_type con_msg_manager_type;
typedef base::endpoint_msg_manager_type endpoint_msg_manager_type;
typedef base::alog_type alog_type;
typedef base::elog_type elog_type;
//typedef websocketpp::log::stub elog_type;
//typedef websocketpp::log::stub alog_type;
typedef base::rng_type rng_type;
struct transport_config : public base::transport_config {
typedef type::concurrency_type concurrency_type;
typedef type::alog_type alog_type;
typedef type::elog_type elog_type;
typedef type::request_type request_type;
typedef type::response_type response_type;
typedef websocketpp::transport::asio::basic_socket::endpoint socket_type;
};
typedef websocketpp::transport::asio::endpoint<transport_config> transport_type;
static const long timeout_open_handshake = 0;
};
using websocket_server_type = websocketpp::server<asio_with_stub_log>;
// API prefixes whose responses must never be cached because
// the calls are mutating (broadcast, locks, etc.).
// Uses proper JSON parsing to reliably detect both
// "method":"network_broadcast_api.xxx" and "method":"call","params":["network_broadcast_api",...]
static bool is_cacheable_request(const fc::variant& request) {
try {
if (!request.is_object()) return true;
const auto& obj = request.get_object();
// Check top-level method
if (obj.contains("method")) {
std::string method = obj["method"].as_string();
if (method.find("network_broadcast_api") != std::string::npos) return false;
if (method.find("debug_node") != std::string::npos) return false;
}
// Check params for call-style requests: params[0] is the API name
if (obj.contains("params") && obj["params"].is_array()) {
const auto& params = obj["params"].get_array();
if (!params.empty() && params[0].is_string()) {
std::string api_name = params[0].as_string();
if (api_name.find("network_broadcast_api") != std::string::npos) return false;
if (api_name.find("debug_node") != std::string::npos) return false;
}
}
} catch (...) {
// Malformed request — don't cache
return false;
}
return true;
}
// Extract the "id" value from a parsed JSON-RPC request as a raw string
// suitable for injecting into a response (preserves quotes for string ids).
// Returns "" if no id field is found.
static std::string extract_request_id(const fc::variant& request) {
try {
if (!request.is_object()) return "";
const auto& obj = request.get_object();
if (!obj.contains("id")) return "";
const auto& id = obj["id"];
// Return the JSON-serialized form of the id value
// so it can be directly spliced into a response.
return fc::json::to_string(id);
} catch (...) {
return "";
}
}
// Generate a cache key from a parsed JSON-RPC request that is independent
// of the "id" field. Uses only method + params so that identical calls with
// different IDs share the same cache entry, preventing cache bypass via
// id rotation (spam attack pattern).
static std::string make_cache_key(const fc::variant& request) {
// For batch requests (array), use full body hash
if (request.is_array()) {
return fc::sha256::hash(fc::json::to_string(request)).str();
}
std::string key_material;
try {
if (!request.is_object()) return fc::sha256::hash(key_material).str();
const auto& obj = request.get_object();
if (obj.contains("method")) {
key_material += fc::json::to_string(obj["method"]);
}
if (obj.contains("params")) {
key_material += fc::json::to_string(obj["params"]);
}
} catch (...) {
// On any parse error, use empty key material
}
return fc::sha256::hash(key_material).str();
}
// Replace the "id" value in a JSON-RPC response string with a new one,
// ensuring the response id matches the request id per JSON-RPC 2.0 spec.
static std::string patch_response_id(const std::string& response, const std::string& new_id) {
if (new_id.empty()) return response;
// Parse response properly to find and replace id
try {
auto resp = fc::json::from_string(response);
if (!resp.is_object()) return response;
auto& obj = resp.get_object();
if (!obj.contains("id")) return response;
// Replace id value and re-serialize
auto id_var = fc::json::from_string(new_id);
// We need to mutate the object — convert to mutable_variant_object
fc::mutable_variant_object mobj(obj);
mobj["id"] = id_var;
return fc::json::to_string(mobj);
} catch (...) {
// Fallback: if parsing fails, return response as-is
return response;
}
}
// Cache entry for JSON-RPC responses
struct cache_entry {
std::string response;
uint32_t block_num;
};
// ── request accounting, IP lists and admission limits ───────────────────────
// All of it is driven by `webserver-stats-enabled` (off by default: the node
// then behaves exactly as before). The blacklist works even with stats off —
// it is a security control, not a metric. Enabled limits keep their counters
// even while stats logging is disabled.
enum class admission {
allow,
blacklisted,
rate_limited
};
static uint32_t now_seconds() {
return static_cast<uint32_t>(::time(nullptr));
}
// ::ffff:1.2.3.4 (IPv4-mapped IPv6, what an IPv6 listening socket reports for
// IPv4 clients) is folded back to 1.2.3.4 so a single client is one identity
// regardless of how the socket was opened.
static std::string normalize_ip(std::string ip) {
static const std::string mapped = "::ffff:";
if (ip.size() > mapped.size() && ip.compare(0, mapped.size(), mapped) == 0) {
ip.erase(0, mapped.size());
}
return ip;
}
static bool valid_ip_text(const std::string &ip) {
if (ip.empty() || ip.size() > 45) return false;
for (char c : ip) {
if (!(std::isdigit(static_cast<unsigned char>(c)) || c == '.' || c == ':' ||
(c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
return false;
}
}
return true;
}
static std::string iso_utc(uint32_t t) {
std::time_t tt = static_cast<std::time_t>(t);
std::tm tm{};
#ifdef _WIN32
gmtime_s(&tm, &tt);
#else
gmtime_r(&tt, &tm);
#endif
char buf[32];
std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tm);
return std::string(buf);
}
static std::string peer_ip(const websocket_server_type::connection_ptr &con) {
boost::system::error_code ec;
const auto ep = con->get_socket().remote_endpoint(ec);
if (ec) return "unknown";
return normalize_ip(ep.address().to_string());
}
struct webserver_plugin::webserver_plugin_impl final {
public:
boost::thread_group& thread_pool = appbase::app().scheduler();
webserver_plugin_impl(thread_pool_size_t thread_pool_size) : thread_pool_work(asio::make_work_guard(this->thread_pool_ios)) {
for (uint32_t i = 0; i < thread_pool_size; ++i) {
thread_pool.create_thread(std::bind(static_cast<std::size_t(asio::io_context::*)()>(&asio::io_context::run), &thread_pool_ios));
}
}
void start_webserver();
void stop_webserver();
void handle_ws_message(websocket_server_type *, connection_hdl, websocket_server_type::message_ptr);
void handle_http_message(websocket_server_type *, connection_hdl);
// Cache methods
fc::optional<std::string> get_cached_response(const std::string& request_hash);
void cache_response(const std::string& request_hash, const std::string& response, uint32_t block_num);
void clear_cache();
shared_ptr<std::thread> http_thread;
asio::io_context http_ios;
optional<tcp::endpoint> http_endpoint;
websocket_server_type http_server;
shared_ptr<std::thread> ws_thread;
asio::io_context ws_ios;
optional<tcp::endpoint> ws_endpoint;
websocket_server_type ws_server;
asio::io_context thread_pool_ios;
asio::executor_work_guard<asio::io_context::executor_type> thread_pool_work;
plugins::json_rpc::plugin *api;
chain::plugin *chain_plugin = nullptr;
snapshot::snapshot_plugin *snap_plugin = nullptr;
boost::signals2::connection chain_sync_con;
boost::signals2::connection applied_block_conn;
// Cache for JSON-RPC responses
std::unordered_map<std::string, cache_entry> response_cache;
std::mutex cache_mutex;
uint32_t current_block_num = 0;
bool cache_enabled = true;
size_t max_cache_size = 10000;
// Request accounting and admission. `stats_mutex` guards everything below
// up to `state_path`; request handlers take it once per request.
mutable std::mutex stats_mutex;
bool stats_enabled = false;
std::string config_policy;
std::unordered_set<std::string> trusted_proxies;
std::string client_ip(const websocket_server_type::connection_ptr &con) const {
std::string ip = peer_ip(con);
if (!trusted_proxies.count(ip)) return ip;
const std::string header = con->get_request().get_header("X-Forwarded-For");
if (header.size() > 4096) return ip;
std::vector<std::string> hops;
size_t start = 0;
while (start < header.size()) {
const size_t end = header.find(',', start);
std::string hop = header.substr(start, end == std::string::npos ? end : end - start);
const auto first = hop.find_first_not_of(" \t");
const auto last = hop.find_last_not_of(" \t");
hop = first == std::string::npos ? "" : hop.substr(first, last - first + 1);
hop = normalize_ip(hop);
if (!valid_ip_text(hop)) return ip;
hops.push_back(hop);
if (end == std::string::npos) break;
start = end + 1;
}
// Walk from the authenticated TCP peer towards the client. Never trust
// the leftmost address supplied by an untrusted hop.
for (auto it = hops.rbegin(); it != hops.rend() && trusted_proxies.count(ip); ++it)
ip = *it;
return ip;
}
webserver_limits limits;
detail::ip_counter_cache ip_stats;
std::unordered_set<std::string> whitelist;
std::unordered_set<std::string> blacklist;
uint64_t total_requests = 0;
uint64_t blocked_requests = 0;
uint64_t limited_requests = 0;
std::string stats_log_path;
uint64_t stats_log_max_bytes = 10ULL * 1024 * 1024;
uint32_t stats_log_keep = 5;
uint32_t stats_interval_sec = 60;
std::string state_path;
std::atomic<bool> stats_stop{false};
std::thread stats_thread;
std::chrono::steady_clock::time_point last_stats_flush;
// HTTP requests being answered right now. Every one of them pins its
// connection — and therefore its socket — until the response is sent, so an
// unbounded queue is an unbounded descriptor demand. Live incident
// 2026-11-01: local pollers that spin while the head is frozen opened
// ~11k connections/s, ~1.5k of them ended up half-closed on our side, and
// the node hit EMFILE — it could no longer write its block-vote round file
// and stopped voting for blocks. The cap turns that into shed requests
// (503) instead of a mute validator.
std::atomic<uint64_t> http_inflight{0};
uint64_t http_inflight_max = 1024;
std::atomic<uint64_t> http_inflight_shed{0};
// Releases one inflight slot when the last owner goes away. Shared between
// the pool task and the API callback: the slot is held until the response is
// actually sent, which is exactly as long as the socket stays open.
struct http_inflight_hold {
std::atomic<uint64_t> &counter;
explicit http_inflight_hold(std::atomic<uint64_t> &c) : counter(c) {}
~http_inflight_hold() { counter.fetch_sub(1, std::memory_order_relaxed); }
};
// Called by both HTTP and WS handlers before any work is done. Returns
// `allow`, `blacklisted` or `rate_limited`; counters are updated here.
admission admit(const std::string &raw_ip);
void rotate_stats_log_locked();
void flush_stats_locked(bool force);
void stats_loop();
bool save_admin_state_locked();
bool load_admin_state_locked(std::string &error);
};
void webserver_plugin::webserver_plugin_impl::start_webserver() {
if (ws_endpoint) {
ws_thread = std::make_shared<std::thread>([&]() {
ilog("start processing ws thread");
try {
ws_server.clear_access_channels(websocketpp::log::alevel::all);
ws_server.clear_error_channels(websocketpp::log::elevel::all);
ws_server.init_asio(&ws_ios);
ws_server.set_reuse_addr(true);
ws_server.set_message_handler(std::bind(&webserver_plugin_impl::handle_ws_message, this, &ws_server, std::placeholders::_1, std::placeholders::_2));
if (http_endpoint && http_endpoint == ws_endpoint) {
ws_server.set_http_handler(std::bind(&webserver_plugin_impl::handle_http_message, this, &ws_server, std::placeholders::_1));
ilog("start listending for http requests");
}
ilog("start listening for ws requests");
ws_server.listen(*ws_endpoint);
ws_server.start_accept();
ws_ios.run();
ilog("ws io service exit");
} catch (...) {
elog("error thrown from http io service");
}
});
}
if (http_endpoint && ((ws_endpoint && ws_endpoint != http_endpoint) || !ws_endpoint)) {
http_thread = std::make_shared<std::thread>( [&]() {
ilog("start processing http thread");
try {
http_server.clear_access_channels(websocketpp::log::alevel::all);
http_server.clear_error_channels(websocketpp::log::elevel::all);
http_server.init_asio(&http_ios);
http_server.set_reuse_addr(true);
http_server.set_http_handler([this](connection_hdl hdl) {
this->handle_http_message(&this->http_server, hdl);
});
ilog("start listening for http requests");
http_server.listen(*http_endpoint);
http_server.start_accept();
http_ios.run();
ilog("http io service exit");
} catch (...) {
elog("error thrown from http io service");
}
});
}
}
void webserver_plugin::webserver_plugin_impl::stop_webserver() {
if (ws_server.is_listening()) {
ws_server.stop_listening();
}
if (http_server.is_listening()) {
http_server.stop_listening();
}
thread_pool_ios.stop();
thread_pool.join_all();
if (ws_thread) {
ws_ios.stop();
ws_thread->join();
ws_thread.reset();
}
if (http_thread) {
http_ios.stop();
http_thread->join();
http_thread.reset();
}
}
fc::optional<std::string> webserver_plugin::webserver_plugin_impl::get_cached_response(const std::string& request_hash) {
if (!cache_enabled) {
return fc::optional<std::string>();
}
std::lock_guard<std::mutex> lock(cache_mutex);
auto it = response_cache.find(request_hash);
if (it != response_cache.end()) {
// Check if the cached response is still valid for current block
if (it->second.block_num == current_block_num) {
return it->second.response;
}
}
return fc::optional<std::string>();
}
void webserver_plugin::webserver_plugin_impl::cache_response(const std::string& request_hash, const std::string& response, uint32_t block_num) {
if (!cache_enabled) {
return;
}
std::lock_guard<std::mutex> lock(cache_mutex);
// Simple eviction: clear if cache is too large
if (response_cache.size() >= max_cache_size) {
response_cache.clear();
}
response_cache[request_hash] = cache_entry{response, block_num};
}
void webserver_plugin::webserver_plugin_impl::clear_cache() {
std::lock_guard<std::mutex> lock(cache_mutex);
response_cache.clear();
}
// ── stats/limits implementation ─────────────────────────────────────────────
admission webserver_plugin::webserver_plugin_impl::admit(const std::string &raw_ip) {
const std::string ip = normalize_ip(raw_ip);
const uint32_t now = now_seconds();
std::lock_guard<std::mutex> lock(stats_mutex);
// The blacklist is enforced even when stats are off: it is an access
// control, not a metric.
if (blacklist.count(ip)) {
++blocked_requests;
auto it = ip_stats.find(ip);
if (it != ip_stats.end()) { auto &c = ip_stats.touch(ip); ++c.blocked; c.last_seen = now; }
return admission::blacklisted;
}
if (!stats_enabled && !limits.enabled) {
return admission::allow;
}
// Bounded LRU admission evicts only the oldest inactive counter.
// A source-address spray must not lock every new client out for a day.
auto &c = ip_stats.touch(ip);
c.last_seen = now;
++c.total;
++total_requests;
const uint32_t minute_bucket = now / 60;
const uint32_t hour_bucket = now / 3600;
const uint32_t day_bucket = now / 86400;
if (c.minute_bucket != minute_bucket) { c.minute_bucket = minute_bucket; c.minute = 0; }
if (c.hour_bucket != hour_bucket) { c.hour_bucket = hour_bucket; c.hour = 0; }
if (c.day_bucket != day_bucket) { c.day_bucket = day_bucket; c.day = 0; }
++c.minute;
++c.hour;
++c.day;
if (limits.enabled && !whitelist.count(ip)) {
if (c.minute > limits.per_minute || c.hour > limits.per_hour ||
c.day > limits.per_day) {
++c.limited;
++limited_requests;
return admission::rate_limited;
}
}
return admission::allow;
}
void webserver_plugin::webserver_plugin_impl::rotate_stats_log_locked() {
if (stats_log_path.empty() || stats_log_max_bytes == 0) return;
boost::system::error_code ec;
const uintmax_t size = boost::filesystem::file_size(stats_log_path, ec);
if (ec || size < stats_log_max_bytes) return;
const std::string base = stats_log_path;
try {
if (stats_log_keep == 0) {
boost::filesystem::remove(base, ec);
} else {
// base.N is the oldest; shift down and drop the last one.
boost::system::error_code ignore;
boost::filesystem::remove(base + "." + std::to_string(stats_log_keep), ignore);
for (uint32_t i = stats_log_keep; i > 1; --i) {
const std::string from = base + "." + std::to_string(i - 1);
const std::string to = base + "." + std::to_string(i);
if (boost::filesystem::exists(from, ignore)) {
boost::filesystem::rename(from, to, ignore);
}
}
boost::filesystem::rename(base, base + ".1", ignore);
}
ilog("webserver stats log rotated (${s} bytes, keeping ${k})",
("s", size)("k", stats_log_keep));
} catch (const std::exception &e) {
wlog("webserver stats log rotation failed: ${e}", ("e", e.what()));
}
}
void webserver_plugin::webserver_plugin_impl::flush_stats_locked(bool force) {
std::unique_lock<std::mutex> lock(stats_mutex);
if (!stats_enabled || stats_log_path.empty()) return;
struct row { std::string ip; detail::ip_counters c; bool white; bool black; };
std::vector<row> changed;
for (auto &kv : ip_stats) {
auto &c = kv.second;
if (!force && c.total + c.blocked == c.logged) continue;
c.logged = c.total + c.blocked;
changed.push_back({kv.first, c, whitelist.count(kv.first) != 0, blacklist.count(kv.first) != 0});
}
if (changed.empty() && !force) return;
const uint64_t total = total_requests, blocked = blocked_requests, limited = limited_requests;
const size_t ips = ip_stats.size();
const auto policy = limits;
lock.unlock(); // Formatting and filesystem I/O do not block admission.
const uint32_t now = now_seconds();
const auto ts = iso_utc(now);
std::ostringstream out;
for (const auto &r : changed) {
const auto &c = r.c;
out << ts << " ip=" << r.ip << " total=" << c.total
<< " minute=" << c.minute << " hour=" << c.hour << " day=" << c.day
<< " blocked=" << c.blocked << " limited=" << c.limited
<< " whitelisted=" << r.white << " blacklisted=" << r.black << "\n";
}
out << ts << " summary total=" << total << " ips=" << ips
<< " blocked=" << blocked << " limited=" << limited
<< " limit_m=" << policy.per_minute << " limit_h=" << policy.per_hour
<< " limit_d=" << policy.per_day << " limits_enabled=" << policy.enabled << "\n";
try {
rotate_stats_log_locked();
std::ofstream f(stats_log_path, std::ios::app | std::ios::binary);
if (!f.is_open()) {
// The directory may not exist yet (custom path).
const auto parent = boost::filesystem::path(stats_log_path).parent_path();
if (!parent.empty()) {
boost::system::error_code ec;
boost::filesystem::create_directories(parent, ec);
}
f.open(stats_log_path, std::ios::app | std::ios::binary);
}
if (!f.is_open()) {
wlog("webserver stats log is not writable: ${p}", ("p", stats_log_path));
return;
}
f << out.str();
f.flush();
} catch (const std::exception &e) {
wlog("webserver stats log write failed: ${e}", ("e", e.what()));
}
}
void webserver_plugin::webserver_plugin_impl::stats_loop() {
const uint32_t step_ms = 1000;
uint32_t waited_ms = 0;
while (!stats_stop.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds(step_ms));
waited_ms += step_ms;
if (waited_ms < stats_interval_sec * 1000) continue;
waited_ms = 0;
flush_stats_locked(false);
}
}
bool webserver_plugin::webserver_plugin_impl::save_admin_state_locked() {
if (state_path.empty()) return false;
fc::mutable_variant_object v;
v("config_policy", config_policy);
v("stats_enabled", stats_enabled);
v("limits_enabled", limits.enabled);
v("per_minute", limits.per_minute);
v("per_hour", limits.per_hour);
v("per_day", limits.per_day);
fc::variants wl, bl;
for (const auto &ip : whitelist) wl.push_back(fc::variant(ip));
for (const auto &ip : blacklist) bl.push_back(fc::variant(ip));
v("whitelist", fc::variant(wl));
v("blacklist", fc::variant(bl));
try {
const std::string tmp = state_path + ".tmp";
{
std::ofstream f(tmp, std::ios::binary | std::ios::trunc);
if (!f.is_open()) return false;
f << fc::json::to_string(fc::variant(v));
f.flush();
if (!f.good()) return false;
}
boost::system::error_code ec;
boost::filesystem::rename(tmp, state_path, ec);
if (ec) {
boost::filesystem::remove(state_path, ec);
boost::filesystem::rename(tmp, state_path, ec);
}
return !ec;
} catch (const std::exception &e) {
wlog("webserver admin state save failed: ${e}", ("e", e.what()));
return false;
}
}
bool webserver_plugin::webserver_plugin_impl::load_admin_state_locked(std::string &error) {
if (state_path.empty()) {
error = "no state file configured";
return false;
}
if (!boost::filesystem::exists(state_path)) {
error = "state file not found: " + state_path;
return false;
}
try {
std::ifstream f(state_path, std::ios::binary);
if (!f.is_open()) {
error = "cannot open state file: " + state_path;
return false;
}
std::stringstream ss;
ss << f.rdbuf();
const fc::variant v = fc::json::from_string(ss.str());
const auto &o = v.get_object();
auto read_u32 = [&](const char *key, uint32_t fallback) -> uint32_t {
if (!o.contains(key)) return fallback;
try {
const int64_t x = o[key].as_int64();
return x < 0 ? 0 : static_cast<uint32_t>(x);
} catch (...) {
return fallback;
}
};
// Parse into locals and commit only when the whole file is valid:
// a malformed field must not leave the live policy half-updated.
const bool same_config = o.contains("config_policy") &&
o["config_policy"].as_string() == config_policy;
bool new_stats = stats_enabled;
bool new_limits_enabled = limits.enabled;
if (same_config && o.contains("stats_enabled")) new_stats = o["stats_enabled"].as_bool();
if (same_config && o.contains("limits_enabled")) new_limits_enabled = o["limits_enabled"].as_bool();
const uint32_t new_m = std::max<uint32_t>(1, (same_config ? read_u32("per_minute", limits.per_minute) : limits.per_minute));
const uint32_t new_h = std::max<uint32_t>(1, (same_config ? read_u32("per_hour", limits.per_hour) : limits.per_hour));
const uint32_t new_d = std::max<uint32_t>(1, (same_config ? read_u32("per_day", limits.per_day) : limits.per_day));
auto read_list = [&](const char *key) {
std::unordered_set<std::string> dst;
if (!o.contains(key)) return dst;
const auto &arr = o[key].get_array();
for (const auto &item : arr) {
const std::string ip = normalize_ip(item.as_string());
if (valid_ip_text(ip)) dst.insert(ip);
}
return dst;
};
const bool has_wl = o.contains("whitelist");
const bool has_bl = o.contains("blacklist");
std::unordered_set<std::string> new_wl = has_wl ? read_list("whitelist")
: std::unordered_set<std::string>();
std::unordered_set<std::string> new_bl = has_bl ? read_list("blacklist")
: std::unordered_set<std::string>();
stats_enabled = new_stats;
limits.enabled = new_limits_enabled;
limits.per_minute = new_m;
limits.per_hour = new_h;
limits.per_day = new_d;
if (has_wl) whitelist = std::move(new_wl);
if (has_bl) blacklist = std::move(new_bl);
return true;
} catch (const std::exception &e) {
error = std::string("cannot parse state file: ") + e.what();
return false;
}
}
void webserver_plugin::webserver_plugin_impl::handle_ws_message(
websocket_server_type *server,
connection_hdl hdl,
websocket_server_type::message_ptr msg
) {
auto con = server->get_con_from_hdl(hdl);
const admission verdict = admit(client_ip(con));
if (verdict != admission::allow) {
const char *msg = verdict == admission::blacklisted
? "{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32005,\"message\":\"forbidden\"},\"id\":null}"
: "{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32006,\"message\":\"rate limit exceeded\"},\"id\":null}";
try {
con->send(msg);
} catch (...) {
}
return;
}
boost::asio::post(thread_pool_ios, [con, msg, this]() {
try {
if ((chain_plugin && chain_plugin->is_recovering()) ||
(snap_plugin && snap_plugin->is_snapshot_reloading())) {
auto ec = con->send("{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32003,\"message\":\"Node is recovering from shared memory corruption, please retry later\"},\"id\":null}");
if (ec) throw websocketpp::exception(ec);
return;
}
if (msg->get_opcode() == websocketpp::frame::opcode::text) {
auto body = msg->get_payload();
// Parse JSON once for all cache operations
fc::variant parsed;
try {
parsed = fc::json::from_string(body);
} catch (...) {
// Invalid JSON — skip cache, let json_rpc handle the error
api->call(body, [con](const std::string &data){
auto ec = con->send(data);
if (ec) throw websocketpp::exception(ec);
});
return;
}
bool cacheable = is_cacheable_request(parsed);
// Generate id-independent cache key from request body
std::string request_hash;
std::string request_id;
if (cacheable) {
request_hash = make_cache_key(parsed);
request_id = extract_request_id(parsed);
// Check cache first
auto cached_response = get_cached_response(request_hash);
if (cached_response.valid()) {
// Patch the id in cached response to match request
std::string patched = patch_response_id(*cached_response, request_id);
auto ec = con->send(patched);
if (ec) {
throw websocketpp::exception(ec);
}
return;
}
}
api->call(body, [con, this, request_hash, cacheable](const std::string &data){
auto ec = con->send(data);
if (ec) {
throw websocketpp::exception(ec);
}
// Cache the response only for read-only methods
if (cacheable) {
cache_response(request_hash, data, current_block_num);
}
});
} else {
con->send("error: string payload expected");
}
} catch (const fc::exception &e) {
con->send("error calling API " + e.to_string());
}
});
}
void webserver_plugin::webserver_plugin_impl::handle_http_message(websocket_server_type *server, connection_hdl hdl) {
auto con = server->get_con_from_hdl(hdl);
switch (admit(client_ip(con))) {
case admission::blacklisted:
con->append_header("Access-Control-Allow-Origin", "*");
con->set_body("forbidden");
con->set_status(websocketpp::http::status_code::forbidden);
try { con->send_http_response(); } catch (...) {}
return;
case admission::rate_limited:
con->append_header("Access-Control-Allow-Origin", "*");
con->append_header("Retry-After", "60");
con->set_body("rate limit exceeded");
con->set_status(websocketpp::http::status_code::too_many_requests);
try { con->send_http_response(); } catch (...) {}
return;
case admission::allow:
break;
}
con->defer_http_response();
// CORS preflight
if (con->get_request().get_method() == "OPTIONS") {
con->append_header("Access-Control-Allow-Origin", "*");
con->append_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
// Reflect exactly the headers the browser asked to send. A fixed
// allow-list blocks any request carrying a header outside it
// (custom X-* headers, x-api-key, etc.), which the browser reports
// as a CORS preflight failure. Falls back to the common defaults
// when the browser did not advertise any headers.
const std::string &requested_headers = con->get_request().get_header("Access-Control-Request-Headers");
con->append_header("Access-Control-Allow-Headers",
requested_headers.empty() ? std::string("Content-Type, Authorization") : requested_headers);
con->append_header("Access-Control-Max-Age", "86400");
con->set_status(websocketpp::http::status_code::ok);
try { con->send_http_response(); } catch (...) {}
return;
}
// Shed before the request takes a slot in the pool. Rejecting here is cheap
// (the response travels the same path as a normal one) and it is the only
// place where the node can still say "no" to a flood.
if (http_inflight_max != 0 && http_inflight.load(std::memory_order_relaxed) >= http_inflight_max) {
http_inflight_shed.fetch_add(1, std::memory_order_relaxed);
con->append_header("Access-Control-Allow-Origin", "*");
con->append_header("Retry-After", "5");
con->set_body("{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32005,\"message\":\"Node is overloaded, retry later\"},\"id\":null}");
con->set_status(websocketpp::http::status_code::service_unavailable);
try { con->send_http_response(); } catch (...) {}
return;
}
http_inflight.fetch_add(1, std::memory_order_relaxed);
auto hold = std::make_shared<http_inflight_hold>(http_inflight);
boost::asio::post(thread_pool_ios, [con, this, hold]() {
if ((chain_plugin && chain_plugin->is_recovering()) ||
(snap_plugin && snap_plugin->is_snapshot_reloading())) {
con->append_header("Access-Control-Allow-Origin", "*");
con->set_body("{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32003,\"message\":\"Node is recovering from shared memory corruption, please retry later\"},\"id\":null}");
con->set_status(websocketpp::http::status_code::service_unavailable);
try { con->send_http_response(); } catch (...) {}
return;
}
auto body = con->get_request_body();
if (body.empty()) {
con->append_header("Access-Control-Allow-Origin", "*");
con->set_body("empty request body");
con->set_status(websocketpp::http::status_code::bad_request);
try { con->send_http_response(); } catch (...) {}
return;
}
// Parse JSON once for all cache operations
fc::variant parsed;
try {
parsed = fc::json::from_string(body);
} catch (...) {
// Invalid JSON — skip cache, let json_rpc handle the error
try {
api->call(body, [con, hold](const std::string &data){
con->append_header("Access-Control-Allow-Origin", "*");
con->set_body(data);
con->set_status(websocketpp::http::status_code::ok);
con->send_http_response();
});
} catch (fc::exception &e) {
edump((e));
con->append_header("Access-Control-Allow-Origin", "*");
con->set_body("Could not call API");
con->set_status(websocketpp::http::status_code::not_found);
try { con->send_http_response(); } catch (...) {}
}
return;
}
bool cacheable = is_cacheable_request(parsed);
// Generate id-independent cache key from request body
std::string request_hash;
std::string request_id;
if (cacheable) {
request_hash = make_cache_key(parsed);
request_id = extract_request_id(parsed);
// Check cache first
auto cached_response = get_cached_response(request_hash);
if (cached_response.valid()) {
// Patch the id in cached response to match request
std::string patched = patch_response_id(*cached_response, request_id);
con->append_header("Access-Control-Allow-Origin", "*");
con->set_body(patched);
con->set_status(websocketpp::http::status_code::ok);
con->send_http_response();
return;
}
}
try {
api->call(body, [con, this, request_hash, cacheable, hold](const std::string &data){
// this lambda can be called from any thread in application
// for example, when task was delegated ( see msg_pack(msg_pack&&) )
con->append_header("Access-Control-Allow-Origin", "*");
con->set_body(data);
con->set_status(websocketpp::http::status_code::ok);
con->send_http_response();
// Cache the response only for read-only methods
if (cacheable) {
cache_response(request_hash, data, current_block_num);
}
});
} catch (fc::exception &e) {
// this case happens if exception was thrown on parsing request
edump((e));
con->append_header("Access-Control-Allow-Origin", "*");
con->set_body("Could not call API");
con->set_status(websocketpp::http::status_code::not_found);
// this sending response can't be merged with sending response from try-block
// because try-block can work from other thread,
// when catch-block happens in current thread on parsing request
try {
con->send_http_response();
} catch (...) {
// disable segfault
}
}
});
}
webserver_plugin::webserver_plugin() {
}
webserver_admin_state webserver_plugin::admin_state(size_t max_ips) const {
webserver_admin_state st;