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

libbitcoin / libbitcoin-network / 44022301104

17 Nov 2026 05:11AM UTC coverage: 93.977% (-0.2%) from 94.161%
44022301104

push

github

web-flow
Merge pull request #1039 from pmienk/master

Regenerate artifacts.

15307 of 16288 relevant lines covered (93.98%)

2415.25 hits per line

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

83.45
/src/io/socket.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/io/socket.hpp>
20

21
#include <atomic>
22
#include <bitcoin/network/define.hpp>
23
#include "backend.hpp"
24
#include "native.hpp"
25

26
namespace libbitcoin {
27
namespace network {
28
namespace io {
29

30
using namespace system;
31
using namespace detail;
32

33
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
34
BC_PUSH_WARNING(NO_REINTERPRET_CAST)
35

36
#if defined(HAVE_WINDOWS)
37
    constexpr int shutdown_receive = SD_RECEIVE;
38
    constexpr int shutdown_send = SD_SEND;
39
    constexpr int shutdown_both = SD_BOTH;
40
    constexpr int send_flags = 0;
41
#else
42
    constexpr int shutdown_receive = SHUT_RD;
43
    constexpr int shutdown_send = SHUT_WR;
44
    constexpr int shutdown_both = SHUT_RDWR;
45
#if defined(MSG_NOSIGNAL)
46
    constexpr int send_flags = MSG_NOSIGNAL;
47
#else
48
    constexpr int send_flags = 0;
49
#endif
50
#endif
51

52
static descriptor_ptr make_descriptor(const executor& executor) NOEXCEPT
2,004 ✔
53
{
54
    return std::make_shared<descriptor>(executor.context().scheduler());
2,004 ✔
55
}
56

57
static detail::backend& backend_of(const executor& executor) NOEXCEPT
81,657 ✔
58
{
59
    return executor.context().scheduler().backend();
81,657 ✔
60
}
61

62
static code native_code() NOEXCEPT
192 ✔
63
{
64
    return to_code(last_error());
192 ✔
65
}
66

67
template <typename Option>
68
static code set_socket_option(native_socket socket, int level, int name,
658 ✔
69
    Option value) NOEXCEPT
70
{
71
    if (::setsockopt(socket, level, name, pointer_cast<const char>(&value),
658 ✔
72
        sizeof(value)) != 0)
73
        return native_code();
×
74

75
    return error::success;
658 ✔
76
}
77

78
// Deliver the result on the executor (never within the initiating call).
79
static void post_result(const executor& executor,
22 ✔
80
    const socket::io_handler& handler, const code& ec) NOEXCEPT
81
{
82
    executor.post([handler, ec]() NOEXCEPT
22 ✔
83
    {
84
        handler(ec, zero);
22 ✔
85
    });
22 ✔
86
}
22 ✔
87

88
template <typename Buffers>
89
static size_t total_size(const Buffers& buffers) NOEXCEPT
84,549 ✔
90
{
91
    size_t total{};
92
    for (const auto& buffer: buffers)
169,363 ✔
93
        total = ceilinged_add(total, buffer.size());
84,814 ✔
94

95
    return total;
84,549 ✔
96
}
97

98
#if defined(HAVE_WINDOWS)
99
template <typename Buffers>
100
static std::vector<WSABUF> to_native(const Buffers& buffers) NOEXCEPT
101
{
102
    std::vector<WSABUF> out{};
103
    out.reserve(buffers.size());
104
    for (const auto& buffer: buffers)
105
        out.push_back(
106
        {
107
            possible_narrow_cast<ULONG>(buffer.size()),
108
            pointer_cast<CHAR>(const_cast<void*>(buffer.data()))
109
        });
110

111
    return out;
112
}
113
#else
114
template <typename Buffers>
115
static std::vector<iovec> to_native(const Buffers& buffers) NOEXCEPT
6,472 ✔
116
{
117
    std::vector<iovec> out{};
6,472 ✔
118
    out.reserve(buffers.size());
6,472 ✔
119
    for (const auto& buffer: buffers)
12,944 ✔
120
        out.push_back(
6,472 ✔
121
        {
122
            const_cast<void*>(static_cast<const void*>(buffer.data())),
6,472 ✔
123
            buffer.size()
6,472 ✔
124
        });
125

126
    return out;
6,472 ✔
127
}
×
128
#endif
129

130
// tcp
131
// ----------------------------------------------------------------------------
132

133
tcp::tcp(bool v6) NOEXCEPT
1,133 ✔
134
  : v6_(v6)
1,133 ✔
135
{
136
}
1,133 ✔
137

138
tcp tcp::v4() NOEXCEPT
127 ✔
139
{
140
    return tcp{ false };
127 ✔
141
}
142

143
tcp tcp::v6() NOEXCEPT
×
144
{
145
    return tcp{ true };
×
146
}
147

148
tcp tcp::of(const endpoint& point) NOEXCEPT
1,006 ✔
149
{
150
    return tcp{ point.address().is_v6() };
1,006 ✔
151
}
152

153
bool tcp::is_v6() const NOEXCEPT
1,133 ✔
154
{
155
    return v6_;
1,133 ✔
156
}
157

158
// socket
159
// ----------------------------------------------------------------------------
160

161
socket::socket(const executor& executor) NOEXCEPT
1,207 ✔
162
  : executor_(executor), descriptor_(make_descriptor(executor))
1,207 ✔
163
{
164
}
1,207 ✔
165

166
socket::socket(socket&& other) NOEXCEPT
175 ✔
167
  : executor_(other.executor_), descriptor_(std::move(other.descriptor_))
175 ✔
168
{
169
    other.descriptor_ = make_descriptor(other.executor_);
175 ✔
170
}
175 ✔
171

172
socket& socket::operator=(socket&& other) NOEXCEPT
×
173
{
174
    if (this != &other)
×
175
    {
176
        code ignore{};
×
177
        close(ignore);
×
178
        executor_ = other.executor_;
×
179
        descriptor_ = std::move(other.descriptor_);
×
180
        other.descriptor_ = make_descriptor(other.executor_);
×
181
    }
182

183
    return *this;
×
184
}
185

186
socket::~socket() NOEXCEPT
1,382 ✔
187
{
188
    code ignore{};
1,382 ✔
189
    close(ignore);
1,382 ✔
190
}
1,382 ✔
191

192
socket::executor_type socket::get_executor() const NOEXCEPT
63 ✔
193
{
194
    return executor_;
63 ✔
195
}
196

197
bool socket::is_open() const NOEXCEPT
82,728 ✔
198
{
199
    return descriptor_->handle != invalid_socket;
82,728 ✔
200
}
201

202
socket::native_handle_type socket::native_handle() const NOEXCEPT
1 ✔
203
{
204
    return static_cast<native_handle_type>(descriptor_->handle);
1 ✔
205
}
206

207
void socket::open(const tcp& protocol, code& ec) NOEXCEPT
531 ✔
208
{
209
    if (is_open())
531 ✔
210
    {
211
        ec = error::connect_failed;
×
212
        return;
×
213
    }
214

215
    int native{};
531 ✔
216
    backend_of(executor_).open(descriptor_, protocol.is_v6(), native);
531 ✔
217
    ec = to_code(native);
531 ✔
218
}
219

220
void socket::bind(const endpoint& point, code& ec) NOEXCEPT
32 ✔
221
{
222
    const auto address = to_socket_address(point);
32 ✔
223
    if (!is_zero(::bind(descriptor_->handle, address.data(), address.size)))
32 ✔
224
    {
225
        ec = native_code();
1 ✔
226
        return;
1 ✔
227
    }
228

229
    descriptor_->bound = true;
31 ✔
230
    ec = error::success;
31 ✔
231
}
232

233
void socket::close(code& ec) NOEXCEPT
2,608 ✔
234
{
235
    if (is_open())
2,608 ✔
236
        backend_of(executor_).close(*descriptor_);
1,011 ✔
237

238
    ec = error::success;
2,608 ✔
239
}
2,608 ✔
240

241
void socket::close() NOEXCEPT
216 ✔
242
{
243
    code ignore{};
216 ✔
244
    close(ignore);
216 ✔
245
}
216 ✔
246

247
void socket::cancel(code& ec) NOEXCEPT
4 ✔
248
{
249
    if (!is_open())
4 ✔
250
    {
251
        ec = error::bad_stream;
×
252
        return;
×
253
    }
254

255
    backend_of(executor_).cancel(*descriptor_);
4 ✔
256
    ec = error::success;
4 ✔
257
}
258

259
void socket::shutdown(shutdown_type what, code& ec) NOEXCEPT
609 ✔
260
{
261
    const auto how = what == shutdown_type::receive ? shutdown_receive :
609 ✔
262
        (what == shutdown_type::send ? shutdown_send : shutdown_both);
263

264
    ec = !is_zero(::shutdown(descriptor_->handle, how)) ? native_code() :
609 ✔
265
        code{ error::success };
266
}
609 ✔
267

268
void socket::set_option(const no_delay& option, code& ec) NOEXCEPT
387 ✔
269
{
270
    ec = set_socket_option(descriptor_->handle, IPPROTO_TCP, TCP_NODELAY,
387 ✔
271
        to_int(option.value));
387 ✔
272
}
387 ✔
273

274
void socket::set_option(const keep_alive& option, code& ec) NOEXCEPT
×
275
{
276
    ec = set_socket_option(descriptor_->handle, SOL_SOCKET, SO_KEEPALIVE,
×
277
        to_int(option.value));
×
278
}
×
279

280
void socket::non_blocking(bool value, code& ec) NOEXCEPT
3 ✔
281
{
282
    // Posix sockets are always nonblocking (blocking calls wait on poll).
283
#if defined(HAVE_WINDOWS)
284
    int native{};
285
    if (!set_blocking(descriptor_->handle, !value, native))
286
    {
287
        ec = to_code(native);
288
        return;
289
    }
290
#endif
291

292
    descriptor_->non_blocking = value;
3 ✔
293
    ec = error::success;
3 ✔
294
}
3 ✔
295

296
bool socket::non_blocking() const NOEXCEPT
1 ✔
297
{
298
    return descriptor_->non_blocking;
1 ✔
299
}
300

301
size_t socket::available(code& ec) const NOEXCEPT
1 ✔
302
{
303
#if defined(HAVE_WINDOWS)
304
    u_long count{};
305
    if (!is_zero(::ioctlsocket(descriptor_->handle, FIONREAD, &count)))
306
#else
307
    int count{};
1 ✔
308
    if (!is_zero(::ioctl(descriptor_->handle, FIONREAD, &count)))
1 ✔
309
#endif
310
    {
311
        ec = native_code();
×
312
        return zero;
×
313
    }
314

315
    ec = error::success;
1 ✔
316
#if defined(HAVE_WINDOWS)
317
    return possible_wide_cast<size_t>(count);
318
#else
319
    return possible_wide_cast<size_t>(sign_cast<unsigned int>(count));
1 ✔
320
#endif
321
}
322

323
endpoint socket::local_endpoint(code& ec) const NOEXCEPT
441 ✔
324
{
325
    socket_address address{};
441 ✔
326
    address.size = sizeof(address.storage);
441 ✔
327
    const auto handle = descriptor_->handle;
441 ✔
328
    if (!is_zero(::getsockname(handle, address.data(), &address.size)))
441 ✔
329
    {
330
        ec = native_code();
×
331
        return {};
×
332
    }
333

334
    ec = error::success;
441 ✔
335
    return to_endpoint(address.data());
441 ✔
336
}
337

338
endpoint socket::remote_endpoint(code& ec) const NOEXCEPT
307 ✔
339
{
340
    socket_address address{};
307 ✔
341
    address.size = sizeof(address.storage);
307 ✔
342
    const auto handle = descriptor_->handle;
307 ✔
343
    if (!is_zero(::getpeername(handle, address.data(), &address.size)))
307 ✔
344
    {
345
        ec = native_code();
×
346
        return {};
×
347
    }
348

349
    ec = error::success;
307 ✔
350
    return to_endpoint(address.data());
307 ✔
351
}
352

353
endpoint socket::local_endpoint() const NOEXCEPT
34 ✔
354
{
355
    code ignore{};
34 ✔
356
    return local_endpoint(ignore);
34 ✔
357
}
358

359
endpoint socket::remote_endpoint() const NOEXCEPT
4 ✔
360
{
361
    code ignore{};
4 ✔
362
    return remote_endpoint(ignore);
4 ✔
363
}
364

365
bool socket::half_closed() const NOEXCEPT
14 ✔
366
{
367
    if (!is_open())
14 ✔
368
        return false;
369

370
#if defined(HAVE_WINDOWS)
371
    TCP_INFO_v0 info{};
372
    DWORD version{};
373
    DWORD size{};
374
    if (is_zero(::WSAIoctl(descriptor_->handle, SIO_TCP_INFO, &version,
375
        sizeof(version), &info, sizeof(info), &size, nullptr, nullptr)))
376
        return info.State == TCPSTATE_CLOSE_WAIT ||
377
            info.State == TCPSTATE_CLOSED;
378

379
#elif defined(HAVE_APPLE)
380
    struct tcp_connection_info info{};
381
    socklen_t size = sizeof(info);
382
    if (is_zero(::getsockopt(descriptor_->handle, IPPROTO_TCP,
383
        TCP_CONNECTION_INFO, &info, &size)))
384
        return info.tcpi_state == TCPS_CLOSE_WAIT ||
385
            (info.tcpi_state == TCPS_CLOSED && !is_zero(info.tcpi_srtt));
386

387
#elif defined(HAVE_LINUX)
388
    constexpr auto minimum = possible_narrow_cast<socklen_t>(
389
        offsetof(tcp_info, tcpi_rcv_mss) + sizeof(tcp_info::tcpi_rcv_mss));
390

391
    struct tcp_info info{};
13 ✔
392
    socklen_t size = sizeof(info);
13 ✔
393
    if (is_zero(::getsockopt(descriptor_->handle, IPPROTO_TCP, TCP_INFO,
13 ✔
394
        &info, &size)) && size >= minimum)
13 ✔
395
        return info.tcpi_state == TCP_CLOSE_WAIT ||
13 ✔
396
            (info.tcpi_state == TCP_CLOSE && !is_zero(info.tcpi_rcv_mss));
2 ✔
397

398
    pollfd peer{ descriptor_->handle, POLLRDHUP, 0 };
×
399
    if (is_one(::poll(&peer, 1, 0)))
×
400
        return is_nonzero(peer.revents & POLLRDHUP);
×
401

402
#elif defined(HAVE_BSD)
403
    struct tcp_info info{};
404
    socklen_t size = sizeof(info);
405
    if (is_zero(::getsockopt(descriptor_->handle, IPPROTO_TCP, TCP_INFO,
406
        &info, &size)))
407
        return info.tcpi_state == TCPS_CLOSE_WAIT;
408

409
    if (last_error() == ECONNRESET)
410
        return true;
411
#endif
412
    return false;
413
}
414

415
void socket::async_connect(const endpoint& point,
191 ✔
416
    result_handler&& handler) NOEXCEPT
417
{
418
    io_handler completion =
419
        [handler = std::move(handler)](const code& ec, size_t) NOEXCEPT
382 ✔
420
        {
421
            handler(ec);
191 ✔
422
        };
191 ✔
423

424
    if (!is_open())
191 ✔
425
    {
426
        code ec{};
188 ✔
427
        open(tcp::of(point), ec);
188 ✔
428
        if (ec)
188 ✔
429
        {
430
            post_result(executor_, completion, ec);
×
431
            return;
×
432
        }
433
    }
434

435
    constexpr auto kind = operation::kind::connect;
436
    const auto op = new operation{ kind, descriptor_, executor_ };
191 ✔
437
    op->target = to_socket_address(point);
191 ✔
438
    op->handler = std::move(completion);
191 ✔
439
    backend_of(executor_).start(op);
191 ✔
440
}
191 ✔
441

442
void socket::do_read(mutable_buffers&& buffers, io_handler&& handler) NOEXCEPT
77,040 ✔
443
{
444
    if (!is_open())
77,040 ✔
445
    {
446
        post_result(executor_, handler, error::bad_stream);
11 ✔
447
        return;
11 ✔
448
    }
449

450
    constexpr auto kind = operation::kind::read;
451
    const auto op = new operation{ kind, descriptor_, executor_ };
77,029 ✔
452
    op->handler = std::move(handler);
77,029 ✔
453
    op->requested = total_size(buffers);
77,029 ✔
454
#if defined(HAVE_WINDOWS)
455
    op->buffers = to_native(buffers);
456
#else
457
    op->in = std::move(buffers);
77,029 ✔
458
#endif
459
    backend_of(executor_).start(op);
77,029 ✔
460
}
461

462
void socket::do_write(const_buffers&& buffers, io_handler&& handler) NOEXCEPT
1,058 ✔
463
{
464
    if (!is_open())
1,058 ✔
465
    {
466
        post_result(executor_, handler, error::bad_stream);
10 ✔
467
        return;
10 ✔
468
    }
469

470
    constexpr auto kind = operation::kind::write;
471
    const auto op = new operation{ kind, descriptor_, executor_ };
1,048 ✔
472
    op->handler = std::move(handler);
1,048 ✔
473
    op->requested = total_size(buffers);
1,048 ✔
474
#if defined(HAVE_WINDOWS)
475
    op->buffers = to_native(buffers);
476
#else
477
    op->out = std::move(buffers);
1,048 ✔
478
#endif
479
    backend_of(executor_).start(op);
1,048 ✔
480
}
481

482
// Synchronous.
483
// ----------------------------------------------------------------------------
484

485
void socket::connect(const endpoint& point, code& ec) NOEXCEPT
309 ✔
486
{
487
    if (!is_open())
309 ✔
488
    {
489
        open(tcp::of(point), ec);
309 ✔
490
        if (ec)
309 ✔
491
            return;
×
492
    }
493

494
    const auto address = to_socket_address(point);
309 ✔
495
    const auto handle = descriptor_->handle;
309 ✔
496
    if (is_zero(::connect(handle, address.data(), address.size)))
309 ✔
497
    {
498
        ec = error::success;
×
499
        return;
×
500
    }
501

502
    auto native = last_error();
309 ✔
503
    if (!is_in_progress(native) || descriptor_->non_blocking)
309 ✔
504
    {
505
        ec = to_code(native);
×
506
        return;
×
507
    }
508

509
    if (!wait_ready(handle, true, native))
309 ✔
510
    {
511
        ec = to_code(native);
×
512
        return;
×
513
    }
514

515
    int result{};
309 ✔
516
    socklen_t size = sizeof(result);
309 ✔
517
    const auto value = pointer_cast<char>(&result);
309 ✔
518
    if (!is_zero(::getsockopt(handle, SOL_SOCKET, SO_ERROR, value, &size)))
309 ✔
519
        result = last_error();
×
520

521
    ec = to_code(result);
309 ✔
522
}
523

524
size_t socket::do_read_some(const mutable_buffers& buffers, code& ec) NOEXCEPT
5,738 ✔
525
{
526
    const auto requested = total_size(buffers);
5,738 ✔
527
    if (is_zero(requested))
5,738 ✔
528
    {
529
        ec = error::success;
×
530
        return zero;
×
531
    }
532

533
    auto native_buffers = to_native(buffers);
5,738 ✔
534
    while (true)
535
    {
536
#if defined(HAVE_WINDOWS)
537
        DWORD bytes{};
538
        DWORD flags{};
539
        const auto result = ::WSARecv(descriptor_->handle,
540
            native_buffers.data(),
541
            possible_narrow_cast<DWORD>(native_buffers.size()),
542
            &bytes, &flags, nullptr, nullptr);
543

544
        const auto failed = result == SOCKET_ERROR;
545
        const size_t count = bytes;
546
#else
547
        const auto result = ::readv(descriptor_->handle, native_buffers.data(),
6,615 ✔
548
            possible_narrow_sign_cast<int>(native_buffers.size()));
549

550
        const auto failed = is_negative(result);
6,615 ✔
551
        const auto count = failed ? zero :
6,615 ✔
552
            possible_narrow_sign_cast<size_t>(result);
5,736 ✔
553
#endif
554
        if (!failed)
6,615 ✔
555
        {
556
            ec = is_zero(count) ? error::peer_disconnect : error::success;
11,413 ✔
557
            return count;
5,736 ✔
558
        }
559

560
        auto native = last_error();
879 ✔
561
#if !defined(HAVE_WINDOWS)
562
        if (native == EINTR)
879 ✔
563
            continue;
×
564
#endif
565
        if (is_would_block(native) && !descriptor_->non_blocking &&
1,756 ✔
566
            wait_ready(descriptor_->handle, false, native))
877 ✔
567
            continue;
877 ✔
568

569
        ec = to_code(native);
2 ✔
570
        return zero;
571
    }
877 ✔
572
}
5,738 ✔
573

574
size_t socket::do_write_some(const const_buffers& buffers, code& ec) NOEXCEPT
734 ✔
575
{
576
    const auto requested = total_size(buffers);
734 ✔
577
    if (is_zero(requested))
734 ✔
578
    {
579
        ec = error::success;
×
580
        return zero;
×
581
    }
582

583
    const auto handle = descriptor_->handle;
734 ✔
584
    auto native_buffers = to_native(buffers);
734 ✔
585
    while (true)
586
    {
587
#if defined(HAVE_WINDOWS)
588
        DWORD bytes{};
589
        const auto result = ::WSASend(handle,
590
            native_buffers.data(),
591
            possible_narrow_cast<DWORD>(native_buffers.size()), &bytes,
592
            send_flags, nullptr, nullptr);
593

594
        const auto failed = result == SOCKET_ERROR;
595
        const size_t count = bytes;
596
#else
597
        msghdr message{};
734 ✔
598
        message.msg_iov = native_buffers.data();
734 ✔
599
        message.msg_iovlen = native_buffers.size();
734 ✔
600
        const auto result = ::sendmsg(handle, &message, send_flags);
734 ✔
601

602
        const auto failed = is_negative(result);
734 ✔
603
        const auto count = failed ? zero :
734 ✔
604
            possible_narrow_sign_cast<size_t>(result);
734 ✔
605
#endif
606
        if (!failed)
734 ✔
607
        {
608
            ec = error::success;
734 ✔
609
            return count;
734 ✔
610
        }
611

612
        auto native = last_error();
×
613
#if !defined(HAVE_WINDOWS)
614
        if (native == EINTR)
×
615
            continue;
×
616
#endif
617
        if (is_would_block(native) && !descriptor_->non_blocking &&
×
618
            wait_ready(descriptor_->handle, true, native))
×
619
            continue;
×
620

621
        ec = to_code(native);
×
622
        return zero;
623
    }
×
624
}
734 ✔
625

626
// acceptor
627
// ----------------------------------------------------------------------------
628

629
acceptor::acceptor(const executor& executor) NOEXCEPT
622 ✔
630
  : executor_(executor), descriptor_(make_descriptor(executor))
622 ✔
631
{
632
}
622 ✔
633

634
acceptor::acceptor(const executor& executor, const endpoint& point) NOEXCEPT
94 ✔
635
  : acceptor(executor)
94 ✔
636
{
637
    code ec{};
94 ✔
638
    open(tcp::of(point), ec);
94 ✔
639
    if (!ec) set_option(reuse_address{ true }, ec);
94 ✔
640
    if (!ec) bind(point, ec);
94 ✔
641
    if (!ec) listen(ec);
94 ✔
642
    if (ec) close(ec);
94 ✔
643
}
94 ✔
644

645
acceptor::~acceptor() NOEXCEPT
622 ✔
646
{
647
    code ignore{};
622 ✔
648
    close(ignore);
622 ✔
649
}
622 ✔
650

651
acceptor::executor_type acceptor::get_executor() const NOEXCEPT
×
652
{
653
    return executor_;
×
654
}
655

656
bool acceptor::is_open() const NOEXCEPT
2,131 ✔
657
{
658
    return descriptor_->handle != invalid_socket;
2,131 ✔
659
}
660

661
acceptor::native_handle_type acceptor::native_handle() const NOEXCEPT
×
662
{
663
    return static_cast<native_handle_type>(descriptor_->handle);
×
664
}
665

666
void acceptor::open(const tcp& protocol, code& ec) NOEXCEPT
602 ✔
667
{
668
    if (is_open())
602 ✔
669
    {
670
        ec = error::connect_failed;
×
671
        return;
×
672
    }
673

674
    int native{};
602 ✔
675
    backend_of(executor_).open(descriptor_, protocol.is_v6(), native);
602 ✔
676
    ec = to_code(native);
602 ✔
677
}
678

679
void acceptor::set_option(const reuse_address& option, code& ec) NOEXCEPT
268 ✔
680
{
681
    ec = set_socket_option(descriptor_->handle, SOL_SOCKET, SO_REUSEADDR,
268 ✔
682
        to_int(option.value));
268 ✔
683
}
268 ✔
684

685
void acceptor::set_option(const v6_only& option, code& ec) NOEXCEPT
3 ✔
686
{
687
    ec = set_socket_option(descriptor_->handle, IPPROTO_IPV6, IPV6_V6ONLY,
3 ✔
688
        to_int(option.value));
3 ✔
689
}
3 ✔
690

691
void acceptor::bind(const endpoint& point, code& ec) NOEXCEPT
602 ✔
692
{
693
    const auto address = to_socket_address(point);
602 ✔
694
    if (!is_zero(::bind(descriptor_->handle, address.data(), address.size)))
602 ✔
695
    {
696
        ec = native_code();
6 ✔
697
        return;
6 ✔
698
    }
699

700
    descriptor_->bound = true;
596 ✔
701
    ec = error::success;
596 ✔
702
}
703

704
void acceptor::listen(code& ec) NOEXCEPT
596 ✔
705
{
706
    ec = !is_zero(::listen(descriptor_->handle, SOMAXCONN)) ? native_code() :
596 ✔
707
        code{ error::success };
708
}
596 ✔
709

710
void acceptor::close(code& ec) NOEXCEPT
859 ✔
711
{
712
    if (is_open())
859 ✔
713
        backend_of(executor_).close(*descriptor_);
602 ✔
714

715
    ec = error::success;
859 ✔
716
}
859 ✔
717

718
void acceptor::close() NOEXCEPT
55 ✔
719
{
720
    code ignore{};
55 ✔
721
    close(ignore);
55 ✔
722
}
55 ✔
723

724
void acceptor::cancel(code& ec) NOEXCEPT
145 ✔
725
{
726
    if (!is_open())
145 ✔
727
    {
728
        ec = error::bad_stream;
7 ✔
729
        return;
7 ✔
730
    }
731

732
    backend_of(executor_).cancel(*descriptor_);
138 ✔
733
    ec = error::success;
138 ✔
734
}
735

736
endpoint acceptor::local_endpoint(code& ec) const NOEXCEPT
507 ✔
737
{
738
    socket_address address{};
507 ✔
739
    address.size = sizeof(address.storage);
507 ✔
740
    const auto handle = descriptor_->handle;
507 ✔
741
    if (!is_zero(::getsockname(handle, address.data(), &address.size)))
507 ✔
742
    {
743
        ec = native_code();
×
744
        return {};
×
745
    }
746

747
    ec = error::success;
507 ✔
748
    return to_endpoint(address.data());
507 ✔
749
}
750

751
endpoint acceptor::local_endpoint() const NOEXCEPT
502 ✔
752
{
753
    code ignore{};
502 ✔
754
    return local_endpoint(ignore);
502 ✔
755
}
756

757
void acceptor::async_accept(socket& peer, result_handler&& handler) NOEXCEPT
393 ✔
758
{
759
    socket::io_handler completion =
760
        [handler = std::move(handler)](const code& ec, size_t) NOEXCEPT
786 ✔
761
        {
762
            handler(ec);
393 ✔
763
        };
393 ✔
764

765
    if (!is_open() || peer.is_open())
393 ✔
766
    {
767
        const auto ec = is_open() ? error::connect_failed : error::bad_stream;
1 ✔
768
        post_result(executor_, completion, ec);
1 ✔
769
        return;
770
    }
771

772
    constexpr auto kind = operation::kind::accept;
773
    const auto op = new operation{ kind, descriptor_, executor_ };
392 ✔
774
    op->peer = peer.descriptor_;
392 ✔
775
    op->handler = std::move(completion);
392 ✔
776
    backend_of(executor_).start(op);
392 ✔
777
}
393 ✔
778

779
void acceptor::accept(socket& peer, code& ec) NOEXCEPT
109 ✔
780
{
781
    if (!is_open() || peer.is_open())
109 ✔
782
    {
783
        ec = is_open() ? error::connect_failed : error::bad_stream;
×
784
        return;
×
785
    }
786

787
    while (true)
788
    {
789
        const auto accepted = ::accept(descriptor_->handle, nullptr, nullptr);
211 ✔
790
        if (accepted != invalid_socket)
211 ✔
791
        {
792
            int native{};
109 ✔
793
#if !defined(HAVE_WINDOWS)
794
            ::fcntl(accepted, F_SETFD, FD_CLOEXEC);
109 ✔
795
            if (!set_blocking(accepted, false, native))
109 ✔
796
            {
797
                close_socket(accepted);
×
798
                ec = to_code(native);
×
799
                return;
×
800
            }
801
#endif
802
            if (!backend_of(executor_).adopt(peer.descriptor_, accepted,
218 ✔
803
                descriptor_->v6, native))
109 ✔
804
            {
805
                close_socket(accepted);
×
806
                ec = to_code(native);
×
807
                return;
×
808
            }
809

810
            ec = error::success;
109 ✔
811
            return;
109 ✔
812
        }
813

814
        auto native = last_error();
102 ✔
815
#if !defined(HAVE_WINDOWS)
816
        if (native == EINTR || native == ECONNABORTED)
102 ✔
817
            continue;
×
818
#endif
819
        if (is_would_block(native) && !descriptor_->non_blocking &&
204 ✔
820
            wait_ready(descriptor_->handle, false, native))
102 ✔
821
            continue;
102 ✔
822

823
        ec = to_code(native);
×
824
        return;
825
    }
102 ✔
826
}
827

828
// resolver
829
// ----------------------------------------------------------------------------
830

831
struct resolver::state
832
{
833
    std::atomic<size_t> cancels{};
834
};
835

836
static code resolve_code(int result) NOEXCEPT
128 ✔
837
{
838
    switch (result)
128 ✔
839
    {
840
        case 0:
124 ✔
841
            return error::success;
124 ✔
842
#if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
843
        case EAI_NODATA:
×
844
#endif
845
        case EAI_FAIL:
846
            return error::operation_failed;
×
847
        default:
4 ✔
848
            return error::resolve_failed;
4 ✔
849
    }
850
}
851

852
resolver::resolver(const executor& executor) NOEXCEPT
274 ✔
853
  : executor_(executor), state_(std::make_shared<state>())
274 ✔
854
{
855
}
274 ✔
856

857
resolver::~resolver() NOEXCEPT
274 ✔
858
{
859
    cancel();
274 ✔
860
}
274 ✔
861

862
resolver::executor_type resolver::get_executor() const NOEXCEPT
×
863
{
864
    return executor_;
×
865
}
866

867
void resolver::async_resolve(const std::string& host,
128 ✔
868
    const std::string& service, resolve_handler&& handler) NOEXCEPT
869
{
870
    auto& scheduler = executor_.context().scheduler();
128 ✔
871
    scheduler.work_started();
128 ✔
872

873
    const auto started = state_->cancels.load();
128 ✔
874
    scheduler.resolve([&scheduler, state = state_, started,
256 ✔
875
        executor = executor_, host, service,
876
        handler = std::move(handler)]() NOEXCEPT
128 ✔
877
    {
878
        addrinfo hints{};
128 ✔
879
        hints.ai_family = AF_UNSPEC;
880
        hints.ai_socktype = SOCK_STREAM;
128 ✔
881
        hints.ai_protocol = IPPROTO_TCP;
128 ✔
882
        hints.ai_flags = AI_ADDRCONFIG;
128 ✔
883

884
        addrinfo* results{};
128 ✔
885
        const auto result = ::getaddrinfo(host.c_str(), service.c_str(),
128 ✔
886
            &hints, &results);
887

888
        endpoints range{};
128 ✔
889
        for (auto it = results; it != nullptr; it = it->ai_next)
252 ✔
890
            if (it->ai_family == AF_INET || it->ai_family == AF_INET6)
124 ✔
891
                range.push_back(to_endpoint(it->ai_addr));
124 ✔
892

893
        if (results != nullptr)
128 ✔
894
            ::freeaddrinfo(results);
124 ✔
895

896
        scheduler.complete([state, started, executor, handler,
256 ✔
897
            ec = resolve_code(result), range = std::move(range)]() NOEXCEPT
128 ✔
898
        {
899
            const auto canceled = state->cancels.load() != started;
128 ✔
900
            const code value = canceled ? error::operation_canceled : ec;
128 ✔
901
            executor.dispatch([handler, value, range]() NOEXCEPT
128 ✔
902
            {
903
                handler(value, value ? endpoints{} : range);
128 ✔
904
            });
128 ✔
905
        });
128 ✔
906
    });
128 ✔
907
}
128 ✔
908

909
void resolver::cancel() NOEXCEPT
316 ✔
910
{
911
    ++state_->cancels;
316 ✔
912
}
316 ✔
913

914
// async_connect (range)
915
// ----------------------------------------------------------------------------
916

917
namespace {
918

919
struct range_connect
920
  : std::enable_shared_from_this<range_connect>
921
{
922
    range_connect(io::socket& socket, const endpoints& range,
120 ✔
923
        connect_handler&& handler) NOEXCEPT
924
      : socket(socket), range(range), handler(std::move(handler))
120 ✔
925
    {
926
    }
120 ✔
927

928
    void next() NOEXCEPT
136 ✔
929
    {
930
        if (index == range.size())
136 ✔
931
        {
932
            const auto ec = last ? last : code{ error::resolve_failed };
16 ✔
933
            socket.get_executor().post(
48 ✔
934
                [self = shared_from_this(), ec]() NOEXCEPT
32 ✔
935
                {
936
                    self->handler(ec, {});
16 ✔
937
                });
16 ✔
938

939
            return;
940
        }
941

942
        code ignore{};
120 ✔
943
        socket.close(ignore);
120 ✔
944
        socket.async_connect(range.at(index),
120 ✔
945
            [self = shared_from_this()](const code& ec) NOEXCEPT
240 ✔
946
            {
947
                self->handle(ec);
120 ✔
948
            });
120 ✔
949
    }
950

951
    void handle(const code& ec) NOEXCEPT
120 ✔
952
    {
953
        if (!ec || ec == error::operation_canceled)
120 ✔
954
        {
955
            handler(ec, ec ? endpoint{} : range.at(index));
103 ✔
956
            return;
103 ✔
957
        }
958

959
        if (!socket.is_open())
17 ✔
960
        {
961
            handler(error::operation_canceled, {});
1 ✔
962
            return;
1 ✔
963
        }
964

965
        last = ec;
16 ✔
966
        ++index;
16 ✔
967
        next();
16 ✔
968
    }
969

970
    io::socket& socket;
971
    const endpoints range;
972
    const connect_handler handler;
973
    size_t index{};
974
    code last{};
975
};
976

977
} // namespace
978

979
void async_connect(io::socket& socket, const endpoints& range,
120 ✔
980
    connect_handler&& handler) NOEXCEPT
981
{
982
    std::make_shared<range_connect>(socket, range,
120 ✔
983
        std::move(handler))->next();
120 ✔
984
}
120 ✔
985

986
BC_POP_WARNING()
987
BC_POP_WARNING()
988

989
} // namespace io
990
} // namespace network
991
} // 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