1 /* Copyright (c) 2012-2019. The SimGrid Team. All rights reserved. */
3 /* This program is free software; you can redistribute it and/or modify it
4 * under the terms of the license (GNU LGPL) which comes with this package. */
6 #include "bittorrent-peer.h"
7 #include "bittorrent-messages.h"
8 #include "connection.h"
10 #include <simgrid/msg.h>
13 #include <stdio.h> /* snprintf */
15 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_peers, "Messages specific for the peers");
18 * User parameters for transferred file data. For the test, the default values are :
19 * File size: 10 pieces * 5 blocks/piece * 16384 bytes/block = 819200 bytes
21 #define FILE_PIECES 10UL
22 #define PIECES_BLOCKS 5UL
23 #define BLOCK_SIZE 16384
24 static const unsigned long int FILE_SIZE = FILE_PIECES * PIECES_BLOCKS * BLOCK_SIZE;
26 /** Number of blocks asked by each request */
27 #define BLOCKS_REQUESTED 2
29 #define ENABLE_END_GAME_MODE 1
30 #define SLEEP_DURATION 1
32 int count_pieces(unsigned int bitfield)
35 unsigned int n = bitfield;
43 int peer_has_not_piece(peer_t peer, unsigned int piece)
45 return !(peer->bitfield & 1U << piece);
48 /** Check that a piece is not currently being download by the peer. */
49 int peer_is_not_downloading_piece(peer_t peer, unsigned int piece)
51 return !(peer->current_pieces & 1U << piece);
54 void get_status(char** status, unsigned int bitfield)
56 for (int i = FILE_PIECES - 1; i >= 0; i--)
57 (*status)[i] = (bitfield & (1U << i)) ? '1' : '0';
58 (*status)[FILE_PIECES] = '\0';
61 /** Peer main function */
62 int peer(int argc, char* argv[])
65 xbt_assert(argc == 3 || argc == 4, "Wrong number of arguments");
68 peer_t peer = peer_init(xbt_str_parse_int(argv[1], "Invalid ID: %s"), argc == 4 ? 1 : 0);
71 double deadline = xbt_str_parse_double(argv[2], "Invalid deadline: %s");
72 xbt_assert(deadline > 0, "Wrong deadline supplied");
74 char* status = xbt_malloc0(FILE_PIECES + 1);
75 get_status(&status, peer->bitfield);
76 XBT_INFO("Hi, I'm joining the network with id %d", peer->id);
77 // Getting peer data from the tracker.
78 if (get_peers_data(peer)) {
79 XBT_DEBUG("Got %d peers from the tracker. Current status is: %s", xbt_dict_length(peer->peers), status);
80 peer->begin_receive_time = MSG_get_clock();
81 MSG_mailbox_set_async(peer->mailbox);
82 if (has_finished(peer->bitfield)) {
83 send_handshake_all(peer);
85 leech_loop(peer, deadline);
87 seed_loop(peer, deadline);
89 XBT_INFO("Couldn't contact the tracker.");
92 get_status(&status, peer->bitfield);
93 XBT_INFO("Here is my current status: %s", status);
94 if (peer->comm_received) {
95 MSG_comm_destroy(peer->comm_received);
103 /** @brief Peer main loop when it is leeching.
104 * @param peer peer data
105 * @param deadline time at which the peer has to leave
107 void leech_loop(peer_t peer, double deadline)
109 double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
110 XBT_DEBUG("Start downloading.");
112 /* Send a "handshake" message to all the peers it got (since it couldn't have gotten more than 50 peers) */
113 send_handshake_all(peer);
114 XBT_DEBUG("Starting main leech loop");
116 while (MSG_get_clock() < deadline && count_pieces(peer->bitfield) < FILE_PIECES) {
117 if (peer->comm_received == NULL) {
118 peer->task_received = NULL;
119 peer->comm_received = MSG_task_irecv(&peer->task_received, peer->mailbox);
121 if (MSG_comm_test(peer->comm_received)) {
122 msg_error_t status = MSG_comm_get_status(peer->comm_received);
123 MSG_comm_destroy(peer->comm_received);
124 peer->comm_received = NULL;
125 if (status == MSG_OK) {
126 handle_message(peer, peer->task_received);
129 // We don't execute the choke algorithm if we don't already have a piece
130 if (MSG_get_clock() >= next_choked_update && count_pieces(peer->bitfield) > 0) {
131 update_choked_peers(peer);
132 next_choked_update += UPDATE_CHOKED_INTERVAL;
134 MSG_process_sleep(SLEEP_DURATION);
138 if (has_finished(peer->bitfield))
139 XBT_DEBUG("%d becomes a seeder", peer->id);
142 /** @brief Peer main loop when it is seeding
143 * @param peer peer data
144 * @param deadline time when the peer will leave
146 void seed_loop(peer_t peer, double deadline)
148 double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
149 XBT_DEBUG("Start seeding.");
150 // start the main seed loop
151 while (MSG_get_clock() < deadline) {
152 if (peer->comm_received == NULL) {
153 peer->task_received = NULL;
154 peer->comm_received = MSG_task_irecv(&peer->task_received, peer->mailbox);
156 if (MSG_comm_test(peer->comm_received)) {
157 msg_error_t status = MSG_comm_get_status(peer->comm_received);
158 MSG_comm_destroy(peer->comm_received);
159 peer->comm_received = NULL;
160 if (status == MSG_OK) {
161 handle_message(peer, peer->task_received);
164 if (MSG_get_clock() >= next_choked_update) {
165 update_choked_peers(peer);
166 // TODO: Change the choked peer algorithm when seeding.
167 next_choked_update += UPDATE_CHOKED_INTERVAL;
169 MSG_process_sleep(SLEEP_DURATION);
175 /** @brief Retrieves the peer list from the tracker
176 * @param peer current peer data
178 int get_peers_data(peer_t peer)
181 double timeout = MSG_get_clock() + GET_PEERS_TIMEOUT;
183 // Build the task to send to the tracker
184 tracker_task_data_t data =
185 tracker_task_data_new(MSG_host_get_name(MSG_host_self()), peer->mailbox_tracker, peer->id, 0, 0, FILE_SIZE);
186 msg_task_t task_send = MSG_task_create(NULL, 0, TRACKER_COMM_SIZE, data);
187 while ((success == 0) && MSG_get_clock() < timeout) {
188 XBT_DEBUG("Sending a peer request to the tracker.");
189 msg_error_t status = MSG_task_send_with_timeout(task_send, TRACKER_MAILBOX, GET_PEERS_TIMEOUT);
190 if (status == MSG_OK) {
196 msg_task_t task_received = NULL;
197 while ((success == 0) && MSG_get_clock() < timeout) {
198 msg_comm_t comm_received = MSG_task_irecv(&task_received, peer->mailbox_tracker);
199 msg_error_t status = MSG_comm_wait(comm_received, GET_PEERS_TIMEOUT);
200 if (status == MSG_OK) {
201 tracker_task_data_t data = MSG_task_get_data(task_received);
204 // Add the peers the tracker gave us to our peer list.
205 xbt_dynar_foreach (data->peers, i, peer_id) {
206 if (peer_id != peer->id)
207 xbt_dict_set_ext(peer->peers, (char*)&peer_id, sizeof(int), connection_new(peer_id), NULL);
210 // free the communication and the task
211 MSG_comm_destroy(comm_received);
212 tracker_task_data_free(data);
213 MSG_task_destroy(task_received);
220 /** @brief Initialize the peer data.
221 * @param peer peer data
222 * @param id id of the peer to take in the network
223 * @param seed indicates if the peer is a seed.
225 peer_t peer_init(int id, int seed)
227 peer_t peer = xbt_new(s_peer_t, 1);
229 peer->hostname = MSG_host_get_name(MSG_host_self());
231 snprintf(peer->mailbox, MAILBOX_SIZE - 1, "%d", id);
232 snprintf(peer->mailbox_tracker, MAILBOX_SIZE - 1, "tracker_%d", id);
233 peer->peers = xbt_dict_new_homogeneous(NULL);
234 peer->active_peers = xbt_dict_new_homogeneous(NULL);
237 peer->bitfield = (1U << FILE_PIECES) - 1U;
238 peer->bitfield_blocks = (1ULL << (FILE_PIECES * PIECES_BLOCKS)) - 1ULL;
241 peer->bitfield_blocks = 0;
244 peer->current_pieces = 0;
246 peer->pieces_count = xbt_new0(short, FILE_PIECES);
248 peer->comm_received = NULL;
255 /** Destroys a poor peer object. */
256 void peer_free(peer_t peer)
259 connection_t connection;
260 xbt_dict_cursor_t cursor;
261 xbt_dict_foreach (peer->peers, cursor, key, connection) {
262 connection_free(connection);
264 xbt_dict_free(&peer->peers);
265 xbt_dict_free(&peer->active_peers);
266 xbt_free(peer->pieces_count);
270 /** @brief Returns if a peer has finished downloading the file
271 * @param bitfield peer bitfield
273 int has_finished(unsigned int bitfield)
275 return bitfield == (1U << FILE_PIECES) - 1U;
278 int nb_interested_peers(peer_t peer)
280 xbt_dict_cursor_t cursor = NULL;
282 connection_t connection;
284 xbt_dict_foreach (peer->peers, cursor, key, connection) {
285 if (connection->interested)
291 void update_active_peers_set(peer_t peer, connection_t remote_peer)
293 if ((remote_peer->interested != 0) && (remote_peer->choked_upload == 0)) {
294 // add in the active peers set
295 xbt_dict_set_ext(peer->active_peers, (char*)&remote_peer->id, sizeof(int), remote_peer, NULL);
296 } else if (xbt_dict_get_or_null_ext(peer->active_peers, (char*)&remote_peer->id, sizeof(int))) {
297 xbt_dict_remove_ext(peer->active_peers, (char*)&remote_peer->id, sizeof(int));
301 /** @brief Handle a received message sent by another peer
302 * @param peer Peer data
303 * @param task task received.
305 void handle_message(peer_t peer, msg_task_t task)
307 const char* type_names[10] = {"HANDSHAKE", "CHOKE", "UNCHOKE", "INTERESTED", "NOTINTERESTED",
308 "HAVE", "BITFIELD", "REQUEST", "PIECE", "CANCEL"};
309 message_t message = MSG_task_get_data(task);
310 XBT_DEBUG("Received a %s message from %s (%s)", type_names[message->type], message->mailbox,
311 message->issuer_host_name);
313 connection_t remote_peer;
314 remote_peer = xbt_dict_get_or_null_ext(peer->peers, (char*)&message->peer_id, sizeof(int));
316 switch (message->type) {
317 case MESSAGE_HANDSHAKE:
318 // Check if the peer is in our connection list.
319 if (remote_peer == 0) {
320 xbt_dict_set_ext(peer->peers, (char*)&message->peer_id, sizeof(int), connection_new(message->peer_id), NULL);
321 send_handshake(peer, message->mailbox);
323 // Send our bitfield to the peer
324 send_bitfield(peer, message->mailbox);
326 case MESSAGE_BITFIELD:
327 // Update the pieces list
328 update_pieces_count_from_bitfield(peer, message->bitfield);
329 // Store the bitfield
330 remote_peer->bitfield = message->bitfield;
331 xbt_assert(!remote_peer->am_interested, "Should not be interested at first");
332 if (is_interested(peer, remote_peer)) {
333 remote_peer->am_interested = 1;
334 send_interested(peer, message->mailbox);
337 case MESSAGE_INTERESTED:
338 xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
339 // Update the interested state of the peer.
340 remote_peer->interested = 1;
341 update_active_peers_set(peer, remote_peer);
343 case MESSAGE_NOTINTERESTED:
344 xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
345 remote_peer->interested = 0;
346 update_active_peers_set(peer, remote_peer);
348 case MESSAGE_UNCHOKE:
349 xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
350 xbt_assert(remote_peer->choked_download);
351 remote_peer->choked_download = 0;
352 // Send requests to the peer, since it has unchoked us
353 if (remote_peer->am_interested)
354 request_new_piece_to_peer(peer, remote_peer);
357 xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
358 xbt_assert(!remote_peer->choked_download);
359 remote_peer->choked_download = 1;
360 if (remote_peer->current_piece != -1)
361 remove_current_piece(peer, remote_peer, remote_peer->current_piece);
364 XBT_DEBUG("\t for piece %d", message->index);
365 xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong HAVE message received");
366 remote_peer->bitfield = remote_peer->bitfield | (1U << message->index);
367 peer->pieces_count[message->index]++;
368 // If the piece is in our pieces, we tell the peer that we are interested.
369 if ((remote_peer->am_interested == 0) && peer_has_not_piece(peer, message->index)) {
370 remote_peer->am_interested = 1;
371 send_interested(peer, message->mailbox);
372 if (remote_peer->choked_download == 0)
373 request_new_piece_to_peer(peer, remote_peer);
376 case MESSAGE_REQUEST:
377 xbt_assert(remote_peer->interested);
378 xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong request received");
379 if (remote_peer->choked_upload == 0) {
380 XBT_DEBUG("\t for piece %d (%d,%d)", message->index, message->block_index,
381 message->block_index + message->block_length);
382 if (!peer_has_not_piece(peer, message->index)) {
383 send_piece(peer, message->mailbox, message->index, message->block_index, message->block_length);
386 XBT_DEBUG("\t for piece %d but he is choked.", message->peer_id);
390 XBT_DEBUG(" \t for piece %d (%d,%d)", message->index, message->block_index,
391 message->block_index + message->block_length);
392 xbt_assert(!remote_peer->choked_download);
393 xbt_assert(remote_peer->am_interested || ENABLE_END_GAME_MODE,
394 "Can't received a piece if I'm not interested wihtout end-game mode!"
395 "piece (%d) bitfield(%u) remote bitfield(%u)",
396 message->index, peer->bitfield, remote_peer->bitfield);
397 xbt_assert(remote_peer->choked_download != 1, "Can't received a piece if I'm choked !");
398 xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong piece received");
399 // TODO: Execute à computation.
400 if (peer_has_not_piece(peer, message->index)) {
401 update_bitfield_blocks(peer, message->index, message->block_index, message->block_length);
402 if (piece_complete(peer, message->index)) {
403 // Removing the piece from our piece list
404 remove_current_piece(peer, remote_peer, message->index);
405 // Setting the fact that we have the piece
406 peer->bitfield = peer->bitfield | (1U << message->index);
407 char* status = xbt_malloc0(FILE_PIECES + 1);
408 get_status(&status, peer->bitfield);
409 XBT_DEBUG("My status is now %s", status);
411 // Sending the information to all the peers we are connected to
412 send_have(peer, message->index);
413 // sending UNINTERESTED to peers that do not have what we want.
414 update_interested_after_receive(peer);
415 } else { // piece not completed
416 send_request_to_peer(peer, remote_peer, message->index); // ask for the next block
419 XBT_DEBUG("However, we already have it");
420 xbt_assert(ENABLE_END_GAME_MODE, "Should not happen because we don't use end game mode !");
421 request_new_piece_to_peer(peer, remote_peer);
429 // Update the peer speed.
431 connection_add_speed_value(remote_peer, 1.0 / (MSG_get_clock() - peer->begin_receive_time));
433 peer->begin_receive_time = MSG_get_clock();
435 task_message_free(task);
438 /** Selects the appropriate piece to download and requests it to the remote_peer */
439 void request_new_piece_to_peer(peer_t peer, connection_t remote_peer)
441 int piece = select_piece_to_download(peer, remote_peer);
443 peer->current_pieces |= (1U << (unsigned int)piece);
444 send_request_to_peer(peer, remote_peer, piece);
448 /** remove current_piece from the list of currently downloaded pieces. */
449 void remove_current_piece(peer_t peer, connection_t remote_peer, unsigned int current_piece)
451 peer->current_pieces &= ~(1U << current_piece);
452 remote_peer->current_piece = -1;
455 /** @brief Updates the list of who has a piece from a bitfield
456 * @param peer peer we want to update the list
457 * @param bitfield bitfield
459 void update_pieces_count_from_bitfield(peer_t peer, unsigned int bitfield)
461 for (int i = 0; i < FILE_PIECES; i++) {
462 if (bitfield & (1U << i)) {
463 peer->pieces_count[i]++;
468 /** @brief Return the piece to be downloaded
469 * There are two cases (as described in "Bittorrent Architecture Protocol", Ryan Toole :
470 * If a piece is partially downloaded, this piece will be selected prioritarily
471 * If the peer has strictly less than 4 pieces, he chooses a piece at random.
472 * If the peer has more than pieces, he downloads the pieces that are the less replicated (rarest policy).
473 * If all pieces have been downloaded or requested, we select a random requested piece (endgame mode).
474 * @param peer: local peer
475 * @param remote_peer: information about the connection
476 * @return the piece to download if possible. -1 otherwise
478 int select_piece_to_download(peer_t peer, connection_t remote_peer)
480 int piece = partially_downloaded_piece(peer, remote_peer);
481 // strict priority policy
486 if (count_pieces(peer->current_pieces) >= (FILE_PIECES - count_pieces(peer->bitfield)) &&
487 (is_interested(peer, remote_peer) != 0)) {
488 #if ENABLE_END_GAME_MODE == 0
491 int nb_interesting_pieces = 0;
492 // compute the number of interesting pieces
493 for (int i = 0; i < FILE_PIECES; i++) {
494 if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i)) {
495 nb_interesting_pieces++;
498 xbt_assert(nb_interesting_pieces != 0);
499 // get a random interesting piece
500 int random_piece_index = rand() % nb_interesting_pieces;
501 int current_index = 0;
502 for (int i = 0; i < FILE_PIECES; i++) {
503 if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i)) {
504 if (random_piece_index == current_index) {
511 xbt_assert(piece != -1);
514 // Random first policy
515 if (count_pieces(peer->bitfield) < 4 && (is_interested_and_free(peer, remote_peer) != 0)) {
516 int nb_interesting_pieces = 0;
517 // compute the number of interesting pieces
518 for (int i = 0; i < FILE_PIECES; i++) {
519 if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
520 peer_is_not_downloading_piece(peer, i)) {
521 nb_interesting_pieces++;
524 xbt_assert(nb_interesting_pieces != 0);
525 // get a random interesting piece
526 int random_piece_index = rand() % nb_interesting_pieces;
527 int current_index = 0;
528 for (int i = 0; i < FILE_PIECES; i++) {
529 if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
530 peer_is_not_downloading_piece(peer, i)) {
531 if (random_piece_index == current_index) {
538 xbt_assert(piece != -1);
540 } else { // Rarest first policy
541 short min = SHRT_MAX;
542 int nb_min_pieces = 0;
543 int current_index = 0;
544 // compute the smallest number of copies of available pieces
545 for (int i = 0; i < FILE_PIECES; i++) {
546 if (peer->pieces_count[i] < min && peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
547 peer_is_not_downloading_piece(peer, i))
548 min = peer->pieces_count[i];
550 xbt_assert(min != SHRT_MAX || (is_interested_and_free(peer, remote_peer) == 0));
551 // compute the number of rarest pieces
552 for (int i = 0; i < FILE_PIECES; i++) {
553 if (peer->pieces_count[i] == min && peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
554 peer_is_not_downloading_piece(peer, i))
557 xbt_assert(nb_min_pieces != 0 || (is_interested_and_free(peer, remote_peer) == 0));
558 // get a random rarest piece
559 int random_rarest_index = 0;
560 if (nb_min_pieces > 0) {
561 random_rarest_index = rand() % nb_min_pieces;
563 for (int i = 0; i < FILE_PIECES; i++) {
564 if (peer->pieces_count[i] == min && peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
565 peer_is_not_downloading_piece(peer, i)) {
566 if (random_rarest_index == current_index) {
573 xbt_assert(piece != -1 || (is_interested_and_free(peer, remote_peer) == 0));
578 /** @brief Update the list of current choked and unchoked peers, using the choke algorithm
579 * @param peer the current peer
581 void update_choked_peers(peer_t peer)
583 if (nb_interested_peers(peer) == 0)
585 XBT_DEBUG("(%d) update_choked peers %u active peers", peer->id, xbt_dict_size(peer->active_peers));
586 // update the current round
587 peer->round = (peer->round + 1) % 3;
589 char* key_choked = NULL;
590 connection_t peer_chosen = NULL;
591 connection_t peer_choked = NULL;
592 // remove a peer from the list
593 xbt_dict_cursor_t cursor = NULL;
594 xbt_dict_cursor_first(peer->active_peers, &cursor);
595 if (!xbt_dict_is_empty(peer->active_peers)) {
596 key_choked = xbt_dict_cursor_get_key(cursor);
597 peer_choked = xbt_dict_cursor_get_data(cursor);
599 xbt_dict_cursor_free(&cursor);
601 /**If we are currently seeding, we unchoke the peer which has been unchoked the last time.*/
602 if (has_finished(peer->bitfield)) {
603 connection_t connection;
604 double unchoke_time = MSG_get_clock() + 1;
606 xbt_dict_foreach (peer->peers, cursor, key, connection) {
607 if (connection->last_unchoke < unchoke_time && (connection->interested != 0) &&
608 (connection->choked_upload != 0)) {
609 unchoke_time = connection->last_unchoke;
610 peer_chosen = connection;
614 // Random optimistic unchoking
615 if (peer->round == 0) {
618 // We choose a random peer to unchoke.
620 if (xbt_dict_length(peer->peers) > 0) {
621 id_chosen = rand() % xbt_dict_length(peer->peers);
624 connection_t connection;
625 xbt_dict_foreach (peer->peers, cursor, key, connection) {
626 if (i == id_chosen) {
627 peer_chosen = connection;
632 xbt_dict_cursor_free(&cursor);
633 xbt_assert(peer_chosen != NULL, "A peer should have been selected at this point");
634 if ((peer_chosen->interested == 0) || (peer_chosen->choked_upload == 0))
637 XBT_DEBUG("Nothing to do, keep going");
639 } while (peer_chosen == NULL && j < MAXIMUM_PEERS);
641 // Use the "fastest download" policy.
642 connection_t connection;
643 double fastest_speed = 0.0;
644 xbt_dict_foreach (peer->peers, cursor, key, connection) {
645 if (connection->peer_speed > fastest_speed && (connection->choked_upload != 0) &&
646 (connection->interested != 0)) {
647 peer_chosen = connection;
648 fastest_speed = connection->peer_speed;
654 if (peer_chosen != NULL)
655 XBT_DEBUG("(%d) update_choked peers unchoked (%d) ; int (%d) ; choked (%d) ", peer->id, peer_chosen->id,
656 peer_chosen->interested, peer_chosen->choked_upload);
658 if (peer_choked != peer_chosen) {
659 if (peer_choked != NULL) {
660 xbt_assert((!peer_choked->choked_upload), "Tries to choked a choked peer");
661 peer_choked->choked_upload = 1;
662 xbt_assert((*((int*)key_choked) == peer_choked->id));
663 update_active_peers_set(peer, peer_choked);
664 XBT_DEBUG("(%d) Sending a CHOKE to %d", peer->id, peer_choked->id);
665 send_choked(peer, peer_choked->mailbox);
667 if (peer_chosen != NULL) {
668 xbt_assert((peer_chosen->choked_upload), "Tries to unchoked an unchoked peer");
669 peer_chosen->choked_upload = 0;
670 xbt_dict_set_ext(peer->active_peers, (char*)&peer_chosen->id, sizeof(int), peer_chosen, NULL);
671 peer_chosen->last_unchoke = MSG_get_clock();
672 XBT_DEBUG("(%d) Sending a UNCHOKE to %d", peer->id, peer_chosen->id);
673 update_active_peers_set(peer, peer_chosen);
674 send_unchoked(peer, peer_chosen->mailbox);
679 /** @brief Update "interested" state of peers: send "not interested" to peers that don't have any more pieces we want.
680 * @param peer our peer data
682 void update_interested_after_receive(peer_t peer)
685 xbt_dict_cursor_t cursor;
686 connection_t connection;
687 xbt_dict_foreach (peer->peers, cursor, key, connection) {
688 if (connection->am_interested != 0) {
690 // Check if the peer still has a piece we want.
691 for (int i = 0; i < FILE_PIECES; i++) {
692 if (peer_has_not_piece(peer, i) && connection_has_piece(connection, i)) {
697 if (!interested) { // no more piece to download from connection
698 connection->am_interested = 0;
699 send_notinterested(peer, connection->mailbox);
705 void update_bitfield_blocks(peer_t peer, int index, int block_index, int block_length)
707 xbt_assert((index >= 0 && index <= FILE_PIECES), "Wrong piece.");
708 xbt_assert((block_index >= 0 && block_index <= PIECES_BLOCKS), "Wrong block : %d.", block_index);
709 for (int i = block_index; i < (block_index + block_length); i++) {
710 peer->bitfield_blocks |= (1ULL << (unsigned int)(index * PIECES_BLOCKS + i));
714 /** Returns if a peer has completed the download of a piece */
715 int piece_complete(peer_t peer, int index)
717 for (int i = 0; i < PIECES_BLOCKS; i++) {
718 if (!(peer->bitfield_blocks & 1ULL << (index * PIECES_BLOCKS + i))) {
725 /** Returns the first block that a peer doesn't have in a piece. If the peer has all blocks of the piece, returns -1. */
726 int get_first_block(peer_t peer, int piece)
728 for (int i = 0; i < PIECES_BLOCKS; i++) {
729 if (!(peer->bitfield_blocks & 1ULL << (piece * PIECES_BLOCKS + i))) {
736 /** Indicates if the remote peer has a piece not stored by the local peer */
737 int is_interested(peer_t peer, connection_t remote_peer)
739 return remote_peer->bitfield & (peer->bitfield ^ ((1 << FILE_PIECES) - 1));
742 /** Indicates if the remote peer has a piece not stored by the local peer nor requested by the local peer */
743 int is_interested_and_free(peer_t peer, connection_t remote_peer)
745 for (int i = 0; i < FILE_PIECES; i++) {
746 if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) && peer_is_not_downloading_piece(peer, i)) {
753 /** Returns a piece that is partially downloaded and stored by the remote peer if any -1 otherwise. */
754 int partially_downloaded_piece(peer_t peer, connection_t remote_peer)
756 for (int i = 0; i < FILE_PIECES; i++) {
757 if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) && peer_is_not_downloading_piece(peer, i) &&
758 get_first_block(peer, i) > 0)
764 /** @brief Send request messages to a peer that have unchoked us
766 * @param remote_peer peer data to the peer we want to send the request
768 void send_request_to_peer(peer_t peer, connection_t remote_peer, int piece)
770 remote_peer->current_piece = piece;
771 xbt_assert(connection_has_piece(remote_peer, piece));
772 int block_index = get_first_block(peer, piece);
773 if (block_index != -1) {
774 int block_length = MIN(BLOCKS_REQUESTED, PIECES_BLOCKS - block_index);
775 send_request(peer, remote_peer->mailbox, piece, block_index, block_length);
779 /***********************************************************
781 * Low level message functions
783 ***********************************************************/
785 /** @brief Send a "interested" message to a peer
786 * @param peer peer data
787 * @param mailbox destination mailbox
789 void send_interested(peer_t peer, const char* mailbox)
791 msg_task_t task = task_message_new(MESSAGE_INTERESTED, peer->hostname, peer->mailbox, peer->id,
792 task_message_size(MESSAGE_INTERESTED));
793 MSG_task_dsend(task, mailbox, task_message_free);
794 XBT_DEBUG("Sending INTERESTED to %s", mailbox);
797 /** @brief Send a "not interested" message to a peer
798 * @param peer peer data
799 * @param mailbox destination mailbox
801 void send_notinterested(peer_t peer, const char* mailbox)
803 msg_task_t task = task_message_new(MESSAGE_NOTINTERESTED, peer->hostname, peer->mailbox, peer->id,
804 task_message_size(MESSAGE_NOTINTERESTED));
805 MSG_task_dsend(task, mailbox, task_message_free);
806 XBT_DEBUG("Sending NOTINTERESTED to %s", mailbox);
809 /** @brief Send a handshake message to all the peers the peer has.
810 * @param peer peer data
812 void send_handshake_all(peer_t peer)
814 connection_t remote_peer;
815 xbt_dict_cursor_t cursor = NULL;
817 xbt_dict_foreach (peer->peers, cursor, key, remote_peer) {
818 msg_task_t task = task_message_new(MESSAGE_HANDSHAKE, peer->hostname, peer->mailbox, peer->id,
819 task_message_size(MESSAGE_HANDSHAKE));
820 MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
821 XBT_DEBUG("Sending a HANDSHAKE to %s", remote_peer->mailbox);
825 /** @brief Send a "handshake" message to an user
826 * @param peer peer data
827 * @param mailbox mailbox where to we send the message
829 void send_handshake(peer_t peer, const char* mailbox)
831 XBT_DEBUG("Sending a HANDSHAKE to %s", mailbox);
832 msg_task_t task = task_message_new(MESSAGE_HANDSHAKE, peer->hostname, peer->mailbox, peer->id,
833 task_message_size(MESSAGE_HANDSHAKE));
834 MSG_task_dsend(task, mailbox, task_message_free);
837 /** Send a "choked" message to a peer. */
838 void send_choked(peer_t peer, const char* mailbox)
840 XBT_DEBUG("Sending a CHOKE to %s", mailbox);
842 task_message_new(MESSAGE_CHOKE, peer->hostname, peer->mailbox, peer->id, task_message_size(MESSAGE_CHOKE));
843 MSG_task_dsend(task, mailbox, task_message_free);
846 /** Send a "unchoked" message to a peer */
847 void send_unchoked(peer_t peer, const char* mailbox)
849 XBT_DEBUG("Sending a UNCHOKE to %s", mailbox);
851 task_message_new(MESSAGE_UNCHOKE, peer->hostname, peer->mailbox, peer->id, task_message_size(MESSAGE_UNCHOKE));
852 MSG_task_dsend(task, mailbox, task_message_free);
855 /** Send a "HAVE" message to all peers we are connected to */
856 void send_have(peer_t peer, int piece)
858 XBT_DEBUG("Sending HAVE message to all my peers");
859 connection_t remote_peer;
860 xbt_dict_cursor_t cursor = NULL;
862 xbt_dict_foreach (peer->peers, cursor, key, remote_peer) {
863 msg_task_t task = task_message_index_new(MESSAGE_HAVE, peer->hostname, peer->mailbox, peer->id, piece,
864 task_message_size(MESSAGE_HAVE));
865 MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
869 /** @brief Send a bitfield message to all the peers the peer has.
870 * @param peer peer data
872 void send_bitfield(peer_t peer, const char* mailbox)
874 XBT_DEBUG("Sending a BITFIELD to %s", mailbox);
875 msg_task_t task = task_message_bitfield_new(peer->hostname, peer->mailbox, peer->id, peer->bitfield, FILE_PIECES);
876 MSG_task_dsend(task, mailbox, task_message_free);
879 /** Send a "request" message to a pair, containing a request for a piece */
880 void send_request(peer_t peer, const char* mailbox, int piece, int block_index, int block_length)
882 XBT_DEBUG("Sending a REQUEST to %s for piece %d (%d,%d)", mailbox, piece, block_index, block_length);
883 msg_task_t task = task_message_request_new(peer->hostname, peer->mailbox, peer->id, piece, block_index, block_length);
884 MSG_task_dsend(task, mailbox, task_message_free);
887 /** Send a "piece" message to a pair, containing a piece of the file */
888 void send_piece(peer_t peer, const char* mailbox, int piece, int block_index, int block_length)
890 XBT_DEBUG("Sending the PIECE %d (%d,%d) to %s", piece, block_index, block_length, mailbox);
891 xbt_assert(piece >= 0, "Tried to send a piece that doesn't exist.");
892 xbt_assert(!peer_has_not_piece(peer, piece), "Tried to send a piece that we doesn't have.");
894 task_message_piece_new(peer->hostname, peer->mailbox, peer->id, piece, block_index, block_length, BLOCK_SIZE);
895 MSG_task_dsend(task, mailbox, task_message_free);