Coverage Report

Created: 2026-11-13 17:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/ipc/capnp/protocol.cpp
Line
Count
Source
1
// Copyright (c) 2021-present The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#include <interfaces/init.h>
6
#include <ipc/capnp/context.h>
7
#include <ipc/capnp/init.capnp.h>
8
#include <ipc/capnp/init.capnp.proxy.h>
9
#include <ipc/capnp/protocol.h>
10
#include <ipc/exception.h>
11
#include <ipc/protocol.h>
12
#include <kj/async.h>
13
#include <mp/proxy-io.h>
14
#include <mp/proxy-types.h>
15
#include <mp/util.h>
16
#include <util/log.h>
17
#include <util/threadnames.h>
18
19
#include <cassert>
20
#include <cerrno>
21
#include <future>
22
#include <list>
23
#include <memory>
24
#include <mutex>
25
#include <optional>
26
#include <string>
27
#include <sys/socket.h>
28
#include <system_error>
29
#include <thread>
30
31
namespace ipc {
32
namespace capnp {
33
namespace {
34
35
mp::Log GetRequestedIPCLogLevel()
36
21
{
37
21
    if (util::log::ShouldTraceLog(BCLog::IPC)) return mp::Log::Trace;
38
4
    if (util::log::ShouldDebugLog(BCLog::IPC)) return mp::Log::Debug;
39
40
    // Info, Warning, and Error are logged unconditionally
41
4
    return mp::Log::Info;
42
4
}
43
44
void IpcLogFn(mp::LogMessage message)
45
3.26k
{
46
3.26k
    switch (message.level) {
47
642
    case mp::Log::Trace:
48
642
        LogTrace(BCLog::IPC, "%s", message.message);
49
642
        return;
50
2.48k
    case mp::Log::Debug:
51
2.48k
        LogDebug(BCLog::IPC, "%s", message.message);
52
2.48k
        return;
53
119
    case mp::Log::Info:
54
119
        LogInfo("ipc: %s", message.message);
55
119
        return;
56
0
    case mp::Log::Warning:
57
0
        LogWarning("ipc: %s", message.message);
58
0
        return;
59
18
    case mp::Log::Error:
60
18
        LogError("ipc: %s", message.message);
61
18
        return;
62
0
    case mp::Log::Raise:
63
0
        LogError("ipc: %s", message.message);
64
0
        throw Exception(message.message);
65
3.26k
    } // no default case, so the compiler can warn about missing cases
66
67
    // Be conservative and assume that if MP ever adds a new log level, it
68
    // should only be shown at our most verbose level.
69
0
    LogTrace(BCLog::IPC, "%s", message.message);
70
0
}
71
72
class CapnpProtocol : public Protocol
73
{
74
public:
75
55
    CapnpProtocol(const char* exe_name) : m_exe_name{exe_name} {}
76
    ~CapnpProtocol() noexcept(true)
77
55
    {
78
55
        m_loop_ref.reset();
79
55
        if (m_loop_thread.joinable()) m_loop_thread.join();
80
55
        assert(!m_loop);
81
55
    };
82
    std::unique_ptr<interfaces::Init> connect(mp::Stream stream) override
83
12
    {
84
12
        startLoop();
85
12
        return mp::ConnectStream<messages::Init>(*m_loop, std::move(stream));
86
12
    }
87
    void listen(mp::SocketId listen_fd, interfaces::Init& init, std::optional<size_t> max_connections) override
88
18
    {
89
18
        startLoop();
90
18
        if (::listen(listen_fd, /*backlog=*/5) != 0) {
91
0
            throw std::system_error(errno, std::system_category());
92
0
        }
93
18
        mp::ListenConnections<messages::Init>(*m_loop, listen_fd, init, max_connections);
94
18
    }
95
    void serve(interfaces::Init& init, const std::function<mp::Stream()>& make_stream) override
96
1
    {
97
1
        assert(!m_loop);
98
1
        mp::CurrentThread().thread_name = mp::ThreadName(m_exe_name);
99
1
        mp::LogOptions opts = {
100
1
            .log_fn = IpcLogFn,
101
1
            .log_level = GetRequestedIPCLogLevel()
102
1
        };
103
1
        m_loop.emplace(m_exe_name, std::move(opts), &m_context);
104
1
        mp::ServeStream<messages::Init>(*m_loop, make_stream(), init);
105
1
        m_parent_connection = &m_loop->m_incoming_connections.back();
106
1
        m_loop->loop();
107
1
        m_loop.reset();
108
1
    }
109
    void disconnectIncoming() override
110
17
    {
111
17
        if (!m_loop) return;
112
        // Delete incoming connections, except the connection to a parent
113
        // process (if there is one), since a parent process should be able to
114
        // monitor and control this process, even during shutdown.
115
14
        m_loop->sync([&] {
116
14
            std::erase_if(m_loop->m_incoming_connections, [this](mp::Connection& c) { return &c != m_parent_connection; });
117
14
        });
118
14
    }
119
    mp::Stream makeStream(mp::SocketId socket) override
120
13
    {
121
13
        startLoop();
122
13
        return mp::MakeStream(*m_loop, socket);
123
13
    }
124
    void addCleanup(std::type_index type, void* iface, std::function<void()> cleanup) override
125
0
    {
126
0
        mp::ProxyTypeRegister::types().at(type)(iface).cleanup_fns.emplace_back(std::move(cleanup));
127
0
    }
128
0
    Context& context() override { return m_context; }
129
    void startLoop()
130
43
    {
131
43
        if (m_loop) return;
132
20
        std::promise<void> promise;
133
20
        m_loop_thread = std::thread([&] {
134
20
            util::ThreadRename("capnp-loop");
135
20
            mp::LogOptions opts = {
136
20
                .log_fn = IpcLogFn,
137
20
                .log_level = GetRequestedIPCLogLevel()
138
20
            };
139
20
            m_loop.emplace(m_exe_name, std::move(opts), &m_context);
140
20
            m_loop_ref.emplace(*m_loop);
141
20
            promise.set_value();
142
20
            m_loop->loop();
143
20
            m_loop.reset();
144
20
        });
145
20
        promise.get_future().wait();
146
20
    }
147
    const char* m_exe_name;
148
    Context m_context;
149
    //! EventLoop object which manages I/O events for all connections.
150
    std::optional<mp::EventLoop> m_loop;
151
    //! Reference to the same EventLoop. Increments the loop’s refcount on
152
    //! creation, decrements on destruction. The loop thread exits when the
153
    //! refcount reaches 0. Other IPC objects also hold their own EventLoopRef.
154
    std::optional<mp::EventLoopRef> m_loop_ref;
155
    //! Connection to parent, if this is a child process spawned by a parent process.
156
    mp::Connection* m_parent_connection{nullptr};
157
    std::thread m_loop_thread;
158
};
159
} // namespace
160
161
55
std::unique_ptr<Protocol> MakeCapnpProtocol(const char* exe_name) { return std::make_unique<CapnpProtocol>(exe_name); }
162
} // namespace capnp
163
} // namespace ipc