Coverage Report

Created: 2026-07-14 18:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/bitcoin/src/mapport.cpp
Line
Count
Source
1
// Copyright (c) 2011-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 <mapport.h>
6
7
#include <clientversion.h>
8
#include <common/netif.h>
9
#include <common/pcp.h>
10
#include <common/system.h>
11
#include <net.h>
12
#include <netaddress.h>
13
#include <netbase.h>
14
#include <random.h>
15
#include <util/log.h>
16
#include <util/thread.h>
17
#include <util/threadinterrupt.h>
18
19
#include <atomic>
20
#include <cassert>
21
#include <chrono>
22
#include <functional>
23
#include <string>
24
#include <thread>
25
26
static CThreadInterrupt g_mapport_interrupt;
27
static std::thread g_mapport_thread;
28
29
using namespace std::chrono_literals;
30
static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD{20min};
31
static constexpr auto PORT_MAPPING_RETRY_PERIOD{5min};
32
33
static void ProcessPCP()
34
27
{
35
    // The same nonce is used for all mappings, this is allowed by the spec, and simplifies keeping track of them.
36
27
    PCPMappingNonce pcp_nonce;
37
27
    GetRandBytes(pcp_nonce);
38
39
27
    bool ret = false;
40
27
    bool no_resources = false;
41
27
    const uint16_t private_port = GetListenPort();
42
    // Multiply the reannounce period by two, as we'll try to renew approximately halfway.
43
27
    const uint32_t requested_lifetime = std::chrono::seconds(PORT_MAPPING_REANNOUNCE_PERIOD * 2).count();
44
27
    uint32_t actual_lifetime = 0;
45
27
    std::chrono::milliseconds sleep_time;
46
47
    // Local functor to handle result from PCP/NATPMP mapping.
48
27
    auto handle_mapping = [&](std::variant<MappingResult, MappingError> &res) -> void {
49
27
        if (MappingResult* mapping = std::get_if<MappingResult>(&res)) {
  Branch (49:28): [True: 0, False: 27]
50
0
            LogInfo("portmap: Added mapping %s", mapping->ToString());
51
0
            AddLocal(mapping->external, LOCAL_MAPPED);
52
0
            ret = true;
53
0
            actual_lifetime = std::min(actual_lifetime, mapping->lifetime);
54
27
        } else if (MappingError *err = std::get_if<MappingError>(&res)) {
  Branch (54:34): [True: 27, False: 0]
55
            // Detailed error will already have been logged internally in respective Portmap function.
56
27
            if (*err == MappingError::NO_RESOURCES) {
  Branch (56:17): [True: 0, False: 27]
57
0
                no_resources = true;
58
0
            }
59
27
        }
60
27
    };
61
62
27
    do {
63
27
        actual_lifetime = requested_lifetime;
64
27
        no_resources = false; // Set to true if there was any "no resources" error.
65
27
        ret = false; // Set to true if any mapping succeeds.
66
67
        // IPv4
68
27
        std::optional<CNetAddr> gateway4 = QueryDefaultGateway(NET_IPV4);
69
27
        if (!gateway4) {
  Branch (69:13): [True: 0, False: 27]
70
0
            LogDebug(BCLog::NET, "portmap: Could not determine IPv4 default gateway\n");
71
27
        } else {
72
27
            LogDebug(BCLog::NET, "portmap: gateway [IPv4]: %s\n", gateway4->ToStringAddr());
73
74
            // Open a port mapping on whatever local address we have toward the gateway.
75
27
            struct in_addr inaddr_any;
76
27
            inaddr_any.s_addr = htonl(INADDR_ANY);
77
27
            auto res = PCPRequestPortMap(pcp_nonce, *gateway4, CNetAddr(inaddr_any), private_port, requested_lifetime, g_mapport_interrupt);
78
27
            MappingError* pcp_err = std::get_if<MappingError>(&res);
79
27
            if (pcp_err && *pcp_err == MappingError::UNSUPP_VERSION) {
  Branch (79:17): [True: 27, False: 0]
  Branch (79:28): [True: 0, False: 27]
80
0
                LogDebug(BCLog::NET, "portmap: Got unsupported PCP version response, falling back to NAT-PMP\n");
81
0
                res = NATPMPRequestPortMap(*gateway4, private_port, requested_lifetime, g_mapport_interrupt);
82
0
            }
83
27
            handle_mapping(res);
84
27
        }
85
86
        // IPv6
87
27
        std::optional<CNetAddr> gateway6 = QueryDefaultGateway(NET_IPV6);
88
27
        if (!gateway6) {
  Branch (88:13): [True: 27, False: 0]
89
27
            LogDebug(BCLog::NET, "portmap: Could not determine IPv6 default gateway\n");
90
27
        } else {
91
0
            LogDebug(BCLog::NET, "portmap: gateway [IPv6]: %s\n", gateway6->ToStringAddr());
92
93
            // Try to open pinholes for all routable local IPv6 addresses.
94
0
            for (const auto &addr: GetLocalAddresses()) {
  Branch (94:34): [True: 0, False: 0]
95
0
                if (!addr.IsRoutable() || !addr.IsIPv6()) continue;
  Branch (95:21): [True: 0, False: 0]
  Branch (95:43): [True: 0, False: 0]
96
0
                auto res = PCPRequestPortMap(pcp_nonce, *gateway6, addr, private_port, requested_lifetime, g_mapport_interrupt);
97
0
                handle_mapping(res);
98
0
            }
99
0
        }
100
101
        // Log message if we got NO_RESOURCES.
102
27
        if (no_resources) {
  Branch (102:13): [True: 0, False: 27]
103
0
            LogWarning("portmap: At least one mapping failed because of a NO_RESOURCES error. This usually indicates that the port is already used on the router. If this is the only instance of bitcoin running on the network, this will resolve itself automatically. Otherwise, you might want to choose a different P2P port to prevent this conflict.\n");
104
0
        }
105
106
        // Sanity-check returned lifetime.
107
27
        if (actual_lifetime < 30) {
  Branch (107:13): [True: 0, False: 27]
108
0
            LogWarning("portmap: Got impossibly short mapping lifetime of %d seconds\n", actual_lifetime);
109
0
            return;
110
0
        }
111
        // RFC6887 11.2.1 recommends that clients send their first renewal packet at a time chosen with uniform random
112
        // distribution in the range 1/2 to 5/8 of expiration time.
113
27
        std::chrono::seconds sleep_time_min(actual_lifetime / 2);
114
27
        std::chrono::seconds sleep_time_max(actual_lifetime * 5 / 8);
115
27
        sleep_time = sleep_time_min + FastRandomContext().randrange<std::chrono::milliseconds>(sleep_time_max - sleep_time_min);
116
27
    } while (ret && g_mapport_interrupt.sleep_for(sleep_time));
  Branch (116:14): [True: 0, False: 27]
  Branch (116:21): [True: 0, False: 0]
117
118
    // We don't delete the mappings when the thread is interrupted because this would add additional complexity, so
119
    // we rather just choose a fairly short expiry time.
120
27
}
121
122
/// \anchor mapport
123
static void ThreadMapPort()
124
27
{
125
27
    do {
126
27
        ProcessPCP();
127
27
    } while (g_mapport_interrupt.sleep_for(PORT_MAPPING_RETRY_PERIOD));
  Branch (127:14): [True: 0, False: 27]
128
27
}
129
130
void StartThreadMapPort()
131
27
{
132
27
    if (!g_mapport_thread.joinable()) {
  Branch (132:9): [True: 27, False: 0]
133
27
        assert(!g_mapport_interrupt);
  Branch (133:9): [True: 27, False: 0]
134
27
        g_mapport_thread = std::thread(&util::TraceThread, "mapport", &ThreadMapPort);
135
27
    }
136
27
}
137
138
void StartMapPort(bool enable)
139
27
{
140
27
    if (enable) {
  Branch (140:9): [True: 27, False: 0]
141
27
        StartThreadMapPort();
142
27
    } else {
143
0
        InterruptMapPort();
144
0
        StopMapPort();
145
0
    }
146
27
}
147
148
void InterruptMapPort()
149
150k
{
150
150k
    if (g_mapport_thread.joinable()) {
  Branch (150:9): [True: 150k, False: 0]
151
150k
        g_mapport_interrupt();
152
150k
    }
153
150k
}
154
155
void StopMapPort()
156
150k
{
157
150k
    if (g_mapport_thread.joinable()) {
  Branch (157:9): [True: 150k, False: 0]
158
150k
        g_mapport_thread.join();
159
150k
        g_mapport_interrupt.reset();
160
150k
    }
161
150k
}