11#include <sys/socket.h>
16#include <netinet/in.h>
17#include <netinet/tcp.h>
18#ifdef LIBE3_ENABLE_SCTP
19#include <netinet/sctp.h>
35constexpr const char* LOG_TAG =
"PosixConn";
36constexpr const char* IPC_BASE_DIR =
"/tmp/dapps";
39constexpr const char* SHARED_DEFAULT_ENDPOINT =
"ipc:///tmp/dapps/setup";
40constexpr const char* DEFAULT_IPC_PATH =
"/tmp/dapps/e3";
41constexpr int POLL_TIMEOUT_MS = 500;
42constexpr int SEND_TIMEOUT_MS = 500;
43constexpr int CONNECT_ATTEMPTS = 10;
44constexpr int CONNECT_PAUSE_MS = 200;
45constexpr int LISTEN_BACKLOG = 64;
47constexpr uint32_t SCTP_PPID = 0x00E3A001;
48constexpr int SCTP_PROCEDURE_STREAM = 0;
49constexpr int SCTP_INDICATION_STREAM = 1;
50constexpr int64_t SETUP_PUMP_AFTER_NS = 1'000'000'000;
53 return std::chrono::duration_cast<std::chrono::nanoseconds>(
54 std::chrono::steady_clock::now().time_since_epoch()).count();
58int wait_readable(
int fd,
int timeout_ms) {
59 struct pollfd pfd{fd, POLLIN, 0};
60 return poll(&pfd, 1, timeout_ms);
66std::string strip_scheme(
const std::string& endpoint) {
67 auto pos = endpoint.find(
"://");
68 return pos == std::string::npos ? endpoint : endpoint.substr(pos + 3);
79int sctp_socket(
int family) {
80#ifdef LIBE3_ENABLE_SCTP
81 return socket(family, SOCK_STREAM, IPPROTO_SCTP);
84 E3_LOG_ERROR(LOG_TAG) <<
"SCTP transport requested but libe3 was built without it. "
85 "Rebuild with -DLIBE3_ENABLE_SCTP=ON (needs libsctp-dev), "
86 "or use the TCP or IPC transport.";
87 errno = EPROTONOSUPPORT;
92void set_timeout(
int fd,
int option,
int timeout_ms,
const char* name) {
94 tv.tv_sec = timeout_ms / 1000;
95 tv.tv_usec = (timeout_ms % 1000) * 1000;
96 if (setsockopt(fd, SOL_SOCKET, option, &tv,
sizeof(tv)) != 0) {
97 E3_LOG_WARN(LOG_TAG) <<
"Failed to set " << name <<
": " << strerror(errno);
101void set_nonblocking(
int fd) {
102 int flags = fcntl(fd, F_GETFL, 0);
103 if (flags < 0 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
104 E3_LOG_WARN(LOG_TAG) <<
"Failed to set O_NONBLOCK: " << strerror(errno);
113enum class Read { PDU,
NONE, CLOSED,
ERROR };
120Read pop_stream_frame(std::vector<uint8_t>& rx, std::vector<uint8_t>& out) {
121 if (rx.size() <
sizeof(uint32_t)) {
125 std::memcpy(&size, rx.data(),
sizeof(size));
127 if (size == 0 || size > MAX_PDU) {
131 if (rx.size() <
sizeof(uint32_t) + size) {
134 out.assign(rx.begin() +
sizeof(uint32_t), rx.begin() +
sizeof(uint32_t) + size);
135 rx.erase(rx.begin(), rx.begin() +
sizeof(uint32_t) + size);
139bool would_block(
int error) {
140 return error == EINTR || error == EAGAIN || error == EWOULDBLOCK;
152Read read_one(
int fd,
E3TransportLayer transport, std::vector<uint8_t>& rx, std::vector<uint8_t>& out) {
154 if (Read buffered = pop_stream_frame(rx, out); buffered != Read::NONE) {
157 std::array<uint8_t, 16384> chunk;
158 ssize_t n = ::recv(fd, chunk.data(), chunk.size(), 0);
160 rx.insert(rx.end(), chunk.begin(), chunk.begin() + n);
161 return pop_stream_frame(rx, out);
166 return would_block(errno) ? Read::NONE : Read::ERROR;
171 struct iovec iov{out.data(), out.size()};
175 ssize_t n = ::recvmsg(fd, &msg, 0);
177 return would_block(errno) ? Read::NONE : Read::ERROR;
182 if (msg.msg_flags & MSG_TRUNC) {
183 E3_LOG_ERROR(LOG_TAG) <<
"PDU longer than " << MAX_PDU <<
" bytes";
186 out.resize(
static_cast<size_t>(n));
190#ifdef LIBE3_ENABLE_SCTP
191 static thread_local std::array<uint8_t, MAX_PDU> chunk;
192 alignas(
struct cmsghdr) char control[CMSG_SPACE(sizeof(struct sctp_rcvinfo))];
193 struct iovec iov{chunk.data(), chunk.size()};
197 msg.msg_control = control;
198 msg.msg_controllen =
sizeof(control);
199 ssize_t n = ::recvmsg(fd, &msg, 0);
201 return would_block(errno) ? Read::NONE : Read::ERROR;
206 if (msg.msg_flags & MSG_NOTIFICATION) {
210 for (
struct cmsghdr* c = CMSG_FIRSTHDR(&msg); c !=
nullptr; c = CMSG_NXTHDR(&msg, c)) {
211 if (c->cmsg_level == IPPROTO_SCTP && c->cmsg_type == SCTP_RCVINFO) {
212 struct sctp_rcvinfo info;
213 std::memcpy(&info, CMSG_DATA(c),
sizeof(info));
214 const uint32_t ppid = ntohl(info.rcv_ppid);
215 if (ppid != 0 && ppid != SCTP_PPID) {
216 E3_LOG_ERROR(LOG_TAG) <<
"Message with payload protocol id 0x" << std::hex << ppid;
222 rx.insert(rx.end(), chunk.begin(), chunk.begin() + n);
223 if (rx.size() > MAX_PDU) {
224 E3_LOG_ERROR(LOG_TAG) <<
"PDU longer than " << MAX_PDU <<
" bytes";
227 if (msg.msg_flags & MSG_EOR) {
248 if (data.empty() || data.size() > MAX_PDU) {
249 E3_LOG_ERROR(LOG_TAG) <<
"PDU of " << data.size() <<
" bytes cannot be sent";
250 return ErrorCode::INVALID_PARAM;
254 uint32_t prefix = htonl(
static_cast<uint32_t
>(data.size()));
256 iov[0].iov_base = &prefix;
257 iov[0].iov_len =
sizeof(prefix);
258 iov[1].iov_base =
const_cast<uint8_t*
>(data.data());
259 iov[1].iov_len = data.size();
261 const size_t total =
sizeof(prefix) + data.size();
263 while (sent < total) {
264 struct iovec cur[2] = {iov[0], iov[1]};
267 while (first < 2 && skip >= cur[first].iov_len) {
268 skip -= cur[first].iov_len;
271 cur[first].iov_base =
static_cast<uint8_t*
>(cur[first].iov_base) + skip;
272 cur[first].iov_len -= skip;
274 msg.msg_iov = cur + first;
275 msg.msg_iovlen = 2 - first;
276 ssize_t n = ::sendmsg(fd, &msg, MSG_NOSIGNAL);
278 if (errno == EINTR) {
281 E3_LOG_ERROR(LOG_TAG) <<
"Failed to send: " << strerror(errno);
282 return ErrorCode::TRANSPORT_ERROR;
284 sent +=
static_cast<size_t>(n);
286 return ErrorCode::SUCCESS;
292 n = ::send(fd, data.data(), data.size(), MSG_NOSIGNAL);
293 }
while (n < 0 && errno == EINTR);
294 if (n < 0 ||
static_cast<size_t>(n) != data.size()) {
295 E3_LOG_ERROR(LOG_TAG) <<
"Failed to send: " << strerror(errno);
296 return ErrorCode::TRANSPORT_ERROR;
298 return ErrorCode::SUCCESS;
301#ifdef LIBE3_ENABLE_SCTP
302 alignas(
struct cmsghdr) char control[CMSG_SPACE(sizeof(struct sctp_sndinfo))]{};
303 struct iovec iov{
const_cast<uint8_t*
>(data.data()), data.size()};
307 msg.msg_control = control;
308 msg.msg_controllen =
sizeof(control);
309 struct cmsghdr* c = CMSG_FIRSTHDR(&msg);
310 c->cmsg_level = IPPROTO_SCTP;
311 c->cmsg_type = SCTP_SNDINFO;
312 c->cmsg_len = CMSG_LEN(
sizeof(
struct sctp_sndinfo));
313 struct sctp_sndinfo info{};
315 info.snd_ppid = htonl(SCTP_PPID);
316 std::memcpy(CMSG_DATA(c), &info,
sizeof(info));
319 n = ::sendmsg(fd, &msg, MSG_NOSIGNAL);
320 }
while (n < 0 && errno == EINTR);
321 if (n < 0 ||
static_cast<size_t>(n) != data.size()) {
322 E3_LOG_ERROR(LOG_TAG) <<
"Failed to send: " << strerror(errno);
323 return ErrorCode::TRANSPORT_ERROR;
325 return ErrorCode::SUCCESS;
328 return ErrorCode::TRANSPORT_ERROR;
333std::string address_text(
const sockaddr_storage& ss) {
334 char text[INET6_ADDRSTRLEN] = {};
335 if (ss.ss_family == AF_INET) {
336 const auto* in =
reinterpret_cast<const sockaddr_in*
>(&ss);
337 inet_ntop(AF_INET, &in->sin_addr, text,
sizeof(text));
338 }
else if (ss.ss_family == AF_INET6) {
339 const auto* in6 =
reinterpret_cast<const sockaddr_in6*
>(&ss);
340 if (IN6_IS_ADDR_V4MAPPED(&in6->sin6_addr)) {
341 inet_ntop(AF_INET, &in6->sin6_addr.s6_addr[12], text,
sizeof(text));
343 inet_ntop(AF_INET6, &in6->sin6_addr, text,
sizeof(text));
354 std::vector<uint8_t>
rx;
382 const std::string& endpoint,
387 , endpoint_uri_(endpoint)
392 setup_endpoint_ = endpoint == SHARED_DEFAULT_ENDPOINT ? DEFAULT_IPC_PATH : strip_scheme(endpoint);
397 <<
" port " << port_;
404PosixE3Connector::Target PosixE3Connector::target()
const {
405 Target where{
"", std::to_string(port_)};
407 for (
const char* scheme : {
"tcp://",
"sctp://"}) {
408 if (endpoint_uri_.rfind(scheme, 0) == 0) {
409 rest = endpoint_uri_.substr(std::strlen(scheme));
416 if (rest[0] ==
'[') {
417 const auto close = rest.find(
']');
418 if (close == std::string::npos) {
421 where.host = rest.substr(1, close - 1);
422 if (close + 1 < rest.size() && rest[close + 1] ==
':') {
423 where.port = rest.substr(close + 2);
426 const auto colon = rest.rfind(
':');
427 if (colon != std::string::npos && rest.find(
':') == colon) {
428 where.host = rest.substr(0, colon);
429 where.port = rest.substr(colon + 1);
434 if (where.port.empty()) {
435 where.port = std::to_string(port_);
440int PosixE3Connector::make_socket(
int family)
const {
441 switch (transport_layer_) {
443 return socket(AF_UNIX, SOCK_SEQPACKET, 0);
445 return sctp_socket(family);
447 return socket(family, SOCK_STREAM, 0);
451void PosixE3Connector::tune_socket(
int fd, SocketKind kind)
const {
453 if (kind == SocketKind::ACCEPTED) {
454 set_timeout(fd, SO_SNDTIMEO, SEND_TIMEOUT_MS,
"SO_SNDTIMEO");
459 if (kind == SocketKind::LISTENER) {
460 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one,
sizeof(one));
462 if (kind != SocketKind::LISTENER) {
463 set_timeout(fd, SO_SNDTIMEO, SEND_TIMEOUT_MS,
"SO_SNDTIMEO");
466 if (kind != SocketKind::LISTENER && setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one,
sizeof(one)) != 0) {
467 E3_LOG_WARN(LOG_TAG) <<
"Failed to set TCP_NODELAY: " << strerror(errno);
471#ifdef LIBE3_ENABLE_SCTP
472 if (kind != SocketKind::ACCEPTED) {
475 struct sctp_initmsg init{};
476 init.sinit_num_ostreams = 2;
477 init.sinit_max_instreams = 2;
478 if (setsockopt(fd, IPPROTO_SCTP, SCTP_INITMSG, &init,
sizeof(init)) != 0) {
479 E3_LOG_WARN(LOG_TAG) <<
"Failed to request two SCTP streams: " << strerror(errno);
481 if (options_.socket_buffer_bytes > 0) {
482 const int size =
static_cast<int>(options_.socket_buffer_bytes);
483 setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &size,
sizeof(size));
484 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size,
sizeof(size));
486 if (!options_.sctp_delayed_sack) {
487 struct sctp_sack_info sack{};
488 sack.sack_assoc_id = 0;
491 if (setsockopt(fd, IPPROTO_SCTP, SCTP_DELAYED_SACK, &sack,
sizeof(sack)) != 0) {
492 E3_LOG_WARN(LOG_TAG) <<
"Failed to turn delayed SACK off: " << strerror(errno);
496 if (kind != SocketKind::LISTENER) {
497 if (setsockopt(fd, IPPROTO_SCTP, SCTP_NODELAY, &one,
sizeof(one)) != 0) {
498 E3_LOG_WARN(LOG_TAG) <<
"Failed to set SCTP_NODELAY: " << strerror(errno);
500 if (setsockopt(fd, IPPROTO_SCTP, SCTP_RECVRCVINFO, &one,
sizeof(one)) != 0) {
501 E3_LOG_WARN(LOG_TAG) <<
"Failed to ask for the SCTP receive info: " << strerror(errno);
507int PosixE3Connector::listen_on(
const Target& where) {
512 if (stat(IPC_BASE_DIR, &st) == -1 && mkdir(IPC_BASE_DIR, 0777) == -1 && errno != EEXIST) {
513 E3_LOG_ERROR(LOG_TAG) <<
"Failed to create IPC directory: " << strerror(errno);
516 chmod(IPC_BASE_DIR, 0777);
521 fd = make_socket(AF_UNIX);
525 struct sockaddr_un addr{};
526 addr.sun_family = AF_UNIX;
529 result = bind(fd,
reinterpret_cast<struct sockaddr*
>(&addr),
sizeof(addr));
530 }
else if (where.host.empty()) {
532 fd = make_socket(AF_INET6);
535 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &off,
sizeof(off));
536 tune_socket(fd, SocketKind::LISTENER);
537 struct sockaddr_in6 addr{};
538 addr.sin6_family = AF_INET6;
539 addr.sin6_addr = in6addr_any;
540 addr.sin6_port = htons(
static_cast<uint16_t
>(std::stoi(where.port)));
541 result = bind(fd,
reinterpret_cast<struct sockaddr*
>(&addr),
sizeof(addr));
548 fd = make_socket(AF_INET);
552 tune_socket(fd, SocketKind::LISTENER);
553 struct sockaddr_in addr{};
554 addr.sin_family = AF_INET;
555 addr.sin_addr.s_addr = INADDR_ANY;
556 addr.sin_port = htons(
static_cast<uint16_t
>(std::stoi(where.port)));
557 result = bind(fd,
reinterpret_cast<struct sockaddr*
>(&addr),
sizeof(addr));
560 struct addrinfo hints{};
561 hints.ai_family = AF_UNSPEC;
562 hints.ai_socktype = SOCK_STREAM;
563 hints.ai_flags = AI_PASSIVE;
564 struct addrinfo* found =
nullptr;
565 if (getaddrinfo(where.host.c_str(), where.port.c_str(), &hints, &found) != 0 || found ==
nullptr) {
566 E3_LOG_ERROR(LOG_TAG) <<
"Cannot resolve " << where.host;
569 fd = make_socket(found->ai_family);
571 tune_socket(fd, SocketKind::LISTENER);
572 result = bind(fd, found->ai_addr, found->ai_addrlen);
579 if (result < 0 || listen(fd, LISTEN_BACKLOG) < 0) {
588int PosixE3Connector::connect_to(
const Target& where) {
591 errno = ENAMETOOLONG;
594 int fd = make_socket(AF_UNIX);
598 struct sockaddr_un addr{};
599 addr.sun_family = AF_UNIX;
601 if (connect(fd,
reinterpret_cast<struct sockaddr*
>(&addr),
sizeof(addr)) < 0) {
602 const int saved = errno;
607 tune_socket(fd, SocketKind::CLIENT);
610 struct addrinfo hints{};
611 hints.ai_family = AF_UNSPEC;
612 hints.ai_socktype = SOCK_STREAM;
613 struct addrinfo* found =
nullptr;
614 const std::string host = where.host.empty() ?
"127.0.0.1" : where.host;
615 if (getaddrinfo(host.c_str(), where.port.c_str(), &hints, &found) != 0 || found ==
nullptr) {
616 errno = EHOSTUNREACH;
620 int saved = ECONNREFUSED;
621 for (
struct addrinfo* a = found; a !=
nullptr && fd < 0; a = a->ai_next) {
622 int candidate = make_socket(a->ai_family);
627 tune_socket(candidate, SocketKind::CLIENT);
628 if (connect(candidate, a->ai_addr, a->ai_addrlen) == 0) {
642bool PosixE3Connector::admit(
const void* address)
const {
646 const auto& ss = *
static_cast<const sockaddr_storage*
>(address);
647 if (!options_.allowed_peers.empty()) {
648 const std::string text = address_text(ss);
649 if (std::find(options_.allowed_peers.begin(), options_.allowed_peers.end(), text)
650 == options_.allowed_peers.end()) {
651 E3_LOG_WARN(LOG_TAG) <<
"Refused a connection from " << text <<
": not in the allowed peers";
655 if (options_.maximum_associations > 0) {
656 std::lock_guard<std::mutex> lock(peers_mutex_);
657 if (peers_.size() >= options_.maximum_associations) {
658 E3_LOG_WARN(LOG_TAG) <<
"Refused a connection from " << address_text(ss)
659 <<
": " << options_.maximum_associations <<
" peers are connected";
671 listener_ = listen_on(target());
673 return ErrorCode::CONNECTION_FAILED;
677 return ErrorCode::SUCCESS;
682 return listener_ >= 0 ? ErrorCode::SUCCESS : ErrorCode::NOT_INITIALIZED;
687 return listener_ >= 0 ? ErrorCode::SUCCESS : ErrorCode::NOT_INITIALIZED;
690void PosixE3Connector::accept_pending() {
691 while (listener_ >= 0 && wait_readable(listener_, 0) == 1) {
692 sockaddr_storage address{};
693 socklen_t length =
sizeof(address);
694 int fd = accept(listener_,
reinterpret_cast<struct sockaddr*
>(&address), &length);
698 if (!admit(&address)) {
702 tune_socket(fd, SocketKind::ACCEPTED);
703 auto peer = std::make_shared<Peer>(fd, next_token_++);
706 std::lock_guard<std::mutex> lock(peers_mutex_);
707 peers_.push_back(peer);
708 count = peers_.size();
710 E3_LOG_INFO(LOG_TAG) <<
"Peer connected (" << count <<
" total)";
714std::shared_ptr<PosixE3Connector::Peer> PosixE3Connector::find_peer(uint64_t token) {
715 std::lock_guard<std::mutex> lock(peers_mutex_);
716 for (
const auto& peer : peers_) {
717 if (peer->token == token) {
724void PosixE3Connector::drop_peer(
const std::shared_ptr<Peer>& peer) {
728 std::lock_guard<std::mutex> lock(peers_mutex_);
729 peers_.erase(std::remove(peers_.begin(), peers_.end(), peer), peers_.end());
730 remaining = peers_.size();
733 std::lock_guard<std::mutex> lock(closed_mutex_);
734 closed_peers_.push_back(peer->token);
736 if (!peer->seen_first) {
737 E3_LOG_INFO(LOG_TAG) <<
"A connection closed before it sent a complete setup request. A dApp built "
738 "before libe3 0.6 uses three connections and unframed messages, which "
739 "this endpoint does not serve.";
741 E3_LOG_INFO(LOG_TAG) <<
"Peer disconnected (" << remaining <<
" remain)";
744void PosixE3Connector::push_setup(
const std::shared_ptr<Peer>& peer, std::vector<uint8_t>&& pdu) {
746 std::lock_guard<std::mutex> lock(queue_mutex_);
747 setup_queue_.push_back(
Queued{peer, peer->token, std::move(pdu)});
749 setup_ready_.notify_one();
752bool PosixE3Connector::receiver_idle()
const {
753 return now_ns() - last_receive_ns_.load() > SETUP_PUMP_AFTER_NS;
762bool PosixE3Connector::pump(std::vector<uint8_t>& out, uint64_t& token,
int timeout_ms) {
763 std::vector<std::shared_ptr<Peer>> snapshot;
765 std::lock_guard<std::mutex> lock(peers_mutex_);
770 for (
const auto& peer : snapshot) {
774 while (!peer->rx.empty()) {
775 Read r = pop_stream_frame(peer->rx, out);
776 if (r == Read::ERROR) {
780 if (r != Read::PDU) {
783 if (!peer->seen_first) {
784 peer->seen_first =
true;
785 push_setup(peer, std::move(out));
793 std::vector<struct pollfd> pfds;
794 pfds.reserve(1 + snapshot.size());
795 pfds.push_back({listener_, POLLIN, 0});
796 for (
const auto& peer : snapshot) {
797 pfds.push_back({peer->fd, POLLIN, 0});
799 int ready = poll(pfds.data(), pfds.size(), timeout_ms);
803 if (pfds[0].revents & POLLIN) {
807 const size_t count = snapshot.size();
808 for (
size_t k = 0; k < count; ++k) {
809 const size_t index = (round_robin_ + k) % count;
810 const auto& peer = snapshot[index];
811 if (!(pfds[index + 1].revents & (POLLIN | POLLHUP | POLLERR | POLLNVAL))) {
814 Read r = read_one(peer->fd, transport_layer_, peer->rx, out);
815 if (r == Read::PDU) {
816 if (!peer->seen_first) {
817 peer->seen_first =
true;
818 push_setup(peer, std::move(out));
821 round_robin_ = index + 1;
826 E3_LOG_INFO(LOG_TAG) <<
"The first message is not a length-prefixed PDU. A dApp built before "
827 "libe3 0.6 sends its setup request without a prefix.";
829 if (r == Read::CLOSED || r == Read::ERROR
830 || (r == Read::NONE && (pfds[index + 1].revents & (POLLERR | POLLNVAL)))) {
835 round_robin_ = (round_robin_ + 1) % count;
842 return receive_client(buffer);
845 return static_cast<int>(ErrorCode::NOT_CONNECTED);
847 last_receive_ns_.store(now_ns());
849 std::lock_guard<std::mutex> lock(queue_mutex_);
850 if (!inbound_queue_.empty()) {
851 Queued item = std::move(inbound_queue_.front());
852 inbound_queue_.pop_front();
853 buffer = std::move(item.
data);
854 last_peer_token_ = item.
token;
855 return static_cast<int>(buffer.size());
858 std::lock_guard<std::mutex> reader(reader_mutex_);
860 if (pump(buffer, token, POLL_TIMEOUT_MS)) {
861 last_peer_token_ = token;
862 return static_cast<int>(buffer.size());
869 return static_cast<int>(ErrorCode::NOT_CONNECTED);
871 const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(POLL_TIMEOUT_MS);
874 std::unique_lock<std::mutex> lock(queue_mutex_);
875 if (!setup_queue_.empty()) {
876 Queued item = std::move(setup_queue_.front());
877 setup_queue_.pop_front();
878 buffer = std::move(item.
data);
879 setup_peer_ = item.
peer;
880 last_setup_token_ = item.
token;
881 return static_cast<int>(buffer.size());
884 if (shutdown_requested_.load() || std::chrono::steady_clock::now() >= deadline) {
889 if (receiver_idle() && reader_mutex_.try_lock()) {
890 std::vector<uint8_t> pdu;
892 if (pump(pdu, token, 100)) {
893 std::lock_guard<std::mutex> lock(queue_mutex_);
894 inbound_queue_.push_back(
Queued{
nullptr, token, std::move(pdu)});
896 reader_mutex_.unlock();
898 std::unique_lock<std::mutex> lock(queue_mutex_);
899 setup_ready_.wait_for(lock, std::chrono::milliseconds(50),
900 [
this] {
return !setup_queue_.empty() || shutdown_requested_.load(); });
906 std::shared_ptr<Peer> peer = setup_peer_;
908 return ErrorCode::NOT_CONNECTED;
910 std::lock_guard<std::mutex> lock(peer->write_mutex);
921 if (shutdown_requested_.load()) {
922 return ErrorCode::CANCELLED;
925 if (client_fd_ < 0) {
926 return ErrorCode::NOT_CONNECTED;
928 std::lock_guard<std::mutex> lock(client_write_mutex_);
932 return ErrorCode::NOT_CONNECTED;
935 std::vector<std::shared_ptr<Peer>> targets;
936 if (peer_token == 0) {
937 std::lock_guard<std::mutex> lock(peers_mutex_);
939 }
else if (
auto peer = find_peer(peer_token)) {
940 targets.push_back(peer);
942 return ErrorCode::NOT_CONNECTED;
947 for (
const auto& peer : targets) {
948 std::lock_guard<std::mutex> lock(peer->write_mutex);
949 if (write_pdu(peer->fd, transport_layer_, data, kind) != ErrorCode::SUCCESS) {
957 if (failed && sent == 0) {
958 return ErrorCode::TRANSPORT_ERROR;
960 return ErrorCode::SUCCESS;
964 return last_peer_token_;
968 return last_setup_token_;
972 std::lock_guard<std::mutex> lock(closed_mutex_);
973 std::vector<uint64_t> closed;
974 closed.swap(closed_peers_);
983 const Target where = target();
985 for (
int attempt = 0; attempt < CONNECT_ATTEMPTS && fd < 0; ++attempt) {
986 fd = connect_to(where);
988 if (shutdown_requested_.load()) {
989 return ErrorCode::CANCELLED;
991 std::this_thread::sleep_for(std::chrono::milliseconds(CONNECT_PAUSE_MS));
996 <<
": " << strerror(errno);
997 return ErrorCode::CONNECTION_FAILED;
1003 awaiting_setup_response_.store(
true);
1006 return ErrorCode::SUCCESS;
1009ErrorCode PosixE3Connector::reconnect_client() {
1010 if (client_fd_ >= 0) {
1018 if (client_fd_ < 0) {
1019 return ErrorCode::NOT_CONNECTED;
1023 if (setup_request_sent_) {
1025 if (rc != ErrorCode::SUCCESS) {
1029 setup_request_sent_ =
true;
1030 std::lock_guard<std::mutex> lock(client_write_mutex_);
1035 if (client_fd_ < 0) {
1036 return static_cast<int>(ErrorCode::NOT_CONNECTED);
1038 if (!awaiting_setup_response_.load()) {
1039 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1042 std::lock_guard<std::mutex> reader(reader_mutex_);
1043 Read r = Read::NONE;
1045 r = pop_stream_frame(client_rx_, buffer);
1047 if (r == Read::NONE) {
1048 const int ready = wait_readable(client_fd_, POLL_TIMEOUT_MS);
1053 return errno == EINTR ? 0 :
static_cast<int>(ErrorCode::TRANSPORT_ERROR);
1055 r = read_one(client_fd_, transport_layer_, client_rx_, buffer);
1057 if (r == Read::PDU) {
1058 awaiting_setup_response_.store(
false);
1059 await_cv_.notify_all();
1060 return static_cast<int>(buffer.size());
1062 if (r == Read::CLOSED) {
1063 return static_cast<int>(ErrorCode::NOT_CONNECTED);
1065 return r == Read::ERROR ?
static_cast<int>(ErrorCode::TRANSPORT_ERROR) : 0;
1069 return client_fd_ >= 0 ? ErrorCode::SUCCESS : ErrorCode::NOT_CONNECTED;
1073 return client_fd_ >= 0 ? ErrorCode::SUCCESS : ErrorCode::NOT_CONNECTED;
1076int PosixE3Connector::receive_client(std::vector<uint8_t>& buffer) {
1077 if (client_fd_ < 0) {
1078 return static_cast<int>(ErrorCode::NOT_CONNECTED);
1080 if (awaiting_setup_response_.load()) {
1081 std::unique_lock<std::mutex> lock(await_mutex_);
1082 await_cv_.wait_for(lock, std::chrono::milliseconds(POLL_TIMEOUT_MS), [
this] {
1083 return !awaiting_setup_response_.load() || shutdown_requested_.load();
1085 if (awaiting_setup_response_.load()) {
1089 std::lock_guard<std::mutex> reader(reader_mutex_);
1090 Read r = Read::NONE;
1092 r = pop_stream_frame(client_rx_, buffer);
1094 if (r == Read::NONE) {
1095 const int ready = wait_readable(client_fd_, POLL_TIMEOUT_MS);
1100 return errno == EINTR ? 0 :
static_cast<int>(ErrorCode::TRANSPORT_ERROR);
1102 r = read_one(client_fd_, transport_layer_, client_rx_, buffer);
1106 return static_cast<int>(buffer.size());
1108 return static_cast<int>(ErrorCode::NOT_CONNECTED);
1110 return static_cast<int>(ErrorCode::TRANSPORT_ERROR);
1121 E3_LOG_DEBUG(LOG_TAG) <<
"Shutting down POSIX connector";
1122 shutdown_requested_.store(
true);
1123 setup_ready_.notify_all();
1124 await_cv_.notify_all();
1125 if (listener_ >= 0) {
1129 std::lock_guard<std::mutex> lock(peers_mutex_);
1130 for (
const auto& peer : peers_) {
1134 if (client_fd_ >= 0) {
1142 std::lock_guard<std::mutex> lock(peers_mutex_);
1146 std::lock_guard<std::mutex> lock(queue_mutex_);
1147 setup_queue_.clear();
1148 inbound_queue_.clear();
1150 setup_peer_.reset();
1152 std::lock_guard<std::mutex> lock(closed_mutex_);
1153 closed_peers_.clear();
1155 if (client_fd_ >= 0) {
1159 if (listener_ >= 0) {
1169 E3_LOG_INFO(LOG_TAG) <<
"POSIX connector disposed";
E3Role role_
Role of this peer.
std::string setup_endpoint_
Endpoint of the setup channel.
ErrorCode send_setup_request_client(const std::vector< uint8_t > &data) override
Send a SetupRequest on the setup channel (dApp role).
~PosixE3Connector() override
Close every socket.
uint64_t last_peer_token() const override
Which peer supplied the bytes the last receive() returned (RAN role).
int recv_setup_request(std::vector< uint8_t > &buffer) override
Receive a setup request.
uint64_t last_setup_peer_token() const override
Which peer sent the setup request the last recv_setup_request() returned (RAN role).
void dispose() override
Clean up and release all resources.
int receive(std::vector< uint8_t > &buffer) override
Receive data from the inbound channel.
ErrorCode send(const std::vector< uint8_t > &data) override
Send data on the outbound channel.
ErrorCode setup_initial_connection_client() override
Connect the setup channel (dApp role: REQ connect).
E3TransportLayer transport_layer() const noexcept override
Get the transport layer type.
ErrorCode send_to(uint64_t peer_token, const std::vector< uint8_t > &data, PduClass kind) override
Send data to one peer, or to all of them (RAN role).
int recv_setup_response_client(std::vector< uint8_t > &buffer) override
Receive a SetupResponse on the setup channel (dApp role).
ErrorCode send_response(const std::vector< uint8_t > &data) override
Send a setup response.
PosixE3Connector(E3TransportLayer transport_layer, const std::string &endpoint, uint16_t port, const PosixOptions &options)
Create a POSIX connector.
void shutdown() override
Interrupt blocking operations for shutdown.
ErrorCode setup_outbound_connection_client() override
Connect the outbound channel (dApp role: PUB connect to the RAN's subscriber endpoint).
ErrorCode setup_inbound_connection_client() override
Connect the inbound channel (dApp role: SUB connect to the RAN's publisher endpoint).
std::vector< uint64_t > take_closed_peers() override
Peers whose connection has closed since the last call (RAN role).
ErrorCode setup_initial_connection() override
Set up the initial connection (setup channel).
ErrorCode setup_inbound_connection() override
Set up the inbound connection (SUB channel).
ErrorCode setup_outbound_connection() override
Set up the outbound connection (PUB channel).
Logging facility for libe3.
#define E3_LOG_WARN(component)
#define E3_LOG_DEBUG(component)
#define E3_LOG_INFO(component)
#define E3_LOG_ERROR(component)
ErrorCode
Error codes returned by libe3 operations Use shared error-code list (see libe3/error_codes....
E3TransportLayer
Transport layer types (matches Python E3TransportLayer).
@ SCTP
SCTP (O-RAN standard).
@ IPC
Unix Domain Sockets / IPC.
@ DAPP
dApp (connects to a RAN agent)
constexpr size_t MAX_PROTOCOL_DATA_SIZE
Largest protocolData of an indication, in bytes.
PduClass
What a PDU is for, so that a link that has streams can pick one.
@ PROCEDURE
A request, a response, a control, a release: anything but an indication.
@ INDICATION
An indication message.
POSIX socket-based E3 Connector.
One accepted connection of a RAN. Closes its socket when the last reference goes.
std::vector< uint8_t > rx
Bytes read and not yet a whole PDU; the reader's alone.
Peer(int f, uint64_t t)
Take over an accepted connection.
bool seen_first
The first PDU, the setup request, was read; the reader's alone.
uint64_t token
Never reused by this connector.
std::mutex write_mutex
One writer at a time.
A PDU read from a peer and waiting for the thread that takes it.
std::shared_ptr< Peer > peer
Who sent it.
std::vector< uint8_t > data
The PDU.
uint64_t token
The sender's token.
Socket and admission options of the POSIX link.