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;
52static inline void yield_to_sys() { optimistic_yield(ESP8266_YIELD_INTERVAL_US); }
54static inline void yield_to_sys() {}
58static int lwip_err_to_errno(err_t err) {
80#define LWIP_LOG(msg, ...) ESP_LOGVV(TAG, "socket %p: " msg, this, ##__VA_ARGS__)
82#define LWIP_LOG(msg, ...)
92static void pcb_detach_abort(
struct tcp_pcb *pcb) {
93 tcp_arg(pcb,
nullptr);
94 tcp_recv(pcb,
nullptr);
95 tcp_err(pcb,
nullptr);
106static err_t pcb_detach_close(
struct tcp_pcb *pcb) {
107 tcp_arg(pcb,
nullptr);
108 tcp_recv(pcb,
nullptr);
109 tcp_err(pcb,
nullptr);
110 err_t err = tcp_close(pcb);
121 if (this->
pcb_ !=
nullptr) {
122 LWIP_LOG(
"tcp_abort(%p)", this->
pcb_);
123 pcb_detach_abort(this->
pcb_);
124 this->
pcb_ =
nullptr;
129 if (name ==
nullptr) {
134 if (this->
family_ == AF_INET6) {
139 auto *addr6 =
reinterpret_cast<const sockaddr_in6 *
>(name);
140 *port = ntohs(addr6->sin6_port);
141 inet6_addr_to_ip6addr(ip_2_ip6(ip), &addr6->sin6_addr);
143 IP_SET_TYPE_VAL(*ip, IPADDR_TYPE_ANY);
151 auto *addr4 =
reinterpret_cast<const sockaddr_in *
>(name);
152 *port = ntohs(addr4->sin_port);
153 ip_addr_set_ip4_u32(ip, addr4->sin_addr.s_addr);
159 if (this->
pcb_ ==
nullptr) {
168 LWIP_LOG(
"tcp_bind(%p ip=%s port=%u)", this->
pcb_, ipaddr_ntoa(&ip), port);
169 err_t err = tcp_bind(this->
pcb_, &ip, port);
171 LWIP_LOG(
" -> err %d", err);
172 errno = lwip_err_to_errno(err);
180 if (this->
pcb_ ==
nullptr) {
184 LWIP_LOG(
"tcp_close(%p)", this->
pcb_);
185 err_t err = pcb_detach_close(this->
pcb_);
186 this->
pcb_ =
nullptr;
188 LWIP_LOG(
" -> err %d", err);
189 errno = lwip_err_to_errno(err);
197 if (this->
pcb_ ==
nullptr) {
201 bool shut_rx =
false, shut_tx =
false;
202 if (how == SHUT_RD) {
204 }
else if (how == SHUT_WR) {
206 }
else if (how == SHUT_RDWR) {
207 shut_rx = shut_tx =
true;
212 LWIP_LOG(
"tcp_shutdown(%p shut_rx=%d shut_tx=%d)", this->
pcb_, shut_rx ? 1 : 0, shut_tx ? 1 : 0);
213 err_t err = tcp_shutdown(this->
pcb_, shut_rx, shut_tx);
215 LWIP_LOG(
" -> err %d", err);
216 errno = lwip_err_to_errno(err);
224 if (this->
pcb_ ==
nullptr) {
228 if (name ==
nullptr || addrlen ==
nullptr) {
232 return this->
ip2sockaddr_(&this->
pcb_->remote_ip, this->pcb_->remote_port, name, addrlen);
237 if (this->
pcb_ ==
nullptr) {
241 if (name ==
nullptr || addrlen ==
nullptr) {
245 return this->
ip2sockaddr_(&this->
pcb_->local_ip, this->pcb_->local_port, name, addrlen);
270 if (this->
pcb_ ==
nullptr) {
274 if (optlen ==
nullptr || optval ==
nullptr) {
278 if (level == SOL_SOCKET && optname == SO_REUSEADDR) {
285 *
reinterpret_cast<int *
>(optval) = 1;
289 if (level == SOL_SOCKET && optname == SO_RCVTIMEO) {
290 if (*optlen <
sizeof(
struct timeval)) {
295 auto *tv =
reinterpret_cast<struct timeval *
>(optval);
296 tv->tv_sec = ms / 1000;
297 tv->tv_usec = (ms % 1000) * 1000;
298 *optlen =
sizeof(
struct timeval);
301 if (level == IPPROTO_TCP && optname == TCP_NODELAY) {
306 *
reinterpret_cast<int *
>(optval) = this->
nodelay_;
317 if (this->
pcb_ ==
nullptr) {
321 if (level == SOL_SOCKET && optname == SO_REUSEADDR) {
330 if (level == SOL_SOCKET && optname == SO_RCVTIMEO) {
331 if (optlen <
sizeof(
struct timeval)) {
335 const auto *tv =
reinterpret_cast<const struct timeval *
>(optval);
336 uint32_t ms = tv->tv_sec * 1000 + tv->tv_usec / 1000;
341 if (level == SOL_SOCKET && optname == SO_SNDTIMEO) {
345 if (level == IPPROTO_TCP && optname == TCP_NODELAY) {
350 int val = *
reinterpret_cast<const int *
>(optval);
360 if (this->
family_ == AF_INET) {
370 inet_addr_from_ip4addr(&addr->
sin_addr, ip_2_ip4(ip));
374 else if (this->
family_ == AF_INET6) {
388 ip4_2_ipv4_mapped_ipv6(ip_2_ip6(&mapped), ip_2_ip4(ip));
389 inet6_addr_from_ip6addr(&addr->
sin6_addr, ip_2_ip6(&mapped));
391 inet6_addr_from_ip6addr(&addr->
sin6_addr, ip_2_ip6(ip));
406 if (this->
rx_buf_ !=
nullptr) {
415 LWIP_LOG(
"init(%p)", this->
pcb_);
416 tcp_arg(this->
pcb_,
this);
419 if (initial_rx !=
nullptr) {
434 auto *arg_this =
reinterpret_cast<LWIPRawImpl *
>(arg);
435 ESP_LOGVV(TAG,
"socket %p: err(err=%d)", arg_this, err);
436 if (arg_this->connect_err_ == EINPROGRESS) {
439 arg_this->connect_err_ = err == ERR_RST ? ECONNREFUSED : ETIMEDOUT;
441 arg_this->pcb_ =
nullptr;
447 auto *arg_this =
reinterpret_cast<LWIPRawImpl *
>(arg);
455 if (this->
pcb_ ==
nullptr) {
460 errno = this->
connect_err_ == EINPROGRESS ? EALREADY : EISCONN;
470 if (IP_IS_ANY_TYPE_VAL(ip)) {
471 if (ip6_addr_isipv4mappedipv6(ip_2_ip6(&ip))) {
472 unmap_ipv4_mapped_ipv6(ip_2_ip4(&ip), ip_2_ip6(&ip));
479 LWIP_LOG(
"tcp_connect(%p ip=%s port=%u)", this->
pcb_, ipaddr_ntoa(&ip), port);
482 LWIP_LOG(
" -> err %d", err);
483 errno = lwip_err_to_errno(err);
493 if (this->
pcb_ ==
nullptr) {
515 auto *arg_this =
reinterpret_cast<LWIPRawImpl *
>(arg);
516 return arg_this->
recv_fn(pb, err);
522 LWIP_LOG(
"recv(pb=%p err=%d)", pb, err);
536 if (this->
rx_buf_ ==
nullptr) {
559 if (elapsed >= timeout_ms)
567 if (this->
pcb_ ==
nullptr) {
577 if (this->
rx_buf_ ==
nullptr) {
583 uint8_t *buf8 =
reinterpret_cast<uint8_t *
>(buf);
585 size_t pb_len = this->
rx_buf_->len;
589 size_t copysize = std::min(
len, pb_left);
590 memcpy(buf8,
reinterpret_cast<uint8_t *
>(this->
rx_buf_->payload) + this->rx_buf_offset_, copysize);
592 if (pb_left == copysize) {
594 if (this->
rx_buf_->next ==
nullptr) {
598 this->rx_buf_offset_ = 0;
604 this->rx_buf_offset_ = 0;
607 this->rx_buf_offset_ += copysize;
609 LWIP_LOG(
"tcp_recved(%p %u)", this->
pcb_, copysize);
610 tcp_recved(this->
pcb_, copysize);
650 for (
int i = 0; i < iovcnt; i++) {
651 ssize_t err = this->
read_locked_(
reinterpret_cast<uint8_t *
>(iov[i].iov_base), iov[i].iov_len);
660 if ((
size_t) err != iov[i].iov_len)
668 if (this->
pcb_ ==
nullptr) {
674 if (buf ==
nullptr) {
678 auto space = tcp_sndbuf(this->
pcb_);
683 size_t to_send = std::min((
size_t) space,
len);
684 LWIP_LOG(
"tcp_write(%p buf=%p %u)", this->
pcb_, buf, to_send);
685 err_t err = tcp_write(this->
pcb_, buf, to_send, TCP_WRITE_FLAG_COPY);
686 if (err == ERR_MEM) {
687 LWIP_LOG(
" -> err ERR_MEM");
692 LWIP_LOG(
" -> err %d", err);
701 if (this->
pcb_ ==
nullptr) {
705 LWIP_LOG(
"tcp_output(%p)", this->
pcb_);
706 err_t err = tcp_output(this->
pcb_);
708 LWIP_LOG(
" -> err %d", err);
714 if (err != ERR_ABRT) {
746 for (
int i = 0; i < iovcnt; i++) {
756 if ((
size_t) err != iov[i].iov_len)
776 for (uint8_t i = 0; i < this->accepted_socket_count_; i++) {
777 auto &entry = this->accepted_pcbs_[i];
778 if (entry.pcb !=
nullptr) {
779 pcb_detach_abort(entry.pcb);
782 if (entry.rx_buf !=
nullptr) {
783 pbuf_free(entry.rx_buf);
784 entry.rx_buf =
nullptr;
787 this->accepted_socket_count_ = 0;
796 if (this->
pcb_ !=
nullptr) {
797 tcp_close(this->
pcb_);
798 this->
pcb_ =
nullptr;
804 LWIP_LOG(
"init(%p)", this->
pcb_);
805 tcp_arg(this->
pcb_,
this);
806 tcp_accept(this->
pcb_, LWIPRawListenImpl::s_accept_fn);
814 ESP_LOGVV(TAG,
"socket %p: err(err=%d)", arg_this, err);
815 arg_this->pcb_ =
nullptr;
818void LWIPRawListenImpl::s_queued_err_fn(
void *arg, err_t err) {
824 auto *entry =
reinterpret_cast<QueuedPcb *
>(arg);
825 entry->pcb =
nullptr;
829err_t LWIPRawListenImpl::s_queued_recv_fn(
void *arg,
struct tcp_pcb *pcb,
struct pbuf *pb, err_t err) {
836 auto *entry =
reinterpret_cast<QueuedPcb *
>(arg);
837 if (pb ==
nullptr || err != ERR_OK) {
842 entry->rx_closed =
true;
846 if (entry->rx_buf ==
nullptr) {
849 pbuf_cat(entry->rx_buf, pb);
854err_t LWIPRawListenImpl::s_accept_fn(
void *arg,
struct tcp_pcb *newpcb, err_t err) {
855 auto *arg_this =
reinterpret_cast<LWIPRawListenImpl *
>(arg);
856 return arg_this->accept_fn_(newpcb, err);
861 if (this->
pcb_ ==
nullptr) {
867 while (this->accepted_socket_count_ > 0) {
868 QueuedPcb entry = this->accepted_pcbs_[0];
871 for (uint8_t i = 1; i < this->accepted_socket_count_; i++) {
872 this->accepted_pcbs_[i - 1] = this->accepted_pcbs_[i];
873 if (this->accepted_pcbs_[i - 1].pcb !=
nullptr) {
874 tcp_arg(this->accepted_pcbs_[i - 1].pcb, &this->accepted_pcbs_[i - 1]);
877 this->accepted_pcbs_[this->accepted_socket_count_ - 1] = {};
878 this->accepted_socket_count_--;
879 if (entry.pcb ==
nullptr) {
881 if (entry.rx_buf !=
nullptr) {
882 pbuf_free(entry.rx_buf);
886 LWIP_LOG(
"Connection accepted by application, queue size: %d", this->accepted_socket_count_);
889 auto sock = make_unique<LWIPRawImpl>(this->
family_, entry.pcb);
890 sock->init(entry.rx_buf, entry.rx_closed);
891 if (addr !=
nullptr) {
892 sock->getpeername(addr, addrlen);
894 LWIP_LOG(
"accept(%p)", sock.get());
903 if (this->
pcb_ ==
nullptr) {
907 LWIP_LOG(
"tcp_listen_with_backlog(%p backlog=%d)", this->
pcb_, backlog);
908 struct tcp_pcb *listen_pcb = tcp_listen_with_backlog(this->
pcb_, backlog);
909 if (listen_pcb ==
nullptr) {
910 tcp_abort(this->
pcb_);
911 this->
pcb_ =
nullptr;
916 this->
pcb_ = listen_pcb;
918 LWIP_LOG(
"tcp_arg(%p)", this->
pcb_);
919 tcp_arg(this->
pcb_,
this);
920 tcp_accept(this->
pcb_, LWIPRawListenImpl::s_accept_fn);
927err_t LWIPRawListenImpl::accept_fn_(
struct tcp_pcb *newpcb, err_t err) {
930 LWIP_LOG(
"accept(newpcb=%p err=%d)", newpcb, err);
931 if (err != ERR_OK || newpcb ==
nullptr) {
939 if (this->accepted_socket_count_ >= MAX_ACCEPTED_SOCKETS) {
940 LWIP_LOG(
"Rejecting connection, queue full (%d)", this->accepted_socket_count_);
948 uint8_t idx = this->accepted_socket_count_++;
949 this->accepted_pcbs_[idx] = {newpcb,
nullptr,
false};
955 tcp_arg(newpcb, &this->accepted_pcbs_[idx]);
956 tcp_err(newpcb, LWIPRawListenImpl::s_queued_err_fn);
957 tcp_recv(newpcb, LWIPRawListenImpl::s_queued_recv_fn);
958 LWIP_LOG(
"Accepted connection, queue size: %d", this->accepted_socket_count_);
959#ifdef USE_OTA_PLATFORM_ESPHOME
970std::unique_ptr<Socket>
socket(
int domain,
int type,
int protocol) {
971 if (
type != SOCK_STREAM) {
972 ESP_LOGE(TAG,
"UDP sockets not supported on this platform, use WiFiUDP");
977 auto *pcb = tcp_new();
980 auto *sock =
new LWIPRawImpl((
sa_family_t) domain, pcb);
982 return std::unique_ptr<Socket>{sock};
991 if (
type != SOCK_STREAM) {
992 ESP_LOGE(TAG,
"UDP sockets not supported on this platform, use WiFiUDP");
997 auto *pcb = tcp_new();
1002 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)
bool sockaddr2ip_(const struct sockaddr *name, socklen_t addrlen, ip_addr_t *ip, uint16_t *port) const
sockaddr of this socket's family to lwip address and port; false with errno on mismatch
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)
ConnectPollResult poll_connect(int &err_out) const
int connect(const struct sockaddr *addr, socklen_t addrlen)
Non-blocking: returns -1/EINPROGRESS once the SYN is queued, see poll_connect().
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)
static err_t s_connected_fn(void *arg, struct tcp_pcb *pcb, err_t err)
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.
ConnectPollResult
Outcome of polling a non-blocking connect(); see socket::poll_connect().
@ CONNECT_POLL_RESULT_CONNECTED
@ CONNECT_POLL_RESULT_ERROR
@ CONNECT_POLL_RESULT_PENDING
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.
struct in6_addr sin6_addr
Platform-specific main loop wake primitives.