1 /*
2 * (C) 2014,2017 Jack Lloyd
3 *     2017 René Korthaus, Rohde & Schwarz Cybersecurity
4 *
5 * Botan is released under the Simplified BSD License (see license.txt)
6 */
7 
8 #ifndef BOTAN_CLI_SOCKET_UTILS_H_
9 #define BOTAN_CLI_SOCKET_UTILS_H_
10 
11 #include <botan/build.h>
12 #include "cli_exceptions.h"
13 
14 #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
15 
16 #include <winsock2.h>
17 #include <WS2tcpip.h>
18 
19 typedef SOCKET socket_type;
20 
invalid_socket()21 inline socket_type invalid_socket() { return INVALID_SOCKET; }
22 
23 typedef size_t ssize_t;
24 typedef int sendrecv_len_type;
25 
close_socket(socket_type s)26 inline void close_socket(socket_type s) { ::closesocket(s); }
27 
28 #define STDIN_FILENO _fileno(stdin)
29 
init_sockets()30 inline void init_sockets()
31    {
32    WSAData wsa_data;
33    WORD wsa_version = MAKEWORD(2, 2);
34 
35    if(::WSAStartup(wsa_version, &wsa_data) != 0)
36       {
37       throw Botan_CLI::CLI_Error("WSAStartup() failed: " + std::to_string(WSAGetLastError()));
38       }
39 
40    if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
41       {
42       ::WSACleanup();
43       throw Botan_CLI::CLI_Error("Could not find a usable version of Winsock.dll");
44       }
45    }
46 
stop_sockets()47 inline void stop_sockets()
48    {
49    ::WSACleanup();
50    }
51 
err_to_string(int e)52 inline std::string err_to_string(int e)
53    {
54    // TODO use strerror_s here
55    return "Error code " + std::to_string(e);
56    }
57 
close(int fd)58 inline int close(int fd)
59    {
60    return ::closesocket(fd);
61    }
62 
read(int s,void * buf,size_t len)63 inline int read(int s, void* buf, size_t len)
64    {
65    return ::recv(s, reinterpret_cast<char*>(buf), static_cast<int>(len), 0);
66    }
67 
send(int s,const uint8_t * buf,size_t len,int flags)68 inline int send(int s, const uint8_t* buf, size_t len, int flags)
69    {
70    return ::send(s, reinterpret_cast<const char*>(buf), static_cast<int>(len), flags);
71    }
72 
73 #elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
74 
75 #include <sys/types.h>
76 #include <sys/time.h>
77 #include <sys/socket.h>
78 #include <arpa/inet.h>
79 #include <netinet/in.h>
80 #include <netdb.h>
81 #include <unistd.h>
82 #include <errno.h>
83 #include <fcntl.h>
84 
85 typedef int socket_type;
86 typedef size_t sendrecv_len_type;
87 
invalid_socket()88 inline socket_type invalid_socket() { return -1; }
close_socket(socket_type s)89 inline void close_socket(socket_type s) { ::close(s); }
90 
init_sockets()91 inline void init_sockets() {}
stop_sockets()92 inline void stop_sockets() {}
93 
err_to_string(int e)94 inline std::string err_to_string(int e)
95    {
96    return std::strerror(e);
97    }
98 
99 #endif
100 
101 #if !defined(MSG_NOSIGNAL)
102    #define MSG_NOSIGNAL 0
103 #endif
104 
105 #endif
106