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_NET
105
106 ///Define this to not use exceptions
107 #ifndef KISSNET_NO_EXCEP
108 #define kissnet_fatal_error(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_setting = int;
312 using buffsize_t = size_t;
313
314 //To get consistent socket API between Windows and Linux:
315 static const int INVALID_SOCKET = -1;
316 static const int SOCKET_ERROR = -1;
317 using SOCKET = int;
318 using SOCKADDR_IN = sockaddr_in;
319 using SOCKADDR = sockaddr;
320 using IN_ADDR = in_addr;
321
322 //Wrap them in their WIN32 names
323 inline int closesocket(SOCKET in)
324 {
325 return close(in);
326 }
327
328 template <typename... Params>
329 inline int ioctlsocket(int fd, int request, Params&&... params)
330 {
331 return ioctl(fd, request, params...);
332 }
333
334 #define KISSNET_OS_SPECIFIC_PAYLOAD_NAME dummy
335 #define KISSNET_OS_SPECIFIC char dummy
336 #define KISSNET_OS_INIT dummy = 42;
337
338 namespace unix_specific
339 {
340 }
341
342 inline int get_error_code()
343 {
344 return errno;
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_TCP
361 #define SOL_TCP IPPROTO_TCP
362 #endif
363
364 ///Main namespace of kissnet
365 namespace kissnet
366 {
367
368 ///Exception-less error handling infrastructure
369 namespace error
370 {
371 static void (*callback)(const std::string&, void* ctx) = nullptr;
372 static void* ctx = nullptr;
373 static bool abortOnFatalError = true;
374
375 inline void handle(const std::string& str)
376 {
377 //if the error::callback function has been provided, call that
378 if (callback)
379 {
380 callback(str, ctx);
381 }
382 //Print error into the standard error output
383 else
384 {
385 fputs(str.c_str(), stderr);
386 }
387
388 //If the error abort hasn't been deactivated
389 if (abortOnFatalError)
390 {
391 abort();
392 }
393 }
394 }
395
396 ///low level protocol used, between TCP\TCP_SSL and UDP
397 enum class protocol {
398 tcp,
399 tcp_ssl,
400 udp
401 };
402
403 ///File descriptor set types
404 static constexpr int fds_read = 0x1;
405 static constexpr int fds_write = 0x2;
406 static constexpr int fds_except = 0x4;
407
408 ///buffer is an array of std::byte
409 template <size_t buff_size>
410 using buffer = std::array<std::byte, buff_size>;
411
412 ///port_t is the port
413 using port_t = uint16_t;
414
415 ///An endpoint is where the network will connect to (address and port)
416 struct endpoint
417 {
418 ///The address to connect to
419 std::string address{};
420
421 ///The port to connect to
422 port_t port{};
423
424 ///Default constructor, the endpoint is not valid at that point, but you can set the address/port manually
425 endpoint() = default;
426
427 ///Basically create the endpoint with what you give it
428 endpoint(std::string addr, port_t prt) :
429 address{ std::move(addr) }, port{ prt }
430 {}
431
432 static bool is_valid_port_number(unsigned long n)
433 {
434 return n < 1 << 16;
435 }
436
437 ///Construct the endpoint from "address:port"
438 endpoint(std::string addr)
439 {
440 const auto separator = addr.find_last_of(':');
441
442 //Check if input wasn't missformed
443 if (separator == std::string::npos)
444 kissnet_fatal_error("string is not of address:port form");
445 if (separator == addr.size() - 1)
446 kissnet_fatal_error("string has ':' as last character. Expected port number here");
447
448 //Isolate address
449 address = addr.substr(0, separator);
450
451 //Read from string as unsigned
452 const auto parsed_port = strtoul(addr.substr(separator + 1).c_str(), 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_number(parsed_port))
457 kissnet_fatal_error("Invalid port number " + std::to_string(parsed_port));
458
459 //Store it
460 port = static_cast<port_t>(parsed_port);
461 }
462
463 ///Construct an endpoint from a SOCKADDR
464 endpoint(SOCKADDR* addr)
465 {
466 switch (addr->sa_family)
467 {
468 case AF_INET: {
469 auto ip_addr = (SOCKADDR_IN*)(addr);
470 address = inet_ntoa(ip_addr->sin_addr);
471 port = ntohs(ip_addr->sin_port);
472 }
473 break;
474
475 case AF_INET6: {
476 auto ip_addr = (sockaddr_in6*)(addr);
477 char buffer[INET6_ADDRSTRLEN];
478 address = inet_ntop(AF_INET6, &(ip_addr->sin6_addr), buffer, INET6_ADDRSTRLEN);
479 port = ntohs(ip_addr->sin6_port);
480 }
481 break;
482
483 default: {
484 kissnet_fatal_error("Trying to construct an endpoint for a protocol familly that is neither AF_INET or AF_INET6");
485 }
486 }
487
488 if (address.empty())
489 kissnet_fatal_error("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_socket = [](int af, int type, int protocol) {
497 return ::socket(af, type, protocol);
498 };
499
500
501 ///select()
502 inline auto syscall_select = [](int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, struct timeval* timeout) {
503 return ::select(nfds, readfds, writefds, exceptfds, timeout);
504 };
505
506 ///recv()
507 inline auto syscall_recv = [](SOCKET s, char* buff, buffsize_t len, int flags) {
508 return ::recv(s, buff, len, flags);
509 };
510
511 ///send()
512 inline auto syscall_send = [](SOCKET s, const char* buff, buffsize_t len, int flags) {
513 return ::send(s, buff, len, flags);
514 };
515
516 ///bind()
517 inline auto syscall_bind = [](SOCKET s, const struct sockaddr* name, socklen_t namelen) {
518 return ::bind(s, name, namelen);
519 };
520
521 ///connect()
522 inline auto syscall_connect = [](SOCKET s, const struct sockaddr* name, socklen_t namelen) {
523 return ::connect(s, name, namelen);
524 };
525
526 ///listen()
527 inline auto syscall_listen = [](SOCKET s, int backlog) {
528 return ::listen(s, backlog);
529 };
530
531 ///accept()
532 inline auto syscall_accept = [](SOCKET s, struct sockaddr* addr, socklen_t* addrlen) {
533 return ::accept(s, addr, addrlen);
534 };
535
536 ///shutdown()
537 inline auto syscall_shutdown = [](SOCKET s) {
538 return ::shutdown(s, SHUT_RDWR);
539 };
540
541 ///Represent the status of a socket as returned by a socket operation (send, received). Implicitly convertible to bool
542 struct socket_status
543 {
544 ///Enumeration of socket status, with a 1 byte footprint
545 enum values : int8_t {
546 errored = 0x0,
547 valid = 0x1,
548 cleanly_disconnected = 0x2,
549 non_blocking_would_have_blocked = 0x3,
550 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 values value;
558
559 ///Use the default constructor
560 socket_status() :
561 value{ errored } {}
562
563 ///Construct a "errored/valid" status for a true/false
564 explicit socket_status(bool state) :
565 value(values(state ? valid : errored)) {}
566
567 socket_status(values v) :
568 value(v) {}
569
570 ///Copy socket status by default
571 socket_status(const socket_status&) = default;
572
573 ///Move socket status by default
574 socket_status(socket_status&&) = default;
575
576 ///implicitly convert this object to const bool (as the status should not change)
577 operator 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 value > 0;
581 }
582
583 int8_t get_value()
584 {
585 return value;
586 }
587
588 bool operator==(values v)
589 {
590 return v == 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 <protocol sock_proto>
667 class 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_status = std::tuple<size_t, 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_SPECIFIC;
674
675 ///operatic-system type for a socket object
676 SOCKET sock = 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 endpoint bind_loc = {};
685
686 ///Address information structures
687 addrinfo getaddrinfo_hints = {};
688 addrinfo* getaddrinfo_results = nullptr;
689 addrinfo* socket_addrinfo = nullptr;
690
691 void initialize_addrinfo()
692 {
693 int type{};
694 int iprotocol{};
695 if constexpr (sock_proto == protocol::tcp || sock_proto == protocol::tcp_ssl)
696 {
697 type = SOCK_STREAM;
698 iprotocol = IPPROTO_TCP;
699 }
700
701 else if constexpr (sock_proto == protocol::udp)
702 {
703 type = SOCK_DGRAM;
704 iprotocol = IPPROTO_UDP;
705 }
706
707 getaddrinfo_hints = {};
708 getaddrinfo_hints.ai_family = AF_UNSPEC;
709 getaddrinfo_hints.ai_socktype = type;
710 getaddrinfo_hints.ai_protocol = iprotocol;
711 getaddrinfo_hints.ai_flags = AI_ADDRCONFIG;
712 }
713
714 ///Create and connect to socket
715 socket_status connect(addrinfo* addr, int64_t timeout, bool createsocket)
716 {
717 if constexpr (sock_proto == protocol::tcp || sock_proto == protocol::tcp_ssl) //only TCP is a connected protocol
718 {
719 if (createsocket)
720 {
721 close();
722 socket_addrinfo = nullptr;
723 sock = syscall_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
724 }
725
726 if (sock == INVALID_SOCKET)
727 return socket_status::errored;
728
729 socket_addrinfo = addr;
730
731 if (timeout > 0)
732 set_non_blocking(true);
733
734 int error = syscall_connect(sock, addr->ai_addr, socklen_t(addr->ai_addrlen));
735 if (error == SOCKET_ERROR)
736 {
737 error = get_error_code();
738 if (error == EWOULDBLOCK || error == EAGAIN || error == EINPROGRESS)
739 {
740 struct timeval tv;
741 tv.tv_sec = static_cast<long>(timeout / 1000);
742 tv.tv_usec = 1000 * static_cast<long>(timeout % 1000);
743
744 fd_set fd_write, fd_except;;
745 FD_ZERO(&fd_write);
746 FD_SET(sock, &fd_write);
747 FD_ZERO(&fd_except);
748 FD_SET(sock, &fd_except);
749
750 int ret = syscall_select(static_cast<int>(sock) + 1, NULL, &fd_write, &fd_except, &tv);
751 if (ret == -1)
752 error = get_error_code();
753 else if (ret == 0)
754 error = ETIMEDOUT;
755 else
756 {
757 socklen_t errlen = sizeof(error);
758 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&error), &errlen) != 0)
759 kissnet_fatal_error("getting socket error returned an error");
760 }
761 }
762 }
763
764 if (timeout > 0)
765 set_non_blocking(false);
766
767 if (error == 0)
768 {
769 return socket_status::valid;
770 }
771 else
772 {
773 close();
774 socket_addrinfo = nullptr;
775 return socket_status::errored;
776 }
777 }
778
779 kissnet_fatal_error("connect called for non-tcp socket");
780 }
781
782 ///sockaddr struct
783 sockaddr_storage socket_input = {};
784 socklen_t socket_input_socklen = 0;
785
786 public:
787 ///Construct an invalid socket
788 socket() = default;
789
790 ///socket<> isn't copyable
791 socket(const socket&) = delete;
792
793 ///socket<> isn't copyable
794 socket& operator=(const socket&) = delete;
795
796 ///Move constructor. socket<> isn't copyable
797 socket(socket&& other) noexcept
798 {
799 KISSNET_OS_SPECIFIC_PAYLOAD_NAME = std::move(other.KISSNET_OS_SPECIFIC_PAYLOAD_NAME);
800 bind_loc = std::move(other.bind_loc);
801 sock = std::move(other.sock);
802 socket_input = std::move(other.socket_input);
803 socket_input_socklen = std::move(other.socket_input_socklen);
804 getaddrinfo_results = std::move(other.getaddrinfo_results);
805 socket_addrinfo = std::move(other.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.sock = INVALID_SOCKET;
815 other.getaddrinfo_results = nullptr;
816 other.socket_addrinfo = nullptr;
817 }
818
819 ///Move assign operation
820 socket& operator=(socket&& other) noexcept
821 {
822 if (this != &other)
823 {
824 if (!(sock < 0) || sock != INVALID_SOCKET)
825 closesocket(sock);
826
827 KISSNET_OS_SPECIFIC_PAYLOAD_NAME = std::move(other.KISSNET_OS_SPECIFIC_PAYLOAD_NAME);
828 bind_loc = std::move(other.bind_loc);
829 sock = std::move(other.sock);
830 socket_input = std::move(other.socket_input);
831 socket_input_socklen = std::move(other.socket_input_socklen);
832 getaddrinfo_results = std::move(other.getaddrinfo_results);
833 socket_addrinfo = std::move(other.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.sock = INVALID_SOCKET;
843 other.getaddrinfo_results = nullptr;
844 other.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 operator==(const socket& other) const
851 {
852 return sock == other.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_valid() const
857 {
858 return sock != INVALID_SOCKET;
859 }
860
861 inline operator bool() const
862 {
863 return is_valid();
864 }
865
866 ///Construct socket and (if applicable) connect to the endpoint
867 socket(endpoint bind_to) :
868 bind_loc{ std::move(bind_to) }
869 {
870 //operating system related housekeeping
871 KISSNET_OS_INIT;
872
873 //Do we use streams or datagrams
874 initialize_addrinfo();
875
876 if (getaddrinfo(bind_loc.address.c_str(), std::to_string(bind_loc.port).c_str(), &getaddrinfo_hints, &getaddrinfo_results) != 0)
877 {
878 kissnet_fatal_error("getaddrinfo failed!");
879 }
880
881 for (auto* addr = getaddrinfo_results; addr; addr = addr->ai_next)
882 {
883 sock = syscall_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
884 if (sock != INVALID_SOCKET)
885 {
886 socket_addrinfo = addr;
887 break;
888 }
889 }
890
891 if (sock == INVALID_SOCKET)
892 {
893 kissnet_fatal_error("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 socket(SOCKET native_sock, endpoint bind_to) :
899 sock{ native_sock }, bind_loc(std::move(bind_to))
900 {
901 KISSNET_OS_INIT;
902
903 initialize_addrinfo();
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_blocking(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(sock, F_GETFL, 0);
915 const auto newflags = state ? flags | O_NONBLOCK : flags ^ O_NONBLOCK;
916 if (fcntl(sock, F_SETFL, newflags) < 0)
917 #endif
918 kissnet_fatal_error("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_broadcast(bool state = true) const
924 {
925 const int broadcast = state ? 1 : 0;
926 if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<const char*>(&broadcast), sizeof(broadcast)) != 0)
927 kissnet_fatal_error("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_delay(bool state = true) const
933 {
934 if constexpr (sock_proto == protocol::tcp)
935 {
936 const int tcpnodelay = state ? 1 : 0;
937 if (setsockopt(sock, SOL_TCP, TCP_NODELAY, reinterpret_cast<const char*>(&tcpnodelay), sizeof(tcpnodelay)) != 0)
938 kissnet_fatal_error("setting socket tcpnodelay mode returned an error");
939 }
940 }
941
942 /// Get socket status
943 socket_status get_status() const
944 {
945 int sockerror = 0;
946 socklen_t errlen = sizeof(sockerror);
947 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&sockerror), &errlen) != 0)
948 kissnet_fatal_error("getting socket error returned an error");
949
950 return sockerror == SOCKET_ERROR ? socket_status::errored : socket_status::valid;
951 }
952
953 ///Bind socket locally using the address and port of the endpoint
954 void bind()
955 {
956 if (syscall_bind(sock, static_cast<SOCKADDR*>(socket_addrinfo->ai_addr), socklen_t(socket_addrinfo->ai_addrlen)) == SOCKET_ERROR)
957 {
958 kissnet_fatal_error("bind() failed\n");
959 }
960 }
961
962 ///(For TCP) connect to the endpoint as client
963 socket_status connect(int64_t timeout = 0)
964 {
965 if constexpr (sock_proto == protocol::tcp) //only TCP is a connected protocol
966 {
967 // try to connect to existing native socket, if any.
968 auto curr_addr = socket_addrinfo;
969 if (connect(curr_addr, timeout, false) != socket_status::valid)
970 {
971 // try to create/connect native socket for one of the other addrinfo, if any
972 for (auto* addr = getaddrinfo_results; addr; addr = addr->ai_next)
973 {
974 if (addr == curr_addr)
975 continue; // already checked
976
977 if (connect(addr, timeout, true) == socket_status::valid)
978 break; // success
979 }
980 }
981
982 if (sock == INVALID_SOCKET)
983 kissnet_fatal_error("unable to create connectable socket!");
984
985 return 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 listen()
1028 {
1029 if constexpr (sock_proto == protocol::tcp)
1030 {
1031 if (syscall_listen(sock, SOMAXCONN) == SOCKET_ERROR)
1032 {
1033 kissnet_fatal_error("listen failed\n");
1034 }
1035 }
1036 }
1037
1038 ///(for TCP) Wait for incoming connection, return socket connect to the client. Blocking.
1039 socket accept()
1040 {
1041 if constexpr (sock_proto != protocol::tcp)
1042 {
1043 return { INVALID_SOCKET, {} };
1044 }
1045
1046 sockaddr_storage socket_address;
1047 SOCKET s;
1048 socklen_t size = sizeof socket_address;
1049
1050 if ((s = syscall_accept(sock, reinterpret_cast<SOCKADDR*>(&socket_address), &size)) == INVALID_SOCKET)
1051 {
1052 const auto error = get_error_code();
1053 switch (error)
1054 {
1055 case EWOULDBLOCK: //if socket "would have blocked" from the call, ignore
1056 case EINTR: //if blocking call got interrupted, ignore;
1057 return {};
1058 }
1059
1060 kissnet_fatal_error("accept() returned an invalid socket\n");
1061 }
1062
1063 return { s, endpoint(reinterpret_cast<SOCKADDR*>(&socket_address)) };
1064 }
1065
1066 void close()
1067 {
1068 if (sock != 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 closesocket(sock);
1085 }
1086
1087 sock = INVALID_SOCKET;
1088 }
1089
1090 void shutdown()
1091 {
1092 if (sock != INVALID_SOCKET)
1093 {
1094 syscall_shutdown(sock);
1095 }
1096 }
1097
1098 ///Close socket on destruction
1099 ~socket()
1100 {
1101 close();
1102
1103 if (getaddrinfo_results)
1104 freeaddrinfo(getaddrinfo_results);
1105 }
1106
1107 ///Select socket with timeout
1108 socket_status select(int fds, int64_t timeout)
1109 {
1110 fd_set fd_read, fd_write, fd_except;;
1111 struct timeval tv;
1112
1113 tv.tv_sec = static_cast<long>(timeout / 1000);
1114 tv.tv_usec = 1000 * static_cast<long>(timeout % 1000);
1115
1116 if (fds & fds_read)
1117 {
1118 FD_ZERO(&fd_read);
1119 FD_SET(sock, &fd_read);
1120 }
1121 if (fds & fds_write)
1122 {
1123 FD_ZERO(&fd_write);
1124 FD_SET(sock, &fd_write);
1125 }
1126 if (fds & fds_except)
1127 {
1128 FD_ZERO(&fd_except);
1129 FD_SET(sock, &fd_except);
1130 }
1131
1132 int ret = syscall_select(static_cast<int>(sock) + 1,
1133 fds & fds_read ? &fd_read : NULL,
1134 fds & fds_write ? &fd_write : NULL,
1135 fds & fds_except ? &fd_except : NULL, &tv);
1136 if (ret == -1)
1137 return socket_status::errored;
1138 else if (ret == 0)
1139 return socket_status::timed_out;
1140 return socket_status::valid;
1141 }
1142
1143 template <size_t buff_size>
1144 bytes_with_status send(const buffer<buff_size>& buff, const size_t length = buff_size)
1145 {
1146 assert(buff_size >= length);
1147 return send(buff.data(), length);
1148 }
1149
1150 ///Send some bytes through the pipe
1151 bytes_with_status send(const std::byte* read_buff, size_t length)
1152 {
1153 auto received_bytes{ 0 };
1154 if constexpr (sock_proto == protocol::tcp)
1155 {
1156 received_bytes = syscall_send(sock, reinterpret_cast<const char*>(read_buff), static_cast<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 == protocol::udp)
1165 {
1166 received_bytes = sendto(sock, reinterpret_cast<const char*>(read_buff), static_cast<buffsize_t>(length), 0, static_cast<SOCKADDR*>(socket_addrinfo->ai_addr), socklen_t(socket_addrinfo->ai_addrlen));
1167 }
1168
1169 if (received_bytes < 0)
1170 {
1171 if (get_error_code() == EWOULDBLOCK)
1172 {
1173 return { 0, socket_status::non_blocking_would_have_blocked };
1174 }
1175
1176 return { 0, socket_status::errored };
1177 }
1178
1179 return { received_bytes, 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_status recv(buffer<buff_size>& write_buff, size_t start_offset = 0)
1185 {
1186 auto received_bytes = 0;
1187 if constexpr (sock_proto == protocol::tcp)
1188 {
1189 received_bytes = syscall_recv(sock, reinterpret_cast<char*>(write_buff.data()) + start_offset, static_cast<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 == protocol::udp)
1198 {
1199 socket_input_socklen = sizeof socket_input;
1200
1201 received_bytes = ::recvfrom(sock, reinterpret_cast<char*>(write_buff.data()) + start_offset, static_cast<buffsize_t>(buff_size - start_offset), 0, reinterpret_cast<sockaddr*>(&socket_input), &socket_input_socklen);
1202 }
1203
1204 if (received_bytes < 0)
1205 {
1206 const auto error = get_error_code();
1207 if (error == EWOULDBLOCK)
1208 return { 0, socket_status::non_blocking_would_have_blocked };
1209 if (error == EAGAIN)
1210 return { 0, socket_status::non_blocking_would_have_blocked };
1211 return { 0, socket_status::errored };
1212 }
1213
1214 if (received_bytes == 0)
1215 {
1216 return { received_bytes, socket_status::cleanly_disconnected };
1217 }
1218
1219 return { size_t(received_bytes), socket_status::valid };
1220 }
1221
1222 ///receive up-to len bytes inside the memory location pointed by buffer
1223 bytes_with_status recv(std::byte* buffer, size_t len, bool wait = true)
1224 {
1225 auto received_bytes = 0;
1226 if constexpr (sock_proto == protocol::tcp)
1227 {
1228 int flags;
1229 if (wait)
1230 flags = MSG_WAITALL;
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_DONTWAIT;
1238 #endif
1239 }
1240 received_bytes = syscall_recv(sock, reinterpret_cast<char*>(buffer), static_cast<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 == protocol::udp)
1254 {
1255 socket_input_socklen = sizeof socket_input;
1256
1257 received_bytes = ::recvfrom(sock, reinterpret_cast<char*>(buffer), static_cast<buffsize_t>(len), 0, reinterpret_cast<sockaddr*>(&socket_input), &socket_input_socklen);
1258 }
1259
1260 if (received_bytes < 0)
1261 {
1262 const auto error = get_error_code();
1263 if (error == EWOULDBLOCK)
1264 return { 0, socket_status::non_blocking_would_have_blocked };
1265 if (error == EAGAIN)
1266 return { 0, socket_status::non_blocking_would_have_blocked };
1267 return { 0, socket_status::errored };
1268 }
1269
1270 if (received_bytes == 0)
1271 {
1272 return { received_bytes, socket_status::cleanly_disconnected };
1273 }
1274
1275 return { size_t(received_bytes), socket_status::valid };
1276 }
1277
1278 ///Return the endpoint where this socket is talking to
1279 endpoint get_bind_loc() const
1280 {
1281 return bind_loc;
1282 }
1283
1284 ///Return an endpoint that originated the data in the last recv
1285 endpoint get_recv_endpoint() const
1286 {
1287 if constexpr (sock_proto == protocol::tcp)
1288 {
1289 return get_bind_loc();
1290 }
1291 if constexpr (sock_proto == protocol::udp)
1292 {
1293 return { (sockaddr*)&socket_input };
1294 }
1295 }
1296
1297 ///Return the number of bytes available inside the socket
1298 size_t bytes_available() const
1299 {
1300 static ioctl_setting size = 0;
1301 const auto status = ioctlsocket(sock, FIONREAD, &size);
1302
1303 if (status < 0)
1304 {
1305 kissnet_fatal_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 protocol get_protocol()
1313 {
1314 return sock_proto;
1315 }
1316 };
1317
1318 ///Alias for socket<protocol::tcp>
1319 using tcp_socket = socket<protocol::tcp>;
1320 ///Alias for socket<protocol::tcp_ssl>
1321 using tcp_ssl_socket = socket<protocol::tcp_ssl>;
1322 ///Alias for socket<protocol::udp>
1323 using udp_socket = socket<protocol::udp>;
1324 }
1325
1326 //cleanup preprocessor macros
1327 #undef KISSNET_OS_SPECIFIC_PAYLOAD_NAME
1328 #undef KISSNET_OS_SPECIFIC
1329 #undef KISSNET_OS_INIT
1330 #undef kissnet_fatal_error
1331
1332 #endif //KISS_NET