-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurtorrent.cpp
1211 lines (1116 loc) · 35.4 KB
/
urtorrent.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 <openssl/sha.h>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <cstring>
#include <stdlib.h>
#include "bencode.h"
#include "urlcode.h"
#include <ios>
#include <unistd.h>
#include <string.h>
#include <sstream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <random>
#include <vector>
#include <arpa/inet.h>
#include <pthread.h>
#include <functional>
#include <thread>
#include <chrono>
#include <math.h>
#include <curl/curl.h>
using namespace std;
pthread_mutex_t mutex_finish; //I have 3 critical region
pthread_mutex_t mutex_global;
pthread_mutex_t mutex_peers;
pthread_mutex_t mutex_files;
pthread_mutex_t mutex_have;
//global variables
vector<string> peers_ip;
vector<int> peers_port;
vector<int> peers_flag;
vector<long long> peers_down;
vector<long long> peers_up;
vector<vector<int>> peers_have;
int global_bitfield[410];
long long downloaded, uploaded, bytes_left;
int port;
int seeder;
int verbose;
int piece_length;
int piece_num;
int info_length;
int bitfield_num;
unsigned char info_hash[SHA_DIGEST_LENGTH]; //20
void *connection_handler(void *); //to deal with multi-connected
void* socket_handler(void* lp); //to deal with the message
void *send_handler(void *); //to deal with the message
void *establish_handler(void *); //to deal with the message
char* bitfield;
int num_peers;
char peer_id[20];
vector<int> boardcast_have;
char pieces[410][20];
int finish;
string my_ip;
string filename;
string announce, info_name;
//tracker info
int complete, downloaded2, incomplete, interval, min_interval;
string announce_ip;
int announce_port;
bool announcing;
struct Pass {
int portno;
int fd;
};
void error(const char *msg) {
perror(msg);
exit(0);
}
bool fileExists(string file_name) {
ifstream infile(file_name);
return infile.good();
}
bool pieceGood(int index, string p) {
char* piece =(char*) malloc(piece_length);
p.copy(piece, piece_length, 0);
unsigned char info_hash2[SHA_DIGEST_LENGTH];
int remain = info_length-((piece_num-1)*piece_length);
if(index == piece_num-1) {
unsigned char* subbuf = new unsigned char[remain];
memcpy((char*)subbuf, piece, remain);
//cout<<subbuf<<endl;
SHA1(subbuf, remain, info_hash2);
delete[] subbuf;
}
else {
unsigned char* subbuf2 = new unsigned char[piece_length];
memcpy((char*)subbuf2, piece, piece_length);
SHA1(subbuf2, piece_length, info_hash2);
delete[] subbuf2;
}
if(verbose) {
for(int i = 0; i < 20; i++)
printf("%02x", info_hash2[i]);
printf("\n");
for(int j = 0; j < 20; j++)
printf("%02hhx", pieces[index][j]);
printf("\n");
}
if(memcmp(info_hash2, reinterpret_cast<unsigned char*>(pieces[index]), 20) == 0) {
free(piece);
return true;
}
else {
free(piece);
return false;
}
}
string readPiece(string file_name, int index) {
int start, end;
int length;
int remain;
if(index == piece_num-1) {
remain = info_length-((piece_num-1)*piece_length);
length = remain;
//cout<<info_length<<endl;
//cout<<length<<endl;
}
else
length = piece_length;
char* buffer = new char[length];
pthread_mutex_lock(&mutex_files);
ifstream infile(file_name, ios::binary);
if(infile.is_open()) {
start = index*piece_length;
if(index == piece_num-1) {
end = (index)*piece_length + remain;
}
else {
end = (index+1)*piece_length;
}
infile.seekg(start);
infile.read(buffer, end-start);
string str(buffer, length);
delete[] buffer;
//cout<<buffer<<endl;
infile.close();
pthread_mutex_unlock(&mutex_files);
return str;
}
else {
error("ERROR reading piece from file");
}
}
void writePiece(string file_name, int index, string p) {
char* piece = (char*)malloc(piece_length);
p.copy(piece, piece_length, 0);
if(fileExists(file_name)) {
ofstream outfile;
int start, end;
pthread_mutex_lock(&mutex_files);
outfile.open(file_name, ios::binary | ios::out | ios::in);
start = index*piece_length;
int remain = info_length-((piece_num-1)*piece_length);
if(index == piece_num-1) {
end = (index)*piece_length + remain;
//cout<<index<<" "<<remain<<" "<<end<<endl;
outfile.seekp(start);
outfile.write(piece, end-start);
//cout<<"last piece"<<endl;
}
else {
end = (index+1)*piece_length;
outfile.seekp(start);
outfile.write(piece, end-start);
}
outfile.close();
pthread_mutex_unlock(&mutex_files);
}
}
void createFile(string file_name, int file_size) {
vector<char> empty(1, 0);
ofstream outfile(file_name, ios::binary | ios::out);
if(!outfile) {
error("ERROR creating file");
}
for(int i = 0; i < file_size; i++) {
if(!outfile.write(&empty[0], empty.size())) {
error("ERROR writing to file");
}
}
outfile.close();
}
bool checkFile(string file_name) {
bytes_left = info_length;
int length;
int remain = info_length-((piece_num-1)*piece_length);
bool is_complete = true;
for(int i = 0; i < piece_num; i++) {
if(i == piece_num-1) {
length = remain;
}
else {
length = piece_length;
}
string piece = readPiece(filename, i);
//cout<<piece<<endl;
bool check = pieceGood(i, piece);
//cout<<check<<endl;
if(check) {
bytes_left -= length;
bitfield[i] = '1';
}
else {
bitfield[i] = '0';
is_complete = false;
}
}
return is_complete;
}
char* int_to_bytes(int value) {
char* src = new char [5];
src[0] = (char) ((value>>24) & 0xFF);
src[1] = (char) ((value>>16) & 0xFF);
src[2] = (char) ((value>>8) & 0xFF);
src[3] = (char) (value & 0xFF);
src[4] = 0;
return src;
}
string build_message(int length, char ID, string payload) {
//cout<<"??"<<endl;
string message;
char* length_char = int_to_bytes(length);
for(int i = 0; i < 4; i++)
message.push_back(length_char[i]);
message += ID;
message += payload;
//cout<<"??"<<endl;
//for (int i = 0; i < length; i++)
//printf("%02x", (unsigned char)message[i]);
return message;
}
string build_request(unsigned char* hash, string peer_id, int port, int up, int down, int left, int comp, string event) {
char request[1024];
strcpy(request, "GET /announce?info_hash=");
string hash2((char*)hash);
strcat(request, encode(hash2).c_str());
strcat(request, "&peer_id=");
strcat(request, encode(peer_id).c_str());
strcat(request, "&port=");
strcat(request, to_string(port).c_str());
strcat(request, "&uploaded=");
strcat(request, to_string(up).c_str());
strcat(request, "&downloaded=");
strcat(request, to_string(down).c_str());
strcat(request, "&left=");
strcat(request, to_string(left).c_str());
strcat(request, "&compact=");
strcat(request, to_string(comp).c_str());
strcat(request, "&event=");
strcat(request, event.c_str());
strcat(request, " HTTP/1.1\r\n\r\n");
string str(request);
return str;
}
size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
((string*)userp)->append((char*)contents, size* nmemb);
return size* nmemb;
}
string get_my_ip() {
CURL *curl;
CURLcode res;
string ip;
while(ip.empty()) {
//cout<<"test"<<endl;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://checkip.dyndns.org");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ip);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3L);
res = curl_easy_perform(curl);
//cout<<"test2"<<endl;
curl_easy_cleanup(curl);
}
}
int start = ip.find("Current IP Address: ");
int end = ip.rfind("</body>");
ip = ip.substr(start+20, end-(start+20));
//cout<<ip<<endl;
return ip;
}
void print_metainfo(string file_name, string peer_id) {
//unsigned char id_buf[8192];
//unsigned char id_hash[20];
//memcpy((char*)id_buf, peer_id.c_str(), peer_id.size());
//SHA1(id_buf, sizeof(id_buf) - 1, id_hash);
printf("\tIP/port : %s/%d\n", my_ip.c_str(), port);
printf("\tID : %s\n", peer_id.c_str());
//printf("\tID : ");
//for (int i = 0; i < 20; i++)
// printf("%02x", id_hash[i]);
//printf("\n");
printf("\tmetainfo file : %s\n", file_name.c_str());
printf("\tinfo hash : ");
for(int i = 0; i < 20; i++)
printf("%02x", info_hash[i]);
printf("\n");
printf("\tfile name : %s\n", info_name.c_str());
printf("\tpiece length : %d\n", piece_length);
printf("\tfile size : %d (%d * [piece length] + %d)\n", info_length, piece_num-1, info_length-(piece_num-1)*piece_length);
printf("\tannounce URL : %s\n", announce.c_str());
printf("\tpieces' hashes:\n");
for(int i = 0; i < piece_num; i++) {
printf("\t%d\t", i);
for(int j = 0; j < 20; j++)
printf("%02hhx", pieces[i][j]);
printf("\n");
}
printf("\n");
}
void print_tracker_info(int option, int comp, int down, int inc, int inter, int min) {
printf("\t%-9s | %-10s | %-10s | %-8s | %-12s\n", "complete", "downloaded", "incomplete", "interval", "min interval");
printf("\t---------------------------------------------------------------\n");
printf("\t%-9d | %-10d | %-10d | %-8d | %-12d\n", comp, down, inc, inter, min);
printf("\t---------------------------------------------------------------\n");
int vector_size = peers_ip.size();
if(option == 0) {
printf("\tPeer List: \n");
printf("\t%-16s | %-5s\n", "IP", "Port");
printf("\t-------------------------------\n");
for(int i = 0; i < vector_size; i++) {
string ip_i = peers_ip[i];
string port_i = to_string(peers_port[i]);
printf("\t%-16s | %-5s\n", ip_i.c_str(), port_i.c_str());
}
}
else {
printf("\tPeer List (self included): \n");
printf("\t\t%-16s | %-5s\n", "IP", "Port");
printf("\t\t-------------------------------\n");
for(int i = 0; i < vector_size; i++) {
string ip_i = peers_ip[i];
string port_i = to_string(peers_port[i]);
printf("\t\t%-16s | %-5s\n", ip_i.c_str(), port_i.c_str());
}
}
}
void print_show() {
printf("\t%-2s | %-15s | %-6s | %-10s | %-10s | %s\n", "ID", "IP address", "Status", "Down/s", "Up/s", "Bitfield");
printf("\t---------------------------------------------------------------------\n");
pthread_mutex_lock(&mutex_peers);
for(int i = 0; i < peers_ip.size(); i++) {
//cout<<peers_down[i]<<endl;
string ip_i = peers_ip[i];
printf("\t%-2d | %-15s | %-6s | %-10d | %-10d | %s\n", i, ip_i.c_str(), "0000", peers_down[i], peers_up[i], bitfield);
}
pthread_mutex_unlock(&mutex_peers);
printf("\n");
}
//print download info
void print_status() {
printf("\t%-10s | %-10s | %-10s | %-16s\n", "Downloaded", "Uploaded", "Left", "My bit field");
printf("\t---------------------------------------------------------\n");
printf("\t%-10d | %-10d | %-10d | %s\n", downloaded, uploaded, bytes_left, bitfield);
//cout<<bitfield<<endl;
printf("\n");
}
string tracker_announce(string peer_id, int port, unsigned char* hash, string event) {
int sockfd;
struct sockaddr_in serv_addr;
struct in_addr ip_addr;
struct hostent *server;
char buffer[1024];
char rec_buffer[1024];
bzero(buffer, 1024);
bzero(rec_buffer, 1024);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0)
error("ERROR opening socket");
if(!inet_aton(announce_ip.c_str(), &ip_addr))
error("ERROR parsing IP address");
//cout<<announce_ip<<" "<<announce_ip.length()<<endl;
server = gethostbyaddr((const void *)&ip_addr, sizeof(ip_addr), AF_INET);
if(server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr,server->h_length);
serv_addr.sin_port = htons(announce_port);
if(connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting3");
//GET request
string request;
request = build_request(hash, peer_id, port, uploaded, downloaded, bytes_left, 1, event);
strcpy(buffer, request.c_str());
//cout<<"buffer "<<buffer<<endl;
int wn = write(sockfd,buffer,strlen(buffer));//write to server
if (wn < 0)
error("ERROR writing to socket");
wn = read(sockfd,rec_buffer,1024);//get ACK
//printf("%s\n",rec_buffer);
string temp(rec_buffer, 1024);
int start_temp = temp.find("d8:complete");
//cout<<start_temp<<endl;
//tracker response
string response = temp.substr(0, temp.find("\r\n"));
//get content length
int len;
char* ch = strstr(const_cast<char*>(temp.c_str()), "Content-Length:");
int i = 0;
char cont_len[20];
for(i = 0; i < 20; i++) {
char next = ch[strlen("Content-Length:")+i];
if(next == '\r' || next == '\n') {
break;
}
cont_len[i] = next;
}
len = atoi(cont_len);
string st = temp.substr(start_temp, len);
be_node *peer_node = be_decode(st.c_str(), len);
start_temp = st.find("5:peers");
int end_temp = st.find(":", start_temp+7);
string find_peers = st.substr(start_temp+7, end_temp-7-start_temp);
num_peers = atoi(find_peers.c_str())/6;
for(int i = 0; peer_node->val.d[i].val; i++) {
if(strcmp(peer_node->val.d[i].key,"complete") == 0) {
complete = ((peer_node->val.d[i].val)->val.i);
}
else if(strcmp(peer_node->val.d[i].key,"downloaded") == 0) {
downloaded2 = ((peer_node->val.d[i].val)->val.i);
}
else if(strcmp(peer_node->val.d[i].key,"incomplete") == 0) {
incomplete = ((peer_node->val.d[i].val)->val.i);
}
else if(strcmp(peer_node->val.d[i].key,"interval") == 0) {
interval = ((peer_node->val.d[i].val)->val.i);
}
else if(strcmp(peer_node->val.d[i].key,"min interval") == 0) {
min_interval = ((peer_node->val.d[i].val)->val.i);
}
else if(strcmp(peer_node->val.d[i].key,"peers") == 0) {
for(int j = 0; j < num_peers; j++) {
if(verbose) {
cout<<"ss "<<(int)(*((peer_node->val.d[i].val)->val.s+(j*6)))<<endl;
cout<<"ss "<<(int)(*((peer_node->val.d[i].val)->val.s+(j*6)+1))<<endl;
cout<<"ss "<<(int)(*((peer_node->val.d[i].val)->val.s+(j*6)+2))<<endl;
cout<<"ss "<<(int)(*((peer_node->val.d[i].val)->val.s+(j*6)+3))<<endl;
cout<<"ss "<<((unsigned char)(*((peer_node->val.d[i].val)->val.s+(j*6)+4)))*256+(unsigned char)(*((peer_node->val.d[i].val)->val.s+(j*6)+5))<<endl;
cout<<"ss "<<endl;
}
stringstream strStream;
strStream<<(int)(unsigned char)*((peer_node->val.d[i].val)->val.s+(j*6));
strStream<<".";
strStream<<(int)(unsigned char)*((peer_node->val.d[i].val)->val.s+(j*6)+1);
strStream<<".";
strStream<<(int)(unsigned char)*((peer_node->val.d[i].val)->val.s+(j*6)+2);
strStream<<".";
strStream<<(int)(unsigned char)*((peer_node->val.d[i].val)->val.s+(j*6)+3);
string addr_temp = strStream.str();
//cout<<"addr_temp "<<addr_temp<<endl;
int temp_port = ((unsigned char)*((peer_node->val.d[i].val)->val.s+(j*6)+4))*256 + (unsigned char)*((peer_node->val.d[i].val)->val.s+(j*6)+5);
bool has = false;
pthread_mutex_lock(&mutex_peers);
if(!peers_ip.empty()) {
int vector_size = peers_ip.size();
for(int k = 0; k < vector_size; k++) {
string ip_k = peers_ip[k];
int port_k = peers_port[k];
if(ip_k == addr_temp && port_k == temp_port) {
has = true;
}
}
if(!has) {
if(memcmp(addr_temp.c_str(), "0.0.0.0", 7)!=0 ) {
peers_ip.push_back(addr_temp);
peers_port.push_back(temp_port);
peers_flag.push_back(0);
peers_down.push_back(0);
peers_up.push_back(0);
vector<int> piece_have;
peers_have.push_back(piece_have);
}
}
}
else {
if(memcmp(addr_temp.c_str(), "0.0.0.0", 7) != 0) {
peers_ip.push_back(addr_temp);
peers_port.push_back(temp_port);
peers_flag.push_back(0);
peers_down.push_back(0);
peers_up.push_back(0);
vector<int> piece_have;
peers_have.push_back(piece_have);
}
}
pthread_mutex_unlock(&mutex_peers);
}
}
//cout<<"str: "<<(n->val.d[i].key)<<endl;
}
if(peer_node)
be_free(peer_node);
close(sockfd);
return response;
}
void periodic_announce(string peer_id, int port, unsigned char* hash1) {
while(1) {
//realistically n should be between min_interval and interval
//but for our purposes we will go with a smaller number
int n;
string response;
//n = min_interval;
n = 10;
tracker_announce(peer_id, port, hash1, "");
this_thread::sleep_for(chrono::seconds(n));
}
}
void start_announce_thread(string peer_id, int port, unsigned char* hash1) {
thread t(periodic_announce, peer_id, port, hash1);
t.detach();
this_thread::sleep_for(chrono::seconds(1));
//cout<<"seeder "<<seeder<<endl;
}
int main(int argc, char* argv[]) {
strcpy(peer_id, "UR-1-0--");
//random numbers
srand(time(NULL));
for(int i = 0; i < 12; i++) {
strcat(peer_id, to_string(rand() % 10).c_str());
}
announcing = false;
if(argc < 3) {
fprintf(stderr,"need filename and port number\n");
exit(0);
}
port = atoi(argv[2]);
string torrent_name = argv[1];
ifstream infile(torrent_name);
if(argc == 4)
verbose = atoi(argv[3]);
else
verbose = 0;
char buffer[1024];
bzero(buffer, 1024);
char rec_buffer[1024];
bzero(rec_buffer, 1024);
if(!infile) {
fprintf(stderr, "file open error\n");
exit(0);
}
//cout<<"until now"<<endl;
pthread_t tid;
if(pthread_create( &tid, NULL, connection_handler, (void*) 0) < 0) {
perror("Error on create thread");
}
if(verbose)
cout<<"torrent_name "<<torrent_name<<endl;
string buf;
infile>>noskipws;
long long length = 0;
while(!infile.eof()) {
char pr;
infile>>pr;
buf = buf + pr;
length++;
}
//cout<<buf<<endl;
int info_start = buf.find("4:info");
//string subbuf = buf.substr(info_start+6, length-8-info_start);
unsigned char subbuf[8192];
memcpy((char*)subbuf, (buf.substr(info_start+6, length-8-info_start)).c_str(), length-8-info_start);
SHA1(subbuf, length-8-info_start, info_hash);
//cout<<"info_start "<<info_start<<endl;
//printf("info_hash: ");
//for (int i = 0; i < SHA_DIGEST_LENGTH; i++)
// printf("%02x", info_hash[i]);
//printf("\n");
info_start = buf.find("6:pieces");
int info_end = buf.find(":", info_start+8);
piece_num = atoi((buf.substr(info_start+8, info_end-8-info_start)).c_str())/20;
bitfield_num = piece_num/8 + 1;
finish = piece_num;
//cout<<"piece_num "<<piece_num<<endl;
infile.close();
be_node *n = be_decode(buf.c_str(), length);
string hash2((char*)info_hash);
for(int i = 0; n->val.d[i].val; i++) {
if(strcmp(n->val.d[i].key,"announce") == 0) {
announce = ((n->val.d[i].val)->val.s);
}
else if(strcmp(n->val.d[i].key,"info") == 0) {
for(int j = 0; (n->val.d[i].val)->val.d[j].val; j++) {
//cout<<"info: "<<((n->val.d[i].val)->val.d[j].key)<<endl;
if(strcmp((n->val.d[i].val)->val.d[j].key,"length") == 0) {
info_length = ((n->val.d[i].val)->val.d[j].val)->val.i;
}
else if(strcmp((n->val.d[i].val)->val.d[j].key,"name") == 0) {
info_name = ((n->val.d[i].val)->val.d[j].val)->val.s;
}
else if(strcmp((n->val.d[i].val)->val.d[j].key,"piece length") == 0) {
piece_length = ((n->val.d[i].val)->val.d[j].val)->val.i;
}
else if(strcmp((n->val.d[i].val)->val.d[j].key,"pieces") == 0) {
for(int k = 0; k < piece_num; k++) {
memcpy(pieces[k], ((n->val.d[i].val)->val.d[j].val)->val.s+20*k, 20);
//printf("%d ", k);
//for (int l = 0; l < 20; l++)
// printf("%02hhx", pieces[k][l]);
//printf("\n");
}
}
}
}
}
int announce_start, announce_mid, announce_end;
//announce_start = announce.find("http://") + 7;
announce_start = 7;
announce_mid = announce.rfind(":");
announce_end = announce.find("/announce");
announce_ip = announce.substr(announce_start, announce_mid-announce_start);
announce_port = atoi(announce.substr(announce_mid+1, announce_end-(announce_mid+1)).c_str());
//cout<<"announce "<<announce_ip<<" "<<announce_port<<endl;
downloaded = 0;
uploaded = 0;
filename = torrent_name.substr(0, torrent_name.rfind("."));
bitfield = (char*) malloc(piece_num+1);
memset(bitfield, '0', piece_num);
bitfield[piece_num] = '\0';
//cout<<"test "<<piece_num<<" "<<bitfield<<endl;
if(fileExists(filename)) {
if(checkFile(filename)) {
seeder = 1;
bytes_left = 0;
}
else {
seeder = 0;
start_announce_thread(peer_id, port, info_hash);
announcing = true;
}
}
else {
seeder = 0;
memset(bitfield, '0', piece_num);
bytes_left = info_length;
cout<<"Original file not found, creating "<<filename<<"..."<<endl;
createFile(filename, info_length);
start_announce_thread(peer_id, port, info_hash);
announcing = true;
}
//cout<<"bitfield "<<bitfield<<endl;
while(1) {
cout<<"urtorrent>";
string command;
cin>>command;
if(command == "metainfo") {
my_ip = get_my_ip();
//cout<<my_ip<<endl;
print_metainfo(torrent_name, peer_id);
}
else if(command == "announce") {
string response;
response = tracker_announce(peer_id, port, info_hash, "started");
cout<<"\tTracker responded: "<<response<<endl;
print_tracker_info(0, complete, downloaded, incomplete, interval, min_interval);
if(!announcing) {
start_announce_thread(peer_id, port, info_hash);
announcing = true;
}
if(!seeder) {
pthread_t tid;
if(pthread_create(&tid, NULL, establish_handler, (void*) 0) < 0) {
perror("Error on create thread");
}
}
}
else if(command == "trackerinfo") {
print_tracker_info(1, complete, downloaded, incomplete, interval, min_interval);
}
else if(command == "show") {
print_show();
}
else if(command == "status") {
//checkFile(filename);
print_status();
}
else if(command == "quit") {
if(n)
be_free(n);
return 0;
}
}
}
void *connection_handler(void *) {
while(1) {
int sockfd;
socklen_t clilen;
int *newsockfd;
char *deal_sock;
struct sockaddr_in serv_addr, cli_addr;
//printf("Waiting for data from sender \n");
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port);
int on = 1;
if((setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on))) < 0)
error("setsockopt failed");
if(bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,10);
clilen = sizeof(cli_addr);
while(1) {
pthread_t thread_id;
newsockfd = (int*)malloc(sizeof(int));
*newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if(*newsockfd != -1) {
pthread_create(&thread_id,0,&socket_handler, (void*)newsockfd );
//pthread_detach(thread_id);
}
}
close(sockfd);
}
}
void* socket_handler(void* lp) {
int *newsockfd = (int*)lp;
int on = 1;
int connection_port = 0;
int flag_port = 1;
char *message = new char[piece_length+13];
if(verbose)
cout<<"piece_length "<<piece_length<<endl;
while(1) {
if(verbose)
cout<<"new read "<<connection_port<<endl;
on = read(*newsockfd,message,piece_length+13);
if(on < 0)
error("ERROR reading from socket");
if(memcmp(message+1, "URTorrent protocol", 18) == 0) { //get handshake
if(verbose)
printf("Handshake from server:%s\n",message);
int rec_length = (int)*(unsigned char*)message;
if(flag_port) {
connection_port = (unsigned char)*(message+47)*256 + (unsigned char)*(message+48);
flag_port = 0;
}
char check_hash[SHA_DIGEST_LENGTH];
if(verbose)
cout<<"rec_length "<<rec_length<<endl;
memcpy(check_hash, (message+27), SHA_DIGEST_LENGTH);
char check_id[20];
memcpy(check_id, (message+47), 20);
if(verbose) {
printf("info_hash: ");
for(int i = 0; i < SHA_DIGEST_LENGTH; i++)
printf("%02x", info_hash[i]);
printf("\n");
printf("check_hash: ");
for(int i = 0; i < SHA_DIGEST_LENGTH; i++)
printf("%02x", (unsigned char)check_hash[i]);
printf("\n");
}
if(memcmp(check_hash, (char*)info_hash, SHA_DIGEST_LENGTH) == 0) {
string reply_handshake;
int reply_handshake_length = 4+1+bitfield_num;
for(int j = 0; j < piece_num; j += 8) {
char to_byte = (char) 0;
for(int k = 0; k < 8; k++) {
if(*(bitfield+j+k)=='1') {
to_byte += (char)pow(2,7-k);
}
}
reply_handshake.push_back(to_byte);
}
printf("reply_handshake %d %d\n", bitfield_num, piece_num);
for(int j = 0; j < bitfield_num; j++)
printf("%02x", (unsigned char)reply_handshake[j]);
printf("\n");
//while(1);
//build_message(reply_handshake_length, (char)5, reply_handshake);
on = write(*newsockfd,build_message(reply_handshake_length, (char)5, reply_handshake).c_str(),reply_handshake_length);
//start as choked and not interested
on = write(*newsockfd, build_message(1, (char)0, "").c_str(), 1);
on = write(*newsockfd, build_message(1, (char)3, "").c_str(), 1);
if(on < 0)
error("ERROR writing from socket");
}
else
error("info_hash is not match");
}
else if(*(message+4) == (char)2) { //get interested
//unchoke
on = write(*newsockfd,build_message(1, (char)1, "").c_str(), 1);
}
else if(*(message+4) == (char)6) { //get request
//time upload start
double up_start, up_end;
up_start = chrono::duration_cast<chrono::milliseconds >(chrono::system_clock::now().time_since_epoch()).count();
if(verbose)
printf("id 6\n");
if(verbose) {
for(int j = 0; j < 17; j++)
printf("%02x", (unsigned char)message[j]);
printf("\n");
}
int piece_index = (unsigned char)message[5]*16777216 + (unsigned char)message[6]*65536 + (unsigned char)message[7]*256 + (unsigned char)message[8];
int piece_begin = (unsigned char)message[9]*16777216 + (unsigned char)message[10]*65536 + (unsigned char)message[11]*256 + (unsigned char)message[12];
int piece_length = (unsigned char)message[13]*16777216 + (unsigned char)message[14]*65536 + (unsigned char)message[15]*256 + (unsigned char)message[16];
if(verbose) {
cout<<"piece_index "<<piece_index<<endl;
cout<<"piece_begin "<<piece_begin<<endl;
cout<<"piece_length "<<piece_length<<endl;
}
char* piece_buffer = (char*) malloc(piece_length+13);
piece_buffer[4] = (char) 7;
string piece_send;
if(piece_index<piece_num) {
char* length_char = int_to_bytes(piece_length+9);
piece_buffer[0] = length_char[0];
piece_buffer[1] = length_char[1];
piece_buffer[2] = length_char[2];
piece_buffer[3] = length_char[3];
delete [] length_char;
piece_buffer[5] = message[5];
piece_buffer[6] = message[6];
piece_buffer[7] = message[7];
piece_buffer[8] = message[8];
piece_buffer[9] = (char)0;
piece_buffer[10] = (char)0;
piece_buffer[11] = (char)0;
piece_buffer[12] = (char)0;
piece_send = readPiece(filename, piece_index);
//cout<<"piece_send.c_str() "<<piece_send.c_str()<<endl;
memcpy(piece_buffer+13, piece_send.c_str(), piece_length);
}
else {
piece_buffer[0] = (char)0;
piece_buffer[1] = (char)0;
piece_buffer[2] = (char)0;
piece_buffer[3] = (char)9;
}
on = write(*newsockfd, piece_buffer, piece_length+13);
int remain = info_length-((piece_num-1)*piece_length);
if(piece_index == piece_num-1)
uploaded += remain;
else
uploaded += piece_length;
free(piece_buffer);
up_end = chrono::duration_cast<chrono::milliseconds >(chrono::system_clock::now().time_since_epoch()).count();
//time upload end
double dur = (up_end-up_start);
if(dur < 1)
dur = 1;
//cout<<"dur "<<dur<<endl;
long long up_rate = (long long) 1000*((double)piece_length/dur);
//cout<<"should be "<<up_rate<<endl;
for(int i = 0; i < peers_ip.size(); i++) {
//cout<<"cmp ports "<<connection_port<<" "<<peers_port[i]<<endl;
if(connection_port == peers_port[i]) {
peers_up[i] = up_rate;
//cout<<"upload test"<<endl;
}
}
//cout<<"up "<<up_rate<<endl;
}
else if(*(message+4) == (char)4) {//get have
if(verbose)
printf("id 4\n");
if(verbose) {
for(int j = 0; j < 13; j++)
printf("%02x", (unsigned char)message[j]);
printf("\n");
}
int have_index = (unsigned char)message[5]*16777216 + (unsigned char)message[6]*65536 + (unsigned char)message[7]*256 + (unsigned char)message[8];
int sender_port = (unsigned char)message[9]*256 + (unsigned char)message[10];
if(verbose)
cout<<"have_index "<<have_index<<" "<<sender_port<<endl;
pthread_mutex_lock(&mutex_global);
global_bitfield[have_index] = sender_port;
//cout<<"GGGlo "<<have_index<<" "<<sender_port<<endl;
pthread_mutex_unlock(&mutex_global);
}
else
cout<<"wtf"<<endl;
}
FINISH:
free(newsockfd);
return 0;
}
void *send_handler(void *arg) {
Pass *peer_pass = (Pass*)arg;
char handshake_buffer[67];
char *message = new char[piece_length+13];
handshake_buffer[0] = (char)67;
//int rec_length = (int)*handshake_buffer;
//cout<<"rec_length "<<rec_length<<" "<<(int)handshake_length<<endl;
memcpy(handshake_buffer+1, "URTorrent protocol",18);
//printf("handshake_buffer: %s\n", handshake_buffer);
for(int k = 0; k < 8; k++)
handshake_buffer[19+k]=(char)0;
memcpy((char*)(handshake_buffer+27), (char*)info_hash, SHA_DIGEST_LENGTH);
//strcat(handshake_buffer, info_hash_temp);
memcpy((char*)(handshake_buffer+47), peer_id, 20);
char* get_port = int_to_bytes(port);
delete [] get_port;
if(verbose) {
printf("handshake_buffer: ");
for(int i = 0; i < 67; i++)
printf("%02x", (unsigned char)handshake_buffer[i]);
printf("\n");
}
int sn = write(peer_pass->fd,handshake_buffer, 67); //send handshake
char* bitfield_buffer = (char*)malloc(5+piece_num);
sn = read(peer_pass->fd,bitfield_buffer, 5+piece_num);
if(verbose) {
printf("bitfield from server:%s");
for(int i = 0; i < piece_num; i++)
printf("%02x", bitfield_buffer[i]);
printf("\n");
}
vector<char> peer_bitfield;