aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/utils/http_util/socket.cpp
blob: a2b9d55679495f17239d1c2c1141cf5cc865893c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
* OS and machine specific utility functions
* (C) 2015,2016,2017 Jack Lloyd
* (C) 2016 Daniel Neus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/socket.h>
#include <botan/exceptn.h>
#include <botan/mem_ops.h>
#include <chrono>

#if defined(BOTAN_HAS_BOOST_ASIO)
  /*
  * We don't need serial port support anyway, and asking for it
  * causes macro conflicts with Darwin's termios.h when this
  * file is included in the amalgamation. GH #350
  */
  #define BOOST_ASIO_DISABLE_SERIAL_PORT
  #include <boost/asio.hpp>

#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <netdb.h>
  #include <string.h>
  #include <unistd.h>
  #include <errno.h>

#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
  #define NOMINMAX 1
  #include <winsock2.h>
  #include <ws2tcpip.h>
  #include <windows.h>
#endif

namespace Botan {

namespace {

#if defined(BOTAN_HAS_BOOST_ASIO)

class Asio_Socket final : public OS::Socket
   {
   public:
      Asio_Socket(const std::string& hostname, const std::string& service) :
         m_tcp(m_io)
         {
         boost::asio::ip::tcp::resolver resolver(m_io);
         boost::asio::ip::tcp::resolver::query query(hostname, service);
         boost::asio::connect(m_tcp, resolver.resolve(query));
         }

      void write(const uint8_t buf[], size_t len) override
         {
         boost::asio::write(m_tcp, boost::asio::buffer(buf, len));
         }

      size_t read(uint8_t buf[], size_t len) override
         {
         boost::system::error_code error;
         size_t got = m_tcp.read_some(boost::asio::buffer(buf, len), error);

         if(error)
            {
            if(error == boost::asio::error::eof)
               return 0;
            throw boost::system::system_error(error); // Some other error.
            }

         return got;
         }

   private:
      boost::asio::io_service m_io;
      boost::asio::ip::tcp::socket m_tcp;
   };

#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)

class Winsock_Socket final : public OS::Socket
   {
   public:
      Winsock_Socket(const std::string& hostname, const std::string& service)
         {
         WSAData wsa_data;
         WORD wsa_version = MAKEWORD(2, 2);

         if (::WSAStartup(wsa_version, &wsa_data) != 0)
            {
            throw Exception("WSAStartup() failed: " + std::to_string(WSAGetLastError()));
            }

         if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
            {
            ::WSACleanup();
            throw Exception("Could not find a usable version of Winsock.dll");
            }

         addrinfo hints;
         ::memset(&hints, 0, sizeof(addrinfo));
         hints.ai_family = AF_UNSPEC;
         hints.ai_socktype = SOCK_STREAM;
         addrinfo* res;

         if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)
            {
            throw Exception("Name resolution failed for " + hostname);
            }

         for(addrinfo* rp = res; (m_socket == INVALID_SOCKET) && (rp != nullptr); rp = rp->ai_next)
            {
            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

            // unsupported socket type?
            if(m_socket == INVALID_SOCKET)
               continue;

            if(::connect(m_socket, rp->ai_addr, rp->ai_addrlen) != 0)
               {
               ::closesocket(m_socket);
               m_socket = INVALID_SOCKET;
               continue;
               }
            }

         ::freeaddrinfo(res);

         if(m_socket == INVALID_SOCKET)
            {
            throw Exception("Connecting to " + hostname +
                            " for service " + service + " failed");
            }
         }

      ~Winsock_Socket()
         {
         ::closesocket(m_socket);
         m_socket = INVALID_SOCKET;
         ::WSACleanup();
         }

      void write(const uint8_t buf[], size_t len) override
         {
         size_t sent_so_far = 0;
         while(sent_so_far != len)
            {
            const size_t left = len - sent_so_far;
            int sent = ::send(m_socket,
                              cast_uint8_ptr_to_char(buf + sent_so_far),
                              static_cast<int>(left),
                              0);

            if(sent == SOCKET_ERROR)
               throw Exception("Socket write failed with error " +
                               std::to_string(::WSAGetLastError()));
            else
               sent_so_far += static_cast<size_t>(sent);
            }
         }

      size_t read(uint8_t buf[], size_t len) override
         {
         int got = ::recv(m_socket,
                          cast_uint8_ptr_to_char(buf),
                          static_cast<int>(len), 0);

         if(got == SOCKET_ERROR)
            throw Exception("Socket read failed with error " +
                            std::to_string(::WSAGetLastError()));
         return static_cast<size_t>(got);
         }

   private:
      SOCKET m_socket = INVALID_SOCKET;
   };

#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
class BSD_Socket final : public OS::Socket
   {
   public:
      BSD_Socket(const std::string& hostname, const std::string& service)
         {
         addrinfo hints;
         ::memset(&hints, 0, sizeof(addrinfo));
         hints.ai_family = AF_UNSPEC;
         hints.ai_socktype = SOCK_STREAM;
         addrinfo* res;

         if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)
            {
            throw Exception("Name resolution failed for " + hostname);
            }

         m_fd = -1;

         for(addrinfo* rp = res; (m_fd < 0) && (rp != nullptr); rp = rp->ai_next)
            {
            m_fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

            if(m_fd < 0)
               {
               // unsupported socket type?
               continue;
               }

            if(::connect(m_fd, rp->ai_addr, rp->ai_addrlen) != 0)
               {
               ::close(m_fd);
               m_fd = -1;
               continue;
               }
            }

         ::freeaddrinfo(res);

         if(m_fd < 0)
            {
            throw Exception("Connecting to " + hostname +
                            " for service " + service + " failed");
            }
         }

      ~BSD_Socket()
         {
         ::close(m_fd);
         m_fd = -1;
         }

      void write(const uint8_t buf[], size_t len) override
         {
         size_t sent_so_far = 0;
         while(sent_so_far != len)
            {
            const size_t left = len - sent_so_far;
            ssize_t sent = ::write(m_fd, &buf[sent_so_far], left);
            if(sent < 0)
               throw Exception("Socket write failed with error '" +
                               std::string(::strerror(errno)) + "'");
            else
               sent_so_far += static_cast<size_t>(sent);
            }
         }

      size_t read(uint8_t buf[], size_t len) override
         {
         ssize_t got = ::read(m_fd, buf, len);

         if(got < 0)
            throw Exception("Socket read failed with error '" +
                            std::string(::strerror(errno)) + "'");
         return static_cast<size_t>(got);
         }

   private:
      int m_fd;
   };

#endif

}

std::unique_ptr<OS::Socket>
OS::open_socket(const std::string& hostname,
                const std::string& service)
   {
#if defined(BOTAN_HAS_BOOST_ASIO)
   return std::unique_ptr<OS::Socket>(new Asio_Socket(hostname, service));

#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
   return std::unique_ptr<OS::Socket>(new Winsock_Socket(hostname, service));

#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
   return std::unique_ptr<OS::Socket>(new BSD_Socket(hostname, service));

#else
   // No sockets for you
   return std::unique_ptr<Socket>();
#endif
   }

}