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

libbitcoin / libbitcoin-network / 45308313741

24 Nov 2026 01:53AM UTC coverage: 94.184% (-0.02%) from 94.202%
45308313741

push

github

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

Move p2p user agent text from system, don't set in in ws.

16227 of 17229 relevant lines covered (94.18%)

2156.38 hits per line

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

90.5
/src/net/socket_ws.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/define.hpp>
22
#include <bitcoin/network/log/log.hpp>
23
#include <bitcoin/network/settings.hpp>
24
#include <bitcoin/network/ws/ws.hpp>
25

26
namespace libbitcoin {
27
namespace network {
28

29
using namespace system;
30
using namespace std::placeholders;
31

32
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
33
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
34

35
// WS (read).
36
// ----------------------------------------------------------------------------
37
// flat_buffer's max_size() must be large enough to hold complete ws framed
38
// message. Read fails if message exceeds this limit.
39

40
void socket::ws_read(http::flat_buffer& out,
5 ✔
41
    count_handler&& handler) NOEXCEPT
42
{
43
    io::dispatch(strand_,
5 ✔
44
        std::bind(&socket::do_ws_read,
10 ✔
45
            shared_from_this(), std::ref(out), std::move(handler)));
10 ✔
46
}
5 ✔
47

48
// private
49
void socket::do_ws_read(ref<http::flat_buffer> out,
5 ✔
50
    const count_handler& handler) NOEXCEPT
51
{
52
    BC_ASSERT(stranded());
5 ✔
53
    async_read(out.get(), handler);
5 ✔
54
}
5 ✔
55

56
// WS (write).
57
// ----------------------------------------------------------------------------
58

59
void socket::ws_write(const io::const_buffer& in, bool binary,
126 ✔
60
    count_handler&& handler) NOEXCEPT
61
{
62
    io::dispatch(strand_,
126 ✔
63
        std::bind(&socket::do_ws_write,
252 ✔
64
            shared_from_this(), in, binary, std::move(handler)));
252 ✔
65
}
126 ✔
66

67
// private
68
void socket::do_ws_write(const io::const_buffer& in, bool binary,
126 ✔
69
    const count_handler& handler) NOEXCEPT
70
{
71
    BC_ASSERT(stranded());
126 ✔
72
    async_write(in, binary, true, handler);
126 ✔
73
}
126 ✔
74

75
// WS (upgrade).
76
// ----------------------------------------------------------------------------
77

78
// The response is written before the upgrade (or refusal) is returned.
79
code socket::accept_websocket(const http::request& request) NOEXCEPT
27 ✔
80
{
81
    BC_ASSERT(stranded());
27 ✔
82
    BC_ASSERT(!websocket());
27 ✔
83

84
    ws::response response{};
27 ✔
85
    const auto ec = ws::accept(response, request.base());
27 ✔
86

87
    http::serializer<false, http::string_body> serializer{ response };
27 ✔
88
    data_chunk bytes{};
27 ✔
89
    code error{};
27 ✔
90
    while (!serializer.is_done() && !error)
54 ✔
91
        for (const auto& buffer: serializer.next(error))
57 ✔
92
            bytes.insert(bytes.end(), pointer_cast<const uint8_t>(
30 ✔
93
                buffer.data()), std::next(pointer_cast<const uint8_t>(
94
                    buffer.data()), buffer.size()));
57 ✔
95

96
    VARIANT_DISPATCH_FUNCTION(io::write, get_tcp(),
54 ✔
97
        io::buffer(bytes), error);
98

99
    if (error || ec)
27 ✔
100
        return error::operation_failed;
3 ✔
101

102
    ws_reader_.emplace(maximum_, true);
24 ✔
103
    ws_input_.clear();
24 ✔
104
    ws_continuing_ = false;
24 ✔
105
    ws_closing_ = false;
24 ✔
106
    websocket_.store(true);
24 ✔
107
    return error::success;
24 ✔
108
}
27 ✔
109

110
// WS (framing).
111
// ----------------------------------------------------------------------------
112
// Read assembles one data message, answering pings and peer's close.
113
// Frames written in order, so control frames queue behind data frames.
114

115
// private
116
void socket::do_ws_read_message(const ref<http::flat_buffer>& out,
24 ✔
117
    const count_handler& handler) NOEXCEPT
118
{
119
    BC_ASSERT(stranded());
24 ✔
120

121
    while (true)
122
    {
123
        ws::reader::event event{};
26 ✔
124
        code ec{};
26 ✔
125
        const auto data = ws_input_.data();
26 ✔
126
        const std::span<const uint8_t> bytes
127
        {
128
            pointer_cast<const uint8_t>(data.data()), data.size()
129
        };
26 ✔
130

131
        const auto used = ws_reader_->put(bytes, out.get(), event, ec);
26 ✔
132
        ws_input_.consume(used);
26 ✔
133

134
        if (ec == error::need_more)
26 ✔
135
            break;
136

137
        if (ec)
13 ✔
138
        {
139
            handler(ec, out.get().size());
×
140
            return;
11 ✔
141
        }
142

143
        const auto& payload = ws_reader_->control();
13 ✔
144
        switch (event)
13 ✔
145
        {
146
            case ws::reader::event::message:
10 ✔
147
                handler(error::success, out.get().size());
10 ✔
148
                return;
10 ✔
149
            case ws::reader::event::ping:
1 ✔
150
                do_ws_event(ws::opcode::ping, payload);
1 ✔
151
                ws_pong(payload);
1 ✔
152
                continue;
3 ✔
153
            case ws::reader::event::pong:
1 ✔
154
                do_ws_event(ws::opcode::pong, payload);
1 ✔
155
                continue;
1 ✔
156
            case ws::reader::event::close:
1 ✔
157
            {
158
                do_ws_event(ws::opcode::close, payload);
1 ✔
159
                if (ws_closing_)
1 ✔
160
                {
161
                    handler(error::websocket_closed, out.get().size());
×
162
                    return;
×
163
                }
164

165
                // The close is answered with the peer's close code.
166
                ws_closing_ = true;
1 ✔
167
                const auto echo_size = payload.size() < two ? zero : two;
1 ✔
168
                const auto echo_end = std::next(payload.begin(), echo_size);
1 ✔
169
                const data_chunk echo{ payload.begin(), echo_end };
1 ✔
170

171
                ws_send(ws::opcode::close, echo,
1 ✔
172
                    std::bind(&socket::handle_ws_echo,
2 ✔
173
                        shared_from_this(), _1, _2, out, handler));
2 ✔
174
                return;
175
            }
1 ✔
176
            case ws::reader::event::none:
×
177
            default:
178
                continue;
×
179
        }
2 ✔
180
    }
2 ✔
181

182
    const auto limit = floored_subtract(ws_input_.max_size(),
13 ✔
183
        ws_input_.size());
13 ✔
184
    const auto size = std::min(limit, std::max(ws_input_.capacity() -
26 ✔
185
        ws_input_.size(), header_));
13 ✔
186

187
    try
188
    {
189
        VARIANT_DISPATCH_METHOD(get_tcp(),
26 ✔
190
            async_read_some(ws_input_.prepare(size),
191
                std::bind(&socket::handle_ws_read_message,
192
                    shared_from_this(), _1, _2, out, handler)));
193
    }
194
    catch (const std::exception& e)
×
195
    {
196
        LOGF("Exception @ ws_read: " << e.what());
×
197
        handler(error::operation_failed, {});
×
198
    }
×
199
}
200

201
// private
202
void socket::handle_ws_read_message(const code& ec, size_t size,
13 ✔
203
    const ref<http::flat_buffer>& out, const count_handler& handler) NOEXCEPT
204
{
205
    BC_ASSERT(stranded());
13 ✔
206

207
    if (ec == error::operation_canceled)
13 ✔
208
    {
209
        handler(error::channel_stopped, out.get().size());
×
210
        return;
×
211
    }
212

213
    if (ec)
13 ✔
214
    {
215
        if (ec == error::unknown) logx("ws-read", ec);
×
216
        handler(ec, out.get().size());
×
217
        return;
×
218
    }
219

220
    ws_input_.commit(size);
13 ✔
221
    do_ws_read_message(out, handler);
13 ✔
222
}
223

224
// private
225
// Server closes connection once closing handshake is complete.
226
void socket::handle_ws_echo(const code&, size_t,
1 ✔
227
    const ref<http::flat_buffer>& out, const count_handler& handler) NOEXCEPT
228
{
229
    BC_ASSERT(stranded());
1 ✔
230

231
    code ignore{};
1 ✔
232
    get_base().shutdown(io::socket::shutdown_type::send, ignore);
1 ✔
233
    handler(error::websocket_closed, out.get().size());
1 ✔
234
}
1 ✔
235

236
// private
237
// Data frame continues message of preceding unfinished frame.
238
void socket::ws_send_data(const io::const_buffer& data, bool binary,
133 ✔
239
    bool finish, const count_handler& handler) NOEXCEPT
240
{
241
    BC_ASSERT(stranded());
133 ✔
242

243
    const auto code = ws_continuing_ ? ws::opcode::continuation :
133 ✔
244
        (binary ? ws::opcode::binary : ws::opcode::text);
8 ✔
245

246
    ws_continuing_ = !finish;
133 ✔
247
    const auto frame = emplace_shared<ws_frame>();
133 ✔
248
    frame->header = ws::serialize_header(code, finish,
266 ✔
249
        possible_wide_cast<uint64_t>(data.size()));
133 ✔
250
    frame->data = data;
133 ✔
251
    frame->handler = handler;
133 ✔
252
    frame->finish = finish;
133 ✔
253
    ws_queue_.push_back(frame);
133 ✔
254
    ws_write_next();
133 ✔
255
}
133 ✔
256

257
// private
258
void socket::ws_send(ws::opcode code, const data_chunk& payload,
3 ✔
259
    const count_handler& handler) NOEXCEPT
260
{
261
    BC_ASSERT(stranded());
3 ✔
262

263
    const auto frame = emplace_shared<ws_frame>();
3 ✔
264
    frame->header = ws::serialize_header(code, true,
6 ✔
265
        possible_wide_cast<uint64_t>(payload.size()));
3 ✔
266
    frame->payload = payload;
3 ✔
267
    frame->handler = handler;
3 ✔
268
    frame->control = true;
3 ✔
269
    ws_queue_.push_back(frame);
3 ✔
270
    ws_write_next();
3 ✔
271
}
3 ✔
272

273
// private
274
// Unsent pong answers only most recent ping (rfc6455 5.5.3).
275
void socket::ws_pong(const data_chunk& payload) NOEXCEPT
1 ✔
276
{
277
    BC_ASSERT(stranded());
1 ✔
278

279
    const auto queued = !is_null(ws_pong_);
1 ✔
280
    if (!queued)
1 ✔
281
    {
282
        ws_pong_ = emplace_shared<ws_frame>();
1 ✔
283
        ws_pong_->control = true;
1 ✔
284
    }
285

286
    ws_pong_->header = ws::serialize_header(ws::opcode::pong, true,
2 ✔
287
        possible_wide_cast<uint64_t>(payload.size()));
1 ✔
288
    ws_pong_->payload = payload;
1 ✔
289

290
    if (!queued)
1 ✔
291
    {
292
        ws_queue_.push_back(ws_pong_);
1 ✔
293
        ws_write_next();
1 ✔
294
    }
295
}
1 ✔
296

297
// private
298
void socket::ws_write_next() NOEXCEPT
274 ✔
299
{
300
    BC_ASSERT(stranded());
274 ✔
301

302
    if (ws_writing_ || ws_queue_.empty())
274 ✔
303
        return;
137 ✔
304

305
    ws_writing_ = true;
137 ✔
306
    const auto frame = ws_queue_.front();
137 ✔
307
    if (frame == ws_pong_)
137 ✔
308
        ws_pong_.reset();
1 ✔
309
    const auto payload = frame->payload.empty() ? frame->data :
137 ✔
310
        io::const_buffer{ frame->payload.data(), frame->payload.size() };
137 ✔
311

312
    frame->buffers =
274 ✔
313
    {
314
        io::const_buffer{ frame->header.data(), frame->header.size() },
137 ✔
315
        payload
316
    };
317

318
    const count_handler complete = std::bind(&socket::handle_ws_frame,
274 ✔
319
        shared_from_this(), _1, _2, frame);
411 ✔
320

321
    if (frame->control)
137 ✔
322
        interject(frame->buffers, complete);
4 ✔
323
    else
324
        transmit(frame->buffers, frame->finish, complete);
133 ✔
325
}
137 ✔
326

327
// private
328
void socket::handle_ws_frame(const code& ec, size_t,
137 ✔
329
    const ws_frame::ptr& frame) NOEXCEPT
330
{
331
    BC_ASSERT(stranded());
137 ✔
332

333
    ws_writing_ = false;
137 ✔
334
    ws_queue_.pop_front();
137 ✔
335
    const auto canceled = (ec == error::operation_canceled);
137 ✔
336
    const auto code = canceled ? error::channel_stopped : ec;
137 ✔
337

338
    if (code == error::unknown)
137 ✔
339
        logx("ws-write", ec);
×
340

341
    // Failed write fails frames that follow it. These are removed before any
342
    // handler runs, as handler may queue (and write) another frame.
343
    std::deque<ws_frame::ptr> failed{};
137 ✔
344
    if (code)
137 ✔
345
    {
346
        ws_pong_.reset();
×
347
        std::swap(failed, ws_queue_);
×
348
    }
349

350
    // The payload size is reported (as with stream writes).
351
    const auto size = frame->payload.empty() ? frame->data.size() :
137 ✔
352
        frame->payload.size();
4 ✔
353

354
    if (frame->handler)
137 ✔
355
        frame->handler(code, size);
136 ✔
356

357
    for (const auto& next: failed)
137 ✔
358
        if (next->handler)
×
359
            next->handler(code, zero);
×
360

361
    if (!code)
137 ✔
362
        ws_write_next();
137 ✔
363
}
137 ✔
364

365
// WS (events).
366
// ----------------------------------------------------------------------------
367

368
// private
369
void socket::do_ws_event(ws::opcode kind, const data_chunk& data) NOEXCEPT
3 ✔
370
{
371
    BC_ASSERT(stranded());
3 ✔
372

373
    switch (kind)
3 ✔
374
    {
375
        case ws::opcode::ping:
1 ✔
376
            LOGX("WS ping [" << endpoint() << "] size: " << data.size());
1 ✔
377
            break;
378
        case ws::opcode::pong:
1 ✔
379
            LOGX("WS pong [" << endpoint() << "] size: " << data.size());
1 ✔
380
            break;
381
        case ws::opcode::close:
1 ✔
382
        {
383
            uint16_t value{};
1 ✔
384
            std::string reason{};
1 ✔
385
            code ignore{};
1 ✔
386
            ws::parse_close(value, reason, data, ignore);
1 ✔
387
            LOGX("WS close [" << endpoint() << "] " << value << " "
1 ✔
388
                << reason);
389
            break;
390
        }
1 ✔
391
        default:
392
            break;
393
    }
394
}
3 ✔
395

396
BC_POP_WARNING()
397
BC_POP_WARNING()
398

399
} // namespace network
400
} // 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