4#ifdef USE_SOCKET_IMPL_LWIP_TCP
14#ifdef USE_OTA_PLATFORM_ESPHOME
21#include <hardware/sync.h>
44#define LWIP_LOCK() esphome::LwIPLock lwip_lock_guard
46static const char *
const TAG =
"socket";
50static constexpr uint32_t ESP8266_YIELD_INTERVAL_US = 1000;
55#define LWIP_LOG(msg, ...) ESP_LOGVV(TAG, "socket %p: " msg, this, ##__VA_ARGS__)
57#define LWIP_LOG(msg, ...)
67static void pcb_detach_abort(
struct tcp_pcb *pcb) {
68 tcp_arg(pcb,
nullptr);
69 tcp_recv(pcb,
nullptr);
70 tcp_err(pcb,
nullptr);
82static err_t pcb_detach_close(
struct tcp_pcb *pcb) {
83 tcp_arg(pcb,
nullptr);
84 tcp_recv(pcb,
nullptr);
85 tcp_err(pcb,
nullptr);
86 err_t err = tcp_close(pcb);
97 if (this->
pcb_ !=
nullptr) {
98 LWIP_LOG(
"tcp_abort(%p)", this->
pcb_);
99 pcb_detach_abort(this->
pcb_);
100 this->
pcb_ =
nullptr;
106 if (this->
pcb_ ==
nullptr) {
110 if (name ==
nullptr) {
117 if (this->
family_ == AF_INET) {
122 auto *addr4 =
reinterpret_cast<const sockaddr_in *
>(name);
123 port = ntohs(addr4->sin_port);
125 ip.
u_addr.
ip4.addr = addr4->sin_addr.s_addr;
126 LWIP_LOG(
"tcp_bind(%p ip=%s port=%u)", this->
pcb_, ip4addr_ntoa(&ip.
u_addr.
ip4), port);
127 }
else if (this->
family_ == AF_INET6) {
132 auto *addr6 =
reinterpret_cast<const sockaddr_in6 *
>(name);
133 port = ntohs(addr6->sin6_port);
134 ip.
type = IPADDR_TYPE_ANY;
135 memcpy(&ip.
u_addr.
ip6.addr, &addr6->sin6_addr.un.u8_addr, 16);
136 LWIP_LOG(
"tcp_bind(%p ip=%s port=%u)", this->
pcb_, ip6addr_ntoa(&ip.
u_addr.
ip6), port);
142 if (this->
family_ != AF_INET) {
146 auto *addr4 =
reinterpret_cast<const sockaddr_in *
>(name);
147 port = ntohs(addr4->sin_port);
148 ip.addr = addr4->sin_addr.s_addr;
149 LWIP_LOG(
"tcp_bind(%p ip=%u port=%u)", this->
pcb_, ip.addr, port);
151 err_t err = tcp_bind(this->
pcb_, &ip, port);
152 if (err == ERR_USE) {
153 LWIP_LOG(
" -> err ERR_USE");
157 if (err == ERR_VAL) {
158 LWIP_LOG(
" -> err ERR_VAL");
163 LWIP_LOG(
" -> err %d", err);
172 if (this->
pcb_ ==
nullptr) {
176 LWIP_LOG(
"tcp_close(%p)", this->
pcb_);
177 err_t err = pcb_detach_close(this->
pcb_);
178 this->
pcb_ =
nullptr;
180 LWIP_LOG(
" -> err %d", err);
181 errno = err == ERR_MEM ? ENOMEM : EIO;
189 if (this->
pcb_ ==
nullptr) {
193 bool shut_rx =
false, shut_tx =
false;
194 if (how == SHUT_RD) {
196 }
else if (how == SHUT_WR) {
198 }
else if (how == SHUT_RDWR) {
199 shut_rx = shut_tx =
true;
204 LWIP_LOG(
"tcp_shutdown(%p shut_rx=%d shut_tx=%d)", this->
pcb_, shut_rx ? 1 : 0, shut_tx ? 1 : 0);
205 err_t err = tcp_shutdown(this->
pcb_, shut_rx, shut_tx);
207 LWIP_LOG(
" -> err %d", err);
208 errno = err == ERR_MEM ? ENOMEM : EIO;
216 if (this->
pcb_ ==
nullptr) {
220 if (name ==
nullptr || addrlen ==
nullptr) {
224 return this->
ip2sockaddr_(&this->
pcb_->remote_ip, this->pcb_->remote_port, name, addrlen);
229 if (this->
pcb_ ==
nullptr) {
233 if (name ==
nullptr || addrlen ==
nullptr) {
237 return this->
ip2sockaddr_(&this->
pcb_->local_ip, this->pcb_->local_port, name, addrlen);
262 if (this->
pcb_ ==
nullptr) {
266 if (optlen ==
nullptr || optval ==
nullptr) {
270 if (level == SOL_SOCKET && optname == SO_REUSEADDR) {
277 *
reinterpret_cast<int *
>(optval) = 1;
281 if (level == SOL_SOCKET && optname == SO_RCVTIMEO) {
282 if (*optlen <
sizeof(
struct timeval)) {
287 auto *tv =
reinterpret_cast<struct timeval *
>(optval);
288 tv->tv_sec = ms / 1000;
289 tv->tv_usec = (ms % 1000) * 1000;
290 *optlen =
sizeof(
struct timeval);
293 if (level == IPPROTO_TCP && optname == TCP_NODELAY) {
298 *
reinterpret_cast<int *
>(optval) = this->
nodelay_;
309 if (this->
pcb_ ==
nullptr) {
313 if (level == SOL_SOCKET && optname == SO_REUSEADDR) {
322 if (level == SOL_SOCKET && optname == SO_RCVTIMEO) {
323 if (optlen <
sizeof(
struct timeval)) {
327 const auto *tv =
reinterpret_cast<const struct timeval *
>(optval);
328 uint32_t ms = tv->tv_sec * 1000 + tv->tv_usec / 1000;
333 if (level == SOL_SOCKET && optname == SO_SNDTIMEO) {
337 if (level == IPPROTO_TCP && optname == TCP_NODELAY) {
342 int val = *
reinterpret_cast<const int *
>(optval);
352 if (this->
family_ == AF_INET) {
362 inet_addr_from_ip4addr(&addr->
sin_addr, ip_2_ip4(ip));
366 else if (this->
family_ == AF_INET6) {
380 ip4_2_ipv4_mapped_ipv6(ip_2_ip6(&mapped), ip_2_ip4(ip));
381 inet6_addr_from_ip6addr(&addr->
sin6_addr, ip_2_ip6(&mapped));
383 inet6_addr_from_ip6addr(&addr->
sin6_addr, ip_2_ip6(ip));
398 if (this->
rx_buf_ !=
nullptr) {
407 LWIP_LOG(
"init(%p)", this->
pcb_);
408 tcp_arg(this->
pcb_,
this);
411 if (initial_rx !=
nullptr) {
426 auto *arg_this =
reinterpret_cast<LWIPRawImpl *
>(arg);
427 ESP_LOGVV(TAG,
"socket %p: err(err=%d)", arg_this, err);
428 arg_this->pcb_ =
nullptr;
432 auto *arg_this =
reinterpret_cast<LWIPRawImpl *
>(arg);
433 return arg_this->
recv_fn(pb, err);
439 LWIP_LOG(
"recv(pb=%p err=%d)", pb, err);
453 if (this->
rx_buf_ ==
nullptr) {
476 if (elapsed >= timeout_ms)
484 if (this->
pcb_ ==
nullptr) {
494 if (this->
rx_buf_ ==
nullptr) {
500 uint8_t *buf8 =
reinterpret_cast<uint8_t *
>(buf);
502 size_t pb_len = this->
rx_buf_->len;
506 size_t copysize = std::min(
len, pb_left);
507 memcpy(buf8,
reinterpret_cast<uint8_t *
>(this->
rx_buf_->payload) + this->rx_buf_offset_, copysize);
509 if (pb_left == copysize) {
511 if (this->
rx_buf_->next ==
nullptr) {
515 this->rx_buf_offset_ = 0;
521 this->rx_buf_offset_ = 0;
524 this->rx_buf_offset_ += copysize;
526 LWIP_LOG(
"tcp_recved(%p %u)", this->
pcb_, copysize);
527 tcp_recved(this->
pcb_, copysize);
548 optimistic_yield(ESP8266_YIELD_INTERVAL_US);
570 for (
int i = 0; i < iovcnt; i++) {
571 ssize_t err = this->
read_locked_(
reinterpret_cast<uint8_t *
>(iov[i].iov_base), iov[i].iov_len);
580 if ((
size_t) err != iov[i].iov_len)
588 if (this->
pcb_ ==
nullptr) {
594 if (buf ==
nullptr) {
598 auto space = tcp_sndbuf(this->
pcb_);
603 size_t to_send = std::min((
size_t) space,
len);
604 LWIP_LOG(
"tcp_write(%p buf=%p %u)", this->
pcb_, buf, to_send);
605 err_t err = tcp_write(this->
pcb_, buf, to_send, TCP_WRITE_FLAG_COPY);
606 if (err == ERR_MEM) {
607 LWIP_LOG(
" -> err ERR_MEM");
612 LWIP_LOG(
" -> err %d", err);
621 if (this->
pcb_ ==
nullptr) {
625 LWIP_LOG(
"tcp_output(%p)", this->
pcb_);
626 err_t err = tcp_output(this->
pcb_);
628 LWIP_LOG(
" -> err %d", err);
634 if (err != ERR_ABRT) {
643 optimistic_yield(ESP8266_YIELD_INTERVAL_US);
668 for (
int i = 0; i < iovcnt; i++) {
678 if ((
size_t) err != iov[i].iov_len)
698 for (uint8_t i = 0; i < this->accepted_socket_count_; i++) {
699 auto &entry = this->accepted_pcbs_[i];
700 if (entry.pcb !=
nullptr) {
701 pcb_detach_abort(entry.pcb);
704 if (entry.rx_buf !=
nullptr) {
705 pbuf_free(entry.rx_buf);
706 entry.rx_buf =
nullptr;
709 this->accepted_socket_count_ = 0;
718 if (this->
pcb_ !=
nullptr) {
719 tcp_close(this->
pcb_);
720 this->
pcb_ =
nullptr;
726 LWIP_LOG(
"init(%p)", this->
pcb_);
727 tcp_arg(this->
pcb_,
this);
728 tcp_accept(this->
pcb_, LWIPRawListenImpl::s_accept_fn);
736 ESP_LOGVV(TAG,
"socket %p: err(err=%d)", arg_this, err);
737 arg_this->pcb_ =
nullptr;
740void LWIPRawListenImpl::s_queued_err_fn(
void *arg, err_t err) {
746 auto *entry =
reinterpret_cast<QueuedPcb *
>(arg);
747 entry->pcb =
nullptr;
751err_t LWIPRawListenImpl::s_queued_recv_fn(
void *arg,
struct tcp_pcb *pcb,
struct pbuf *pb, err_t err) {
758 auto *entry =
reinterpret_cast<QueuedPcb *
>(arg);
759 if (pb ==
nullptr || err != ERR_OK) {
764 entry->rx_closed =
true;
768 if (entry->rx_buf ==
nullptr) {
771 pbuf_cat(entry->rx_buf, pb);
776err_t LWIPRawListenImpl::s_accept_fn(
void *arg,
struct tcp_pcb *newpcb, err_t err) {
777 auto *arg_this =
reinterpret_cast<LWIPRawListenImpl *
>(arg);
778 return arg_this->accept_fn_(newpcb, err);
783 if (this->
pcb_ ==
nullptr) {
789 while (this->accepted_socket_count_ > 0) {
790 QueuedPcb entry = this->accepted_pcbs_[0];
793 for (uint8_t i = 1; i < this->accepted_socket_count_; i++) {
794 this->accepted_pcbs_[i - 1] = this->accepted_pcbs_[i];
795 if (this->accepted_pcbs_[i - 1].pcb !=
nullptr) {
796 tcp_arg(this->accepted_pcbs_[i - 1].pcb, &this->accepted_pcbs_[i - 1]);
799 this->accepted_pcbs_[this->accepted_socket_count_ - 1] = {};
800 this->accepted_socket_count_--;
801 if (entry.pcb ==
nullptr) {
803 if (entry.rx_buf !=
nullptr) {
804 pbuf_free(entry.rx_buf);
808 LWIP_LOG(
"Connection accepted by application, queue size: %d", this->accepted_socket_count_);
811 auto sock = make_unique<LWIPRawImpl>(this->
family_, entry.pcb);
812 sock->init(entry.rx_buf, entry.rx_closed);
813 if (addr !=
nullptr) {
814 sock->getpeername(addr, addrlen);
816 LWIP_LOG(
"accept(%p)", sock.get());
825 if (this->
pcb_ ==
nullptr) {
829 LWIP_LOG(
"tcp_listen_with_backlog(%p backlog=%d)", this->
pcb_, backlog);
830 struct tcp_pcb *listen_pcb = tcp_listen_with_backlog(this->
pcb_, backlog);
831 if (listen_pcb ==
nullptr) {
832 tcp_abort(this->
pcb_);
833 this->
pcb_ =
nullptr;
838 this->
pcb_ = listen_pcb;
840 LWIP_LOG(
"tcp_arg(%p)", this->
pcb_);
841 tcp_arg(this->
pcb_,
this);
842 tcp_accept(this->
pcb_, LWIPRawListenImpl::s_accept_fn);
849err_t LWIPRawListenImpl::accept_fn_(
struct tcp_pcb *newpcb, err_t err) {
852 LWIP_LOG(
"accept(newpcb=%p err=%d)", newpcb, err);
853 if (err != ERR_OK || newpcb ==
nullptr) {
861 if (this->accepted_socket_count_ >= MAX_ACCEPTED_SOCKETS) {
862 LWIP_LOG(
"Rejecting connection, queue full (%d)", this->accepted_socket_count_);
870 uint8_t idx = this->accepted_socket_count_++;
871 this->accepted_pcbs_[idx] = {newpcb,
nullptr,
false};
877 tcp_arg(newpcb, &this->accepted_pcbs_[idx]);
878 tcp_err(newpcb, LWIPRawListenImpl::s_queued_err_fn);
879 tcp_recv(newpcb, LWIPRawListenImpl::s_queued_recv_fn);
880 LWIP_LOG(
"Accepted connection, queue size: %d", this->accepted_socket_count_);
881#ifdef USE_OTA_PLATFORM_ESPHOME
892std::unique_ptr<Socket>
socket(
int domain,
int type,
int protocol) {
893 if (
type != SOCK_STREAM) {
894 ESP_LOGE(TAG,
"UDP sockets not supported on this platform, use WiFiUDP");
899 auto *pcb = tcp_new();
902 auto *sock =
new LWIPRawImpl((
sa_family_t) domain, pcb);
904 return std::unique_ptr<Socket>{sock};
913 if (
type != SOCK_STREAM) {
914 ESP_LOGE(TAG,
"UDP sockets not supported on this platform, use WiFiUDP");
919 auto *pcb = tcp_new();
924 return std::unique_ptr<ListenSocket>{sock};
int getsockname(struct sockaddr *name, socklen_t *addrlen)
size_t getsockname_to(std::span< char, SOCKADDR_STR_LEN > buf)
Format local address into a fixed-size buffer (no heap allocation)
int bind(const struct sockaddr *name, socklen_t addrlen)
int ip2sockaddr_(ip_addr_t *ip, uint16_t port, struct sockaddr *name, socklen_t *addrlen)
int setsockopt(int level, int optname, const void *optval, socklen_t optlen)
int getsockopt(int level, int optname, void *optval, socklen_t *optlen)
int getpeername(struct sockaddr *name, socklen_t *addrlen)
size_t getpeername_to(std::span< char, SOCKADDR_STR_LEN > buf)
Format peer address into a fixed-size buffer (no heap allocation)
Connected socket implementation for LWIP raw TCP.
ssize_t read_locked_(void *buf, size_t len)
static err_t s_recv_fn(void *arg, struct tcp_pcb *pcb, struct pbuf *pb, err_t err)
void init(struct pbuf *initial_rx=nullptr, bool initial_rx_closed=false)
bool waiting_for_data_() const
ssize_t readv(const struct iovec *iov, int iovcnt)
static void s_err_fn(void *arg, err_t err)
err_t recv_fn(struct pbuf *pb, err_t err)
ssize_t internal_write_(const void *buf, size_t len)
ssize_t write(const void *buf, size_t len)
ssize_t read(void *buf, size_t len)
ssize_t writev(const struct iovec *iov, int iovcnt)
Listening socket implementation for LWIP raw TCP.
static void s_err_fn(void *arg, err_t err)
std::unique_ptr< LWIPRawImpl > accept(struct sockaddr *addr, socklen_t *addrlen)
void esphome_wake_ota_component_any_context()
void ESPHOME_ALWAYS_INLINE wakeable_delay(uint32_t ms)
Host wakeable_delay uses select() over the registered fds — defined in wake_host.cpp.
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< ListenSocket > socket_listen(int domain, int type, int protocol)
Create a listening socket of the given domain, type and protocol.
std::unique_ptr< ListenSocket > socket_listen_loop_monitored(int domain, int type, int protocol)
std::unique_ptr< Socket > socket(int domain, int type, int protocol)
Create a socket of the given domain, type and protocol.
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.
void esphome_wake_ota_component_any_context()
uint32_t IRAM_ATTR HOT millis()
void IRAM_ATTR wake_loop_any_context()
IRAM_ATTR entry point for ISR callers — defined in wake_esp8266.cpp.
union ip_addr_t::@147 u_addr
struct in6_addr sin6_addr
Platform-specific main loop wake primitives.