1 /* Copyright (c) 2012-2017. 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. */
8 #include "connection.h"
10 #include <simgrid/msg.h>
11 #include <xbt/RngStream.h>
14 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_peers, "Messages specific for the peers");
17 * User parameters for transferred file data. For the test, the default values are :
18 * File size: 10 pieces * 5 blocks/piece * 16384 bytes/block = 819200 bytes
20 #define FILE_PIECES 10U
21 #define PIECES_BLOCKS 5U
22 #define BLOCK_SIZE 16384
23 static const unsigned long int FILE_SIZE = FILE_PIECES * PIECES_BLOCKS * BLOCK_SIZE;
25 /** Number of blocks asked by each request */
26 #define BLOCKS_REQUESTED 2
28 #define ENABLE_END_GAME_MODE 1
29 #define SLEEP_DURATION 1
31 int count_pieces(unsigned int bitfield){
33 unsigned int n = bitfield;
41 int peer_has_not_piece(peer_t peer, unsigned int piece){
42 return !(peer->bitfield & 1U<<piece);
45 /** Check that a piece is not currently being download by the peer. */
46 int peer_is_not_downloading_piece(peer_t peer, unsigned int piece){
47 return !(peer->current_pieces & 1U<<piece);
50 void get_status(char **status, unsigned int bitfield){
51 for(int i=FILE_PIECES-1; i>=0; i--)
52 (*status)[i] = (bitfield & (1U << i)) ? '1' : '0';
53 (*status)[FILE_PIECES] = '\0';
56 /** Peer main function */
57 int peer(int argc, char *argv[])
60 xbt_assert(argc == 3 || argc == 4, "Wrong number of arguments");
63 peer_t peer = peer_init(xbt_str_parse_int(argv[1],"Invalid ID: %s"), argc==4 ? 1:0);
66 double deadline = xbt_str_parse_double(argv[2],"Invalid deadline: %s");
67 xbt_assert(deadline > 0, "Wrong deadline supplied");
69 char *status = xbt_malloc0(FILE_PIECES+1);
70 get_status(&status, peer->bitfield);
71 XBT_INFO("Hi, I'm joining the network with id %d", peer->id);
72 //Getting peer data from the tracker.
73 if (get_peers_data(peer)) {
74 XBT_DEBUG("Got %d peers from the tracker. Current status is: %s", xbt_dict_length(peer->peers), status);
75 peer->begin_receive_time = MSG_get_clock();
76 MSG_mailbox_set_async(peer->mailbox);
77 if (has_finished(peer->bitfield)) {
78 send_handshake_all(peer);
80 leech_loop(peer, deadline);
82 seed_loop(peer, deadline);
84 XBT_INFO("Couldn't contact the tracker.");
87 get_status(&status, peer->bitfield);
88 XBT_INFO("Here is my current status: %s", status);
89 if (peer->comm_received) {
90 MSG_comm_destroy(peer->comm_received);
98 /** @brief Peer main loop when it is leeching.
99 * @param peer peer data
100 * @param deadline time at which the peer has to leave
102 void leech_loop(peer_t peer, double deadline)
104 double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
105 XBT_DEBUG("Start downloading.");
107 /* Send a "handshake" message to all the peers it got (since it couldn't have gotten more than 50 peers) */
108 send_handshake_all(peer);
109 XBT_DEBUG("Starting main leech loop");
111 while (MSG_get_clock() < deadline && count_pieces(peer->bitfield) < FILE_PIECES) {
112 if (peer->comm_received == NULL) {
113 peer->task_received = NULL;
114 peer->comm_received = MSG_task_irecv(&peer->task_received, peer->mailbox);
116 if (MSG_comm_test(peer->comm_received)) {
117 msg_error_t status = MSG_comm_get_status(peer->comm_received);
118 MSG_comm_destroy(peer->comm_received);
119 peer->comm_received = NULL;
120 if (status == MSG_OK) {
121 handle_message(peer, peer->task_received);
124 //We don't execute the choke algorithm if we don't already have a piece
125 if (MSG_get_clock() >= next_choked_update && count_pieces(peer->bitfield) > 0) {
126 update_choked_peers(peer);
127 next_choked_update += UPDATE_CHOKED_INTERVAL;
129 MSG_process_sleep(SLEEP_DURATION);
133 if (has_finished(peer->bitfield))
134 XBT_DEBUG("%d becomes a seeder", peer->id);
137 /** @brief Peer main loop when it is seeding
138 * @param peer peer data
139 * @param deadline time when the peer will leave
141 void seed_loop(peer_t peer, double deadline)
143 double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
144 XBT_DEBUG("Start seeding.");
145 //start the main seed loop
146 while (MSG_get_clock() < deadline) {
147 if (peer->comm_received == NULL) {
148 peer->task_received = NULL;
149 peer->comm_received = MSG_task_irecv(&peer->task_received, peer->mailbox);
151 if (MSG_comm_test(peer->comm_received)) {
152 msg_error_t status = MSG_comm_get_status(peer->comm_received);
153 MSG_comm_destroy(peer->comm_received);
154 peer->comm_received = NULL;
155 if (status == MSG_OK) {
156 handle_message(peer, peer->task_received);
159 if (MSG_get_clock() >= next_choked_update) {
160 update_choked_peers(peer);
161 //TODO: Change the choked peer algorithm when seeding.
162 next_choked_update += UPDATE_CHOKED_INTERVAL;
164 MSG_process_sleep(SLEEP_DURATION);
170 /** @brief Retrieves the peer list from the tracker
171 * @param peer current peer data
173 int get_peers_data(peer_t peer)
176 double timeout = MSG_get_clock() + GET_PEERS_TIMEOUT;
178 //Build the task to send to the tracker
179 tracker_task_data_t data = tracker_task_data_new(MSG_host_get_name(MSG_host_self()), peer->mailbox_tracker,
180 peer->id, 0, 0, FILE_SIZE);
181 msg_task_t task_send = MSG_task_create(NULL, 0, TRACKER_COMM_SIZE, data);
182 while ((success == 0) && MSG_get_clock() < timeout) {
183 XBT_DEBUG("Sending a peer request to the tracker.");
184 msg_error_t status = MSG_task_send_with_timeout(task_send, TRACKER_MAILBOX, GET_PEERS_TIMEOUT);
185 if (status == MSG_OK) {
191 msg_task_t task_received = NULL;
192 while ((success == 0) && MSG_get_clock() < timeout) {
193 msg_comm_t comm_received = MSG_task_irecv(&task_received, peer->mailbox_tracker);
194 msg_error_t status = MSG_comm_wait(comm_received, GET_PEERS_TIMEOUT);
195 if (status == MSG_OK) {
196 tracker_task_data_t data = MSG_task_get_data(task_received);
199 //Add the peers the tracker gave us to our peer list.
200 xbt_dynar_foreach(data->peers, i, peer_id) {
201 if (peer_id != peer->id)
202 xbt_dict_set_ext(peer->peers, (char *) &peer_id, sizeof(int), connection_new(peer_id), NULL);
205 //free the communication and the task
206 MSG_comm_destroy(comm_received);
207 tracker_task_data_free(data);
208 MSG_task_destroy(task_received);
215 /** @brief Initialize the peer data.
216 * @param peer peer data
217 * @param id id of the peer to take in the network
218 * @param seed indicates if the peer is a seed.
220 peer_t peer_init(int id, int seed)
222 peer_t peer = xbt_new(s_peer_t,1);
224 peer->hostname = MSG_host_get_name(MSG_host_self());
226 snprintf(peer->mailbox,MAILBOX_SIZE-1, "%d", id);
227 snprintf(peer->mailbox_tracker,MAILBOX_SIZE-1, "tracker_%d", id);
228 peer->peers = xbt_dict_new_homogeneous(NULL);
229 peer->active_peers = xbt_dict_new_homogeneous(NULL);
232 peer->bitfield = (1U<<FILE_PIECES)-1U;
233 peer->bitfield_blocks = (1ULL<<(FILE_PIECES * PIECES_BLOCKS))-1ULL ;
236 peer->bitfield_blocks = 0;
239 peer->current_pieces = 0;
241 peer->pieces_count = xbt_new0(short, FILE_PIECES);
243 peer->stream = (RngStream)MSG_host_get_data(MSG_host_self());
244 peer->comm_received = NULL;
251 /** Destroys a poor peer object. */
252 void peer_free(peer_t peer)
255 connection_t connection;
256 xbt_dict_cursor_t cursor;
257 xbt_dict_foreach(peer->peers, cursor, key, connection) {
258 connection_free(connection);
260 xbt_dict_free(&peer->peers);
261 xbt_dict_free(&peer->active_peers);
262 xbt_free(peer->pieces_count);
266 /** @brief Returns if a peer has finished downloading the file
267 * @param bitfield peer bitfield
269 int has_finished(unsigned int bitfield)
271 return bitfield == (1U<<FILE_PIECES)-1U;
274 int nb_interested_peers(peer_t peer)
276 xbt_dict_cursor_t cursor = NULL;
278 connection_t connection;
280 xbt_dict_foreach(peer->peers, cursor, key, connection) {
281 if (connection->interested)
287 void update_active_peers_set(peer_t peer, connection_t remote_peer)
289 if ((remote_peer->interested != 0) && (remote_peer->choked_upload == 0)) {
290 //add in the active peers set
291 xbt_dict_set_ext(peer->active_peers, (char *) &remote_peer->id, sizeof(int), remote_peer, NULL);
292 } else if (xbt_dict_get_or_null_ext(peer->active_peers, (char *) &remote_peer->id, sizeof(int))) {
293 xbt_dict_remove_ext(peer->active_peers, (char *) &remote_peer->id, sizeof(int));
297 /** @brief Handle a received message sent by another peer
298 * @param peer Peer data
299 * @param task task received.
301 void handle_message(peer_t peer, msg_task_t task)
303 const char* type_names[10] =
304 {"HANDSHAKE","CHOKE","UNCHOKE","INTERESTED","NOTINTERESTED","HAVE","BITFIELD","REQUEST", "PIECE", "CANCEL" };
305 message_t message = MSG_task_get_data(task);
306 XBT_DEBUG("Received a %s message from %s (%s)", type_names[message->type], message->mailbox,
307 message->issuer_host_name);
309 connection_t remote_peer;
310 remote_peer = xbt_dict_get_or_null_ext(peer->peers, (char *) &message->peer_id, sizeof(int));
312 switch (message->type) {
313 case MESSAGE_HANDSHAKE:
314 //Check if the peer is in our connection list.
315 if (remote_peer == 0) {
316 xbt_dict_set_ext(peer->peers, (char *) &message->peer_id, sizeof(int), connection_new(message->peer_id), NULL);
317 send_handshake(peer, message->mailbox);
319 //Send our bitfield to the peer
320 send_bitfield(peer, message->mailbox);
322 case MESSAGE_BITFIELD:
323 //Update the pieces list
324 update_pieces_count_from_bitfield(peer, message->bitfield);
326 remote_peer->bitfield = message->bitfield;
327 xbt_assert(!remote_peer->am_interested, "Should not be interested at first");
328 if (is_interested(peer, remote_peer)) {
329 remote_peer->am_interested = 1;
330 send_interested(peer, message->mailbox);
333 case MESSAGE_INTERESTED:
334 xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
335 //Update the interested state of the peer.
336 remote_peer->interested = 1;
337 update_active_peers_set(peer, remote_peer);
339 case MESSAGE_NOTINTERESTED:
340 xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
341 remote_peer->interested = 0;
342 update_active_peers_set(peer, remote_peer);
344 case MESSAGE_UNCHOKE:
345 xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
346 xbt_assert(remote_peer->choked_download);
347 remote_peer->choked_download = 0;
348 //Send requests to the peer, since it has unchoked us
349 if (remote_peer->am_interested)
350 request_new_piece_to_peer(peer, remote_peer);
353 xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
354 xbt_assert(!remote_peer->choked_download);
355 remote_peer->choked_download = 1;
356 if (remote_peer->current_piece != -1)
357 remove_current_piece(peer, remote_peer, remote_peer->current_piece);
360 XBT_DEBUG("\t for piece %d", message->index);
361 xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong HAVE message received");
362 remote_peer->bitfield = remote_peer->bitfield | (1U<<message->index);
363 peer->pieces_count[message->index]++;
364 //If the piece is in our pieces, we tell the peer that we are interested.
365 if ((remote_peer->am_interested == 0) && peer_has_not_piece(peer,message->index)) {
366 remote_peer->am_interested = 1;
367 send_interested(peer, message->mailbox);
368 if (remote_peer->choked_download == 0)
369 request_new_piece_to_peer(peer, remote_peer);
372 case MESSAGE_REQUEST:
373 xbt_assert(remote_peer->interested);
374 xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong request received");
375 if (remote_peer->choked_upload == 0) {
376 XBT_DEBUG("\t for piece %d (%d,%d)", message->index, message->block_index,
377 message->block_index + message->block_length);
378 if (!peer_has_not_piece(peer, message->index)) {
379 send_piece(peer, message->mailbox, message->index, message->block_index, message->block_length);
382 XBT_DEBUG("\t for piece %d but he is choked.", message->peer_id);
386 XBT_DEBUG(" \t for piece %d (%d,%d)", message->index, message->block_index,
387 message->block_index + message->block_length);
388 xbt_assert(!remote_peer->choked_download);
389 xbt_assert(remote_peer->am_interested || ENABLE_END_GAME_MODE,
390 "Can't received a piece if I'm not interested wihtout end-game mode!"
391 "piece (%d) bitfield(%u) remote bitfield(%u)", message->index, peer->bitfield, remote_peer->bitfield);
392 xbt_assert(remote_peer->choked_download != 1, "Can't received a piece if I'm choked !");
393 xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong piece received");
394 //TODO: Execute à computation.
395 if (peer_has_not_piece(peer,message->index)) {
396 update_bitfield_blocks(peer, message->index, message->block_index, message->block_length);
397 if (piece_complete(peer, message->index)) {
398 //Removing the piece from our piece list
399 remove_current_piece(peer, remote_peer, message->index);
400 //Setting the fact that we have the piece
401 peer->bitfield = peer->bitfield | (1U<<message->index);
402 char* status = xbt_malloc0(FILE_PIECES+1);
403 get_status(&status, peer->bitfield);
404 XBT_DEBUG("My status is now %s", status);
406 //Sending the information to all the peers we are connected to
407 send_have(peer, message->index);
408 //sending UNINTERESTED to peers that do not have what we want.
409 update_interested_after_receive(peer);
410 } else { // piece not completed
411 send_request_to_peer(peer, remote_peer, message->index); // ask for the next block
414 XBT_DEBUG("However, we already have it");
415 xbt_assert(ENABLE_END_GAME_MODE, "Should not happen because we don't use end game mode !");
416 request_new_piece_to_peer(peer, remote_peer);
424 //Update the peer speed.
426 connection_add_speed_value(remote_peer, 1.0 / (MSG_get_clock() - peer->begin_receive_time));
428 peer->begin_receive_time = MSG_get_clock();
430 task_message_free(task);
433 /** Selects the appropriate piece to download and requests it to the remote_peer */
434 void request_new_piece_to_peer(peer_t peer, connection_t remote_peer)
436 int piece = select_piece_to_download(peer, remote_peer);
438 peer->current_pieces|= (1U << (unsigned int) piece);
439 send_request_to_peer(peer, remote_peer, piece);
443 /** remove current_piece from the list of currently downloaded pieces. */
444 void remove_current_piece(peer_t peer, connection_t remote_peer, unsigned int current_piece)
446 peer->current_pieces &= ~(1U << current_piece);
447 remote_peer->current_piece = -1;
450 /** @brief Updates the list of who has a piece from a bitfield
451 * @param peer peer we want to update the list
452 * @param bitfield bitfield
454 void update_pieces_count_from_bitfield(peer_t peer, unsigned int bitfield)
456 for (int i = 0; i < FILE_PIECES; i++) {
457 if ((bitfield & (1U << i))) {
458 peer->pieces_count[i]++;
463 /** @brief Return the piece to be downloaded
464 * There are two cases (as described in "Bittorrent Architecture Protocol", Ryan Toole :
465 * If a piece is partially downloaded, this piece will be selected prioritarily
466 * If the peer has strictly less than 4 pieces, he chooses a piece at random.
467 * If the peer has more than pieces, he downloads the pieces that are the less replicated (rarest policy).
468 * If all pieces have been downloaded or requested, we select a random requested piece (endgame mode).
469 * @param peer: local peer
470 * @param remote_peer: information about the connection
471 * @return the piece to download if possible. -1 otherwise
473 int select_piece_to_download(peer_t peer, connection_t remote_peer)
475 int piece = partially_downloaded_piece(peer, remote_peer);
476 // strict priority policy
481 if (count_pieces(peer->current_pieces) >= (FILE_PIECES - count_pieces(peer->bitfield)) &&
482 (is_interested(peer, remote_peer) != 0)) {
483 #if ENABLE_END_GAME_MODE == 0
486 int nb_interesting_pieces = 0;
487 // compute the number of interesting pieces
488 for (int i = 0; i < FILE_PIECES; i++) {
489 if (peer_has_not_piece(peer,i) && connection_has_piece(remote_peer,i)) {
490 nb_interesting_pieces++;
493 xbt_assert(nb_interesting_pieces != 0);
494 // get a random interesting piece
495 int random_piece_index = RngStream_RandInt(peer->stream, 0, nb_interesting_pieces - 1);
496 int current_index = 0;
497 for (int i = 0; i < FILE_PIECES; i++) {
498 if (peer_has_not_piece(peer,i) && connection_has_piece(remote_peer,i)) {
499 if (random_piece_index == current_index) {
506 xbt_assert(piece != -1);
509 // Random first policy
510 if (count_pieces(peer->bitfield) < 4 && (is_interested_and_free(peer, remote_peer) != 0)) {
511 int nb_interesting_pieces = 0;
512 // compute the number of interesting pieces
513 for (int i = 0; i < FILE_PIECES; i++) {
514 if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer,i) && peer_is_not_downloading_piece(peer, i)) {
515 nb_interesting_pieces++;
518 xbt_assert(nb_interesting_pieces != 0);
519 // get a random interesting piece
520 int random_piece_index = RngStream_RandInt(peer->stream, 0, nb_interesting_pieces - 1);
521 int current_index = 0;
522 for (int i = 0; i < FILE_PIECES; i++) {
523 if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer,i) && peer_is_not_downloading_piece(peer, i)) {
524 if (random_piece_index == current_index) {
531 xbt_assert(piece != -1);
533 } else { // Rarest first policy
534 short min = SHRT_MAX;
535 int nb_min_pieces = 0;
536 int current_index = 0;
537 // compute the smallest number of copies of available pieces
538 for (int i = 0; i < FILE_PIECES; i++) {
539 if (peer->pieces_count[i] < min && peer_has_not_piece(peer, i) && connection_has_piece(remote_peer,i) &&
540 peer_is_not_downloading_piece(peer, i))
541 min = peer->pieces_count[i];
543 xbt_assert(min != SHRT_MAX || (is_interested_and_free(peer, remote_peer) ==0));
544 // compute the number of rarest 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))
550 xbt_assert(nb_min_pieces != 0 || (is_interested_and_free(peer, remote_peer)==0));
551 // get a random rarest piece
552 int random_rarest_index = RngStream_RandInt(peer->stream, 0, nb_min_pieces - 1);
553 for (int i = 0; i < FILE_PIECES; i++) {
554 if (peer->pieces_count[i] == min && peer_has_not_piece(peer, i) && connection_has_piece(remote_peer,i) &&
555 peer_is_not_downloading_piece(peer, i)) {
556 if (random_rarest_index == current_index) {
563 xbt_assert(piece != -1 || (is_interested_and_free(peer, remote_peer) == 0));
568 /** @brief Update the list of current choked and unchoked peers, using the choke algorithm
569 * @param peer the current peer
571 void update_choked_peers(peer_t peer)
573 if (nb_interested_peers(peer) == 0)
575 XBT_DEBUG("(%d) update_choked peers %d active peers", peer->id, xbt_dict_size(peer->active_peers));
576 //update the current round
577 peer->round = (peer->round + 1) % 3;
579 char *key_choked=NULL;
580 connection_t peer_choosed = NULL;
581 connection_t peer_choked = NULL;
582 //remove a peer from the list
583 xbt_dict_cursor_t cursor = NULL;
584 xbt_dict_cursor_first(peer->active_peers, &cursor);
585 if (xbt_dict_length(peer->active_peers) > 0) {
586 key_choked = xbt_dict_cursor_get_key(cursor);
587 peer_choked = xbt_dict_cursor_get_data(cursor);
589 xbt_dict_cursor_free(&cursor);
591 /**If we are currently seeding, we unchoke the peer which has been unchoked the last time.*/
592 if (has_finished(peer->bitfield)) {
593 connection_t connection;
594 double unchoke_time = MSG_get_clock() + 1;
596 xbt_dict_foreach(peer->peers, cursor, key, connection) {
597 if (connection->last_unchoke < unchoke_time &&
598 (connection->interested != 0) && (connection->choked_upload != 0)) {
599 unchoke_time = connection->last_unchoke;
600 peer_choosed = connection;
604 //Random optimistic unchoking
605 if (peer->round == 0) {
608 //We choose a random peer to unchoke.
609 int id_chosen = RngStream_RandInt(peer->stream, 0, xbt_dict_length(peer->peers) - 1);
611 connection_t connection;
612 xbt_dict_foreach(peer->peers, cursor, key, connection) {
613 if (i == id_chosen) {
614 peer_choosed = connection;
619 xbt_dict_cursor_free(&cursor);
620 if (peer_choosed == NULL)
621 THROWF(unknown_error, 0, "A peer should have be selected at this point");
622 else if ((peer_choosed->interested == 0) || (peer_choosed->choked_upload == 0))
625 XBT_DEBUG("Nothing to do, keep going");
627 } while (peer_choosed == NULL && j < MAXIMUM_PAIRS);
629 //Use the "fastest download" policy.
630 connection_t connection;
631 double fastest_speed = 0.0;
632 xbt_dict_foreach(peer->peers, cursor, key, connection) {
633 if (connection->peer_speed > fastest_speed &&
634 (connection->choked_upload != 0) && (connection->interested != 0)) {
635 peer_choosed = connection;
636 fastest_speed = connection->peer_speed;
642 if (peer_choosed != NULL)
643 XBT_DEBUG("(%d) update_choked peers unchoked (%d) ; int (%d) ; choked (%d) ",
644 peer->id, peer_choosed->id, peer_choosed->interested, peer_choosed->choked_upload);
646 if (peer_choked != peer_choosed) {
647 if (peer_choked != NULL) {
648 xbt_assert((!peer_choked->choked_upload), "Tries to choked a choked peer");
649 peer_choked->choked_upload = 1;
650 xbt_assert((*((int *) key_choked) == peer_choked->id));
651 update_active_peers_set(peer, peer_choked);
652 XBT_DEBUG("(%d) Sending a CHOKE to %d", peer->id, peer_choked->id);
653 send_choked(peer, peer_choked->mailbox);
655 if (peer_choosed != NULL) {
656 xbt_assert((peer_choosed->choked_upload), "Tries to unchoked an unchoked peer");
657 peer_choosed->choked_upload = 0;
658 xbt_dict_set_ext(peer->active_peers, (char *) &peer_choosed->id, sizeof(int), peer_choosed, NULL);
659 peer_choosed->last_unchoke = MSG_get_clock();
660 XBT_DEBUG("(%d) Sending a UNCHOKE to %d", peer->id, peer_choosed->id);
661 update_active_peers_set(peer, peer_choosed);
662 send_unchoked(peer, peer_choosed->mailbox);
667 /** @brief Update "interested" state of peers: send "not interested" to peers that don't have any more pieces we want.
668 * @param peer our peer data
670 void update_interested_after_receive(peer_t peer)
673 xbt_dict_cursor_t cursor;
674 connection_t connection;
676 xbt_dict_foreach(peer->peers, cursor, key, connection) {
678 if (connection->am_interested != 0) {
679 //Check if the peer still has a piece we want.
680 for (int i = 0; i < FILE_PIECES; i++) {
681 if (peer_has_not_piece(peer, i) && connection_has_piece(connection,i)) {
686 if (!interested) { //no more piece to download from connection
687 connection->am_interested = 0;
688 send_notinterested(peer, connection->mailbox);
694 void update_bitfield_blocks(peer_t peer, int index, int block_index, int block_length)
696 xbt_assert((index >= 0 && index <= FILE_PIECES), "Wrong piece.");
697 xbt_assert((block_index >= 0 && block_index <= PIECES_BLOCKS), "Wrong block : %d.", block_index);
698 for (int i = block_index; i < (block_index + block_length); i++) {
699 peer->bitfield_blocks |= (1ULL<<(unsigned int)(index * PIECES_BLOCKS + i));
703 /** Returns if a peer has completed the download of a piece */
704 int piece_complete(peer_t peer, int index)
706 for (int i = 0; i < PIECES_BLOCKS; i++) {
707 if (!(peer->bitfield_blocks & 1ULL<<(index * PIECES_BLOCKS + i))) {
714 /** Returns the first block that a peer doesn't have in a piece. If the peer has all blocks of the piece, returns -1. */
715 int get_first_block(peer_t peer, int piece)
717 for (int i = 0; i < PIECES_BLOCKS; i++) {
718 if (!(peer->bitfield_blocks & 1ULL<<(piece * PIECES_BLOCKS + i))) {
725 /** Indicates if the remote peer has a piece not stored by the local peer */
726 int is_interested(peer_t peer, connection_t remote_peer)
728 return remote_peer->bitfield & (peer->bitfield^((1<<FILE_PIECES)-1));
731 /** Indicates if the remote peer has a piece not stored by the local peer nor requested by the local peer */
732 int is_interested_and_free(peer_t peer, connection_t remote_peer)
734 for (int i = 0; i < FILE_PIECES; i++) {
735 if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer,i) && peer_is_not_downloading_piece(peer, i)) {
742 /** Returns a piece that is partially downloaded and stored by the remote peer if any -1 otherwise. */
743 int partially_downloaded_piece(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)) {
747 if (get_first_block(peer, i) > 0)
754 /** @brief Send request messages to a peer that have unchoked us
756 * @param remote_peer peer data to the peer we want to send the request
758 void send_request_to_peer(peer_t peer, connection_t remote_peer, int piece)
760 remote_peer->current_piece = piece;
761 xbt_assert(connection_has_piece(remote_peer,piece));
762 int block_index = get_first_block(peer, piece);
763 if (block_index != -1) {
764 int block_length = MIN(BLOCKS_REQUESTED, PIECES_BLOCKS - block_index);
765 send_request(peer, remote_peer->mailbox, piece, block_index, block_length);
769 /***********************************************************
771 * Low level message functions
773 ***********************************************************/
775 /** @brief Send a "interested" message to a peer
776 * @param peer peer data
777 * @param mailbox destination mailbox
779 void send_interested(peer_t peer, const char *mailbox)
781 msg_task_t task = task_message_new(MESSAGE_INTERESTED, peer->hostname, peer->mailbox, peer->id,
782 task_message_size(MESSAGE_INTERESTED));
783 MSG_task_dsend(task, mailbox, task_message_free);
784 XBT_DEBUG("Sending INTERESTED to %s", mailbox);
787 /** @brief Send a "not interested" message to a peer
788 * @param peer peer data
789 * @param mailbox destination mailbox
791 void send_notinterested(peer_t peer, const char *mailbox)
793 msg_task_t task = task_message_new(MESSAGE_NOTINTERESTED, peer->hostname, peer->mailbox, peer->id,
794 task_message_size(MESSAGE_NOTINTERESTED));
795 MSG_task_dsend(task, mailbox, task_message_free);
796 XBT_DEBUG("Sending NOTINTERESTED to %s", mailbox);
799 /** @brief Send a handshake message to all the peers the peer has.
800 * @param peer peer data
802 void send_handshake_all(peer_t peer)
804 connection_t remote_peer;
805 xbt_dict_cursor_t cursor = NULL;
807 xbt_dict_foreach(peer->peers, cursor, key, remote_peer) {
808 msg_task_t task = task_message_new(MESSAGE_HANDSHAKE, peer->hostname, peer->mailbox, peer->id,
809 task_message_size(MESSAGE_HANDSHAKE));
810 MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
811 XBT_DEBUG("Sending a HANDSHAKE to %s", remote_peer->mailbox);
815 /** @brief Send a "handshake" message to an user
816 * @param peer peer data
817 * @param mailbox mailbox where to we send the message
819 void send_handshake(peer_t peer, const char *mailbox)
821 XBT_DEBUG("Sending a HANDSHAKE to %s", mailbox);
822 msg_task_t task = task_message_new(MESSAGE_HANDSHAKE, peer->hostname, peer->mailbox, peer->id,
823 task_message_size(MESSAGE_HANDSHAKE));
824 MSG_task_dsend(task, mailbox, task_message_free);
827 /** Send a "choked" message to a peer. */
828 void send_choked(peer_t peer, const char *mailbox)
830 XBT_DEBUG("Sending a CHOKE to %s", mailbox);
831 msg_task_t task = task_message_new(MESSAGE_CHOKE, peer->hostname, peer->mailbox, peer->id,
832 task_message_size(MESSAGE_CHOKE));
833 MSG_task_dsend(task, mailbox, task_message_free);
836 /** Send a "unchoked" message to a peer */
837 void send_unchoked(peer_t peer, const char *mailbox)
839 XBT_DEBUG("Sending a UNCHOKE to %s", mailbox);
840 msg_task_t task = task_message_new(MESSAGE_UNCHOKE, peer->hostname, peer->mailbox, peer->id,
841 task_message_size(MESSAGE_UNCHOKE));
842 MSG_task_dsend(task, mailbox, task_message_free);
845 /** Send a "HAVE" message to all peers we are connected to */
846 void send_have(peer_t peer, int piece)
848 XBT_DEBUG("Sending HAVE message to all my peers");
849 connection_t remote_peer;
850 xbt_dict_cursor_t cursor = NULL;
852 xbt_dict_foreach(peer->peers, cursor, key, remote_peer) {
853 msg_task_t task = task_message_index_new(MESSAGE_HAVE, peer->hostname, peer->mailbox, peer->id, piece,
854 task_message_size(MESSAGE_HAVE));
855 MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
859 /** @brief Send a bitfield message to all the peers the peer has.
860 * @param peer peer data
862 void send_bitfield(peer_t peer, const char *mailbox)
864 XBT_DEBUG("Sending a BITFIELD to %s", mailbox);
865 msg_task_t task = task_message_bitfield_new(peer->hostname, peer->mailbox, peer->id, peer->bitfield, FILE_PIECES);
866 MSG_task_dsend(task, mailbox, task_message_free);
869 /** Send a "request" message to a pair, containing a request for a piece */
870 void send_request(peer_t peer, const char *mailbox, int piece, int block_index, int block_length)
872 XBT_DEBUG("Sending a REQUEST to %s for piece %d (%d,%d)", mailbox, piece, block_index, block_length);
873 msg_task_t task = task_message_request_new(peer->hostname, peer->mailbox, peer->id, piece, block_index, block_length);
874 MSG_task_dsend(task, mailbox, task_message_free);
877 /** Send a "piece" message to a pair, containing a piece of the file */
878 void send_piece(peer_t peer, const char *mailbox, int piece, int block_index, int block_length)
880 XBT_DEBUG("Sending the PIECE %d (%d,%d) to %s", piece, block_index, block_length, mailbox);
881 xbt_assert(piece >= 0, "Tried to send a piece that doesn't exist.");
882 xbt_assert(!peer_has_not_piece(peer,piece), "Tried to send a piece that we doesn't have.");
883 msg_task_t task = task_message_piece_new(peer->hostname, peer->mailbox, peer->id, piece, block_index, block_length,
885 MSG_task_dsend(task, mailbox, task_message_free);