Skip to content

Commit

Permalink
Return actual socket errors on Windows.
Browse files Browse the repository at this point in the history
  • Loading branch information
gitlarryf committed Dec 15, 2023
1 parent e98b114 commit e8ffd2e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
28 changes: 23 additions & 5 deletions lib/net.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,26 @@

// https://wiki.openssl.org/index.php/SSL/TLS_Client

static std::string socket_error(int err)
{
static char msgbuf[256] = { '\0' };
#ifdef _WIN32
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
msgbuf,
sizeof(msgbuf),
NULL);
#else
snprintf(msgbuf, sizeof(msgbuf), "%s", strerror(err));
#endif
if (msgbuf[0] == '\0') {
snprintf(msgbuf, sizeof(msgbuf), "(No Error Text) - %d", err);
}
return std::string(msgbuf);
}

class SocketObject: public Object {
public:
SocketObject() {}
Expand Down Expand Up @@ -133,9 +153,8 @@ class RawSocketObject: public SocketObject {
std::vector<unsigned char> buffer(n);
int r = ::recv(handle, reinterpret_cast<char *>(const_cast<unsigned char *>(buffer.data())), n, 0);
if (r < 0) {
int err = errno;
perror("recv");
return Cell(std::vector<Cell> {Cell(number_from_uint32(CHOICE_RecvResult_error)), Cell(utf8string(strerror(err)))});
int err = socketerror;
return Cell(std::vector<Cell> {Cell(number_from_uint32(CHOICE_RecvResult_error)), Cell(utf8string(socket_error(err)))});
}
if (r == 0) {
return Cell(std::vector<Cell> {Cell(number_from_uint32(CHOICE_RecvResult_eof))});
Expand All @@ -150,8 +169,7 @@ class RawSocketObject: public SocketObject {
socklen_t sin_len = sizeof(sin);
int r = ::recvfrom(handle, reinterpret_cast<char *>(const_cast<unsigned char *>(buffer.data())), n, 0, reinterpret_cast<sockaddr *>(&sin), &sin_len);
if (r < 0) {
int err = errno;
perror("recvfrom");
int err = socketerror;
return Cell(std::vector<Cell> {Cell(number_from_uint32(CHOICE_RecvFromResult_error)), Cell(utf8string(strerror(err)))});
}
if (r == 0) {
Expand Down
2 changes: 2 additions & 0 deletions src/socketx.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <winsock.h>
typedef int socklen_t;
#pragma warning(disable: 4127) // incompatible with FD_SET()
#define socketerror WSAGetLastError()

#else

Expand All @@ -15,5 +16,6 @@ typedef int socklen_t;
typedef int SOCKET;
const int INVALID_SOCKET = -1;
inline void closesocket(int x) { close(x); }
#define socketerror errno

#endif

0 comments on commit e8ffd2e

Please sign in to comment.