• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

libbitcoin / libbitcoin-network / 35515274750

20 Sep 2026 02:02PM UTC coverage: 48.45% (+0.05%) from 48.405%
35515274750

push

github

web-flow
Merge pull request #906 from evoskuil/master

Refactor for consistent socket settings injection.

74 of 90 new or added lines in 10 files covered. (82.22%)

11 existing lines in 7 files now uncovered.

27951 of 57690 relevant lines covered (48.45%)

163731.84 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

21.68
/src/net/socket_http.cpp
1
/**
2
 * Copyright (c) 2011-2026 libbitcoin developers
3
 *
4
 * This file is part of libbitcoin.
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Affero General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU Affero General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Affero General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
#include <bitcoin/network/net/socket.hpp>
20

21
#include <bitcoin/network/config/config.hpp>
22
#include <bitcoin/network/define.hpp>
23
#include <bitcoin/network/log/log.hpp>
24
#include <bitcoin/network/messages/messages.hpp>
25
#include <bitcoin/network/settings.hpp>
26

27
namespace libbitcoin {
28
namespace network {
29
    
30
using namespace system;
31
using namespace std::placeholders;
32

33
// Shared pointers required in handler parameters so closures control lifetime.
34
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
35
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
36
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
37

38
// DETECT (first read).
39
// ----------------------------------------------------------------------------
40

41
// local
42
constexpr bool is_json_open(char byte) NOEXCEPT
43
{
44
    // A json value opens with an object or array, and neither is a valid
45
    // http method token character (rfc9110 tchar).
46
    return byte == '{' || byte == '[';
×
47
}
48

49
// local
50
constexpr bool is_line_break(char byte) NOEXCEPT
51
{
52
    // A server tolerates empty lines preceding a request line (rfc9112).
53
    return byte == '\r' || byte == '\n';
×
54
}
55

56
// local
57
// False implies inconclusive (the buffer holds only empty lines).
58
inline bool detect_json(bool& json, const http::flat_buffer& buffer) NOEXCEPT
×
59
{
60
    const auto data = buffer.data();
×
61
    const std::string_view bytes{ static_cast<const char*>(data.data()),
62
        data.size() };
63

64
    for (const auto byte: bytes)
×
65
    {
66
        if (is_line_break(byte))
×
67
            continue;
68

69
        json = is_json_open(byte);
×
70
        return true;
×
71
    }
72

73
    return false;
74
}
75

76
void socket::detect(http::flat_buffer& buffer,
×
77
    count_handler&& handler) NOEXCEPT
78
{
79
    boost::asio::dispatch(strand_,
×
80
        std::bind(&socket::do_detect, shared_from_this(),
×
81
            std::ref(buffer), std::move(handler)));
×
82
}
×
83

84
// private
85
void socket::do_detect(const ref<http::flat_buffer>& buffer,
×
86
    const count_handler& handler) NOEXCEPT
87
{
88
    BC_ASSERT(stranded());
×
89

90
    bool json{};
×
91
    if (detect_json(json, buffer.get()))
×
92
    {
93
        detected_.store(true);
94
        downgraded_.store(json);
×
95
        handler(error::success, zero);
×
96
        return;
×
97
    }
98

99
    // Tolerated empty lines only, so read more (bounded by the buffer).
100
    async_read(buffer.get(),
×
101
        std::bind(&socket::handle_detect,
×
102
            shared_from_this(), _1, _2, buffer, handler));
×
103
}
104

105
// private
106
void socket::handle_detect(const code& ec, size_t size,
×
107
    const ref<http::flat_buffer>& buffer,
108
    const count_handler& handler) NOEXCEPT
109
{
110
    BC_ASSERT(stranded());
×
111

112
    if (ec)
×
113
    {
114
        handler(ec, size);
×
115
        return;
×
116
    }
117

118
    // async_read prepares, the caller commits (as does handle_body_read).
119
    buffer.get().commit(size);
×
120
    do_detect(buffer, handler);
×
121
}
122

123
// HTTP/WS (read).
124
// ----------------------------------------------------------------------------
125

126
void socket::http_read(http::flat_buffer& buffer,
1 ✔
127
    http::request& request, count_handler&& handler) NOEXCEPT
128
{
129
    boost::asio::dispatch(strand_,
1 ✔
130
        std::bind(&socket::do_http_read, shared_from_this(),
2 ✔
131
            std::ref(buffer), std::ref(request), std::move(handler)));
1 ✔
132
}
1 ✔
133

134
// private
135
void socket::do_http_read(ref<http::flat_buffer> buffer,
1 ✔
136
    const ref<http::request>& request,
137
    const count_handler& handler) NOEXCEPT
138
{
139
    BC_ASSERT(stranded());
1 ✔
140

141
    async_read_http(buffer.get(), request.get(), handler);
1 ✔
142
}
1 ✔
143

144
// private
145
void socket::handle_http_read(const boost_code& ec, size_t size,
1 ✔
146
    const ref<http::request>& request, const http_parser_ptr& parser,
147
    const count_handler& handler) NOEXCEPT
148
{
149
    BC_ASSERT(stranded());
1 ✔
150

151
    if (error::asio_is_canceled(ec))
1 ✔
152
    {
153
        handler(error::channel_stopped, size);
×
154
        return;
1 ✔
155
    }
156

157
    if (!ec && boost::beast::websocket::is_upgrade(parser->get()))
1 ✔
158
    {
159
        // Publish the upgrade request, the channel accepts or refuses it.
160
        request.get() = parser->release();
2 ✔
161
        handler(error::upgrade, size);
1 ✔
162
        return;
1 ✔
163
    }
164

165
    if (!ec)
×
166
    {
167
        request.get() = parser->release();
×
168

169
        // Dispatch of `verb::unknown` is reserved for websocket.
170
        if (request.get().method() == http::verb::unknown)
×
171
        {
172
            handler(error::bad_method, size);
×
173
            return;
×
174
        }
175
    }
176

177
    const auto code = error::http_to_error_code(ec);
×
178
    if (code == error::unknown) logx("http-read", ec);
×
179
    handler(code, size);
×
180
}
181

182
// HTTP/WS (write).
183
// ----------------------------------------------------------------------------
184

185
void socket::http_write(http::response&& response,
2 ✔
186
    count_handler&& handler) NOEXCEPT
187
{
188
    const auto out = move_shared(std::move(response));
189
    boost::asio::dispatch(strand_,
2 ✔
190
        std::bind(&socket::do_http_write, shared_from_this(),
4 ✔
191
            out, std::move(handler)));
192
}
2 ✔
193

194
// private
195
void socket::do_http_write(const http::response_ptr& response,
2 ✔
196
    const count_handler& handler) NOEXCEPT
197
{
198
    BC_ASSERT(stranded());
2 ✔
199
    async_write_http(std::move(*response), handler);
2 ✔
200
}
2 ✔
201

202
// private
203
void socket::handle_http_write(const boost_code& ec, size_t size,
2 ✔
204
    const http::response_ptr&, const count_handler& handler) NOEXCEPT
205
{
206
    BC_ASSERT(stranded());
2 ✔
207
    reclaim_buffer();
2 ✔
208

209
    if (error::asio_is_canceled(ec))
2 ✔
210
    {
211
        handler(error::channel_stopped, size);
×
212
        return;
×
213
    }
214

215
    const auto code = error::http_to_error_code(ec);
2 ✔
216
    if (code == error::unknown) logx("http-write", ec);
2 ✔
217
    handler(code, size);
2 ✔
218
}
219

220
// HTTP (progressive read).
221
// ----------------------------------------------------------------------------
222
// The caller owns the parser, which owns http framing (content length and
223
// chunk decoding) across the message. A batched json-rpc body delivers each
224
// message from the paused parse (need_buffer), mapped to success here.
225

226
void socket::http_read_header(http::flat_buffer& buffer, http_parser& parser,
1 ✔
227
    count_handler&& handler) NOEXCEPT
228
{
229
    boost::asio::dispatch(strand_,
1 ✔
230
        std::bind(&socket::do_http_read_header, shared_from_this(),
2 ✔
231
            std::ref(buffer), std::ref(parser), std::move(handler)));
1 ✔
232
}
1 ✔
233

234
// private
235
void socket::do_http_read_header(ref<http::flat_buffer> buffer,
1 ✔
236
    const ref<http_parser>& parser, const count_handler& handler) NOEXCEPT
237
{
238
    BC_ASSERT(stranded());
1 ✔
239

240
    try
241
    {
242
        // Websocket messages have no http headers.
243
        if (websocket())
1 ✔
244
        {
245
            handler(error::operation_failed, {});
×
246
            return;
×
247
        }
248

249
        auto& parse = parser.get();
250
        parse.body_limit(maximum_);
1 ✔
251
        parse.header_limit(limit<uint32_t>(maximum_));
1 ✔
252

253
        VARIANT_DISPATCH_FUNCTION(boost::beast::http::async_read_header,
4 ✔
254
            get_tcp(), buffer.get(), parse,
255
            std::bind(&socket::handle_http_read_header,
256
                shared_from_this(), _1, _2, parser, handler));
257
    }
258
    catch (const std::exception& e)
×
259
    {
260
        LOGF("Exception @ http_read_header: " << e.what());
×
261
        handler(error::operation_failed, {});
×
262
    }
×
263
}
264

265
// private
266
void socket::handle_http_read_header(const boost_code& ec, size_t size,
1 ✔
267
    const ref<http_parser>& parser, const count_handler& handler) NOEXCEPT
268
{
269
    BC_ASSERT(stranded());
1 ✔
270

271
    if (error::asio_is_canceled(ec))
1 ✔
272
    {
273
        handler(error::channel_stopped, size);
×
274
        return;
×
275
    }
276

277
    if (!ec && boost::beast::websocket::is_upgrade(parser.get().get()))
×
278
    {
279
        handler(error::upgrade, size);
×
280
        return;
×
281
    }
282

283
    // Dispatch of `verb::unknown` is reserved for websocket.
284
    if (!ec && parser.get().get().method() == http::verb::unknown)
×
285
    {
286
        handler(error::bad_method, size);
×
287
        return;
×
288
    }
289

290
    const auto code = error::http_to_error_code(ec);
1 ✔
291
    if (code == error::unknown) logx("http-read-header", ec);
1 ✔
292
    handler(code, size);
1 ✔
293
}
294

295
void socket::http_read_some(http::flat_buffer& buffer, http_parser& parser,
×
296
    count_handler&& handler) NOEXCEPT
297
{
298
    boost::asio::dispatch(strand_,
×
299
        std::bind(&socket::do_http_read_some, shared_from_this(),
×
300
            std::ref(buffer), std::ref(parser), std::move(handler)));
×
301
}
×
302

303
void socket::http_read_body(http::flat_buffer& buffer, http_parser& parser,
×
304
    count_handler&& handler) NOEXCEPT
305
{
306
    boost::asio::dispatch(strand_,
×
307
        std::bind(&socket::do_http_read_body, shared_from_this(),
×
308
            std::ref(buffer), std::ref(parser), std::move(handler)));
×
309
}
×
310

311
// private
312
void socket::do_http_read_body(ref<http::flat_buffer> buffer,
×
313
    const ref<http_parser>& parser, const count_handler& handler) NOEXCEPT
314
{
315
    BC_ASSERT(stranded());
×
316

317
    try
318
    {
319
        // Websocket messages have no http framing.
320
        if (websocket())
×
321
        {
322
            handler(error::operation_failed, {});
×
323
            return;
×
324
        }
325

326
        VARIANT_DISPATCH_FUNCTION(boost::beast::http::async_read,
×
327
            get_tcp(), buffer.get(), parser.get(),
328
            std::bind(&socket::handle_http_read_some,
329
                shared_from_this(), _1, _2, handler));
330
    }
331
    catch (const std::exception& e)
×
332
    {
333
        LOGF("Exception @ http_read_body: " << e.what());
×
334
        handler(error::operation_failed, {});
×
335
    }
×
336
}
337

338
// private
339
void socket::do_http_read_some(ref<http::flat_buffer> buffer,
×
340
    const ref<http_parser>& parser, const count_handler& handler) NOEXCEPT
341
{
342
    BC_ASSERT(stranded());
×
343

344
    try
345
    {
346
        // Websocket messages have no http framing.
347
        if (websocket())
×
348
        {
349
            handler(error::operation_failed, {});
×
350
            return;
×
351
        }
352

353
        VARIANT_DISPATCH_FUNCTION(boost::beast::http::async_read_some,
×
354
            get_tcp(), buffer.get(), parser.get(),
355
            std::bind(&socket::handle_http_read_some,
356
                shared_from_this(), _1, _2, handler));
357
    }
358
    catch (const std::exception& e)
×
359
    {
360
        LOGF("Exception @ http_read_some: " << e.what());
×
361
        handler(error::operation_failed, {});
×
362
    }
×
363
}
364

365
// private
366
void socket::handle_http_read_some(const boost_code& ec, size_t size,
×
367
    const count_handler& handler) NOEXCEPT
368
{
369
    BC_ASSERT(stranded());
×
370

371
    if (error::asio_is_canceled(ec))
×
372
    {
373
        handler(error::channel_stopped, size);
×
374
        return;
×
375
    }
376

377
    // A batched body reader delivers a message by pausing the parse, which
378
    // maps to error::need_buffer (distinguished from progress by caller).
379
    const auto code = error::http_to_error_code(ec);
×
380
    if (code == error::unknown) logx("http-read-some", ec);
×
381
    handler(code, size);
×
382
}
383

384
// HTTP (progressive write).
385
// ----------------------------------------------------------------------------
386
// The header is written once (chunked, no content length), and each response
387
// part is then written as chunk data, the batch close part terminating the
388
// chunked body. This mirrors the progressive read (nothing is materialized).
389

390
void socket::http_write_header(http::response&& response,
×
391
    count_handler&& handler) NOEXCEPT
392
{
393
    const auto out = emplace_shared<header_state>(std::move(response));
394
    boost::asio::dispatch(strand_,
×
395
        std::bind(&socket::do_http_write_header, shared_from_this(),
×
396
            out, std::move(handler)));
397
}
×
398

399
// private
400
void socket::do_http_write_header(const header_state::ptr& out,
×
401
    const count_handler& handler) NOEXCEPT
402
{
403
    BC_ASSERT(stranded());
×
404

405
    try
406
    {
407
        // Websocket messages have no http headers.
408
        if (websocket())
×
409
        {
410
            handler(error::operation_failed, {});
×
411
            return;
×
412
        }
413

414
        VARIANT_DISPATCH_FUNCTION(boost::beast::http::async_write_header,
×
415
            get_tcp(), out->serializer,
416
            std::bind(&socket::handle_http_write_header,
417
                shared_from_this(), _1, _2, out, handler));
418
    }
419
    catch (const std::exception& e)
×
420
    {
421
        LOGF("Exception @ http_write_header: " << e.what());
×
422
        handler(error::operation_failed, {});
×
423
    }
×
424
}
425

426
// private
427
void socket::handle_http_write_header(const boost_code& ec, size_t size,
×
428
    const header_state::ptr&, const count_handler& handler) NOEXCEPT
429
{
430
    BC_ASSERT(stranded());
×
431

432
    if (error::asio_is_canceled(ec))
×
433
    {
434
        handler(error::channel_stopped, size);
×
435
        return;
×
436
    }
437

438
    const auto code = error::http_to_error_code(ec);
×
439
    if (code == error::unknown) logx("http-write-header", ec);
×
440
    handler(code, size);
×
441
}
442

443
void socket::rpc_write_chunk(rpc::response&& response,
×
444
    count_handler&& handler) NOEXCEPT
445
{
446
    http::response wrapper{};
×
447
    wrapper.body() = std::move(response);
NEW
448
    assign_buffer(wrapper.body());
×
449

450
    boost_code ec{};
×
451
    const auto out = emplace_shared<chunk_state>(std::move(wrapper));
452
    out->writer.init(ec);
×
453

454
    boost::asio::dispatch(strand_,
×
455
        std::bind(&socket::do_chunk_write,
×
456
            shared_from_this(), ec, zero, out, std::move(handler)));
×
457
}
×
458

459
// private
460
void socket::do_chunk_write(boost_code ec, size_t total,
×
461
    const chunk_state::ptr& out, const count_handler& handler) NOEXCEPT
462
{
463
    BC_ASSERT(stranded());
×
464

465
    // Websocket messages have no http framing.
466
    if (websocket())
×
467
    {
468
        handler(error::operation_failed, total);
×
469
        return;
×
470
    }
471

472
    const auto buffer = ec ? chunk_state::out_buffer{} : out->writer.get(ec);
×
473
    if (!buffer.has_value())
×
474
    {
475
        handler(error::bad_stream, total);
×
476
        return;
×
477
    }
478

479
    if (ec)
×
480
    {
481
        const auto code = error::http_to_error_code(ec);
×
482
        if (code == error::unknown) logx("chunk-write", ec);
×
483
        handler(code, total);
×
484
        return;
485
    }
486

487
    out->more = buffer.value().second;
×
488
    const auto& data = buffer.value().first;
×
489

490
    try
491
    {
492
        // Frame the part buffer as http chunk data (chunk_state lifetime).
493
        out->part.emplace(boost::beast::http::make_chunk(data));
×
494

495
        VARIANT_DISPATCH_FUNCTION(boost::asio::async_write, get_tcp(),
×
496
            out->part.value(), std::bind(&socket::handle_chunk_write,
497
                shared_from_this(), _1, _2, total, out, handler));
498
    }
499
    catch (const std::exception& e)
×
500
    {
501
        LOGF("Exception @ chunk_write: " << e.what());
×
502
        handler(error::operation_failed, total);
×
503
    }
×
504
}
505

506
// private
507
void socket::handle_chunk_write(const boost_code& ec, size_t size,
×
508
    size_t total, const chunk_state::ptr& out,
509
    const count_handler& handler) NOEXCEPT
510
{
511
    BC_ASSERT(stranded());
×
512

513
    total = ceilinged_add(total, size);
×
514
    if (error::asio_is_canceled(ec))
×
515
    {
NEW
516
        reclaim_buffer();
×
517
        handler(error::channel_stopped, total);
×
518
        return;
×
519
    }
520

521
    if (ec)
×
522
    {
NEW
523
        reclaim_buffer();
×
524
        const auto code = error::asio_to_error_code(ec);
×
525
        if (code == error::unknown) logx("chunk-write", ec);
×
526
        handler(code, total);
×
527
        return;
528
    }
529

530
    if (out->more)
×
531
    {
532
        do_chunk_write({}, total, out, handler);
×
533
        return;
×
534
    }
535

NEW
536
    reclaim_buffer();
×
537

538
    // Only the batch close part terminates the chunked body.
539
    if (!out->last())
×
540
    {
541
        handler(error::success, total);
×
542
        return;
×
543
    }
544

545
    try
546
    {
547
        static constexpr std::string_view terminal{ "0\r\n\r\n" };
548
        const asio::const_buffer last{ terminal.data(), terminal.size() };
549

550
        VARIANT_DISPATCH_FUNCTION(boost::asio::async_write, get_tcp(),
×
551
            last, std::bind(&socket::handle_chunk_last,
552
                shared_from_this(), _1, _2, total, handler));
553
    }
554
    catch (const std::exception& e)
×
555
    {
556
        LOGF("Exception @ chunk_last: " << e.what());
×
557
        handler(error::operation_failed, total);
×
558
    }
×
559
}
560

561
// private
562
void socket::handle_chunk_last(const boost_code& ec, size_t size,
×
563
    size_t total, const count_handler& handler) NOEXCEPT
564
{
565
    BC_ASSERT(stranded());
×
566

567
    total = ceilinged_add(total, size);
568
    if (error::asio_is_canceled(ec))
×
569
    {
570
        handler(error::channel_stopped, total);
×
571
        return;
×
572
    }
573

574
    const auto code = error::asio_to_error_code(ec);
×
575
    if (code == error::unknown) logx("chunk-last", ec);
×
576
    handler(code, total);
×
577
}
578

579
BC_POP_WARNING()
580
BC_POP_WARNING()
581
BC_POP_WARNING()
582

583
} // namespace network
584
} // namespace libbitcoin
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc