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 Feb 3, 2024
1 parent e98b114 commit d03a469
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
29 changes: 23 additions & 6 deletions lib/net.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,25 @@

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

static std::string socket_error(int err)
{
#ifdef _WIN32
static char msgbuf[256] = { '\0' };
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() {}
Expand Down Expand Up @@ -133,9 +152,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,9 +168,8 @@ 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");
return Cell(std::vector<Cell> {Cell(number_from_uint32(CHOICE_RecvFromResult_error)), Cell(utf8string(strerror(err)))});
int err = socketerror();
return Cell(std::vector<Cell> {Cell(number_from_uint32(CHOICE_RecvFromResult_error)), Cell(utf8string(socket_error(err)))});
}
if (r == 0) {
return Cell(std::vector<Cell> {Cell(number_from_uint32(CHOICE_RecvFromResult_eof))});
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 d03a469

Please sign in to comment.