ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
api_outgoing_connection.cpp
Go to the documentation of this file.
2#if defined(USE_API) && defined(USE_API_OUTGOING_CONNECTION)
3
4#include "api_connection.h"
5#include "api_server.h"
9#include "esphome/core/log.h"
10
11#include <cerrno>
12#include <cinttypes>
13#include <cstdint>
14#include <cstring>
15
16namespace esphome::api {
17
18ESPHOME_LOG_TAG(TAG, "api.outgoing");
19
20#ifndef API_OUTGOING_CONNECTION_HOST
21static constexpr uint32_t OUTGOING_TARGET_PREF_HASH = 629847102UL;
22#endif
23
24#ifndef API_OUTGOING_CONNECTION_HOST
25// Read the connection's peer address into target; false when unavailable or
26// of a family this build cannot dial
27static bool peer_to_target(APIConnection *conn, SavedOutgoingTarget &target) {
28 // Zeroed because the raw lwIP getpeername() leaves sin6_scope_id untouched
29 struct sockaddr_storage peer = {};
30 socklen_t peer_len = sizeof(peer);
31 if (conn->getpeername((struct sockaddr *) &peer, &peer_len) != 0) {
32 return false;
33 }
34 const sa_family_t family = ((struct sockaddr *) &peer)->sa_family;
35#if USE_NETWORK_IPV6
36 if (family == AF_INET6) {
37 const auto *addr6 = reinterpret_cast<const struct sockaddr_in6 *>(&peer);
38 const auto *bytes = reinterpret_cast<const uint8_t *>(&addr6->sin6_addr);
39 uint32_t prefix[3];
40 memcpy(prefix, bytes, sizeof(prefix));
41#if USE_NETWORK_IPV4
42 // A dual-stack listener reports an IPv4 peer as ::ffff:a.b.c.d
43 if (prefix[0] == 0 && prefix[1] == 0 && prefix[2] == htonl(0xFFFFUL)) {
44 target.family = AF_INET;
45 memcpy(target.addr, bytes + sizeof(prefix), sizeof(struct in_addr));
46 return true;
47 }
48#endif
49 // A link-local target is only reachable through the interface it came in
50 // on. Device platforms number interfaces from one; a host build can hand
51 // out an index too large to store, and a truncated one dials the wrong
52 // interface, so that target is not remembered at all.
53 if (addr6->sin6_scope_id > UINT8_MAX) {
54 return false;
55 }
56 target.family = AF_INET6;
57 memcpy(target.addr, bytes, sizeof(target.addr));
58 target.scope_id = static_cast<uint8_t>(addr6->sin6_scope_id);
59 return true;
60 }
61#endif
62#if USE_NETWORK_IPV4
63 if (family != AF_INET) {
64 return false;
65 }
66 const auto *addr4 = reinterpret_cast<const struct sockaddr_in *>(&peer);
67 target.family = AF_INET;
68 memcpy(target.addr, &addr4->sin_addr, sizeof(addr4->sin_addr));
69 return true;
70#else
71 return false;
72#endif
73}
74#endif
75
77#ifdef API_OUTGOING_CONNECTION_HOST
78 // Validation only lets through a literal both inet_pton and inet6_aton
79 // accept, so this cannot fail
80 return socket::set_sockaddr((struct sockaddr *) addr, sizeof(*addr), API_OUTGOING_CONNECTION_HOST,
81 API_OUTGOING_CONNECTION_PORT);
82#else
83#if USE_NETWORK_IPV6
84 if (this->saved_.family == AF_INET6) {
85 auto *addr6 = reinterpret_cast<struct sockaddr_in6 *>(addr);
86 memset(addr6, 0, sizeof(*addr6));
87 addr6->sin6_family = AF_INET6;
88 addr6->sin6_port = htons(API_OUTGOING_CONNECTION_PORT);
89 memcpy(&addr6->sin6_addr, this->saved_.addr, sizeof(this->saved_.addr));
90 addr6->sin6_scope_id = this->saved_.scope_id;
91 return sizeof(*addr6);
92 }
93#endif
94#if USE_NETWORK_IPV4
95 if (this->saved_.family != AF_INET) {
96 return 0;
97 }
98 auto *addr4 = reinterpret_cast<struct sockaddr_in *>(addr);
99 memset(addr4, 0, sizeof(*addr4));
100 addr4->sin_family = AF_INET;
101 addr4->sin_port = htons(API_OUTGOING_CONNECTION_PORT);
102 memcpy(&addr4->sin_addr, this->saved_.addr, sizeof(addr4->sin_addr));
103 return sizeof(*addr4);
104#else
105 return 0;
106#endif
107#endif
108}
109
110#ifndef API_OUTGOING_CONNECTION_HOST
111void OutgoingConnectionManager::format_target_(std::span<char, socket::SOCKADDR_STR_LEN> buf) const {
112 struct sockaddr_storage addr;
113 socklen_t addr_len = this->target_sockaddr_(&addr);
114 if (addr_len == 0) {
115 buf[0] = '\0';
116 return;
117 }
118 // Clears buf itself if it cannot format the address
119 socket::format_sockaddr_to((struct sockaddr *) &addr, addr_len, buf);
120}
121#endif
122
124#ifndef API_OUTGOING_CONNECTION_HOST
125 this->target_pref_ = global_preferences->make_preference<SavedOutgoingTarget>(OUTGOING_TARGET_PREF_HASH, true);
126 struct sockaddr_storage addr;
127 // dump_config() prints whichever target this leaves in place
128 if (this->target_pref_.load(&this->saved_) && this->target_sockaddr_(&addr) != 0) {
129 this->host_persisted_ = true;
130 } else {
131 // Never saved, failed its size or CRC check, or holds an unknown family
132 this->saved_ = {};
133 }
134#endif
135}
136
138 if (server->has_outgoing_target_client_()) {
139 return; // on_target_client() already reset the dial state
140 }
141 if (this->dialed_conn_ != nullptr) {
142 // A live dialed session (flagged or not, e.g. a host: peer) is the
143 // target; a silent one dies on the handshake timeout
144 return;
145 }
147 switch (this->state_) {
149 // Target went away; give it the configured delay to reconnect first
150 this->schedule_wait_(now, IDLE_WAIT_MS);
151 break;
153 if (now - this->state_ts_ >= this->wait_) {
154 this->try_dial_(server, now);
155 }
156 break;
158 this->poll_connect_(server, now);
159 break;
160 }
161}
162
164 if (!network::is_connected()) {
165 return; // still WAITING with the wait elapsed, so the next loop rechecks
166 }
167 struct sockaddr_storage addr;
168 socklen_t addr_len = this->target_sockaddr_(&addr);
169 const bool at_limit = server->at_client_limit_();
170 // No target is the steady state until a dial-back client has ever connected
171 if (addr_len == 0 || at_limit || !server->noise_ctx_.has_psk()) {
172 // Repeats for as long as the reason holds, so keep it out of debug logs
173 ESP_LOGV(TAG, "Not dialing: %s",
174 addr_len == 0 ? LOG_STR_LITERAL("no target")
175 : (at_limit ? LOG_STR_LITERAL("max connections") : LOG_STR_LITERAL("no key")));
176 // Not a dial failure; retry without escalating the backoff
178 return;
179 }
180 this->dial_socket_ = socket::socket_loop_monitored(((struct sockaddr *) &addr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
181 if (!this->dial_socket_ || this->dial_socket_->setblocking(false) != 0) {
182 ESP_LOGW(TAG, "Socket %s failed: errno %d",
183 this->dial_socket_ ? LOG_STR_LITERAL("setblocking") : LOG_STR_LITERAL("create"), errno);
184 this->schedule_retry_(now);
185 return;
186 }
187#ifdef API_OUTGOING_CONNECTION_HOST
188 ESP_LOGD(TAG, "Dialing " API_OUTGOING_CONNECTION_HOST ":%u", API_OUTGOING_CONNECTION_PORT);
189#else
190 char host[socket::SOCKADDR_STR_LEN];
191 socket::format_sockaddr_to((struct sockaddr *) &addr, addr_len, host);
192 ESP_LOGD(TAG, "Dialing %s:%u", host, API_OUTGOING_CONNECTION_PORT);
193#endif
194 int err = this->dial_socket_->connect((struct sockaddr *) &addr, addr_len);
195 if (err == 0) {
196 // Immediate success (possible for localhost)
197 this->handoff_(server, now);
198 return;
199 }
200 if (errno != EINPROGRESS) {
201 ESP_LOGW(TAG, "Connect failed: %d", errno);
202 this->schedule_retry_(now);
203 return;
204 }
206 this->state_ts_ = now;
207}
208
210 if (now - this->state_ts_ >= CONNECT_TIMEOUT_MS) {
211 ESP_LOGW(TAG, "Connect timeout");
212 this->schedule_retry_(now);
213 return;
214 }
215 int err = 0;
216 switch (socket::poll_connect(*this->dial_socket_, err)) {
218 break;
220 this->handoff_(server, now);
221 break;
223 ESP_LOGW(TAG, "Connect failed: %d", err);
224 this->schedule_retry_(now);
225 break;
226 }
227}
228
230 this->dialed_conn_ = server->add_outgoing_client_(std::move(this->dial_socket_));
231 if (this->dialed_conn_ == nullptr) {
232 // Only preconditions (slot limit, key cleared) refuse the handoff; the
233 // peer is reachable, so do not escalate the backoff
235 return;
236 }
237 // Connected; dialed_conn_ gates further dialing until the session settles
239}
240
242 this->dial_socket_.reset(); // no-op when the socket was handed off
244 this->state_ts_ = now;
245 this->wait_ = wait;
246}
247
249 // +/-20% jitter so a fleet of devices does not retry one server in lockstep
250 const uint32_t jitter_span = this->backoff_ / 5;
251 this->schedule_wait_(now, this->backoff_ - jitter_span + (random_uint32() % (2 * jitter_span + 1)));
252 this->backoff_ = std::min(this->backoff_ * 2, BACKOFF_MAX_MS);
253}
254
256 if (conn != this->dialed_conn_) {
257 return;
258 }
259 this->dialed_conn_ = nullptr;
260 if (was_authenticated) {
261 // A working peer (e.g. a host: target that never sends the flag)
262 // disconnected normally; state is IDLE, so loop() applies the delay
263 this->backoff_ = BACKOFF_MIN_MS;
264 } else {
266 }
267}
268
270 // The target is connected; stop any dial in flight and reset the backoff.
271 // A dialed connection stays tracked unless it is this one: an inbound
272 // target must not orphan a still-open dial.
273 this->dial_socket_.reset();
274 if (conn == this->dialed_conn_) {
275 this->dialed_conn_ = nullptr;
276 }
278 this->backoff_ = BACKOFF_MIN_MS;
279#ifndef API_OUTGOING_CONNECTION_HOST
280 SavedOutgoingTarget target{};
281 if (!peer_to_target(conn, target)) {
282 ESP_LOGW(TAG, "Not remembering this target; its address cannot be dialed");
283 return;
284 }
285 if (this->host_persisted_ && memcmp(&target, &this->saved_, sizeof(target)) == 0) {
286 return; // unchanged and already on flash; avoid flash wear
287 }
288 // Use the fresh address this boot even if the flash write fails; a failed
289 // write is retried on the next flagged hello via host_persisted_
290 this->saved_ = target;
291 if (!this->persist_target_()) {
292 ESP_LOGW(TAG, "Failed to save target");
293 return;
294 }
295 char host[socket::SOCKADDR_STR_LEN];
296 this->format_target_(host);
297 ESP_LOGD(TAG, "Remembered %s as the dial target", host);
298#endif
299}
300
302 // The boot delay differs from delay: on deep sleep builds, so print the
303 // value that actually applies
304 ESP_LOGCONFIG(TAG,
305 " Outgoing connection port: %u\n"
306 " Outgoing connection boot delay: %" PRIu32 "ms",
307 API_OUTGOING_CONNECTION_PORT, BOOT_WAIT_MS);
308 // Both forms keep their text out of RAM on ESP8266: in the format string,
309 // or through LOG_STR_LITERAL
310#ifdef API_OUTGOING_CONNECTION_HOST
311 ESP_LOGCONFIG(TAG, " Outgoing connection host: " API_OUTGOING_CONNECTION_HOST);
312#else
313 char buf[socket::SOCKADDR_STR_LEN];
314 this->format_target_(buf);
315 ESP_LOGCONFIG(TAG, " Outgoing connection host: %s", buf[0] == '\0' ? LOG_STR_LITERAL("none remembered yet") : buf);
316#endif
317}
318
319} // namespace esphome::api
320#endif // USE_API && USE_API_OUTGOING_CONNECTION
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
int getpeername(struct sockaddr *addr, socklen_t *addrlen) const
Get the peer address itself, for remembering a dial-back target.
bool at_client_limit_() const
Definition api_server.h:285
bool has_outgoing_target_client_() const
Definition api_server.h:289
APIConnection * add_outgoing_client_(std::unique_ptr< socket::Socket > sock)
noise::NoiseContext noise_ctx_
Definition api_server.h:400
void poll_connect_(APIServer *server, uint32_t now)
void handoff_(APIServer *server, uint32_t now)
socklen_t target_sockaddr_(struct sockaddr_storage *addr) const
Fill addr with the target and return its length, or 0 when there is none.
void format_target_(std::span< char, socket::SOCKADDR_STR_LEN > buf) const
Format the remembered target for a log line; empty when there is none.
void on_client_removed(APIConnection *conn, bool was_authenticated)
Clears the dialed-connection gate; dying unauthenticated escalates the backoff.
void schedule_wait_(uint32_t now, uint32_t wait)
void on_target_client(APIConnection *conn)
A key-verified client declared itself a dial-back target; last one wins.
std::unique_ptr< socket::Socket > dial_socket_
void try_dial_(APIServer *server, uint32_t now)
uint16_t addr_len
uint32_t socklen_t
Definition headers.h:109
uint8_t sa_family_t
Definition headers.h:69
ESPHOME_LOG_TAG(TAG, "api.connection")
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:36
ConnectPollResult poll_connect(Socket &sock, int &err_out)
Poll a connect() that returned EINPROGRESS.
Definition socket.h:223
socklen_t set_sockaddr(struct sockaddr *addr, socklen_t addrlen, const char *ip_address, uint16_t port)
Set a sockaddr to the specified address and port for the IP version used by socket_ip().
size_t format_sockaddr_to(const struct sockaddr *addr_ptr, socklen_t len, std::span< char, SOCKADDR_STR_LEN > buf)
Format sockaddr into caller-provided buffer, returns length written (excluding null)
std::unique_ptr< Socket > socket_loop_monitored(int domain, int type, int protocol)
Create a socket and monitor it for data in the main loop.
ESPPreferences * global_preferences
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:10
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24