Debian Codegraph @

lib/kissnet/kissnet.hpp

raw symbols SCIP
1 /*
2 * MIT License
3 *
4 * Copyright (c) 2018-2020 Arthur Brainville (Ybalrid) and with the help of
5 * Comunity Contributors!
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
24 *
25 * INTRODUCTION
26 * ============
27 *
28 * Kissnet is a simple C++17 layer around the raw OS provided socket API to be
29 * used on IP networks with the TCP and UDP protocols.
30 *
31 * Kissnet is not a networking framework, and it will not process your data or
32 * assist you in any way. Kissnet's only goal is to provide a simple API to send
33 * and receive bytes,
34 * without having to play around with a bunch of structure, file descriptors,
35 * handles and pointers given to a C-style API. The other goal of kissnet is to
36 * provide an API that will works in a cross platform setting.
37 *
38 * Kissnet will automatically manage the eventual startup/shutdown of the
39 * library needed to perform socket operations on a particular platform. (e.g.
40 * the Windows Socket API on MS-Windows.
41 *
42 * Kissnet leverages (and expect you to do so), multiple features from C++17,
43 * including: std::byte, if constexpr, structured bindings, if-initializer and
44 * template parameter type deduction.
45 *
46 * The library is structured across 4 exposed data types:
47 *
48 * - buffer<size_t> : a static array of std::byte implemented via std::array.
49 * This is what you should use to hold raw data you are getting from a socket,
50 * before extracting what you need from the bytes
51 * - port_t : a 16 bit unsigned number. Represent a network port number
52 * - endpoint : a structure that represent a location where you need to connect
53 * to. Contains a hostname (as std::string) and a port number (as port_t)
54 * - socket<protocol> : a templated class that represents an ipv4 or ipv6 socket.
55 * Protocol is either TCP or UDP
56 *
57 * Kissnet does error handling in 2 ways:
58 *
59 * 1:
60 * When an operation can generate an error that the user should handle by hand
61 * anyway, a tuple containing the expected type returned, and an object that
62 * represent the status of what happens is returned.
63 *
64 * For example, socket send/receive operation can discover that the connection
65 * was closed, or was shut down properly. It could also be the fact that a
66 * socket was configured "non blocking" and would have blocked in this
67 * situation. On both occasion, these methods will return the fact that 0 bytes
68 * came across as the transaction size, and the status will indicate either an
69 * error (socket no longer valid), or an actual status message (connection
70 * closed, socket would have blocked)
71 *
72 * These status objects will behave like a const bool that equals "false" when
73 * an error occurred, and "true" when it's just a status notification
74 *
75 * 2:
76 * Fatal errors are by default handled by throwing a runtime_error exception.
77 * But, for many reasons, you may want to
78 * not use exceptions entirely.
79 *
80 * kissnet give you some facilities to get fatal errors information back, and
81 * to choose how to handle it. Kissnet give you a few levers you can use:
82 *
83 * - You can deactivate the exception support by #defining KISSNET_NO_EXCEP
84 * before #including kissnet.hpp. Instead, kissnet will use a function based
85 * error handler
86 * - By default, the error handler prints to stderr the error message, and
87 * abort the program
88 * - kissnet::error::callback is a function pointer that gets a string, and a
89 * context pointer. The string is the error message, and the context pointer
90 * what ever you gave kissnet for the occasion. This is a global pointer that
91 * you can set as you want. This will override the "print to stderr" behavior
92 * at fatal error time.
93 * - kissnet::error::ctx is a void*, this will be passed to your error handler
94 * as a "context" pointer. If you need your handler to write to a log,
95 * or to turn on the HTCPCP enabled teapot on John's desk, you can.
96 * - kissnet::abortOnFatalError is a boolean that will control the call to
97 * abort(). This is independent to the fact that you did set or not an error
98 * callback. please note that any object involved with the operation that
99 * triggered the fatal error is probably in an invalid state, and probably
100 * deserve to be thrown away.
101 */
102
103 #ifndef KISS_NET
104 #define KISS_NETcxx . . $ `lib/kissnet/kissnet.hpp:104:9`!
105
106 ///Define this to not use exceptions
107 #ifndef KISSNET_NO_EXCEP
108 #define kissnet_fatal_errorcxx . . $ `lib/kissnet/kissnet.hpp:108:9`!(STR) throw std::runtime_error(STR)
109 #else
110 #define kissnet_fatal_error(STR) kissnet::error::handle(STR);
111 #endif
112
113
114 #include <array>
115 #include <memory>
116 #include <cstddef>
117 #include <cstdint>
118 #include <cstring>
119 #include <cassert>
120 #include <stdexcept>
121 #include <string>
122 #include <utility>
123
124 #ifdef _WIN32
125
126 #define _WINSOCK_DEPRECATED_NO_WARNINGS
127 #define WIN32_LEAN_AND_MEAN
128
129 #ifndef NOMINMAX
130 #define NOMINMAX
131 #endif //endif nominmax
132
133 #include <winsock2.h>
134 #include <ws2tcpip.h>
135 #include <windows.h>
136
137 using ioctl_setting = u_long;
138 using buffsize_t = int;
139
140 #define AI_ADDRCONFIG 0x00000400
141
142 #ifndef SHUT_RDWR
143 #define SHUT_RDWR SD_BOTH
144 #endif
145
146 // taken from: https://github.com/rxi/dyad/blob/915ae4939529b9aaaf6ebfd2f65c6cff45fc0eac/src/dyad.c#L58
147 inline const char* inet_ntop(int af, const void* src, char* dst, socklen_t size)
148 {
149 union
150 {
151 struct sockaddr sa;
152 struct sockaddr_in sai;
153 struct sockaddr_in6 sai6;
154 } addr;
155 int res;
156 memset(&addr, 0, sizeof(addr));
157 addr.sa.sa_family = af;
158 if (af == AF_INET6)
159 {
160 memcpy(&addr.sai6.sin6_addr, src, sizeof(addr.sai6.sin6_addr));
161 }
162 else
163 {
164 memcpy(&addr.sai.sin_addr, src, sizeof(addr.sai.sin_addr));
165 }
166 res = WSAAddressToStringA(&addr.sa, sizeof(addr), 0, dst, reinterpret_cast<LPDWORD>(&size));
167 if (res != 0) return NULL;
168 return dst;
169 }
170
171 //Handle WinSock2/Windows Socket API initialization and cleanup
172 #pragma comment(lib, "Ws2_32.lib")
173 namespace kissnet
174 {
175
176 namespace win32_specific
177 {
178 ///Forward declare the object that will permit to manage the WSAStartup/Cleanup automatically
179 struct WSA;
180
181 ///Enclose the global pointer in this namespace. Only use this inside a shared_ptr
182 namespace internal_state
183 {
184 static WSA* global_WSA = nullptr;
185 }
186
187 ///WSA object. Only to be constructed with std::make_shared()
188 struct WSA : std::enable_shared_from_this<WSA>
189 {
190 //For safety, only initialize Windows Socket API once, and delete it once
191 ///Prevent copy construct
192 WSA(const WSA&) = delete;
193 ///Prevent copy assignment
194 WSA& operator=(const WSA&) = delete;
195 ///Prevent moving
196 WSA(WSA&&) = delete;
197 ///Prevent move assignment
198 WSA& operator=(WSA&&) = delete;
199
200 ///data storage
201 WSADATA wsa_data;
202
203 ///Startup
204 WSA() :
205 wsa_data{}
206 {
207 if (const auto status = WSAStartup(MAKEWORD(2, 2), &wsa_data); status != 0)
208 {
209 std::string error_message;
210 switch (status) // https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsastartup#return-value
211 {
212 default:
213 error_message = "Unknown error happened.";
214 break;
215 case WSASYSNOTREADY:
216 error_message = "The underlying network subsystem is not ready for network communication.";
217 break;
218 case WSAVERNOTSUPPORTED: //unlikely, we specify 2.2!
219 error_message = " The version of Windows Sockets support requested "
220 "(2.2)" //we know here the version was 2.2, add that to the error message copied from MSDN
221 " is not provided by this particular Windows Sockets implementation. ";
222 break;
223 case WSAEINPROGRESS:
224 error_message = "A blocking Windows Sockets 1.1 operation is in progress.";
225 break;
226 case WSAEPROCLIM:
227 error_message = "A limit on the number of tasks supported by the Windows Sockets implementation has been reached.";
228 break;
229 case WSAEFAULT: //unlikely, if this ctor is running, wsa_data is part of this object's "stack" data
230 error_message = "The lpWSAData parameter is not a valid pointer.";
231 break;
232 }
233 kissnet_fatal_error(error_message);
234 }
235 #ifdef KISSNET_WSA_DEBUG
236 std::cerr << "Initialized Windows Socket API\n";
237 #endif
238 }
239
240 ///Cleanup
241 ~WSA()
242 {
243 WSACleanup();
244 internal_state::global_WSA = nullptr;
245 #ifdef KISSNET_WSA_DEBUG
246 std::cerr << "Cleanup Windows Socket API\n";
247 #endif
248 }
249
250 ///get the shared pointer
251 std::shared_ptr<WSA> getPtr()
252 {
253 return shared_from_this();
254 }
255 };
256
257 ///Get-or-create the global pointer
258 inline std::shared_ptr<WSA> getWSA()
259 {
260 //If it has been created already:
261 if (internal_state::global_WSA)
262 return internal_state::global_WSA->getPtr(); //fetch the smart pointer from the naked pointer
263
264 //Create in wsa
265 auto wsa = std::make_shared<WSA>();
266
267 //Save the raw address in the global state
268 internal_state::global_WSA = wsa.get();
269
270 //Return the smart pointer
271 return wsa;
272 }
273 }
274
275 #define KISSNET_OS_SPECIFIC_PAYLOAD_NAME wsa_ptr
276 #define KISSNET_OS_SPECIFIC std::shared_ptr<kissnet::win32_specific::WSA> KISSNET_OS_SPECIFIC_PAYLOAD_NAME
277 #define KISSNET_OS_INIT KISSNET_OS_SPECIFIC_PAYLOAD_NAME = kissnet::win32_specific::getWSA()
278
279 ///Return the last error code
280 inline int get_error_code()
281 {
282 const auto error = WSAGetLastError();
283
284 //We need to posixify the values that we are actually using inside this header.
285 switch (error)
286 {
287 case WSAEWOULDBLOCK:
288 return EWOULDBLOCK;
289 case WSAEBADF:
290 return EBADF;
291 case WSAEINTR:
292 return EINTR;
293 default:
294 return error;
295 }
296 }
297 }
298 #else //UNIX platform
299
300 #include <sys/types.h>
301 #include <sys/socket.h>
302 #include <sys/ioctl.h>
303 #include <arpa/inet.h>
304 #include <netinet/in.h>
305 #include <netinet/tcp.h>
306 #include <netdb.h>
307 #include <unistd.h>
308 #include <errno.h>
309 #include <fcntl.h>
310
311 using ioctl_settingcxx . . $ ioctl_setting# = int;
312 using buffsize_tcxx . . $ buffsize_t# = size_t;
313
314 //To get consistent socket API between Windows and Linux:
315 static const int INVALID_SOCKETcxx . . $ INVALID_SOCKET. = -1;
316 static const int SOCKET_ERRORcxx . . $ SOCKET_ERROR. = -1;
317 using SOCKETcxx . . $ SOCKET# = int;
318 using SOCKADDR_INcxx . . $ SOCKADDR_IN# = sockaddr_in;
319 using SOCKADDRcxx . . $ SOCKADDR# = sockaddr;
320 using IN_ADDRcxx . . $ IN_ADDR# = in_addr;
321
322 //Wrap them in their WIN32 names
323 inline int closesocketcxx . . $ closesocket(7864480464b09eea).(SOCKETcxx . . $ SOCKET# in)
324 {
325 return close(in);
326 }
327
328 template <typename... Params>
329 inline int ioctlsocketcxx . . $ ioctlsocket(73aba6a03902b195).(int fd, int request, Params&&... params)
330 {
331 return ioctl(fd, request, params...);
332 }
333
334 #define KISSNET_OS_SPECIFIC_PAYLOAD_NAMEcxx . . $ `lib/kissnet/kissnet.hpp:334:9`! dummy
335 #define KISSNET_OS_SPECIFICcxx . . $ `lib/kissnet/kissnet.hpp:335:9`! char dummy
336 #define KISSNET_OS_INITcxx . . $ `lib/kissnet/kissnet.hpp:336:9`! dummy = 42;
337
338 namespace unix_specificcxx . . $ unix_specific/
339 {
340 }
341
342 inline int get_error_codecxx . . $ get_error_code(b126dc7c1de90089).()
343 {
344 return errnocxx . . $ `<external>/17633486526465735210/errno.h:38:10`!;
345 }
346
347 #endif //ifdef WIN32
348
349
350 #ifdef KISSNET_USE_OPENSSL
351
352 #include <openssl/ssl.h>
353 #include <openssl/err.h>
354
355 #include <vector>
356 #include <mutex>
357
358 #endif //Kissnet use OpenSSL
359
360 #ifndef SOL_TCPcxx . . $ `<external>/14446708121216675145/tcp.h:206:10`!
361 #define SOL_TCP IPPROTO_TCP
362 #endif
363
364 ///Main namespace of kissnet
365 namespace kissnetcxx . . $ kissnet/
366 {
367
368 ///Exception-less error handling infrastructure
369 namespace errorcxx . . $ kissnet/error/
370 {
371 static void (*callbackcxx . . $ kissnet/error/callback.)(const stdcxx . . $ std/::stringcxx . . $ std/string#&, void* ctx) = nullptr;
372 static void* ctxcxx . . $ kissnet/error/ctx. = nullptr;
373 static bool abortOnFatalErrorcxx . . $ kissnet/error/abortOnFatalError. = true;
374
375 inline void handlecxx . . $ kissnet/error/handle(9c546c94e5fcce4e).(const stdcxx . . $ std/::stringcxx . . $ std/string#& str)
376 {
377 //if the error::callback function has been provided, call that
378 if (callbackcxx . . $ kissnet/error/callback.)
379 {
380 callbackcxx . . $ kissnet/error/callback.(str, ctxcxx . . $ kissnet/error/ctx.);
381 }
382 //Print error into the standard error output
383 else
384 {
385 fputs(str.c_strcxx . . $ std/__cxx11/basic_string#c_str(8e614c7de0b1573e).(), stderrcxx . . $ `<external>/232824719582829767/stdio.h:155:9`!);
386 }
387
388 //If the error abort hasn't been deactivated
389 if (abortOnFatalErrorcxx . . $ kissnet/error/abortOnFatalError.)
390 {
391 abort();
392 }
393 }
394 }
395
396 ///low level protocol used, between TCP\TCP_SSL and UDP
397 enum class protocolcxx . . $ kissnet/protocol# {
398 tcpcxx . . $ kissnet/protocol#tcp.,
399 tcp_sslcxx . . $ kissnet/protocol#tcp_ssl.,
400 udpcxx . . $ kissnet/protocol#udp.
401 };
402
403 ///File descriptor set types
404 static constexpr int fds_readcxx . . $ kissnet/fds_read. = 0x1;
405 static constexpr int fds_writecxx . . $ kissnet/fds_write. = 0x2;
406 static constexpr int fds_exceptcxx . . $ kissnet/fds_except. = 0x4;
407
408 ///buffer is an array of std::byte
409 template <size_t buff_size>
410 using buffercxx . . $ kissnet/buffer# = stdcxx . . $ std/::arraycxx . . $ std/array#<stdcxx . . $ std/::byte, buff_size>;
411
412 ///port_t is the port
413 using port_tcxx . . $ kissnet/port_t# = uint16_tcxx . . $ uint16_t#;
414
415 ///An endpoint is where the network will connect to (address and port)
416 struct endpointcxx . . $ kissnet/endpoint#
417 {
418 ///The address to connect to
419 stdcxx . . $ std/::stringcxx . . $ std/string# addresscxx . . $ kissnet/endpoint#address.{cxx . . $ std/__cxx11/basic_string#basic_string(925dcc5e17f50391).};
420
421 ///The port to connect to
422 port_tcxx . . $ kissnet/port_t# portcxx . . $ kissnet/endpoint#port.{};
423
424 ///Default constructor, the endpoint is not valid at that point, but you can set the address/port manually
425 endpointcxx . . $ kissnet/endpoint#endpoint(ced63f7c635d850d).() = default;
426
427 ///Basically create the endpoint with what you give it
428 endpointcxx . . $ kissnet/endpoint#endpoint(e76fccd46cad07df).(stdcxx . . $ std/::stringcxx . . $ std/string# addr, port_tcxx . . $ kissnet/port_t# prt) :
429 addresscxx . . $ std/__cxx11/basic_string#basic_string(8f3aaafa33d05d0b).{ stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(addr) }, portcxx . . $ kissnet/endpoint#port.{ prt }
430 {}
431
432 static bool is_valid_port_numbercxx . . $ kissnet/endpoint#is_valid_port_number(31596a199e1d8a50).(unsigned long n)
433 {
434 return n < 1 << 16;
435 }
436
437 ///Construct the endpoint from "address:port"
438 endpointcxx . . $ kissnet/endpoint#endpoint(8d4ab0a187bf9331).(stdcxx . . $ std/::stringcxx . . $ std/string# addr)
439 {
440 const auto separator = addr.find_last_ofcxx . . $ std/__cxx11/basic_string#find_last_of(2dda2fc6b78abe68).(':');
441
442 //Check if input wasn't missformed
443 if (separator == stdcxx . . $ std/::stringcxx . . $ std/string#::nposcxx . . $ std/__cxx11/basic_string#npos.)
444 kissnet_fatal_errorcxx . . $ std/("string is not of address:port form");
445 if (separator == addr.sizecxx . . $ std/__cxx11/basic_string#size(6f8bd5c0ea8fb29a).() - 1)
446 kissnet_fatal_errorcxx . . $ std/runtime_error#runtime_error(85c52e162fed56f9).("string has ':' as last character. Expected port number here");
447
448 //Isolate address
449 addresscxx . . $ kissnet/endpoint#address. =cxx . . $ std/__cxx11/basic_string#`operator=`(36befb0d0c9f966). addr.substrcxx . . $ std/__cxx11/basic_string#substr(149c655009c9bbd2).(0, separator);
450
451 //Read from string as unsigned
452 const auto parsed_port = strtoul(addr.substrcxx . . $ std/__cxx11/basic_string#substr(149c655009c9bbd2).(separator + 1).c_strcxx . . $ std/__cxx11/basic_string#c_str(8e614c7de0b1573e).(), nullptr, 10);
453
454 //In all other cases, port was always given as a port_t type, strongly preventing it to be a number outside of the [0; 65535] range. Here it's not the case.
455 //To detect errors early, check it here :
456 if (!is_valid_port_numbercxx . . $ kissnet/endpoint#is_valid_port_number(31596a199e1d8a50).(parsed_port))
457 kissnet_fatal_errorcxx . . $ std/("Invalid port number " + std::to_string(parsed_port));
458
459 //Store it
460 portcxx . . $ kissnet/endpoint#port. = static_cast<port_tcxx . . $ kissnet/port_t#>(parsed_port);
461 }
462
463 ///Construct an endpoint from a SOCKADDR
464 endpointcxx . . $ kissnet/endpoint#endpoint(d12266ced554fd61).(SOCKADDRcxx . . $ SOCKADDR#* addr)
465 {
466 switch (addr->sa_family)
467 {
468 case AF_INETcxx . . $ `<external>/8962547315054503424/socket.h:97:9`!: {
469 auto ip_addr = (SOCKADDR_INcxx . . $ SOCKADDR_IN#*)(addr);
470 addresscxx . . $ kissnet/endpoint#address. =cxx . . $ std/__cxx11/basic_string#`operator=`(978ca1133b5f6e74). inet_ntoa(ip_addr->sin_addr);
471 portcxx . . $ kissnet/endpoint#port. = ntohs(ip_addr->sin_port);
472 }
473 break;
474
475 case AF_INET6cxx . . $ `<external>/8962547315054503424/socket.h:105:9`!: {
476 auto ip_addr = (sockaddr_in6*)(addr);
477 char buffer[INET6_ADDRSTRLENcxx . . $ `<external>/9581057695539925927/in.h:245:9`!];
478 addresscxx . . $ kissnet/endpoint#address. =cxx . . $ std/__cxx11/basic_string#`operator=`(978ca1133b5f6e74). inet_ntop(AF_INET6cxx . . $ `<external>/8962547315054503424/socket.h:105:9`!, &(ip_addr->sin6_addr), buffer, INET6_ADDRSTRLENcxx . . $ `<external>/9581057695539925927/in.h:245:9`!);
479 portcxx . . $ kissnet/endpoint#port. = ntohs(ip_addr->sin6_port);
480 }
481 break;
482
483 default: {
484 kissnet_fatal_errorcxx . . $ `lib/kissnet/kissnet.hpp:108:9`!("Trying to construct an endpoint for a protocol familly that is neither AF_INET or AF_INET6");
485 }
486 }
487
488 if (addresscxx . . $ kissnet/endpoint#address..emptycxx . . $ std/__cxx11/basic_string#empty(3482b152b9333168).())
489 kissnet_fatal_errorcxx . . $ std/("Couldn't construct endpoint from sockaddr(_storage) struct");
490 }
491 };
492
493 //Wrap "system calls" here to avoid conflicts with the names used in the socket class
494
495 ///socket()
496 inline auto syscall_socketcxx . . $ kissnet/syscall_socket. = [](int af, int type, int protocol) {
497 return ::socket(af, type, protocol);
498 };
499
500
501 ///select()
502 inline auto syscall_selectcxx . . $ kissnet/syscall_select. = [](int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, struct timevalcxx . . $ timeval#* timeout) {
503 return ::select(nfds, readfds, writefds, exceptfds, timeout);
504 };
505
506 ///recv()
507 inline auto syscall_recvcxx . . $ kissnet/syscall_recv. = [](SOCKETcxx . . $ SOCKET# s, char* buff, buffsize_tcxx . . $ buffsize_t# len, int flags) {
508 return ::recv(s, buff, len, flags);
509 };
510
511 ///send()
512 inline auto syscall_sendcxx . . $ kissnet/syscall_send. = [](SOCKETcxx . . $ SOCKET# s, const char* buff, buffsize_tcxx . . $ buffsize_t# len, int flags) {
513 return ::send(s, buff, len, flags);
514 };
515
516 ///bind()
517 inline auto syscall_bindcxx . . $ kissnet/syscall_bind. = [](SOCKETcxx . . $ SOCKET# s, const struct sockaddr* name, socklen_t namelen) {
518 return ::bind(s, name, namelen);
519 };
520
521 ///connect()
522 inline auto syscall_connectcxx . . $ kissnet/syscall_connect. = [](SOCKETcxx . . $ SOCKET# s, const struct sockaddr* name, socklen_t namelen) {
523 return ::connect(s, name, namelen);
524 };
525
526 ///listen()
527 inline auto syscall_listencxx . . $ kissnet/syscall_listen. = [](SOCKETcxx . . $ SOCKET# s, int backlog) {
528 return ::listen(s, backlog);
529 };
530
531 ///accept()
532 inline auto syscall_acceptcxx . . $ kissnet/syscall_accept. = [](SOCKETcxx . . $ SOCKET# s, struct sockaddr* addr, socklen_t* addrlen) {
533 return ::accept(s, addr, addrlen);
534 };
535
536 ///shutdown()
537 inline auto syscall_shutdowncxx . . $ kissnet/syscall_shutdown. = [](SOCKETcxx . . $ SOCKET# s) {
538 return ::shutdown(s, SHUT_RDWRcxx . . $ `<external>/14344695994193663403/socket.h:48:9`!);
539 };
540
541 ///Represent the status of a socket as returned by a socket operation (send, received). Implicitly convertible to bool
542 struct socket_statuscxx . . $ kissnet/socket_status#
543 {
544 ///Enumeration of socket status, with a 1 byte footprint
545 enum valuescxx . . $ kissnet/socket_status#values# : int8_tcxx . . $ int8_t# {
546 erroredcxx . . $ kissnet/socket_status#errored. = 0x0,
547 validcxx . . $ kissnet/socket_status#valid. = 0x1,
548 cleanly_disconnectedcxx . . $ kissnet/socket_status#cleanly_disconnected. = 0x2,
549 non_blocking_would_have_blockedcxx . . $ kissnet/socket_status#non_blocking_would_have_blocked. = 0x3,
550 timed_outcxx . . $ kissnet/socket_status#timed_out. = 0x4
551
552 /* ... any other info on a "still valid socket" goes here ... */
553
554 };
555
556 ///Actual value of the socket_status.
557 const valuescxx . . $ kissnet/socket_status#values# valuecxx . . $ kissnet/socket_status#value.;
558
559 ///Use the default constructor
560 socket_statuscxx . . $ kissnet/socket_status#socket_status(49f6e7a06ebc5aa8).() :
561 valuecxx . . $ kissnet/socket_status#value.{ erroredcxx . . $ kissnet/socket_status#errored. } {}
562
563 ///Construct a "errored/valid" status for a true/false
564 explicit socket_statuscxx . . $ kissnet/socket_status#socket_status(b45ddcbc8423892c).(bool state) :
565 valuecxx . . $ kissnet/socket_status#value.(valuescxx . . $ kissnet/socket_status#values#(state ? validcxx . . $ kissnet/socket_status#valid. : erroredcxx . . $ kissnet/socket_status#errored.)) {}
566
567 socket_statuscxx . . $ kissnet/socket_status#socket_status(f75c08ff6e89cd6d).(valuescxx . . $ kissnet/socket_status#values# v) :
568 valuecxx . . $ kissnet/socket_status#value.(v) {}
569
570 ///Copy socket status by default
571 socket_statuscxx . . $ kissnet/socket_status#socket_status(2b4a6c1cc972d82e).(const socket_statuscxx . . $ kissnet/socket_status#&) = default;
572
573 ///Move socket status by default
574 socket_statuscxx . . $ kissnet/socket_status#socket_status(84472b20995c98dc).(socket_statuscxx . . $ kissnet/socket_status#&&) = default;
575
576 ///implicitly convert this object to const bool (as the status should not change)
577 operatorcxx . . $ kissnet/socket_status#`operator bool`(50ce9a9e25b4a850). bool() const
578 {
579 //See the above enum: every value <= 0 correspond to an error, and will return false. Every value > 0 returns true
580 return valuecxx . . $ kissnet/socket_status#value. > 0;
581 }
582
583 int8_tcxx . . $ int8_t# get_valuecxx . . $ kissnet/socket_status#get_value(f1c002f0206d8350).()
584 {
585 return valuecxx . . $ kissnet/socket_status#value.;
586 }
587
588 bool operatorcxx . . $ kissnet/socket_status#`operator==`(cf8419e095e6f54e).==(valuescxx . . $ kissnet/socket_status#values# v)
589 {
590 return v == valuecxx . . $ kissnet/socket_status#value.;
591 }
592 };
593
594 #ifdef KISSNET_USE_OPENSSL
595 #if OPENSSL_VERSION_NUMBER < 0x10100000L
596 static std::shared_ptr <std::vector< std::mutex > > SSL_lock_cs;
597
598 class ThreadSafe_SSL
599 {
600 public:
601 ThreadSafe_SSL()
602 {
603 SSL_lock_cs = std::make_shared< std::vector < std::mutex > >( CRYPTO_num_locks() );
604
605 CRYPTO_set_locking_callback((void (*)(int, int, const char*, int))
606 win32_locking_callback);
607 }
608
609 ~ThreadSafe_SSL() { CRYPTO_set_locking_callback(nullptr); }
610
611 private:
612 static void win32_locking_callback(int mode, int type, const char* file, int line)
613 {
614 auto& locks = *SSL_lock_cs;
615
616 if (mode & CRYPTO_LOCK)
617 {
618 locks[type].lock();
619 }
620 else
621 {
622 locks[type].unlock();
623 }
624 }
625 };
626
627 #endif
628
629 class Initialize_SSL
630 {
631 public:
632 Initialize_SSL()
633 {
634 #if OPENSSL_VERSION_NUMBER < 0x1010001fL
635 SSL_load_error_strings();
636 SSL_library_init();
637 #else
638 OPENSSL_init_ssl(
639 OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL
640 );
641
642 OPENSSL_init_crypto(
643 OPENSSL_INIT_LOAD_CONFIG | OPENSSL_INIT_ADD_ALL_CIPHERS | OPENSSL_INIT_ADD_ALL_DIGESTS,
644 nullptr
645 );
646 #endif
647 }
648
649 ~Initialize_SSL()
650 {
651 #if OPENSSL_VERSION_NUMBER < 0x1010001fL
652 ERR_free_strings();
653 #endif
654 }
655
656 #if OPENSSL_VERSION_NUMBER < 0x10100000L
657 private:
658 ThreadSafe_SSL thread_setup;
659 #endif
660 };
661
662 static Initialize_SSL InitializeSSL;
663 #endif
664
665 ///Class that represent a socket
666 template <protocolcxx . . $ kissnet/protocol# sock_proto>
667 class socketcxx . . $ kissnet/socket#
668 {
669 ///Represent a number of bytes with a status information. Some of the methods of this class returns this.
670 using bytes_with_statuscxx . . $ kissnet/socket#bytes_with_status# = stdcxx . . $ std/::tuplecxx . . $ std/tuple#<size_t, socket_statuscxx . . $ kissnet/socket_status#>;
671
672 ///OS specific stuff. payload we have to hold onto for RAII management of the Operating System's socket library (e.g. Windows Socket API WinSock2)
673 KISSNET_OS_SPECIFICcxx . . $ kissnet/socket#dummy.;
674
675 ///operatic-system type for a socket object
676 SOCKETcxx . . $ SOCKET# sockcxx . . $ kissnet/socket#sock. = INVALID_SOCKETcxx . . $ INVALID_SOCKET.;
677
678 #ifdef KISSNET_USE_OPENSSL
679 SSL* pSSL = nullptr;
680 SSL_CTX* pContext = nullptr;
681 #endif
682
683 ///Location where this socket is bound
684 endpointcxx . . $ kissnet/endpoint# bind_loccxx . . $ kissnet/socket#bind_loc. =cxx . . $ kissnet/endpoint#endpoint(ced63f7c635d850d). {};
685
686 ///Address information structures
687 addrinfo getaddrinfo_hintscxx . . $ kissnet/socket#getaddrinfo_hints. = {};
688 addrinfo* getaddrinfo_resultscxx . . $ kissnet/socket#getaddrinfo_results. = nullptr;
689 addrinfo* socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo. = nullptr;
690
691 void initialize_addrinfocxx . . $ kissnet/socket#initialize_addrinfo(49f6e7a06ebc5aa8).()
692 {
693 int type{};
694 int iprotocol{};
695 if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::tcpcxx . . $ kissnet/protocol#tcp. || sock_proto == protocolcxx . . $ kissnet/protocol#::tcp_sslcxx . . $ kissnet/protocol#tcp_ssl.)
696 {
697 type = SOCK_STREAMcxx . . $ `<external>/5956532346368192945/socket_type.h:28:9`!;
698 iprotocol = IPPROTO_TCPcxx . . $ `<external>/9581057695539925927/in.h:51:9`!;
699 }
700
701 else if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::udpcxx . . $ kissnet/protocol#udp.)
702 {
703 type = SOCK_DGRAMcxx . . $ `<external>/5956532346368192945/socket_type.h:31:9`!;
704 iprotocol = IPPROTO_UDPcxx . . $ `<external>/9581057695539925927/in.h:57:9`!;
705 }
706
707 getaddrinfo_hintscxx . . $ kissnet/socket#getaddrinfo_hints. = {};
708 getaddrinfo_hintscxx . . $ kissnet/socket#getaddrinfo_hints..ai_family = AF_UNSPECcxx . . $ `<external>/8962547315054503424/socket.h:93:9`!;
709 getaddrinfo_hintscxx . . $ kissnet/socket#getaddrinfo_hints..ai_socktype = type;
710 getaddrinfo_hintscxx . . $ kissnet/socket#getaddrinfo_hints..ai_protocol = iprotocol;
711 getaddrinfo_hintscxx . . $ kissnet/socket#getaddrinfo_hints..ai_flags = AI_ADDRCONFIGcxx . . $ `<external>/564697342961150458/netdb.h:601:10`!;
712 }
713
714 ///Create and connect to socket
715 socket_statuscxx . . $ kissnet/socket_status# connectcxx . . $ kissnet/socket#connect(8e71ca6ac31925f).(addrinfo* addr, int64_tcxx . . $ int64_t# timeout, bool createsocket)
716 {
717 if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::tcpcxx . . $ kissnet/protocol#tcp. || sock_proto == protocolcxx . . $ kissnet/protocol#::tcp_sslcxx . . $ kissnet/protocol#tcp_ssl.) //only TCP is a connected protocol
718 {
719 if (createsocket)
720 {
721 closecxx . . $ kissnet/socket#close(49f6e7a06ebc5aa8).();
722 socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo. = nullptr;
723 sockcxx . . $ kissnet/socket#sock. = syscall_socketcxx . . $ kissnet/syscall_socket.(cxx . . $ kissnet/$anonymous_type_e00f1fb89d7f0574_0#`operator()`(ccfa90015542b148).addr->ai_family, addr->ai_socktype, addr->ai_protocol);
724 }
725
726 if (sockcxx . . $ kissnet/socket#sock. == INVALID_SOCKETcxx . . $ INVALID_SOCKET.)
727 return socket_statuscxx . . $ kissnet/socket_status#socket_status(f75c08ff6e89cd6d).::erroredcxx . . $ kissnet/socket_status#errored.;
728
729 socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo. = addr;
730
731 if (timeout > 0)
732 set_non_blockingcxx . . $ kissnet/socket#set_non_blocking(a85845bc2b7828e2).(true);
733
734 int error = syscall_connectcxx . . $ kissnet/syscall_connect.(cxx . . $ kissnet/$anonymous_type_e00f1fb89d7f0574_1#`operator()`(ef9c2fff92b3289).sockcxx . . $ kissnet/socket#sock., addr->ai_addr, socklen_t(addr->ai_addrlen));
735 if (error == SOCKET_ERRORcxx . . $ SOCKET_ERROR.)
736 {
737 error = get_error_codecxx . . $ get_error_code(b126dc7c1de90089).();
738 if (error == EWOULDBLOCKcxx . . $ `<external>/17922322188510340118/errno.h:22:9`! || error == EAGAINcxx . . $ `<external>/8987895939074593727/errno-base.h:15:9`! || error == EINPROGRESScxx . . $ `<external>/17922322188510340118/errno.h:99:9`!)
739 {
740 struct timevalcxx . . $ timeval# tv;
741 tv.tv_seccxx . . $ timeval#tv_sec. = static_cast<long>(timeout / 1000);
742 tv.tv_useccxx . . $ timeval#tv_usec. = 1000 * static_cast<long>(timeout % 1000);
743
744 fd_set fd_write, fd_except;;
745 FD_ZEROcxx . . $ `<external>/946878812840035423/select.h:88:9`!(&fd_write);
746 FD_SETcxx . . $ kissnet/socket#sock.(sock, &fd_write);
747 FD_ZEROcxx . . $ `<external>/946878812840035423/select.h:88:9`!(&fd_except);
748 FD_SETcxx . . $ `<external>/946878812840035423/select.h:85:9`!(sock, &fd_except);
749
750 int ret = syscall_selectcxx . . $ kissnet/syscall_select.(cxx . . $ kissnet/$anonymous_type_e00f1fb89d7f0574_2#`operator()`(874222d739bf2201).static_cast<int>(sockcxx . . $ kissnet/socket#sock.) + 1, NULLcxx . . $ `/usr/lib/gcc/x86_64-linux-gnu/15/include/stddef.h:416:9`!, &fd_write, &fd_except, &tv);
751 if (ret == -1)
752 error = get_error_codecxx . . $ get_error_code(b126dc7c1de90089).();
753 else if (ret == 0)
754 error = ETIMEDOUTcxx . . $ `<external>/17922322188510340118/errno.h:94:9`!;
755 else
756 {
757 socklen_t errlen = sizeof(error);
758 if (getsockopt(sockcxx . . $ kissnet/socket#sock., SOL_SOCKETcxx . . $ `<external>/9030916627833342711/socket.h:9:9`!, SO_ERRORcxx . . $ `<external>/9030916627833342711/socket.h:14:9`!, reinterpret_cast<char*>(&error), &errlen) != 0)
759 kissnet_fatal_errorcxx . . $ std/runtime_error#runtime_error(85c52e162fed56f9).("getting socket error returned an error");
760 }
761 }
762 }
763
764 if (timeout > 0)
765 set_non_blockingcxx . . $ kissnet/socket#set_non_blocking(a85845bc2b7828e2).(false);
766
767 if (error == 0)
768 {
769 return socket_statuscxx . . $ kissnet/socket_status#socket_status(f75c08ff6e89cd6d).::validcxx . . $ kissnet/socket_status#valid.;
770 }
771 else
772 {
773 closecxx . . $ kissnet/socket#close(49f6e7a06ebc5aa8).();
774 socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo. = nullptr;
775 return socket_statuscxx . . $ kissnet/socket_status#::erroredcxx . . $ kissnet/socket_status#errored.;
776 }
777 }
778
779 kissnet_fatal_errorcxx . . $ `lib/kissnet/kissnet.hpp:108:9`!("connect called for non-tcp socket");
780 }
781
782 ///sockaddr struct
783 sockaddr_storage socket_inputcxx . . $ kissnet/socket#socket_input. = {};
784 socklen_t socket_input_socklencxx . . $ kissnet/socket#socket_input_socklen. = 0;
785
786 public:
787 ///Construct an invalid socket
788 socketcxx . . $ kissnet/socket#`socket<sock_proto>`(49f6e7a06ebc5aa8).() = default;
789
790 ///socket<> isn't copyable
791 socketcxx . . $ kissnet/socket#`socket<sock_proto>`(b61104bb9e4687a6).(const socket&) = delete;
792
793 ///socket<> isn't copyable
794 socket& operatorcxx . . $ kissnet/socket#`operator=`(982042c849b38f38).=(const socket&) = delete;
795
796 ///Move constructor. socket<> isn't copyable
797 socketcxx . . $ kissnet/socket#`socket<sock_proto>`(5b442dd224d1f4b7).(socket&& other) noexcept
798 {
799 KISSNET_OS_SPECIFIC_PAYLOAD_NAMEcxx . . $ `lib/kissnet/kissnet.hpp:334:9`! = stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.KISSNET_OS_SPECIFIC_PAYLOAD_NAMEcxx . . $ kissnet/socket#dummy.);
800 bind_loccxx . . $ kissnet/socket#bind_loc. =cxx . . $ kissnet/endpoint#`operator=`(554e8b3a2bbe5f8c). stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.bind_loccxx . . $ kissnet/socket#bind_loc.);
801 sockcxx . . $ kissnet/socket#sock. = stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.sockcxx . . $ kissnet/socket#sock.);
802 socket_inputcxx . . $ kissnet/socket#socket_input. = stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.socket_inputcxx . . $ kissnet/socket#socket_input.);
803 socket_input_socklencxx . . $ kissnet/socket#socket_input_socklen. = stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.socket_input_socklencxx . . $ kissnet/socket#socket_input_socklen.);
804 getaddrinfo_resultscxx . . $ kissnet/socket#getaddrinfo_results. = stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.getaddrinfo_resultscxx . . $ kissnet/socket#getaddrinfo_results.);
805 socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo. = stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo.);
806
807 #ifdef KISSNET_USE_OPENSSL
808 pSSL = other.pSSL;
809 pContext = other.pContext;
810 other.pSSL = nullptr;
811 other.pContext = nullptr;
812 #endif
813
814 other.sockcxx . . $ kissnet/socket#sock. = INVALID_SOCKETcxx . . $ INVALID_SOCKET.;
815 other.getaddrinfo_resultscxx . . $ kissnet/socket#getaddrinfo_results. = nullptr;
816 other.socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo. = nullptr;
817 }
818
819 ///Move assign operation
820 socket& operatorcxx . . $ kissnet/socket#`operator=`(3ea8aa8ccef87593).=(socket&& other) noexcept
821 {
822 if (this != &other)
823 {
824 if (!(sockcxx . . $ kissnet/socket#sock. < 0) || sockcxx . . $ kissnet/socket#sock. != INVALID_SOCKETcxx . . $ INVALID_SOCKET.)
825 closesocketcxx . . $ closesocket(7864480464b09eea).(sockcxx . . $ kissnet/socket#sock.);
826
827 KISSNET_OS_SPECIFIC_PAYLOAD_NAMEcxx . . $ `lib/kissnet/kissnet.hpp:334:9`! = stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.KISSNET_OS_SPECIFIC_PAYLOAD_NAMEcxx . . $ kissnet/socket#dummy.);
828 bind_loccxx . . $ kissnet/socket#bind_loc. =cxx . . $ kissnet/endpoint#`operator=`(554e8b3a2bbe5f8c). stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.bind_loccxx . . $ kissnet/socket#bind_loc.);
829 sockcxx . . $ kissnet/socket#sock. = stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.sockcxx . . $ kissnet/socket#sock.);
830 socket_inputcxx . . $ kissnet/socket#socket_input. = stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.socket_inputcxx . . $ kissnet/socket#socket_input.);
831 socket_input_socklencxx . . $ kissnet/socket#socket_input_socklen. = stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.socket_input_socklencxx . . $ kissnet/socket#socket_input_socklen.);
832 getaddrinfo_resultscxx . . $ kissnet/socket#getaddrinfo_results. = stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.getaddrinfo_resultscxx . . $ kissnet/socket#getaddrinfo_results.);
833 socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo. = stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(other.socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo.);
834
835 #ifdef KISSNET_USE_OPENSSL
836 pSSL = other.pSSL;
837 pContext = other.pContext;
838 other.pSSL = nullptr;
839 other.pContext = nullptr;
840 #endif
841
842 other.sockcxx . . $ kissnet/socket#sock. = INVALID_SOCKETcxx . . $ INVALID_SOCKET.;
843 other.getaddrinfo_resultscxx . . $ kissnet/socket#getaddrinfo_results. = nullptr;
844 other.socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo. = nullptr;
845 }
846 return *this;
847 }
848
849 ///Return true if the underlying OS provided socket representation (file descriptor, handle...). Both socket are pointing to the same thing in this case
850 bool operatorcxx . . $ kissnet/socket#`operator==`(c506d5f696e058c3).==(const socket& other) const
851 {
852 return sockcxx . . $ kissnet/socket#sock. == other.sockcxx . . $ kissnet/socket#sock.;
853 }
854
855 ///Return true if socket is valid. If this is false, you probably shouldn't attempt to send/receive anything, it will probably explode in your face!
856 bool is_validcxx . . $ kissnet/socket#is_valid(50ce9a9e25b4a850).() const
857 {
858 return sockcxx . . $ kissnet/socket#sock. != INVALID_SOCKETcxx . . $ INVALID_SOCKET.;
859 }
860
861 inline operatorcxx . . $ kissnet/socket#`operator bool`(50ce9a9e25b4a850). bool() const
862 {
863 return is_validcxx . . $ kissnet/socket#is_valid(50ce9a9e25b4a850).();
864 }
865
866 ///Construct socket and (if applicable) connect to the endpoint
867 socketcxx . . $ kissnet/socket#`socket<sock_proto>`(fd934d33336f6a28).(endpointcxx . . $ kissnet/endpoint# bind_to) :
868 bind_loccxx . . $ kissnet/socket#bind_loc.{ stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(bind_to) }
869 {
870 //operating system related housekeeping
871 KISSNET_OS_INITcxx . . $ kissnet/socket#dummy.;
872
873 //Do we use streams or datagrams
874 initialize_addrinfocxx . . $ kissnet/socket#initialize_addrinfo(49f6e7a06ebc5aa8).();
875
876 if (getaddrinfo(bind_loccxx . . $ kissnet/socket#bind_loc..addresscxx . . $ kissnet/endpoint#address..c_strcxx . . $ std/__cxx11/basic_string#c_str(8e614c7de0b1573e).(), stdcxx . . $ std/::to_stringcxx . . $ std/__cxx11/to_string(3d81e17e7a87eecc).(bind_loccxx . . $ kissnet/socket#bind_loc..portcxx . . $ kissnet/endpoint#port.).c_strcxx . . $ std/__cxx11/basic_string#c_str(8e614c7de0b1573e).(), &getaddrinfo_hintscxx . . $ kissnet/socket#getaddrinfo_hints., &getaddrinfo_resultscxx . . $ kissnet/socket#getaddrinfo_results.) != 0)
877 {
878 kissnet_fatal_errorcxx . . $ std/runtime_error#("getaddrinfo failed!");
879 }
880
881 for (auto* addr = getaddrinfo_resultscxx . . $ kissnet/socket#getaddrinfo_results.; addr; addr = addr->ai_next)
882 {
883 sockcxx . . $ kissnet/socket#sock. = syscall_socketcxx . . $ kissnet/syscall_socket.(cxx . . $ kissnet/$anonymous_type_e00f1fb89d7f0574_0#`operator()`(ccfa90015542b148).addr->ai_family, addr->ai_socktype, addr->ai_protocol);
884 if (sockcxx . . $ kissnet/socket#sock. != INVALID_SOCKETcxx . . $ INVALID_SOCKET.)
885 {
886 socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo. = addr;
887 break;
888 }
889 }
890
891 if (sockcxx . . $ kissnet/socket#sock. == INVALID_SOCKETcxx . . $ INVALID_SOCKET.)
892 {
893 kissnet_fatal_errorcxx . . $ std/runtime_error#runtime_error(85c52e162fed56f9).("unable to create socket!");
894 }
895 }
896
897 ///Construct a socket from an operating system socket, an additional endpoint to remember from where we are
898 socketcxx . . $ kissnet/socket#`socket<sock_proto>`(52f7c6cc58d26318).(SOCKETcxx . . $ SOCKET# native_sock, endpointcxx . . $ kissnet/endpoint# bind_to) :
899 sockcxx . . $ kissnet/socket#sock.{ native_sock }, bind_loccxx . . $ kissnet/socket#bind_loc.(stdcxx . . $ std/::movecxx . . $ std/move(e35c19a1ba7baa26).(bind_to))
900 {
901 KISSNET_OS_INITcxx . . $ kissnet/socket#dummy.;
902
903 initialize_addrinfocxx . . $ kissnet/socket#initialize_addrinfo(49f6e7a06ebc5aa8).();
904 }
905
906 ///Set the socket in non blocking mode
907 /// \param state By default "true". If put to false, it will set the socket back into blocking, normal mode
908 void set_non_blockingcxx . . $ kissnet/socket#set_non_blocking(a85845bc2b7828e2).(bool state = true) const
909 {
910 #ifdef _WIN32
911 ioctl_setting set = state ? 1 : 0;
912 if (ioctlsocket(sock, FIONBIO, &set) < 0)
913 #else
914 const auto flags = fcntl(sockcxx . . $ kissnet/socket#sock., F_GETFLcxx . . $ `<external>/14578502075116107718/fcntl-linux.h:168:9`!, 0);
915 const auto newflags = state ? flags | O_NONBLOCKcxx . . $ `<external>/14578502075116107718/fcntl-linux.h:62:10`! : flags ^ O_NONBLOCKcxx . . $ `<external>/14578502075116107718/fcntl-linux.h:62:10`!;
916 if (fcntl(sockcxx . . $ kissnet/socket#sock., F_SETFLcxx . . $ `<external>/14578502075116107718/fcntl-linux.h:169:9`!, newflags) < 0)
917 #endif
918 kissnet_fatal_errorcxx . . $ std/runtime_error#runtime_error(85c52e162fed56f9).("setting socket to nonblock returned an error");
919 }
920
921 ///Set the socket option for broadcasts
922 /// \param state By default "true". If put to false, it will disable broadcasts
923 void set_broadcastcxx . . $ kissnet/socket#set_broadcast(a85845bc2b7828e2).(bool state = true) const
924 {
925 const int broadcast = state ? 1 : 0;
926 if(setsockopt(sockcxx . . $ kissnet/socket#sock., SOL_SOCKETcxx . . $ `<external>/9030916627833342711/socket.h:9:9`!, SO_BROADCASTcxx . . $ `<external>/9030916627833342711/socket.h:16:9`!, reinterpret_cast<const char*>(&broadcast), sizeof(broadcast)) != 0)
927 kissnet_fatal_errorcxx . . $ std/runtime_error#runtime_error(85c52e162fed56f9).("setting socket broadcast mode returned an error");
928 }
929
930 /// Set the socket option for TCPNoDelay
931 /// \param state By default "true". If put to false, it will disable TCPNoDelay
932 void set_tcp_no_delaycxx . . $ kissnet/socket#set_tcp_no_delay(a85845bc2b7828e2).(bool state = true) const
933 {
934 if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::tcpcxx . . $ kissnet/protocol#tcp.)
935 {
936 const int tcpnodelay = state ? 1 : 0;
937 if (setsockopt(sockcxx . . $ kissnet/socket#sock., SOL_TCPcxx . . $ `<external>/14446708121216675145/tcp.h:206:10`!, TCP_NODELAYcxx . . $ `<external>/14446708121216675145/tcp.h:40:9`!, reinterpret_cast<const char*>(&tcpnodelay), sizeof(tcpnodelay)) != 0)
938 kissnet_fatal_errorcxx . . $ std/("setting socket tcpnodelay mode returned an error");
939 }
940 }
941
942 /// Get socket status
943 socket_statuscxx . . $ kissnet/socket_status# get_statuscxx . . $ kissnet/socket#get_status(4913b257ea0784c8).() const
944 {
945 int sockerror = 0;
946 socklen_t errlen = sizeof(sockerror);
947 if (getsockopt(sockcxx . . $ kissnet/socket#sock., SOL_SOCKETcxx . . $ `<external>/9030916627833342711/socket.h:9:9`!, SO_ERRORcxx . . $ `<external>/9030916627833342711/socket.h:14:9`!, reinterpret_cast<char*>(&sockerror), &errlen) != 0)
948 kissnet_fatal_errorcxx . . $ std/runtime_error#("getting socket error returned an error");
949
950 return sockerrorcxx . . $ kissnet/socket_status#socket_status(f75c08ff6e89cd6d). == SOCKET_ERRORcxx . . $ SOCKET_ERROR. ? socket_statuscxx . . $ kissnet/socket_status#::erroredcxx . . $ kissnet/socket_status#errored. : socket_statuscxx . . $ kissnet/socket_status#::validcxx . . $ kissnet/socket_status#valid.;
951 }
952
953 ///Bind socket locally using the address and port of the endpoint
954 void bindcxx . . $ kissnet/socket#bind(49f6e7a06ebc5aa8).()
955 {
956 if (syscall_bindcxx . . $ kissnet/syscall_bind.(cxx . . $ kissnet/$anonymous_type_e00f1fb89d7f0574_3#`operator()`(ef9c2fff92b3289).sockcxx . . $ kissnet/socket#sock., static_cast<SOCKADDRcxx . . $ SOCKADDR#*>(socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo.->ai_addr), socklen_t(socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo.->ai_addrlen)) == SOCKET_ERRORcxx . . $ SOCKET_ERROR.)
957 {
958 kissnet_fatal_errorcxx . . $ `lib/kissnet/kissnet.hpp:108:9`!("bind() failed\n");
959 }
960 }
961
962 ///(For TCP) connect to the endpoint as client
963 socket_statuscxx . . $ kissnet/socket_status# connectcxx . . $ kissnet/socket#connect(fc54a4b67016a244).(int64_tcxx . . $ int64_t# timeout = 0)
964 {
965 if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::tcpcxx . . $ kissnet/protocol#tcp.) //only TCP is a connected protocol
966 {
967 // try to connect to existing native socket, if any.
968 auto curr_addr = socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo.;
969 if (connectcxx . . $ kissnet/socket#connect(fc54a4b67016a244).(curr_addr, timeout, false) != socket_statuscxx . . $ kissnet/socket_status#::validcxx . . $ kissnet/socket_status#valid.)
970 {
971 // try to create/connect native socket for one of the other addrinfo, if any
972 for (auto* addr = getaddrinfo_resultscxx . . $ kissnet/socket#getaddrinfo_results.; addr; addr = addr->ai_next)
973 {
974 if (addr == curr_addr)
975 continue; // already checked
976
977 if (connectcxx . . $ kissnet/socket#connect(8e71ca6ac31925f).(addr, timeout, true) == socket_statuscxx . . $ kissnet/socket_status#::validcxx . . $ kissnet/socket_status#valid.)
978 break; // success
979 }
980 }
981
982 if (sockcxx . . $ kissnet/socket#sock. == INVALID_SOCKETcxx . . $ INVALID_SOCKET.)
983 kissnet_fatal_errorcxx . . $ std/runtime_error#runtime_error(85c52e162fed56f9).("unable to create connectable socket!");
984
985 return socket_statuscxx . . $ kissnet/socket_status#socket_status(f75c08ff6e89cd6d).::validcxx . . $ kissnet/socket_status#valid.;
986 }
987 #ifdef KISSNET_USE_OPENSSL
988 else if constexpr (sock_proto == protocol::tcp_ssl) //only TCP is a connected protocol
989 {
990 // try to connect to existing native socket, if any.
991 auto curr_addr = socket_addrinfo;
992 if (connect(curr_addr, timeout, false) != socket_status::valid)
993 {
994 // try to create/connect native socket for one of the other addrinfo, if any
995 for (auto* addr = getaddrinfo_results; addr; addr = addr->ai_next)
996 {
997 if (addr == curr_addr)
998 continue; // already checked
999
1000 if (connect(addr, timeout, true) == socket_status::valid)
1001 break; // success
1002 }
1003 }
1004
1005 if (sock == INVALID_SOCKET)
1006 kissnet_fatal_error("unable to create connectable socket!");
1007
1008 auto* pMethod = TLSv1_2_client_method();
1009
1010 pContext = SSL_CTX_new(pMethod);
1011 pSSL = SSL_new(pContext);
1012 if (!pSSL)
1013 return socket_status::errored;
1014
1015 if (!(static_cast<bool>(SSL_set_fd(pSSL, sock))))
1016 return socket_status::errored;
1017
1018 if (SSL_connect(pSSL) != 1)
1019 return socket_status::errored;
1020
1021 return socket_status::valid;
1022 }
1023 #endif
1024 }
1025
1026 ///(for TCP= setup socket to listen to connection. Need to be called on binded socket, before being able to accept()
1027 void listencxx . . $ kissnet/socket#listen(49f6e7a06ebc5aa8).()
1028 {
1029 if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::tcpcxx . . $ kissnet/protocol#tcp.)
1030 {
1031 if (syscall_listencxx . . $ kissnet/syscall_listen.(cxx . . $ kissnet/$anonymous_type_e00f1fb89d7f0574_4#`operator()`(adc74905ab378dc7).sockcxx . . $ kissnet/socket#sock., SOMAXCONNcxx . . $ `<external>/8962547315054503424/socket.h:178:9`!) == SOCKET_ERRORcxx . . $ SOCKET_ERROR.)
1032 {
1033 kissnet_fatal_errorcxx . . $ std/runtime_error#("listen failed\n");
1034 }
1035 }
1036 }
1037
1038 ///(for TCP) Wait for incoming connection, return socket connect to the client. Blocking.
1039 socket acceptcxx . . $ kissnet/socket#accept(d20524ecc9507e4c).()
1040 {
1041 if constexpr (sock_proto != protocolcxx . . $ kissnet/protocol#::tcpcxx . . $ kissnet/protocol#tcp.)
1042 {
1043 return { INVALID_SOCKETcxx . . $ INVALID_SOCKET., {} };
1044 }
1045
1046 sockaddr_storage socket_address;
1047 SOCKETcxx . . $ SOCKET# s;
1048 socklen_t size = sizeof socket_address;
1049
1050 if ((s = syscall_acceptcxx . . $ kissnet/syscall_accept.(cxx . . $ kissnet/$anonymous_type_e00f1fb89d7f0574_5#`operator()`(8b2f9ad422d5f0e5).sockcxx . . $ kissnet/socket#sock., reinterpret_cast<SOCKADDRcxx . . $ SOCKADDR#*>(&socket_address), &size)) == INVALID_SOCKETcxx . . $ INVALID_SOCKET.)
1051 {
1052 const auto error = get_error_codecxx . . $ get_error_code(b126dc7c1de90089).();
1053 switch (error)
1054 {
1055 case EWOULDBLOCKcxx . . $ `<external>/17922322188510340118/errno.h:22:9`!: //if socket "would have blocked" from the call, ignore
1056 case EINTRcxx . . $ `<external>/8987895939074593727/errno-base.h:8:9`!: //if blocking call got interrupted, ignore;
1057 return {};
1058 }
1059
1060 kissnet_fatal_errorcxx . . $ std/("accept() returned an invalid socket\n");
1061 }
1062
1063 return { s, endpointcxx . . $ kissnet/endpoint#(reinterpret_cast<SOCKADDRcxx . . $ SOCKADDR#*>(&socket_address)) };
1064 }
1065
1066 void closecxx . . $ kissnet/socket#close(49f6e7a06ebc5aa8).()
1067 {
1068 if (sockcxx . . $ kissnet/socket#sock. != INVALID_SOCKETcxx . . $ INVALID_SOCKET.)
1069 {
1070 #ifdef KISSNET_USE_OPENSSL
1071 if constexpr (sock_proto == protocol::tcp_ssl)
1072 {
1073 if (pSSL)
1074 {
1075 SSL_set_shutdown(pSSL, SSL_RECEIVED_SHUTDOWN | SSL_SENT_SHUTDOWN);
1076 SSL_shutdown(pSSL);
1077 SSL_free(pSSL);
1078 if(pContext)
1079 SSL_CTX_free(pContext);
1080 }
1081 }
1082 #endif
1083
1084 closesocketcxx . . $ closesocket(7864480464b09eea).(sockcxx . . $ kissnet/socket#sock.);
1085 }
1086
1087 sockcxx . . $ kissnet/socket#sock. = INVALID_SOCKETcxx . . $ INVALID_SOCKET.;
1088 }
1089
1090 void shutdowncxx . . $ kissnet/socket#shutdown(49f6e7a06ebc5aa8).()
1091 {
1092 if (sockcxx . . $ kissnet/socket#sock. != INVALID_SOCKETcxx . . $ INVALID_SOCKET.)
1093 {
1094 syscall_shutdowncxx . . $ kissnet/syscall_shutdown.(cxx . . $ kissnet/$anonymous_type_e00f1fb89d7f0574_6#`operator()`(7ccb52b1bfe01045).sockcxx . . $ kissnet/socket#sock.);
1095 }
1096 }
1097
1098 ///Close socket on destruction
1099 ~cxx . . $ kissnet/socket#`~socket<sock_proto>`(49f6e7a06ebc5aa8).socket()
1100 {
1101 closecxx . . $ kissnet/socket#close(49f6e7a06ebc5aa8).();
1102
1103 if (getaddrinfo_resultscxx . . $ kissnet/socket#getaddrinfo_results.)
1104 freeaddrinfo(getaddrinfo_resultscxx . . $ kissnet/socket#getaddrinfo_results.);
1105 }
1106
1107 ///Select socket with timeout
1108 socket_statuscxx . . $ kissnet/socket_status# selectcxx . . $ kissnet/socket#select(a70ecaee8a8d8cbe).(int fds, int64_tcxx . . $ int64_t# timeout)
1109 {
1110 fd_set fd_read, fd_write, fd_except;;
1111 struct timevalcxx . . $ timeval# tv;
1112
1113 tv.tv_seccxx . . $ timeval#tv_sec. = static_cast<long>(timeout / 1000);
1114 tv.tv_useccxx . . $ timeval#tv_usec. = 1000 * static_cast<long>(timeout % 1000);
1115
1116 if (fds & fds_readcxx . . $ kissnet/fds_read.)
1117 {
1118 FD_ZEROcxx . . $ `<external>/946878812840035423/select.h:88:9`!(&fd_read);
1119 FD_SETcxx . . $ `<external>/946878812840035423/select.h:85:9`!(sock, &fd_read);
1120 }
1121 if (fds & fds_writecxx . . $ kissnet/fds_write.)
1122 {
1123 FD_ZEROcxx . . $ `<external>/946878812840035423/select.h:88:9`!(&fd_write);
1124 FD_SETcxx . . $ kissnet/socket#sock.(sock, &fd_write);
1125 }
1126 if (fds & fds_exceptcxx . . $ kissnet/fds_except.)
1127 {
1128 FD_ZEROcxx . . $ `<external>/946878812840035423/select.h:88:9`!(&fd_except);
1129 FD_SETcxx . . $ `<external>/946878812840035423/select.h:85:9`!(sock, &fd_except);
1130 }
1131
1132 int ret = syscall_selectcxx . . $ kissnet/syscall_select.(cxx . . $ kissnet/$anonymous_type_e00f1fb89d7f0574_2#`operator()`(874222d739bf2201).static_cast<int>(sockcxx . . $ kissnet/socket#sock.) + 1,
1133 fds & fds_readcxx . . $ kissnet/fds_read. ? &fd_read : NULLcxx . . $ `/usr/lib/gcc/x86_64-linux-gnu/15/include/stddef.h:416:9`!,
1134 fds & fds_writecxx . . $ kissnet/fds_write. ? &fd_write : NULLcxx . . $ `/usr/lib/gcc/x86_64-linux-gnu/15/include/stddef.h:416:9`!,
1135 fds & fds_exceptcxx . . $ kissnet/fds_except. ? &fd_except : NULLcxx . . $ `/usr/lib/gcc/x86_64-linux-gnu/15/include/stddef.h:416:9`!, &tv);
1136 if (ret == -1)
1137 return socket_statuscxx . . $ kissnet/socket_status#::erroredcxx . . $ kissnet/socket_status#errored.;
1138 else if (ret == 0)
1139 return socket_statuscxx . . $ kissnet/socket_status#socket_status(f75c08ff6e89cd6d).::timed_outcxx . . $ kissnet/socket_status#timed_out.;
1140 return socket_statuscxx . . $ kissnet/socket_status#::validcxx . . $ kissnet/socket_status#valid.;
1141 }
1142
1143 template <size_t buff_size>
1144 bytes_with_statuscxx . . $ kissnet/socket#bytes_with_status# sendcxx . . $ kissnet/socket#send(d91f6d067cdbfefc).(const buffercxx . . $ kissnet/buffer#<buff_size>& buff, const size_t length = buff_size)
1145 {
1146 assertcxx . . $ `/usr/include/assert.h:102:11`!(buff_size >= length);
1147 return sendcxx . . $ kissnet/socket#send(d91f6d067cdbfefc).(buff.datacxx . . $ std/array#data(258ee1c9e0a18a5c).(), length);
1148 }
1149
1150 ///Send some bytes through the pipe
1151 bytes_with_statuscxx . . $ kissnet/socket#bytes_with_status# sendcxx . . $ kissnet/socket#send(9541104488f187ad).(const stdcxx . . $ std/::byte* read_buff, size_t length)
1152 {
1153 auto received_bytes{ 0 };
1154 if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::tcpcxx . . $ kissnet/protocol#tcp.)
1155 {
1156 received_bytes = syscall_sendcxx . . $ kissnet/syscall_send.(cxx . . $ kissnet/$anonymous_type_e00f1fb89d7f0574_7#`operator()`(86bd1f4c7980d605).sockcxx . . $ kissnet/socket#sock., reinterpret_cast<const char*>(read_buff), static_cast<buffsize_tcxx . . $ buffsize_t#>(length), 0);
1157 }
1158 #ifdef KISSNET_USE_OPENSSL
1159 else if constexpr (sock_proto == protocol::tcp_ssl)
1160 {
1161 received_bytes = SSL_write(pSSL, reinterpret_cast<const char*>(read_buff), static_cast<buffsize_t>(length));
1162 }
1163 #endif
1164 else if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::udpcxx . . $ kissnet/protocol#udp.)
1165 {
1166 received_bytes = sendto(sockcxx . . $ kissnet/socket#sock., reinterpret_cast<const char*>(read_buff), static_cast<buffsize_tcxx . . $ buffsize_t#>(length), 0, static_cast<SOCKADDRcxx . . $ SOCKADDR#*>(socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo.->ai_addr), socklen_t(socket_addrinfocxx . . $ kissnet/socket#socket_addrinfo.->ai_addrlen));
1167 }
1168
1169 if (received_bytes < 0)
1170 {
1171 if (get_error_codecxx . . $ get_error_code(b126dc7c1de90089).() == EWOULDBLOCKcxx . . $ `<external>/17922322188510340118/errno.h:22:9`!)
1172 {
1173 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). 0, socket_statuscxx . . $ kissnet/socket_status#::non_blocking_would_have_blockedcxx . . $ kissnet/socket_status#non_blocking_would_have_blocked. };
1174 }
1175
1176 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). 0, socket_statuscxx . . $ kissnet/socket_status#::erroredcxx . . $ kissnet/socket_status#errored. };
1177 }
1178
1179 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). received_bytes, socket_statuscxx . . $ kissnet/socket_status#::validcxx . . $ kissnet/socket_status#valid. };
1180 }
1181
1182 ///receive bytes inside the buffer, return the number of bytes you got. You can choose to write inside the buffer at a specific start offset (in number of bytes)
1183 template <size_t buff_size>
1184 bytes_with_statuscxx . . $ kissnet/socket#bytes_with_status# recvcxx . . $ kissnet/socket#recv(dca3851a397fb1a4).(buffercxx . . $ kissnet/buffer#<buff_size>& write_buff, size_t start_offset = 0)
1185 {
1186 auto received_bytes = 0;
1187 if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::tcpcxx . . $ kissnet/protocol#tcp.)
1188 {
1189 received_bytes = syscall_recvcxx . . $ kissnet/syscall_recv.(cxx . . $ kissnet/$anonymous_type_e00f1fb89d7f0574_8#`operator()`(b9240665eb6994b0).sockcxx . . $ kissnet/socket#sock., reinterpret_cast<char*>(write_buff.datacxx . . $ std/array#data(258ee1c9e0a18a5c).()) + start_offset, static_cast<buffsize_tcxx . . $ buffsize_t#>(buff_size - start_offset), 0);
1190 }
1191 #ifdef KISSNET_USE_OPENSSL
1192 else if constexpr (sock_proto == protocol::tcp_ssl)
1193 {
1194 received_bytes = SSL_read(pSSL, reinterpret_cast<char*>(write_buff.data()) + start_offset, static_cast<buffsize_t>(buff_size - start_offset));
1195 }
1196 #endif
1197 else if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::udpcxx . . $ kissnet/protocol#udp.)
1198 {
1199 socket_input_socklencxx . . $ kissnet/socket#socket_input_socklen. = sizeof socket_inputcxx . . $ kissnet/socket#socket_input.;
1200
1201 received_bytes = ::recvfrom(sockcxx . . $ kissnet/socket#sock., reinterpret_cast<char*>(write_buff.datacxx . . $ std/array#data(8e614c7de0b1573e).()) + start_offset, static_cast<buffsize_tcxx . . $ buffsize_t#>(buff_size - start_offset), 0, reinterpret_cast<sockaddr*>(&socket_inputcxx . . $ kissnet/socket#socket_input.), &socket_input_socklencxx . . $ kissnet/socket#socket_input_socklen.);
1202 }
1203
1204 if (received_bytes < 0)
1205 {
1206 const auto error = get_error_codecxx . . $ get_error_code(b126dc7c1de90089).();
1207 if (error == EWOULDBLOCKcxx . . $ `<external>/17922322188510340118/errno.h:22:9`!)
1208 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). 0, socket_statuscxx . . $ kissnet/socket_status#::non_blocking_would_have_blockedcxx . . $ kissnet/socket_status#non_blocking_would_have_blocked. };
1209 if (error == EAGAINcxx . . $ `<external>/8987895939074593727/errno-base.h:15:9`!)
1210 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). 0, socket_statuscxx . . $ kissnet/socket_status#::non_blocking_would_have_blockedcxx . . $ kissnet/socket_status#non_blocking_would_have_blocked. };
1211 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). 0, socket_statuscxx . . $ kissnet/socket_status#::erroredcxx . . $ kissnet/socket_status#errored. };
1212 }
1213
1214 if (received_bytes == 0)
1215 {
1216 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). received_bytes, socket_statuscxx . . $ kissnet/socket_status#::cleanly_disconnectedcxx . . $ kissnet/socket_status#cleanly_disconnected. };
1217 }
1218
1219 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). size_t(received_bytes), socket_statuscxx . . $ kissnet/socket_status#::validcxx . . $ kissnet/socket_status#valid. };
1220 }
1221
1222 ///receive up-to len bytes inside the memory location pointed by buffer
1223 bytes_with_statuscxx . . $ kissnet/socket#bytes_with_status# recvcxx . . $ kissnet/socket#recv(4e4ee72ac4b70ab3).(stdcxx . . $ std/::byte* buffer, size_t len, bool wait = true)
1224 {
1225 auto received_bytes = 0;
1226 if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::tcpcxx . . $ kissnet/protocol#tcp.)
1227 {
1228 int flags;
1229 if (wait)
1230 flags = MSG_WAITALLcxx . . $ `<external>/8962547315054503424/socket.h:230:9`!;
1231 else
1232 {
1233 #ifdef _WIN32
1234 flags = 0; // MSG_DONTWAIT not avail on windows, need to make socket nonblockingto emulate
1235 set_non_blocking(true);
1236 #else
1237 flags = MSG_DONTWAITcxx . . $ `<external>/8962547315054503424/socket.h:226:9`!;
1238 #endif
1239 }
1240 received_bytes = syscall_recvcxx . . $ kissnet/syscall_recv.(cxx . . $ kissnet/$anonymous_type_e00f1fb89d7f0574_8#`operator()`(b9240665eb6994b0).sockcxx . . $ kissnet/socket#sock., reinterpret_cast<char*>(buffer), static_cast<buffsize_tcxx . . $ buffsize_t#>(len), flags);
1241 #ifdef _WIN32
1242 set_non_blocking(false);
1243 #endif
1244 }
1245
1246 #ifdef KISSNET_USE_OPENSSL
1247 else if constexpr (sock_proto == protocol::tcp_ssl)
1248 {
1249 received_bytes = SSL_read(pSSL, reinterpret_cast<char*>(buffer), static_cast<buffsize_t>(len));
1250 }
1251 #endif
1252
1253 else if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::udpcxx . . $ kissnet/protocol#udp.)
1254 {
1255 socket_input_socklencxx . . $ kissnet/socket#socket_input_socklen. = sizeof socket_inputcxx . . $ kissnet/socket#socket_input.;
1256
1257 received_bytes = ::recvfrom(sockcxx . . $ kissnet/socket#sock., reinterpret_cast<char*>(buffer), static_cast<buffsize_tcxx . . $ buffsize_t#>(len), 0, reinterpret_cast<sockaddr*>(&socket_inputcxx . . $ kissnet/socket#socket_input.), &socket_input_socklencxx . . $ kissnet/socket#socket_input_socklen.);
1258 }
1259
1260 if (received_bytes < 0)
1261 {
1262 const auto error = get_error_codecxx . . $ get_error_code(b126dc7c1de90089).();
1263 if (error == EWOULDBLOCKcxx . . $ `<external>/17922322188510340118/errno.h:22:9`!)
1264 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). 0, socket_statuscxx . . $ kissnet/socket_status#::non_blocking_would_have_blockedcxx . . $ kissnet/socket_status#non_blocking_would_have_blocked. };
1265 if (error == EAGAINcxx . . $ `<external>/8987895939074593727/errno-base.h:15:9`!)
1266 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). 0, socket_statuscxx . . $ kissnet/socket_status#::non_blocking_would_have_blockedcxx . . $ kissnet/socket_status#non_blocking_would_have_blocked. };
1267 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). 0, socket_statuscxx . . $ kissnet/socket_status#::erroredcxx . . $ kissnet/socket_status#errored. };
1268 }
1269
1270 if (received_bytes == 0)
1271 {
1272 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). received_bytes, socket_statuscxx . . $ kissnet/socket_status#::cleanly_disconnectedcxx . . $ kissnet/socket_status#cleanly_disconnected. };
1273 }
1274
1275 return {cxx . . $ std/tuple#tuple(533e79eb6234819d). size_t(received_bytes), socket_statuscxx . . $ kissnet/socket_status#::validcxx . . $ kissnet/socket_status#valid. };
1276 }
1277
1278 ///Return the endpoint where this socket is talking to
1279 endpointcxx . . $ kissnet/endpoint# get_bind_loccxx . . $ kissnet/socket#get_bind_loc(28873b813346cadf).() const
1280 {
1281 return bind_loccxx . . $ kissnet/socket#bind_loc.;
1282 }
1283
1284 ///Return an endpoint that originated the data in the last recv
1285 endpointcxx . . $ kissnet/endpoint# get_recv_endpointcxx . . $ kissnet/socket#get_recv_endpoint(28873b813346cadf).() const
1286 {
1287 if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::tcpcxx . . $ kissnet/protocol#tcp.)
1288 {
1289 return get_bind_loccxx . . $ kissnet/socket#get_bind_loc(28873b813346cadf).();
1290 }
1291 if constexpr (sock_proto == protocolcxx . . $ kissnet/protocol#::udpcxx . . $ kissnet/protocol#udp.)
1292 {
1293 return {cxx . . $ kissnet/endpoint#endpoint(d12266ced554fd61). (sockaddr*)&socket_inputcxx . . $ kissnet/socket#socket_input. };
1294 }
1295 }
1296
1297 ///Return the number of bytes available inside the socket
1298 size_t bytes_availablecxx . . $ kissnet/socket#bytes_available(fe4d2d262d4164a8).() const
1299 {
1300 static ioctl_settingcxx . . $ ioctl_setting# size = 0;
1301 const auto status = ioctlsocketcxx . . $ ioctlsocket(73aba6a03902b195).(sockcxx . . $ kissnet/socket#sock., FIONREADcxx . . $ `<external>/123502480044527469/ioctls.h:46:9`!, &size);
1302
1303 if (status < 0)
1304 {
1305 kissnet_fatal_errorcxx . . $ std/runtime_error#("ioctlsocket status is negative when getting FIONREAD\n");
1306 }
1307
1308 return size > 0 ? size : 0;
1309 }
1310
1311 ///Return the protocol used by this socket
1312 static protocolcxx . . $ kissnet/protocol# get_protocolcxx . . $ kissnet/socket#get_protocol(803b4d80abe0110c).()
1313 {
1314 return sock_proto;
1315 }
1316 };
1317
1318 ///Alias for socket<protocol::tcp>
1319 using tcp_socketcxx . . $ kissnet/tcp_socket# = socketcxx . . $ kissnet/socket#<protocolcxx . . $ kissnet/protocol#::tcpcxx . . $ kissnet/protocol#tcp.>;
1320 ///Alias for socket<protocol::tcp_ssl>
1321 using tcp_ssl_socketcxx . . $ kissnet/tcp_ssl_socket# = socketcxx . . $ kissnet/socket#<protocolcxx . . $ kissnet/protocol#::tcp_sslcxx . . $ kissnet/protocol#tcp_ssl.>;
1322 ///Alias for socket<protocol::udp>
1323 using udp_socketcxx . . $ kissnet/udp_socket# = socketcxx . . $ kissnet/socket#<protocolcxx . . $ kissnet/protocol#::udpcxx . . $ kissnet/protocol#udp.>;
1324 }
1325
1326 //cleanup preprocessor macros
1327 #undef KISSNET_OS_SPECIFIC_PAYLOAD_NAMEcxx . . $ `lib/kissnet/kissnet.hpp:334:9`!
1328 #undef KISSNET_OS_SPECIFICcxx . . $ `lib/kissnet/kissnet.hpp:335:9`!
1329 #undef KISSNET_OS_INITcxx . . $ `lib/kissnet/kissnet.hpp:336:9`!
1330 #undef kissnet_fatal_errorcxx . . $ `lib/kissnet/kissnet.hpp:108:9`!
1331
1332 #endif //KISS_NET