From 51e45db81ccf520e808ef35cfdd1b7b85018848c Mon Sep 17 00:00:00 2001 From: Larry Frieson Date: Thu, 14 Dec 2023 22:40:43 -0800 Subject: [PATCH] Return actual socket errors on Windows. --- lib/net.cpp | 29 +++++++++++++++++++++++------ src/socketx.h | 2 ++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/lib/net.cpp b/lib/net.cpp index beacfcb7b8..685ee9e11a 100644 --- a/lib/net.cpp +++ b/lib/net.cpp @@ -15,6 +15,25 @@ // https://wiki.openssl.org/index.php/SSL/TLS_Client +static std::string socket_error_message(int err) +{ +#ifdef _WIN32 + char msgbuf[256]; + DWORD r = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + err, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + msgbuf, + sizeof(msgbuf), + NULL); + if (r == 0) { + snprintf(msgbuf, sizeof(msgbuf), "(No Error Text) - %d", err); + } + return msgbuf; +#endif + return strerror(err); +} + class SocketObject: public Object { public: SocketObject() {} @@ -133,9 +152,8 @@ class RawSocketObject: public SocketObject { std::vector buffer(n); int r = ::recv(handle, reinterpret_cast(const_cast(buffer.data())), n, 0); if (r < 0) { - int err = errno; - perror("recv"); - return Cell(std::vector {Cell(number_from_uint32(CHOICE_RecvResult_error)), Cell(utf8string(strerror(err)))}); + int err = socket_error(); + return Cell(std::vector {Cell(number_from_uint32(CHOICE_RecvResult_error)), Cell(utf8string(socket_error_message(err)))}); } if (r == 0) { return Cell(std::vector {Cell(number_from_uint32(CHOICE_RecvResult_eof))}); @@ -150,9 +168,8 @@ class RawSocketObject: public SocketObject { socklen_t sin_len = sizeof(sin); int r = ::recvfrom(handle, reinterpret_cast(const_cast(buffer.data())), n, 0, reinterpret_cast(&sin), &sin_len); if (r < 0) { - int err = errno; - perror("recvfrom"); - return Cell(std::vector {Cell(number_from_uint32(CHOICE_RecvFromResult_error)), Cell(utf8string(strerror(err)))}); + int err = socket_error(); + return Cell(std::vector {Cell(number_from_uint32(CHOICE_RecvFromResult_error)), Cell(utf8string(socket_error_message(err)))}); } if (r == 0) { return Cell(std::vector {Cell(number_from_uint32(CHOICE_RecvFromResult_eof))}); diff --git a/src/socketx.h b/src/socketx.h index eece91497b..aeade61a4b 100644 --- a/src/socketx.h +++ b/src/socketx.h @@ -3,6 +3,7 @@ #include typedef int socklen_t; #pragma warning(disable: 4127) // incompatible with FD_SET() +#define socket_error() WSAGetLastError() #else @@ -15,5 +16,6 @@ typedef int socklen_t; typedef int SOCKET; const int INVALID_SOCKET = -1; inline void closesocket(int x) { close(x); } +#define socket_error() errno #endif