Skip to content

Commit d46bd98

Browse files
refactor: improve socket error messages on windows
1 parent 7c53eb8 commit d46bd98

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

src/dpp/sslconnection.cpp

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,29 @@ bool close_socket(dpp::socket sfd)
105105
return false;
106106
}
107107

108+
std::string get_socket_error() {
109+
#ifdef _WIN32
110+
wchar_t *wide_buffer{nullptr};
111+
std::string message{"Unknown error"};
112+
113+
FormatMessageW(
114+
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
115+
nullptr, WSAGetLastError(), 0, reinterpret_cast<LPWSTR>(&wide_buffer), 0, nullptr
116+
);
117+
if (wide_buffer) {
118+
int size_needed = WideCharToMultiByte(CP_UTF8, 0, wide_buffer, -1, nullptr, 0, nullptr, nullptr);
119+
if (size_needed > 0) {
120+
message.resize(size_needed - 1);
121+
WideCharToMultiByte(CP_UTF8, 0, wide_buffer, -1, message.data(), size_needed, nullptr, nullptr);
122+
}
123+
LocalFree(wide_buffer);
124+
}
125+
return message;
126+
#else
127+
return strerror(errno);
128+
#endif
129+
}
130+
108131
bool set_nonblocking(dpp::socket sockfd, bool non_blocking)
109132
{
110133
const int enable{1};
@@ -151,7 +174,7 @@ int ssl_connection::start_connecting(dpp::socket sockfd, const struct sockaddr *
151174
&& err != WSAEWOULDBLOCK
152175
#endif
153176
&& err != EWOULDBLOCK && err != EINPROGRESS) {
154-
throw connection_exception(err_connect_failure, strerror(errno));
177+
throw connection_exception(err_connect_failure, get_socket_error());
155178
} else if (rc == 0) {
156179
/* We are ready RIGHT NOW, connection already succeeded */
157180
socket_events ev;
@@ -258,15 +281,11 @@ void ssl_connection::connect() {
258281
const dns_cache_entry* addr = resolve_hostname(hostname, port);
259282
sfd = addr->make_connecting_socket();
260283
address_t destination = addr->get_connecting_address(from_string<uint16_t>(this->port, std::dec));
261-
if (sfd == ERROR_STATUS) {
262-
err = errno;
263-
} else {
264-
start_connecting(sfd, destination.get_socket_address(), destination.size());
265-
}
266284
/* Check if valid connection started */
267285
if (sfd == ERROR_STATUS) {
268-
throw dpp::connection_exception(err_connect_failure, strerror(err));
286+
throw dpp::connection_exception(err_connect_failure, get_socket_error());
269287
}
288+
start_connecting(sfd, destination.get_socket_address(), destination.size());
270289
}
271290

272291
void ssl_connection::socket_write(const std::string_view data) {

0 commit comments

Comments
 (0)