Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
308a7b83924a124136a32d5aa5fa30f3a26f5d75
[simgrid.git] / teshsuite / msg / app-bittorrent / bittorrent-peer.c
1 /* Copyright (c) 2012-2019. The SimGrid Team. All rights reserved.          */
2
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. */
5
6 #include "bittorrent-peer.h"
7 #include "bittorrent-messages.h"
8 #include "connection.h"
9 #include "tracker.h"
10 #include <simgrid/msg.h>
11 #include <xbt/RngStream.h>
12
13 #include <limits.h>
14 #include <stdio.h> /* snprintf */
15
16 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_peers, "Messages specific for the peers");
17
18 /*
19  * User parameters for transferred file data. For the test, the default values are :
20  * File size: 10 pieces * 5 blocks/piece * 16384 bytes/block = 819200 bytes
21  */
22 #define FILE_PIECES 10UL
23 #define PIECES_BLOCKS 5UL
24 #define BLOCK_SIZE 16384
25 static const unsigned long int FILE_SIZE = FILE_PIECES * PIECES_BLOCKS * BLOCK_SIZE;
26
27 /** Number of blocks asked by each request */
28 #define BLOCKS_REQUESTED 2
29
30 #define ENABLE_END_GAME_MODE 1
31 #define SLEEP_DURATION 1
32
33 int count_pieces(unsigned int bitfield)
34 {
35   int count      = 0;
36   unsigned int n = bitfield;
37   while (n) {
38     count += n & 1U;
39     n >>= 1U;
40   }
41   return count;
42 }
43
44 int peer_has_not_piece(peer_t peer, unsigned int piece)
45 {
46   return !(peer->bitfield & 1U << piece);
47 }
48
49 /** Check that a piece is not currently being download by the peer. */
50 int peer_is_not_downloading_piece(peer_t peer, unsigned int piece)
51 {
52   return !(peer->current_pieces & 1U << piece);
53 }
54
55 void get_status(char** status, unsigned int bitfield)
56 {
57   for (int i             = FILE_PIECES - 1; i >= 0; i--)
58     (*status)[i]         = (bitfield & (1U << i)) ? '1' : '0';
59   (*status)[FILE_PIECES] = '\0';
60 }
61
62 /** Peer main function */
63 int peer(int argc, char* argv[])
64 {
65   // Check arguments
66   xbt_assert(argc == 3 || argc == 4, "Wrong number of arguments");
67
68   // Build peer object
69   peer_t peer = peer_init(xbt_str_parse_int(argv[1], "Invalid ID: %s"), argc == 4 ? 1 : 0);
70
71   // Retrieve deadline
72   double deadline = xbt_str_parse_double(argv[2], "Invalid deadline: %s");
73   xbt_assert(deadline > 0, "Wrong deadline supplied");
74
75   char* status = xbt_malloc0(FILE_PIECES + 1);
76   get_status(&status, peer->bitfield);
77   XBT_INFO("Hi, I'm joining the network with id %d", peer->id);
78   // Getting peer data from the tracker.
79   if (get_peers_data(peer)) {
80     XBT_DEBUG("Got %d peers from the tracker. Current status is: %s", xbt_dict_length(peer->peers), status);
81     peer->begin_receive_time = MSG_get_clock();
82     MSG_mailbox_set_async(peer->mailbox);
83     if (has_finished(peer->bitfield)) {
84       send_handshake_all(peer);
85     } else {
86       leech_loop(peer, deadline);
87     }
88     seed_loop(peer, deadline);
89   } else {
90     XBT_INFO("Couldn't contact the tracker.");
91   }
92
93   get_status(&status, peer->bitfield);
94   XBT_INFO("Here is my current status: %s", status);
95   if (peer->comm_received) {
96     MSG_comm_destroy(peer->comm_received);
97   }
98
99   xbt_free(status);
100   peer_free(peer);
101   return 0;
102 }
103
104 /** @brief Peer main loop when it is leeching.
105  *  @param peer peer data
106  *  @param deadline time at which the peer has to leave
107  */
108 void leech_loop(peer_t peer, double deadline)
109 {
110   double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
111   XBT_DEBUG("Start downloading.");
112
113   /* Send a "handshake" message to all the peers it got (since it couldn't have gotten more than 50 peers) */
114   send_handshake_all(peer);
115   XBT_DEBUG("Starting main leech loop");
116
117   while (MSG_get_clock() < deadline && count_pieces(peer->bitfield) < FILE_PIECES) {
118     if (peer->comm_received == NULL) {
119       peer->task_received = NULL;
120       peer->comm_received = MSG_task_irecv(&peer->task_received, peer->mailbox);
121     }
122     if (MSG_comm_test(peer->comm_received)) {
123       msg_error_t status = MSG_comm_get_status(peer->comm_received);
124       MSG_comm_destroy(peer->comm_received);
125       peer->comm_received = NULL;
126       if (status == MSG_OK) {
127         handle_message(peer, peer->task_received);
128       }
129     } else {
130       // We don't execute the choke algorithm if we don't already have a piece
131       if (MSG_get_clock() >= next_choked_update && count_pieces(peer->bitfield) > 0) {
132         update_choked_peers(peer);
133         next_choked_update += UPDATE_CHOKED_INTERVAL;
134       } else {
135         MSG_process_sleep(SLEEP_DURATION);
136       }
137     }
138   }
139   if (has_finished(peer->bitfield))
140     XBT_DEBUG("%d becomes a seeder", peer->id);
141 }
142
143 /** @brief Peer main loop when it is seeding
144  *  @param peer peer data
145  *  @param deadline time when the peer will leave
146  */
147 void seed_loop(peer_t peer, double deadline)
148 {
149   double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
150   XBT_DEBUG("Start seeding.");
151   // start the main seed loop
152   while (MSG_get_clock() < deadline) {
153     if (peer->comm_received == NULL) {
154       peer->task_received = NULL;
155       peer->comm_received = MSG_task_irecv(&peer->task_received, peer->mailbox);
156     }
157     if (MSG_comm_test(peer->comm_received)) {
158       msg_error_t status = MSG_comm_get_status(peer->comm_received);
159       MSG_comm_destroy(peer->comm_received);
160       peer->comm_received = NULL;
161       if (status == MSG_OK) {
162         handle_message(peer, peer->task_received);
163       }
164     } else {
165       if (MSG_get_clock() >= next_choked_update) {
166         update_choked_peers(peer);
167         // TODO: Change the choked peer algorithm when seeding.
168         next_choked_update += UPDATE_CHOKED_INTERVAL;
169       } else {
170         MSG_process_sleep(SLEEP_DURATION);
171       }
172     }
173   }
174 }
175
176 /** @brief Retrieves the peer list from the tracker
177  *  @param peer current peer data
178  */
179 int get_peers_data(peer_t peer)
180 {
181   int success    = 0;
182   double timeout = MSG_get_clock() + GET_PEERS_TIMEOUT;
183
184   // Build the task to send to the tracker
185   tracker_task_data_t data =
186       tracker_task_data_new(MSG_host_get_name(MSG_host_self()), peer->mailbox_tracker, peer->id, 0, 0, FILE_SIZE);
187   msg_task_t task_send = MSG_task_create(NULL, 0, TRACKER_COMM_SIZE, data);
188   while ((success == 0) && MSG_get_clock() < timeout) {
189     XBT_DEBUG("Sending a peer request to the tracker.");
190     msg_error_t status = MSG_task_send_with_timeout(task_send, TRACKER_MAILBOX, GET_PEERS_TIMEOUT);
191     if (status == MSG_OK) {
192       success = 1;
193     }
194   }
195
196   success                  = 0;
197   msg_task_t task_received = NULL;
198   while ((success == 0) && MSG_get_clock() < timeout) {
199     msg_comm_t comm_received = MSG_task_irecv(&task_received, peer->mailbox_tracker);
200     msg_error_t status       = MSG_comm_wait(comm_received, GET_PEERS_TIMEOUT);
201     if (status == MSG_OK) {
202       tracker_task_data_t data = MSG_task_get_data(task_received);
203       unsigned i;
204       int peer_id;
205       // Add the peers the tracker gave us to our peer list.
206       xbt_dynar_foreach (data->peers, i, peer_id) {
207         if (peer_id != peer->id)
208           xbt_dict_set_ext(peer->peers, (char*)&peer_id, sizeof(int), connection_new(peer_id), NULL);
209       }
210       success = 1;
211       // free the communication and the task
212       MSG_comm_destroy(comm_received);
213       tracker_task_data_free(data);
214       MSG_task_destroy(task_received);
215     }
216   }
217
218   return success;
219 }
220
221 /** @brief Initialize the peer data.
222  *  @param peer peer data
223  *  @param id id of the peer to take in the network
224  *  @param seed indicates if the peer is a seed.
225  */
226 peer_t peer_init(int id, int seed)
227 {
228   peer_t peer    = xbt_new(s_peer_t, 1);
229   peer->id       = id;
230   peer->hostname = MSG_host_get_name(MSG_host_self());
231
232   snprintf(peer->mailbox, MAILBOX_SIZE - 1, "%d", id);
233   snprintf(peer->mailbox_tracker, MAILBOX_SIZE - 1, "tracker_%d", id);
234   peer->peers        = xbt_dict_new_homogeneous(NULL);
235   peer->active_peers = xbt_dict_new_homogeneous(NULL);
236
237   if (seed) {
238     peer->bitfield        = (1U << FILE_PIECES) - 1U;
239     peer->bitfield_blocks = (1ULL << (FILE_PIECES * PIECES_BLOCKS)) - 1ULL;
240   } else {
241     peer->bitfield        = 0;
242     peer->bitfield_blocks = 0;
243   }
244
245   peer->current_pieces = 0;
246
247   peer->pieces_count = xbt_new0(short, FILE_PIECES);
248
249   peer->stream        = (RngStream)MSG_host_get_data(MSG_host_self());
250   peer->comm_received = NULL;
251
252   peer->round = 0;
253
254   return peer;
255 }
256
257 /** Destroys a poor peer object. */
258 void peer_free(peer_t peer)
259 {
260   char* key;
261   connection_t connection;
262   xbt_dict_cursor_t cursor;
263   xbt_dict_foreach (peer->peers, cursor, key, connection) {
264     connection_free(connection);
265   }
266   xbt_dict_free(&peer->peers);
267   xbt_dict_free(&peer->active_peers);
268   xbt_free(peer->pieces_count);
269   xbt_free(peer);
270 }
271
272 /** @brief Returns if a peer has finished downloading the file
273  *  @param bitfield peer bitfield
274  */
275 int has_finished(unsigned int bitfield)
276 {
277   return bitfield == (1U << FILE_PIECES) - 1U;
278 }
279
280 int nb_interested_peers(peer_t peer)
281 {
282   xbt_dict_cursor_t cursor = NULL;
283   char* key;
284   connection_t connection;
285   int nb = 0;
286   xbt_dict_foreach (peer->peers, cursor, key, connection) {
287     if (connection->interested)
288       nb++;
289   }
290   return nb;
291 }
292
293 void update_active_peers_set(peer_t peer, connection_t remote_peer)
294 {
295   if ((remote_peer->interested != 0) && (remote_peer->choked_upload == 0)) {
296     // add in the active peers set
297     xbt_dict_set_ext(peer->active_peers, (char*)&remote_peer->id, sizeof(int), remote_peer, NULL);
298   } else if (xbt_dict_get_or_null_ext(peer->active_peers, (char*)&remote_peer->id, sizeof(int))) {
299     xbt_dict_remove_ext(peer->active_peers, (char*)&remote_peer->id, sizeof(int));
300   }
301 }
302
303 /** @brief Handle a received message sent by another peer
304  * @param peer Peer data
305  * @param task task received.
306  */
307 void handle_message(peer_t peer, msg_task_t task)
308 {
309   const char* type_names[10] = {"HANDSHAKE", "CHOKE",    "UNCHOKE", "INTERESTED", "NOTINTERESTED",
310                                 "HAVE",      "BITFIELD", "REQUEST", "PIECE",      "CANCEL"};
311   message_t message = MSG_task_get_data(task);
312   XBT_DEBUG("Received a %s message from %s (%s)", type_names[message->type], message->mailbox,
313             message->issuer_host_name);
314
315   connection_t remote_peer;
316   remote_peer = xbt_dict_get_or_null_ext(peer->peers, (char*)&message->peer_id, sizeof(int));
317
318   switch (message->type) {
319     case MESSAGE_HANDSHAKE:
320       // Check if the peer is in our connection list.
321       if (remote_peer == 0) {
322         xbt_dict_set_ext(peer->peers, (char*)&message->peer_id, sizeof(int), connection_new(message->peer_id), NULL);
323         send_handshake(peer, message->mailbox);
324       }
325       // Send our bitfield to the peer
326       send_bitfield(peer, message->mailbox);
327       break;
328     case MESSAGE_BITFIELD:
329       // Update the pieces list
330       update_pieces_count_from_bitfield(peer, message->bitfield);
331       // Store the bitfield
332       remote_peer->bitfield = message->bitfield;
333       xbt_assert(!remote_peer->am_interested, "Should not be interested at first");
334       if (is_interested(peer, remote_peer)) {
335         remote_peer->am_interested = 1;
336         send_interested(peer, message->mailbox);
337       }
338       break;
339     case MESSAGE_INTERESTED:
340       xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
341       // Update the interested state of the peer.
342       remote_peer->interested = 1;
343       update_active_peers_set(peer, remote_peer);
344       break;
345     case MESSAGE_NOTINTERESTED:
346       xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
347       remote_peer->interested = 0;
348       update_active_peers_set(peer, remote_peer);
349       break;
350     case MESSAGE_UNCHOKE:
351       xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
352       xbt_assert(remote_peer->choked_download);
353       remote_peer->choked_download = 0;
354       // Send requests to the peer, since it has unchoked us
355       if (remote_peer->am_interested)
356         request_new_piece_to_peer(peer, remote_peer);
357       break;
358     case MESSAGE_CHOKE:
359       xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
360       xbt_assert(!remote_peer->choked_download);
361       remote_peer->choked_download = 1;
362       if (remote_peer->current_piece != -1)
363         remove_current_piece(peer, remote_peer, remote_peer->current_piece);
364       break;
365     case MESSAGE_HAVE:
366       XBT_DEBUG("\t for piece %d", message->index);
367       xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong HAVE message received");
368       remote_peer->bitfield = remote_peer->bitfield | (1U << message->index);
369       peer->pieces_count[message->index]++;
370       // If the piece is in our pieces, we tell the peer that we are interested.
371       if ((remote_peer->am_interested == 0) && peer_has_not_piece(peer, message->index)) {
372         remote_peer->am_interested = 1;
373         send_interested(peer, message->mailbox);
374         if (remote_peer->choked_download == 0)
375           request_new_piece_to_peer(peer, remote_peer);
376       }
377       break;
378     case MESSAGE_REQUEST:
379       xbt_assert(remote_peer->interested);
380       xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong request received");
381       if (remote_peer->choked_upload == 0) {
382         XBT_DEBUG("\t for piece %d (%d,%d)", message->index, message->block_index,
383                   message->block_index + message->block_length);
384         if (!peer_has_not_piece(peer, message->index)) {
385           send_piece(peer, message->mailbox, message->index, message->block_index, message->block_length);
386         }
387       } else {
388         XBT_DEBUG("\t for piece %d but he is choked.", message->peer_id);
389       }
390       break;
391     case MESSAGE_PIECE:
392       XBT_DEBUG(" \t for piece %d (%d,%d)", message->index, message->block_index,
393                 message->block_index + message->block_length);
394       xbt_assert(!remote_peer->choked_download);
395       xbt_assert(remote_peer->am_interested || ENABLE_END_GAME_MODE,
396                  "Can't received a piece if I'm not interested wihtout end-game mode!"
397                  "piece (%d) bitfield(%u) remote bitfield(%u)",
398                  message->index, peer->bitfield, remote_peer->bitfield);
399       xbt_assert(remote_peer->choked_download != 1, "Can't received a piece if I'm choked !");
400       xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong piece received");
401       // TODO: Execute Ã  computation.
402       if (peer_has_not_piece(peer, message->index)) {
403         update_bitfield_blocks(peer, message->index, message->block_index, message->block_length);
404         if (piece_complete(peer, message->index)) {
405           // Removing the piece from our piece list
406           remove_current_piece(peer, remote_peer, message->index);
407           // Setting the fact that we have the piece
408           peer->bitfield = peer->bitfield | (1U << message->index);
409           char* status   = xbt_malloc0(FILE_PIECES + 1);
410           get_status(&status, peer->bitfield);
411           XBT_DEBUG("My status is now %s", status);
412           xbt_free(status);
413           // Sending the information to all the peers we are connected to
414           send_have(peer, message->index);
415           // sending UNINTERESTED to peers that do not have what we want.
416           update_interested_after_receive(peer);
417         } else {                                                   // piece not completed
418           send_request_to_peer(peer, remote_peer, message->index); // ask for the next block
419         }
420       } else {
421         XBT_DEBUG("However, we already have it");
422         xbt_assert(ENABLE_END_GAME_MODE, "Should not happen because we don't use end game mode !");
423         request_new_piece_to_peer(peer, remote_peer);
424       }
425       break;
426     case MESSAGE_CANCEL:
427       break;
428     default:
429       THROW_IMPOSSIBLE;
430   }
431   // Update the peer speed.
432   if (remote_peer) {
433     connection_add_speed_value(remote_peer, 1.0 / (MSG_get_clock() - peer->begin_receive_time));
434   }
435   peer->begin_receive_time = MSG_get_clock();
436
437   task_message_free(task);
438 }
439
440 /** Selects the appropriate piece to download and requests it to the remote_peer */
441 void request_new_piece_to_peer(peer_t peer, connection_t remote_peer)
442 {
443   int piece = select_piece_to_download(peer, remote_peer);
444   if (piece != -1) {
445     peer->current_pieces |= (1U << (unsigned int)piece);
446     send_request_to_peer(peer, remote_peer, piece);
447   }
448 }
449
450 /** remove current_piece from the list of currently downloaded pieces. */
451 void remove_current_piece(peer_t peer, connection_t remote_peer, unsigned int current_piece)
452 {
453   peer->current_pieces &= ~(1U << current_piece);
454   remote_peer->current_piece = -1;
455 }
456
457 /** @brief Updates the list of who has a piece from a bitfield
458  *  @param peer peer we want to update the list
459  *  @param bitfield bitfield
460  */
461 void update_pieces_count_from_bitfield(peer_t peer, unsigned int bitfield)
462 {
463   for (int i = 0; i < FILE_PIECES; i++) {
464     if (bitfield & (1U << i)) {
465       peer->pieces_count[i]++;
466     }
467   }
468 }
469
470 /** @brief Return the piece to be downloaded
471  * There are two cases (as described in "Bittorrent Architecture Protocol", Ryan Toole :
472  * If a piece is partially downloaded, this piece will be selected prioritarily
473  * If the peer has strictly less than 4 pieces, he chooses a piece at random.
474  * If the peer has more than pieces, he downloads the pieces that are the less replicated (rarest policy).
475  * If all pieces have been downloaded or requested, we select a random requested piece (endgame mode).
476  * @param peer: local peer
477  * @param remote_peer: information about the connection
478  * @return the piece to download if possible. -1 otherwise
479  */
480 int select_piece_to_download(peer_t peer, connection_t remote_peer)
481 {
482   int piece = partially_downloaded_piece(peer, remote_peer);
483   // strict priority policy
484   if (piece != -1)
485     return piece;
486
487   // end game mode
488   if (count_pieces(peer->current_pieces) >= (FILE_PIECES - count_pieces(peer->bitfield)) &&
489       (is_interested(peer, remote_peer) != 0)) {
490 #if ENABLE_END_GAME_MODE == 0
491     return -1;
492 #endif
493     int nb_interesting_pieces = 0;
494     // compute the number of interesting pieces
495     for (int i = 0; i < FILE_PIECES; i++) {
496       if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i)) {
497         nb_interesting_pieces++;
498       }
499     }
500     xbt_assert(nb_interesting_pieces != 0);
501     // get a random interesting piece
502     int random_piece_index = RngStream_RandInt(peer->stream, 0, nb_interesting_pieces - 1);
503     int current_index      = 0;
504     for (int i = 0; i < FILE_PIECES; i++) {
505       if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i)) {
506         if (random_piece_index == current_index) {
507           piece = i;
508           break;
509         }
510         current_index++;
511       }
512     }
513     xbt_assert(piece != -1);
514     return piece;
515   }
516   // Random first policy
517   if (count_pieces(peer->bitfield) < 4 && (is_interested_and_free(peer, remote_peer) != 0)) {
518     int nb_interesting_pieces = 0;
519     // compute the number of interesting pieces
520     for (int i = 0; i < FILE_PIECES; i++) {
521       if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
522           peer_is_not_downloading_piece(peer, i)) {
523         nb_interesting_pieces++;
524       }
525     }
526     xbt_assert(nb_interesting_pieces != 0);
527     // get a random interesting piece
528     int random_piece_index = RngStream_RandInt(peer->stream, 0, nb_interesting_pieces - 1);
529     int current_index      = 0;
530     for (int i = 0; i < FILE_PIECES; i++) {
531       if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
532           peer_is_not_downloading_piece(peer, i)) {
533         if (random_piece_index == current_index) {
534           piece = i;
535           break;
536         }
537         current_index++;
538       }
539     }
540     xbt_assert(piece != -1);
541     return piece;
542   } else { // Rarest first policy
543     short min         = SHRT_MAX;
544     int nb_min_pieces = 0;
545     int current_index = 0;
546     // compute the smallest number of copies of available pieces
547     for (int i = 0; i < FILE_PIECES; i++) {
548       if (peer->pieces_count[i] < min && peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
549           peer_is_not_downloading_piece(peer, i))
550         min = peer->pieces_count[i];
551     }
552     xbt_assert(min != SHRT_MAX || (is_interested_and_free(peer, remote_peer) == 0));
553     // compute the number of rarest pieces
554     for (int i = 0; i < FILE_PIECES; i++) {
555       if (peer->pieces_count[i] == min && peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
556           peer_is_not_downloading_piece(peer, i))
557         nb_min_pieces++;
558     }
559     xbt_assert(nb_min_pieces != 0 || (is_interested_and_free(peer, remote_peer) == 0));
560     // get a random rarest piece
561     int random_rarest_index = RngStream_RandInt(peer->stream, 0, nb_min_pieces - 1);
562     for (int i = 0; i < FILE_PIECES; i++) {
563       if (peer->pieces_count[i] == min && peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
564           peer_is_not_downloading_piece(peer, i)) {
565         if (random_rarest_index == current_index) {
566           piece = i;
567           break;
568         }
569         current_index++;
570       }
571     }
572     xbt_assert(piece != -1 || (is_interested_and_free(peer, remote_peer) == 0));
573     return piece;
574   }
575 }
576
577 /** @brief Update the list of current choked and unchoked peers, using the choke algorithm
578  *  @param peer the current peer
579  */
580 void update_choked_peers(peer_t peer)
581 {
582   if (nb_interested_peers(peer) == 0)
583     return;
584   XBT_DEBUG("(%d) update_choked peers %u active peers", peer->id, xbt_dict_size(peer->active_peers));
585   // update the current round
586   peer->round = (peer->round + 1) % 3;
587   char* key;
588   char* key_choked          = NULL;
589   connection_t peer_choosed = NULL;
590   connection_t peer_choked  = NULL;
591   // remove a peer from the list
592   xbt_dict_cursor_t cursor = NULL;
593   xbt_dict_cursor_first(peer->active_peers, &cursor);
594   if (!xbt_dict_is_empty(peer->active_peers)) {
595     key_choked  = xbt_dict_cursor_get_key(cursor);
596     peer_choked = xbt_dict_cursor_get_data(cursor);
597   }
598   xbt_dict_cursor_free(&cursor);
599
600   /**If we are currently seeding, we unchoke the peer which has been unchoked the last time.*/
601   if (has_finished(peer->bitfield)) {
602     connection_t connection;
603     double unchoke_time = MSG_get_clock() + 1;
604
605     xbt_dict_foreach (peer->peers, cursor, key, connection) {
606       if (connection->last_unchoke < unchoke_time && (connection->interested != 0) &&
607           (connection->choked_upload != 0)) {
608         unchoke_time = connection->last_unchoke;
609         peer_choosed = connection;
610       }
611     }
612   } else {
613     // Random optimistic unchoking
614     if (peer->round == 0) {
615       int j = 0;
616       do {
617         // We choose a random peer to unchoke.
618         int id_chosen = RngStream_RandInt(peer->stream, 0, xbt_dict_length(peer->peers) - 1);
619         int i         = 0;
620         connection_t connection;
621         xbt_dict_foreach (peer->peers, cursor, key, connection) {
622           if (i == id_chosen) {
623             peer_choosed = connection;
624             break;
625           }
626           i++;
627         }
628         xbt_dict_cursor_free(&cursor);
629         xbt_assert(peer_choosed != NULL, "A peer should have been selected at this point");
630         if ((peer_choosed->interested == 0) || (peer_choosed->choked_upload == 0))
631           peer_choosed = NULL;
632         else
633           XBT_DEBUG("Nothing to do, keep going");
634         j++;
635       } while (peer_choosed == NULL && j < MAXIMUM_PEERS);
636     } else {
637       // Use the "fastest download" policy.
638       connection_t connection;
639       double fastest_speed = 0.0;
640       xbt_dict_foreach (peer->peers, cursor, key, connection) {
641         if (connection->peer_speed > fastest_speed && (connection->choked_upload != 0) &&
642             (connection->interested != 0)) {
643           peer_choosed  = connection;
644           fastest_speed = connection->peer_speed;
645         }
646       }
647     }
648   }
649
650   if (peer_choosed != NULL)
651     XBT_DEBUG("(%d) update_choked peers unchoked (%d) ; int (%d) ; choked (%d) ", peer->id, peer_choosed->id,
652               peer_choosed->interested, peer_choosed->choked_upload);
653
654   if (peer_choked != peer_choosed) {
655     if (peer_choked != NULL) {
656       xbt_assert((!peer_choked->choked_upload), "Tries to choked a choked peer");
657       peer_choked->choked_upload = 1;
658       xbt_assert((*((int*)key_choked) == peer_choked->id));
659       update_active_peers_set(peer, peer_choked);
660       XBT_DEBUG("(%d) Sending a CHOKE to %d", peer->id, peer_choked->id);
661       send_choked(peer, peer_choked->mailbox);
662     }
663     if (peer_choosed != NULL) {
664       xbt_assert((peer_choosed->choked_upload), "Tries to unchoked an unchoked peer");
665       peer_choosed->choked_upload = 0;
666       xbt_dict_set_ext(peer->active_peers, (char*)&peer_choosed->id, sizeof(int), peer_choosed, NULL);
667       peer_choosed->last_unchoke = MSG_get_clock();
668       XBT_DEBUG("(%d) Sending a UNCHOKE to %d", peer->id, peer_choosed->id);
669       update_active_peers_set(peer, peer_choosed);
670       send_unchoked(peer, peer_choosed->mailbox);
671     }
672   }
673 }
674
675 /** @brief Update "interested" state of peers: send "not interested" to peers that don't have any more pieces we want.
676  *  @param peer our peer data
677  */
678 void update_interested_after_receive(peer_t peer)
679 {
680   char* key;
681   xbt_dict_cursor_t cursor;
682   connection_t connection;
683   xbt_dict_foreach (peer->peers, cursor, key, connection) {
684     if (connection->am_interested != 0) {
685       int interested = 0;
686       // Check if the peer still has a piece we want.
687       for (int i = 0; i < FILE_PIECES; i++) {
688         if (peer_has_not_piece(peer, i) && connection_has_piece(connection, i)) {
689           interested = 1;
690           break;
691         }
692       }
693       if (!interested) { // no more piece to download from connection
694         connection->am_interested = 0;
695         send_notinterested(peer, connection->mailbox);
696       }
697     }
698   }
699 }
700
701 void update_bitfield_blocks(peer_t peer, int index, int block_index, int block_length)
702 {
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 (int i = block_index; i < (block_index + block_length); i++) {
706     peer->bitfield_blocks |= (1ULL << (unsigned int)(index * PIECES_BLOCKS + i));
707   }
708 }
709
710 /** Returns if a peer has completed the download of a piece */
711 int piece_complete(peer_t peer, int index)
712 {
713   for (int i = 0; i < PIECES_BLOCKS; i++) {
714     if (!(peer->bitfield_blocks & 1ULL << (index * PIECES_BLOCKS + i))) {
715       return 0;
716     }
717   }
718   return 1;
719 }
720
721 /** Returns the first block that a peer doesn't have in a piece. If the peer has all blocks of the piece, returns -1. */
722 int get_first_block(peer_t peer, int piece)
723 {
724   for (int i = 0; i < PIECES_BLOCKS; i++) {
725     if (!(peer->bitfield_blocks & 1ULL << (piece * PIECES_BLOCKS + i))) {
726       return i;
727     }
728   }
729   return -1;
730 }
731
732 /** Indicates if the remote peer has a piece not stored by the local peer */
733 int is_interested(peer_t peer, connection_t remote_peer)
734 {
735   return remote_peer->bitfield & (peer->bitfield ^ ((1 << FILE_PIECES) - 1));
736 }
737
738 /** Indicates if the remote peer has a piece not stored by the local peer nor requested by the local peer */
739 int is_interested_and_free(peer_t peer, connection_t remote_peer)
740 {
741   for (int i = 0; i < FILE_PIECES; i++) {
742     if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) && peer_is_not_downloading_piece(peer, i)) {
743       return 1;
744     }
745   }
746   return 0;
747 }
748
749 /** Returns a piece that is partially downloaded and stored by the remote peer if any -1 otherwise. */
750 int partially_downloaded_piece(peer_t peer, connection_t remote_peer)
751 {
752   for (int i = 0; i < FILE_PIECES; i++) {
753     if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) && peer_is_not_downloading_piece(peer, i) &&
754         get_first_block(peer, i) > 0)
755       return i;
756   }
757   return -1;
758 }
759
760 /** @brief Send request messages to a peer that have unchoked us
761  *  @param peer peer
762  *  @param remote_peer peer data to the peer we want to send the request
763  */
764 void send_request_to_peer(peer_t peer, connection_t remote_peer, int piece)
765 {
766   remote_peer->current_piece = piece;
767   xbt_assert(connection_has_piece(remote_peer, piece));
768   int block_index = get_first_block(peer, piece);
769   if (block_index != -1) {
770     int block_length = MIN(BLOCKS_REQUESTED, PIECES_BLOCKS - block_index);
771     send_request(peer, remote_peer->mailbox, piece, block_index, block_length);
772   }
773 }
774
775 /***********************************************************
776  *
777  *  Low level message functions
778  *
779  ***********************************************************/
780
781 /** @brief Send a "interested" message to a peer
782  *  @param peer peer data
783  *  @param mailbox destination mailbox
784  */
785 void send_interested(peer_t peer, const char* mailbox)
786 {
787   msg_task_t task = task_message_new(MESSAGE_INTERESTED, peer->hostname, peer->mailbox, peer->id,
788                                      task_message_size(MESSAGE_INTERESTED));
789   MSG_task_dsend(task, mailbox, task_message_free);
790   XBT_DEBUG("Sending INTERESTED to %s", mailbox);
791 }
792
793 /** @brief Send a "not interested" message to a peer
794  *  @param peer peer data
795  *  @param mailbox destination mailbox
796  */
797 void send_notinterested(peer_t peer, const char* mailbox)
798 {
799   msg_task_t task = task_message_new(MESSAGE_NOTINTERESTED, peer->hostname, peer->mailbox, peer->id,
800                                      task_message_size(MESSAGE_NOTINTERESTED));
801   MSG_task_dsend(task, mailbox, task_message_free);
802   XBT_DEBUG("Sending NOTINTERESTED to %s", mailbox);
803 }
804
805 /** @brief Send a handshake message to all the peers the peer has.
806  *  @param peer peer data
807  */
808 void send_handshake_all(peer_t peer)
809 {
810   connection_t remote_peer;
811   xbt_dict_cursor_t cursor = NULL;
812   char* key;
813   xbt_dict_foreach (peer->peers, cursor, key, remote_peer) {
814     msg_task_t task = task_message_new(MESSAGE_HANDSHAKE, peer->hostname, peer->mailbox, peer->id,
815                                        task_message_size(MESSAGE_HANDSHAKE));
816     MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
817     XBT_DEBUG("Sending a HANDSHAKE to %s", remote_peer->mailbox);
818   }
819 }
820
821 /** @brief Send a "handshake" message to an user
822  *  @param peer peer data
823  *  @param mailbox mailbox where to we send the message
824  */
825 void send_handshake(peer_t peer, const char* mailbox)
826 {
827   XBT_DEBUG("Sending a HANDSHAKE to %s", mailbox);
828   msg_task_t task = task_message_new(MESSAGE_HANDSHAKE, peer->hostname, peer->mailbox, peer->id,
829                                      task_message_size(MESSAGE_HANDSHAKE));
830   MSG_task_dsend(task, mailbox, task_message_free);
831 }
832
833 /** Send a "choked" message to a peer. */
834 void send_choked(peer_t peer, const char* mailbox)
835 {
836   XBT_DEBUG("Sending a CHOKE to %s", mailbox);
837   msg_task_t task =
838       task_message_new(MESSAGE_CHOKE, peer->hostname, peer->mailbox, peer->id, task_message_size(MESSAGE_CHOKE));
839   MSG_task_dsend(task, mailbox, task_message_free);
840 }
841
842 /** Send a "unchoked" message to a peer */
843 void send_unchoked(peer_t peer, const char* mailbox)
844 {
845   XBT_DEBUG("Sending a UNCHOKE to %s", mailbox);
846   msg_task_t task =
847       task_message_new(MESSAGE_UNCHOKE, peer->hostname, peer->mailbox, peer->id, task_message_size(MESSAGE_UNCHOKE));
848   MSG_task_dsend(task, mailbox, task_message_free);
849 }
850
851 /** Send a "HAVE" message to all peers we are connected to */
852 void send_have(peer_t peer, int piece)
853 {
854   XBT_DEBUG("Sending HAVE message to all my peers");
855   connection_t remote_peer;
856   xbt_dict_cursor_t cursor = NULL;
857   char* key;
858   xbt_dict_foreach (peer->peers, cursor, key, remote_peer) {
859     msg_task_t task = task_message_index_new(MESSAGE_HAVE, peer->hostname, peer->mailbox, peer->id, piece,
860                                              task_message_size(MESSAGE_HAVE));
861     MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
862   }
863 }
864
865 /** @brief Send a bitfield message to all the peers the peer has.
866  *  @param peer peer data
867  */
868 void send_bitfield(peer_t peer, const char* mailbox)
869 {
870   XBT_DEBUG("Sending a BITFIELD to %s", mailbox);
871   msg_task_t task = task_message_bitfield_new(peer->hostname, peer->mailbox, peer->id, peer->bitfield, FILE_PIECES);
872   MSG_task_dsend(task, mailbox, task_message_free);
873 }
874
875 /** Send a "request" message to a pair, containing a request for a piece */
876 void send_request(peer_t peer, const char* mailbox, int piece, int block_index, int block_length)
877 {
878   XBT_DEBUG("Sending a REQUEST to %s for piece %d (%d,%d)", mailbox, piece, block_index, block_length);
879   msg_task_t task = task_message_request_new(peer->hostname, peer->mailbox, peer->id, piece, block_index, block_length);
880   MSG_task_dsend(task, mailbox, task_message_free);
881 }
882
883 /** Send a "piece" message to a pair, containing a piece of the file */
884 void send_piece(peer_t peer, const char* mailbox, int piece, int block_index, int block_length)
885 {
886   XBT_DEBUG("Sending the PIECE %d (%d,%d) to %s", piece, block_index, block_length, mailbox);
887   xbt_assert(piece >= 0, "Tried to send a piece that doesn't exist.");
888   xbt_assert(!peer_has_not_piece(peer, piece), "Tried to send a piece that we doesn't have.");
889   msg_task_t task =
890       task_message_piece_new(peer->hostname, peer->mailbox, peer->id, piece, block_index, block_length, BLOCK_SIZE);
891   MSG_task_dsend(task, mailbox, task_message_free);
892 }