-
Notifications
You must be signed in to change notification settings - Fork 0
/
netbase.cpp
1474 lines (1210 loc) · 43.4 KB
/
netbase.cpp
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
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <errno.h>
#include <string>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
//#include "net/base/ip_endpoint.h"
#define WRAP_SYSAPI(ret,func) do{ \
ret = func; \
}while( ret == -1 && ( errno == EINTR))
#define WRAP_SYSAPI_INTR(ret,func) do{ \
ret = func; \
}while( ret == -1 && errno == EINTR)
#define WRAP_CLOSE_FD(fd) do{ \
if( (fd) != -1 ){ close(fd); (fd) = -1; } }while(0)
#define WRAP_WAIT_THRID(thrid) do{ \
if( (thrid) != 0 ){ void* p = NULL; pthread_join(thrid,&p); (thrid) = 0; } }while(0)
#define POLLIN_FLAG (POLLIN|POLLHUP|POLLERR)
#define SET_POLLIN_FLAG(pollfds,fileid) { (pollfds).fd = fileid; (pollfds).events = POLLIN_FLAG; }
#define IS_POLLIN_OK(revent) (((revent) & POLLIN) && (!((revent) & (POLLERR|POLLHUP|POLLNVAL))) )
#define TCP_DEFAULTBACK_LOG 5
#define RMXQUIC_ERRCODE_CONNFAIL -1
#define RMXQUIC_ERRCODE_LISTENFAIL -2
#define RMXQUIC_ERRCODE_EPOLLFAIL -3
#define RMXQUIC_ERRCODE_EPOLLTIMEOUT -4
#define RMXQUIC_ERRCODE_EPOLLUSRSTOP -5
#define RMXQUIC_ERRCODE_NOTCONNECT -6
#define RMXQUIC_ERRCODE_NOTSUPPORT -7
#define RMXQUIC_ERRCODE_INITFAIL -8
#define RMXQUIC_ERRCODE_NOMEM -9
#define RMXQUIC_ERRCODE_BUFSIZE -10 // buf size too small
#define RMXTRACE_DEFAULT_FLAG ( RMXTRACE_FLAG_DEBUG|RMXTRACE_FLAG_INFO | RMXTRACE_FLAG_ERROR )
typedef void* (*RMXQUIC_TASK_ROUTINE)(void *);
namespace net{
class QuicClock;
class IPEndPoint;
bool NetComm_Init();
int NetComm_IPInfo2Addr(IPEndPoint *server_address, const char *hostname,int port,bool isserv);
void NetComm_DumpHex(const unsigned char* content, int contentlen);
bool NetComm_WriteN(int fd,char* p, size_t size);
bool NetComm_ReadN(int fd,char* p,size_t size,int intervaltimeout_ms);
int NetComm_InitUDP(IPEndPoint *server_address,IPEndPoint* local_address,const char *hostname,uint16_t port,bool isserv);
int NetComm_UDPSend(int sd,const char *buf,int len,const IPEndPoint *server_address);
int NetComm_UDPRecv(int sd,char* buf,size_t maxsz,IPEndPoint *peer_address);
void NetComm_CloseSocket(int sd);
int RMXCQuic_TCPAccept(int ld,sockaddr_storage* dst);
bool NetComm_TCPGetLocalPort(int sd,uint16_t& port);
int NetComm_TCPCreate(const char *serv,uint16_t port,bool isbind,int connecttimeout_ms);
bool NetComm_RecvN(int sd,char* p, size_t size,int timeout_ms,uint16_t interval_wait_ms);
bool NetComm_SendN(int sd,const char* p, size_t size);
bool NetComm_Poll(int sd,int timeout_ms);
bool NetComm_PollEx(int sd,int timeout_ms,bool& haserror);
bool NetComm_StartTask(pthread_t *thrid,void* (*start_routine)(void*),void *arg);
bool NetComm_RSAGenKey(std::string& priv,std::string& pub);
int NetComm_RSA256Hash(unsigned char hash[32],const char *string, int len);
int NetComm_RSASign(std::string &signature,const char *data, int dataLen,const char *privkey, int privkeylen);
int NetComm_RSAVerify(const std::string &signature,const char *data, int dataLen,const char *pubkey, int pubkeylen);
#if( RMXUDP_SSLMODE == 0 )
int NetComm_GCMEncrypt(const unsigned char *plaintext, int plaintext_len, const unsigned char *aad,
int aad_len, const unsigned char *key,const unsigned char *iv,int iv_len,
unsigned char *ciphertext,int taglen);
int NetComm_GCMDecrypt(const unsigned char *ciphertext, int ciphertext_len, const unsigned char *aad,
int aad_len,const unsigned char *key, const unsigned char *iv,int iv_len,
unsigned char *plaintext,int taglen);
#endif
//int NetComm_QuicConnect(int isipv6,const char *addr,int port);
}
/* a quic connect include:
* task runner
* proof verifiers -> GoProofVerifier::VerifyProof
* ProofVerifyJobVerifyProof_C
* -> new job, verify proof
*
* client writer
*/
#include <time.h>
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#include <sys/syscall.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <sys/types.h>
//#include <ifaddrs.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
//#include <net/if.h>
#ifdef ANDROID
#include <unwind.h>
#else
#include <execinfo.h>
#ifdef __cplusplus
#include <execinfo.h>
#include <cxxabi.h>
#endif
#endif
#include "openssl/sha.h"
#include "openssl/bio.h"
#include "openssl/pem.h"
#include "openssl/err.h"
#include "openssl/evp.h"
#include "openssl/ssl.h"
#include "rmxudp_common.h"
#include "net/base/ip_endpoint.h"
#include "net/quic/quic_clock.h"
#include "rmxquic/rmxquic_logging.h"
#ifndef TRACE_DETAIL
#define TRACE_UDP(cont,sz,addr,issnd,ret)
#else
static int DecQuichead(const uint8_t *content, int len,const sockaddr_in *addr,int issend,int ret);
#define TRACE_UDP(cont,sz,addr,issnd,ret) do{ \
if(g_RmxQuicTraceFlag & RMXTRACE_FLAG_IO) DecQuichead((const uint8_t *)cont,sz,(struct sockaddr_in *)addr,issnd,ret); \
}while(0)
#endif
namespace net{
#if( RMXUDP_SSLMODE == 0 ) && ((defined __APPLE__) || (!defined RMXUDPLIBMODE))
static void ExitCleanOpenSSL()
{
ERR_free_strings();
EVP_cleanup();
}
#endif
bool NetComm_Init()
{
#if( RMXUDP_SSLMODE == 0 ) && ((defined __APPLE__) || (!defined RMXUDPLIBMODE))
SSL_library_init();
OpenSSL_add_all_algorithms();
ERR_load_BIO_strings();
ERR_load_crypto_strings();
SSL_load_error_strings();
atexit(ExitCleanOpenSSL);
#endif
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sigaction( SIGPIPE, &sa, 0 );
return true;
}
void NetComm_CloseSocket(int sd)
{
#ifdef _WIN32_
closesocket(sd);
#else
close(sd);
#endif
}
#if 0
bool NetComm_GetEthInfo(std::string& name,std::string& ipaddr,std::string& macaddr)
{
char addrBuf[128] = "";
bool ret = false;
struct ifaddrs *ifa_list= 0, *ifa;
if (getifaddrs(&ifa_list)== -1) {
return false;
}
int32_t sd = socket( PF_INET, SOCK_DGRAM, 0 );
if( sd < 0 )
{
/// free memory allocated by getifaddrs
freeifaddrs( ifa_list );
return false;
}
for (ifa = ifa_list; ifa; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr )
continue;
/// print MAC address
struct ifreq req;
strcpy( req.ifr_name, ifa->ifa_name );
if( ioctl( sd, SIOCGIFHWADDR, &req ) != -1 ){
uint8_t* mac = (uint8_t*)req.ifr_ifru.ifru_hwaddr.sa_data;
char macbuf[32] = "";
sprintf(macbuf, "%02X:%02X:%02X:%02X:%02X:%02X",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] );
macaddr = macbuf;
}
if(ifa->ifa_addr->sa_family == AF_INET) {
const struct sockaddr_in *addr = (const struct sockaddr_in*)ifa->ifa_addr;
if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, 127)) {
ret = true;
}
}
else {
const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)ifa->ifa_addr;
if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, 127)) {
ret = true;
}
}
if( ret ){
if( ifa->ifa_name)
name = ifa->ifa_name;
addrBuf[127] = 0;
ipaddr = addrBuf;
if( strcmp(ifa->ifa_name,"lo") )
break;
}
}
freeifaddrs(ifa_list);
NetComm_CloseSocket(sd);
return ret;
}
#endif
bool NetComm_WriteN(int fd,const char *buf,size_t len)
{
int ret = -1;
while( len > 0 ){
WRAP_SYSAPI(ret,write(fd,buf,len));
if( ret <= 0 ){
return false;
}
len -= ret;
buf += ret;
}
return true;
}
bool NetComm_ReadN(int fd,char* p,size_t size,int intervaltimeout_ms)
{
size_t rest = size;
while( rest > 0 ){
int ret;
WRAP_SYSAPI( ret , read(fd,p,rest) );
if( ret <= 0 ){
return false;
}
rest -= ret;
p += ret;
if( !NetComm_Poll(fd,intervaltimeout_ms) )
return false;
}
return true;
}
int NetComm_InitUDP(IPEndPoint *server_address,IPEndPoint* local_address,const char *hostname,uint16_t port,bool isserv){
char service[32];
struct addrinfo hints, *res, *ressave;
int n;
int sd = -1;
int retval = -1;
IPEndPoint convaddr;
// server input local name and port, expect output local_address
// client input server's name and port, expect output server_address and local_address
if( !local_address )
return -1;
if( isserv ){
if( port == 0 )
return -1;
if( !hostname )
hostname = "0.0.0.0";
}
else{
if( !hostname || !hostname[0] || port == 0 || !server_address )
return -1;
}
sprintf(service,"%d",port);
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_ADDRCONFIG;
n = getaddrinfo(hostname, service, &hints, &res);
if (n <0 || !res) {
fprintf(stderr,
"getaddrinfo error:: [%s]\n",
gai_strerror(n));
return -1;
}
ressave = res;
do{
// check address
retval = convaddr.FromSockAddr(res->ai_addr,res->ai_addrlen) ? 0 : -1;
if( retval != 0){
continue;
}
int family = convaddr.GetFamily();
if( convaddr.address() == IPAddress::IPv4Localhost()
|| convaddr.address() == IPAddress::IPv6Localhost() ){
if( isserv || family == ADDRESS_FAMILY_IPV6 )
continue;
}
else if( convaddr.address().IsZero() ){
if( !isserv )
continue;
}
// check if socket can success create
sd = socket( family == ADDRESS_FAMILY_IPV6 ? AF_INET6 : AF_INET,SOCK_DGRAM,0);
if( sd == -1 )
continue;
struct sockaddr_storage addr;
socklen_t addrlen = sizeof(addr);
if( isserv ){
retval = convaddr.ToSockAddr((struct sockaddr*)&addr,&addrlen) ? 0 : -1;
if( retval == 0 )
retval = bind(sd,(sockaddr *)&addr,addrlen);
}
else{
IPEndPoint tmpaddr(convaddr.address(),22);
retval = tmpaddr.ToSockAddr((struct sockaddr*)&addr,&addrlen)? 0 : -1;
if( retval == 0 ){
char c = 'c';
retval = sendto(sd,&c,1,0,(struct sockaddr *)&addr,addrlen) == 1 ? 0 : -1;
}
if( retval >= 0 ){
struct sockaddr_storage laddr;
socklen_t address_length = sizeof(laddr);
retval = getsockname(sd,(sockaddr *)&laddr,&address_length);
if( retval == 0 ){
if( !local_address->FromSockAddr((sockaddr *)&laddr,address_length) ){
retval = -1;
}
}
}
}
if( retval == 0 ){
break;
}
NetComm_CloseSocket(sd);
sd = -1;
}while((res = res->ai_next) != NULL);
freeaddrinfo(ressave);
if( retval == 0 ){
if( isserv ){
*local_address = convaddr;
}
else{
*server_address = convaddr;
}
return sd;
}
else{
return -1;
}
}
int NetComm_UDPSend(int sd,const char *buf,int len,const IPEndPoint *peer_address)
{
if( peer_address ){
sockaddr_storage dst;
socklen_t dstlen = sizeof(dst);
if(! peer_address->ToSockAddr((sockaddr *)&dst, &dstlen) ){
RMXQUIC_TRACE_ERROR("serv send fail, addr invalid\n");
return -1;
}
int ret;
WRAP_SYSAPI(ret,sendto(sd,buf,len,0,(struct sockaddr *)&dst,dstlen));
//RMXQUIC_TRACE_FATAL("send %d len %d ret:%d\n",sd,len,ret);
TRACE_UDP(buf,len,&dst,1,ret);
return ret;
}
else{
int ret;
WRAP_SYSAPI(ret, send(sd,buf,len,0));
TRACE_UDP(buf,len,NULL,1,ret);
return ret;
}
}
bool NetComm_Poll(int sd,int timeout_ms)
{
bool haserror = false;
return NetComm_PollEx(sd,timeout_ms,haserror);
}
bool NetComm_PollEx(int sd,int timeout_ms,bool& haserror)
{
int ret = -1;
struct pollfd pfds = {sd,POLLIN_FLAG,0};
WRAP_SYSAPI( ret , poll(&pfds,1,timeout_ms));
if( ret == 1 && IS_POLLIN_OK(pfds.revents ) ){
haserror = false;
return true;
}
haserror = (ret != 0 ); // if not timeout, consider occur error
return false;
}
int NetComm_UDPRecv(int sd,char* buf,size_t maxsz,IPEndPoint *peer_address)
{
if( peer_address ){
sockaddr_storage dst;
socklen_t dstlen = sizeof(dst);
int ret;
WRAP_SYSAPI(ret , recvfrom(sd,buf,maxsz,0,(struct sockaddr *)&dst,&dstlen));
//RMXQUIC_TRACE_FATAL("recv %d len %d \n",sd,ret);
if(! peer_address->FromSockAddr((sockaddr *)&dst, dstlen) ){
RMXQUIC_TRACE_ERROR("serv recv %d fail, addr invalid\n",ret);
return -1;
}
TRACE_UDP(buf,ret,&dst,0,ret);
return ret;
}
else{
int ret;
WRAP_SYSAPI(ret , recv(sd,buf,maxsz,0));
TRACE_UDP(buf,ret,NULL,0,ret);
return ret;
}
}
static int CreateTCP(struct addrinfo *pinfo,
const struct sockaddr *addr,socklen_t addrlen,
bool isbind,int connecttimeout_ms)
{
int sockfd = -1;
if( pinfo ){
sockfd = socket(pinfo->ai_family, pinfo->ai_socktype,
pinfo->ai_protocol);
addr = pinfo->ai_addr;
addrlen = pinfo->ai_addrlen;
}
else{
sockfd = socket(AF_INET, SOCK_STREAM,0);
}
if(sockfd < 0) {
return -1;
}
int on = 1;
if( isbind ){
if( setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) != 0 ){
RMXQUIC_TRACE_WARNING( "tcp reuse port fail\n");
}
if(bind(sockfd, addr, addrlen) == 0
&& listen(sockfd, TCP_DEFAULTBACK_LOG) == 0 ) {
return sockfd;
}
NetComm_CloseSocket(sockfd);
return -1;
}
int sock_opt = 1;
if( connecttimeout_ms != -1){
ioctl(sockfd, FIONBIO, &sock_opt);
}
int connret = connect(sockfd, addr, addrlen);
if( connret == -1 && connecttimeout_ms != -1
&& (errno == EWOULDBLOCK || errno == EINPROGRESS) ){
pollfd pfd;
pfd.fd = sockfd;
pfd.events = POLLOUT;
int error = 0;
socklen_t errorlen = sizeof(error);
int ret = -1;
WRAP_SYSAPI(ret , poll( &pfd, 1, connecttimeout_ms ));
if( ret == 1
&& getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (char *)&error, &errorlen) == 0
&& error == 0 ){
connret = 0;
}
}
if( connret == 0) {
if( connecttimeout_ms != -1){
sock_opt = 0;
ioctl(sockfd, FIONBIO, &sock_opt);
}
setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (void*)&on, sizeof(on)) ;
return sockfd;
}
NetComm_CloseSocket(sockfd);
return -1;
}
int RMXCQuic_TCPAccept(int ld,sockaddr_storage* dst)
{
if( ld == -1 )
return -1;
sockaddr_storage tmp;
if( !dst ) dst = &tmp;
int sd = -1;
while(1){
socklen_t len = sizeof(tmp);
sd = accept(ld,(struct sockaddr *)dst,&len);
if( sd >= 0 )
break;
if( sd == -1 ){
if( errno == EINTR )
continue;
else
return -1;
}
}
int flag = 1;
int ret = setsockopt( sd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag) );
if (ret == -1) {
RMXQUIC_TRACE_WARNING("Couldn't setsockopt(TCP_NODELAY)\n");
}
return sd;
}
bool NetComm_TCPGetLocalPort(int sd,uint16_t& port)
{
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
memset(&addr,0,sizeof(addr));
port = 0;
if( getsockname(sd, (struct sockaddr*) &addr, &len) != 0) {
return false;
}
port = htons(addr.sin_port);
return true;
}
int NetComm_TCPCreate(const char *serv,uint16_t port,bool isbind,int connecttimeout_ms)
{
int sockfd = -1;
char portstr[32];
struct addrinfo hints, *res, *ressave;
if( serv && *serv && inet_addr(serv) == inet_addr("127.0.0.1")){
struct sockaddr_in addr;
memset(&addr,0,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(serv);
return CreateTCP(NULL,(const sockaddr *)&addr,sizeof(addr),isbind,connecttimeout_ms);
}
bzero(&hints, sizeof(struct addrinfo));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if( isbind ){
hints.ai_flags = AI_PASSIVE;
}
else{
if( !serv || !serv[0] ){
RMXQUIC_TRACE_WARNING( "SockAPI_Create param error for %s:%d bind:%d\n",serv ? serv: "NULL",port,isbind);
return -1;
}
}
sprintf(portstr,"%d",port);
int ret = getaddrinfo(serv, portstr, &hints, &res);
if( ret != 0) {
RMXQUIC_TRACE_WARNING( "SockAPI_Create getaddr fail for %s:%d bind:%d\n",serv ? serv: "NULL",port,isbind);
return -1;
}
ressave = res;
do {
struct sockaddr_in* paddr = (struct sockaddr_in*)res->ai_addr;
if( isbind ){
if( paddr->sin_addr.s_addr == htonl(0x7f000001))
continue;
}
else{
if( paddr->sin_addr.s_addr == 0)
continue;
}
sockfd = CreateTCP(res,NULL,0,isbind,connecttimeout_ms);
if(sockfd >= 0) {
break;
}
}while((res = res->ai_next) != NULL);
freeaddrinfo(ressave);
if( sockfd >= 0 )
return sockfd;
RMXQUIC_TRACE_WARNING( "SockAPI_Create fatal create fail for %s:%d bind:%d\n",serv ? serv: "NULL",port,isbind);
return -1;
}
bool NetComm_RecvN(int sd,char* p, size_t size,int timeout_ms,uint16_t interval_wait_ms){
if( sd < 0 )
return false;
while( size > 0 ){
int ret;
if( timeout_ms != -1 ){
if( !NetComm_Poll(sd,timeout_ms) )
return false;
timeout_ms = interval_wait_ms;
}
WRAP_SYSAPI( ret , recv(sd,p,size,0) );
if( ret <= 0 ){
RMXQUIC_TRACE_WARNING( " %d recv data error, ret: %d,errno:%d\n" ,sd,ret , errno);
return false;
}
size -= ret;
p += ret;
}
return true;
}
bool NetComm_SendN(int sd,const char* p, size_t size){
if( sd < 0 )
return false;
while( size > 0 ){
int ret;
WRAP_SYSAPI( ret , send(sd,p,size,0) );
if( ret <= 0 ){
RMXQUIC_TRACE_WARNING( " %d send data error, ret: %d,errno:%d\n" ,sd,ret , errno);
return false;
}
size -= ret;
p += ret;
}
return true;
}
bool NetComm_StartTask(pthread_t *thrid,void* (*start_routine)(void*),void *arg)
{
pthread_t slave_tid;
int ret = pthread_create(thrid ? thrid : &slave_tid, NULL, start_routine, arg);
if( ret == 0 && !thrid )
pthread_detach(slave_tid);
return ret == 0;
}
static int Rsa2String(RSA *r,std::string& out,bool isPublic)
{
//bp_private = BIO_new_file(RSA_PRIV_FILE, "w+");
BIO* bp = BIO_new(BIO_s_mem());
int ret = isPublic ? PEM_write_bio_RSAPublicKey(bp, r) :
PEM_write_bio_RSAPrivateKey(bp, r, NULL, NULL, 0, NULL, NULL);;
if(ret != 1){
out.clear();
BIO_free_all(bp);
return 0;
}
int keylen = BIO_pending(bp);
char *buf = new char[keylen+1];
BIO_read(bp,buf , keylen);
buf[keylen] = 0;
out.assign(buf,keylen+1);
delete[] buf;
BIO_free_all(bp);
return 1;
}
bool NetComm_RSAGenKey(std::string& priv,std::string& pub){
priv.clear();
pub.clear();
RSA *r = NULL;
// 1. generate rsa key
BIGNUM* bne = BN_new();
int ret = BN_set_word(bne,RSA_F4);
if(ret != 1){
goto free_all;
}
r = RSA_new();
ret = RSA_generate_key_ex(r, 2048, bne, NULL);
if(ret != 1){
goto free_all;
}
// 2. save public key
// 3. save private key
ret = Rsa2String(r,priv,false);
if( ret == 1 ){
ret = Rsa2String(r,pub,true);
if( ret != 1 ){
priv.clear();
}
}
// 4. free
free_all:
RSA_free(r);
BN_free(bne);
/* //// ONLY CHECK RSA SIGN/VERIFY FUNCTION
std::string sign;
const char* data = "hellpafafasfasfadsasfsdafafasdfsdagfgfafgadsfasfasdfadf";
int ret1 = NetComm_RSASign(sign,data,strlen(data),priv.data(),priv.size());
int ret2 = NetComm_RSAVerify(sign,data,strlen(data),pub.data(),pub.size());
*/
return (ret == 1);
}
int NetComm_RSA256Hash(unsigned char hash[32],const char *string, int len)
{
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, string, len);
SHA256_Final(hash, &sha256);
return 0;
}
int NetComm_RSASign(std::string &sign,const char *data, int dataLen,const char *privkey, int privkeylen)
{
if( !data || dataLen <= 0 || !privkey || privkeylen <= 0 )
return -1;
unsigned char hash[SHA256_DIGEST_LENGTH];
unsigned char signature[2048/8];
unsigned int signatureLength;
int sigret = 0;
SHA256( (unsigned char *)data,dataLen, hash );
BIO *mem = BIO_new_mem_buf((void *)privkey, privkeylen);
if (mem != NULL){
RSA *rsa_private = PEM_read_bio_RSAPrivateKey(mem, NULL, NULL, NULL);
if (rsa_private != NULL
&& RSA_check_key(rsa_private) != 0 ){
sigret = RSA_sign( NID_sha256, hash, SHA256_DIGEST_LENGTH, signature, &signatureLength, rsa_private );
if( sigret == 1 )
sign.assign((char *)signature,signatureLength);
}
if( rsa_private )
RSA_free(rsa_private);
BIO_free (mem);
}
return sigret == 1 ? 0 : -1;
}
int NetComm_RSAVerify(const std::string &sign,const char *data, int dataLen,const char *pubkey, int pubkeylen)
{
if( !data || dataLen <= 0 || !pubkey || pubkeylen <= 0 )
return -1;
unsigned char hash[SHA256_DIGEST_LENGTH];
int sigret = 0;
SHA256( (unsigned char *)data,dataLen, hash );
BIO *mem = BIO_new_mem_buf((void*)pubkey, pubkeylen);
if (mem != NULL){
RSA *rsa_public = PEM_read_bio_RSAPublicKey(mem, NULL, NULL, NULL);
if (rsa_public != NULL ){
sigret = RSA_verify( NID_sha256, hash, SHA256_DIGEST_LENGTH, (const unsigned char *)sign.data(), sign.size(), rsa_public );
}
if( rsa_public )
RSA_free(rsa_public);
BIO_free (mem);
}
return sigret == 1 ? 0 : -1;
}
#if( RMXUDP_SSLMODE == 0 )
#define OPENSSL_PRN_INFO(fmt,arg...) //RMXQUIC_TRACE_INFO(fmt,##arg)
static int gcmdeccnt = 0;
static int gcmenccnt = 0;
#define OPENSSL_PRN_ERROR(fmt,arg...) { \
char buf[256] = ""; unsigned long err = ERR_get_error(); \
RMXQUIC_TRACE_WARNING( fmt " err:%lu dec/enc:%d/%d <%s>\n",##arg,err,gcmdeccnt,gcmenccnt,ERR_error_string(err,buf)); \
}
#define OPENSSL_PUT_ERROR(x,y) OPENSSL_PRN_ERROR( #x " " #y "dec/enc:%d/%d \n",gcmdeccnt,gcmenccnt)
int NetComm_GCMEncrypt(const unsigned char *plaintext, int plaintext_len, const unsigned char *aad,
int aad_len, const unsigned char *key,const unsigned char *iv,int iv_len,
unsigned char *ciphertext,int taglen)
{
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())){
OPENSSL_PRN_ERROR("create ctx fail\n");
return -1;
}
/* Initialise the encryption operation. */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL)){
EVP_CIPHER_CTX_free(ctx);
OPENSSL_PRN_ERROR("init ctx fail\n");
return -1;
}
/* Set IV length if default 12 bytes (96 bits) is not appropriate */
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv_len, NULL)){
EVP_CIPHER_CTX_free(ctx);
OPENSSL_PRN_ERROR("EVP_CTRL_GCM_SET_IVLEN fail\n");
return -1;
}
/* Initialise key and IV */
if(1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)){
EVP_CIPHER_CTX_free(ctx);
OPENSSL_PRN_ERROR("EVP_CTRL_GCM_SET_IV + key fail\n");
return -1;
}
/* Provide any AAD data. This can be called zero or more times as
* required
*/
if( aad && aad_len > 0 ){
if(1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len)){
EVP_CIPHER_CTX_free(ctx);
OPENSSL_PRN_ERROR("EVP_EncryptUpdate NULL fail\n");
return -1;
}
}
OPENSSL_PRN_INFO("enc: %d out: txtlen %d + %d aad:%d \n", plaintext_len,ciphertext_len,len,aad_len);
/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)){
EVP_CIPHER_CTX_free(ctx);
OPENSSL_PRN_ERROR("EVP_EncryptUpdate txt fail\n");
return -1;
}
ciphertext_len = len;
/* Finalise the encryption. Normally ciphertext bytes may be written at
* this stage, but this does not occur in GCM mode
*/
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)){
EVP_CIPHER_CTX_free(ctx);
OPENSSL_PRN_ERROR("EVP_EncryptFinal_ex fail\n");
return -1;
}
OPENSSL_PRN_INFO("enc:%s %d out: txtlen %d + %d\n",plaintext, plaintext_len,ciphertext_len,len);
ciphertext_len += len;
/* Get the tag */
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, taglen, ciphertext + ciphertext_len )){
EVP_CIPHER_CTX_free(ctx);
OPENSSL_PRN_ERROR("EVP_CTRL_GCM_GET_TAG fail\n");
return -1;
}
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
gcmenccnt ++;
return ciphertext_len + taglen;
}
int NetComm_GCMDecrypt(const unsigned char *ciphertext, int ciphertext_len, const unsigned char *aad,
int aad_len,const unsigned char *key, const unsigned char *iv,int iv_len,
unsigned char *plaintext,int taglen)
{
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
int ret;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())){
OPENSSL_PRN_ERROR("EVP_CIPHER_CTX_new fail\n");
return -1;
}
/* Initialise the decryption operation. */
if(!EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL)){
EVP_CIPHER_CTX_free(ctx);
OPENSSL_PRN_ERROR("EVP_DecryptInit_ex fail\n");
return -1;
}
/* Set IV length. Not necessary if this is 12 bytes (96 bits) */
if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv_len, NULL)){
EVP_CIPHER_CTX_free(ctx);
OPENSSL_PRN_ERROR("EVP_CTRL_GCM_SET_IVLEN fail\n");