16# ifndef WIN32_LEAN_AND_MEAN
17# define WIN32_LEAN_AND_MEAN
26# include <arpa/inet.h>
29# include <netinet/in.h>
30# include <semaphore.h>
32# include <sys/socket.h>
34# include <sys/types.h>
36# if defined(__APPLE__)
48using native_socket_t = SOCKET;
49const native_socket_t invalid_socket = INVALID_SOCKET;
51void ensureSocketInit()
53 static std::once_flag flag;
54 std::call_once(flag, []() {
56 WSAStartup(MAKEWORD(2, 2), &wsaData);
60int closeNativeSocket(native_socket_t s)
62 return closesocket(s);
70std::string lastError()
72 return std::to_string(GetLastError());
75std::string lastSocketError()
77 return std::to_string(WSAGetLastError());
82using native_socket_t = int;
83const native_socket_t invalid_socket = -1;
85void ensureSocketInit()
89int closeNativeSocket(native_socket_t s)
96 return errno == EINTR;
99std::string lastError()
101 return std::strerror(errno);
104std::string lastSocketError()
106 return std::strerror(errno);
111native_socket_t toNative(std::intptr_t fd)
113 return static_cast<native_socket_t
>(fd);
116std::intptr_t fromNative(native_socket_t s)
118 return (s == invalid_socket) ? -1 :
static_cast<std::intptr_t
>(s);
121bool addressToString(
const sockaddr_in& addr, std::string& host,
int& port)
123 char buf[INET_ADDRSTRLEN];
124 if (inet_ntop(AF_INET,
const_cast<in_addr*
>(&addr.sin_addr), buf,
sizeof(buf)) ==
nullptr) {
128 port = ntohs(addr.sin_port);
145 name +=
"_" + std::to_string(port);
147 name +=
"_" + std::to_string(index);
168 const auto sz =
static_cast<unsigned long long>(size);
169 HANDLE h = CreateFileMappingA(INVALID_HANDLE_VALUE,
172 static_cast<DWORD
>(sz >> 32),
173 static_cast<DWORD
>(sz & 0xFFFFFFFFULL),
176 yCError(
SHMEMCARRIER,
"Cannot create shared memory %s (error %s)", name.c_str(), lastError().c_str());
179 if (GetLastError() == ERROR_ALREADY_EXISTS) {
186 void* p = MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0, 0);
188 yCError(
SHMEMCARRIER,
"Cannot map shared memory %s (error %s)", name.c_str(), lastError().c_str());
203 HANDLE h = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, name.c_str());
205 yCError(
SHMEMCARRIER,
"Cannot open shared memory %s (error %s)", name.c_str(), lastError().c_str());
209 void* p = MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0, 0);
211 yCError(
SHMEMCARRIER,
"Cannot map shared memory %s (error %s)", name.c_str(), lastError().c_str());
216 MEMORY_BASIC_INFORMATION
info;
217 m_size = (VirtualQuery(p, &
info,
sizeof(
info)) != 0) ?
info.RegionSize : 0;
225 if (m_data !=
nullptr) {
226 UnmapViewOfFile(m_data);
229 if (m_handle !=
nullptr) {
230 CloseHandle(
static_cast<HANDLE>(m_handle));
249 shm_unlink(name.c_str());
251 int fd = shm_open(name.c_str(), O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
253 yCError(
SHMEMCARRIER,
"Cannot create shared memory %s (%s)", name.c_str(), lastError().c_str());
257 if (ftruncate(fd,
static_cast<off_t
>(size)) != 0) {
258 yCError(
SHMEMCARRIER,
"Cannot resize shared memory %s (%s)", name.c_str(), lastError().c_str());
260 shm_unlink(name.c_str());
264 void* p = mmap(
nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
266 if (p == MAP_FAILED) {
267 yCError(
SHMEMCARRIER,
"Cannot map shared memory %s (%s)", name.c_str(), lastError().c_str());
268 shm_unlink(name.c_str());
281 int fd = shm_open(name.c_str(), O_RDWR, 0);
283 yCError(
SHMEMCARRIER,
"Cannot open shared memory %s (%s)", name.c_str(), lastError().c_str());
288 if (fstat(fd, &st) != 0 || st.st_size <= 0) {
294 const auto size =
static_cast<size_t>(st.st_size);
295 void* p = mmap(
nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
297 if (p == MAP_FAILED) {
298 yCError(
SHMEMCARRIER,
"Cannot map shared memory %s (%s)", name.c_str(), lastError().c_str());
309 if (m_data !=
nullptr) {
310 munmap(m_data, m_size);
318 shm_unlink(name.c_str());
339 HANDLE h = CreateSemaphoreA(
nullptr,
static_cast<LONG
>(initial),
static_cast<LONG
>(max), name.c_str());
341 yCError(
SHMEMCARRIER,
"Cannot create semaphore %s (error %s)", name.c_str(), lastError().c_str());
344 if (GetLastError() == ERROR_ALREADY_EXISTS) {
358 HANDLE h = OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, FALSE, name.c_str());
360 yCError(
SHMEMCARRIER,
"Cannot open semaphore %s (error %s)", name.c_str(), lastError().c_str());
369 if (m_handle !=
nullptr) {
370 CloseHandle(
static_cast<HANDLE>(m_handle));
383 if (m_handle ==
nullptr) {
386 return WaitForSingleObject(
static_cast<HANDLE>(m_handle), INFINITE) == WAIT_OBJECT_0;
391 if (m_handle ==
nullptr) {
394 const auto ms =
static_cast<DWORD
>(timeout > 0 ? timeout * 1000.0 : 0);
395 return WaitForSingleObject(
static_cast<HANDLE>(m_handle), ms) == WAIT_OBJECT_0;
400 if (m_handle ==
nullptr) {
403 return ReleaseSemaphore(
static_cast<HANDLE>(m_handle), 1,
nullptr) != 0;
414 sem_unlink(name.c_str());
416 sem_t* s = sem_open(name.c_str(), O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, initial);
417 if (s == SEM_FAILED) {
418 yCError(
SHMEMCARRIER,
"Cannot create semaphore %s (%s)", name.c_str(), lastError().c_str());
429 sem_t* s = sem_open(name.c_str(), 0);
430 if (s == SEM_FAILED) {
440 if (m_handle !=
nullptr) {
441 sem_close(
static_cast<sem_t*
>(m_handle));
448 sem_unlink(name.c_str());
453 if (m_handle ==
nullptr) {
456 while (sem_wait(
static_cast<sem_t*
>(m_handle)) != 0) {
457 if (errno != EINTR) {
466 if (m_handle ==
nullptr) {
469 auto* s =
static_cast<sem_t*
>(m_handle);
471#if defined(__APPLE__)
473 const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration<double>(timeout);
475 if (sem_trywait(s) == 0) {
478 if (errno != EAGAIN && errno != EINTR) {
481 if (std::chrono::steady_clock::now() >= deadline) {
484 std::this_thread::sleep_for(std::chrono::microseconds(100));
489 clock_gettime(CLOCK_REALTIME, &ts);
490 const auto sec =
static_cast<time_t
>(timeout);
492 ts.tv_nsec +=
static_cast<long>((timeout -
static_cast<double>(sec)) * 1e9);
493 if (ts.tv_nsec >= 1000000000L) {
495 ts.tv_nsec -= 1000000000L;
497 while (sem_timedwait(s, &ts) != 0) {
498 if (errno != EINTR) {
508 if (m_handle ==
nullptr) {
511 return sem_post(
static_cast<sem_t*
>(m_handle)) == 0;
531 native_socket_t s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
532 if (s == invalid_socket) {
538 std::memset(&addr, 0,
sizeof(addr));
539 addr.sin_family = AF_INET;
540 addr.sin_addr.s_addr = htonl(INADDR_ANY);
541 addr.sin_port = htons(
static_cast<uint16_t
>(port));
543 if (::bind(s,
reinterpret_cast<sockaddr*
>(&addr),
sizeof(addr)) != 0) {
544 yCError(
SHMEMCARRIER,
"Cannot bind socket to port %d (%s)", port, lastSocketError().c_str());
545 closeNativeSocket(s);
549 if (::listen(s, 5) != 0) {
551 closeNativeSocket(s);
555 m_fd = fromNative(s);
568 s = ::accept(toNative(m_fd),
nullptr,
nullptr);
569 }
while (s == invalid_socket && isInterrupted());
571 if (s == invalid_socket) {
576 stream.m_fd = fromNative(s);
586 std::memset(&hints, 0,
sizeof(hints));
587 hints.ai_family = AF_INET;
588 hints.ai_socktype = SOCK_STREAM;
589 hints.ai_protocol = IPPROTO_TCP;
591 addrinfo* res =
nullptr;
592 const std::string service = std::to_string(port);
593 if (getaddrinfo(host.c_str(), service.c_str(), &hints, &res) != 0 || res ==
nullptr) {
598 native_socket_t s = invalid_socket;
599 for (addrinfo* ai = res; ai !=
nullptr; ai = ai->ai_next) {
600 s = ::socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
601 if (s == invalid_socket) {
606 ret = ::connect(s, ai->ai_addr,
static_cast<int>(ai->ai_addrlen));
607 }
while (ret != 0 && isInterrupted());
611 closeNativeSocket(s);
616 if (s == invalid_socket) {
617 yCError(
SHMEMCARRIER,
"Cannot connect to %s:%d (%s)", host.c_str(), port, lastSocketError().c_str());
621#if defined(__APPLE__)
623 setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &on,
sizeof(on));
626 m_fd = fromNative(s);
636#if defined(MSG_NOSIGNAL)
637 const int flags = MSG_NOSIGNAL;
642 const char* p =
static_cast<const char*
>(data);
644 auto ret = ::send(toNative(m_fd), p,
static_cast<int>(len), flags);
646 if (isInterrupted()) {
655 len -=
static_cast<size_t>(ret);
666 char* p =
static_cast<char*
>(data);
668 auto ret = ::recv(toNative(m_fd), p,
static_cast<int>(len), 0);
670 if (isInterrupted()) {
679 len -=
static_cast<size_t>(ret);
691 auto ret = ::recv(toNative(m_fd), &buf, 1, 0);
703 const int err = WSAGetLastError();
704 return !(err == WSAEWOULDBLOCK || err == WSAEINTR);
706 return !(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR);
717 return ioctlsocket(toNative(m_fd), FIONBIO, &
mode) == 0;
719 int flags = fcntl(toNative(m_fd), F_GETFL, 0);
723 return fcntl(toNative(m_fd), F_SETFL, flags | O_NONBLOCK) == 0;
733 socklen_t len =
sizeof(addr);
734 if (getsockname(toNative(m_fd),
reinterpret_cast<sockaddr*
>(&addr), &len) != 0) {
737 return addressToString(addr, host, port);
746 socklen_t len =
sizeof(addr);
747 if (getpeername(toNative(m_fd),
reinterpret_cast<sockaddr*
>(&addr), &len) != 0) {
750 return addressToString(addr, host, port);
756 closeNativeSocket(toNative(m_fd));
const yarp::os::LogComponent & SHMEMCARRIER()
bool waitFor(double timeout)
Wait at most timeout seconds. Returns true if the semaphore was acquired.
bool wait()
Wait until the semaphore is available.
static void unlink(const std::string &name)
Remove the name of the semaphore (no-op on Windows)
bool create(const std::string &name, unsigned int initial, unsigned int max)
Create a new semaphore (removing any stale semaphore with the same name)
bool open(const std::string &name)
Open an existing semaphore.
static void unlink(const std::string &name)
Remove the name of the segment (no-op on Windows)
void close()
Unmap the segment.
bool create(const std::string &name, size_t size)
Create a new segment (removing any stale segment with the same name)
bool open(const std::string &name)
Open an existing segment.
A minimal IPv4 TCP socket.
bool recvAll(void *data, size_t len)
Receive exactly len bytes (blocking socket)
bool accept(Socket &stream)
Accept a connection on a listening socket.
bool connect(const std::string &host, int port)
bool listen(int port)
Listen on all the interfaces (port 0 means any free port)
bool isPeerClosed()
Check, on a non-blocking socket, whether the connection was closed or reset by the peer (e....
bool sendAll(const void *data, size_t len)
Send exactly len bytes (blocking socket)
bool getRemoteAddress(std::string &host, int &port) const
bool getLocalAddress(std::string &host, int &port) const
#define yCError(component,...)
std::string objectName(const char *kind, int port, int index=-1)
Build the name of a named inter-process object.