Debian Codegraph @

crt/aws-c-io/source/windows/winsock_init.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 /* clang is just a naive little idealist and doesn't understand that it can't just
7 go around re-ordering windows header files. Also, sorry about the C++ style comments
8 below, clang-format doesn't work (at least on my version) with the c-style comments. */
9
10 // clang-format off
11 #include <winsock2.h>
12 #include <ws2tcpip.h>
13 #include <mswsock.h>
14 // clang-format on
15
16 #include <aws/io/logging.h>
17 #include <aws/io/private/socket_impl.h>
18 #include <aws/io/socket.h>
19
20 #include <stdlib.h>
21
22 static LPFN_CONNECTEX s_connect_ex_fn = NULL;
23 static LPFN_ACCEPTEX s_accept_ex_fn = NULL;
24 static bool s_winsock_init = false;
25
26 void aws_check_and_init_winsock(void) {
27
28 if (!s_winsock_init) {
29 AWS_LOGF_INFO(AWS_LS_IO_SOCKET, "static: initializing WinSock");
30 WORD requested_version = MAKEWORD(2, 2);
31 WSADATA wsa_data;
32 if (WSAStartup(requested_version, &wsa_data)) {
33 AWS_LOGF_FATAL(
34 AWS_LS_IO_SOCKET, "static: WinSock initialization failed with error %d", (int)GetLastError());
35 AWS_ASSERT(0);
36 exit(-1);
37 }
38
39 SOCKET dummy_socket = socket(AF_INET, SOCK_STREAM, 0);
40 AWS_ASSERT(dummy_socket != INVALID_SOCKET);
41
42 AWS_LOGF_INFO(AWS_LS_IO_SOCKET, "static: loading WSAID_CONNECTEX function");
43 GUID connect_ex_guid = WSAID_CONNECTEX;
44 DWORD bytes_written = 0;
45 int rc = WSAIoctl(
46 dummy_socket,
47 SIO_GET_EXTENSION_FUNCTION_POINTER,
48 &connect_ex_guid,
49 sizeof(connect_ex_guid),
50 &s_connect_ex_fn,
51 sizeof(s_connect_ex_fn),
52 &bytes_written,
53 NULL,
54 NULL);
55
56 if (rc) {
57 AWS_LOGF_ERROR(
58 AWS_LS_IO_SOCKET, "static: failed to load WSAID_CONNECTEX function with error %d", (int)GetLastError());
59 AWS_ASSERT(0);
60 exit(-1);
61 }
62
63 AWS_LOGF_INFO(AWS_LS_IO_SOCKET, "static: loading WSAID_ACCEPTEX function");
64 GUID accept_ex_guid = WSAID_ACCEPTEX;
65 bytes_written = 0;
66 rc = WSAIoctl(
67 dummy_socket,
68 SIO_GET_EXTENSION_FUNCTION_POINTER,
69 &accept_ex_guid,
70 sizeof(accept_ex_guid),
71 &s_accept_ex_fn,
72 sizeof(s_accept_ex_fn),
73 &bytes_written,
74 NULL,
75 NULL);
76
77 if (rc) {
78 AWS_LOGF_ERROR(
79 AWS_LS_IO_SOCKET, "static: failed to load WSAID_ACCEPTEX function with error %d", (int)GetLastError());
80 AWS_ASSERT(0);
81 exit(-1);
82 }
83
84 closesocket(dummy_socket);
85 s_winsock_init = true;
86 }
87 }
88
89 aws_ms_fn_ptr aws_winsock_get_connectex_fn(void) {
90 aws_check_and_init_winsock();
91 return (aws_ms_fn_ptr)s_connect_ex_fn;
92 }
93
94 aws_ms_fn_ptr aws_winsock_get_acceptex_fn(void) {
95 aws_check_and_init_winsock();
96 return (aws_ms_fn_ptr)s_accept_ex_fn;
97 }