join 1.0
lightweight network framework library
Loading...
Searching...
No Matches
socket.hpp
Go to the documentation of this file.
1
25#ifndef JOIN_CORE_SOCKET_HPP
26#define JOIN_CORE_SOCKET_HPP
27
28// libjoin.
29#include <join/protocol.hpp>
30#include <join/endpoint.hpp>
31#include <join/openssl.hpp>
32#include <join/reactor.hpp>
33#include <join/utils.hpp>
34#include <join/error.hpp>
35
36// Libraries.
37#include <openssl/err.h>
38
39// C++.
40#include <type_traits>
41#include <iostream>
42
43// C.
44#include <netinet/tcp.h>
45#include <linux/icmp.h>
46#include <sys/ioctl.h>
47#include <sys/stat.h>
48#include <fnmatch.h>
49#include <cassert>
50#include <fcntl.h>
51#include <poll.h>
52
53namespace join
54{
58 template <class Protocol>
60 {
61 public:
62 using Ptr = std::unique_ptr<BasicSocket<Protocol>>;
63 using Endpoint = typename Protocol::Endpoint;
64
68 enum Mode
69 {
72 };
73
97
109
115 {
116 }
117
123 : _mode (mode)
124 {
125 }
126
131 BasicSocket (const BasicSocket& other) = delete;
132
138 BasicSocket& operator= (const BasicSocket& other) = delete;
139
145 : _state (other._state)
146 , _mode (other._mode)
147 , _handle (other._handle)
148 , _protocol (other._protocol)
149 {
150 other._state = State::Closed;
151 other._mode = Mode::NonBlocking;
152 other._handle = -1;
153 other._protocol = Protocol ();
154 }
155
162 {
163 this->close ();
164
165 this->_state = other._state;
166 this->_mode = other._mode;
167 this->_handle = other._handle;
168 this->_protocol = other._protocol;
169
170 other._state = State::Closed;
171 other._mode = Mode::NonBlocking;
172 other._handle = -1;
173 other._protocol = Protocol ();
174
175 return *this;
176 }
177
181 virtual ~BasicSocket ()
182 {
183 if (this->_handle != -1)
184 {
185 ::close (this->_handle);
186 }
187 }
188
194 virtual int open (const Protocol& protocol = Protocol ()) noexcept
195 {
196 if (this->_state != State::Closed)
197 {
198 lastError = make_error_code (Errc::InUse);
199 return -1;
200 }
201
202 if (this->_mode == Mode::NonBlocking)
203 this->_handle = ::socket (protocol.family (), protocol.type () | SOCK_NONBLOCK, protocol.protocol ());
204 else
205 this->_handle = ::socket (protocol.family (), protocol.type (), protocol.protocol ());
206
207 if (this->_handle == -1)
208 {
209 lastError = std::error_code (errno, std::generic_category ());
210 this->close ();
211 return -1;
212 }
213
215 this->_protocol = protocol;
216
217 return 0;
218 }
219
223 virtual void close () noexcept
224 {
225 if (this->_state != State::Closed)
226 {
227 ::close (this->_handle);
228 this->_state = State::Closed;
229 this->_handle = -1;
230 }
231 }
232
238 virtual int bind (const Endpoint& endpoint) noexcept
239 {
240 if ((this->_state == State::Closed) && (this->open (endpoint.protocol ()) == -1))
241 {
242 return -1;
243 }
244
245 if (endpoint.protocol ().family () == AF_PACKET)
246 {
247 if (reinterpret_cast<const struct sockaddr_ll*> (endpoint.addr ())->sll_ifindex == 0)
248 {
249 lastError = std::make_error_code (std::errc::no_such_device);
250 return -1;
251 }
252 }
253 else if ((endpoint.protocol ().family () == AF_INET6) || (endpoint.protocol ().family () == AF_INET))
254 {
255 this->setOption (Option::ReuseAddr, 1);
256 }
257 else if (endpoint.protocol ().family () == AF_UNIX)
258 {
259 ::unlink (endpoint.device ().c_str ());
260 }
261
262 if (::bind (this->_handle, endpoint.addr (), endpoint.length ()) == -1)
263 {
264 lastError = std::error_code (errno, std::generic_category ());
265 return -1;
266 }
267
268 return 0;
269 }
270
275 virtual int canRead () const noexcept
276 {
277 int available = 0;
278
279 // check if data can be read in the socket internal buffer.
280 if (::ioctl (this->_handle, FIONREAD, &available) == -1)
281 {
282 lastError = std::error_code (errno, std::generic_category ());
283 return -1;
284 }
285
286 return available;
287 }
288
294 virtual bool waitReadyRead (int timeout = 0) const noexcept
295 {
296 return (this->wait (true, false, timeout) == 0);
297 }
298
305 virtual int read (char* data, unsigned long maxSize) noexcept
306 {
307 struct iovec iov;
308 iov.iov_base = data;
309 iov.iov_len = maxSize;
310
311 struct msghdr message;
312 message.msg_name = nullptr;
313 message.msg_namelen = 0;
314 message.msg_iov = &iov;
315 message.msg_iovlen = 1;
316 message.msg_control = nullptr;
317 message.msg_controllen = 0;
318
319 int size = ::recvmsg (this->_handle, &message, 0);
320 if (size < 1)
321 {
322 if (size == -1)
323 {
324 lastError = std::error_code (errno, std::generic_category ());
325 }
326 else
327 {
329 }
330 return -1;
331 }
332
333 return size;
334 }
335
341 virtual bool waitReadyWrite (int timeout = 0) const noexcept
342 {
343 return (this->wait (false, true, timeout) == 0);
344 }
345
352 virtual int write (const char* data, unsigned long maxSize) noexcept
353 {
354 struct iovec iov;
355 iov.iov_base = const_cast<char*> (data);
356 iov.iov_len = maxSize;
357
358 struct msghdr message;
359 message.msg_name = nullptr;
360 message.msg_namelen = 0;
361 message.msg_iov = &iov;
362 message.msg_iovlen = 1;
363 message.msg_control = nullptr;
364 message.msg_controllen = 0;
365
366 int result = ::sendmsg (this->_handle, &message, 0);
367 if (result == -1)
368 {
369 lastError = std::error_code (errno, std::generic_category ());
370 return -1;
371 }
372
373 return result;
374 }
375
380 void setMode (Mode mode) noexcept
381 {
382 this->_mode = mode;
383
384 if (this->_state != State::Closed)
385 {
386 int flags = ::fcntl (this->_handle, F_GETFL, 0);
387
388 if (this->_mode == Mode::NonBlocking)
389 {
390 flags = flags | O_NONBLOCK;
391 }
392 else
393 {
394 flags = flags & ~O_NONBLOCK;
395 }
396
397 ::fcntl (this->_handle, F_SETFL, flags);
398 }
399 }
400
407 virtual int setOption (Option option, int value) noexcept
408 {
409 int optlevel, optname;
410
411 switch (option)
412 {
414 optlevel = SOL_SOCKET;
415 optname = SO_KEEPALIVE;
416 break;
417
419 optlevel = SOL_SOCKET;
420 optname = SO_SNDBUF;
421 break;
422
424 optlevel = SOL_SOCKET;
425 optname = SO_RCVBUF;
426 break;
427
429 optlevel = SOL_SOCKET;
430 optname = SO_TIMESTAMP;
431 break;
432
434 optlevel = SOL_SOCKET;
435 optname = SO_REUSEADDR;
436 break;
437
439 optlevel = SOL_SOCKET;
440 optname = SO_REUSEPORT;
441 break;
442
444 optlevel = SOL_SOCKET;
445 optname = SO_BROADCAST;
446 break;
447
448 case Option::AuxData:
449 optlevel = SOL_PACKET;
450 optname = PACKET_AUXDATA;
451 break;
452
453 default:
455 return -1;
456 }
457
458 int result = ::setsockopt (this->_handle, optlevel, optname, &value, sizeof (value));
459 if (result == -1)
460 {
461 lastError = std::error_code (errno, std::generic_category ());
462 return -1;
463 }
464
465 return 0;
466 }
467
473 {
474 struct sockaddr_storage sa;
475 socklen_t sa_len = sizeof (struct sockaddr_storage);
476
477 if (::getsockname (this->_handle, reinterpret_cast<struct sockaddr*> (&sa), &sa_len) == -1)
478 {
479 return {};
480 }
481
482 return Endpoint (reinterpret_cast<struct sockaddr*> (&sa), sa_len);
483 }
484
489 bool opened () const noexcept
490 {
491 return (this->_state != State::Closed);
492 }
493
498 virtual bool encrypted () const noexcept
499 {
500 return false;
501 }
502
507 int family () const noexcept
508 {
509 return this->_protocol.family ();
510 }
511
516 int type () const noexcept
517 {
518 return this->_protocol.type ();
519 }
520
525 int protocol () const noexcept
526 {
527 return this->_protocol.protocol ();
528 }
529
534 int handle () const noexcept
535 {
536 return this->_handle;
537 }
538
546 static uint16_t checksum (const uint16_t* data, size_t len, uint16_t current = 0)
547 {
548 uint32_t sum = current;
549
550 while (len > 1)
551 {
552 sum += *data++;
553 len -= 2;
554 }
555
556 if (len == 1)
557 {
558#if __BYTE_ORDER == __LITTLE_ENDIAN
559 sum += *reinterpret_cast<const uint8_t*> (data);
560#else
561 sum += *reinterpret_cast<const uint8_t*> (data) << 8;
562#endif
563 }
564
565 sum = (sum >> 16) + (sum & 0xffff);
566 sum += (sum >> 16);
567
568 return static_cast<uint16_t> (~sum);
569 }
570
571 protected:
579 int wait (bool wantRead, bool wantWrite, int timeout) const noexcept
580 {
581 struct pollfd handle = {.fd = this->_handle, .events = 0, .revents = 0};
582
583 if (wantRead)
584 {
585 handle.events |= POLLIN;
586 }
587
588 if (wantWrite)
589 {
590 handle.events |= POLLOUT;
591 }
592
593 int nset = (handle.fd > -1) ? ::poll (&handle, 1, timeout) : -1;
594 if (nset != 1)
595 {
596 if (nset == -1)
597 {
598 if (handle.fd == -1)
599 {
600 errno = EBADF;
601 }
602 lastError = std::error_code (errno, std::generic_category ());
603 }
604 else
605 {
606 lastError = make_error_code (Errc::TimedOut);
607 }
608
609 return -1;
610 }
611
612 return 0;
613 }
614
617
620
622 int _handle = -1;
623
625 Protocol _protocol;
626 };
627
634 template <class Protocol>
635 constexpr bool operator< (const BasicSocket<Protocol>& a, const BasicSocket<Protocol>& b) noexcept
636 {
637 return a.handle () < b.handle ();
638 }
639
643 template <class Protocol>
644 class BasicDatagramSocket : public BasicSocket<Protocol>
645 {
646 public:
647 using Ptr = std::unique_ptr<BasicDatagramSocket<Protocol>>;
651 using Endpoint = typename Protocol::Endpoint;
652
660
665 BasicDatagramSocket (Mode mode, int ttl = 60)
666 : BasicSocket<Protocol> (mode)
667 , _ttl (ttl)
668 {
669 }
670
676
683
689 : BasicSocket<Protocol> (std::move (other))
690 , _remote (std::move (other._remote))
691 , _ttl (other._ttl)
692 {
693 other._ttl = 60;
694 }
695
702 {
703 BasicSocket<Protocol>::operator= (std::move (other));
704
705 _remote = std::move (other._remote);
706 _ttl = other._ttl;
707
708 other._ttl = 60;
709
710 return *this;
711 }
712
716 virtual ~BasicDatagramSocket () = default;
717
723 virtual int open (const Protocol& protocol = Protocol ()) noexcept override
724 {
726 if (result == -1)
727 {
728 return -1;
729 }
730
731 int off = 0;
732
733 if ((protocol.protocol () == IPPROTO_UDP) || (protocol.protocol () == IPPROTO_TCP))
734 {
735 if ((protocol.family () == AF_INET6) &&
736 (::setsockopt (this->_handle, IPPROTO_IPV6, IPV6_V6ONLY, &off, sizeof (off)) == -1))
737 {
738 lastError = std::error_code (errno, std::generic_category ());
739 this->close ();
740 return -1;
741 }
742 }
743
744 if ((protocol.protocol () == IPPROTO_ICMPV6) || (protocol.protocol () == IPPROTO_ICMP))
745 {
746 if ((protocol.family () == AF_INET) &&
747 (::setsockopt (this->_handle, IPPROTO_IP, IP_HDRINCL, &off, sizeof (off)) == -1))
748 {
749 lastError = std::error_code (errno, std::generic_category ());
750 this->close ();
751 return -1;
752 }
753
754 this->setOption (Option::MulticastTtl, this->_ttl);
755 this->setOption (Option::Ttl, this->_ttl);
756 }
757
758 return 0;
759 }
760
766 virtual int bindToDevice (const std::string& device) noexcept
767 {
768 if (this->_state == State::Closed)
769 {
771 return -1;
772 }
773
774 if (this->_state == State::Connected)
775 {
776 lastError = make_error_code (Errc::InUse);
777 return -1;
778 }
779
780 if ((this->_protocol.family () == AF_INET6) || (this->_protocol.family () == AF_INET))
781 {
782 this->setOption (Option::ReuseAddr, 1);
783 }
784
785 int result = setsockopt (this->_handle, SOL_SOCKET, SO_BINDTODEVICE, device.c_str (), device.size ());
786 if (result == -1)
787 {
788 lastError = std::error_code (errno, std::generic_category ());
789 return -1;
790 }
791
792 return 0;
793 }
794
800 virtual int connect (const Endpoint& endpoint)
801 {
802 if ((this->_state != State::Closed) && (this->_state != State::Disconnected))
803 {
804 lastError = make_error_code (Errc::InUse);
805 return -1;
806 }
807
808 if ((this->_state == State::Closed) && (this->open (endpoint.protocol ()) == -1))
809 {
810 return -1;
811 }
812
813 int result = ::connect (this->_handle, endpoint.addr (), endpoint.length ());
814
815 this->_state = State::Connecting;
816 this->_remote = endpoint;
817
818 if (result == -1)
819 {
820 lastError = std::error_code (errno, std::generic_category ());
821 if (lastError != std::errc::operation_in_progress)
822 {
823 this->close ();
824 }
825 return -1;
826 }
827
828 this->_state = State::Connected;
829
830 return 0;
831 }
832
837 virtual int disconnect ()
838 {
839 if (this->_state == State::Connected)
840 {
841 struct sockaddr_storage nullAddr;
842 ::memset (&nullAddr, 0, sizeof (nullAddr));
843
844 nullAddr.ss_family = AF_UNSPEC;
845
846 int result = ::connect (this->_handle, reinterpret_cast<struct sockaddr*> (&nullAddr),
847 sizeof (struct sockaddr_storage));
848 if (result == -1)
849 {
850 if (errno != EAFNOSUPPORT)
851 {
852 lastError = std::error_code (errno, std::generic_category ());
853 return -1;
854 }
855 }
856
857 this->_state = State::Disconnected;
858 this->_remote = {};
859 }
860
861 return 0;
862 }
863
867 virtual void close () noexcept override
868 {
870 this->_remote = {};
871 }
872
879 virtual int read (char* data, unsigned long maxSize) noexcept override
880 {
881 return BasicSocket<Protocol>::read (data, maxSize);
882 }
883
891 virtual int readFrom (char* data, unsigned long maxSize, Endpoint* endpoint = nullptr) noexcept
892 {
893 struct sockaddr_storage sa;
894 socklen_t sa_len = sizeof (struct sockaddr_storage);
895
896 int size = ::recvfrom (this->_handle, data, maxSize, 0, reinterpret_cast<struct sockaddr*> (&sa), &sa_len);
897 if (size < 1)
898 {
899 if (size == -1)
900 {
901 lastError = std::error_code (errno, std::generic_category ());
902 }
903 else
904 {
906 this->_state = State::Disconnected;
907 }
908
909 return -1;
910 }
911
912 if (endpoint != nullptr)
913 {
914 *endpoint = Endpoint (reinterpret_cast<struct sockaddr*> (&sa), sa_len);
915 }
916
917 return size;
918 }
919
926 virtual int write (const char* data, unsigned long maxSize) noexcept override
927 {
928 return BasicSocket<Protocol>::write (data, maxSize);
929 }
930
938 virtual int writeTo (const char* data, unsigned long maxSize, const Endpoint& endpoint) noexcept
939 {
940 if ((this->_state == State::Closed) && (this->open (endpoint.protocol ()) == -1))
941 {
942 return -1;
943 }
944
945 int result = ::sendto (this->_handle, data, maxSize, 0, endpoint.addr (), endpoint.length ());
946 if (result < 0)
947 {
948 lastError = std::error_code (errno, std::generic_category ());
949 return -1;
950 }
951
952 return result;
953 }
954
961 virtual int setOption (Option option, int value) noexcept override
962 {
963 if (this->_state == State::Closed)
964 {
966 return -1;
967 }
968
969 int optlevel, optname;
970
971 switch (option)
972 {
973 case Option::Ttl:
974 if (this->family () == AF_INET6)
975 {
976 optlevel = IPPROTO_IPV6;
977 optname = IPV6_UNICAST_HOPS;
978 }
979 else
980 {
981 optlevel = IPPROTO_IP;
982 optname = IP_TTL;
983 }
984 break;
985
986 case Option::MulticastLoop:
987 if (this->family () == AF_INET6)
988 {
989 optlevel = IPPROTO_IPV6;
990 optname = IPV6_MULTICAST_LOOP;
991 }
992 else
993 {
994 optlevel = IPPROTO_IP;
995 optname = IP_MULTICAST_LOOP;
996 }
997 break;
998
999 case Option::MulticastTtl:
1000 if (this->family () == AF_INET6)
1001 {
1002 optlevel = IPPROTO_IPV6;
1003 optname = IPV6_MULTICAST_HOPS;
1004 }
1005 else
1006 {
1007 optlevel = IPPROTO_IP;
1008 optname = IP_MULTICAST_TTL;
1009 }
1010 break;
1011
1012 case Option::PathMtuDiscover:
1013 if (this->family () == AF_INET6)
1014 {
1015 optlevel = IPPROTO_IPV6;
1016 optname = IPV6_MTU_DISCOVER;
1017 }
1018 else
1019 {
1020 optlevel = IPPROTO_IP;
1021 optname = IP_MTU_DISCOVER;
1022 }
1023 break;
1024
1025 case Option::RcvError:
1026 if (this->family () == AF_INET6)
1027 {
1028 optlevel = IPPROTO_IPV6;
1029 optname = IPV6_RECVERR;
1030 }
1031 else
1032 {
1033 optlevel = IPPROTO_IP;
1034 optname = IP_RECVERR;
1035 }
1036 break;
1037
1038 default:
1039 return BasicSocket<Protocol>::setOption (option, value);
1040 }
1041
1042 int result = ::setsockopt (this->_handle, optlevel, optname, &value, sizeof (value));
1043 if (result == -1)
1044 {
1045 lastError = std::error_code (errno, std::generic_category ());
1046 return -1;
1047 }
1048
1049 return 0;
1050 }
1051
1056 const Endpoint& remoteEndpoint () const
1057 {
1058 return this->_remote;
1059 }
1060
1065 virtual bool connected () noexcept
1066 {
1067 return (this->_state == State::Connected);
1068 }
1069
1074 int mtu () const
1075 {
1076 if (this->_state == State::Closed)
1077 {
1079 return -1;
1080 }
1081
1082 int result = -1, value = -1;
1083 socklen_t valueLen = sizeof (value);
1084
1085 if (this->_protocol.family () == AF_INET6)
1086 {
1087 result = ::getsockopt (this->_handle, IPPROTO_IPV6, IPV6_MTU, &value, &valueLen);
1088 }
1089 else if (this->_protocol.family () == AF_INET)
1090 {
1091 result = ::getsockopt (this->_handle, IPPROTO_IP, IP_MTU, &value, &valueLen);
1092 }
1093 else
1094 {
1096 return -1;
1097 }
1098
1099 if (result == -1)
1100 {
1101 lastError = std::error_code (errno, std::generic_category ());
1102 return -1;
1103 }
1104
1105 return value;
1106 }
1107
1112 int ttl () const
1113 {
1114 return this->_ttl;
1115 }
1116
1117 protected:
1120
1122 int _ttl = 60;
1123 };
1124
1131 template <class Protocol>
1133 {
1134 return a.handle () < b.handle ();
1135 }
1136
1140 template <class Protocol>
1142 {
1143 public:
1144 using Ptr = std::unique_ptr<BasicStreamSocket<Protocol>>;
1148 using Endpoint = typename Protocol::Endpoint;
1149
1157
1163 : BasicDatagramSocket<Protocol> (mode)
1164 {
1165 }
1166
1171 BasicStreamSocket (const BasicStreamSocket& other) = delete;
1172
1179
1185 : BasicDatagramSocket<Protocol> (std::move (other))
1186 {
1187 }
1188
1195 {
1197
1198 return *this;
1199 }
1200
1204 virtual ~BasicStreamSocket () = default;
1205
1211 virtual bool waitConnected (int timeout = 0)
1212 {
1213 if (this->_state != State::Connected)
1214 {
1215 if (this->_state != State::Connecting)
1216 {
1218 return false;
1219 }
1220
1221 if (!this->waitReadyWrite (timeout))
1222 {
1223 return false;
1224 }
1225
1226 return connected ();
1227 }
1228
1229 return true;
1230 }
1231
1236 virtual int disconnect () override
1237 {
1238 if (this->_state == State::Connected)
1239 {
1240 ::shutdown (this->_handle, SHUT_WR);
1241 this->_state = State::Disconnecting;
1242 }
1243
1244 if (this->_state == State::Disconnecting)
1245 {
1246 char buffer[4096];
1247 // closing before reading can make the client
1248 // not see all of our output.
1249 // we have to do a "lingering close"
1250 for (;;)
1251 {
1252 int result = this->read (buffer, sizeof (buffer));
1253 if (result <= 0)
1254 {
1255 if ((result == -1) && (lastError == Errc::TemporaryError))
1256 {
1257 return -1;
1258 }
1259
1260 break;
1261 }
1262 }
1263
1264 ::shutdown (this->_handle, SHUT_RD);
1265 this->_state = State::Disconnected;
1266 }
1267
1268 this->close ();
1269
1270 return 0;
1271 }
1272
1278 virtual bool waitDisconnected (int timeout = 0)
1279 {
1280 if ((this->_state != State::Disconnected) && (this->_state != State::Closed))
1281 {
1282 if (this->_state != State::Disconnecting)
1283 {
1285 return false;
1286 }
1287
1288 auto start = std::chrono::steady_clock::now ();
1289 int elapsed = 0;
1290
1291 while ((lastError == Errc::TemporaryError) && (elapsed <= timeout))
1292 {
1293 if (!this->waitReadyRead (timeout - elapsed))
1294 {
1295 return false;
1296 }
1297
1298 if (this->disconnect () == 0)
1299 {
1300 return true;
1301 }
1302
1303 if (timeout)
1304 {
1305 elapsed = std::chrono::duration_cast<std::chrono::milliseconds> (
1306 std::chrono::steady_clock::now () - start)
1307 .count ();
1308 }
1309 }
1310
1311 return false;
1312 }
1313
1314 return true;
1315 }
1316
1324 int readExactly (char* data, unsigned long size, int timeout = 0)
1325 {
1326 unsigned long numRead = 0;
1327
1328 while (numRead < size)
1329 {
1330 int result = this->read (data + numRead, size - numRead);
1331 if (result == -1)
1332 {
1333 if (lastError == Errc::TemporaryError)
1334 {
1335 if (this->waitReadyRead (timeout))
1336 continue;
1337 }
1338
1339 return -1;
1340 }
1341
1342 numRead += result;
1343 }
1344
1345 return 0;
1346 }
1347
1355 int readExactly (std::string& data, unsigned long size, int timeout = 0)
1356 {
1357 data.resize (size);
1358 return readExactly (&data[0], size, timeout);
1359 }
1360
1368 int writeExactly (const char* data, unsigned long size, int timeout = 0)
1369 {
1370 unsigned long numWrite = 0;
1371
1372 while (numWrite < size)
1373 {
1374 int result = this->write (data + numWrite, size - numWrite);
1375 if (result == -1)
1376 {
1377 if (lastError == Errc::TemporaryError)
1378 {
1379 if (this->waitReadyWrite (timeout))
1380 continue;
1381 }
1382
1383 return -1;
1384 }
1385
1386 numWrite += result;
1387 }
1388
1389 return 0;
1390 }
1391
1398 virtual int setOption (Option option, int value) noexcept override
1399 {
1400 if (this->_state == State::Closed)
1401 {
1403 return -1;
1404 }
1405
1406 int optlevel, optname;
1407
1408 switch (option)
1409 {
1410 case Option::NoDelay:
1411 optlevel = IPPROTO_TCP;
1412 optname = TCP_NODELAY;
1413 break;
1414
1415 case Option::KeepIdle:
1416 optlevel = IPPROTO_TCP;
1417 optname = TCP_KEEPIDLE;
1418 break;
1419
1420 case Option::KeepIntvl:
1421 optlevel = IPPROTO_TCP;
1422 optname = TCP_KEEPINTVL;
1423 break;
1424
1425 case Option::KeepCount:
1426 optlevel = IPPROTO_TCP;
1427 optname = TCP_KEEPCNT;
1428 break;
1429
1430 default:
1431 return BasicDatagramSocket<Protocol>::setOption (option, value);
1432 }
1433
1434 int result = ::setsockopt (this->_handle, optlevel, optname, &value, sizeof (value));
1435 if (result == -1)
1436 {
1437 lastError = std::error_code (errno, std::generic_category ());
1438 return -1;
1439 }
1440
1441 return 0;
1442 }
1443
1448 virtual bool connecting () const noexcept
1449 {
1450 return (this->_state == State::Connecting);
1451 }
1452
1457 virtual bool connected () noexcept override
1458 {
1459 if (this->_state == State::Connected)
1460 {
1461 return true;
1462 }
1463 else if (this->_state != State::Connecting)
1464 {
1465 return false;
1466 }
1467
1468 int optval;
1469 socklen_t optlen = sizeof (optval);
1470
1471 int result = ::getsockopt (this->_handle, SOL_SOCKET, SO_ERROR, &optval, &optlen);
1472 if ((result == -1) || (optval != 0))
1473 {
1474 return false;
1475 }
1476
1477 this->_state = State::Connected;
1478
1479 return true;
1480 }
1481
1483 friend class BasicStreamAcceptor<Protocol>;
1484 };
1485
1492 template <class Protocol>
1493 constexpr bool operator< (const BasicStreamSocket<Protocol>& a, const BasicStreamSocket<Protocol>& b) noexcept
1494 {
1495 return a.handle () < b.handle ();
1496 }
1497
1501 enum class TlsErrc
1502 {
1505 };
1506
1510 class TlsCategory : public std::error_category
1511 {
1512 public:
1517 virtual const char* name () const noexcept;
1518
1524 virtual std::string message (int code) const;
1525 };
1526
1531 const std::error_category& getTlsCategory ();
1532
1538 std::error_code make_error_code (TlsErrc code);
1539
1545 std::error_condition make_error_condition (TlsErrc code);
1546
1550 template <class Protocol>
1551 class BasicTlsSocket : public BasicStreamSocket<Protocol>
1552 {
1553 public:
1554 using Ptr = std::unique_ptr<BasicTlsSocket<Protocol>>;
1558 using Endpoint = typename Protocol::Endpoint;
1559
1565 {
1566 }
1567
1573 : BasicStreamSocket<Protocol> (mode)
1574 , _tlsContext (SSL_CTX_new (TLS_client_method ()))
1575 {
1576 // enable the OpenSSL bug workaround options.
1577 SSL_CTX_set_options (this->_tlsContext.get (), SSL_OP_ALL);
1578
1579 // disallow compression.
1580 SSL_CTX_set_options (this->_tlsContext.get (), SSL_OP_NO_COMPRESSION);
1581
1582 // disallow usage of SSLv2, SSLv3, TLSv1 and TLSv1.1 which are considered insecure.
1583 SSL_CTX_set_options (this->_tlsContext.get (),
1584 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1);
1585
1586 // setup write mode.
1587 SSL_CTX_set_mode (this->_tlsContext.get (),
1588 SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1589
1590 // automatically renegotiates.
1591 SSL_CTX_set_mode (this->_tlsContext.get (), SSL_MODE_AUTO_RETRY);
1592
1593 // set session cache mode to client by default.
1594 SSL_CTX_set_session_cache_mode (this->_tlsContext.get (), SSL_SESS_CACHE_CLIENT);
1595
1596 // no verification by default.
1597 SSL_CTX_set_verify (this->_tlsContext.get (), SSL_VERIFY_NONE, nullptr);
1598
1599 // set default TLSv1.2 and below cipher suites.
1600 SSL_CTX_set_cipher_list (this->_tlsContext.get (), join::defaultCipher.c_str ());
1601
1602 // set default TLSv1.3 cipher suites.
1603 SSL_CTX_set_ciphersuites (this->_tlsContext.get (), join::defaultCipher_1_3.c_str ());
1604 }
1605
1611 : BasicTlsSocket (Mode::NonBlocking, std::move (tlsContext))
1612 {
1613 }
1614
1621 : BasicStreamSocket<Protocol> (mode)
1622 , _tlsContext (std::move (tlsContext))
1623 {
1624 if (this->_tlsContext == nullptr)
1625 {
1626 throw std::invalid_argument ("OpenSSL context is invalid");
1627 }
1628 }
1629
1634 BasicTlsSocket (const BasicTlsSocket& other) = delete;
1635
1642
1648 : BasicStreamSocket<Protocol> (std::move (other))
1649 , _tlsContext (std::move (other._tlsContext))
1650 , _tlsHandle (std::move (other._tlsHandle))
1651 , _tlsState (other._tlsState)
1652 {
1653 if (this->_tlsHandle)
1654 {
1655 SSL_set_app_data (this->_tlsHandle.get (), this);
1656 }
1657
1658 other._tlsState = TlsState::NonEncrypted;
1659 }
1660
1667 {
1668 BasicStreamSocket<Protocol>::operator= (std::move (other));
1669
1670 this->_tlsContext = std::move (other._tlsContext);
1671 this->_tlsHandle = std::move (other._tlsHandle);
1672 this->_tlsState = other._tlsState;
1673
1674 if (this->_tlsHandle)
1675 {
1676 SSL_set_app_data (this->_tlsHandle.get (), this);
1677 }
1678
1679 other._tlsState = TlsState::NonEncrypted;
1680
1681 return *this;
1682 }
1683
1687 virtual ~BasicTlsSocket () = default;
1688
1694 int connectEncrypted (const Endpoint& endpoint)
1695 {
1696 if (BasicStreamSocket<Protocol>::connect (endpoint) == -1)
1697 {
1698 return -1;
1699 }
1700
1701 if (this->startEncryption () == -1)
1702 {
1703 this->close ();
1704 return -1;
1705 }
1706
1707 return 0;
1708 }
1709
1715 {
1716 if (this->encrypted () == false)
1717 {
1718 this->_tlsHandle.reset (SSL_new (this->_tlsContext.get ()));
1719 if (this->_tlsHandle == nullptr)
1720 {
1721 lastError = make_error_code (Errc::OutOfMemory);
1722 return -1;
1723 }
1724
1725 if (SSL_set_fd (this->_tlsHandle.get (), this->_handle) != 1)
1726 {
1727 lastError = make_error_code (Errc::InvalidParam);
1728 this->_tlsHandle.reset ();
1729 return -1;
1730 }
1731
1732 if (SSL_is_server (this->_tlsHandle.get ()) == 0)
1733 {
1734 if (!this->_remote.hostname ().empty () &&
1735 (SSL_set_tlsext_host_name (this->_tlsHandle.get (), this->_remote.hostname ().c_str ()) != 1))
1736 {
1737 lastError = make_error_code (Errc::InvalidParam);
1738 this->_tlsHandle.reset ();
1739 return -1;
1740 }
1741
1742 SSL_set_connect_state (this->_tlsHandle.get ());
1743 }
1744 else
1745 {
1746 SSL_set_accept_state (this->_tlsHandle.get ());
1747 }
1748
1749 SSL_set_app_data (this->_tlsHandle.get (), this);
1750
1751#ifdef DEBUG
1752 SSL_set_info_callback (this->_tlsHandle.get (), infoWrapper);
1753#endif
1754
1755 return startHandshake ();
1756 }
1757
1758 return 0;
1759 }
1760
1766 bool waitEncrypted (int timeout = 0)
1767 {
1768 if (this->encrypted () == false)
1769 {
1770 if (this->_state == State::Connecting)
1771 {
1772 if (!this->waitConnected (timeout))
1773 {
1774 return false;
1775 }
1776
1777 if (this->startEncryption () == 0)
1778 {
1779 return true;
1780 }
1781 }
1782
1783 while ((lastError == Errc::TemporaryError) &&
1784 (SSL_want_read (this->_tlsHandle.get ()) || SSL_want_write (this->_tlsHandle.get ())))
1785 {
1786 if (this->wait (SSL_want_read (this->_tlsHandle.get ()), SSL_want_write (this->_tlsHandle.get ()),
1787 timeout) == -1)
1788 {
1789 return false;
1790 }
1791
1792 if (this->startHandshake () == 0)
1793 {
1794 return true;
1795 }
1796 }
1797
1798 return false;
1799 }
1800
1801 return true;
1802 }
1803
1808 virtual int disconnect () override
1809 {
1810 if (this->encrypted ())
1811 {
1812 // check if the close_notify alert was already sent.
1813 if ((SSL_get_shutdown (this->_tlsHandle.get ()) & SSL_SENT_SHUTDOWN) == false)
1814 {
1815 // send the close_notify alert to the peer.
1816 int result = SSL_shutdown (this->_tlsHandle.get ());
1817 if (result < 0)
1818 {
1819 // shutdown was not successful.
1820 switch (SSL_get_error (this->_tlsHandle.get (), result))
1821 {
1822 case SSL_ERROR_WANT_READ:
1823 case SSL_ERROR_WANT_WRITE:
1824 // SSL_shutdown want read or want write.
1826 break;
1827 case SSL_ERROR_SYSCALL:
1828 // an error occurred at the socket level.
1829 switch (errno)
1830 {
1831 case 0:
1832 case ECONNRESET:
1833 case EPIPE:
1836 this->_state = State::Disconnected;
1837 break;
1838 default:
1839 lastError = std::error_code (errno, std::generic_category ());
1840 break;
1841 }
1842 break;
1843 default:
1844 // SSL protocol error.
1845#ifdef DEBUG
1846 std::cout << ERR_reason_error_string (ERR_get_error ()) << std::endl;
1847#endif
1849 break;
1850 }
1851
1852 return -1;
1853 }
1854 else if (result == 1)
1855 {
1856 // shutdown was successfully completed.
1857 // close_notify alert was sent and the peer's close_notify alert was received.
1859 }
1860 else
1861 {
1862 // shutdown is not yet finished.
1863 // the close_notify was sent but the peer did not send it back yet.
1864 // SSL_read must be called to do a bidirectional shutdown.
1865 }
1866 }
1867 }
1868
1870 }
1871
1875 virtual void close () noexcept override
1876 {
1879 this->_tlsHandle.reset ();
1880 }
1881
1887 virtual bool waitReadyRead (int timeout = 0) const noexcept override
1888 {
1889 if (this->encrypted () &&
1890 (SSL_want_read (this->_tlsHandle.get ()) || SSL_want_write (this->_tlsHandle.get ())))
1891 {
1892 return (this->wait (SSL_want_read (this->_tlsHandle.get ()), SSL_want_write (this->_tlsHandle.get ()),
1893 timeout) == 0);
1894 }
1895
1897 }
1898
1903 virtual int canRead () const noexcept override
1904 {
1905 if (this->encrypted ())
1906 {
1907 return SSL_pending (this->_tlsHandle.get ());
1908 }
1909
1911 }
1912
1919 virtual int read (char* data, unsigned long maxSize) noexcept override
1920 {
1921 if (this->encrypted ())
1922 {
1923 // read data.
1924 int result = SSL_read (this->_tlsHandle.get (), data, int (maxSize));
1925 if (result < 1)
1926 {
1927 switch (SSL_get_error (this->_tlsHandle.get (), result))
1928 {
1929 case SSL_ERROR_WANT_READ:
1930 case SSL_ERROR_WANT_WRITE:
1931 case SSL_ERROR_WANT_X509_LOOKUP:
1932 // SSL_read want read, want write or want lookup.
1934 break;
1935 case SSL_ERROR_ZERO_RETURN:
1936 // a close notify alert was received.
1937 // we have to answer by sending a close notify alert too.
1939 if (SSL_get_shutdown (this->_tlsHandle.get ()) & SSL_SENT_SHUTDOWN)
1940 {
1942 }
1943 break;
1944 case SSL_ERROR_SYSCALL:
1945 // an error occurred at the socket level.
1946 switch (errno)
1947 {
1948 case 0:
1949 case ECONNRESET:
1950 case EPIPE:
1953 this->_state = State::Disconnected;
1954 break;
1955 default:
1956 lastError = std::error_code (errno, std::generic_category ());
1957 break;
1958 }
1959 break;
1960 default:
1961 // SSL protocol error.
1962#ifdef DEBUG
1963 std::cout << ERR_reason_error_string (ERR_get_error ()) << std::endl;
1964#endif
1966 break;
1967 }
1968
1969 return -1;
1970 }
1971
1972 return result;
1973 }
1974
1975 return BasicStreamSocket<Protocol>::read (data, maxSize);
1976 }
1977
1983 virtual bool waitReadyWrite (int timeout = 0) const noexcept override
1984 {
1985 if (this->encrypted () &&
1986 (SSL_want_read (this->_tlsHandle.get ()) || SSL_want_write (this->_tlsHandle.get ())))
1987 {
1988 return (this->wait (SSL_want_read (this->_tlsHandle.get ()), SSL_want_write (this->_tlsHandle.get ()),
1989 timeout) == 0);
1990 }
1991
1993 }
1994
2001 virtual int write (const char* data, unsigned long maxSize) noexcept override
2002 {
2003 if (this->encrypted ())
2004 {
2005 // write data.
2006 int result = SSL_write (this->_tlsHandle.get (), data, int (maxSize));
2007 if (result < 1)
2008 {
2009 switch (SSL_get_error (this->_tlsHandle.get (), result))
2010 {
2011 case SSL_ERROR_WANT_READ:
2012 case SSL_ERROR_WANT_WRITE:
2013 case SSL_ERROR_WANT_X509_LOOKUP:
2014 // SSL_write want read, want write or want lookup.
2016 break;
2017 case SSL_ERROR_ZERO_RETURN:
2018 // a close notify alert was received.
2019 // we have to answer by sending a close notify alert too.
2021 if (SSL_get_shutdown (this->_tlsHandle.get ()) & SSL_SENT_SHUTDOWN)
2022 {
2024 }
2025 break;
2026 case SSL_ERROR_SYSCALL:
2027 // an error occurred at the socket level.
2028 switch (errno)
2029 {
2030 case 0:
2031 case ECONNRESET:
2032 case EPIPE:
2035 this->_state = State::Disconnected;
2036 break;
2037 default:
2038 lastError = std::error_code (errno, std::generic_category ());
2039 break;
2040 }
2041 break;
2042 default:
2043 // SSL protocol error.
2044#ifdef DEBUG
2045 std::cout << ERR_reason_error_string (ERR_get_error ()) << std::endl;
2046#endif
2048 break;
2049 }
2050
2051 return -1;
2052 }
2053
2054 return result;
2055 }
2056
2057 return BasicStreamSocket<Protocol>::write (data, maxSize);
2058 }
2059
2064 virtual bool encrypted () const noexcept override
2065 {
2066 return (this->_tlsState == TlsState::Encrypted);
2067 }
2068
2075 int setCertificate (const std::string& cert, const std::string& key = "")
2076 {
2077 if (((this->_tlsHandle)
2078 ? SSL_use_certificate_file (this->_tlsHandle.get (), cert.c_str (), SSL_FILETYPE_PEM)
2079 : SSL_CTX_use_certificate_file (this->_tlsContext.get (), cert.c_str (), SSL_FILETYPE_PEM)) == 0)
2080 {
2081 lastError = make_error_code (Errc::InvalidParam);
2082 return -1;
2083 }
2084
2085 if (key.size ())
2086 {
2087 if (((this->_tlsHandle)
2088 ? SSL_use_PrivateKey_file (this->_tlsHandle.get (), key.c_str (), SSL_FILETYPE_PEM)
2089 : SSL_CTX_use_PrivateKey_file (this->_tlsContext.get (), key.c_str (), SSL_FILETYPE_PEM)) == 0)
2090 {
2091 lastError = make_error_code (Errc::InvalidParam);
2092 return -1;
2093 }
2094 }
2095
2096 if (((this->_tlsHandle) ? SSL_check_private_key (this->_tlsHandle.get ())
2097 : SSL_CTX_check_private_key (this->_tlsContext.get ())) == 0)
2098 {
2099 lastError = make_error_code (Errc::InvalidParam);
2100 return -1;
2101 }
2102
2103 return 0;
2104 }
2105
2111 int setCaPath (const std::string& caPath)
2112 {
2113 struct stat st;
2114 if (stat (caPath.c_str (), &st) != 0 || !S_ISDIR (st.st_mode) ||
2115 SSL_CTX_load_verify_locations (this->_tlsContext.get (), nullptr, caPath.c_str ()) == 0)
2116 {
2117 lastError = make_error_code (Errc::InvalidParam);
2118 return -1;
2119 }
2120
2121 return 0;
2122 }
2123
2129 int setCaFile (const std::string& caFile)
2130 {
2131 struct stat st;
2132 if (stat (caFile.c_str (), &st) != 0 || !S_ISREG (st.st_mode) ||
2133 SSL_CTX_load_verify_locations (this->_tlsContext.get (), caFile.c_str (), nullptr) == 0)
2134 {
2135 lastError = make_error_code (Errc::InvalidParam);
2136 return -1;
2137 }
2138
2139 return 0;
2140 }
2141
2147 void setVerify (bool verify, int depth = -1)
2148 {
2149 if (verify == true)
2150 {
2151 SSL_CTX_set_verify (this->_tlsContext.get (), SSL_VERIFY_PEER, verifyWrapper);
2152 SSL_CTX_set_verify_depth (this->_tlsContext.get (), depth);
2153 }
2154 else
2155 {
2156 SSL_CTX_set_verify (this->_tlsContext.get (), SSL_VERIFY_NONE, nullptr);
2157 }
2158 }
2159
2165 int setCipher (const std::string& cipher)
2166 {
2167 if (((this->_tlsHandle) ? SSL_set_cipher_list (this->_tlsHandle.get (), cipher.c_str ())
2168 : SSL_CTX_set_cipher_list (this->_tlsContext.get (), cipher.c_str ())) == 0)
2169 {
2170 lastError = make_error_code (Errc::InvalidParam);
2171 return -1;
2172 }
2173
2174 return 0;
2175 }
2176
2182 int setCipher_1_3 (const std::string& cipher)
2183 {
2184 if (((this->_tlsHandle) ? SSL_set_ciphersuites (this->_tlsHandle.get (), cipher.c_str ())
2185 : SSL_CTX_set_ciphersuites (this->_tlsContext.get (), cipher.c_str ())) == 0)
2186 {
2187 lastError = make_error_code (Errc::InvalidParam);
2188 return -1;
2189 }
2190
2191 return 0;
2192 }
2193
2194 protected:
2203
2209 {
2210 // start the SSL handshake.
2211 int result = SSL_do_handshake (this->_tlsHandle.get ());
2212 if (result < 1)
2213 {
2214 switch (SSL_get_error (this->_tlsHandle.get (), result))
2215 {
2216 case SSL_ERROR_WANT_READ:
2217 case SSL_ERROR_WANT_WRITE:
2218 case SSL_ERROR_WANT_X509_LOOKUP:
2219 // SSL_do_handshake want read or want write.
2221 break;
2222 case SSL_ERROR_ZERO_RETURN:
2223 // a close notify alert was received.
2224 // we have to answer by sending a close notify alert too.
2226 break;
2227 case SSL_ERROR_SYSCALL:
2228 // an error occurred at the socket level.
2229 switch (errno)
2230 {
2231 case 0:
2232 case ECONNRESET:
2233 case EPIPE:
2235 this->_state = State::Disconnected;
2236 break;
2237 default:
2238 lastError = std::error_code (errno, std::generic_category ());
2239 break;
2240 }
2241 break;
2242 default:
2243 // SSL protocol error.
2244#ifdef DEBUG
2245 std::cout << ERR_reason_error_string (ERR_get_error ()) << std::endl;
2246#endif
2248 break;
2249 }
2250
2251 return -1;
2252 }
2253
2255
2256 return 0;
2257 }
2258
2265 static void infoWrapper (const SSL* ssl, int where, int ret)
2266 {
2267 assert (ssl);
2268 static_cast<BasicTlsSocket<Protocol>*> (SSL_get_app_data (ssl))->infoCallback (where, ret);
2269 }
2270
2276 void infoCallback (int where, int ret) const
2277 {
2278 if (where & SSL_CB_ALERT)
2279 {
2280 std::cout << "SSL/TLS Alert ";
2281 (where & SSL_CB_READ) ? std::cout << "[read] " : std::cout << "[write] ";
2282 std::cout << SSL_alert_type_string_long (ret) << ":";
2283 std::cout << SSL_alert_desc_string_long (ret);
2284 std::cout << std::endl;
2285 }
2286 else if (where & SSL_CB_LOOP)
2287 {
2288 std::cout << "SSL/TLS State ";
2289 (SSL_in_connect_init (this->_tlsHandle.get ())) ? std::cout << "[connect] "
2290 : (SSL_in_accept_init (this->_tlsHandle.get ())) ? std::cout << "[accept] "
2291 : std::cout << "[undefined] ";
2292 std::cout << SSL_state_string_long (this->_tlsHandle.get ());
2293 std::cout << std::endl;
2294 }
2295 else if (where & SSL_CB_HANDSHAKE_START)
2296 {
2297 std::cout << "SSL/TLS Handshake [Start] " << SSL_state_string_long (this->_tlsHandle.get ())
2298 << std::endl;
2299 }
2300 else if (where & SSL_CB_HANDSHAKE_DONE)
2301 {
2302 std::cout << "SSL/TLS Handshake [Done] " << SSL_state_string_long (this->_tlsHandle.get ())
2303 << std::endl;
2304 std::cout << SSL_CTX_sess_number (this->_tlsContext.get ()) << " items in the session cache"
2305 << std::endl;
2306 std::cout << SSL_CTX_sess_connect (this->_tlsContext.get ()) << " client connects" << std::endl;
2307 std::cout << SSL_CTX_sess_connect_good (this->_tlsContext.get ()) << " client connects that finished"
2308 << std::endl;
2309 std::cout << SSL_CTX_sess_connect_renegotiate (this->_tlsContext.get ())
2310 << " client renegotiations requested" << std::endl;
2311 std::cout << SSL_CTX_sess_accept (this->_tlsContext.get ()) << " server connects" << std::endl;
2312 std::cout << SSL_CTX_sess_accept_good (this->_tlsContext.get ()) << " server connects that finished"
2313 << std::endl;
2314 std::cout << SSL_CTX_sess_accept_renegotiate (this->_tlsContext.get ())
2315 << " server renegotiations requested" << std::endl;
2316 std::cout << SSL_CTX_sess_hits (this->_tlsContext.get ()) << " session cache hits" << std::endl;
2317 std::cout << SSL_CTX_sess_cb_hits (this->_tlsContext.get ()) << " external session cache hits"
2318 << std::endl;
2319 std::cout << SSL_CTX_sess_misses (this->_tlsContext.get ()) << " session cache misses" << std::endl;
2320 std::cout << SSL_CTX_sess_timeouts (this->_tlsContext.get ()) << " session cache timeouts" << std::endl;
2321 std::cout << "negotiated " << SSL_get_cipher (this->_tlsHandle.get ()) << " cipher suite" << std::endl;
2322 }
2323 }
2324
2331 static int verifyWrapper (int preverified, X509_STORE_CTX* context)
2332 {
2333 SSL* ssl = static_cast<SSL*> (X509_STORE_CTX_get_ex_data (context, SSL_get_ex_data_X509_STORE_CTX_idx ()));
2334
2335 assert (ssl);
2336 return static_cast<BasicTlsSocket<Protocol>*> (SSL_get_app_data (ssl))
2337 ->verifyCallback (preverified, context);
2338 }
2339
2346 int verifyCallback (int preverified, X509_STORE_CTX* context) const
2347 {
2348 int maxDepth = SSL_get_verify_depth (this->_tlsHandle.get ());
2349 int dpth = X509_STORE_CTX_get_error_depth (context);
2350
2351#ifdef DEBUG
2352 std::cout << "verification started at depth=" << dpth << std::endl;
2353#endif
2354
2355 // catch a too long certificate chain.
2356 if ((maxDepth >= 0) && (dpth > maxDepth))
2357 {
2358 preverified = 0;
2359 X509_STORE_CTX_set_error (context, X509_V_ERR_CERT_CHAIN_TOO_LONG);
2360 }
2361
2362 if (!preverified)
2363 {
2364#ifdef DEBUG
2365 std::cout << "verification failed at depth=" << dpth << " - "
2366 << X509_verify_cert_error_string (X509_STORE_CTX_get_error (context)) << std::endl;
2367#endif
2368 return 0;
2369 }
2370
2371 // check the certificate host name.
2372 if (!verifyCert (context))
2373 {
2374#ifdef DEBUG
2375 std::cout << "rejected by CERT at depth=" << dpth << std::endl;
2376#endif
2377 return 0;
2378 }
2379
2380 // check the revocation list.
2381 /*if (!verifyCrl (context))
2382 {
2383 #ifdef DEBUG
2384 std::cout << "rejected by CRL at depth=" << dpth << std::endl;
2385 #endif
2386 return 0;
2387 }*/
2388
2389 // check ocsp.
2390 /*if (!verifyOcsp (context))
2391 {
2392 #ifdef DEBUG
2393 std::cout << "rejected by OCSP at depth=" << dpth << std::endl;
2394 #endif
2395 return 0;
2396 }*/
2397
2398#ifdef DEBUG
2399 std::cout << "certificate accepted at depth=" << dpth << std::endl;
2400#endif
2401
2402 return 1;
2403 }
2404
2410 int verifyCert (X509_STORE_CTX* context) const
2411 {
2412 int depth = X509_STORE_CTX_get_error_depth (context);
2413 X509* cert = X509_STORE_CTX_get_current_cert (context);
2414
2415 char buf[256];
2416 X509_NAME_oneline (X509_get_subject_name (cert), buf, sizeof (buf));
2417#ifdef DEBUG
2418 std::cout << "subject=" << buf << std::endl;
2419#endif
2420
2421 // check the certificate host name
2422 if (depth == 0)
2423 {
2424 // confirm a match between the hostname and the hostnames listed in the certificate.
2425 if (!checkHostName (cert))
2426 {
2427#ifdef DEBUG
2428 std::cout << "no match for hostname in the certificate" << std::endl;
2429#endif
2430 return 0;
2431 }
2432 }
2433
2434 return 1;
2435 }
2436
2442 bool checkHostName (X509* certificate) const
2443 {
2444 bool match = false;
2445
2446 // get alternative names.
2447 join::StackOfGeneralNamePtr altnames (reinterpret_cast<STACK_OF (GENERAL_NAME)*> (
2448 X509_get_ext_d2i (certificate, NID_subject_alt_name, 0, 0)));
2449 if (altnames)
2450 {
2451 for (int i = 0; (i < sk_GENERAL_NAME_num (altnames.get ())) && !match; ++i)
2452 {
2453 // get a handle to alternative name.
2454 GENERAL_NAME* current_name = sk_GENERAL_NAME_value (altnames.get (), i);
2455
2456 if (current_name->type == GEN_DNS)
2457 {
2458 // get data and length.
2459 const char* host = reinterpret_cast<const char*> (ASN1_STRING_get0_data (current_name->d.ia5));
2460 size_t len = size_t (ASN1_STRING_length (current_name->d.ia5));
2461 std::string pattern (host, host + len), serverName (this->_remote.hostname ());
2462
2463 // strip off trailing dots.
2464 if (pattern.back () == '.')
2465 {
2466 pattern.pop_back ();
2467 }
2468
2469 if (serverName.back () == '.')
2470 {
2471 serverName.pop_back ();
2472 }
2473
2474 // compare to pattern.
2475 if (fnmatch (pattern.c_str (), serverName.c_str (), 0) == 0)
2476 {
2477 // an alternative name matched the server hostname.
2478 match = true;
2479 }
2480 }
2481 }
2482 }
2483
2484 return match;
2485 }
2486
2492 /*int verifyCrl ([[maybe_unused]]X509_STORE_CTX *context) const
2493 {
2494 return 1;
2495 }*/
2496
2502 /*int verifyOcsp ([[maybe_unused]]X509_STORE_CTX *context) const
2503 {
2504 return 1;
2505 }*/
2506
2509
2512
2515
2517 friend class BasicTlsAcceptor<Protocol>;
2518 };
2519
2526 template <class Protocol>
2527 constexpr bool operator< (const BasicTlsSocket<Protocol>& a, const BasicTlsSocket<Protocol>& b) noexcept
2528 {
2529 return a.handle () < b.handle ();
2530 }
2531}
2532
2533namespace std
2534{
2536 template <>
2537 struct is_error_condition_enum<join::TlsErrc> : public true_type
2538 {
2539 };
2540}
2541
2542#endif
basic datagram socket class.
Definition socket.hpp:645
virtual ~BasicDatagramSocket()=default
Destroy the instance.
BasicDatagramSocket(const BasicDatagramSocket &other)=delete
Copy constructor.
typename BasicSocket< Protocol >::Option Option
Definition socket.hpp:649
BasicDatagramSocket(Mode mode, int ttl=60)
Create instance specifying the mode.
Definition socket.hpp:665
virtual int connect(const Endpoint &endpoint)
make a connection to the given endpoint.
Definition socket.hpp:800
virtual int bindToDevice(const std::string &device) noexcept
assigns the specified device to the socket.
Definition socket.hpp:766
std::unique_ptr< BasicDatagramSocket< Protocol > > Ptr
Definition socket.hpp:647
virtual bool connected() noexcept
check if the socket is connected.
Definition socket.hpp:1065
virtual int setOption(Option option, int value) noexcept override
set the given option to the given value.
Definition socket.hpp:961
Endpoint _remote
remote endpoint.
Definition socket.hpp:1119
virtual int read(char *data, unsigned long maxSize) noexcept override
read data.
Definition socket.hpp:879
int _ttl
packet time to live.
Definition socket.hpp:1122
virtual int write(const char *data, unsigned long maxSize) noexcept override
write data.
Definition socket.hpp:926
virtual void close() noexcept override
close the socket handle.
Definition socket.hpp:867
typename Protocol::Endpoint Endpoint
Definition socket.hpp:651
int ttl() const
returns the Time-To-Live value.
Definition socket.hpp:1112
BasicDatagramSocket(int ttl=60)
Default constructor.
Definition socket.hpp:656
typename BasicSocket< Protocol >::State State
Definition socket.hpp:650
int mtu() const
get socket mtu.
Definition socket.hpp:1074
BasicDatagramSocket & operator=(const BasicDatagramSocket &other)=delete
Copy assignment operator.
virtual int readFrom(char *data, unsigned long maxSize, Endpoint *endpoint=nullptr) noexcept
read data on the socket.
Definition socket.hpp:891
virtual int writeTo(const char *data, unsigned long maxSize, const Endpoint &endpoint) noexcept
write data on the socket.
Definition socket.hpp:938
virtual int disconnect()
shutdown the connection.
Definition socket.hpp:837
typename BasicSocket< Protocol >::Mode Mode
Definition socket.hpp:648
virtual int open(const Protocol &protocol=Protocol()) noexcept override
open socket using the given protocol.
Definition socket.hpp:723
BasicDatagramSocket(BasicDatagramSocket &&other)
Move constructor.
Definition socket.hpp:688
const Endpoint & remoteEndpoint() const
determine the remote endpoint associated with this socket.
Definition socket.hpp:1056
basic socket class.
Definition socket.hpp:60
bool opened() const noexcept
check if the socket is opened.
Definition socket.hpp:489
BasicSocket & operator=(const BasicSocket &other)=delete
copy assignment operator.
virtual int open(const Protocol &protocol=Protocol()) noexcept
open socket using the given protocol.
Definition socket.hpp:194
static uint16_t checksum(const uint16_t *data, size_t len, uint16_t current=0)
get standard 1s complement checksum.
Definition socket.hpp:546
void setMode(Mode mode) noexcept
set the socket to the non-blocking or blocking mode.
Definition socket.hpp:380
State
socket states.
Definition socket.hpp:102
@ Disconnected
Definition socket.hpp:106
@ Connecting
Definition socket.hpp:103
@ Disconnecting
Definition socket.hpp:105
@ Closed
Definition socket.hpp:107
@ Connected
Definition socket.hpp:104
Protocol _protocol
protocol.
Definition socket.hpp:625
virtual int setOption(Option option, int value) noexcept
set the given option to the given value.
Definition socket.hpp:407
Mode _mode
socket mode.
Definition socket.hpp:619
virtual void close() noexcept
close the socket.
Definition socket.hpp:223
int family() const noexcept
get socket address family.
Definition socket.hpp:507
Mode
socket modes.
Definition socket.hpp:69
@ Blocking
Definition socket.hpp:70
@ NonBlocking
Definition socket.hpp:71
virtual bool waitReadyRead(int timeout=0) const noexcept
block until new data is available for reading.
Definition socket.hpp:294
std::unique_ptr< BasicSocket< Protocol > > Ptr
Definition socket.hpp:62
virtual ~BasicSocket()
destroy the socket instance.
Definition socket.hpp:181
virtual int bind(const Endpoint &endpoint) noexcept
assigns the specified endpoint to the socket.
Definition socket.hpp:238
Endpoint localEndpoint() const
determine the local endpoint associated with this socket.
Definition socket.hpp:472
BasicSocket()
default constructor.
Definition socket.hpp:113
int type() const noexcept
get the protocol communication semantic.
Definition socket.hpp:516
State _state
socket state.
Definition socket.hpp:616
typename Protocol::Endpoint Endpoint
Definition socket.hpp:63
virtual bool encrypted() const noexcept
check if the socket is secure.
Definition socket.hpp:498
Option
socket options.
Definition socket.hpp:78
@ MulticastTtl
Definition socket.hpp:92
@ SndBuffer
Definition socket.hpp:84
@ Ttl
Definition socket.hpp:90
@ Broadcast
Definition socket.hpp:89
@ RcvError
Definition socket.hpp:94
@ ReusePort
Definition socket.hpp:88
@ MulticastLoop
Definition socket.hpp:91
@ KeepAlive
Definition socket.hpp:80
@ ReuseAddr
Definition socket.hpp:87
@ KeepCount
Definition socket.hpp:83
@ KeepIntvl
Definition socket.hpp:82
@ AuxData
Definition socket.hpp:95
@ PathMtuDiscover
Definition socket.hpp:93
@ NoDelay
Definition socket.hpp:79
@ TimeStamp
Definition socket.hpp:86
@ KeepIdle
Definition socket.hpp:81
@ RcvBuffer
Definition socket.hpp:85
virtual bool waitReadyWrite(int timeout=0) const noexcept
block until at least one byte can be written.
Definition socket.hpp:341
BasicSocket(BasicSocket &&other)
move constructor.
Definition socket.hpp:144
int handle() const noexcept
get socket native handle.
Definition socket.hpp:534
virtual int read(char *data, unsigned long maxSize) noexcept
read data.
Definition socket.hpp:305
virtual int write(const char *data, unsigned long maxSize) noexcept
write data.
Definition socket.hpp:352
BasicSocket(Mode mode)
create socket instance specifying the mode.
Definition socket.hpp:122
int wait(bool wantRead, bool wantWrite, int timeout) const noexcept
wait for the socket handle to become ready.
Definition socket.hpp:579
int protocol() const noexcept
get socket protocol.
Definition socket.hpp:525
int _handle
socket handle.
Definition socket.hpp:622
virtual int canRead() const noexcept
get the number of readable bytes.
Definition socket.hpp:275
BasicSocket(const BasicSocket &other)=delete
copy constructor.
basic stream acceptor class.
Definition protocol.hpp:52
basic stream socket class.
Definition socket.hpp:1142
virtual ~BasicStreamSocket()=default
destroy the instance.
virtual int setOption(Option option, int value) noexcept override
set the given option to the given value.
Definition socket.hpp:1398
virtual bool connecting() const noexcept
check if the socket is connecting.
Definition socket.hpp:1448
BasicStreamSocket(const BasicStreamSocket &other)=delete
copy constructor.
BasicStreamSocket(BasicStreamSocket &&other)
move constructor.
Definition socket.hpp:1184
virtual bool waitConnected(int timeout=0)
block until connected.
Definition socket.hpp:1211
int readExactly(std::string &data, unsigned long size, int timeout=0)
read data until size is reached or an error occurred.
Definition socket.hpp:1355
typename BasicDatagramSocket< Protocol >::Mode Mode
Definition socket.hpp:1145
int writeExactly(const char *data, unsigned long size, int timeout=0)
write data until size is reached or an error occurred.
Definition socket.hpp:1368
BasicStreamSocket(Mode mode)
create instance specifying the mode.
Definition socket.hpp:1162
typename Protocol::Endpoint Endpoint
Definition socket.hpp:1148
std::unique_ptr< BasicStreamSocket< Protocol > > Ptr
Definition socket.hpp:1144
BasicStreamSocket & operator=(const BasicStreamSocket &other)=delete
copy assignment operator.
typename BasicDatagramSocket< Protocol >::Option Option
Definition socket.hpp:1146
virtual bool connected() noexcept override
check if the socket is connected.
Definition socket.hpp:1457
virtual bool waitDisconnected(int timeout=0)
wait until the connection as been shut down.
Definition socket.hpp:1278
virtual int disconnect() override
shutdown the connection.
Definition socket.hpp:1236
BasicStreamSocket()
default constructor.
Definition socket.hpp:1153
int readExactly(char *data, unsigned long size, int timeout=0)
read data until size is reached or an error occurred.
Definition socket.hpp:1324
typename BasicDatagramSocket< Protocol >::State State
Definition socket.hpp:1147
basic TLS acceptor class.
Definition protocol.hpp:54
basic TLS socket class.
Definition socket.hpp:1552
BasicTlsSocket()
default constructor.
Definition socket.hpp:1563
BasicTlsSocket & operator=(const BasicTlsSocket &other)=delete
copy assignment operator.
int setCaFile(const std::string &caFile)
set the location of the trusted CA certificate file.
Definition socket.hpp:2129
virtual int canRead() const noexcept override
get the number of readable bytes.
Definition socket.hpp:1903
int startEncryption()
start socket encryption (perform TLS handshake).
Definition socket.hpp:1714
bool waitEncrypted(int timeout=0)
wait until TLS handshake is performed or timeout occur (non blocking socket).
Definition socket.hpp:1766
virtual bool encrypted() const noexcept override
check if the socket is secure.
Definition socket.hpp:2064
BasicTlsSocket(Mode mode, join::SslCtxPtr tlsContext)
Create socket instance specifying the socket mode and TLS context.
Definition socket.hpp:1620
join::SslCtxPtr _tlsContext
verify certificate revocation using CRL.
Definition socket.hpp:2508
virtual int read(char *data, unsigned long maxSize) noexcept override
read data on the socket.
Definition socket.hpp:1919
void setVerify(bool verify, int depth=-1)
Enable/Disable the verification of the peer certificate.
Definition socket.hpp:2147
join::SslPtr _tlsHandle
TLS handle.
Definition socket.hpp:2511
int verifyCallback(int preverified, X509_STORE_CTX *context) const
trusted CA certificates verification callback.
Definition socket.hpp:2346
virtual bool waitReadyRead(int timeout=0) const noexcept override
block until new data is available for reading.
Definition socket.hpp:1887
int verifyCert(X509_STORE_CTX *context) const
verify certificate validity.
Definition socket.hpp:2410
void infoCallback(int where, int ret) const
state information callback.
Definition socket.hpp:2276
std::unique_ptr< BasicTlsSocket< Protocol > > Ptr
Definition socket.hpp:1554
BasicTlsSocket(Mode mode)
create instance specifying the mode.
Definition socket.hpp:1572
TlsState
TLS state.
Definition socket.hpp:2199
@ Encrypted
Definition socket.hpp:2200
@ NonEncrypted
Definition socket.hpp:2201
TlsState _tlsState
TLS state.
Definition socket.hpp:2514
bool checkHostName(X509 *certificate) const
confirm a match between the hostname contacted and the hostnames listed in the certificate.
Definition socket.hpp:2442
virtual int disconnect() override
shutdown the connection.
Definition socket.hpp:1808
int setCertificate(const std::string &cert, const std::string &key="")
set the certificate and the private key.
Definition socket.hpp:2075
virtual bool waitReadyWrite(int timeout=0) const noexcept override
block until until at least one byte can be written on the socket.
Definition socket.hpp:1983
int setCipher(const std::string &cipher)
set the cipher list (TLSv1.2 and below).
Definition socket.hpp:2165
typename BasicStreamSocket< Protocol >::State State
Definition socket.hpp:1557
typename Protocol::Endpoint Endpoint
Definition socket.hpp:1558
virtual void close() noexcept override
close the socket handle.
Definition socket.hpp:1875
int setCipher_1_3(const std::string &cipher)
set the cipher list (TLSv1.3).
Definition socket.hpp:2182
virtual ~BasicTlsSocket()=default
destroy the instance.
int setCaPath(const std::string &caPath)
set the location of the trusted CA certificates.
Definition socket.hpp:2111
BasicTlsSocket(const BasicTlsSocket &other)=delete
copy constructor.
int startHandshake()
Start SSL handshake.
Definition socket.hpp:2208
typename BasicStreamSocket< Protocol >::Option Option
Definition socket.hpp:1556
static void infoWrapper(const SSL *ssl, int where, int ret)
c style callback wrapper for the state information callback.
Definition socket.hpp:2265
virtual int write(const char *data, unsigned long maxSize) noexcept override
write data on the socket.
Definition socket.hpp:2001
BasicTlsSocket(join::SslCtxPtr tlsContext)
create instance specifying TLS context.
Definition socket.hpp:1610
typename BasicStreamSocket< Protocol >::Mode Mode
Definition socket.hpp:1555
static int verifyWrapper(int preverified, X509_STORE_CTX *context)
c style callback wrapper for the Trusted CA certificates verification callback.
Definition socket.hpp:2331
BasicTlsSocket(BasicTlsSocket &&other)
move constructor.
Definition socket.hpp:1647
int connectEncrypted(const Endpoint &endpoint)
make an encrypted connection to the given endpoint.
Definition socket.hpp:1694
Event handler interface class.
Definition reactor.hpp:46
TLS error category.
Definition socket.hpp:1511
virtual std::string message(int code) const
translate digest error code to human readable error string.
Definition socket.cpp:44
virtual const char * name() const noexcept
get digest error category name.
Definition socket.cpp:35
const std::string key(65, 'a')
key.
Definition acceptor.hpp:32
bool operator<(const BasicUnixEndpoint< Protocol > &a, const BasicUnixEndpoint< Protocol > &b) noexcept
compare if endpoint is lower.
Definition endpoint.hpp:207
std::unique_ptr< SSL_CTX, SslCtxDelete > SslCtxPtr
Definition openssl.hpp:240
std::unique_ptr< STACK_OF(GENERAL_NAME), StackOfGeneralNameDelete > StackOfGeneralNamePtr
Definition openssl.hpp:210
const std::string defaultCipher_1_3
Definition openssl.cpp:40
TlsErrc
TLS error codes.
Definition socket.hpp:1502
const std::error_category & getTlsCategory()
get error category.
Definition socket.cpp:61
std::error_code make_error_code(join::Errc code) noexcept
Create an std::error_code object.
Definition error.cpp:150
const std::string defaultCipher
Definition openssl.cpp:36
std::unique_ptr< SSL, SslDelete > SslPtr
Definition openssl.hpp:225
std::error_condition make_error_condition(join::Errc code) noexcept
Create an std::error_condition object.
Definition error.cpp:159
Definition error.hpp:137