-
Notifications
You must be signed in to change notification settings - Fork 8
/
Network.cpp
1250 lines (943 loc) · 29.9 KB
/
Network.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
#include "Kangaroo.h"
#include <fstream>
#include "SECPK1/IntGroup.h"
#include "Timer.h"
#include <string.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <algorithm>
#include <signal.h>
#ifndef WIN64
#include <pthread.h>
#else
#include "WindowsErrors.h"
#endif
using namespace std;
static SOCKET serverSock = 0;
// ------------------------------------------------------------------------------------------------------
// Common part
// ------------------------------------------------------------------------------------------------------
#define MAX_CLIENT 256
#define WAIT_FOR_READ 1
#define WAIT_FOR_WRITE 2
#define SERVER_VERSION 3
#define SERVER_HEADER 0x67DEDDC1
#define KANG_PER_BLOCK 2048
// Commands
#define SERVER_GETCONFIG 0
#define SERVER_STATUS 1
#define SERVER_SENDDP 2
#define SERVER_SETKNB 3
#define SERVER_SAVEKANG 4
#define SERVER_LOADKANG 5
#define SERVER_RESETDEAD 'R'
// Status
#define SERVER_OK 0
#define SERVER_END 1
#define SERVER_BACKUP 2
#ifdef WIN64
#define close_socket(s) closesocket(s)
typedef int socklen_t;
string GetNetworkError() {
int err = WSAGetLastError();
bool found = false;
int i=0;
while(!found && i<NBWSAERRORS) {
found = (WSAERRORS[i].errCode == err);
if(!found) i++;
}
if(!found) {
char ret[256];
sprintf(ret,"WSA Error code %d",err);
return string(ret);
} else {
return string(WSAERRORS[i].mesg);
}
}
#else
#define close_socket(s) close(s)
string GetNetworkError() {
return string(strerror(errno));
}
#endif
#define GET(name,s,b,bl,t) if( (nbRead=Read(s,(char *)(b),bl,t))<0 ) { ::printf("\nReadError(" name "): %s\n",lastError.c_str()); isConnected = false; close_socket(s); return false; }
#define PUT(name,s,b,bl,t) if( (nbWrite=Write(s,(char *)(b),bl,t))<0 ) { ::printf("\nWriteError(" name "): %s\n",lastError.c_str()); isConnected = false; close_socket(s); return false; }
#define GETFREE(name,s,b,bl,t,x) if( (nbRead=Read(s,(char *)(b),bl,t))<0 ) { ::printf("\nReadError(" name "): %s\n",lastError.c_str()); isConnected = false; ::free(x); close_socket(s); return false; }
#define PUTFREE(name,s,b,bl,t,x) if( (nbWrite=Write(s,(char *)(b),bl,t))<0 ) { ::printf("\nWriteError(" name "): %s\n",lastError.c_str()); isConnected = false; ::free(x); close_socket(s); return false; }
void sig_handler(int signo) {
if(signo == SIGINT) {
::printf("\nTerminated\n");
if(serverSock>0) close_socket(serverSock);
#ifdef WIN64
WSACleanup();
#endif
exit(0);
}
}
int Kangaroo::WaitFor(SOCKET sock,int timeout,int mode) {
fd_set fdset;
fd_set *rd = NULL,*wr = NULL;
struct timeval tmout;
int result;
FD_ZERO(&fdset);
FD_SET(sock,&fdset);
if(mode == WAIT_FOR_READ)
rd = &fdset;
if(mode == WAIT_FOR_WRITE)
wr = &fdset;
tmout.tv_sec = (int)(timeout / 1000);
tmout.tv_usec = (int)(timeout % 1000) * 1000;
do
result = select((int)sock + 1,rd,wr,NULL,&tmout);
#ifdef WIN64
while(result < 0 && WSAGetLastError() == WSAEINTR);
#else
while(result < 0 && errno == EINTR);
#endif
if(result == 0) {
lastError = "The operation timed out";
} else if(result < 0) {
lastError = GetNetworkError();
return 0;
}
return result;
}
int Kangaroo::Write(SOCKET sock,char *buf,int bufsize,int timeout) {
int total_written = 0;
int written = 0;
while(bufsize > 0)
{
// Wait
if(!WaitFor(sock,timeout,WAIT_FOR_WRITE))
return -1;
// Write
do
written = send(sock,buf,bufsize,0);
#ifdef WIN64
while(written == -1 && WSAGetLastError() == WSAEINTR);
#else
while(written == -1 && errno == EINTR);
#endif
if(written <= 0)
break;
buf += written;
total_written += written;
bufsize -= written;
}
if(written < 0) {
lastError = GetNetworkError();
return -1;
}
if(bufsize != 0) {
lastError = "Failed to send entire buffer";
return -1;
}
return total_written;
}
int Kangaroo::Read(SOCKET sock,char *buf,int bufsize,int timeout) { // Timeout in millisec
int rd = 0;
int total_read = 0;
while( bufsize>0 ) {
// Wait
if(!WaitFor(sock,timeout,WAIT_FOR_READ)) {
return -1;
}
// Read
do
rd = recv(sock,buf,bufsize,0);
#ifdef WIN64
while(rd == -1 && WSAGetLastError() == WSAEINTR);
#else
while(rd == -1 && errno == EINTR);
#endif
if( rd <= 0 )
break;
buf += rd;
total_read += rd;
bufsize -= rd;
}
if(rd < 0) {
lastError = GetNetworkError();
return -1;
}
if(rd == 0) {
lastError = "Connection closed";
return -1;
}
return total_read;
}
void Kangaroo::InitSocket() {
#ifdef WIN64
// connect to Winscok DLL
WSADATA WSAData;
int err = WSAStartup(MAKEWORD(2,2),&WSAData);
if(err != 0) {
::printf("WSAStartup failed error : %d\n",err);
exit(-1);
}
#endif
}
// ------------------------------------------------------------------------------------------------------
// Server part
// ------------------------------------------------------------------------------------------------------
// Server status
int32_t Kangaroo::GetServerStatus() {
if(endOfSearch) {
return SERVER_END;
}
if(saveRequest) {
return SERVER_BACKUP;
}
return SERVER_OK;
}
#define CLIENT_ABORT() \
::printf("\nClosing connection with %s\n",p->clientInfo); \
close_socket(p->clientSock); \
return false;
// Server request handler
bool Kangaroo::HandleRequest(TH_PARAM *p) {
char cmdBuff;
uint32_t version = SERVER_VERSION;
int nbRead;
int nbWrite;
int32_t state;
while( p->isRunning ) {
// Wait for command (1h timeout)
nbRead = Read(p->clientSock,(char *)(&cmdBuff),1,(int)(CLIENT_TIMEOUT*1000.0));
if(nbRead<=0) {
CLIENT_ABORT();
}
switch(cmdBuff) {
// ----------------------------------------------------------------------------------------
case SERVER_GETCONFIG: {
::printf("\nNew connection from %s\n",p->clientInfo);
// Send config to the client
PUT("Version",p->clientSock,&version,sizeof(uint32_t),ntimeout);
PUT("RangeStart",p->clientSock,rangeStart.bits64,32,ntimeout);
PUT("RangeEnd",p->clientSock,rangeEnd.bits64,32,ntimeout);
PUT("KeyX",p->clientSock,keysToSearch[keyIdx].x.bits64,32,ntimeout);
PUT("KeyY",p->clientSock,keysToSearch[keyIdx].y.bits64,32,ntimeout);
PUT("DP",p->clientSock,&initDPSize,sizeof(int32_t),ntimeout);
} break;
// ----------------------------------------------------------------------------------------
case SERVER_SETKNB: {
GET("nbKangaroo",p->clientSock,&p->nbKangaroo,sizeof(uint64_t),ntimeout);
totalRW += p->nbKangaroo;
} break;
// ----------------------------------------------------------------------------------------
case SERVER_RESETDEAD: {
char response[5];
collisionInSameHerd = 0;
GET("flush",p->clientSock,&response,2,ntimeout);
sprintf(response,"OK\n");
PUT("resp",p->clientSock,&response,3,ntimeout);
} break;
// ----------------------------------------------------------------------------------------
case SERVER_LOADKANG: {
Int checkSum;
Int K;
uint64_t nbKangaroo = 0;
uint32_t strSize;
char fileName[256];
int256_t* KBuff;
uint32_t nbK;
uint32_t header = HEADKS;
uint32_t version = 0;
GET("fileNameLenght",p->clientSock,&strSize,sizeof(uint32_t),ntimeout);
if(strSize >= 256) {
::printf("\nFileName too long (MAX=256) %s\n",p->clientInfo);
CLIENT_ABORT();
}
GET("fileName",p->clientSock,&fileName,strSize,ntimeout);
fileName[strSize] = 0;
FILE* f = fopen(fileName,"rb");
if(f == NULL) {
// No backup
::printf("LoadKang: Cannot open %s for reading\n",fileName);
::printf("%s\n",::strerror(errno));
PUT("nbKangaroo",p->clientSock,&nbKangaroo,sizeof(uint64_t),ntimeout);
break;
}
if(::fread(&header,sizeof(uint32_t),1,f) != 1) {
::printf("LoadKang: Cannot read from %s\n",fileName);
::printf("%s\n",::strerror(errno));
::fclose(f);
CLIENT_ABORT();
}
if(header!=HEADKS) {
::printf("LoadKang: %s Not a compressed kangaroo file\n",fileName);
::printf("%s\n",::strerror(errno));
::fclose(f);
CLIENT_ABORT();
}
::fread(&version,sizeof(uint32_t),1,f);
::fread(&nbKangaroo,sizeof(uint64_t),1,f);
PUT("nbKangaroo",p->clientSock,&nbKangaroo,sizeof(uint64_t),ntimeout);
checkSum.SetInt32(0);
KBuff = (int256_t*)malloc(KANG_PER_BLOCK * sizeof(int256_t));
while(nbKangaroo > 0) {
if(nbKangaroo > KANG_PER_BLOCK) {
nbK = KANG_PER_BLOCK;
} else {
nbK = (uint32_t)nbKangaroo;
}
for(uint32_t k = 0; k < nbK; k++) {
::fread(&KBuff[k],32,1,f);
// Checksum
K.SetInt32(0);
K.bits64[3] = KBuff[k].i64[3];
K.bits64[2] = KBuff[k].i64[2];
K.bits64[1] = KBuff[k].i64[1];
K.bits64[0] = KBuff[k].i64[0];
checkSum.Add(&K);
}
PUTFREE("packet",p->clientSock,KBuff,nbK * 32,ntimeout,KBuff);
nbKangaroo -= nbK;
}
free(KBuff);
PUT("checkSum",p->clientSock,checkSum.bits64,32,ntimeout);
::fclose(f);
} break;
// ----------------------------------------------------------------------------------------
case SERVER_SAVEKANG: {
Int checkSum;
Int K;
uint64_t nbKangaroo;
uint32_t fileNameSize;
char fileNameTmp[264];
char fileName[256];
int256_t *KBuff;
uint32_t nbK;
uint32_t header = HEADKS;
uint32_t version = 0;
GET("fileNameLenght",p->clientSock,&fileNameSize,sizeof(uint32_t),ntimeout);
if(fileNameSize >= 256) {
::printf("\nFileName too long (MAX=256) %s\n",p->clientInfo);
CLIENT_ABORT();
}
GET("fileName",p->clientSock,&fileName,fileNameSize,ntimeout);
fileName[fileNameSize]=0;
GET("nbKangaroo",p->clientSock,&nbKangaroo,sizeof(uint64_t),ntimeout);
strcpy(fileNameTmp,fileName);
strcat(fileNameTmp,".tmp");
FILE* f = fopen(fileNameTmp,"wb");
if(f == NULL) {
::printf("\nCannot open %s for writing\n",fileNameTmp);
::printf("%s\n",::strerror(errno));
CLIENT_ABORT();
}
if(::fwrite(&header,sizeof(uint32_t),1,f) != 1) {
::printf("\nCannot write to %s\n",fileNameTmp);
::printf("%s\n",::strerror(errno));
::fclose(f);
CLIENT_ABORT();
}
::fwrite(&version,sizeof(uint32_t),1,f);
::fwrite(&nbKangaroo,sizeof(uint64_t),1,f);
checkSum.SetInt32(0);
KBuff = (int256_t *)malloc(KANG_PER_BLOCK*sizeof(int256_t));
while(nbKangaroo>0) {
if(nbKangaroo> KANG_PER_BLOCK) {
nbK = KANG_PER_BLOCK;
} else {
nbK = (uint32_t)nbKangaroo;
}
GETFREE("packet",p->clientSock,KBuff,nbK * 32,ntimeout,KBuff);
for(uint32_t k = 0; k < nbK; k++) {
::fwrite(&KBuff[k],32,1,f);
// Checksum
K.SetInt32(0);
K.bits64[3] = KBuff[k].i64[3];
K.bits64[2] = KBuff[k].i64[2];
K.bits64[1] = KBuff[k].i64[1];
K.bits64[0] = KBuff[k].i64[0];
checkSum.Add(&K);
}
nbKangaroo -= nbK;
}
free(KBuff);
::fclose(f);
K.SetInt32(0);
GET("checksum",p->clientSock,K.bits64,32,ntimeout);
if(!K.IsEqual(&checkSum)) {
::printf("\nWarning, Kangaroo backup wrong checksum %s\n",fileName);
} else {
remove(fileName);
rename(fileNameTmp,fileName);
}
} break;
case SERVER_STATUS: {
state = GetServerStatus();
PUT("Status",p->clientSock,&state,sizeof(int32_t),ntimeout);
} break;
// ----------------------------------------------------------------------------------------
case SERVER_SENDDP: {
DPHEADER head;
GET("DPHeader",p->clientSock,&head,sizeof(DPHEADER),ntimeout);
if(head.header != SERVER_HEADER) {
::printf("\nUnexpected DP header from %s\n",p->clientInfo);
CLIENT_ABORT();
}
if(head.nbDP == 0) {
::printf("\nUnexpected number of DP [%d] from %s\n",head.nbDP,p->clientInfo);
CLIENT_ABORT();
} else {
//::printf("%d DP from %s\n",nbDP,p->clientInfo.c_str());
DP *dp = (DP *)malloc(sizeof(DP)* head.nbDP);
GETFREE("DP",p->clientSock,dp,sizeof(DP)* head.nbDP,ntimeout,dp);
state = GetServerStatus();
PUTFREE("Status",p->clientSock,&state,sizeof(int32_t),ntimeout,dp);
if(nbRead != sizeof(DP)* head.nbDP) {
::printf("\nUnexpected DP size from %s [nbDP=%d,Got %d,Expected %d]\n",
p->clientInfo,head.nbDP,nbRead,(int)(sizeof(DP)* head.nbDP));
free(dp);
CLIENT_ABORT();
} else {
//#define VALIDITY_POINT_CHECK
#ifdef VALIDITY_POINT_CHECK
// Check validity
for(uint32_t i=0;i< head.nbDP;i++) {
uint64_t h = (uint64_t)dp[i].h;
if(h >= HASH_SIZE) {
::printf("\nInvalid data from: %s [dp=%d PID=%u thId=%u gpuId=%u]\n",p->clientInfo,i,
head.processId,head.threadId,head.gpuId);
free(dp);
CLIENT_ABORT();
}
Int dist;
uint32_t kType;
HashTable::CalcDistAndType(dp[i].d,&dist,&kType);
Point P = secp->ComputePublicKey(&dist);
if(kType == WILD)
P = secp->AddDirect(keyToSearch,P);
uint32_t hC = dp[i].h & HASH_MASK;
bool ok = (hC == h) && (P.x.bits64[0] == dp[i].x.i64[0]) && (P.x.bits64[1] == dp[i].x.i64[1]) &&
(P.x.bits64[2] == dp[i].x.i64[2]) && (P.x.bits64[3] == dp[i].x.i64[3]);
if(!ok) {
if(kType==TAME) {
::printf("\nWrong TAME point from: %s [dp=%d PID=%u thId=%u gpuId=%u]\n",p->clientInfo,i,
head.processId,head.threadId,head.gpuId);
} else {
::printf("\nWrong WILD point from: %s [dp=%d PID=%u thId=%u gpuId=%u]\n",p->clientInfo,i,
head.processId,head.threadId,head.gpuId);
}
//::printf("X=%s\n",P.x.GetBase16().c_str());
//::printf("X=%08X%08X%08X%08X\n",dp[i].x.i32[3],dp[i].x.i32[2],dp[i].x.i32[1],dp[i].x.i32[0]);
//::printf("D=%08X%08X%08X%08X\n",dp[i].d.i32[3],dp[i].d.i32[2],dp[i].d.i32[1],dp[i].d.i32[0]);
free(dp);
CLIENT_ABORT();
}
}
#endif
LOCK(ghMutex);
DP_CACHE dc;
dc.nbDP = head.nbDP;
dc.dp = dp;
recvDP.push_back(dc);
UNLOCK(ghMutex);
}
}
} break;
default:
::printf("\nUnexpected command [%d] from %s\n",cmdBuff,p->clientInfo);
CLIENT_ABORT();
}
}
close_socket(p->clientSock);
return true;
}
// Threaded proc
#ifdef WIN64
DWORD WINAPI _acceptThread(LPVOID lpParam) {
#else
void *_acceptThread(void *lpParam) {
#endif
TH_PARAM *p = (TH_PARAM *)lpParam;
p->obj->AddConnectedClient();
p->obj->HandleRequest(p);
p->obj->RemoveConnectedClient();
p->obj->RemoveConnectedKangaroo(p->nbKangaroo);
p->isRunning = false;
free(p->clientInfo);
free(p);
return 0;
}
#ifdef WIN64
DWORD WINAPI _processServer(LPVOID lpParam) {
#else
void *_processServer(void *lpParam) {
#endif
Kangaroo *obj = (Kangaroo *)lpParam;
obj->ProcessServer();
return 0;
}
// Main server loop
void Kangaroo::AcceptConnections(SOCKET server_soc) {
SOCKET clientSock;
::printf("Kangaroo server is ready and listening to TCP port %d ...\n",port);
while(true) {
struct sockaddr_in client_add;
socklen_t len = sizeof(sockaddr_in);
if((clientSock = accept(server_soc,(struct sockaddr*)&client_add,&len)) < 0) {
::printf("Error: Invalid Socket returned by accept(): %s\n",GetNetworkError().c_str());
} else {
TH_PARAM *p = (TH_PARAM *)malloc(sizeof(TH_PARAM));
::memset(p,0,sizeof(TH_PARAM));
char info[256];
::sprintf(info,"%s:%d",inet_ntoa(client_add.sin_addr),ntohs(client_add.sin_port));
#ifdef WIN64
p->clientInfo = ::_strdup(info);
#else
p->clientInfo = ::strdup(info);
#endif
p->obj = this;
p->isRunning = true;
p->clientSock = clientSock;
LaunchThread(_acceptThread,p);
}
}
}
// Starts the server
void Kangaroo::RunServer() {
if(signal(SIGINT,sig_handler) == SIG_ERR)
::printf("\nWarning:can't install singal handler\n");
// Set starting parameters
InitRange();
InitSearchKey();
ComputeExpected((double)initDPSize,&expectedNbOp,&expectedMem);
::printf("Expected operations: 2^%.2f\n",log2(expectedNbOp));
::printf("Expected RAM: %.1fMB\n",expectedMem);
if(initDPSize<0) {
::printf("Error: Server must be launched with a specified number of distinguished bits (-d)\n");
exit(-1);
}
SetDP(initDPSize);
if(sizeof(DP) != 72) {
::printf("Error: Invalid DP size struct\n");
exit(-1);
}
if(sizeof(DPHEADER) != 20) {
::printf("Error: Invalid DPHEADER size struct\n");
exit(-1);
}
if(saveKangaroo) {
::printf("Waring: Server does not support -ws, ignoring\n");
saveKangaroo = false;
}
// Main thread of server (handle backup and collision check)
LaunchThread(_processServer,(TH_PARAM *)this);
Timer::SleepMillis(100);
// Server stuff
InitSocket();
/* Create socket */
serverSock = socket(AF_INET,SOCK_STREAM,0);
if(serverSock<0) {
::printf("Error: Invalid socket : %s\n",GetNetworkError().c_str());
exit(-1);
}
struct sockaddr_in soc_addr;
/* Reuse Address */
int32_t yes = 1;
if(setsockopt(serverSock,SOL_SOCKET,SO_REUSEADDR,(char *)&yes,sizeof(yes)) < 0) {
::printf("Warning: Couldn't Reuse Address: %s\n",GetNetworkError().c_str());
}
memset(&soc_addr,0,sizeof(soc_addr));
soc_addr.sin_family = AF_INET;
soc_addr.sin_port = htons(port);
soc_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(serverSock,(struct sockaddr*)&soc_addr,sizeof(soc_addr))) {
::printf("Error: Can not bind socket. Another server running?\n%s\n",GetNetworkError().c_str());
exit(-1);
}
if(listen(serverSock,MAX_CLIENT)<0) {
::printf("Error: Can not listen to socket\n%s\n",GetNetworkError().c_str());
exit(-1);
}
AcceptConnections(serverSock);
#ifdef WIN64
WSACleanup();
#endif
return;
}
// ------------------------------------------------------------------------------------------------------
// Client part
// ------------------------------------------------------------------------------------------------------
// Connection to the server
bool Kangaroo::ConnectToServer(SOCKET *retSock) {
lastError = "";
// Resolve IP
if(!hostInfo) {
if(signal(SIGINT,sig_handler) == SIG_ERR)
::printf("\nWarning:can't install singal handler\n");
InitSocket();
struct hostent *host_info;
host_info = gethostbyname(serverIp.c_str());
if(host_info == NULL) {
lastError = "Unknown host:" + serverIp;
hostInfo = NULL;
hostInfoLength = 0;
return false;
} else {
hostInfoLength = host_info->h_length;
hostInfo = (char *)malloc(hostInfoLength);
::memcpy(hostInfo,host_info->h_addr,hostInfoLength);
hostAddrType = host_info->h_addrtype;
}
}
struct sockaddr_in server;
// Build TCP connection
SOCKET sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sock < 0) {
lastError = "Socket error: " + GetNetworkError();
return false;
}
// Use non blocking socket
#ifdef WIN64
unsigned long iMode = 0;
if(ioctlsocket(sock,FIONBIO,&iMode) != 0) {
#else
if(fcntl(sock,F_SETFL,O_NONBLOCK) == -1) {
#endif
lastError = "Cannot use non blocking socket, " + GetNetworkError();
close_socket(sock);
return false;
}
// Connect
::memset(&server,0,sizeof(sockaddr_in));
server.sin_family = hostAddrType;
::memcpy((char*)&server.sin_addr,hostInfo,hostInfoLength);
server.sin_port = htons(port);
int connectStatus = connect(sock,(struct sockaddr *)&server,sizeof(server));
#ifdef WIN64
if((connectStatus < 0) && (WSAGetLastError() != WSAEINPROGRESS)) {
#else
if((connectStatus < 0) && (errno != EINPROGRESS)) {
#endif
lastError = "Cannot connect to host: " + GetNetworkError();
close_socket(sock);
return false;
}
if(connectStatus<0) {
// Wait for connection
if(!WaitFor(sock,ntimeout,WAIT_FOR_WRITE)) {
lastError = "Cannot connect, unreachable host " + serverIp;
close_socket(sock);
return false;
}
// Check connection completion
int socket_err;
#ifdef WIN64
int serrlen = sizeof socket_err;
if(getsockopt(sock,SOL_SOCKET,SO_ERROR,(char *)&socket_err,&serrlen) != 0) {
#else
socklen_t serrlen = sizeof(socket_err);
if(getsockopt(sock,SOL_SOCKET,SO_ERROR,&socket_err,&serrlen) == -1) {
#endif
lastError = "Cannot connect to host: " + GetNetworkError();
close_socket(sock);
return false;
}
if(socket_err != 0) {
lastError = "Cannot connect to host: " + string(strerror(socket_err));
close_socket(sock);
return false;
}
}
int on = 1;
if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,
(const char*)&on,sizeof(on)) == -1) {
lastError = "Socket error: setsockopt error SO_REUSEADDR";
close_socket(sock);
return false;
}
int flag = 1;
struct protoent *p;
p = getprotobyname("tcp");
if(setsockopt(sock,p->p_proto,TCP_NODELAY,(char *)&flag,sizeof(flag)) == -1) {
lastError = "Socket error: setsockopt error TCP_NODELAY";
close_socket(sock);
return false;
}
*retSock = sock;
return true;
}
// Wait while server is not ready
void Kangaroo::WaitForServer() {
int nbRead;
int nbWrite;
int32_t status;
bool ok = false;
while(!ok) {
// Wait for connection
while(!isConnected) {
serverStatus = "Fault";
Timer::SleepMillis(1000);
// Try to reconnect
isConnected = ConnectToServer(&serverConn);
if( isConnected ) {
// Resend kangaroo number
char cmd = SERVER_SETKNB;
nbWrite = Write(serverConn,&cmd,1,ntimeout);
if(nbWrite <= 0) {
if(nbWrite < 0)
::printf("\nSendToServer(SetKNb): %s\n",lastError.c_str());
serverStatus = "Not OK";
close_socket(serverConn);
isConnected = false;
}
nbWrite = Write(serverConn,(char *)&totalRW,sizeof(uint64_t),ntimeout);
if(nbWrite <= 0) {
if(nbWrite < 0)
::printf("\nSendToServer(SetKNb): %s\n",lastError.c_str());
serverStatus = "Not OK";
close_socket(serverConn);
isConnected = false;
}
}
}
// Wait for ready
while(isConnected && !ok) {
char cmd = SERVER_STATUS;
nbWrite = Write(serverConn,&cmd,1,ntimeout);
if( nbWrite<=0 ) {
if(nbWrite<0)
::printf("\nSendToServer(Status): %s\n",lastError.c_str());
serverStatus = "Not OK";
close_socket(serverConn);
isConnected = false;
} else {
nbRead = Read(serverConn,(char *)(&status),sizeof(int32_t),ntimeout);
if( nbRead<=0 ) {
if(nbRead<0)
::printf("\nRecvFromServer(Status): %s\n",lastError.c_str());
serverStatus = "Fault";
close_socket(serverConn);
isConnected = false;
} else {
switch(status) {
case SERVER_OK:
serverStatus = "OK";
ok = true;
break;
case SERVER_END:
serverStatus = "END";
endOfSearch = true;
ok = true;
break;
case SERVER_BACKUP:
serverStatus = "Backup";
Timer::SleepMillis(1000);
break;
}
}
}
}
}
}
// Get Kangaroo from server
bool Kangaroo::GetKangaroosFromServer(std::string& fileName,std::vector<int256_t>& kangs) {
int nbRead;
int nbWrite;
uint32_t fileNameSize = (uint32_t)fileName.length();
uint64_t nbKangaroo = 0;
uint32_t nbK;
int256_t* KBuff;
Int checkSum;
WaitForServer();
if(!endOfSearch) {
char cmd = SERVER_LOADKANG;
PUT("CMD",serverConn,&cmd,1,ntimeout);
PUT("fileNameLenght",serverConn,&fileNameSize,sizeof(uint32_t),ntimeout);
PUT("fileName",serverConn,fileName.c_str(),fileNameSize,ntimeout);
GET("nbKangaroo",serverConn,&nbKangaroo,sizeof(uint64_t),ntimeout);
if(nbRead==0) {
::printf("\nFailed to get %s from server\n",fileName.c_str());
return false;
}
if(nbKangaroo==0) {
return true;
}
uint64_t point = (nbKangaroo / KANG_PER_BLOCK) / 32;
uint64_t pointPrint = 0;