OLD | NEW |
| (Empty) |
1 /* | |
2 * Copyright 2011 The Native Client Authors. All rights reserved. | |
3 * Use of this source code is governed by a BSD-style license that can | |
4 * be found in the LICENSE file. | |
5 */ | |
6 #include <winsock2.h> | |
7 | |
8 #include "debug_conn/debug_socket_impl.h" | |
9 #include "debug_conn/debug_util.h" | |
10 | |
11 #define CHECK_ERROR() DebugSocketLogError(__FILE__, __LINE__, 1) | |
12 #define PROCESS_ERROR() DebugSocketLogError(__FILE__, __LINE__, 0) | |
13 | |
14 static int s_SocketsAvailible = 0; | |
15 DSError DebugSocketInit() | |
16 { | |
17 WORD wVersionRequested; | |
18 WSADATA wsaData; | |
19 int err; | |
20 | |
21 // Make sure to request the use of sockets. | |
22 // NOTE: It is safe to call Startup multiple times | |
23 wVersionRequested = MAKEWORD(2, 2); | |
24 err = WSAStartup(wVersionRequested, &wsaData); | |
25 if (err != 0) { | |
26 // We could not find a matching DLL | |
27 debug_log_error("WSAStartup failed with error: %d\n", err); | |
28 return DSE_ERROR; | |
29 } | |
30 | |
31 if (HIBYTE(wsaData.wVersion) != 2) | |
32 { | |
33 // We couldn't get a matching version | |
34 debug_log_error("Could not find a usable version of Winsock.dll\n"); | |
35 WSACleanup(); | |
36 return DSE_ERROR; | |
37 } | |
38 | |
39 s_SocketsAvailible = 1; | |
40 return DSE_OK; | |
41 } | |
42 | |
43 DSError DebugSocketExit() { | |
44 // Make sure to signal we are done with sockets | |
45 // NOTE: It must be called as many times as Startup. | |
46 if (s_SocketsAvailible) | |
47 { | |
48 s_SocketsAvailible = 0; | |
49 WSACleanup(); | |
50 } | |
51 | |
52 return DSE_OK; | |
53 } | |
54 | |
55 DSError DebugSocketCreate(DSHandle *h) { | |
56 SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | |
57 | |
58 if (-1 == s) | |
59 return PROCESS_ERROR(); | |
60 | |
61 *h = (DSHandle) s; | |
62 return DSE_OK; | |
63 } | |
64 | |
65 | |
66 DSError DebugSocketClose(DSHandle handle) { | |
67 SOCKET s = (SOCKET) handle; | |
68 | |
69 // Check this isn't already invalid | |
70 if (-1 == s) | |
71 return DSE_OK; | |
72 | |
73 if (shutdown(s, SD_BOTH)) | |
74 return CHECK_ERROR(); | |
75 | |
76 // If not then close it | |
77 if (closesocket(s) != 0) | |
78 return CHECK_ERROR(); | |
79 | |
80 return DSE_OK; | |
81 } | |
82 | |
83 | |
84 int DebugSocketGetError(int block_ok) { | |
85 int err = GetLastError(); | |
86 | |
87 if (block_ok && (WSAEWOULDBLOCK == err)) | |
88 return 0; | |
89 | |
90 return err; | |
91 } | |
92 | |
OLD | NEW |