-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimple_socket.hpp
More file actions
1775 lines (1506 loc) · 45.4 KB
/
simple_socket.hpp
File metadata and controls
1775 lines (1506 loc) · 45.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SimpleSocket
*
* @author: kaniteru (kaniteru81@gmail.com)
* @repo: https://github.com/kaniteru/SimpleSocket
**/
#ifndef KANITERU_SIMPLE_SOCKET_HPP
#define KANITERU_SIMPLE_SOCKET_HPP
#ifdef _MSVC_LANG
#define CURRENT_CXX_VERSION _MSVC_LANG
#else
#define CURRENT_CXX_VERSION __cplusplus
#endif //_MSVC_LANG
// =========================================================
// === INCLUDE STANDARD HEADERS
// =========================================================
#include <cstdio>
#include <string>
#include <cstring>
#if CURRENT_CXX_VERSION < 201103L
#include <stdint.h>
#else
#include <cstdint>
#endif //CURRENT_CXX_VERSION < 201103L
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <cerrno>
#endif //_WIN32
// =========================================================
// === TYPE DEFINES
// =========================================================
typedef int32_t kani_flag_t;
#ifdef _WIN32
typedef SOCKET kani_socket_t;
typedef int32_t kani_socklen_t;
typedef int32_t kani_buflen_t;
#else
typedef int32_t kani_socket_t;
typedef uint32_t kani_socklen_t;
typedef ssize_t kani_buflen_t;
#endif //_WIN32
// =========================================================
// === MACRO DEFINES
// =========================================================
#define KANI_MAX_SIZE ((size_t) - 1)
#define KANI_MAX_BUF_LEN ((kani_buflen_t) - 1)
#define KANI_MAX_UDP_BUF_LEN 65507
#define KANI_INVALID_BUF_LEN 0
#define KANI_DEFAULT_MAX_MSG_LEN 65535
#ifdef _WIN32
#define KANI_INVALID_SOCKET INVALID_SOCKET
#define KANI_SOCKET_ERROR SOCKET_ERROR
#define KANI_CLOSE_SOCKET(SOCK) closesocket(SOCK);
#else
#define KANI_INVALID_SOCKET (-1)
#define KANI_SOCKET_ERROR (-1)
#define KANI_CLOSE_SOCKET(SOCK) ::close(SOCK);
#endif //_WIN32
#if CURRENT_CXX_VERSION < 201103L
#define override
#define KANI_NULLPTR NULL
#else
#define KANI_NULLPTR nullptr
#endif //CURRENT_CXX_VERSION < 201103L
#if CURRENT_CXX_VERSION >= 201703L
#define KANI_STRVIEW std::string_view
#else
#define KANI_STRVIEW const std::string&
#endif //CURRENT_CXX_VERSION >= 201703L
#ifdef KANITERU_ASYNC_SOCKET_INCLUDED
#define KANITERU_SIMPLE_SOCKET_CHECKED_ASYNC_SOCKET_INCLUDE
namespace async_socket {
class IAsyncSocket;
}
#endif //KANITERU_ASYNC_SOCKET_INCLUDED
namespace kani {
namespace simple_socket {
// ======================= S T R U C T =======================
// === Msg
// ======================= S T R U C T =======================
/**
* @brief Using get status when buffer is sent or received.
* [ SS = SimpleSocket ]
*/
enum eSSMsgStatus {
/* Received failed, to know the cause, using SocketErrTracker */
SS_MSG_STATUS_UNKNOWN = -1,
/* Sent or received success. */
SS_MSG_STATUS_SUCCESS = 0,
/* Failed, using GetWsaLastError() or errno to can track the error. */
SS_MSG_STATUS_FAILED = 1,
/* In the udp client, received msg success but sender isn't the server we want. */
SS_MSG_STATUS_SUCCESS_FROM_UNKNOWN_HOST = 2,
/* The socket was unexpectedly closed, possibly by the peer. */
SS_MSG_STATUS_FAILED_SOCKET_CLOSED = 3,
/* Not enough system or network resources to complete the operation. */
SS_MSG_STATUS_FAILED_NO_RESOURCES = 4,
/* The message being sent or received exceeds the allowable maximum size. */
SS_MSG_STATUS_FAILED_BUF_LEN_TOO_LARGE = 5,
/* The message being sent or received is smaller than the allowable minimum size. */
SS_MSG_STATUS_FAILED_BUF_LEN_TOO_SMALL = 6,
};
/**
* @brief Base of the buffer to send and receive.
*/
struct Msg {
std::string m_msg; /* Buffer of content received or sent */
eSSMsgStatus m_status; /* Result of sent or received a buffer */
public:
/**
* @brief Init with null.
*/
Msg();
/**
* @param [in] msg Contents of the buffer to initialize.
*/
explicit Msg(const std::string& msg);
#if CURRENT_CXX_VERSION >= 201103L
/**
* @param [in] msg Contents of the buffer to initialize.
*/
explicit Msg(std::string&& msg);
#endif //CURRENT_CXX_VERSION >= 201103L
/**
* @param [in] pMsg Char pointer for buffer.
* @param [in] len Buffer length of pStr.
*/
Msg(const char* pMsg, kani_buflen_t len);
};
inline
Msg::Msg() :
m_status(SS_MSG_STATUS_UNKNOWN) { }
inline
Msg::Msg(const std::string& msg) :
m_msg(msg),
m_status(SS_MSG_STATUS_UNKNOWN) { }
#if CURRENT_CXX_VERSION >= 201103L
inline
Msg::Msg(std::string&& msg) :
m_msg(std::move(msg)),
m_status(SS_MSG_STATUS_UNKNOWN) { }
#endif //CURRENT_CXX_VERSION >= 201103L
inline
Msg::Msg(const char* const pMsg, const kani_buflen_t len) :
m_status(SS_MSG_STATUS_UNKNOWN) {
m_msg.assign(pMsg, len);
}
// ======================= S T R U C T =======================
// === SendMsg
// ======================= S T R U C T =======================
/**
* @brief Buffer used for send.
*
* @code
* std::string str = "hello world";
* SendMsg msg(str);
* @endcode
*
* @code
* const char* pStr = "hello world";
* size_t len = strlen(pStr);
* SendMsg msg(pStr, len);
* @endcode
*/
struct SendMsg : public Msg {
kani_buflen_t m_sentLen; /* Length of sent buffer */
public:
/**
* @brief Init with null.
*/
SendMsg();
/**
* @param [in] msg Buffer to send.
*/
explicit SendMsg(const std::string& msg);
#if CURRENT_CXX_VERSION >= 201103L
/**
* @param [in] msg Buffer to send.
*/
explicit SendMsg(std::string&& msg);
#endif //CURRENT_CXX_VERSION >= 201103L
/**
* @param [in] pMsg Char pointer for buffer to send.
* @param [in] len Buffer length of pStr.
*/
SendMsg(const char* pMsg, kani_buflen_t len);
};
inline
SendMsg::SendMsg() :
m_sentLen(0) { }
inline
SendMsg::SendMsg(const std::string& msg) :
Msg(msg),
m_sentLen(0) { }
#if CURRENT_CXX_VERSION >= 201103L
inline
SendMsg::SendMsg(std::string&& msg) :
Msg(std::move(msg)),
m_sentLen(0) { }
#endif //CURRENT_CXX_VERSION >= 201103L
inline
SendMsg::SendMsg(const char* const pMsg, const kani_buflen_t len) :
Msg(pMsg, len),
m_sentLen(0) { }
// ======================= S T R U C T =======================
// === RecvMsg
// ======================= S T R U C T =======================
/**
* @brief Buffer for receive.
*
* @code
* RecvMsg msg;
* @endcode
*
* @code
* size_t maxLen = 1024;
* RecvMsg msg(maxLen);
* @endcode
*/
struct RecvMsg : public Msg {
kani_buflen_t m_recvLen; /* Length of received buffer */
protected:
const kani_buflen_t m_maxLen; /* Receivable buffer length. Must be less than 'KANI_MAX_SIZE'. */
public:
/**
* @return Receivable buffer length
*/
kani_buflen_t get_max_len() const;
public:
/**
* @param [in] maxLen Maximum buffer length that can be received.
*/
explicit RecvMsg(kani_buflen_t maxLen = KANI_DEFAULT_MAX_MSG_LEN);
};
inline
kani_buflen_t RecvMsg::get_max_len() const {
return m_maxLen;
}
inline
RecvMsg::RecvMsg(const kani_buflen_t maxLen) :
m_recvLen(0),
m_maxLen(maxLen) { }
// ======================= S T R U C T =======================
// === SocketInfo
// ======================= S T R U C T =======================
/**
* @brief Using when initializing a socket.
*/
struct SocketInfo {
std::string m_node; /* Host name or ip address. */
std::string m_service; /* Service name or port number. */
int32_t m_protocolFamily; /* Use 'AF_INET' for ipv4 and 'AF_INET6' for ipv6. */
};
// ======================= S T R U C T =======================
// === SocketHints
// ======================= S T R U C T =======================
/**
* @brief Components required when initializing a socket.
*/
struct SocketHints {
bool m_isTcp; /* Should be false if you want udp socket */
bool m_isServer; /* Should be false if you want a client socket */
};
// ======================== C L A S S ========================
// === ISocket
// ======================== C L A S S ========================
/**
* @brief Used to return whether the socket is initialized or not.
*/
enum eSSStartResult {
/* Started successfully. */
SS_START_RESULT_SUCCESS = 0,
/* Failed to start because already started. */
SS_START_RESULT_FAILED_ALREADY_STARTED = 1,
/* Socket creation failed. */
SS_START_RESULT_FAILED_CREATE_SOCKET = 2,
/* Socket binding failed. */
SS_START_RESULT_FAILED_BIND_SOCKET = 3,
/* Failed to listen on the socket. */
SS_START_RESULT_FAILED_LISTEN_SOCKET = 4,
};
// ======================== C L A S S ========================
// === ISocket
// ======================== C L A S S ========================
class ISocket {
public:
/**
* @brief This should initialize the socket and start the server or client.
*
* @return Returns whether the socket was initialized and the server or client started successfully.
*/
virtual eSSStartResult start() = 0;
/**
* @brief This should shut down the server or client and close the socket.
*/
virtual void stop() = 0;
public:
virtual ~ISocket();
};
inline
ISocket::~ISocket() { }
// ======================== C L A S S ========================
// === Socket
// ======================== C L A S S ========================
/**
* @brief Server and Client Interface.
* Helps initialize the socket.
*/
class Socket : public ISocket {
public:
/**
* @brief Before calling start(), you should call this method to ensure that the socket can be initialized.
*
* @return Returns true when the socket is ready to be initialized.
*/
bool is_valid() const;
protected:
/**
* @brief Initialize addrinfo with the supplied args.
* <br>It starts working after zerofilling addrinfo, so if you want to insert additional hints into addrinfo, you should do so after calling this method.
*
* @param [in, out] hints addrinfo to use as hints.
* @param [in] sockHints SocketHints of the options to reference when initializing addrinfo.
*/
static void get_addrinfo_hints(addrinfo& hints, SocketHints sockHints);
/**
* @brief Initialize the m_pAddrInfo by referencing SocketInfo and SocketHints.
*
* @param [in] info
* @param [in] sockHints
* @return Returns false if the information provided in SocketInfo or SocketHints is invalid.
*/
bool parse_socketinfo(const SocketInfo& info, SocketHints sockHints);
public:
Socket();
/**
* @brief Close the socket and free m_pAddrInfo.
*/
virtual ~Socket();
protected:
bool m_isValid; /* Is socket can be initialized? */
kani_socket_t m_socket; /* Socket on the server or client */
addrinfo* m_pAddrInfo; /* Required when creating a socket */
private:
#ifdef _WIN32
WSAData m_wsaData; /* Required on win32 only */
#endif //_WIN32
#ifdef KANITERU_ASYNC_SOCKET_INCLUDED
friend async_socket::IAsyncSocket;
#endif //KANITERU_ASYNC_SOCKET_INCLUDED
};
inline
bool Socket::is_valid() const {
return m_isValid;
}
inline
void Socket::get_addrinfo_hints(addrinfo& hints, const SocketHints sockHints) {
memset(&hints, 0, sizeof(hints));
if (sockHints.m_isTcp) {
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
} else {
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
}
if (sockHints.m_isServer) {
hints.ai_flags = AI_PASSIVE;
}
}
inline
bool Socket::parse_socketinfo(const SocketInfo& info, const SocketHints sockHints) {
addrinfo hints;
get_addrinfo_hints(hints, sockHints);
hints.ai_family = info.m_protocolFamily;
return getaddrinfo(info.m_node.c_str(), info.m_service.c_str(), &hints, &m_pAddrInfo) == 0;
}
inline
Socket::Socket() :
m_isValid(true),
m_socket(KANI_INVALID_SOCKET),
m_pAddrInfo(KANI_NULLPTR) {
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2, 2), &m_wsaData) != 0) {
m_isValid = false;
}
#endif
}
inline
Socket::~Socket() {
if (m_socket != KANI_INVALID_SOCKET) {
KANI_CLOSE_SOCKET(m_socket);
}
if (m_pAddrInfo) {
freeaddrinfo(m_pAddrInfo);
m_pAddrInfo = KANI_NULLPTR;
}
#ifdef _WIN32
WSACleanup();
#endif
}
// ======================== C L A S S ========================
// === IClient
// ======================== C L A S S ========================
/**
* @brief Client Interface
*/
class IClient {
public:
/**
* @brief This should send a message to the server.
*
* @param [in, out] pMsg
* @param [in] flag Flags for send() or sendto().
* @return Returns true if the message was sent successfully.
*/
virtual bool send_msg(SendMsg* pMsg, kani_flag_t flag) const = 0;
/**
* @brief This should receive a message from the server.
*
* @param [in, out] pMsg
* @param [in] flag Flags for recv() or recvfrom().
* @return Returns true if the message was successfully received from the server.
*/
virtual bool recv_msg(RecvMsg* pMsg, kani_flag_t flag) const = 0;
virtual ~IClient();
};
inline
IClient::~IClient() { }
// ======================== C L A S S ========================
// === NetAddr
// ======================== C L A S S ========================
class NetAddr {
public:
/**
* @return Return parse was success.
*/
bool is_valid() const;
/**
* @return Returns sockaddr.
*/
const sockaddr_storage& get_sockaddr() const;
/**
* @return Returns host str (like ip, domain).
*/
KANI_STRVIEW get_host() const;
/**
* @return Returns service str (like port).
*/
KANI_STRVIEW get_service() const;
protected:
/**
* @brief Parse sockaddr to host and service str.
*
* @param [in] flags getnameinfo() flags.
* @return Returns true if parse successful.
*/
bool parse_addr(kani_flag_t flags);
public:
/**
* @brief Init with null.
*/
NetAddr();
/**
* @param [in] sock Target socket. The Socket must be not closed.
* @param [in] flags getnameinfo() flags.
*/
explicit NetAddr(kani_socket_t sock, kani_flag_t flags = NI_NUMERICHOST | NI_NUMERICSERV);
/**
* @param [in] ss Target sockaddr.
* @param [in] flags getnameinfo() flags.
*/
explicit NetAddr(const sockaddr_storage& ss, kani_flag_t flags = NI_NUMERICHOST | NI_NUMERICSERV);
/**
* @param [in] ai Target addrinfo.
* @param [in] flags getnameinfo() flags.
*/
explicit NetAddr(const addrinfo& ai, kani_flag_t flags = NI_NUMERICHOST | NI_NUMERICSERV);
/**
* @param [in] other Other NetAddr.
* @param [in] flags getnameinfo() flags.
*/
explicit NetAddr(const NetAddr& other, kani_flag_t flags = NI_NUMERICHOST | NI_NUMERICSERV);
protected:
bool m_isValid;
std::string m_host;
std::string m_service;
sockaddr_storage m_addr;
};
inline
bool NetAddr::is_valid() const {
return m_isValid;
}
inline
const sockaddr_storage& NetAddr::get_sockaddr() const {
return m_addr;
}
inline
KANI_STRVIEW NetAddr::get_host() const {
return m_host;
}
inline
KANI_STRVIEW NetAddr::get_service() const {
return m_service;
}
inline
bool NetAddr::parse_addr(const kani_flag_t flags) {
char szHost[NI_MAXHOST + 1];
char szService[NI_MAXSERV + 1];
memset(szHost, '\0', sizeof(szHost));
memset(szService, '\0', sizeof(szService));
const bool result = getnameinfo(reinterpret_cast<sockaddr*>(&m_addr), sizeof(m_addr), szHost, NI_MAXHOST, szService, NI_MAXSERV, flags) == 0;
if (result) {
m_host.assign(szHost);
m_service.assign(szService);
}
return result;
}
inline
NetAddr::NetAddr() :
m_isValid(false) { }
inline
NetAddr::NetAddr(const kani_socket_t sock, const kani_flag_t flags) :
m_isValid(false) {
kani_socklen_t len = sizeof(m_addr);
if (getsockname(sock, reinterpret_cast<sockaddr*>(&m_addr), &len) == 0) {
m_isValid = this->parse_addr(flags);
}
}
inline
NetAddr::NetAddr(const sockaddr_storage& ss, const kani_flag_t flags) :
m_addr(ss) {
m_isValid = this->parse_addr(flags);
}
inline
NetAddr::NetAddr(const addrinfo& ai, const kani_flag_t flags) {
memset(&m_addr, 0, sizeof(m_addr));
memcpy(&m_addr, ai.ai_addr, ai.ai_addrlen);
m_isValid = this->parse_addr(flags);
}
inline
NetAddr::NetAddr(const NetAddr& other, const kani_flag_t flags) :
m_addr(other.m_addr) {
m_isValid = this->parse_addr(flags);
}
// ======================== C L A S S ========================
// === MsgHelper
// ======================== C L A S S ========================
/**
* @brief Helper class for message processing operations, including validation and handling message results.
*/
class MsgHelper {
public:
/**
* @brief Validates the buffer size of the given message.
*
* @param [in, out] pMsg A pointer to the SendMsg object whose buffer size needs to be validated.
* @return True if the buffer size is valid, false otherwise.
*/
static bool validate_buf_size(SendMsg* pMsg);
/**
* @brief Validates the buffer size of the max receivable.
*
* @param [in, out] pMsg Pointer to the received message to validate.
* @return True if the buffer size is valid, false otherwise.
*/
static bool validate_buf_size(RecvMsg* pMsg);
/**
* @brief Handles the result of a message after it has been sent.
*
* @param [in, out] pMsg A pointer to the message object that was sent.
* @return Returns true if sent successful.
*/
static bool handle_msg_result(SendMsg* pMsg);
/**
* @brief Handles the result of a received message.
*
* @param [in, out] pMsg A constant pointer to the received message object to be processed.
* @return Returns true if received successful.
*/
static bool handle_msg_result(RecvMsg* pMsg);
/**
* @brief Alloc char buf.
*
* @param [in] len Char len.
* @return Returns nullptr if alloc failed otherwise, Returns char ptr.
*
* @code
* size_t len = 1024;
* char* pBuf = alloc_recv_buf(len);
*
* if (pBuf) { ... }
* @endcode
*/
static char* alloc_recv_buf(size_t len) noexcept;
/**
* @brief Free the allocated char buf.
*
* @param [in, out] p Char ptr.
*
* @code
* char* pBuf = alloc_recv_buf(...);
* ...
* free_recv_buf(pBuf);
* @endcode
*/
static void free_recv_buf(char* p) noexcept;
private:
/**
* @brief Validates the buffer size to ensure it meets required constraints.
*
* @param [in, out] pMsg A msg ptr.
* @param [in] len The length of the buffer to be validated.
* @return Returns -1 = Size is too small.
* Returns 0 = Valid size.
* Returns 1 = Size is too big.
*/
static uint8_t validate_buf_size(Msg* pMsg, size_t len);
/**
* @brief Handles the result of a message processing operation.
*
* @param [in, out] pMsg Pointer to the message being processed.
* @param [in] len The length of the message.
* @return Returns true if len bigger than KANI_INVALID_BUF_LEN.
*/
static bool handle_msg_result(Msg* pMsg, kani_buflen_t len);
};
inline
bool MsgHelper::validate_buf_size(SendMsg* const pMsg) {
return MsgHelper::validate_buf_size(pMsg, pMsg->m_msg.length()) == 0;
}
inline
bool MsgHelper::validate_buf_size(RecvMsg* const pMsg) {
return MsgHelper::validate_buf_size(pMsg, pMsg->get_max_len()) == 0;
}
inline
bool MsgHelper::handle_msg_result(SendMsg* const pMsg) {
return MsgHelper::handle_msg_result(pMsg, pMsg->m_sentLen);
}
inline
bool MsgHelper::handle_msg_result(RecvMsg* const pMsg) {
return MsgHelper::handle_msg_result(pMsg, pMsg->m_recvLen);
}
inline
char* MsgHelper::alloc_recv_buf(const size_t len) noexcept {
char* pRes = KANI_NULLPTR;
const size_t realLen = len + 1;
try {
pRes = new char[realLen];
}
catch (const std::bad_alloc&) {
return KANI_NULLPTR;
}
memset(pRes, '\0', realLen);
return pRes;
}
inline
void MsgHelper::free_recv_buf(char* p) noexcept {
if (p) {
delete[] p;
}
}
inline
uint8_t MsgHelper::validate_buf_size(Msg* const pMsg, const size_t len) {
if (len <= KANI_INVALID_BUF_LEN) {
pMsg->m_status = SS_MSG_STATUS_FAILED_BUF_LEN_TOO_SMALL;
return -1;
}
if (len > KANI_MAX_BUF_LEN || len == KANI_MAX_SIZE) {
pMsg->m_status = SS_MSG_STATUS_FAILED_BUF_LEN_TOO_LARGE;
return 1;
}
return 0;
}
inline
bool MsgHelper::handle_msg_result(Msg* const pMsg, const kani_buflen_t len) {
if (len > KANI_INVALID_BUF_LEN) {
pMsg->m_status = SS_MSG_STATUS_SUCCESS;
return true;
}
if (len == KANI_INVALID_BUF_LEN) {
pMsg->m_status = SS_MSG_STATUS_FAILED_SOCKET_CLOSED;
return false;
}
pMsg->m_status = SS_MSG_STATUS_FAILED;
return false;
}
// ======================== C L A S S ========================
// === TcpMsgHelper
// ======================== C L A S S ========================
/**
* @brief Helps send and receive messages on Tcp socket.
*/
class TcpMsgHelper {
public:
/**
* @brief Send a message to the socket.
*
* @param [in] socket Host or client socket.
* @param [in, out] pMsg Msg ptr.
* @param [in] flag Flags for send().
* @return Returns true if the message was sent successfully.
*
* @code
* kani_socket_t socket = ...;
* SendMsg msg(...);
*
* if (TcpMsgHelper::send_msg(socket, &msg, ...)) { ... }
* @endcode
*/
static bool send_msg(kani_socket_t socket, SendMsg* pMsg, kani_flag_t flag);
/**
* @brief Receive an incoming message from the socket.
*
* @param [in] socket Host or client socket.
* @param [in, out] pMsg Msg ptr.
* @param [in] flag Flags for recv().
* @return Returns true if the message was received successfully.
*
* @code
* kani_socket_t socket = ...;
* RecvMsg msg(...);
*
* if (TcpMsgHelper::recv_msg(socket, &msg, ...)) { ... }
* @endcode
*/
static bool recv_msg(kani_socket_t socket, RecvMsg* pMsg, kani_flag_t flag);
};
inline
bool TcpMsgHelper::send_msg(const kani_socket_t socket, SendMsg* const pMsg, const kani_flag_t flag) {
if (!pMsg || !MsgHelper::validate_buf_size(pMsg)) {
return false;
}
const std::string& str = pMsg->m_msg;
const size_t len = str.length();
if (len > KANI_MAX_BUF_LEN) {
pMsg->m_status = SS_MSG_STATUS_FAILED_BUF_LEN_TOO_LARGE;
return false;
}
pMsg->m_sentLen = send(socket, str.c_str(), static_cast<kani_buflen_t>(len), flag);
return MsgHelper::handle_msg_result(pMsg);
}
inline
bool TcpMsgHelper::recv_msg(const kani_socket_t socket, RecvMsg* const pMsg, const kani_flag_t flag) {
if (!pMsg || !MsgHelper::validate_buf_size(pMsg)) {
return false;
}
const kani_buflen_t maxLen = pMsg->get_max_len();
char* pStr = MsgHelper::alloc_recv_buf(maxLen);
if (!pStr) {
pMsg->m_status = SS_MSG_STATUS_FAILED_NO_RESOURCES;
return false;
}
pMsg->m_recvLen = recv(socket, pStr, maxLen, flag);
const bool result = MsgHelper::handle_msg_result(pMsg);
if (result) {
pMsg->m_msg.assign(pStr, pMsg->m_recvLen);
}
MsgHelper::free_recv_buf(pStr);
pStr = KANI_NULLPTR;
return result;
}
// ======================== C L A S S ========================
// === UdpMsgHelper
// ======================== C L A S S ========================
/**
* @brief Helps send and receive messages on Udp socket.
*/
class UdpMsgHelper {
public:
/**
* @brief Send a message to the sockaddr.
*
* @param [in] socket Host socket.
* @param [in, out] pMsg Msg ptr.
* @param [in] pAddr Target sockaddr.
* @param [in] addrLen Len of target sockaddr
* @param [in] flag Flags for sendto().
* @return Returns true if the message was sent successfully.
*
* @code
* kani_socket_t socket = ...;
* SendMsg msg(...);
* sockaddr_storage addr = ...;
* kani_socklen_t addrLen = sizeof(addr);
*
* if (UdpMsgHelper::send_msg(socket, &msg, reinterpret_cast<sockaddr*>(&addr), addrLen, ...)) { ... }
* @endcode
*/
static bool send_msg(kani_socket_t socket, SendMsg* pMsg, const sockaddr* pAddr, kani_socklen_t addrLen, kani_flag_t flag);
/**
* @brief Send a message to the NetAddr.
*
* @param [in] socket Host socket.
* @param [in, out] pMsg Msg ptr.
* @param [in] pNetAddr Target NetAddr ptr.
* @param [in] flag Flags for sendto().
* @return Returns true if the message was sent successfully.
*
* @code
* kani_socket_t socket = ...;
* SendMsg msg(...);
* NetAddr addr(...);
*
* if (UdpMsgHelper::send_msg(socket, &msg, &addr, ...)) { ... }
* @endcode
*/
static bool send_msg(kani_socket_t socket, SendMsg* pMsg, const NetAddr* pNetAddr, kani_flag_t flag);
/**
* @brief Receive an incoming message from the socket.
*
* @param [in] socket Host socket.
* @param [in, out] pMsg Msg ptr.
* @param [in, out, optional] pAddr Target sockaddr ptr.
* @param [in, out, optional] pAddrLen Len of target sockaddr.
* @param [in] flag Flags for recvfrom().
* @return Returns true if the message was received successfully.
*
* @code
* kani_socket_t socket = ...;
* RecvMsg msg(...);
* sockaddr_storage addr;
* kani_socklen_t addrLen = sizeof(addr);
*
* if (UdpMsgHelper::recv_msg(socket, &msg, reinterpret_cast<sockaddr*>(&addr), &addrLen, ...)) { ... }
* @endcode
*
* @code
* if (UdpMsgHelper::recv_msg(socket, &msg, NULL, NULL, ...)) { ... }
* @endcode
*/
static bool recv_msg(kani_socket_t socket, RecvMsg* pMsg, sockaddr* pAddr, kani_socklen_t* pAddrLen, kani_flag_t flag);
/**
* @brief Receive an incoming message from the socket.
*
* @param [in] socket Host socket.
* @param [in, out] pMsg Msg ptr.
* @param [in, out, optional] pNetAddr Target NetAddr ptr.
* @param [in] flag Flags for recvfrom().
* @return Returns true if the message was received successfully.
*
* @code
* kani_socket_t socket = ...;
* RecvMsg msg(...);
* NetAddr addr;
*
* if (UdpMsgHelper::recv_msg(socket, &msg, &addr, ...)) { ... }
* @endcode
*
* @code
* if (UdpMsgHelper::recv_msg(socket, &msg, NULL, ...)) { ... }
* @endcode