1 /* Copyright (c) 2012-2016. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
9 #include "connection.h"
11 #include <simgrid/msg.h>
12 #include <xbt/RngStream.h>
15 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_peers, "Messages specific for the peers");
17 //TODO: Let users change this
19 * File transfered data
20 * For the test, default values are :
21 * File size: 10 pieces * 5 blocks/piece * 16384 bytes/block = 819200 bytes
24 #define FILE_PIECES 10
25 #define PIECES_BLOCKS 5
26 #define BLOCK_SIZE 16384
27 #define ENABLE_END_GAME_MODE 1
29 /** Number of blocks asked by each request */
30 #define BLOCKS_REQUESTED 2
32 static const unsigned long int FILE_SIZE = FILE_PIECES * PIECES_BLOCKS * BLOCK_SIZE;
34 #define SLEEP_DURATION 1
36 /** Peer main function */
37 int peer(int argc, char *argv[])
41 xbt_assert(argc == 3 || argc == 4, "Wrong number of arguments");
44 peer_init(&peer, xbt_str_parse_int(argv[1],"Invalid ID: %s"), 1);
46 peer_init(&peer, xbt_str_parse_int(argv[1],"Invalid ID: %s"), 0);
49 double deadline = xbt_str_parse_double(argv[2],"Invalid deadline: %s");
50 xbt_assert(deadline > 0, "Wrong deadline supplied");
51 XBT_INFO("Hi, I'm joining the network with id %d", peer.id);
52 //Getting peer data from the tracker.
53 if (get_peers_data(&peer)) {
54 XBT_DEBUG("Got %d peers from the tracker", xbt_dict_length(peer.peers));
55 XBT_DEBUG("Here is my current status: %s", peer.bitfield);
56 peer.begin_receive_time = MSG_get_clock();
57 MSG_mailbox_set_async(peer.mailbox);
58 if (has_finished(peer.bitfield)) {
59 peer.pieces = FILE_PIECES;
60 send_handshake_all(&peer);
61 seed_loop(&peer, deadline);
63 leech_loop(&peer, deadline);
64 seed_loop(&peer, deadline);
67 XBT_INFO("Couldn't contact the tracker.");
70 XBT_INFO("Here is my current status: %s", peer.bitfield);
71 if (peer.comm_received) {
72 MSG_comm_destroy(peer.comm_received);
79 /** @brief Peer main loop when it is leeching.
80 * @param peer peer data
81 * @param deadline time at which the peer has to leave
83 void leech_loop(peer_t peer, double deadline)
85 double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
86 XBT_DEBUG("Start downloading.");
88 * Send a "handshake" message to all the peers it got
89 * (since it couldn't have gotten more than 50 peers)
91 send_handshake_all(peer);
92 XBT_DEBUG("Starting main leech loop");
94 while (MSG_get_clock() < deadline && peer->pieces < FILE_PIECES) {
95 if (peer->comm_received == NULL) {
96 peer->task_received = NULL;
97 peer->comm_received = MSG_task_irecv(&peer->task_received, peer->mailbox);
99 if (MSG_comm_test(peer->comm_received)) {
100 msg_error_t status = MSG_comm_get_status(peer->comm_received);
101 MSG_comm_destroy(peer->comm_received);
102 peer->comm_received = NULL;
103 if (status == MSG_OK) {
104 handle_message(peer, peer->task_received);
107 //We don't execute the choke algorithm if we don't already have a piece
108 if (MSG_get_clock() >= next_choked_update && peer->pieces > 0) {
109 update_choked_peers(peer);
110 next_choked_update += UPDATE_CHOKED_INTERVAL;
112 MSG_process_sleep(SLEEP_DURATION);
116 if (peer->pieces == FILE_PIECES)
117 XBT_DEBUG("%d becomes a seeder", peer->id);
121 /** @brief Peer main loop when it is seeding
122 * @param peer peer data
123 * @param deadline time when the peer will leave
125 void seed_loop(peer_t peer, double deadline)
127 double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
128 XBT_DEBUG("Start seeding.");
129 //start the main seed loop
130 while (MSG_get_clock() < deadline) {
131 if (peer->comm_received == NULL) {
132 peer->task_received = NULL;
133 peer->comm_received = MSG_task_irecv(&peer->task_received, peer->mailbox);
135 if (MSG_comm_test(peer->comm_received)) {
136 msg_error_t status = MSG_comm_get_status(peer->comm_received);
137 MSG_comm_destroy(peer->comm_received);
138 peer->comm_received = NULL;
139 if (status == MSG_OK) {
140 handle_message(peer, peer->task_received);
143 if (MSG_get_clock() >= next_choked_update) {
144 update_choked_peers(peer);
145 //TODO: Change the choked peer algorithm when seeding.
146 next_choked_update += UPDATE_CHOKED_INTERVAL;
148 MSG_process_sleep(SLEEP_DURATION);
154 /** @brief Retrieves the peer list from the tracker
155 * @param peer current peer data
157 int get_peers_data(peer_t peer)
159 int success = 0, send_success = 0;
160 double timeout = MSG_get_clock() + GET_PEERS_TIMEOUT;
161 //Build the task to send to the tracker
162 tracker_task_data_t data = tracker_task_data_new(MSG_host_get_name(MSG_host_self()), peer->mailbox_tracker,
163 peer->id, 0, 0, FILE_SIZE);
164 //Build the task to send.
165 msg_task_t task_send = MSG_task_create(NULL, 0, TRACKER_COMM_SIZE, data);
166 msg_task_t task_received = NULL;
167 msg_comm_t comm_received;
168 while ((send_success == 0) && MSG_get_clock() < timeout) {
169 XBT_DEBUG("Sending a peer request to the tracker.");
170 msg_error_t status = MSG_task_send_with_timeout(task_send, TRACKER_MAILBOX, GET_PEERS_TIMEOUT);
171 if (status == MSG_OK) {
175 while ((success ==0) && MSG_get_clock() < timeout) {
176 comm_received = MSG_task_irecv(&task_received, peer->mailbox_tracker);
177 msg_error_t status = MSG_comm_wait(comm_received, GET_PEERS_TIMEOUT);
178 if (status == MSG_OK) {
179 tracker_task_data_t data = MSG_task_get_data(task_received);
182 //Add the peers the tracker gave us to our peer list.
183 xbt_dynar_foreach(data->peers, i, peer_id) {
184 if (peer_id != peer->id)
185 xbt_dict_set_ext(peer->peers, (char *) &peer_id, sizeof(int), connection_new(peer_id), NULL);
188 //free the communication and the task
189 MSG_comm_destroy(comm_received);
190 tracker_task_data_free(data);
191 MSG_task_destroy(task_received);
192 comm_received = NULL;
199 /** @brief Initialize the peer data.
200 * @param peer peer data
201 * @param id id of the peer to take in the network
202 * @param seed indicates if the peer is a seed.
204 void peer_init(peer_t peer, int id, int seed)
207 snprintf(peer->mailbox,MAILBOX_SIZE-1, "%d", id);
208 snprintf(peer->mailbox_tracker,MAILBOX_SIZE-1, "tracker_%d", id);
209 peer->peers = xbt_dict_new();
210 peer->active_peers = xbt_dict_new();
211 peer->hostname = MSG_host_get_name(MSG_host_self());
213 peer->bitfield = xbt_new(char, FILE_PIECES + 1);
214 peer->bitfield_blocks = xbt_new(char, (FILE_PIECES) * (PIECES_BLOCKS) + 1);
216 memset(peer->bitfield, '1', sizeof(char) * (FILE_PIECES + 1));
217 memset(peer->bitfield_blocks, '1', sizeof(char) * FILE_PIECES * (PIECES_BLOCKS));
219 memset(peer->bitfield, '0', sizeof(char) * (FILE_PIECES + 1));
220 memset(peer->bitfield_blocks, '0', sizeof(char) * FILE_PIECES * (PIECES_BLOCKS));
223 peer->bitfield[FILE_PIECES] = '\0';
226 peer->pieces_count = xbt_new0(short, FILE_PIECES);
228 peer->current_pieces = xbt_dynar_new(sizeof(int), NULL);
230 peer->stream = (RngStream)MSG_host_get_property_value(MSG_host_self(), "stream");
231 peer->comm_received = NULL;
236 /** Destroys a poor peer object. */
237 void peer_free(peer_t peer)
240 connection_t connection;
241 xbt_dict_cursor_t cursor;
242 xbt_dict_foreach(peer->peers, cursor, key, connection) {
243 connection_free(connection);
245 xbt_dict_free(&peer->peers);
246 xbt_dict_free(&peer->active_peers);
247 xbt_dynar_free(&peer->current_pieces);
248 xbt_free(peer->pieces_count);
249 xbt_free(peer->bitfield);
250 xbt_free(peer->bitfield_blocks);
253 /** @brief Returns if a peer has finished downloading the file
254 * @param bitfield peer bitfield
256 int has_finished(char *bitfield)
258 return ((memchr(bitfield, '0', sizeof(char) * FILE_PIECES) == NULL) ? 1 : 0);
261 int nb_interested_peers(peer_t peer)
263 xbt_dict_cursor_t cursor = NULL;
265 connection_t connection;
267 xbt_dict_foreach(peer->peers, cursor, key, connection) {
268 if (connection->interested)
274 void update_active_peers_set(peer_t peer, connection_t remote_peer)
276 if ((remote_peer->interested != 0) && (remote_peer->choked_upload == 0)) {
277 //add in the active peers set
278 xbt_dict_set_ext(peer->active_peers, (char *) &remote_peer->id, sizeof(int), remote_peer, NULL);
279 } else if (xbt_dict_get_or_null_ext(peer->active_peers, (char *) &remote_peer->id, sizeof(int))) {
280 xbt_dict_remove_ext(peer->active_peers, (char *) &remote_peer->id, sizeof(int));
284 /** @brief Handle a received message sent by another peer
285 * @param peer Peer data
286 * @param task task received.
288 void handle_message(peer_t peer, msg_task_t task)
290 message_t message = MSG_task_get_data(task);
291 connection_t remote_peer;
292 remote_peer = xbt_dict_get_or_null_ext(peer->peers, (char *) &message->peer_id, sizeof(int));
293 switch (message->type) {
294 case MESSAGE_HANDSHAKE:
295 XBT_DEBUG("Received a HANDSHAKE from %s (%s)", message->mailbox, message->issuer_host_name);
296 //Check if the peer is in our connection list.
297 if (remote_peer == 0) {
298 xbt_dict_set_ext(peer->peers, (char *) &message->peer_id, sizeof(int), connection_new(message->peer_id), NULL);
299 send_handshake(peer, message->mailbox);
301 //Send our bitfield to the peer
302 send_bitfield(peer, message->mailbox);
304 case MESSAGE_BITFIELD:
305 XBT_DEBUG("Recieved a BITFIELD message from %s (%s)", message->mailbox, message->issuer_host_name);
306 //Update the pieces list
307 update_pieces_count_from_bitfield(peer, message->bitfield);
309 remote_peer->bitfield = xbt_strdup(message->bitfield);
310 xbt_assert(!remote_peer->am_interested, "Should not be interested at first");
311 if (is_interested(peer, remote_peer)) {
312 remote_peer->am_interested = 1;
313 send_interested(peer, message->mailbox);
316 case MESSAGE_INTERESTED:
317 XBT_DEBUG("Recieved an INTERESTED message from %s (%s)", message->mailbox, message->issuer_host_name);
318 xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
319 //Update the interested state of the peer.
320 remote_peer->interested = 1;
321 update_active_peers_set(peer, remote_peer);
323 case MESSAGE_NOTINTERESTED:
324 XBT_DEBUG("Received a NOTINTERESTED message from %s (%s)", message->mailbox, message->issuer_host_name);
325 xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
326 remote_peer->interested = 0;
327 update_active_peers_set(peer, remote_peer);
329 case MESSAGE_UNCHOKE:
330 xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
331 XBT_DEBUG("Received a UNCHOKE message from %s (%s)", message->mailbox, message->issuer_host_name);
332 xbt_assert(remote_peer->choked_download, "WTF !!!");
333 remote_peer->choked_download = 0;
334 //Send requests to the peer, since it has unchoked us
335 if (remote_peer->am_interested)
336 request_new_piece_to_peer(peer, remote_peer);
339 xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
340 XBT_DEBUG("Received a CHOKE message from %s (%s)", message->mailbox, message->issuer_host_name);
341 xbt_assert(!remote_peer->choked_download, "WTF !!!");
342 remote_peer->choked_download = 1;
343 remove_current_piece(peer, remote_peer, remote_peer->current_piece);
346 XBT_DEBUG("Received a HAVE message from %s (%s) of piece %d", message->mailbox, message->issuer_host_name,
348 xbt_assert(remote_peer->bitfield, "bitfield not received");
349 xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong HAVE message received");
350 remote_peer->bitfield[message->index] = '1';
351 peer->pieces_count[message->index]++;
352 //If the piece is in our pieces, we tell the peer that we are interested.
353 if ((remote_peer->am_interested == 0) &&
354 peer->bitfield[message->index] == '0') {
355 remote_peer->am_interested = 1;
356 send_interested(peer, message->mailbox);
357 if (remote_peer->choked_download == 0)
358 request_new_piece_to_peer(peer, remote_peer);
361 case MESSAGE_REQUEST:
362 xbt_assert(remote_peer->interested, "WTF !!!");
364 xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong request received");
365 if (remote_peer->choked_upload == 0) {
366 XBT_DEBUG("Received a REQUEST from %s (%s) for %d (%d,%d)", message->mailbox, message->issuer_host_name,
367 message->index, message->block_index, message->block_index + message->block_length);
368 if (peer->bitfield[message->index] == '1') {
369 send_piece(peer, message->mailbox, message->index, message->block_index, message->block_length);
372 XBT_DEBUG("Received a REQUEST from %s (%s) for %d but he is choked.", message->mailbox,
373 message->issuer_host_name, message->peer_id);
377 XBT_DEBUG("Received piece %d (%d,%d) from %s (%s)", message->index, message->block_index,
378 message->block_index + message->block_length, message->mailbox, message->issuer_host_name);
379 xbt_assert(!remote_peer->choked_download, "WTF !!!");
380 xbt_assert(remote_peer->am_interested || ENABLE_END_GAME_MODE,
381 "Can't received a piece if I'm not interested wihtout end-game mode!"
382 "piece (%d) bitfield(%s) remote bitfield(%s)", message->index, peer->bitfield, remote_peer->bitfield);
383 xbt_assert(remote_peer->choked_download != 1, "Can't received a piece if I'm choked !");
384 xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong piece received");
385 //TODO: Execute à computation.
386 if (peer->bitfield[message->index] == '0') {
387 update_bitfield_blocks(peer, message->index, message->block_index, message->block_length);
388 if (piece_complete(peer, message->index)) {
389 //Removing the piece from our piece list
390 remove_current_piece(peer, remote_peer, message->index);
391 //Setting the fact that we have the piece
392 peer->bitfield[message->index] = '1';
394 XBT_DEBUG("My status is now %s", peer->bitfield);
395 //Sending the information to all the peers we are connected to
396 send_have(peer, message->index);
397 //sending UNINTERSTED to peers that doesn't have what we want.
398 update_interested_after_receive(peer);
399 } else { // piece not completed
400 send_request_to_peer(peer, remote_peer, message->index); // ask for the next block
403 XBT_DEBUG("However, we already have it");
404 xbt_assert(ENABLE_END_GAME_MODE, "Should not happen because we don't use end game mode !");
405 request_new_piece_to_peer(peer, remote_peer);
409 XBT_DEBUG("The received CANCEL from %s (%s)", message->mailbox, message->issuer_host_name);
412 //Update the peer speed.
414 connection_add_speed_value(remote_peer, 1.0 / (MSG_get_clock() - peer->begin_receive_time));
416 peer->begin_receive_time = MSG_get_clock();
418 task_message_free(task);
421 /** Selects the appropriate piece to download and requests it to the remote_peer */
422 void request_new_piece_to_peer(peer_t peer, connection_t remote_peer)
424 int piece = select_piece_to_download(peer, remote_peer);
426 xbt_dynar_push_as(peer->current_pieces, int, piece);
427 send_request_to_peer(peer, remote_peer, piece);
431 /** remove current_piece from the list of currently downloaded pieces. */
432 void remove_current_piece(peer_t peer, connection_t remote_peer, int current_piece)
434 int piece_index = -1, piece;
436 xbt_dynar_foreach(peer->current_pieces, i, piece) {
437 if (piece == current_piece) {
442 if (piece_index != -1)
443 xbt_dynar_remove_at(peer->current_pieces, piece_index, NULL);
444 remote_peer->current_piece = -1;
447 /** @brief Updates the list of who has a piece from a bitfield
448 * @param peer peer we want to update the list
449 * @param bitfield bitfield
451 void update_pieces_count_from_bitfield(peer_t peer, char *bitfield)
454 for (i = 0; i < FILE_PIECES; i++) {
455 if (bitfield[i] == '1') {
456 peer->pieces_count[i]++;
461 /** @brief Return the piece to be downloaded
462 * There are two cases (as described in "Bittorrent Architecture Protocol", Ryan Toole :
463 * If a piece is partially downloaded, this piece will be selected prioritarily
464 * If the peer has strictly less than 4 pieces, he chooses a piece at random.
465 * If the peer has more than pieces, he downloads the pieces that are the less replicated (rarest policy).
466 * If all pieces have been downloaded or requested, we select a random requested piece (endgame mode).
467 * @param peer: local peer
468 * @param remote_peer: information about the connection
469 * @return the piece to download if possible. -1 otherwise
471 int select_piece_to_download(peer_t peer, connection_t remote_peer)
475 piece = partially_downloaded_piece(peer, remote_peer);
476 // strict priority policy
481 if (xbt_dynar_length(peer->current_pieces) >= (FILE_PIECES - peer->pieces) &&
482 (is_interested(peer, remote_peer) != 0)) {
483 if(ENABLE_END_GAME_MODE == 0)
486 int nb_interesting_pieces = 0;
487 int random_piece_index, current_index = 0;
488 // compute the number of interesting pieces
489 for (i = 0; i < FILE_PIECES; i++) {
490 if (peer->bitfield[i] == '0' && remote_peer->bitfield[i] == '1') {
491 nb_interesting_pieces++;
494 xbt_assert(nb_interesting_pieces != 0, "WTF !!!");
495 // get a random interesting piece
496 random_piece_index = RngStream_RandInt(peer->stream, 0, nb_interesting_pieces - 1);
497 for (i = 0; i < FILE_PIECES; i++) {
498 if (peer->bitfield[i] == '0' && remote_peer->bitfield[i] == '1') {
499 if (random_piece_index == current_index) {
506 xbt_assert(piece != -1, "WTF !!!");
509 // Random first policy
510 if (peer->pieces < 4 && (is_interested_and_free(peer, remote_peer) != 0)) {
512 int nb_interesting_pieces = 0;
513 int random_piece_index, current_index = 0;
514 // compute the number of interesting pieces
515 for (i = 0; i < FILE_PIECES; i++) {
516 if (peer->bitfield[i] == '0' && remote_peer->bitfield[i] == '1' &&
517 (in_current_pieces(peer, i) == 0)) {
518 nb_interesting_pieces++;
521 xbt_assert(nb_interesting_pieces != 0, "WTF !!!");
522 // get a random interesting piece
523 random_piece_index = RngStream_RandInt(peer->stream, 0, nb_interesting_pieces - 1);
524 for (i = 0; i < FILE_PIECES; i++) {
525 if (peer->bitfield[i] == '0' && remote_peer->bitfield[i] == '1' &&
526 (in_current_pieces(peer, i) == 0)) {
527 if (random_piece_index == current_index) {
534 xbt_assert(piece != -1, "WTF !!!");
536 } else { // Rarest first policy
538 short min = SHRT_MAX;
539 int nb_min_pieces = 0;
540 int random_rarest_index, current_index = 0;
541 // compute the smallest number of copies of available pieces
542 for (i = 0; i < FILE_PIECES; i++) {
543 if (peer->pieces_count[i] < min && peer->bitfield[i] == '0' &&
544 remote_peer->bitfield[i] == '1' && (in_current_pieces(peer, i) == 0))
545 min = peer->pieces_count[i];
547 xbt_assert(min != SHRT_MAX ||
548 (is_interested_and_free(peer, remote_peer) ==0), "WTF !!!");
549 // compute the number of rarest pieces
550 for (i = 0; i < FILE_PIECES; i++) {
551 if (peer->pieces_count[i] == min && peer->bitfield[i] == '0' &&
552 remote_peer->bitfield[i] == '1' && (in_current_pieces(peer, i) ==0))
555 xbt_assert(nb_min_pieces != 0 ||
556 (is_interested_and_free(peer, remote_peer)==0), "WTF !!!");
557 // get a random rarest piece
558 random_rarest_index = RngStream_RandInt(peer->stream, 0, nb_min_pieces - 1);
559 for (i = 0; i < FILE_PIECES; i++) {
560 if (peer->pieces_count[i] == min && peer->bitfield[i] == '0' &&
561 remote_peer->bitfield[i] == '1' && (in_current_pieces(peer, i)==0)) {
562 if (random_rarest_index == current_index) {
569 xbt_assert(piece != -1 ||
570 (is_interested_and_free(peer, remote_peer) == 0), "WTF !!!");
575 /** @brief Update the list of current choked and unchoked peers, using the choke algorithm
576 * @param peer the current peer
578 void update_choked_peers(peer_t peer)
580 if (nb_interested_peers(peer) == 0)
582 XBT_DEBUG("(%d) update_choked peers %d active peers", peer->id, xbt_dict_size(peer->active_peers));
583 //update the current round
584 peer->round = (peer->round + 1) % 3;
585 char *key, *key_choked=NULL;
586 connection_t peer_choosed = NULL;
587 connection_t peer_choked = NULL;
588 //remove a peer from the list
589 xbt_dict_cursor_t cursor = NULL;
590 xbt_dict_cursor_first(peer->active_peers, &cursor);
591 if (xbt_dict_length(peer->active_peers) > 0) {
592 key_choked = xbt_dict_cursor_get_key(cursor);
593 peer_choked = xbt_dict_cursor_get_data(cursor);
595 xbt_dict_cursor_free(&cursor);
597 /**If we are currently seeding, we unchoke the peer which has been unchoked the last time.*/
598 if (peer->pieces == FILE_PIECES) {
599 connection_t connection;
600 double unchoke_time = MSG_get_clock() + 1;
602 xbt_dict_foreach(peer->peers, cursor, key, connection) {
603 if (connection->last_unchoke < unchoke_time &&
604 (connection->interested != 0) && (connection->choked_upload != 0)) {
605 unchoke_time = connection->last_unchoke;
606 peer_choosed = connection;
610 //Random optimistic unchoking
611 if (peer->round == 0) {
614 //We choose a random peer to unchoke.
615 int id_chosen = RngStream_RandInt(peer->stream, 0, xbt_dict_length(peer->peers) - 1);
617 connection_t connection;
618 xbt_dict_foreach(peer->peers, cursor, key, connection) {
619 if (i == id_chosen) {
620 peer_choosed = connection;
625 xbt_dict_cursor_free(&cursor);
626 if ((peer_choosed->interested == 0) ||
627 (peer_choosed->choked_upload == 0)) {
631 } while (peer_choosed == NULL && j < MAXIMUM_PAIRS);
633 //Use the "fastest download" policy.
634 connection_t connection;
635 double fastest_speed = 0.0;
636 xbt_dict_foreach(peer->peers, cursor, key, connection) {
637 if (connection->peer_speed > fastest_speed &&
638 (connection->choked_upload != 0) && (connection->interested != 0)) {
639 peer_choosed = connection;
640 fastest_speed = connection->peer_speed;
646 if (peer_choosed != NULL)
647 XBT_DEBUG("(%d) update_choked peers unchoked (%d) ; int (%d) ; choked (%d) ",
648 peer->id, peer_choosed->id, peer_choosed->interested, peer_choosed->choked_upload);
650 if (peer_choked != peer_choosed) {
651 if (peer_choked != NULL) {
652 xbt_assert((!peer_choked->choked_upload), "Tries to choked a choked peer");
653 peer_choked->choked_upload = 1;
654 xbt_assert((*((int *) key_choked) == peer_choked->id), "WTF !!!");
655 update_active_peers_set(peer, peer_choked);
656 XBT_DEBUG("(%d) Sending a CHOKE to %d", peer->id, peer_choked->id);
657 send_choked(peer, peer_choked->mailbox);
659 if (peer_choosed != NULL) {
660 xbt_assert((peer_choosed->choked_upload), "Tries to unchoked an unchoked peer");
661 peer_choosed->choked_upload = 0;
662 xbt_dict_set_ext(peer->active_peers, (char *) &peer_choosed->id, sizeof(int), peer_choosed, NULL);
663 peer_choosed->last_unchoke = MSG_get_clock();
664 XBT_DEBUG("(%d) Sending a UNCHOKE to %d", peer->id, peer_choosed->id);
665 update_active_peers_set(peer, peer_choosed);
666 send_unchoked(peer, peer_choosed->mailbox);
671 /** @brief Update "interested" state of peers: send "not interested" to peers that don't have any more pieces we want.
672 * @param peer our peer data
674 void update_interested_after_receive(peer_t peer)
677 xbt_dict_cursor_t cursor;
678 connection_t connection;
680 xbt_dict_foreach(peer->peers, cursor, key, connection) {
682 if (connection->am_interested != 0) {
683 xbt_assert(connection->bitfield, "Bitfield not received");
684 //Check if the peer still has a piece we want.
686 for (i = 0; i < FILE_PIECES; i++) {
687 if (connection->bitfield[i] == '1' && peer->bitfield[i] == '0') {
692 if (!interested) { //no more piece to download from connection
693 connection->am_interested = 0;
694 send_notinterested(peer, connection->mailbox);
700 void update_bitfield_blocks(peer_t peer, int index, int block_index, int block_length)
703 xbt_assert((index >= 0 && index <= FILE_PIECES), "Wrong piece.");
704 xbt_assert((block_index >= 0 && block_index <= PIECES_BLOCKS), "Wrong block : %d.", block_index);
705 for (i = block_index; i < (block_index + block_length); i++) {
706 peer->bitfield_blocks[index * PIECES_BLOCKS + i] = '1';
710 /** Returns if a peer has completed the download of a piece */
711 int piece_complete(peer_t peer, int index)
714 for (i = 0; i < PIECES_BLOCKS; i++) {
715 if (peer->bitfield_blocks[index * PIECES_BLOCKS + i] == '0') {
722 /** Returns the first block that a peer doesn't have in a piece. If the peer has all blocks of the piece, returns -1. */
723 int get_first_block(peer_t peer, int piece)
726 for (i = 0; i < PIECES_BLOCKS; i++) {
727 if (peer->bitfield_blocks[piece * PIECES_BLOCKS + i] == '0') {
734 /** Indicates if the remote peer has a piece not stored by the local peer */
735 int is_interested(peer_t peer, connection_t remote_peer)
737 xbt_assert(remote_peer->bitfield, "Bitfield not received");
739 for (i = 0; i < FILE_PIECES; i++) {
740 if (remote_peer->bitfield[i] == '1' && peer->bitfield[i] == '0') {
747 /** Indicates if the remote peer has a piece not stored by the local peer nor requested by the local peer */
748 int is_interested_and_free(peer_t peer, connection_t remote_peer)
750 xbt_assert(remote_peer->bitfield, "Bitfield not received");
752 for (i = 0; i < FILE_PIECES; i++) {
753 if (remote_peer->bitfield[i] == '1' && peer->bitfield[i] == '0' &&
754 (in_current_pieces(peer, i) == 0)) {
761 /** Returns a piece that is partially downloaded and stored by the remote peer if any -1 otherwise. */
762 int partially_downloaded_piece(peer_t peer, connection_t remote_peer)
764 xbt_assert(remote_peer->bitfield, "Bitfield not received");
766 for (i = 0; i < FILE_PIECES; i++) {
767 if (remote_peer->bitfield[i] == '1' && peer->bitfield[i] == '0' &&
768 (in_current_pieces(peer, i) == 0)) {
769 if (get_first_block(peer, i) > 0)
776 /** @brief Send request messages to a peer that have unchoked us
778 * @param remote_peer peer data to the peer we want to send the request
780 void send_request_to_peer(peer_t peer, connection_t remote_peer, int piece)
782 remote_peer->current_piece = piece;
783 int block_index, block_length;
784 xbt_assert(remote_peer->bitfield, "bitfield not received");
785 xbt_assert(remote_peer->bitfield[piece] == '1', "WTF !!!");
786 block_index = get_first_block(peer, piece);
787 if (block_index != -1) {
788 block_length = PIECES_BLOCKS - block_index;
789 block_length = MIN(BLOCKS_REQUESTED, block_length);
790 send_request(peer, remote_peer->mailbox, piece, block_index, block_length);
794 /** Indicates if a piece is currently being downloaded by the peer. */
795 int in_current_pieces(peer_t peer, int piece)
799 xbt_dynar_foreach(peer->current_pieces, i, peer_piece) {
800 if (peer_piece == piece) {
807 /***********************************************************
809 * Low level message functions
811 ***********************************************************/
813 /** @brief Send a "interested" message to a peer
814 * @param peer peer data
815 * @param mailbox destination mailbox
817 void send_interested(peer_t peer, const char *mailbox)
819 msg_task_t task = task_message_new(MESSAGE_INTERESTED, peer->hostname, peer->mailbox, peer->id,
820 task_message_size(MESSAGE_INTERESTED));
821 MSG_task_dsend(task, mailbox, task_message_free);
822 XBT_DEBUG("Sending INTERESTED to %s", mailbox);
825 /** @brief Send a "not interested" message to a peer
826 * @param peer peer data
827 * @param mailbox destination mailbox
829 void send_notinterested(peer_t peer, const char *mailbox)
831 msg_task_t task = task_message_new(MESSAGE_NOTINTERESTED, peer->hostname, peer->mailbox, peer->id,
832 task_message_size(MESSAGE_NOTINTERESTED));
833 MSG_task_dsend(task, mailbox, task_message_free);
834 XBT_DEBUG("Sending NOTINTERESTED to %s", mailbox);
837 /** @brief Send a handshake message to all the peers the peer has.
838 * @param peer peer data
840 void send_handshake_all(peer_t peer)
842 connection_t remote_peer;
843 xbt_dict_cursor_t cursor = NULL;
845 xbt_dict_foreach(peer->peers, cursor, key, remote_peer) {
846 msg_task_t task = task_message_new(MESSAGE_HANDSHAKE, peer->hostname, peer->mailbox, peer->id,
847 task_message_size(MESSAGE_HANDSHAKE));
848 MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
849 XBT_DEBUG("Sending a HANDSHAKE to %s", remote_peer->mailbox);
853 /** @brief Send a "handshake" message to an user
854 * @param peer peer data
855 * @param mailbox mailbox where to we send the message
857 void send_handshake(peer_t peer, const char *mailbox)
859 msg_task_t task = task_message_new(MESSAGE_HANDSHAKE, peer->hostname, peer->mailbox, peer->id,
860 task_message_size(MESSAGE_HANDSHAKE));
861 MSG_task_dsend(task, mailbox, task_message_free);
862 XBT_DEBUG("Sending a HANDSHAKE to %s", mailbox);
865 /** Send a "choked" message to a peer. */
866 void send_choked(peer_t peer, const char *mailbox)
868 XBT_DEBUG("Sending a CHOKE to %s", mailbox);
869 msg_task_t task = task_message_new(MESSAGE_CHOKE, peer->hostname, peer->mailbox, peer->id,
870 task_message_size(MESSAGE_CHOKE));
871 MSG_task_dsend(task, mailbox, task_message_free);
874 /** Send a "unchoked" message to a peer */
875 void send_unchoked(peer_t peer, const char *mailbox)
877 XBT_DEBUG("Sending a UNCHOKE to %s", mailbox);
878 msg_task_t task = task_message_new(MESSAGE_UNCHOKE, peer->hostname, peer->mailbox, peer->id,
879 task_message_size(MESSAGE_UNCHOKE));
880 MSG_task_dsend(task, mailbox, task_message_free);
883 /** Send a "HAVE" message to all peers we are connected to */
884 void send_have(peer_t peer, int piece)
886 XBT_DEBUG("Sending HAVE message to all my peers");
887 connection_t remote_peer;
888 xbt_dict_cursor_t cursor = NULL;
890 xbt_dict_foreach(peer->peers, cursor, key, remote_peer) {
891 msg_task_t task = task_message_index_new(MESSAGE_HAVE, peer->hostname, peer->mailbox, peer->id, piece,
892 task_message_size(MESSAGE_HAVE));
893 MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
897 /** @brief Send a bitfield message to all the peers the peer has.
898 * @param peer peer data
900 void send_bitfield(peer_t peer, const char *mailbox)
902 XBT_DEBUG("Sending a BITFIELD to %s", mailbox);
903 msg_task_t task = task_message_bitfield_new(peer->hostname, peer->mailbox, peer->id, peer->bitfield, FILE_PIECES);
904 MSG_task_dsend(task, mailbox, task_message_free);
907 /** Send a "request" message to a pair, containing a request for a piece */
908 void send_request(peer_t peer, const char *mailbox, int piece, int block_index, int block_length)
910 XBT_DEBUG("Sending a REQUEST to %s for piece %d (%d,%d)", mailbox, piece, block_index, block_length);
911 msg_task_t task = task_message_request_new(peer->hostname, peer->mailbox, peer->id, piece, block_index, block_length);
912 MSG_task_dsend(task, mailbox, task_message_free);
915 /** Send a "piece" message to a pair, containing a piece of the file */
916 void send_piece(peer_t peer, const char *mailbox, int piece, int block_index, int block_length)
918 XBT_DEBUG("Sending the PIECE %d (%d,%d) to %s", piece, block_index, block_length, mailbox);
919 xbt_assert(piece >= 0, "Tried to send a piece that doesn't exist.");
920 xbt_assert((peer->bitfield[piece] == '1'), "Tried to send a piece that we doesn't have.");
921 msg_task_t task = task_message_piece_new(peer->hostname, peer->mailbox, peer->id, piece, block_index, block_length,
923 MSG_task_dsend(task, mailbox, task_message_free);