Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
1c865bfad149bb5325eb3a6f36c47ceed8227485
[simgrid.git] / teshsuite / msg / app-bittorrent / peer.c
1 /* Copyright (c) 2012-2017. 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 "peer.h"
7 #include "connection.h"
8 #include "messages.h"
9 #include "tracker.h"
10 #include <limits.h>
11 #include <simgrid/msg.h>
12 #include <xbt/RngStream.h>
13
14 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_peers, "Messages specific for the peers");
15
16 /*
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
19  */
20 #define FILE_PIECES 10UL
21 #define PIECES_BLOCKS 5UL
22 #define BLOCK_SIZE 16384
23 static const unsigned long int FILE_SIZE = FILE_PIECES * PIECES_BLOCKS * BLOCK_SIZE;
24
25 /** Number of blocks asked by each request */
26 #define BLOCKS_REQUESTED 2
27
28 #define ENABLE_END_GAME_MODE 1
29 #define SLEEP_DURATION 1
30
31 int count_pieces(unsigned int bitfield)
32 {
33   int count      = 0;
34   unsigned int n = bitfield;
35   while (n) {
36     count += n & 1U;
37     n >>= 1U;
38   }
39   return count;
40 }
41
42 int peer_has_not_piece(peer_t peer, unsigned int piece)
43 {
44   return !(peer->bitfield & 1U << piece);
45 }
46
47 /** Check that a piece is not currently being download by the peer. */
48 int peer_is_not_downloading_piece(peer_t peer, unsigned int piece)
49 {
50   return !(peer->current_pieces & 1U << piece);
51 }
52
53 void get_status(char** status, unsigned int bitfield)
54 {
55   for (int i             = FILE_PIECES - 1; i >= 0; i--)
56     (*status)[i]         = (bitfield & (1U << i)) ? '1' : '0';
57   (*status)[FILE_PIECES] = '\0';
58 }
59
60 /** Peer main function */
61 int peer(int argc, char* argv[])
62 {
63   // Check arguments
64   xbt_assert(argc == 3 || argc == 4, "Wrong number of arguments");
65
66   // Build peer object
67   peer_t peer = peer_init(argv[1], argc == 4 ? 1 : 0);
68
69   // Retrieve deadline
70   double deadline = xbt_str_parse_double(argv[2], "Invalid deadline: %s");
71   xbt_assert(deadline > 0, "Wrong deadline supplied");
72
73   char* status = xbt_malloc0(FILE_PIECES + 1);
74   get_status(&status, peer->bitfield);
75   XBT_INFO("Hi, I'm joining the network with id %d", atoi(peer->id));
76   // Getting peer data from the tracker.
77   if (get_peers_data(peer)) {
78     XBT_DEBUG("Got %d peers from the tracker. Current status is: %s", xbt_dict_length(peer->peers), status);
79     peer->begin_receive_time = MSG_get_clock();
80     MSG_mailbox_set_async(peer->mailbox);
81     if (has_finished(peer->bitfield)) {
82       send_handshake_all(peer);
83     } else {
84       leech_loop(peer, deadline);
85     }
86     seed_loop(peer, deadline);
87   } else {
88     XBT_INFO("Couldn't contact the tracker.");
89   }
90
91   get_status(&status, peer->bitfield);
92   XBT_INFO("Here is my current status: %s", status);
93   if (peer->comm_received) {
94     MSG_comm_destroy(peer->comm_received);
95   }
96
97   xbt_free(status);
98   peer_free(peer);
99   return 0;
100 }
101
102 /** @brief Peer main loop when it is leeching.
103  *  @param peer peer data
104  *  @param deadline time at which the peer has to leave
105  */
106 void leech_loop(peer_t peer, double deadline)
107 {
108   double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
109   XBT_DEBUG("Start downloading.");
110
111   /* Send a "handshake" message to all the peers it got (since it couldn't have gotten more than 50 peers) */
112   send_handshake_all(peer);
113   XBT_DEBUG("Starting main leech loop");
114
115   while (MSG_get_clock() < deadline && count_pieces(peer->bitfield) < FILE_PIECES) {
116     if (peer->comm_received == NULL) {
117       peer->task_received = NULL;
118       peer->comm_received = MSG_task_irecv(&peer->task_received, peer->mailbox);
119     }
120     if (MSG_comm_test(peer->comm_received)) {
121       msg_error_t status = MSG_comm_get_status(peer->comm_received);
122       MSG_comm_destroy(peer->comm_received);
123       peer->comm_received = NULL;
124       if (status == MSG_OK) {
125         handle_message(peer, peer->task_received);
126       }
127     } else {
128       // We don't execute the choke algorithm if we don't already have a piece
129       if (MSG_get_clock() >= next_choked_update && count_pieces(peer->bitfield) > 0) {
130         update_choked_peers(peer);
131         next_choked_update += UPDATE_CHOKED_INTERVAL;
132       } else {
133         MSG_process_sleep(SLEEP_DURATION);
134       }
135     }
136   }
137   if (has_finished(peer->bitfield))
138     XBT_DEBUG("%s becomes a seeder", peer->id);
139 }
140
141 /** @brief Peer main loop when it is seeding
142  *  @param peer peer data
143  *  @param deadline time when the peer will leave
144  */
145 void seed_loop(peer_t peer, double deadline)
146 {
147   double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
148   XBT_DEBUG("Start seeding.");
149   // start the main seed loop
150   while (MSG_get_clock() < deadline) {
151     if (peer->comm_received == NULL) {
152       peer->task_received = NULL;
153       peer->comm_received = MSG_task_irecv(&peer->task_received, peer->mailbox);
154     }
155     if (MSG_comm_test(peer->comm_received)) {
156       msg_error_t status = MSG_comm_get_status(peer->comm_received);
157       MSG_comm_destroy(peer->comm_received);
158       peer->comm_received = NULL;
159       if (status == MSG_OK) {
160         handle_message(peer, peer->task_received);
161       }
162     } else {
163       if (MSG_get_clock() >= next_choked_update) {
164         update_choked_peers(peer);
165         // TODO: Change the choked peer algorithm when seeding.
166         next_choked_update += UPDATE_CHOKED_INTERVAL;
167       } else {
168         MSG_process_sleep(SLEEP_DURATION);
169       }
170     }
171   }
172 }
173
174 /** @brief Retrieves the peer list from the tracker
175  *  @param peer current peer data
176  */
177 int get_peers_data(peer_t peer)
178 {
179   int success    = 0;
180   double timeout = MSG_get_clock() + GET_PEERS_TIMEOUT;
181
182   // Build the task to send to the tracker
183   tracker_task_data_t data =
184       tracker_task_data_new(MSG_host_get_name(MSG_host_self()), peer->mailbox_tracker, peer->id, 0, 0, FILE_SIZE);
185   msg_task_t task_send = MSG_task_create(NULL, 0, TRACKER_COMM_SIZE, data);
186   while ((success == 0) && MSG_get_clock() < timeout) {
187     XBT_DEBUG("Sending a peer request to the tracker.");
188     msg_error_t status = MSG_task_send_with_timeout(task_send, TRACKER_MAILBOX, GET_PEERS_TIMEOUT);
189     if (status == MSG_OK) {
190       success = 1;
191     }
192   }
193
194   success                  = 0;
195   msg_task_t task_received = NULL;
196   while ((success == 0) && MSG_get_clock() < timeout) {
197     msg_comm_t comm_received = MSG_task_irecv(&task_received, peer->mailbox_tracker);
198     msg_error_t status       = MSG_comm_wait(comm_received, GET_PEERS_TIMEOUT);
199     if (status == MSG_OK) {
200       tracker_task_data_t data = MSG_task_get_data(task_received);
201       unsigned i;
202       const char* peer_id;
203       // Add the peers the tracker gave us to our peer list.
204       xbt_dynar_foreach (data->peers, i, peer_id) {
205         if (!strcmp(peer_id, peer->id))
206           xbt_dict_set(peer->peers, peer_id, connection_new(peer_id), NULL);
207       }
208       success = 1;
209       // free the communication and the task
210       MSG_comm_destroy(comm_received);
211       tracker_task_data_free(data);
212       MSG_task_destroy(task_received);
213     }
214   }
215
216   return success;
217 }
218
219 /** @brief Initialize the peer data.
220  *  @param peer peer data
221  *  @param id id of the peer to take in the network
222  *  @param seed indicates if the peer is a seed.
223  */
224 peer_t peer_init(const char* id, int seed)
225 {
226   peer_t peer    = xbt_new(s_peer_t, 1);
227   peer->id       = xbt_strdup(id);
228   peer->hostname = MSG_host_get_name(MSG_host_self());
229
230   snprintf(peer->mailbox, MAILBOX_SIZE - 1, "%s", id);
231   snprintf(peer->mailbox_tracker, MAILBOX_SIZE - 1, "tracker_%s", id);
232   peer->peers        = xbt_dict_new_homogeneous(NULL);
233   peer->active_peers = xbt_dict_new_homogeneous(NULL);
234
235   if (seed) {
236     peer->bitfield        = (1U << FILE_PIECES) - 1U;
237     peer->bitfield_blocks = (1ULL << (FILE_PIECES * PIECES_BLOCKS)) - 1ULL;
238   } else {
239     peer->bitfield        = 0;
240     peer->bitfield_blocks = 0;
241   }
242
243   peer->current_pieces = 0;
244
245   peer->pieces_count = xbt_new0(short, FILE_PIECES);
246
247   peer->stream        = (RngStream)MSG_host_get_data(MSG_host_self());
248   peer->comm_received = NULL;
249
250   peer->round = 0;
251
252   return peer;
253 }
254
255 /** Destroys a poor peer object. */
256 void peer_free(peer_t peer)
257 {
258   char* key;
259   connection_t connection;
260   xbt_dict_cursor_t cursor;
261   xbt_dict_foreach (peer->peers, cursor, key, connection) {
262     connection_free(connection);
263   }
264   xbt_dict_free(&peer->peers);
265   xbt_dict_free(&peer->active_peers);
266   xbt_free(peer->pieces_count);
267   xbt_free(peer->id);
268   xbt_free(peer);
269 }
270
271 /** @brief Returns if a peer has finished downloading the file
272  *  @param bitfield peer bitfield
273  */
274 int has_finished(unsigned int bitfield)
275 {
276   return bitfield == (1U << FILE_PIECES) - 1U;
277 }
278
279 int nb_interested_peers(peer_t peer)
280 {
281   xbt_dict_cursor_t cursor = NULL;
282   char* key;
283   connection_t connection;
284   int nb = 0;
285   xbt_dict_foreach (peer->peers, cursor, key, connection) {
286     if (connection->interested)
287       nb++;
288   }
289   return nb;
290 }
291
292 void update_active_peers_set(peer_t peer, connection_t remote_peer)
293 {
294   if ((remote_peer->interested != 0) && (remote_peer->choked_upload == 0)) {
295     // add in the active peers set
296     xbt_dict_set(peer->active_peers, remote_peer->id, remote_peer, NULL);
297   } else if (xbt_dict_get_or_null(peer->active_peers, remote_peer->id)) {
298     xbt_dict_remove(peer->active_peers, remote_peer->id);
299   }
300 }
301
302 /** @brief Handle a received message sent by another peer
303  * @param peer Peer data
304  * @param task task received.
305  */
306 void handle_message(peer_t peer, msg_task_t task)
307 {
308   const char* type_names[10] = {"HANDSHAKE", "CHOKE",    "UNCHOKE", "INTERESTED", "NOTINTERESTED",
309                                 "HAVE",      "BITFIELD", "REQUEST", "PIECE",      "CANCEL"};
310   message_t message = MSG_task_get_data(task);
311   XBT_DEBUG("Received a %s message from %s (%s)", type_names[message->type], message->mailbox,
312             message->issuer_host_name);
313
314   connection_t remote_peer;
315   remote_peer = xbt_dict_get_or_null(peer->peers, message->peer_id);
316
317   switch (message->type) {
318     case MESSAGE_HANDSHAKE:
319       // Check if the peer is in our connection list.
320       if (remote_peer == 0) {
321         xbt_dict_set(peer->peers, message->peer_id, connection_new(message->peer_id), NULL);
322         send_handshake(peer, message->mailbox);
323       }
324       // Send our bitfield to the peer
325       send_bitfield(peer, message->mailbox);
326       break;
327     case MESSAGE_BITFIELD:
328       // Update the pieces list
329       update_pieces_count_from_bitfield(peer, message->bitfield);
330       // Store the bitfield
331       remote_peer->bitfield = message->bitfield;
332       xbt_assert(!remote_peer->am_interested, "Should not be interested at first");
333       if (is_interested(peer, remote_peer)) {
334         remote_peer->am_interested = 1;
335         send_interested(peer, message->mailbox);
336       }
337       break;
338     case MESSAGE_INTERESTED:
339       xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
340       // Update the interested state of the peer.
341       remote_peer->interested = 1;
342       update_active_peers_set(peer, remote_peer);
343       break;
344     case MESSAGE_NOTINTERESTED:
345       xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
346       remote_peer->interested = 0;
347       update_active_peers_set(peer, remote_peer);
348       break;
349     case MESSAGE_UNCHOKE:
350       xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
351       xbt_assert(remote_peer->choked_download);
352       remote_peer->choked_download = 0;
353       // Send requests to the peer, since it has unchoked us
354       if (remote_peer->am_interested)
355         request_new_piece_to_peer(peer, remote_peer);
356       break;
357     case MESSAGE_CHOKE:
358       xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
359       xbt_assert(!remote_peer->choked_download);
360       remote_peer->choked_download = 1;
361       if (remote_peer->current_piece != -1)
362         remove_current_piece(peer, remote_peer, remote_peer->current_piece);
363       break;
364     case MESSAGE_HAVE:
365       XBT_DEBUG("\t for piece %d", message->index);
366       xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong HAVE message received");
367       remote_peer->bitfield = remote_peer->bitfield | (1U << message->index);
368       peer->pieces_count[message->index]++;
369       // If the piece is in our pieces, we tell the peer that we are interested.
370       if ((remote_peer->am_interested == 0) && peer_has_not_piece(peer, message->index)) {
371         remote_peer->am_interested = 1;
372         send_interested(peer, message->mailbox);
373         if (remote_peer->choked_download == 0)
374           request_new_piece_to_peer(peer, remote_peer);
375       }
376       break;
377     case MESSAGE_REQUEST:
378       xbt_assert(remote_peer->interested);
379       xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong request received");
380       if (remote_peer->choked_upload == 0) {
381         XBT_DEBUG("\t for piece %d (%d,%d)", message->index, message->block_index,
382                   message->block_index + message->block_length);
383         if (!peer_has_not_piece(peer, message->index)) {
384           send_piece(peer, message->mailbox, message->index, message->block_index, message->block_length);
385         }
386       } else {
387         XBT_DEBUG("\t for piece %s but he is choked.", message->peer_id);
388       }
389       break;
390     case MESSAGE_PIECE:
391       XBT_DEBUG(" \t for piece %d (%d,%d)", message->index, message->block_index,
392                 message->block_index + message->block_length);
393       xbt_assert(!remote_peer->choked_download);
394       xbt_assert(remote_peer->am_interested || ENABLE_END_GAME_MODE,
395                  "Can't received a piece if I'm not interested wihtout end-game mode!"
396                  "piece (%d) bitfield(%u) remote bitfield(%u)",
397                  message->index, peer->bitfield, remote_peer->bitfield);
398       xbt_assert(remote_peer->choked_download != 1, "Can't received a piece if I'm choked !");
399       xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong piece received");
400       // TODO: Execute Ã  computation.
401       if (peer_has_not_piece(peer, message->index)) {
402         update_bitfield_blocks(peer, message->index, message->block_index, message->block_length);
403         if (piece_complete(peer, message->index)) {
404           // Removing the piece from our piece list
405           remove_current_piece(peer, remote_peer, message->index);
406           // Setting the fact that we have the piece
407           peer->bitfield = peer->bitfield | (1U << message->index);
408           char* status   = xbt_malloc0(FILE_PIECES + 1);
409           get_status(&status, peer->bitfield);
410           XBT_DEBUG("My status is now %s", status);
411           xbt_free(status);
412           // Sending the information to all the peers we are connected to
413           send_have(peer, message->index);
414           // sending UNINTERESTED to peers that do not have what we want.
415           update_interested_after_receive(peer);
416         } else {                                                   // piece not completed
417           send_request_to_peer(peer, remote_peer, message->index); // ask for the next block
418         }
419       } else {
420         XBT_DEBUG("However, we already have it");
421         xbt_assert(ENABLE_END_GAME_MODE, "Should not happen because we don't use end game mode !");
422         request_new_piece_to_peer(peer, remote_peer);
423       }
424       break;
425     case MESSAGE_CANCEL:
426       break;
427     default:
428       THROW_IMPOSSIBLE;
429   }
430   // Update the peer speed.
431   if (remote_peer) {
432     connection_add_speed_value(remote_peer, 1.0 / (MSG_get_clock() - peer->begin_receive_time));
433   }
434   peer->begin_receive_time = MSG_get_clock();
435
436   task_message_free(task);
437 }
438
439 /** Selects the appropriate piece to download and requests it to the remote_peer */
440 void request_new_piece_to_peer(peer_t peer, connection_t remote_peer)
441 {
442   int piece = select_piece_to_download(peer, remote_peer);
443   if (piece != -1) {
444     peer->current_pieces |= (1U << (unsigned int)piece);
445     send_request_to_peer(peer, remote_peer, piece);
446   }
447 }
448
449 /** remove current_piece from the list of currently downloaded pieces. */
450 void remove_current_piece(peer_t peer, connection_t remote_peer, unsigned int current_piece)
451 {
452   peer->current_pieces &= ~(1U << current_piece);
453   remote_peer->current_piece = -1;
454 }
455
456 /** @brief Updates the list of who has a piece from a bitfield
457  *  @param peer peer we want to update the list
458  *  @param bitfield bitfield
459  */
460 void update_pieces_count_from_bitfield(peer_t peer, unsigned int bitfield)
461 {
462   for (int i = 0; i < FILE_PIECES; i++) {
463     if (bitfield & (1U << i)) {
464       peer->pieces_count[i]++;
465     }
466   }
467 }
468
469 /** @brief Return the piece to be downloaded
470  * There are two cases (as described in "Bittorrent Architecture Protocol", Ryan Toole :
471  * If a piece is partially downloaded, this piece will be selected prioritarily
472  * If the peer has strictly less than 4 pieces, he chooses a piece at random.
473  * If the peer has more than pieces, he downloads the pieces that are the less replicated (rarest policy).
474  * If all pieces have been downloaded or requested, we select a random requested piece (endgame mode).
475  * @param peer: local peer
476  * @param remote_peer: information about the connection
477  * @return the piece to download if possible. -1 otherwise
478  */
479 int select_piece_to_download(peer_t peer, connection_t remote_peer)
480 {
481   int piece = partially_downloaded_piece(peer, remote_peer);
482   // strict priority policy
483   if (piece != -1)
484     return piece;
485
486   // end game mode
487   if (count_pieces(peer->current_pieces) >= (FILE_PIECES - count_pieces(peer->bitfield)) &&
488       (is_interested(peer, remote_peer) != 0)) {
489 #if ENABLE_END_GAME_MODE == 0
490     return -1;
491 #endif
492     int nb_interesting_pieces = 0;
493     // compute the number of interesting pieces
494     for (int i = 0; i < FILE_PIECES; i++) {
495       if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i)) {
496         nb_interesting_pieces++;
497       }
498     }
499     xbt_assert(nb_interesting_pieces != 0);
500     // get a random interesting piece
501     int random_piece_index = RngStream_RandInt(peer->stream, 0, nb_interesting_pieces - 1);
502     int current_index      = 0;
503     for (int i = 0; i < FILE_PIECES; i++) {
504       if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i)) {
505         if (random_piece_index == current_index) {
506           piece = i;
507           break;
508         }
509         current_index++;
510       }
511     }
512     xbt_assert(piece != -1);
513     return piece;
514   }
515   // Random first policy
516   if (count_pieces(peer->bitfield) < 4 && (is_interested_and_free(peer, remote_peer) != 0)) {
517     int nb_interesting_pieces = 0;
518     // compute the number of interesting pieces
519     for (int i = 0; i < FILE_PIECES; i++) {
520       if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
521           peer_is_not_downloading_piece(peer, i)) {
522         nb_interesting_pieces++;
523       }
524     }
525     xbt_assert(nb_interesting_pieces != 0);
526     // get a random interesting piece
527     int random_piece_index = RngStream_RandInt(peer->stream, 0, nb_interesting_pieces - 1);
528     int current_index      = 0;
529     for (int i = 0; i < FILE_PIECES; i++) {
530       if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
531           peer_is_not_downloading_piece(peer, i)) {
532         if (random_piece_index == current_index) {
533           piece = i;
534           break;
535         }
536         current_index++;
537       }
538     }
539     xbt_assert(piece != -1);
540     return piece;
541   } else { // Rarest first policy
542     short min         = SHRT_MAX;
543     int nb_min_pieces = 0;
544     int current_index = 0;
545     // compute the smallest number of copies of available pieces
546     for (int i = 0; i < FILE_PIECES; i++) {
547       if (peer->pieces_count[i] < min && peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
548           peer_is_not_downloading_piece(peer, i))
549         min = peer->pieces_count[i];
550     }
551     xbt_assert(min != SHRT_MAX || (is_interested_and_free(peer, remote_peer) == 0));
552     // compute the number of rarest pieces
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         nb_min_pieces++;
557     }
558     xbt_assert(nb_min_pieces != 0 || (is_interested_and_free(peer, remote_peer) == 0));
559     // get a random rarest piece
560     int random_rarest_index = RngStream_RandInt(peer->stream, 0, nb_min_pieces - 1);
561     for (int i = 0; i < FILE_PIECES; i++) {
562       if (peer->pieces_count[i] == min && peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
563           peer_is_not_downloading_piece(peer, i)) {
564         if (random_rarest_index == current_index) {
565           piece = i;
566           break;
567         }
568         current_index++;
569       }
570     }
571     xbt_assert(piece != -1 || (is_interested_and_free(peer, remote_peer) == 0));
572     return piece;
573   }
574 }
575
576 /** @brief Update the list of current choked and unchoked peers, using the choke algorithm
577  *  @param peer the current peer
578  */
579 void update_choked_peers(peer_t peer)
580 {
581   if (nb_interested_peers(peer) == 0)
582     return;
583   XBT_DEBUG("(%s) update_choked peers %u active peers", peer->id, xbt_dict_size(peer->active_peers));
584   // update the current round
585   peer->round = (peer->round + 1) % 3;
586   char* key;
587   char* key_choked          = NULL;
588   connection_t peer_choosed = NULL;
589   connection_t peer_choked  = NULL;
590   // remove a peer from the list
591   xbt_dict_cursor_t cursor = NULL;
592   xbt_dict_cursor_first(peer->active_peers, &cursor);
593   if (xbt_dict_length(peer->active_peers) > 0) {
594     key_choked  = xbt_dict_cursor_get_key(cursor);
595     peer_choked = xbt_dict_cursor_get_data(cursor);
596   }
597   xbt_dict_cursor_free(&cursor);
598
599   /**If we are currently seeding, we unchoke the peer which has been unchoked the last time.*/
600   if (has_finished(peer->bitfield)) {
601     connection_t connection;
602     double unchoke_time = MSG_get_clock() + 1;
603
604     xbt_dict_foreach (peer->peers, cursor, key, connection) {
605       if (connection->last_unchoke < unchoke_time && (connection->interested != 0) &&
606           (connection->choked_upload != 0)) {
607         unchoke_time = connection->last_unchoke;
608         peer_choosed = connection;
609       }
610     }
611   } else {
612     // Random optimistic unchoking
613     if (peer->round == 0) {
614       int j = 0;
615       do {
616         // We choose a random peer to unchoke.
617         int id_chosen = RngStream_RandInt(peer->stream, 0, xbt_dict_length(peer->peers) - 1);
618         int i         = 0;
619         connection_t connection;
620         xbt_dict_foreach (peer->peers, cursor, key, connection) {
621           if (i == id_chosen) {
622             peer_choosed = connection;
623             break;
624           }
625           i++;
626         }
627         xbt_dict_cursor_free(&cursor);
628         if (peer_choosed == NULL)
629           THROWF(unknown_error, 0, "A peer should have be selected at this point");
630         else 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("(%s) update_choked peers unchoked (%s) ; 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(strcmp(key_choked, peer_choked->id));
659       update_active_peers_set(peer, peer_choked);
660       XBT_DEBUG("(%s) Sending a CHOKE to %s", 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(peer->active_peers, peer_choosed->id, peer_choosed, NULL);
667       peer_choosed->last_unchoke = MSG_get_clock();
668       XBT_DEBUG("(%s) Sending a UNCHOKE to %s", 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 }