Skip to contentSkip to conversation

Fix M_ERRNO behavior on Windows

PATCH Superseded Lev Stipakov 3 participants 10 messages Feb 22, 2022 – Jul 22, 2022

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 Fix M_ERRNO behavior on Windows

From: Lev Stipakov <[email protected]...>

We use M_ERRNO flag in logging to display error code and error message. This has been broken on Windows, where we use error code from GetLastError() and error description from strerror(). strerror() expects C runtime error code, which is quite different from last error code from WinAPI call. As a result, we got incorrect error description.

The ultimate fix would be introducing another flag for WinAPI errors, like M_WINERR and use either that or M_ERRNO depends on context. However, the change would be quite intrusive and in some cases it is hard to say which one to use without looking into internals.

Instead we stick to M_ERRNO and in Windows case we first try to obtain error code from GetLastError() and if it returns ERROR_SUCCESS (which is 0), we assume that we have C runtime error and use errno. To get error description we use strerror_win32() with GetLastError() and strerror() with errno.

strerror_win32() uses FormatMessage() internally, which is the right way to get WinAPI error description.

While on it, add a new flag M_SKERR to display socket error. On Linux it is resolved into M_ERRNO and on Windows to an conjunction of another new flag M_WSAERR and M_ERRNO. With M_WSAERR we use WSAGetLastError() to get error code and strerror_win32() to get error description. WSAGetLastError() is a correct way to get WinSock error code, according to documentation.

---
 src/openvpn/error.c    | 26 ++++++++++++++++++++++----
 src/openvpn/error.h    | 11 ++++++++++-
 src/openvpn/manage.c   |  4 ++--
 src/openvpn/mtu.c      |  2 +-
 src/openvpn/platform.c |  2 +-
 src/openvpn/proxy.c    |  8 ++++----
 src/openvpn/ps.c       |  2 +-
 src/openvpn/socket.c   | 20 ++++++++++----------
 src/openvpn/socket.h   |  6 ++++++
 src/openvpn/socks.c    | 26 +++++++++++++-------------
 10 files changed, 70 insertions(+), 37 deletions(-)
src/openvpn/error.c +22 -4
index b0e9a48c..5da588d9 100644
@@ -242,7 +242,25 @@ x_msg_va(const unsigned int flags, const char *format, va_list arglist)
         return;
     }
 
-    e = openvpn_errno();
+    bool use_strerr = false;
+#ifdef _WIN32
+    if (flags & M_WSAERR)
+    {
+        e = WSAGetLastError();
+    }
+    else
+    {
+        e = GetLastError();
+        if (e == ERROR_SUCCESS)
+        {
+            /* error is likely C runtime, fallback to errno/strerr */
+            use_strerr = true;
+            e = errno;
+        }
+    }
+#else
+    e = errno;
+#endif
 
     /*
      * Apply muting filter.
@@ -264,7 +282,7 @@ x_msg_va(const unsigned int flags, const char *format, va_list arglist)
     if ((flags & M_ERRNO) && e)
     {
         openvpn_snprintf(m2, ERR_BUF_SIZE, "%s: %s (errno=%d)",
-                         m1, strerror(e), e);
+                         m1, use_strerr ? strerror(e) : openvpn_strerror(e, &gc), e);
         SWAP;
     }
 
@@ -678,13 +696,13 @@ x_check_status(int status,
             {
                 msg(x_cs_info_level, "%s %s [%s]: %s (fd=%d,code=%d)", description,
                     sock ? proto2ascii(sock->info.proto, sock->info.af, true) : "",
-                    extended_msg, strerror(my_errno), sock ? sock->sd : -1, my_errno);
+                    extended_msg, openvpn_strerror(my_errno, &gc), sock ? sock->sd : -1, my_errno);
             }
             else
             {
                 msg(x_cs_info_level, "%s %s: %s (fd=%d,code=%d)", description,
                     sock ? proto2ascii(sock->info.proto, sock->info.af, true) : "",
-                    strerror(my_errno), sock ? sock->sd : -1, my_errno);
+                    openvpn_strerror(my_errno, &gc), sock ? sock->sd : -1, my_errno);
             }
 
             if (x_cs_err_delay_ms)
src/openvpn/error.h +10 -1
index ad7defe8..9c3f4dfb 100644
@@ -99,9 +99,18 @@ extern int x_msg_line_num;
 #define M_NONFATAL        (1<<5)         /* non-fatal error */
 #define M_WARN            (1<<6)         /* call syslog with LOG_WARNING */
 #define M_DEBUG           (1<<7)
-
 #define M_ERRNO           (1<<8)         /* show errno description */
 
+#ifdef _WIN32
+#define M_WSAERR          (1<<9)         /* WinSock errors */
+#endif
+
+#ifdef _WIN32
+#define M_SKERR           (M_ERRNO | M_WSAERR) /* socket errors */
+#else
+#define M_SKERR           M_ERRNO
+#endif
+
 #define M_NOMUTE          (1<<11)        /* don't do mute processing */
 #define M_NOPREFIX        (1<<12)        /* don't show date/time prefix */
 #define M_USAGE_SMALL     (1<<13)        /* fatal options error, call usage_small */
src/openvpn/manage.c +2 -2
index 496042a6..2fa508ef 100644
@@ -1890,13 +1890,13 @@ man_connect(struct management *man)
 #if UNIX_SOCK_SUPPORT
         if (man->settings.flags & MF_UNIX_SOCK)
         {
-            msg(D_LINK_ERRORS | M_ERRNO,
+            msg(D_LINK_ERRORS | M_SKERR,
                 "MANAGEMENT: connect to unix socket %s failed",
                 sockaddr_unix_name(&man->settings.local_unix, "NULL"));
         }
         else
 #endif
-        msg(D_LINK_ERRORS | M_ERRNO,
+        msg(D_LINK_ERRORS | M_SKERR,
             "MANAGEMENT: connect to %s failed",
             print_sockaddr(man->settings.local->ai_addr, &gc));
         throw_signal_soft(SIGTERM, "management-connect-failed");
src/openvpn/mtu.c +1 -1
index aa810f1c..45398953 100644
@@ -407,7 +407,7 @@ set_sock_extended_error_passing(int sd)
     int on = 1;
     if (setsockopt(sd, SOL_IP, IP_RECVERR, (void *) &on, sizeof(on)))
     {
-        msg(M_WARN | M_ERRNO,
+        msg(M_WARN | M_SKERR,
             "Note: enable extended error passing on TCP/UDP socket failed (IP_RECVERR)");
     }
 }
src/openvpn/platform.c +1 -1
index 450f28ba..1aafd604 100644
@@ -532,7 +532,7 @@ platform_test_file(const char *filename)
         }
         else
         {
-            if (openvpn_errno() == EACCES)
+            if (errno == EACCES)
             {
                 msg( M_WARN | M_ERRNO, "Could not access file '%s'", filename);
             }
src/openvpn/proxy.c +4 -4
index ed720161..409bc4af 100644
@@ -110,7 +110,7 @@ recv_line(socket_descriptor_t sd,
         {
             if (verbose)
             {
-                msg(D_LINK_ERRORS | M_ERRNO, "recv_line: TCP port read timeout expired");
+                msg(D_LINK_ERRORS | M_SKERR, "recv_line: TCP port read timeout expired");
             }
             goto error;
         }
@@ -120,7 +120,7 @@ recv_line(socket_descriptor_t sd,
         {
             if (verbose)
             {
-                msg(D_LINK_ERRORS | M_ERRNO, "recv_line: TCP port read failed on select()");
+                msg(D_LINK_ERRORS | M_SKERR, "recv_line: TCP port read failed on select()");
             }
             goto error;
         }
@@ -133,7 +133,7 @@ recv_line(socket_descriptor_t sd,
         {
             if (verbose)
             {
-                msg(D_LINK_ERRORS | M_ERRNO, "recv_line: TCP port read failed on recv()");
+                msg(D_LINK_ERRORS | M_SKERR, "recv_line: TCP port read failed on recv()");
             }
             goto error;
         }
@@ -199,7 +199,7 @@ send_line(socket_descriptor_t sd,
     const ssize_t size = send(sd, buf, strlen(buf), MSG_NOSIGNAL);
     if (size != (ssize_t) strlen(buf))
     {
-        msg(D_LINK_ERRORS | M_ERRNO, "send_line: TCP port write failed on send()");
+        msg(D_LINK_ERRORS | M_SKERR, "send_line: TCP port write failed on send()");
         return false;
     }
     return true;
src/openvpn/ps.c +1 -1
index 9dca53c8..64cc1ed3 100644
@@ -429,7 +429,7 @@ proxy_entry_new(struct proxy_connection **list,
     /* connect to port share server */
     if ((sd_server = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
     {
-        msg(M_WARN|M_ERRNO, "PORT SHARE PROXY: cannot create socket");
+        msg(M_WARN|M_SKERR, "PORT SHARE PROXY: cannot create socket");
         return false;
     }
     status = openvpn_connect(sd_server,(const struct sockaddr *)  &server_addr, 5, NULL);
src/openvpn/socket.c +10 -10
index 0f34a5de..acfcfd65 100644
@@ -1143,7 +1143,7 @@ create_socket(struct link_socket *sock, struct addrinfo *addr)
         msg(M_INFO, "Using bind-dev %s", sock->bind_dev);
         if (setsockopt(sock->sd, SOL_SOCKET, SO_BINDTODEVICE, sock->bind_dev, strlen(sock->bind_dev) + 1) != 0)
         {
-            msg(M_WARN|M_ERRNO, "WARN: setsockopt SO_BINDTODEVICE=%s failed", sock->bind_dev);
+            msg(M_WARN|M_SKERR, "WARN: setsockopt SO_BINDTODEVICE=%s failed", sock->bind_dev);
         }
 
     }
@@ -1222,7 +1222,7 @@ socket_do_accept(socket_descriptor_t sd,
 
         if (!socket_defined(new_sd))
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "TCP: getpeername() failed");
+            msg(D_LINK_ERRORS | M_SKERR, "TCP: getpeername() failed");
         }
         else
         {
@@ -1247,7 +1247,7 @@ socket_do_accept(socket_descriptor_t sd,
 
     if (!socket_defined(new_sd))
     {
-        msg(D_LINK_ERRORS | M_ERRNO, "TCP: accept(%d) failed", (int)sd);
+        msg(D_LINK_ERRORS | M_SKERR, "TCP: accept(%d) failed", (int)sd);
     }
     /* only valid if we have remote_len_af!=0 */
     else if (remote_len_af && remote_len != remote_len_af)
@@ -1313,7 +1313,7 @@ socket_listen_accept(socket_descriptor_t sd,
 
         if (status < 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "TCP: select() failed");
+            msg(D_LINK_ERRORS | M_SKERR, "TCP: select() failed");
         }
 
         if (status <= 0)
@@ -1409,12 +1409,12 @@ socket_bind(socket_descriptor_t sd,
         msg(M_INFO, "setsockopt(IPV6_V6ONLY=%d)", v6only);
         if (setsockopt(sd, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &v6only, sizeof(v6only)))
         {
-            msg(M_NONFATAL|M_ERRNO, "Setting IPV6_V6ONLY=%d failed", v6only);
+            msg(M_NONFATAL | M_SKERR, "Setting IPV6_V6ONLY=%d failed", v6only);
         }
     }
     if (bind(sd, cur->ai_addr, cur->ai_addrlen))
     {
-        msg(M_FATAL | M_ERRNO, "%s: Socket bind failed on local address %s",
+        msg(M_FATAL | M_SKERR, "%s: Socket bind failed on local address %s",
             prefix,
             print_sockaddr_ex(local->ai_addr, ":", PS_SHOW_PORT, &gc));
     }
@@ -2254,7 +2254,7 @@ link_socket_close(struct link_socket *sock)
                 msg(D_LOW, "TCP/UDP: Closing socket");
                 if (openvpn_close_socket(sock->sd))
                 {
-                    msg(M_WARN | M_ERRNO, "TCP/UDP: Close Socket failed");
+                    msg(M_WARN | M_SKERR, "TCP/UDP: Close Socket failed");
                 }
             }
             sock->sd = SOCKET_UNDEFINED;
@@ -2271,7 +2271,7 @@ link_socket_close(struct link_socket *sock)
         {
             if (openvpn_close_socket(sock->ctrl_sd))
             {
-                msg(M_WARN | M_ERRNO, "TCP/UDP: Close Socket (ctrl_sd) failed");
+                msg(M_WARN | M_SKERR, "TCP/UDP: Close Socket (ctrl_sd) failed");
             }
             sock->ctrl_sd = SOCKET_UNDEFINED;
         }
@@ -3668,7 +3668,7 @@ sockethandle_finalize(sockethandle_t sh,
                     /* if no error (i.e. just not finished yet), then DON'T execute this code */
                     io->iostate = IOSTATE_INITIAL;
                     ASSERT(ResetEvent(io->overlapped.hEvent));
-                    msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: Completion error");
+                    msg(D_WIN32_IO | SocketHandleErrorFlag(sh), "WIN32 I/O: Completion error");
                 }
             }
             break;
@@ -3681,7 +3681,7 @@ sockethandle_finalize(sockethandle_t sh,
                 /* error return for a non-queued operation */
                 SocketHandleSetLastError(sh, io->status);
                 ret = -1;
-                msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: Completion non-queued error");
+                msg(D_WIN32_IO | SocketHandleErrorFlag(sh), "WIN32 I/O: Completion non-queued error");
             }
             else
             {
src/openvpn/socket.h +6 -0
index e9f1524d..a7ec827a 100644
@@ -301,6 +301,12 @@ SocketHandleSetInvalError(sockethandle_t sh)
     sh.is_handle ? SetLastError(ERROR_INVALID_FUNCTION) : WSASetLastError(WSAEINVAL);
 }
 
+static inline int
+SocketHandleErrorFlag(sockethandle_t sh)
+{
+    return sh.is_handle ? M_ERRNO : M_SKERR;
+}
+
 #else  /* ifdef _WIN32 */
 
 #define openvpn_close_socket(s) close(s)
src/openvpn/socks.c +13 -13
index 768bb613..10107c18 100644
@@ -117,7 +117,7 @@ socks_username_password_auth(struct socks_proxy_info *p,
 
     if (size != strlen(to_send))
     {
-        msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth: TCP port write failed on send()");
+        msg(D_LINK_ERRORS | M_SKERR, "socks_username_password_auth: TCP port write failed on send()");
         goto cleanup;
     }
 
@@ -145,14 +145,14 @@ socks_username_password_auth(struct socks_proxy_info *p,
         /* timeout? */
         if (status == 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth: TCP port read timeout expired");
+            msg(D_LINK_ERRORS | M_SKERR, "socks_username_password_auth: TCP port read timeout expired");
             goto cleanup;
         }
 
         /* error */
         if (status < 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth: TCP port read failed on select()");
+            msg(D_LINK_ERRORS | M_SKERR, "socks_username_password_auth: TCP port read failed on select()");
             goto cleanup;
         }
 
@@ -162,7 +162,7 @@ socks_username_password_auth(struct socks_proxy_info *p,
         /* error? */
         if (size != 1)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth: TCP port read failed on recv()");
+            msg(D_LINK_ERRORS | M_SKERR, "socks_username_password_auth: TCP port read failed on recv()");
             goto cleanup;
         }
 
@@ -204,7 +204,7 @@ socks_handshake(struct socks_proxy_info *p,
     size = send(sd, method_sel, sizeof(method_sel), MSG_NOSIGNAL);
     if (size != sizeof(method_sel))
     {
-        msg(D_LINK_ERRORS | M_ERRNO, "socks_handshake: TCP port write failed on send()");
+        msg(D_LINK_ERRORS | M_SKERR, "socks_handshake: TCP port write failed on send()");
         return false;
     }
 
@@ -232,14 +232,14 @@ socks_handshake(struct socks_proxy_info *p,
         /* timeout? */
         if (status == 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "socks_handshake: TCP port read timeout expired");
+            msg(D_LINK_ERRORS | M_SKERR, "socks_handshake: TCP port read timeout expired");
             return false;
         }
 
         /* error */
         if (status < 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "socks_handshake: TCP port read failed on select()");
+            msg(D_LINK_ERRORS | M_SKERR, "socks_handshake: TCP port read failed on select()");
             return false;
         }
 
@@ -249,7 +249,7 @@ socks_handshake(struct socks_proxy_info *p,
         /* error? */
         if (size != 1)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "socks_handshake: TCP port read failed on recv()");
+            msg(D_LINK_ERRORS | M_SKERR, "socks_handshake: TCP port read failed on recv()");
             return false;
         }
 
@@ -342,14 +342,14 @@ recv_socks_reply(socket_descriptor_t sd,
         /* timeout? */
         if (status == 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "recv_socks_reply: TCP port read timeout expired");
+            msg(D_LINK_ERRORS | M_SKERR, "recv_socks_reply: TCP port read timeout expired");
             return false;
         }
 
         /* error */
         if (status < 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "recv_socks_reply: TCP port read failed on select()");
+            msg(D_LINK_ERRORS | M_SKERR, "recv_socks_reply: TCP port read failed on select()");
             return false;
         }
 
@@ -359,7 +359,7 @@ recv_socks_reply(socket_descriptor_t sd,
         /* error? */
         if (size != 1)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "recv_socks_reply: TCP port read failed on recv()");
+            msg(D_LINK_ERRORS | M_SKERR, "recv_socks_reply: TCP port read failed on recv()");
             return false;
         }
 
@@ -484,7 +484,7 @@ establish_socks_proxy_passthru(struct socks_proxy_info *p,
         const ssize_t size = send(sd, buf, 5 + len + 2, MSG_NOSIGNAL);
         if ((int)size != 5 + (int)len + 2)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "establish_socks_proxy_passthru: TCP port write failed on send()");
+            msg(D_LINK_ERRORS | M_SKERR, "establish_socks_proxy_passthru: TCP port write failed on send()");
             goto error;
         }
     }
@@ -527,7 +527,7 @@ establish_socks_proxy_udpassoc(struct socks_proxy_info *p,
                                   10, MSG_NOSIGNAL);
         if (size != 10)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "establish_socks_proxy_passthru: TCP port write failed on send()");
+            msg(D_LINK_ERRORS | M_SKERR, "establish_socks_proxy_passthru: TCP port write failed on send()");
             goto error;
         }
     }
Signature · 1 line
2.23.0.windows.1
#1 lore raw

Hi,

Sorry for the long delay in getting back to this..

Quoted 69 lines · Lev Stipakov

From: Lev Stipakov <[email protected]...>

We use M_ERRNO flag in logging to display error code and error message. This has been broken on Windows, where we use error code from GetLastError() and error description from strerror(). strerror() expects C runtime error code, which is quite different from last error code from WinAPI call. As a result, we got incorrect error description.

The ultimate fix would be introducing another flag for WinAPI errors, like M_WINERR and use either that or M_ERRNO depends on context. However, the change would be quite intrusive and in some cases it is hard to say which one to use without looking into internals.

Instead we stick to M_ERRNO and in Windows case we first try to obtain error code from GetLastError() and if it returns ERROR_SUCCESS (which is 0), we assume that we have C runtime error and use errno. To get error description we use strerror_win32() with GetLastError() and strerror() with errno.

strerror_win32() uses FormatMessage() internally, which is the right way to get WinAPI error description.

While on it, add a new flag M_SKERR to display socket error. On Linux it is resolved into M_ERRNO and on Windows to an conjunction of another new flag M_WSAERR and M_ERRNO. With M_WSAERR we use WSAGetLastError() to get error code and strerror_win32() to get error description. WSAGetLastError() is a correct way to get WinSock error code, according to documentation.

---
 src/openvpn/error.c    | 26 ++++++++++++++++++++++----
 src/openvpn/error.h    | 11 ++++++++++-
 src/openvpn/manage.c   |  4 ++--
 src/openvpn/mtu.c      |  2 +-
 src/openvpn/platform.c |  2 +-
 src/openvpn/proxy.c    |  8 ++++----
 src/openvpn/ps.c       |  2 +-
 src/openvpn/socket.c   | 20 ++++++++++----------
 src/openvpn/socket.h   |  6 ++++++
 src/openvpn/socks.c    | 26 +++++++++++++-------------
 10 files changed, 70 insertions(+), 37 deletions(-)
src/openvpn/error.c +11 -1
index b0e9a48c..5da588d9 100644
@@ -242,7 +242,25 @@ x_msg_va(const unsigned int flags, const char
 *format, va_list arglist)
         return;
     }
 
-    e = openvpn_errno();
+    bool use_strerr = false;
+#ifdef _WIN32
+    if (flags & M_WSAERR)
+    {
+        e = WSAGetLastError();
+    }
+    else
+    {
+        e = GetLastError();
+        if (e == ERROR_SUCCESS)
+        {

src/openvpn/error.c x_msg_va(const unsigned int flags, const char · line 266

Quoted 10 lines
src/openvpn/error.c +8 -0
+            /* error is likely C runtime, fallback to errno/strerr */
+            use_strerr = true;
+            e = errno;
+        }
+    }
+#else
+    e = errno;
+#endif
 
 

Ideally I would have liked to modify openvpn_errno() and openvpn_strerror() to do the right thing instead of adding this logic here and below. I have not worked out what exactly that would entail -- most likely those two functions would require an extra argument to keep track of the kind of error.

Also there are some places openvpn_errno() is used and the result checked against POSIX error codes:
in forward.c around line 2102:

if (.... && ENETUNREACH == error_code && ...)

where error_code = openvpn_errno() which may return WSAENETUNREACH on Windows not ENETUNREACH-- even that depends on GetLastError() and WSAGetLastError() to behave identically.

Also does code like the below in socket.c do the right thing? (around line 1451 in socket.c)
status = openvpn_errno();
if (status == WSAEWOULDBLOCK) ....
but openvpn_errono() doesn't look for WSA errors (though it probably still works?).

     /*
Quoted 13 lines

* Apply muting filter.

src/openvpn/error.c +1 -1
@@ -264,7 +282,7 @@ x_msg_va(const unsigned int flags, const char *format,
 va_list arglist)
     if ((flags & M_ERRNO) && e)
     {
         openvpn_snprintf(m2, ERR_BUF_SIZE, "%s: %s (errno=%d)",
-                         m1, strerror(e), e);
+                         m1, use_strerr ? strerror(e) :
 openvpn_strerror(e, &gc), e);
         SWAP;
     }

src/openvpn/error.c x_check_status(int status, · line 703

Quoted 10 lines
src/openvpn/error.c +1 -2
@@ -678,13 +696,13 @@ x_check_status(int status,
             {
                 msg(x_cs_info_level, "%s %s [%s]: %s (fd=%d,code=%d)",
 description,
                     sock ? proto2ascii(sock->info.proto, sock->info.af,
 true) : "",
-                    extended_msg, strerror(my_errno), sock ? sock->sd :
-1, my_errno);
+                    extended_msg, openvpn_strerror(my_errno, &gc), sock ?
 sock->sd : -1, my_errno);
 

Here my_errno = openvpn_errno() -- don't we need the fallback to POSIX errno in this case? Could this also get called when a socket error is expected?

Quoted 25 lines
src/openvpn/error.c +0 -0
             }
             else
             {
                 msg(x_cs_info_level, "%s %s: %s (fd=%d,code=%d)",

description,

                     sock ? proto2ascii(sock->info.proto, sock->info.af,

true) : "",

src/openvpn/error.c +1 -2
-                    strerror(my_errno), sock ? sock->sd : -1, my_errno);
+                    openvpn_strerror(my_errno, &gc), sock ? sock->sd :
-1, my_errno);
             }
 
             if (x_cs_err_delay_ms)
src/openvpn/error.h +0 -1
index ad7defe8..9c3f4dfb 100644
@@ -99,9 +99,18 @@ extern int x_msg_line_num;
 #define M_NONFATAL        (1<<5)         /* non-fatal error */
 #define M_WARN            (1<<6)         /* call syslog with LOG_WARNING
 */
 #define M_DEBUG           (1<<7)
-
 #define M_ERRNO           (1<<8)         /* show errno description */
 

src/openvpn/error.h extern int x_msg_line_num; · line 114

Quoted 10 lines
src/openvpn/error.h +9 -0
+#ifdef _WIN32
+#define M_WSAERR          (1<<9)         /* WinSock errors */
+#endif
+
+#ifdef _WIN32
+#define M_SKERR           (M_ERRNO | M_WSAERR) /* socket errors */
+#else
+#define M_SKERR           M_ERRNO
+#endif
 

The two ifdefs could be combined into one.

The rest looks good to me.

Quoted 389 lines
src/openvpn/error.h +1 -0
+
 #define M_NOMUTE          (1<<11)        /* don't do mute processing */
 #define M_NOPREFIX        (1<<12)        /* don't show date/time prefix */
 #define M_USAGE_SMALL     (1<<13)        /* fatal options error, call

usage_small */

src/openvpn/manage.c +2 -2
index 496042a6..2fa508ef 100644
@@ -1890,13 +1890,13 @@ man_connect(struct management *man)
 #if UNIX_SOCK_SUPPORT
         if (man->settings.flags & MF_UNIX_SOCK)
         {
-            msg(D_LINK_ERRORS | M_ERRNO,
+            msg(D_LINK_ERRORS | M_SKERR,
                 "MANAGEMENT: connect to unix socket %s failed",
                 sockaddr_unix_name(&man->settings.local_unix, "NULL"));
         }
         else
 #endif
-        msg(D_LINK_ERRORS | M_ERRNO,
+        msg(D_LINK_ERRORS | M_SKERR,
             "MANAGEMENT: connect to %s failed",
             print_sockaddr(man->settings.local->ai_addr, &gc));
         throw_signal_soft(SIGTERM, "management-connect-failed");
src/openvpn/mtu.c +1 -1
index aa810f1c..45398953 100644
@@ -407,7 +407,7 @@ set_sock_extended_error_passing(int sd)
     int on = 1;
     if (setsockopt(sd, SOL_IP, IP_RECVERR, (void *) &on, sizeof(on)))
     {
-        msg(M_WARN | M_ERRNO,
+        msg(M_WARN | M_SKERR,
             "Note: enable extended error passing on TCP/UDP socket failed
 (IP_RECVERR)");
     }

}

src/openvpn/platform.c +1 -1
index 450f28ba..1aafd604 100644
@@ -532,7 +532,7 @@ platform_test_file(const char *filename)
         }
         else
         {
-            if (openvpn_errno() == EACCES)
+            if (errno == EACCES)
             {
                 msg( M_WARN | M_ERRNO, "Could not access file '%s'",
 filename);
             }
src/openvpn/proxy.c +1 -1
index ed720161..409bc4af 100644
@@ -110,7 +110,7 @@ recv_line(socket_descriptor_t sd,
         {
             if (verbose)
             {
-                msg(D_LINK_ERRORS | M_ERRNO, "recv_line: TCP port read
 timeout expired");
+                msg(D_LINK_ERRORS | M_SKERR, "recv_line: TCP port read
 timeout expired");
             }
             goto error;
         }
src/openvpn/proxy.c +1 -1
@@ -120,7 +120,7 @@ recv_line(socket_descriptor_t sd,
         {
             if (verbose)
             {
-                msg(D_LINK_ERRORS | M_ERRNO, "recv_line: TCP port read
 failed on select()");
+                msg(D_LINK_ERRORS | M_SKERR, "recv_line: TCP port read
 failed on select()");
             }
             goto error;
         }
src/openvpn/proxy.c +1 -1
@@ -133,7 +133,7 @@ recv_line(socket_descriptor_t sd,
         {
             if (verbose)
             {
-                msg(D_LINK_ERRORS | M_ERRNO, "recv_line: TCP port read
 failed on recv()");
+                msg(D_LINK_ERRORS | M_SKERR, "recv_line: TCP port read
 failed on recv()");
             }
             goto error;
         }
src/openvpn/proxy.c +1 -1
@@ -199,7 +199,7 @@ send_line(socket_descriptor_t sd,
     const ssize_t size = send(sd, buf, strlen(buf), MSG_NOSIGNAL);
     if (size != (ssize_t) strlen(buf))
     {
-        msg(D_LINK_ERRORS | M_ERRNO, "send_line: TCP port write failed on
 send()");
+        msg(D_LINK_ERRORS | M_SKERR, "send_line: TCP port write failed on
 send()");
         return false;
     }
     return true;
src/openvpn/ps.c +1 -1
index 9dca53c8..64cc1ed3 100644
@@ -429,7 +429,7 @@ proxy_entry_new(struct proxy_connection **list,
     /* connect to port share server */
     if ((sd_server = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
     {
-        msg(M_WARN|M_ERRNO, "PORT SHARE PROXY: cannot create socket");
+        msg(M_WARN|M_SKERR, "PORT SHARE PROXY: cannot create socket");
         return false;
     }
     status = openvpn_connect(sd_server,(const struct sockaddr *)

&server_addr, 5, NULL);

src/openvpn/socket.c +1 -1
index 0f34a5de..acfcfd65 100644
@@ -1143,7 +1143,7 @@ create_socket(struct link_socket *sock, struct
 addrinfo *addr)
         msg(M_INFO, "Using bind-dev %s", sock->bind_dev);
         if (setsockopt(sock->sd, SOL_SOCKET, SO_BINDTODEVICE,
 sock->bind_dev, strlen(sock->bind_dev) + 1) != 0)
         {
-            msg(M_WARN|M_ERRNO, "WARN: setsockopt SO_BINDTODEVICE=%s
 failed", sock->bind_dev);
+            msg(M_WARN|M_SKERR, "WARN: setsockopt SO_BINDTODEVICE=%s
failed", sock->bind_dev);
         }

     }
src/openvpn/socket.c +4 -5
@@ -1222,7 +1222,7 @@ socket_do_accept(socket_descriptor_t sd,
 
         if (!socket_defined(new_sd))
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "TCP: getpeername() failed");
+            msg(D_LINK_ERRORS | M_SKERR, "TCP: getpeername() failed");
         }
         else
         {
@@ -1247,7 +1247,7 @@ socket_do_accept(socket_descriptor_t sd,
 
     if (!socket_defined(new_sd))
     {
-        msg(D_LINK_ERRORS | M_ERRNO, "TCP: accept(%d) failed", (int)sd);
+        msg(D_LINK_ERRORS | M_SKERR, "TCP: accept(%d) failed", (int)sd);
     }
     /* only valid if we have remote_len_af!=0 */
     else if (remote_len_af && remote_len != remote_len_af)
@@ -1313,7 +1313,7 @@ socket_listen_accept(socket_descriptor_t sd,
 
         if (status < 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "TCP: select() failed");
+            msg(D_LINK_ERRORS | M_SKERR, "TCP: select() failed");
         }
 
         if (status <= 0)
@@ -1409,12 +1409,12 @@ socket_bind(socket_descriptor_t sd,
         msg(M_INFO, "setsockopt(IPV6_V6ONLY=%d)", v6only);
         if (setsockopt(sd, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &v6only,
 sizeof(v6only)))
         {
-            msg(M_NONFATAL|M_ERRNO, "Setting IPV6_V6ONLY=%d failed",
 v6only);
+            msg(M_NONFATAL | M_SKERR, "Setting IPV6_V6ONLY=%d failed",
 v6only);
         }
     }
     if (bind(sd, cur->ai_addr, cur->ai_addrlen))
     {
-        msg(M_FATAL | M_ERRNO, "%s: Socket bind failed on local address

%s",
+ msg(M_FATAL | M_SKERR, "%s: Socket bind failed on local address
%s",

             prefix,
             print_sockaddr_ex(local->ai_addr, ":", PS_SHOW_PORT, &gc));
     }
src/openvpn/socket.c +2 -2
@@ -2254,7 +2254,7 @@ link_socket_close(struct link_socket *sock)
                 msg(D_LOW, "TCP/UDP: Closing socket");
                 if (openvpn_close_socket(sock->sd))
                 {
-                    msg(M_WARN | M_ERRNO, "TCP/UDP: Close Socket failed");
+                    msg(M_WARN | M_SKERR, "TCP/UDP: Close Socket failed");
                 }
             }
             sock->sd = SOCKET_UNDEFINED;
@@ -2271,7 +2271,7 @@ link_socket_close(struct link_socket *sock)
         {
             if (openvpn_close_socket(sock->ctrl_sd))
             {
-                msg(M_WARN | M_ERRNO, "TCP/UDP: Close Socket (ctrl_sd)
 failed");
+                msg(M_WARN | M_SKERR, "TCP/UDP: Close Socket (ctrl_sd)
 failed");
             }
             sock->ctrl_sd = SOCKET_UNDEFINED;
         }
src/openvpn/socket.c +0 -0
@@ -3668,7 +3668,7 @@ sockethandle_finalize(sockethandle_t sh,
                     /* if no error (i.e. just not finished yet), then

DON'T execute this code */

                     io->iostate = IOSTATE_INITIAL;
                     ASSERT(ResetEvent(io->overlapped.hEvent));
-                    msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: Completion
error");
+                    msg(D_WIN32_IO | SocketHandleErrorFlag(sh), "WIN32
I/O: Completion error");
                 }
             }
             break;
src/openvpn/socket.c +1 -1
@@ -3681,7 +3681,7 @@ sockethandle_finalize(sockethandle_t sh,
                 /* error return for a non-queued operation */
                 SocketHandleSetLastError(sh, io->status);
                 ret = -1;
-                msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: Completion
 non-queued error");
+                msg(D_WIN32_IO | SocketHandleErrorFlag(sh), "WIN32 I/O:
 Completion non-queued error");
             }
             else
             {
src/openvpn/socket.h +6 -0
index e9f1524d..a7ec827a 100644
@@ -301,6 +301,12 @@ SocketHandleSetInvalError(sockethandle_t sh)
     sh.is_handle ? SetLastError(ERROR_INVALID_FUNCTION) :
 WSASetLastError(WSAEINVAL);
 }
 
+static inline int
+SocketHandleErrorFlag(sockethandle_t sh)
+{
+    return sh.is_handle ? M_ERRNO : M_SKERR;
+}
+
 #else  /* ifdef _WIN32 */
 

#define openvpn_close_socket(s) close(s)

src/openvpn/socks.c +1 -1
index 768bb613..10107c18 100644
@@ -117,7 +117,7 @@ socks_username_password_auth(struct socks_proxy_info
 *p,
 
     if (size != strlen(to_send))
     {
-        msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth: TCP
 port write failed on send()");
+        msg(D_LINK_ERRORS | M_SKERR, "socks_username_password_auth: TCP
 port write failed on send()");
         goto cleanup;
     }
src/openvpn/socks.c +1 -2
@@ -145,14 +145,14 @@ socks_username_password_auth(struct socks_proxy_info
 *p,
         /* timeout? */
         if (status == 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth:
 TCP port read timeout expired");
+            msg(D_LINK_ERRORS | M_SKERR, "socks_username_password_auth:
 TCP port read timeout expired");
             goto cleanup;
         }
 
         /* error */
         if (status < 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth:

TCP port read failed on select()");
+ msg(D_LINK_ERRORS | M_SKERR, "socks_username_password_auth:
TCP port read failed on select()");

             goto cleanup;
         }
src/openvpn/socks.c +1 -1
@@ -162,7 +162,7 @@ socks_username_password_auth(struct socks_proxy_info
 *p,
         /* error? */
         if (size != 1)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "socks_username_password_auth:
 TCP port read failed on recv()");
+            msg(D_LINK_ERRORS | M_SKERR, "socks_username_password_auth:
 TCP port read failed on recv()");
             goto cleanup;
         }
src/openvpn/socks.c +1 -1
@@ -204,7 +204,7 @@ socks_handshake(struct socks_proxy_info *p,
     size = send(sd, method_sel, sizeof(method_sel), MSG_NOSIGNAL);
     if (size != sizeof(method_sel))
     {
-        msg(D_LINK_ERRORS | M_ERRNO, "socks_handshake: TCP port write
 failed on send()");
+        msg(D_LINK_ERRORS | M_SKERR, "socks_handshake: TCP port write
 failed on send()");
         return false;
     }
src/openvpn/socks.c +2 -2
@@ -232,14 +232,14 @@ socks_handshake(struct socks_proxy_info *p,
         /* timeout? */
         if (status == 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "socks_handshake: TCP port read
 timeout expired");
+            msg(D_LINK_ERRORS | M_SKERR, "socks_handshake: TCP port read
 timeout expired");
             return false;
         }
 
         /* error */
         if (status < 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "socks_handshake: TCP port read
 failed on select()");
+            msg(D_LINK_ERRORS | M_SKERR, "socks_handshake: TCP port read
failed on select()");
             return false;
         }
src/openvpn/socks.c +1 -1
@@ -249,7 +249,7 @@ socks_handshake(struct socks_proxy_info *p,
         /* error? */
         if (size != 1)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "socks_handshake: TCP port read
 failed on recv()");
+            msg(D_LINK_ERRORS | M_SKERR, "socks_handshake: TCP port read
 failed on recv()");
             return false;
         }
src/openvpn/socks.c +2 -2
@@ -342,14 +342,14 @@ recv_socks_reply(socket_descriptor_t sd,
         /* timeout? */
         if (status == 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "recv_socks_reply: TCP port read
 timeout expired");
+            msg(D_LINK_ERRORS | M_SKERR, "recv_socks_reply: TCP port read
 timeout expired");
             return false;
         }
 
         /* error */
         if (status < 0)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "recv_socks_reply: TCP port read
 failed on select()");
+            msg(D_LINK_ERRORS | M_SKERR, "recv_socks_reply: TCP port read
failed on select()");
             return false;
         }
src/openvpn/socks.c +1 -1
@@ -359,7 +359,7 @@ recv_socks_reply(socket_descriptor_t sd,
         /* error? */
         if (size != 1)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "recv_socks_reply: TCP port read
 failed on recv()");
+            msg(D_LINK_ERRORS | M_SKERR, "recv_socks_reply: TCP port read
 failed on recv()");
             return false;
         }
src/openvpn/socks.c +1 -1
@@ -484,7 +484,7 @@ establish_socks_proxy_passthru(struct socks_proxy_info
 *p,
         const ssize_t size = send(sd, buf, 5 + len + 2, MSG_NOSIGNAL);
         if ((int)size != 5 + (int)len + 2)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "establish_socks_proxy_passthru:
 TCP port write failed on send()");
+            msg(D_LINK_ERRORS | M_SKERR, "establish_socks_proxy_passthru:
 TCP port write failed on send()");
             goto error;
         }
     }
src/openvpn/socks.c +1 -1
@@ -527,7 +527,7 @@ establish_socks_proxy_udpassoc(struct socks_proxy_info
 *p,
                                   10, MSG_NOSIGNAL);
         if (size != 10)
         {
-            msg(D_LINK_ERRORS | M_ERRNO, "establish_socks_proxy_passthru:
 TCP port write failed on send()");
+            msg(D_LINK_ERRORS | M_SKERR, "establish_socks_proxy_passthru:
 TCP port write failed on send()");
             goto error;
         }
     }
Quoted 2 lines

--

All that said, it may be hard to get all error reporting fixed in one patch, so we could proceed in steps. First make openvpn_errno() and openvpn_strerror() do the right thing with GetLastError() vs errno, then fix WSA error printing, then the rest if any. Just a thought.

Selva

#3 lore raw

PATCH v2 1/1 Fix M_ERRNO behavior on Windows

In reply to Lev Stipakov

From: Lev Stipakov <[email protected]...>

We use M_ERRNO flag in logging to display error code and error message. This has been broken on Windows, where we use error code from GetLastError() and error description from strerror(). strerror() expects C runtime error code, which is quite different from last error code from WinAPI call. As a result, we got incorrect error description.

The ultimate fix would be introducing another flag for WinAPI errors, like M_WINERR and use either that or M_ERRNO depends on context. However, the change would be quite intrusive and in some cases it is hard to say which one to use without looking into internals.

Instead we stick to M_ERRNO and in Windows case we first try to obtain error code from GetLastError() and if it returns ERROR_SUCCESS (which is 0), we assume that we have C runtime error and use errno. To get error description we use strerror_win32() with GetLastError() and strerror() with errno.

strerror_win32() uses FormatMessage() internally, which
is the right way to get WinAPI error description.
---
v2:
- removed WSA error printing, to be implemented in a follow-up patch
- added missing crt error fallback to x_check_status() and

    main_io_error()

- fixed "network unreachable" detection

 src/openvpn/error.c    | 34 +++++++++++++++++++++++++++-------
 src/openvpn/error.h    | 39 +++++++++++++++++++++++++++++----------
 src/openvpn/forward.c  |  9 ++++++++-
 src/openvpn/manage.c   |  5 +++--
 src/openvpn/platform.c |  2 +-
 src/openvpn/tun.h      |  4 ++--
 6 files changed, 70 insertions(+), 23 deletions(-)
src/openvpn/error.c +27 -7
index 603d6c63..1b7f5cde 100644
@@ -220,6 +220,18 @@ x_msg(const unsigned int flags, const char *format, ...)
     va_end(arglist);
 }
 
+static const char*
+openvpn_strerror(int err, bool crt_error, struct gc_arena *gc)
+{
+#ifdef _WIN32
+    if (!crt_error)
+    {
+        return strerror_win32(err, gc);
+    }
+#endif
+    return strerror(err);
+}
+
 void
 x_msg_va(const unsigned int flags, const char *format, va_list arglist)
 {
@@ -242,7 +254,8 @@ x_msg_va(const unsigned int flags, const char *format, va_list arglist)
         return;
     }
 
-    e = openvpn_errno();
+    bool crt_error = false;
+    e = openvpn_errno_maybe_crt(&crt_error);
 
     /*
      * Apply muting filter.
@@ -264,7 +277,7 @@ x_msg_va(const unsigned int flags, const char *format, va_list arglist)
     if ((flags & M_ERRNO) && e)
     {
         openvpn_snprintf(m2, ERR_BUF_SIZE, "%s: %s (errno=%d)",
-                         m1, strerror(e), e);
+                         m1, openvpn_strerror(e, crt_error, &gc), e);
         SWAP;
     }
 
@@ -643,7 +656,6 @@ x_check_status(int status,
                struct link_socket *sock,
                struct tuntap *tt)
 {
-    const int my_errno = openvpn_errno();
     const char *extended_msg = NULL;
 
     msg(x_cs_verbose_level, "%s %s returned %d",
@@ -666,26 +678,34 @@ x_check_status(int status,
                 sock->info.mtu_changed = true;
             }
         }
-#elif defined(_WIN32)
+#endif /* EXTENDED_SOCKET_ERROR_CAPABILITY */
+
+#ifdef _WIN32
         /* get possible driver error from TAP-Windows driver */
         if (tuntap_defined(tt))
         {
             extended_msg = tap_win_getinfo(tt, &gc);
         }
 #endif
-        if (!ignore_sys_error(my_errno))
+
+        bool crt_error = false;
+        int my_errno = openvpn_errno_maybe_crt(&crt_error);
+
+        if (!ignore_sys_error(my_errno, crt_error))
         {
             if (extended_msg)
             {
                 msg(x_cs_info_level, "%s %s [%s]: %s (fd=%d,code=%d)", description,
                     sock ? proto2ascii(sock->info.proto, sock->info.af, true) : "",
-                    extended_msg, strerror(my_errno), sock ? sock->sd : -1, my_errno);
+                    extended_msg, openvpn_strerror(my_errno, crt_error, &gc),
+                    sock ? sock->sd : -1, my_errno);
             }
             else
             {
                 msg(x_cs_info_level, "%s %s: %s (fd=%d,code=%d)", description,
                     sock ? proto2ascii(sock->info.proto, sock->info.af, true) : "",
-                    strerror(my_errno), sock ? sock->sd : -1, my_errno);
+                    openvpn_strerror(my_errno, crt_error, &gc),
+                    sock ? sock->sd : -1, my_errno);
             }
 
             if (x_cs_err_delay_ms)
src/openvpn/error.h +29 -10
index ad7defe8..be8d97e5 100644
@@ -75,13 +75,10 @@ struct gc_arena;
 /* String and Error functions */
 
 #ifdef _WIN32
-#define openvpn_errno()             GetLastError()
-#define openvpn_strerror(e, gc)     strerror_win32(e, gc)
+#define openvpn_errno() GetLastError()
 const char *strerror_win32(DWORD errnum, struct gc_arena *gc);
-
 #else
-#define openvpn_errno()             errno
-#define openvpn_strerror(x, gc)     strerror(x)
+#define openvpn_errno() errno
 #endif
 
 /*
@@ -352,20 +349,22 @@ msg_get_virtual_output(void)
  * which can be safely ignored.
  */
 static inline bool
-ignore_sys_error(const int err)
+ignore_sys_error(const int err, bool crt_error)
 {
-    /* I/O operation pending */
 #ifdef _WIN32
-    if (err == WSAEWOULDBLOCK || err == WSAEINVAL)
+    if (!crt_error && ((err == WSAEWOULDBLOCK || err == WSAEINVAL)))
     {
         return true;
     }
 #else
-    if (err == EAGAIN)
+    crt_error = true;
+#endif
+
+    /* I/O operation pending */
+    if (crt_error && (err == EAGAIN))
     {
         return true;
     }
-#endif
 
 #if 0 /* if enabled, suppress ENOBUFS errors */
 #ifdef ENOBUFS
@@ -387,6 +386,26 @@ nonfatal(const unsigned int err)
     return err & M_FATAL ? (err ^ M_FATAL) | M_NONFATAL : err;
 }
 
+static inline int
+openvpn_errno_maybe_crt(bool *crt_error)
+{
+    int err = 0;
+    *crt_error = false;
+#ifdef _WIN32
+    err = GetLastError();
+    if (err == ERROR_SUCCESS)
+    {
+        /* error is likely C runtime */
+        *crt_error = true;
+        err = errno;
+    }
+#else
+    *crt_error = true;
+    err = errno;
+#endif
+    return err;
+}
+
 #include "errlevel.h"
 
 #endif /* ifndef ERROR_H */
src/openvpn/forward.c +8 -1
index 8930e578..04828a5c 100644
@@ -1660,7 +1660,14 @@ process_outgoing_link(struct context *c)
         }
 
         /* for unreachable network and "connecting" state switch to the next host */
-        if (size < 0 && ENETUNREACH == error_code && c->c2.tls_multi
+
+        bool unreachable = error_code ==
+#ifdef _WIN32
+            WSAENETUNREACH;
+#else
+            ENETUNREACH;
+#endif
+        if (size < 0 && unreachable && c->c2.tls_multi
             && !tls_initial_packet_received(c->c2.tls_multi) && c->options.mode == MODE_POINT_TO_POINT)
         {
             msg(M_INFO, "Network unreachable, restarting");
src/openvpn/manage.c +3 -2
index 9b03b057..036658b1 100644
@@ -2008,9 +2008,10 @@ man_process_command(struct management *man, const char *line)
 static bool
 man_io_error(struct management *man, const char *prefix)
 {
-    const int err = openvpn_errno();
+    bool crt_error = false;
+    int err = openvpn_errno_maybe_crt(&crt_error);
 
-    if (!ignore_sys_error(err))
+    if (!ignore_sys_error(err, crt_error))
     {
         struct gc_arena gc = gc_new();
         msg(D_MANAGEMENT, "MANAGEMENT: TCP %s error: %s", prefix,
src/openvpn/platform.c +1 -1
index 61afee83..ae1678db 100644
@@ -532,7 +532,7 @@ platform_test_file(const char *filename)
         }
         else
         {
-            if (openvpn_errno() == EACCES)
+            if (errno == EACCES)
             {
                 msg( M_WARN | M_ERRNO, "Could not access file '%s'", filename);
             }
src/openvpn/tun.h +2 -2
index 3a7314c5..4bc35916 100644
@@ -446,7 +446,7 @@ tuntap_stop(int status)
      */
     if (status < 0)
     {
-        return openvpn_errno() == ERROR_FILE_NOT_FOUND;
+        return GetLastError() == ERROR_FILE_NOT_FOUND;
     }
     return false;
 }
@@ -459,7 +459,7 @@ tuntap_abort(int status)
      */
     if (status < 0)
     {
-        return openvpn_errno() == ERROR_OPERATION_ABORTED;
+        return GetLastError() == ERROR_OPERATION_ABORTED;
     }
     return false;
 }
Signature · 1 line
2.23.0.windows.1
#2 lore raw
In reply to Selva Nair

Hi,

Also there are some places openvpn_errno() is used and the result checked

Quoted 9 lines

against POSIX error codes:
in forward.c around line 2102:

if (.... && ENETUNREACH == error_code && ...)

where error_code = openvpn_errno() which may return WSAENETUNREACH on Windows not ENETUNREACH-- even that depends on GetLastError() and WSAGetLastError() to behave identically.

Thanks, fixed.

Quoted 7 lines

Also does code like the below in socket.c do the right thing? (around line 1451 in socket.c)
status = openvpn_errno();
if (status == WSAEWOULDBLOCK) ....
but openvpn_errono() doesn't look for WSA errors (though it probably still works?).

Yeah we compare GetLastError result here with WSA*, but in practice that works. Here we just call openvpn_errno(), we could add WSA* support but this will make code less readable for the benefit of being more "pure", not sure it is worth it.

Quoted 10 lines

- extended_msg, strerror(my_errno), sock ? sock->sd :

Quoted 4 lines

-1, my_errno);
+ extended_msg, openvpn_strerror(my_errno, &gc), sock
? sock->sd : -1, my_errno);

Here my_errno = openvpn_errno() -- don't we need the fallback to POSIX errno in this case? Could this also get called when a socket error is expected?

You are right. I slightly refactored that part to reuse crt error fallback code which we need in 3 different places.

The rest looks good to me.

Quoted 1 line

As you proposed, I removed WSA error printing from this patch, it could come in a follow-up.

V2 is coming.

Acked-by on v2 1/1
#4 lore raw
In reply to Lev Stipakov

Hi,

Thanks for the changes. Looks good.

Quoted 282 lines · Lev Stipakov

From: Lev Stipakov <[email protected]...>

We use M_ERRNO flag in logging to display error code and error message. This has been broken on Windows, where we use error code from GetLastError() and error description from strerror(). strerror() expects C runtime error code, which is quite different from last error code from WinAPI call. As a result, we got incorrect error description.

The ultimate fix would be introducing another flag for WinAPI errors, like M_WINERR and use either that or M_ERRNO depends on context. However, the change would be quite intrusive and in some cases it is hard to say which one to use without looking into internals.

Instead we stick to M_ERRNO and in Windows case we first try to obtain error code from GetLastError() and if it returns ERROR_SUCCESS (which is 0), we assume that we have C runtime error and use errno. To get error description we use strerror_win32() with GetLastError() and strerror() with errno.

strerror_win32() uses FormatMessage() internally, which
is the right way to get WinAPI error description.
---
v2:
- removed WSA error printing, to be implemented in a follow-up patch
- added missing crt error fallback to x_check_status() and

    main_io_error()

- fixed "network unreachable" detection

 src/openvpn/error.c    | 34 +++++++++++++++++++++++++++-------
 src/openvpn/error.h    | 39 +++++++++++++++++++++++++++++----------
 src/openvpn/forward.c  |  9 ++++++++-
 src/openvpn/manage.c   |  5 +++--
 src/openvpn/platform.c |  2 +-
 src/openvpn/tun.h      |  4 ++--
 6 files changed, 70 insertions(+), 23 deletions(-)
src/openvpn/error.c +12 -0
index 603d6c63..1b7f5cde 100644
@@ -220,6 +220,18 @@ x_msg(const unsigned int flags, const char *format,
 ...)
     va_end(arglist);
 }
 
+static const char*
+openvpn_strerror(int err, bool crt_error, struct gc_arena *gc)
+{
+#ifdef _WIN32
+    if (!crt_error)
+    {
+        return strerror_win32(err, gc);
+    }
+#endif
+    return strerror(err);
+}
+
 void
 x_msg_va(const unsigned int flags, const char *format, va_list arglist)

{

src/openvpn/error.c +2 -1
@@ -242,7 +254,8 @@ x_msg_va(const unsigned int flags, const char *format,
 va_list arglist)
         return;
     }
 
-    e = openvpn_errno();
+    bool crt_error = false;
+    e = openvpn_errno_maybe_crt(&crt_error);
 
     /*

* Apply muting filter.

src/openvpn/error.c +11 -6
@@ -264,7 +277,7 @@ x_msg_va(const unsigned int flags, const char *format,
 va_list arglist)
     if ((flags & M_ERRNO) && e)
     {
         openvpn_snprintf(m2, ERR_BUF_SIZE, "%s: %s (errno=%d)",
-                         m1, strerror(e), e);
+                         m1, openvpn_strerror(e, crt_error, &gc), e);
         SWAP;
     }
@@ -643,7 +656,6 @@ x_check_status(int status,
                struct link_socket *sock,
                struct tuntap *tt)
 {
-    const int my_errno = openvpn_errno();
     const char *extended_msg = NULL;
 
     msg(x_cs_verbose_level, "%s %s returned %d",
@@ -666,26 +678,34 @@ x_check_status(int status,
                 sock->info.mtu_changed = true;
             }
         }
-#elif defined(_WIN32)
+#endif /* EXTENDED_SOCKET_ERROR_CAPABILITY */
+
+#ifdef _WIN32
         /* get possible driver error from TAP-Windows driver */
         if (tuntap_defined(tt))
         {
             extended_msg = tap_win_getinfo(tt, &gc);
         }
 #endif
-        if (!ignore_sys_error(my_errno))
+
+        bool crt_error = false;
+        int my_errno = openvpn_errno_maybe_crt(&crt_error);
+
+        if (!ignore_sys_error(my_errno, crt_error))
         {
             if (extended_msg)
             {
                 msg(x_cs_info_level, "%s %s [%s]: %s (fd=%d,code=%d)",
 description,
                     sock ? proto2ascii(sock->info.proto, sock->info.af,
 true) : "",
-                    extended_msg, strerror(my_errno), sock ? sock->sd :
-1, my_errno);
+                    extended_msg, openvpn_strerror(my_errno, crt_error,
 &gc),
+                    sock ? sock->sd : -1, my_errno);
             }
             else
             {
                 msg(x_cs_info_level, "%s %s: %s (fd=%d,code=%d)",
 description,
                     sock ? proto2ascii(sock->info.proto, sock->info.af,

true) : "",

src/openvpn/error.c +2 -1
-                    strerror(my_errno), sock ? sock->sd : -1, my_errno);
+                    openvpn_strerror(my_errno, crt_error, &gc),
+                    sock ? sock->sd : -1, my_errno);
             }
 
             if (x_cs_err_delay_ms)
src/openvpn/error.h +29 -10
index ad7defe8..be8d97e5 100644
@@ -75,13 +75,10 @@ struct gc_arena;
 /* String and Error functions */
 
 #ifdef _WIN32
-#define openvpn_errno()             GetLastError()
-#define openvpn_strerror(e, gc)     strerror_win32(e, gc)
+#define openvpn_errno() GetLastError()
 const char *strerror_win32(DWORD errnum, struct gc_arena *gc);
-
 #else
-#define openvpn_errno()             errno
-#define openvpn_strerror(x, gc)     strerror(x)
+#define openvpn_errno() errno
 #endif
 
 /*
@@ -352,20 +349,22 @@ msg_get_virtual_output(void)
  * which can be safely ignored.
  */
 static inline bool
-ignore_sys_error(const int err)
+ignore_sys_error(const int err, bool crt_error)
 {
-    /* I/O operation pending */
 #ifdef _WIN32
-    if (err == WSAEWOULDBLOCK || err == WSAEINVAL)
+    if (!crt_error && ((err == WSAEWOULDBLOCK || err == WSAEINVAL)))
     {
         return true;
     }
 #else
-    if (err == EAGAIN)
+    crt_error = true;
+#endif
+
+    /* I/O operation pending */
+    if (crt_error && (err == EAGAIN))
     {
         return true;
     }
-#endif
 
 #if 0 /* if enabled, suppress ENOBUFS errors */
 #ifdef ENOBUFS
@@ -387,6 +386,26 @@ nonfatal(const unsigned int err)
     return err & M_FATAL ? (err ^ M_FATAL) | M_NONFATAL : err;
 }
 
+static inline int
+openvpn_errno_maybe_crt(bool *crt_error)
+{
+    int err = 0;
+    *crt_error = false;
+#ifdef _WIN32
+    err = GetLastError();
+    if (err == ERROR_SUCCESS)
+    {
+        /* error is likely C runtime */
+        *crt_error = true;
+        err = errno;
+    }
+#else
+    *crt_error = true;
+    err = errno;
+#endif
+    return err;
+}
+
 #include "errlevel.h"
 
 #endif /* ifndef ERROR_H */
src/openvpn/forward.c +0 -0
index 8930e578..04828a5c 100644
@@ -1660,7 +1660,14 @@ process_outgoing_link(struct context *c)
         }
 
         /* for unreachable network and "connecting" state switch to the

next host */

src/openvpn/forward.c +8 -1
-        if (size < 0 && ENETUNREACH == error_code && c->c2.tls_multi
+
+        bool unreachable = error_code ==
+#ifdef _WIN32
+            WSAENETUNREACH;
+#else
+            ENETUNREACH;
+#endif
+        if (size < 0 && unreachable && c->c2.tls_multi
             && !tls_initial_packet_received(c->c2.tls_multi) &&

c->options.mode == MODE_POINT_TO_POINT)

         {
             msg(M_INFO, "Network unreachable, restarting");
src/openvpn/manage.c +3 -2
index 9b03b057..036658b1 100644
@@ -2008,9 +2008,10 @@ man_process_command(struct management *man, const
 char *line)
 static bool
 man_io_error(struct management *man, const char *prefix)
 {
-    const int err = openvpn_errno();
+    bool crt_error = false;
+    int err = openvpn_errno_maybe_crt(&crt_error);
 
-    if (!ignore_sys_error(err))
+    if (!ignore_sys_error(err, crt_error))
     {
         struct gc_arena gc = gc_new();

msg(D_MANAGEMENT, "MANAGEMENT: TCP %s error: %s", prefix,

src/openvpn/platform.c +1 -1
index 61afee83..ae1678db 100644
@@ -532,7 +532,7 @@ platform_test_file(const char *filename)
         }
         else
         {
-            if (openvpn_errno() == EACCES)
+            if (errno == EACCES)
             {
                 msg( M_WARN | M_ERRNO, "Could not access file '%s'",
 filename);
             }
src/openvpn/tun.h +1 -1
index 3a7314c5..4bc35916 100644
@@ -446,7 +446,7 @@ tuntap_stop(int status)
      */
     if (status < 0)
     {
-        return openvpn_errno() == ERROR_FILE_NOT_FOUND;
+        return GetLastError() == ERROR_FILE_NOT_FOUND;
     }
     return false;
 }

src/openvpn/tun.h tuntap_abort(int status) · line 465

Quoted 8 lines
src/openvpn/tun.h +1 -1
@@ -459,7 +459,7 @@ tuntap_abort(int status)
      */
     if (status < 0)
     {
-        return openvpn_errno() == ERROR_OPERATION_ABORTED;
+        return GetLastError() == ERROR_OPERATION_ABORTED;
     }
     return false;
 }
#5 lore raw
In reply to Lev Stipakov

Your patch has been applied to the master branch.

I've added the S-O-B line according to our developer documentation.

I have come late to the party, but really, code like this should be avoided:

+ bool unreachable = error_code ==
+#ifdef _WIN32
+ WSAENETUNREACH;
+#else
+ ENETUNREACH;
+#endif

what is wrong writing this as follows?

+#ifdef _WIN32
+ bool unreachable = (error_code == WSAENETUNREACH);
+#else
+ bool unreachable = (error_code == ENETUNREACH);
+#endif

one line *less*, and very clear what happens in both branches, not "old style openvpn contortions with #ifdef in the middle of an expression".

Also, assignments of the type "a = b == c;" should use brackets, always
- even if the C compiler understands what this code does, humans need extra brain cycles to make sense of it.

commit 54800aa975418fe3570f3206a5f9b277dc59bd47

Author: Lev Stipakov
Date:   Tue May 3 03:28:40 2022 +0300
     Fix M_ERRNO behavior on Windows

     Acked-by: Selva Nair <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg24270.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#6 lore raw

Hi,

Review

Quoted 9 lines · Gert Doering

I have come late to the party, but really, code like this should be avoided:

(quoted diff) +6 -0
+        bool unreachable = error_code ==
+#ifdef _WIN32
+            WSAENETUNREACH;
+#else
+            ENETUNREACH;
+#endif

Even worse, this is also uncrustify-noncompliant... and I forgot to double check.

I have fixed the whitespace errors introduced in the M_ERRNO patch in commit 28557b50c6c9, as attached (and already pushed).

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...

From 28557b50c6c9354fa50b4a18374c064dc547ac25 Mon Sep 17 00:00:00 2001
From: Gert Doering <[email protected]...>
Date: Thu, 12 May 2022 08:53:04 +0200
Subject: [PATCH] Fix non-compliant whitespace introduced by commit
54800aa975418fe35.

Uncrustify fix.

---
 src/openvpn/error.c   | 2 +-
 src/openvpn/error.h   | 2 +-
 src/openvpn/forward.c | 4 ++--
 3 files changed, 4 insertions(+), 4 deletions(-)
src/openvpn/error.c +1 -1
index 1b7f5cde..49ed1dbc 100644
@@ -220,7 +220,7 @@ x_msg(const unsigned int flags, const char *format, ...)
     va_end(arglist);
 }
 
-static const char*
+static const char *
 openvpn_strerror(int err, bool crt_error, struct gc_arena *gc)
 {
 #ifdef _WIN32
src/openvpn/error.h +1 -1
index be8d97e5..972619fe 100644
@@ -399,7 +399,7 @@ openvpn_errno_maybe_crt(bool *crt_error)
         *crt_error = true;
         err = errno;
     }
-#else
+#else  /* ifdef _WIN32 */
     *crt_error = true;
     err = errno;
 #endif
src/openvpn/forward.c +2 -2
index 04828a5c..6afe152b 100644
@@ -1663,9 +1663,9 @@ process_outgoing_link(struct context *c)
 
         bool unreachable = error_code ==
 #ifdef _WIN32
-            WSAENETUNREACH;
+                           WSAENETUNREACH;
 #else
-            ENETUNREACH;
+                           ENETUNREACH;
 #endif
         if (size < 0 && unreachable && c->c2.tls_multi
             && !tls_initial_packet_received(c->c2.tls_multi) && c->options.mode == MODE_POINT_TO_POINT)
Signature · 1 line
2.36.0
#7 lore raw
In reply to Lev Stipakov

Hi,

Quoted 9 lines · Lev Stipakov

From: Lev Stipakov <[email protected]...>

We use M_ERRNO flag in logging to display error code and error message. This has been broken on Windows, where we use error code from GetLastError() and error description from strerror(). strerror() expects C runtime error code, which is quite different from last error code from WinAPI call. As a result, we got incorrect error description.

This patch breaks extended socket error reporting.

In the git tree, we have those two right next to each other

commit 54800aa975418fe3570f3206a5f9b277dc59bd47

Author: Lev Stipakov <[email protected]...>
Date:   Tue May 3 03:28:40 2022 +0300

Fix M_ERRNO behavior on Windows

-> broken

commit 043c67f36342969cd171d24c70ee6b62ebc95fee

Author: Gert Doering <[email protected]...>
Date:   Tue Feb 22 15:35:14 2022 +0100

Implement --mtu-disc for IPv6 UDP sockets.

-> works

Testing is easy: point openvpn on a Linux system(!) to an unreachable destination (--verb 5 used here, but 3 should be sufficient)).

With 043c67f, this gives

2022-07-22 18:07:59 us=599924 UDPv6 link remote: [AF_INET6]2001:608:2:a::253:1196

W2022-07-22 18:07:59 us=628976 read UDPv6 [ECONNREFUSED]: Connection refused (fd=3,code=111) W2022-07-22 18:08:02 us=168862 read UDPv6 [ECONNREFUSED]: Connection refused (fd=3,code=111) W2022-07-22 18:08:07 us=228896 read UDPv6 [ECONNREFUSED]: Connection refused (fd=3,code=111)

with 54800aa9754, this becomes

2022-07-22 18:14:16 us=271797 UDPv6 link remote: [AF_INET6]2001:608:2:a::253:1196

WWWWW^C2022-07-22 18:14:46 us=706438 event_wait : Interrupted system call (fd=-1,code=4)

("nothing nothing nothing ctrl-c")

I can see that the patch at least touches code close to it...

+#endif /* EXTENDED_SOCKET_ERROR_CAPABILITY */

... so it would be nice if someone could have a look what this patch is trampling on that it shouldn't...

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...
#8 lore raw
Quoted 48 lines · Gert Doering

Hi,

Quoted 9 lines · Lev Stipakov

From: Lev Stipakov <[email protected]...>

We use M_ERRNO flag in logging to display error code and error message. This has been broken on Windows, where we use error code from GetLastError() and error description from strerror(). strerror() expects C runtime error code, which is quite different from last error code from WinAPI call. As a result, we got incorrect error description.

This patch breaks extended socket error reporting.

In the git tree, we have those two right next to each other

commit 54800aa975418fe3570f3206a5f9b277dc59bd47

Author: Lev Stipakov <[email protected]...>
Date:   Tue May 3 03:28:40 2022 +0300

Fix M_ERRNO behavior on Windows

-> broken

commit 043c67f36342969cd171d24c70ee6b62ebc95fee

Author: Gert Doering <[email protected]...>
Date:   Tue Feb 22 15:35:14 2022 +0100

Implement --mtu-disc for IPv6 UDP sockets.

-> works

Testing is easy: point openvpn on a Linux system(!) to an unreachable destination (--verb 5 used here, but 3 should be sufficient)).

With 043c67f, this gives

2022-07-22 18:07:59 us=599924 UDPv6 link remote:

[AF_INET6]2001:608:2:a::253:1196
W2022-07-22 18:07:59 us=628976 read UDPv6 [ECONNREFUSED]: Connection refused (fd=3,code=111)
W2022-07-22 18:08:02 us=168862 read UDPv6 [ECONNREFUSED]: Connection refused (fd=3,code=111)
W2022-07-22 18:08:07 us=228896 read UDPv6 [ECONNREFUSED]: Connection refused (fd=3,code=111)

Quoted 9 lines

with 54800aa9754, this becomes

2022-07-22 18:14:16 us=271797 UDPv6 link remote:

[AF_INET6]2001:608:2:a::253:1196
WWWWW^C2022-07-22 18:14:46 us=706438 event_wait : Interrupted system call (fd=-1,code=4)

("nothing nothing nothing ctrl-c")

This one is tricky -- though the patch appeared to be a no-op for non-Windows, in error.c:x_check_status(), it did move down the line my_errno = openvpn_errno() and thus potentially lose the original error. At that time it looked like a good move (pun intended), though. So much for C99 style..

Especially, before outputting the message we call format_extended_socket_error() which calls recvmsg() which can easily return EAGAIN in errno. To top it, EAGAIN is completely ignored by ignore_sys_error(), so we get nothing printed. I think moving those line back up to the start of the function should fix this

Selva

Quoted 24 lines

I can see that the patch at least touches code close to it...

+#endif /* EXTENDED_SOCKET_ERROR_CAPABILITY */

... so it would be nice if someone could have a look what this patch is trampling on that it shouldn't...

gert
--
"If was one thing all people took for granted, was conviction that if you
feed honest figures into a computer, honest figures come out. Never
doubted
it myself till I met a computer with a sense of humor."
Robert A. Heinlein, The Moon is a Harsh
Mistress

Gert Doering - Munich, Germany
[email protected]...
_______________________________________________
Openvpn-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/openvpn-devel

#9 lore raw

Hi,

Quoted 5 lines · Selva Nair

This one is tricky -- though the patch appeared to be a no-op for non-Windows, in error.c:x_check_status(), it did move down the line my_errno = openvpn_errno() and thus potentially lose the original error. At that time it looked like a good move (pun intended), though. So much for C99 style..

;-)

Thanks for your analysis and patch. I'll stare at it a bit tomorrow and test (and then send the patch I had been working on, to get rid of the setsockopt() error message on IPv4-only sockets...)

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...