-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpeer_manager.c
1219 lines (1023 loc) · 43.3 KB
/
peer_manager.c
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 <stdlib.h>
#include <stdint.h>
#include <curl/curl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
#include "shared.h"
#include "cli.h"
#include "torrent_runtime.h"
#include "peer_manager.h"
#include "piece_manager.h"
#define MAX_PEERS 128
/*
* Periodic functions the peer manager need to do:
* 1. CLI, piece manager, torrent runtime
* 2. Choking algorithm
* 3. Send keep alive messages to peers.
* 4. Send request messages to the tracker
*/
//Global variables
char peer_id[21] = "zackdazhithong417fin";
long int interval; //interval that the client should send request to the tracker
int complete; //number of peers with the entire file, i.e. seeders (integer)
int incomplete; //number of non-seeder peers, aka "leechers" (integer)
struct Peer *head_peer = NULL;
int number_of_peers = 0;
uint16_t readable_peers = 0;
struct pollfd peers_sockets[MAX_PEERS];
struct Peer *unchoked_four[4];
Torrent * g_torrent;
int clientSock;
uint16_t DEBUG_CURRENTLY_DOWNLOADING = 0;
void print_ip_address(uint8_t *addr){
DEBUG_PRINTF("IP Address: ");
for(int i =0;i<4;i++){
if(i!=3) {
DEBUG_PRINTF("%d.", addr[i]);
} else {
DEBUG_PRINTF("%d", addr[i]);
}
}
DEBUG_PRINTF("\n");
}
void print_peer(struct Peer *peer) {
print_ip_address(peer->address);
DEBUG_PRINTF("\n");
DEBUG_PRINTF("Port: %d\n", peer->port);
DEBUG_PRINTF("Socket: %d\n", peer->socket);
DEBUG_PRINTF("am_choking: %d, am_interested: %d, peer_choking: %d, peer_interested: %d\n",
peer->am_choking, peer->am_interested, peer->peer_choking, peer->peer_interested);
DEBUG_PRINTF("Download rate: %ld\n", peer->download_rate);
//TODO: printbitfield
};
/*
Create a fd set of all the file descriptors we have active
peers which we aren't downloading from. These are ones we
listen to incoming messages for.
*/
void peer_manager_update_fd_set(fd_set* fds) {
struct Peer* ptr = head_peer;
FD_ZERO(fds);
while (ptr != NULL) {
if (ptr->curr_dl != 1) {
FD_SET(ptr->socket, fds);
}
ptr = ptr->next;
}
};
void print_peer_list() {
struct Peer *peer = head_peer;
while(peer != NULL) {
print_peer(peer);
peer = peer->next;
}
}
//Tried to establish connection with the peer, timeouts around 5 secs
int create_peer_connection_socket(uint8_t *addr, uint16_t port){
int peer_socket;
if ((peer_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
fprintf(stderr, "socket creation failed\n");
return -1;
}
struct timeval timeout;
timeout.tv_sec = 2;
timeout.tv_usec = 0;
setsockopt(peer_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
setsockopt(peer_socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
struct sockaddr_in servAddr; // Server address
memset(&servAddr, 0, sizeof(servAddr)); // Zero out structure
servAddr.sin_family = AF_INET; // IPv4 address family
memcpy(&servAddr.sin_addr.s_addr, addr, 4);
servAddr.sin_port = port;
if (connect(peer_socket, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0){
close(peer_socket);
DEBUG_PRINTF("socket connection timeout\n");
return 0;
}
return peer_socket;
}
int insert_peerlist_ifnotexists(uint8_t *ip_arr, uint16_t port){
struct Peer *prev = NULL;
struct Peer *cur = head_peer;
while(cur != NULL){
if(memcmp(cur->address, ip_arr, 4) == 0 && cur->port == port)
return 1;
prev = cur;
cur = cur->next;
}
int socket = create_peer_connection_socket(ip_arr, port);
if(socket){
number_of_peers ++;
cur = calloc(sizeof(struct Peer), 1);
memcpy(cur->address, ip_arr, 4);
cur->port = port;
cur->next = NULL;
cur->socket = socket;
cur->handshaked = 0;
cur->peer_choking = 1;
cur->am_choking = 1;
cur->bitfield = calloc((uint32_t) ceil((double) g_torrent->num_pieces / 8), 1);
cur->bitfield_length = (uint32_t) ceil((double) g_torrent->num_pieces / 8);
gettimeofday(&(cur->last_received_message_time), NULL);
gettimeofday(&(cur->last_sent_message_time), NULL);
if(head_peer == NULL){
head_peer = cur;
}else{
prev->next = cur;
}
return 1;
}else{
return 0;
}
}
void insert_peerlist_connect_to_us(uint8_t * ip_arr, uint16_t port, int socket){
struct Peer *prev = NULL;
struct Peer *cur = head_peer;
while(cur != NULL){
if(memcmp(cur->address, ip_arr, 4) == 0 && cur->port == port)
return;
prev = cur;
cur = cur->next;
}
number_of_peers ++;
cur = calloc(sizeof(struct Peer), 1);
memcpy(cur->address, ip_arr, 4);
cur->connect_to_use = 1;
cur->port = port;
cur->next = NULL;
cur->socket = socket;
cur->handshaked = 0;
cur->peer_choking = 1;
cur->am_choking = 1;
cur->bitfield = calloc((uint32_t) ceil((double) g_torrent->num_pieces / 8), 1);
cur->bitfield_length = (uint32_t) ceil((double) g_torrent->num_pieces / 8);
gettimeofday(&(cur->last_received_message_time), NULL);
gettimeofday(&(cur->last_sent_message_time), NULL);
if(head_peer == NULL){
head_peer = cur;
}else{
prev->next = cur;
}
}
void parse_peers_string(const char *string, int tn){
for(int i = 0; i < tn;i++){
uint16_t port;
memcpy(&port, string + i*6 +4, 2);
uint8_t ip_arr[4];
memcpy(ip_arr, string + i*6, 4);
insert_peerlist_ifnotexists(ip_arr, port);
if ((i > 15 && g_debug == 1) || i > 20)
break;
}
DEBUG_PRINTF("\n=================\n");
printf("Connected to %d peers successfully!\n", number_of_peers);
print_peer_list();
DEBUG_PRINTF("=================\n\n");
}
int parse_tracker_response(bencode_t* tracker_response_bencode){
const char* val;
int len;
while (bencode_dict_has_next(tracker_response_bencode)){
const char* key;
int keylen;
bencode_t dict_entry;
if (!bencode_dict_get_next(tracker_response_bencode, &dict_entry, &key, &keylen))
return 1;
if (strncmp(key, "failure reason", keylen) == 0) {
bencode_string_value(&dict_entry, &val, &len);
printf("Tracker Response with fail: %s\n", val);
return 1;
} else if(strncmp(key, "interval", keylen) == 0) {
bencode_int_value(&dict_entry, &interval);
} else if(strncmp(key, "complete", keylen) == 0) {
bencode_int_value(&dict_entry, (long int *)&complete);
printf("Complete (# of seeders) is %d\n", complete);
} else if(strncmp(key, "incomplete", keylen) == 0) {
bencode_int_value(&dict_entry, (long int *)&incomplete);
printf("Incomplete (# of leechers) is %d\n", incomplete);
} else if(strncmp(key, "peers", keylen) == 0) {
// printf("Beginning download in 10 seconds.....\n");
// sleep(10);
bencode_string_value(&dict_entry, &val, &len);
parse_peers_string(val, len/6);
}
}
return 0;
}
size_t write_func(void *ptr, size_t size, size_t nmemb, char **write_stream){
//*write_stream = NULL;
UNUSED(write_stream);
bencode_t tracker_response_bencode;
bencode_init(&tracker_response_bencode, ptr, size*nmemb);
if(parse_tracker_response(&tracker_response_bencode)) {
printf("Parsing the tracker response failed\n");
exit(1);
}
return size*nmemb;
}
void send_tracker_request(){
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
int numBytesDownload = (int) num_pieces_downloaded() * g_torrent->piece_length;
int numBytesUpload = (int) num_piece_upload(); //this one gives bytes
if((uint64_t)numBytesDownload > g_torrent->length)
numBytesDownload = g_torrent->length;
char url[1000] = {0};
char *info_hash_encoded = curl_easy_escape(curl, (const char*) g_torrent->info_hash, 20);
char *peer_id_encoded = curl_easy_escape(curl, peer_id, 20);
sprintf(url, "%s?info_hash=%s&peer_id=%s&port=6881&uploaded=%d&downloaded=%d&left=%ld&compact=1&event=started",
g_torrent->tracker_url, info_hash_encoded, peer_id_encoded, numBytesUpload, numBytesDownload, g_torrent->length);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_func);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
/* always cleanup */
curl_free(info_hash_encoded);
curl_free(peer_id_encoded);
curl_easy_cleanup(curl);
}
}
//remove the peer from the linked list, free the bitfield and the peer itself
int remove_from_peer_linked_list(struct Peer *target){
struct Peer *cur = head_peer;
struct Peer *prev = NULL;
while(cur != NULL){
if(memcmp(cur->address, target->address, 4) == 0 && cur->port == target->port){
if(cur == head_peer){
head_peer = cur->next;
}else{
if(cur != NULL)
prev->next = cur->next;
else
prev->next = NULL;
}
free(cur->bitfield);
close(cur->socket);
free(cur);
return 1;
}
prev = cur;
cur = cur->next;
}
return 0;
}
// Make the pollfd array matches to the sockets in the peers linked list
// Returns # of readable peers
void update_pollfd() {
uint16_t num_read_peers = 0;
struct Peer* ptr = head_peer;
while (ptr != NULL) {
if ((ptr->curr_dl_begin == 0 || ptr->curr_dl == 0) && ptr->socket > 0){
peers_sockets[num_read_peers].fd = ptr->socket;
peers_sockets[num_read_peers].events = POLLIN;
num_read_peers++;
}
ptr = ptr->next;
}
peers_sockets[num_read_peers].fd = clientSock;
peers_sockets[num_read_peers].events = POLLIN;
num_read_peers++;
readable_peers = num_read_peers;
}
int send_handshake_message(struct Peer *peer){
uint8_t send_string[68]; //49+19=68
uint8_t bittorrent_protocol[20] = "BitTorrent protocol";
uint8_t reserved[8] = {0};
int temp = 19;
memcpy(send_string, &temp, 1);
memcpy(send_string + 1, bittorrent_protocol, 19);
memcpy(send_string + 20, reserved, 8);
memcpy(send_string + 28, g_torrent->info_hash, 20);
memcpy(send_string + 48, peer_id, 20);
gettimeofday (&(peer->last_sent_message_time), NULL);
if (send_n_bytes(send_string, 68, peer->socket) == -1) {
close(peer->socket);
remove_from_peer_linked_list(peer);
update_pollfd();
number_of_peers --;
return 0;
}
// send the bitfield the along witht he handshake message
uint64_t bitfield_len = ceil(((double) g_torrent->num_pieces) / 8.0); // len in bytes
uint8_t* bitfield_packet;
bitfield_packet = calloc(4096, sizeof(uint8_t));
uint32_t len_nbo = htobe32(1 + bitfield_len);
memcpy(bitfield_packet , &len_nbo, sizeof(uint32_t));
*(bitfield_packet + 4) = 5;
memcpy(bitfield_packet + 5, piece_manager_get_my_bitfield(), piece_manager_get_my_bitfield_size());
if (send_n_bytes((void*) bitfield_packet, 4 + 1 + bitfield_len, peer->socket) == -1) {
DEBUG_PRINTF("error!!!! sending bitfield!!!\n");
}
return 1;
}
void send_keep_alve_message(struct Peer *peer){
uint32_t len = 0;
if(send_n_bytes(&len, 4, peer->socket) == -1){
remove_from_peer_linked_list(peer);
update_pollfd();
number_of_peers--;
}else{
gettimeofday(&(peer->last_sent_message_time), NULL);
}
}
void send_interested_message(struct Peer *peer, int interested){
uint32_t len = 1;
len = htobe32(len);
uint8_t ID;
if(interested){
ID = 2;
}else{
ID = 3;
}
uint8_t buffer[5];
memcpy(buffer, &len, 4);
memcpy(buffer + 4, &ID, 1);
if(send_n_bytes(buffer, 5, peer->socket) == -1){
remove_from_peer_linked_list(peer);
number_of_peers --;
}else{
gettimeofday(&(peer->last_sent_message_time), NULL);
}
}
int send_choked_message(struct Peer *peer, int choked){
uint32_t len = 1;
len = htobe32(len);
uint8_t ID;
if(choked){
ID = 0;
}else{
ID = 1;
}
uint8_t buffer[5];
memcpy(buffer, &len, 4);
memcpy(buffer + 4, &ID, 1);
if(send_n_bytes(buffer, 5, peer->socket) == -1){
remove_from_peer_linked_list(peer);
number_of_peers --;
return -1;
}else{
gettimeofday(&(peer->last_sent_message_time), NULL);
return 0;
}
}
void send_have_message(struct Peer *peer, int piece_index){
if (peer == NULL)
return;
uint32_t len =5;
len = htobe32(len);
uint8_t ID = 4;
uint8_t buffer[9];
memcpy(buffer, &len, 4);
memcpy(buffer + 4, &ID, 1);
uint32_t p_i = piece_index;
p_i = htobe32(p_i);
memcpy(buffer + 5, &p_i, 4);
if(send_n_bytes(buffer, 9, peer->socket) == -1){
remove_from_peer_linked_list(peer);
update_pollfd();
number_of_peers --;
}else{
gettimeofday(&(peer->last_sent_message_time), NULL);
}
}
void peer_manager_upload_download_complete(uint8_t is_upload, struct Peer* peer, int piece_index){
if (!is_upload) {
DEBUG_PRINTF("[Peer Manager] Finished downloading piece (or subpiece). piece=%d\n",
piece_index);
}
uint32_t total_subpieces = ceil(g_torrent->piece_length / PIECE_DOWNLOAD_SIZE);
// if we're on the last piece...
if ((uint64_t) piece_index == (g_torrent->num_pieces - 1)) {
uint32_t bytes_remain = g_torrent->length - (g_torrent->num_pieces - 1) * g_torrent->piece_length;
total_subpieces = ceil(bytes_remain / PIECE_DOWNLOAD_SIZE);
}
DEBUG_PRINTF("[Peer Manager] - Downloaded %d/%d subpieces.\n",
peer->curr_dl_next_subpiece, total_subpieces);
// IF REMAINING SUBPIECES, DOWNLOAD THE NEXT SUBPIECE
if(!is_upload){
// do a recursive download on the subpieces
if (peer->curr_dl_next_subpiece < total_subpieces) {
DEBUG_PRINTF("[Peer Manager] - Downloading subpiece %d/%d on piece=%d\n",
peer->curr_dl_next_subpiece + 1, total_subpieces, piece_index);
peer_manager_begin_download(peer, piece_index);
return;
} else {
DEBUG_PRINTF("[Peer Manager] Downloaded all subpieces for piece=%d!\n", piece_index);
struct Peer *cur = head_peer;
int peers_broadcasted = 0;
while(cur != NULL){
struct Peer *next = cur->next;
if(peer->curr_up == 0)
send_have_message(cur, piece_index);
cur = next;
peers_broadcasted++;
}
DEBUG_PRINTF("[Peer Manager] - Broadcasted to %d peers we have piece=%d\n", peers_broadcasted, piece_index);
DEBUG_CURRENTLY_DOWNLOADING = 0;
peer->curr_dl = 0;
peer->curr_dl_next_subpiece = 0;
peer->curr_dl_piece_idx = 0;
piece_manager_initiate_download();
}
}else{
peer->curr_up = 0;
peer->curr_up_piece_idx = 0;
}
update_pollfd();
}
int in_a_peers_array(struct Peer **arr, struct Peer *target){
if(target == NULL)
return 0;
for(int i = 0; i<4; i++){
if(arr[i] == target)
return 1;
}
return 0;
}
void choking_algorithm(){
struct Peer *peer = head_peer;
struct Peer *old_three[3];
memcpy(old_three, unchoked_four, 3*sizeof(struct Peer *));
while(peer != NULL){
if(peer->bitfield != NULL && piece_manager_am_interested(peer) && peer->peer_choking == 0){
if(unchoked_four[0] == NULL || peer->download_rate > unchoked_four[0]->download_rate){
unchoked_four[2] = unchoked_four[1];
unchoked_four[1] = unchoked_four[0];
unchoked_four[0] = peer;
peer->am_choking = 0;
}else if(unchoked_four[1] == NULL || peer->download_rate > unchoked_four[1]->download_rate){
unchoked_four[2] = unchoked_four[1];
unchoked_four[1] = peer;
peer->am_choking = 0;
}else if(unchoked_four[2] == NULL || peer->download_rate > unchoked_four[2]->download_rate){
unchoked_four[2] = peer;
peer->am_choking = 0;
}
}
peer = peer->next;
}
//If the peer is first time unchoked, we need to let it know; otherwise not.
if(unchoked_four[0] != NULL && in_a_peers_array(old_three, unchoked_four[0]) == 0 &&
unchoked_four[0]->curr_up == 0 && unchoked_four[0]->curr_dl == 0 && send_choked_message(unchoked_four[0], 0) == -1){
remove_from_peer_linked_list(unchoked_four[0]);
number_of_peers--;
unchoked_four[0] = unchoked_four[1];
unchoked_four[1] = unchoked_four[2];
unchoked_four[2] = NULL;
}
if(unchoked_four[1] != NULL && in_a_peers_array(old_three, unchoked_four[1]) == 0 &&
unchoked_four[1]->curr_up == 0 && unchoked_four[1]->curr_dl == 0 && send_choked_message(unchoked_four[1], 0) == -1){
remove_from_peer_linked_list(unchoked_four[1]);
number_of_peers--;
unchoked_four[1] = unchoked_four[2];
unchoked_four[2] = NULL;
}
if(unchoked_four[2] != NULL && in_a_peers_array(old_three, unchoked_four[2]) == 0 &&
unchoked_four[2]->curr_up == 0 && unchoked_four[2]->curr_dl == 0 && send_choked_message(unchoked_four[2], 0) == -1){
remove_from_peer_linked_list(unchoked_four[2]);
number_of_peers--;
unchoked_four[2] = NULL;
}
for(int i=0; i<3; i++){
if(in_a_peers_array(unchoked_four, old_three[i]) == 0){
//The old unchoked peer is no longer unchoked now
if(old_three[i] != NULL){
old_three[i]->am_choking = 1;
if(old_three[i]->curr_up == 0 && old_three[i]->curr_dl == 0 && send_choked_message(old_three[i], 1) == -1){
remove_from_peer_linked_list(old_three[i]);
number_of_peers--;
}
}
}
}
update_pollfd();
}
void optimistic_unchoking(){
struct Peer *interested_arr[number_of_peers];
struct Peer *old_rand_peer = unchoked_four[3];
int counter = 0;
struct Peer *peer = head_peer;
while(peer != NULL){
if(piece_manager_am_interested(peer) && peer->peer_choking == 0 && peer != unchoked_four[0] && peer != unchoked_four[1] && peer != unchoked_four[2]){
interested_arr[counter] = peer;
counter ++;
}
peer = peer->next;
}
if(counter > 0){
int rand_unchoked = rand() % (counter + 1 - 0) + 0;
unchoked_four[3] = interested_arr[rand_unchoked];
}
if(unchoked_four[3] != old_rand_peer){
if(old_rand_peer != NULL){
old_rand_peer->am_choking = 1;
if(old_rand_peer->curr_up == 0 && old_rand_peer->curr_dl == 0 && send_choked_message(old_rand_peer, 1) == -1){
remove_from_peer_linked_list(old_rand_peer);
number_of_peers --;
}
}
if(unchoked_four[3] != NULL){
unchoked_four[3]->am_choking= 0;
if(unchoked_four[3]->curr_up == 0 && unchoked_four[3]->curr_dl == 0 && send_choked_message(unchoked_four[3], 0) == -1){
remove_from_peer_linked_list(unchoked_four[3]);
number_of_peers --;
unchoked_four[3] = NULL;
}
}
}
update_pollfd();
}
//returns the peer from the given socket
struct Peer *get_peer_from_socket(int socket){
struct Peer *peer = head_peer;
while(peer != NULL){
if(peer->socket == socket)
return peer;
peer = peer->next;
}
return NULL;
}
// Returns 0 if theres no such peer; 1 otherwise
// TODO: Close the connection if it's open. Clean up anything leftover from the peer.
// TODO: Make sure the piece manager is aware of this as well, or the piece manager adapts correctly
int peer_manager_inform_disconnect(struct Peer *peer) {
DEBUG_PRINTF("[Peer Manager] Handling peer disconnect...\n");
if (remove_from_peer_linked_list(peer)) {
update_pollfd();
number_of_peers--;
return 1;
}
// piece_manager_initiate_download();
return 0;
};
//starts the peer manager
int start_peer_manager(Torrent *torrent){
struct timeval choking_algorithm_time, optimistic_unchoking_time, periodic_function_time, tracker_request_time;
gettimeofday(&choking_algorithm_time, NULL);
gettimeofday(&optimistic_unchoking_time, NULL);
gettimeofday(&periodic_function_time, NULL);
gettimeofday(&tracker_request_time, NULL);
g_torrent = torrent;
if(direct_connected == 0){
send_tracker_request();
struct Peer *peer = head_peer;
while(peer != NULL){
struct Peer *next = peer->next;
if(send_handshake_message(peer) == 0){
DEBUG_PRINTF("send handshaking message failed\n");
}
peer = next;
}
}else{
insert_peerlist_ifnotexists(direct_connect_address, direct_connect_port);
if(send_handshake_message(head_peer) == 0){
printf("send handshaking message failed\n");
}
}
uint16_t port = 10000;
if(direct_connected == 1)
port = 10001;
struct sockaddr_in serverAddress;
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddress.sin_port = htons(port);
// Create a socket
clientSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(clientSock < 0){
perror("Making socket fail");
exit(1);
}
/* // Set up for multiple connection socket
if( setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&opt,
sizeof(opt)) < 0 ){
perror("setsockopt");
exit(EXIT_FAILURE);
}
*/
// Bind to the local address
if(bind(clientSock, (struct sockaddr*) &serverAddress, sizeof(serverAddress)) < 0){
perror("Binding fail");
exit(1);
}
// Let socket listen for incoming connection from the client
if(listen(clientSock, 15) < 0){
perror("Listening to incoming connection from client failed");
exit(1);
}
update_pollfd();
while(1){
if (poll(peers_sockets, readable_peers, 0) > 0) {
int n = readable_peers;
for(int i = 0; i<n; i++){
if(peers_sockets[i].fd == clientSock && peers_sockets[i].revents == POLLIN){
struct sockaddr_in clientAddr;
socklen_t clientAddrLen = sizeof(clientAddr);
int peerSocket = accept(clientSock, (struct sockaddr *) &clientAddr, &clientAddrLen);
uint8_t ip_arr[4];
memcpy(ip_arr, &clientAddr.sin_addr.s_addr, 4);
insert_peerlist_connect_to_us(ip_arr, clientAddr.sin_port, peerSocket);
}
else if(peers_sockets[i].revents == POLLIN){
struct Peer *peer = get_peer_from_socket(peers_sockets[i].fd);
DEBUG_PRINT_NET("[Peer Manager] Got poll event on socket=%d\n", peers_sockets[i].fd);
// if we are reading from the peer, continue
if (peer->curr_dl_begin) continue;
gettimeofday(&(peer->last_received_message_time), NULL); //refresh the last message received time
DEBUG_PRINT_NET("[Peer Manager] Processing peer message...\n");
print_peer(peer);
if(peer->handshaked){
DEBUG_PRINT_NET("[Peer Manager] - handshaked=true\n");
uint32_t length;
if (read_n_bytes(&length, 4, peers_sockets[i].fd) == -1) {
DEBUG_PRINT_NET("[Peer Manager] RERROR 5\n");
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
};
length = be32toh(length);
DEBUG_PRINT_NET("[Peer Manager] - len=%d\n", (int) length);
// TODO
if (((int) length) < 0 || length > 16000) exit(1);
// keep alive
if (length == 0) continue;
uint8_t ID;
if (read_n_bytes(&ID, 1, peers_sockets[i].fd) == -1) {
DEBUG_PRINT_NET("[Peer Manager] RERROR 6\n");
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
};
DEBUG_PRINT_NET("[Peer Manager] - id=%d\n", (int) ID);
// choke: <len=0001><id=0>
if (ID == 0) {
print_ip_address(peer->address);
DEBUG_PRINT_NET("[Peer Manager] choked us\n");
peer->peer_choking = 1;
peer->am_choking = 1;
if(peer->curr_dl == 1){
peer->curr_dl = 0;
peer->curr_dl_begin = 0;
peer->curr_dl_next_subpiece = 0;
peer->curr_dl_piece_idx = 0;
piece_manager_cancel_request_for_peer(peer);
}
if(peer->am_choking == 0){
if(peer->curr_up == 0 && send_choked_message(peer, 1) == -1){
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
}
}
};
// unchoke: <len=0001><id=1>
if (ID == 1) {
peer->peer_choking = 0;
};
// interested: <len=0001><id=2>
if(ID == 2) {
print_ip_address(peer->address);
DEBUG_PRINT_NET("[Peer Manager] interested us\n");
send_choked_message(peer, 0);
peer->am_choking = 0;
peer->peer_interested = 1;
};
// not interested: <len=0001><id=3>
if(ID == 3) {
DEBUG_PRINT_NET("[Peer Manager] uninterested\n");
peer->peer_interested = 0;
};
// have: <len=0005><id=4><piece index>
if (ID == 4) {
uint32_t piece_index;
if (read_n_bytes(&piece_index, 4, peers_sockets[i].fd) == -1) {
DEBUG_PRINT_NET("[Peer Manager] RERROR 7\n");
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
}
piece_index = be32toh(piece_index);
set_have_piece(peer->bitfield, piece_index);
}
// bitfield: <len=0001+X><id=5><bitfield>
if(ID == 5){
DEBUG_PRINT_NET("[Peer Manager] Got bitfield\n");
int correct_bitfield = 1;
uint8_t bitfield[length-1];
if (read_n_bytes(bitfield, length-1, peers_sockets[i].fd) == -1) {
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
};
//check if the bitfield length match and if there are any spare bits set
if(length-1 == (uint32_t) ceil((double) g_torrent->num_pieces / 8)){
for(uint32_t j = g_torrent->num_pieces; j < (length-1)*8; j++){
if (have_piece(bitfield, j) == true){
correct_bitfield = 0;
}
}
}else{
correct_bitfield = 0;
}
if(correct_bitfield){
memcpy(peer->bitfield, bitfield, length-1);
}else{
remove_from_peer_linked_list(peer);
number_of_peers--;
}
};
// request: <len=0013><id=6><index><begin><length>
if(ID == 6) {
DEBUG_PRINT_NET("[Peer Manager] request message\n");
uint32_t pieceIndex = 0;
uint32_t begin = 0;
uint32_t length = 0;
// get the piece index
if (read_n_bytes(&pieceIndex, 4, peers_sockets[i].fd) == -1) {
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
};
// get the begin
if (read_n_bytes(&begin, 4, peers_sockets[i].fd) == -1) {
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
};
// get the length
if (read_n_bytes(&length, 4, peers_sockets[i].fd) == -1) {
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
};
pieceIndex = be32toh(pieceIndex);
begin = be32toh(begin);
length = be32toh(length);
if(length > 16000){
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
}
peer->curr_up = 1;
peer->curr_up_piece_idx = pieceIndex;
gettimeofday(&(peer->last_sent_message_time), NULL);
piece_manager_create_upload_manager(peer, pieceIndex, length, begin);
};
// piece: <len=0009+X><id=7><index 4><begin 4><block X>
if(ID == 7) {
// struct timeval timenow;
// gettimeofday(&timenow, NULL);
print_ip_address(peer->address);
peer->curr_dl_begin = 1;
gettimeofday(&(peer->last_received_message_time), NULL);
uint32_t p_idx_nbo;
uint32_t p_begin_nbo;
if ((read_n_bytes(&p_idx_nbo, 4, peer->socket) == -1) ||
(read_n_bytes(&p_begin_nbo, 4, peer->socket) == -1)){
remove_from_peer_linked_list(peer);
number_of_peers --;
}else{
peer->curr_dl_begin = 1;
// pass off the socket to a download manager
piece_manager_create_download_manager(peer, peer->curr_dl_piece_idx, length - 9, ntohl(p_begin_nbo));
}
// }
};
// cancel: <len=0013><id=8><index><begin><length>
if(ID == 8) {
DEBUG_PRINT_NET("[Peer Manager] Cancel message\n");
};
} else {
DEBUG_PRINT_NET("[Peer Manager] Peer not handshaked...\n");
uint8_t pstrlen;
if (read_n_bytes(&pstrlen, 1, peers_sockets[i].fd) == -1) {
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
};
uint8_t pstr[pstrlen];
if (read_n_bytes(pstr, pstrlen, peers_sockets[i].fd) == -1) {
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
};
uint8_t reserved[8];
if (read_n_bytes(reserved, 8, peers_sockets[i].fd) == -1) {
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
};
uint8_t infohash[20];
if (read_n_bytes(infohash, 20, peers_sockets[i].fd) == -1) {
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
};
if(memcmp(infohash, g_torrent->info_hash, 20) != 0){
remove_from_peer_linked_list(peer);
number_of_peers--;
}else{
peer->handshaked = 1;
}
uint8_t peerid[21] = {0};
if (read_n_bytes(peerid, 20, peers_sockets[i].fd) == -1) {
remove_from_peer_linked_list(peer);
number_of_peers--;
continue;
};
if(peer->connect_to_use){