From fe4829776bacef6f75790337a0fd5c0b0e18890b Mon Sep 17 00:00:00 2001
From: Nick Mathewson <nickm@torproject.org>
Date: Mon, 24 Sep 2007 16:26:11 +0000
Subject: [PATCH]  r15324@catbus:  nickm | 2007-09-24 12:22:21 -0400  New
 evutil.h macros to manipulate winsock errors.  Use them in http.c and in
 evutil_socketpair().

svn:r451
---
 evutil.c | 16 ++++++++++------
 evutil.h | 10 ++++++++++
 http.c   |  4 ++--
 3 files changed, 22 insertions(+), 8 deletions(-)

diff --git a/evutil.c b/evutil.c
index 44b3a10a..e87fa461 100644
--- a/evutil.c
+++ b/evutil.c
@@ -77,15 +77,17 @@ evutil_socketpair(int family, int type, int protocol, int fd[2])
 		|| family != AF_UNIX
 #endif
 		) {
-		return -WSAEAFNOSUPPORT;
+		SET_SOCKET_ERROR(WSAEAFNOSUPPORT);
+		return -1;
 	}
 	if (!fd) {
-		return -EINVAL;
+		SET_SOCKET_ERROR(WSAEINVAL);
+		return -1;
 	}
 
 	listener = socket(AF_INET, type, 0);
 	if (listener < 0)
-		return -errno;
+		return -1;
 	memset(&listen_addr, 0, sizeof(listen_addr));
 	listen_addr.sin_family = AF_INET;
 	listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
@@ -134,14 +136,16 @@ evutil_socketpair(int family, int type, int protocol, int fd[2])
 	saved_errno = WSAECONNABORTED;
  tidy_up_and_fail:
 	if (saved_errno < 0)
-		saved_errno = errno;
+		saved_errno = WSAGetLastError();
 	if (listener != -1)
 		EVUTIL_CLOSESOCKET(listener);
 	if (connector != -1)
 		EVUTIL_CLOSESOCKET(connector);
 	if (acceptor != -1)
 		EVUTIL_CLOSESOCKET(acceptor);
-	return -saved_errno;
+
+	SET_SOCKET_ERROR(saved_errno);
+	return -1;
 #endif
 }
 
@@ -157,7 +161,7 @@ evutil_make_socket_nonblocking(int fd)
 	if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
 		event_warn("fcntl(O_NONBLOCK)");
 		return -1;
-	}
+}	
 #endif
 	return 0;
 }
diff --git a/evutil.h b/evutil.h
index 10cb4171..358c8199 100644
--- a/evutil.h
+++ b/evutil.h
@@ -46,6 +46,16 @@ int evutil_make_socket_nonblocking(int sock);
 #define EVUTIL_CLOSESOCKET(s) close(s)
 #endif
 
+#ifdef WIN32
+#define EVUTIL_SOCKET_ERROR() WSAGetLastError()
+#define EVUTIL_SET_SOCKET_ERROR(errcode)		\
+	do { WSASetLastError(errcode); } while (0)
+#else
+#define EVUTIL_SOCKET_ERROR() (errno)
+#define EVUTIL_SET_SOCKET_ERROR(errcode)		\
+		do { errno = (errcode); } while (0)
+#endif
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/http.c b/http.c
index 0d952423..098680dd 100644
--- a/http.c
+++ b/http.c
@@ -2356,9 +2356,9 @@ bind_socket_ai(struct addrinfo *ai)
 	return (fd);
 
  out:
-	serrno = errno;
+	serrno = EVUTIL_SOCKET_ERROR();
 	EVUTIL_CLOSESOCKET(fd);
-	errno = serrno;
+	EVUTIL_SET_SOCKET_ERROR(serrno);
 	return (-1);
 }
 
-- 
2.40.0