Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Cosmetic rename.
[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
12 #include <limits.h>
13 #include <stdio.h> /* snprintf */
14
15 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_peers, "Messages specific for the peers");
16
17 /*
18  * User parameters for transferred file data. For the test, the default values are :
19  * File size: 10 pieces * 5 blocks/piece * 16384 bytes/block = 819200 bytes
20  */
21 #define FILE_PIECES 10UL
22 #define PIECES_BLOCKS 5UL
23 #define BLOCK_SIZE 16384
24 static const unsigned long int FILE_SIZE = FILE_PIECES * PIECES_BLOCKS * BLOCK_SIZE;
25
26 /** Number of blocks asked by each request */
27 #define BLOCKS_REQUESTED 2
28
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(xbt_str_parse_int(argv[1], "Invalid ID: %s"), 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", 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("%d 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       int 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 (peer_id != peer->id)
206           xbt_dict_set_ext(peer->peers, (char*)&peer_id, sizeof(int), 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(int id, int seed)
225 {
226   peer_t peer    = xbt_new(s_peer_t, 1);
227   peer->id       = id;
228   peer->hostname = MSG_host_get_name(MSG_host_self());
229
230   snprintf(peer->mailbox, MAILBOX_SIZE - 1, "%d", id);
231   snprintf(peer->mailbox_tracker, MAILBOX_SIZE - 1, "tracker_%d", 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->comm_received = NULL;
248
249   peer->round = 0;
250
251   return peer;
252 }
253
254 /** Destroys a poor peer object. */
255 void peer_free(peer_t peer)
256 {
257   char* key;
258   connection_t connection;
259   xbt_dict_cursor_t cursor;
260   xbt_dict_foreach (peer->peers, cursor, key, connection) {
261     connection_free(connection);
262   }
263   xbt_dict_free(&peer->peers);
264   xbt_dict_free(&peer->active_peers);
265   xbt_free(peer->pieces_count);
266   xbt_free(peer);
267 }
268
269 /** @brief Returns if a peer has finished downloading the file
270  *  @param bitfield peer bitfield
271  */
272 int has_finished(unsigned int bitfield)
273 {
274   return bitfield == (1U << FILE_PIECES) - 1U;
275 }
276
277 int nb_interested_peers(peer_t peer)
278 {
279   xbt_dict_cursor_t cursor = NULL;
280   char* key;
281   connection_t connection;
282   int nb = 0;
283   xbt_dict_foreach (peer->peers, cursor, key, connection) {
284     if (connection->interested)
285       nb++;
286   }
287   return nb;
288 }
289
290 void update_active_peers_set(peer_t peer, connection_t remote_peer)
291 {
292   if ((remote_peer->interested != 0) && (remote_peer->choked_upload == 0)) {
293     // add in the active peers set
294     xbt_dict_set_ext(peer->active_peers, (char*)&remote_peer->id, sizeof(int), remote_peer, NULL);
295   } else if (xbt_dict_get_or_null_ext(peer->active_peers, (char*)&remote_peer->id, sizeof(int))) {
296     xbt_dict_remove_ext(peer->active_peers, (char*)&remote_peer->id, sizeof(int));
297   }
298 }
299
300 /** @brief Handle a received message sent by another peer
301  * @param peer Peer data
302  * @param task task received.
303  */
304 void handle_message(peer_t peer, msg_task_t task)
305 {
306   const char* type_names[10] = {"HANDSHAKE", "CHOKE",    "UNCHOKE", "INTERESTED", "NOTINTERESTED",
307                                 "HAVE",      "BITFIELD", "REQUEST", "PIECE",      "CANCEL"};
308   message_t message = MSG_task_get_data(task);
309   XBT_DEBUG("Received a %s message from %s (%s)", type_names[message->type], message->mailbox,
310             message->issuer_host_name);
311
312   connection_t remote_peer;
313   remote_peer = xbt_dict_get_or_null_ext(peer->peers, (char*)&message->peer_id, sizeof(int));
314
315   switch (message->type) {
316     case MESSAGE_HANDSHAKE:
317       // Check if the peer is in our connection list.
318       if (remote_peer == 0) {
319         xbt_dict_set_ext(peer->peers, (char*)&message->peer_id, sizeof(int), connection_new(message->peer_id), NULL);
320         send_handshake(peer, message->mailbox);
321       }
322       // Send our bitfield to the peer
323       send_bitfield(peer, message->mailbox);
324       break;
325     case MESSAGE_BITFIELD:
326       // Update the pieces list
327       update_pieces_count_from_bitfield(peer, message->bitfield);
328       // Store the bitfield
329       remote_peer->bitfield = message->bitfield;
330       xbt_assert(!remote_peer->am_interested, "Should not be interested at first");
331       if (is_interested(peer, remote_peer)) {
332         remote_peer->am_interested = 1;
333         send_interested(peer, message->mailbox);
334       }
335       break;
336     case MESSAGE_INTERESTED:
337       xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
338       // Update the interested state of the peer.
339       remote_peer->interested = 1;
340       update_active_peers_set(peer, remote_peer);
341       break;
342     case MESSAGE_NOTINTERESTED:
343       xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
344       remote_peer->interested = 0;
345       update_active_peers_set(peer, remote_peer);
346       break;
347     case MESSAGE_UNCHOKE:
348       xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
349       xbt_assert(remote_peer->choked_download);
350       remote_peer->choked_download = 0;
351       // Send requests to the peer, since it has unchoked us
352       if (remote_peer->am_interested)
353         request_new_piece_to_peer(peer, remote_peer);
354       break;
355     case MESSAGE_CHOKE:
356       xbt_assert((remote_peer != NULL), "A non-in-our-list peer has sent us a message. WTH ?");
357       xbt_assert(!remote_peer->choked_download);
358       remote_peer->choked_download = 1;
359       if (remote_peer->current_piece != -1)
360         remove_current_piece(peer, remote_peer, remote_peer->current_piece);
361       break;
362     case MESSAGE_HAVE:
363       XBT_DEBUG("\t for piece %d", message->index);
364       xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong HAVE message received");
365       remote_peer->bitfield = remote_peer->bitfield | (1U << message->index);
366       peer->pieces_count[message->index]++;
367       // If the piece is in our pieces, we tell the peer that we are interested.
368       if ((remote_peer->am_interested == 0) && peer_has_not_piece(peer, message->index)) {
369         remote_peer->am_interested = 1;
370         send_interested(peer, message->mailbox);
371         if (remote_peer->choked_download == 0)
372           request_new_piece_to_peer(peer, remote_peer);
373       }
374       break;
375     case MESSAGE_REQUEST:
376       xbt_assert(remote_peer->interested);
377       xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong request received");
378       if (remote_peer->choked_upload == 0) {
379         XBT_DEBUG("\t for piece %d (%d,%d)", message->index, message->block_index,
380                   message->block_index + message->block_length);
381         if (!peer_has_not_piece(peer, message->index)) {
382           send_piece(peer, message->mailbox, message->index, message->block_index, message->block_length);
383         }
384       } else {
385         XBT_DEBUG("\t for piece %d but he is choked.", message->peer_id);
386       }
387       break;
388     case MESSAGE_PIECE:
389       XBT_DEBUG(" \t for piece %d (%d,%d)", message->index, message->block_index,
390                 message->block_index + message->block_length);
391       xbt_assert(!remote_peer->choked_download);
392       xbt_assert(remote_peer->choked_download != 1, "Can't received a piece if I'm choked !");
393       xbt_assert((message->index >= 0 && message->index < FILE_PIECES), "Wrong piece received");
394       // TODO: Execute Ã  computation.
395       if (peer_has_not_piece(peer, message->index)) {
396         update_bitfield_blocks(peer, message->index, message->block_index, message->block_length);
397         if (piece_complete(peer, message->index)) {
398           // Removing the piece from our piece list
399           remove_current_piece(peer, remote_peer, message->index);
400           // Setting the fact that we have the piece
401           peer->bitfield = peer->bitfield | (1U << message->index);
402           char* status   = xbt_malloc0(FILE_PIECES + 1);
403           get_status(&status, peer->bitfield);
404           XBT_DEBUG("My status is now %s", status);
405           xbt_free(status);
406           // Sending the information to all the peers we are connected to
407           send_have(peer, message->index);
408           // sending UNINTERESTED to peers that do not have what we want.
409           update_interested_after_receive(peer);
410         } else {                                                   // piece not completed
411           send_request_to_peer(peer, remote_peer, message->index); // ask for the next block
412         }
413       } else {
414         XBT_DEBUG("However, we already have it");
415         request_new_piece_to_peer(peer, remote_peer);
416       }
417       break;
418     case MESSAGE_CANCEL:
419       break;
420     default:
421       THROW_IMPOSSIBLE;
422   }
423   // Update the peer speed.
424   if (remote_peer) {
425     connection_add_speed_value(remote_peer, 1.0 / (MSG_get_clock() - peer->begin_receive_time));
426   }
427   peer->begin_receive_time = MSG_get_clock();
428
429   task_message_free(task);
430 }
431
432 /** Selects the appropriate piece to download and requests it to the remote_peer */
433 void request_new_piece_to_peer(peer_t peer, connection_t remote_peer)
434 {
435   int piece = select_piece_to_download(peer, remote_peer);
436   if (piece != -1) {
437     peer->current_pieces |= (1U << (unsigned int)piece);
438     send_request_to_peer(peer, remote_peer, piece);
439   }
440 }
441
442 /** remove current_piece from the list of currently downloaded pieces. */
443 void remove_current_piece(peer_t peer, connection_t remote_peer, unsigned int current_piece)
444 {
445   peer->current_pieces &= ~(1U << current_piece);
446   remote_peer->current_piece = -1;
447 }
448
449 /** @brief Updates the list of who has a piece from a bitfield
450  *  @param peer peer we want to update the list
451  *  @param bitfield bitfield
452  */
453 void update_pieces_count_from_bitfield(peer_t peer, unsigned int bitfield)
454 {
455   for (int i = 0; i < FILE_PIECES; i++) {
456     if (bitfield & (1U << i)) {
457       peer->pieces_count[i]++;
458     }
459   }
460 }
461
462 /** @brief Return the piece to be downloaded
463  * There are two cases (as described in "Bittorrent Architecture Protocol", Ryan Toole :
464  * If a piece is partially downloaded, this piece will be selected prioritarily
465  * If the peer has strictly less than 4 pieces, he chooses a piece at random.
466  * If the peer has more than pieces, he downloads the pieces that are the less replicated (rarest policy).
467  * If all pieces have been downloaded or requested, we select a random requested piece (endgame mode).
468  * @param peer: local peer
469  * @param remote_peer: information about the connection
470  * @return the piece to download if possible. -1 otherwise
471  */
472 int select_piece_to_download(peer_t peer, connection_t remote_peer)
473 {
474   int piece = partially_downloaded_piece(peer, remote_peer);
475   // strict priority policy
476   if (piece != -1)
477     return piece;
478
479   // end game mode
480   if (count_pieces(peer->current_pieces) >= (FILE_PIECES - count_pieces(peer->bitfield)) &&
481       (is_interested(peer, remote_peer) != 0)) {
482     int nb_interesting_pieces = 0;
483     // compute the number of interesting pieces
484     for (int i = 0; i < FILE_PIECES; i++) {
485       if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i)) {
486         nb_interesting_pieces++;
487       }
488     }
489     xbt_assert(nb_interesting_pieces != 0);
490     // get a random interesting piece
491     int random_piece_index = rand() % nb_interesting_pieces;
492     int current_index      = 0;
493     for (int i = 0; i < FILE_PIECES; i++) {
494       if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i)) {
495         if (random_piece_index == current_index) {
496           piece = i;
497           break;
498         }
499         current_index++;
500       }
501     }
502     xbt_assert(piece != -1);
503     return piece;
504   }
505   // Random first policy
506   if (count_pieces(peer->bitfield) < 4 && (is_interested_and_free(peer, remote_peer) != 0)) {
507     int nb_interesting_pieces = 0;
508     // compute the number of interesting pieces
509     for (int i = 0; i < FILE_PIECES; i++) {
510       if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
511           peer_is_not_downloading_piece(peer, i)) {
512         nb_interesting_pieces++;
513       }
514     }
515     xbt_assert(nb_interesting_pieces != 0);
516     // get a random interesting piece
517     int random_piece_index = rand() % nb_interesting_pieces;
518     int current_index      = 0;
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         if (random_piece_index == current_index) {
523           piece = i;
524           break;
525         }
526         current_index++;
527       }
528     }
529     xbt_assert(piece != -1);
530     return piece;
531   } else { // Rarest first policy
532     short min         = SHRT_MAX;
533     int nb_min_pieces = 0;
534     int current_index = 0;
535     // compute the smallest number of copies of available pieces
536     for (int i = 0; i < FILE_PIECES; i++) {
537       if (peer->pieces_count[i] < min && peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
538           peer_is_not_downloading_piece(peer, i))
539         min = peer->pieces_count[i];
540     }
541     xbt_assert(min != SHRT_MAX || (is_interested_and_free(peer, remote_peer) == 0));
542     // compute the number of rarest pieces
543     for (int i = 0; i < FILE_PIECES; i++) {
544       if (peer->pieces_count[i] == min && peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) &&
545           peer_is_not_downloading_piece(peer, i))
546         nb_min_pieces++;
547     }
548     xbt_assert(nb_min_pieces != 0 || (is_interested_and_free(peer, remote_peer) == 0));
549     // get a random rarest piece
550     int random_rarest_index = 0;
551     if (nb_min_pieces > 0) {
552       random_rarest_index = rand() % nb_min_pieces;
553     }
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         if (random_rarest_index == current_index) {
558           piece = i;
559           break;
560         }
561         current_index++;
562       }
563     }
564     xbt_assert(piece != -1 || (is_interested_and_free(peer, remote_peer) == 0));
565     return piece;
566   }
567 }
568
569 /** @brief Update the list of current choked and unchoked peers, using the choke algorithm
570  *  @param peer the current peer
571  */
572 void update_choked_peers(peer_t peer)
573 {
574   if (nb_interested_peers(peer) == 0)
575     return;
576   XBT_DEBUG("(%d) update_choked peers %u active peers", peer->id, xbt_dict_size(peer->active_peers));
577   // update the current round
578   peer->round = (peer->round + 1) % 3;
579   char* key;
580   char* choked_key         = NULL;
581   connection_t chosen_peer = NULL;
582   connection_t choked_peer = NULL;
583   // remove a peer from the list
584   xbt_dict_cursor_t cursor = NULL;
585   xbt_dict_cursor_first(peer->active_peers, &cursor);
586   if (!xbt_dict_is_empty(peer->active_peers)) {
587     choked_key  = xbt_dict_cursor_get_key(cursor);
588     choked_peer = xbt_dict_cursor_get_data(cursor);
589   }
590   xbt_dict_cursor_free(&cursor);
591
592   /**If we are currently seeding, we unchoke the peer which has been unchoked the last time.*/
593   if (has_finished(peer->bitfield)) {
594     connection_t connection;
595     double unchoke_time = MSG_get_clock() + 1;
596
597     xbt_dict_foreach (peer->peers, cursor, key, connection) {
598       if (connection->last_unchoke < unchoke_time && (connection->interested != 0) &&
599           (connection->choked_upload != 0)) {
600         unchoke_time = connection->last_unchoke;
601         chosen_peer  = connection;
602       }
603     }
604   } else {
605     // Random optimistic unchoking
606     if (peer->round == 0) {
607       int j = 0;
608       do {
609         // We choose a random peer to unchoke.
610         int id_chosen = 0;
611         if (xbt_dict_length(peer->peers) > 0) {
612           id_chosen = rand() % xbt_dict_length(peer->peers);
613         }
614         int i         = 0;
615         connection_t connection;
616         xbt_dict_foreach (peer->peers, cursor, key, connection) {
617           if (i == id_chosen) {
618             chosen_peer = connection;
619             break;
620           }
621           i++;
622         }
623         xbt_dict_cursor_free(&cursor);
624         xbt_assert(chosen_peer != NULL, "A peer should have been selected at this point");
625         if ((chosen_peer->interested == 0) || (chosen_peer->choked_upload == 0))
626           chosen_peer = NULL;
627         else
628           XBT_DEBUG("Nothing to do, keep going");
629         j++;
630       } while (chosen_peer == NULL && j < MAXIMUM_PEERS);
631     } else {
632       // Use the "fastest download" policy.
633       connection_t connection;
634       double fastest_speed = 0.0;
635       xbt_dict_foreach (peer->peers, cursor, key, connection) {
636         if (connection->peer_speed > fastest_speed && (connection->choked_upload != 0) &&
637             (connection->interested != 0)) {
638           chosen_peer   = connection;
639           fastest_speed = connection->peer_speed;
640         }
641       }
642     }
643   }
644
645   if (chosen_peer != NULL)
646     XBT_DEBUG("(%d) update_choked peers unchoked (%d) ; int (%d) ; choked (%d) ", peer->id, chosen_peer->id,
647               chosen_peer->interested, chosen_peer->choked_upload);
648
649   if (choked_peer != chosen_peer) {
650     if (choked_peer != NULL) {
651       xbt_assert((!choked_peer->choked_upload), "Tries to choked a choked peer");
652       choked_peer->choked_upload = 1;
653       xbt_assert((*((int*)choked_key) == choked_peer->id));
654       update_active_peers_set(peer, choked_peer);
655       XBT_DEBUG("(%d) Sending a CHOKE to %d", peer->id, choked_peer->id);
656       send_choked(peer, choked_peer->mailbox);
657     }
658     if (chosen_peer != NULL) {
659       xbt_assert((chosen_peer->choked_upload), "Tries to unchoked an unchoked peer");
660       chosen_peer->choked_upload = 0;
661       xbt_dict_set_ext(peer->active_peers, (char*)&chosen_peer->id, sizeof(int), chosen_peer, NULL);
662       chosen_peer->last_unchoke = MSG_get_clock();
663       XBT_DEBUG("(%d) Sending a UNCHOKE to %d", peer->id, chosen_peer->id);
664       update_active_peers_set(peer, chosen_peer);
665       send_unchoked(peer, chosen_peer->mailbox);
666     }
667   }
668 }
669
670 /** @brief Update "interested" state of peers: send "not interested" to peers that don't have any more pieces we want.
671  *  @param peer our peer data
672  */
673 void update_interested_after_receive(peer_t peer)
674 {
675   char* key;
676   xbt_dict_cursor_t cursor;
677   connection_t connection;
678   xbt_dict_foreach (peer->peers, cursor, key, connection) {
679     if (connection->am_interested != 0) {
680       int interested = 0;
681       // Check if the peer still has a piece we want.
682       for (int i = 0; i < FILE_PIECES; i++) {
683         if (peer_has_not_piece(peer, i) && connection_has_piece(connection, i)) {
684           interested = 1;
685           break;
686         }
687       }
688       if (!interested) { // no more piece to download from connection
689         connection->am_interested = 0;
690         send_notinterested(peer, connection->mailbox);
691       }
692     }
693   }
694 }
695
696 void update_bitfield_blocks(peer_t peer, int index, int block_index, int block_length)
697 {
698   xbt_assert((index >= 0 && index <= FILE_PIECES), "Wrong piece.");
699   xbt_assert((block_index >= 0 && block_index <= PIECES_BLOCKS), "Wrong block : %d.", block_index);
700   for (int i = block_index; i < (block_index + block_length); i++) {
701     peer->bitfield_blocks |= (1ULL << (unsigned int)(index * PIECES_BLOCKS + i));
702   }
703 }
704
705 /** Returns if a peer has completed the download of a piece */
706 int piece_complete(peer_t peer, int index)
707 {
708   for (int i = 0; i < PIECES_BLOCKS; i++) {
709     if (!(peer->bitfield_blocks & 1ULL << (index * PIECES_BLOCKS + i))) {
710       return 0;
711     }
712   }
713   return 1;
714 }
715
716 /** Returns the first block that a peer doesn't have in a piece. If the peer has all blocks of the piece, returns -1. */
717 int get_first_block(peer_t peer, int piece)
718 {
719   for (int i = 0; i < PIECES_BLOCKS; i++) {
720     if (!(peer->bitfield_blocks & 1ULL << (piece * PIECES_BLOCKS + i))) {
721       return i;
722     }
723   }
724   return -1;
725 }
726
727 /** Indicates if the remote peer has a piece not stored by the local peer */
728 int is_interested(peer_t peer, connection_t remote_peer)
729 {
730   return remote_peer->bitfield & (peer->bitfield ^ ((1 << FILE_PIECES) - 1));
731 }
732
733 /** Indicates if the remote peer has a piece not stored by the local peer nor requested by the local peer */
734 int is_interested_and_free(peer_t peer, connection_t remote_peer)
735 {
736   for (int i = 0; i < FILE_PIECES; i++) {
737     if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) && peer_is_not_downloading_piece(peer, i)) {
738       return 1;
739     }
740   }
741   return 0;
742 }
743
744 /** Returns a piece that is partially downloaded and stored by the remote peer if any -1 otherwise. */
745 int partially_downloaded_piece(peer_t peer, connection_t remote_peer)
746 {
747   for (int i = 0; i < FILE_PIECES; i++) {
748     if (peer_has_not_piece(peer, i) && connection_has_piece(remote_peer, i) && peer_is_not_downloading_piece(peer, i) &&
749         get_first_block(peer, i) > 0)
750       return i;
751   }
752   return -1;
753 }
754
755 /** @brief Send request messages to a peer that have unchoked us
756  *  @param peer peer
757  *  @param remote_peer peer data to the peer we want to send the request
758  */
759 void send_request_to_peer(peer_t peer, connection_t remote_peer, int piece)
760 {
761   remote_peer->current_piece = piece;
762   xbt_assert(connection_has_piece(remote_peer, piece));
763   int block_index = get_first_block(peer, piece);
764   if (block_index != -1) {
765     int block_length = MIN(BLOCKS_REQUESTED, PIECES_BLOCKS - block_index);
766     send_request(peer, remote_peer->mailbox, piece, block_index, block_length);
767   }
768 }
769
770 /***********************************************************
771  *
772  *  Low level message functions
773  *
774  ***********************************************************/
775
776 /** @brief Send a "interested" message to a peer
777  *  @param peer peer data
778  *  @param mailbox destination mailbox
779  */
780 void send_interested(peer_t peer, const char* mailbox)
781 {
782   msg_task_t task = task_message_new(MESSAGE_INTERESTED, peer->hostname, peer->mailbox, peer->id,
783                                      task_message_size(MESSAGE_INTERESTED));
784   MSG_task_dsend(task, mailbox, task_message_free);
785   XBT_DEBUG("Sending INTERESTED to %s", mailbox);
786 }
787
788 /** @brief Send a "not interested" message to a peer
789  *  @param peer peer data
790  *  @param mailbox destination mailbox
791  */
792 void send_notinterested(peer_t peer, const char* mailbox)
793 {
794   msg_task_t task = task_message_new(MESSAGE_NOTINTERESTED, peer->hostname, peer->mailbox, peer->id,
795                                      task_message_size(MESSAGE_NOTINTERESTED));
796   MSG_task_dsend(task, mailbox, task_message_free);
797   XBT_DEBUG("Sending NOTINTERESTED to %s", mailbox);
798 }
799
800 /** @brief Send a handshake message to all the peers the peer has.
801  *  @param peer peer data
802  */
803 void send_handshake_all(peer_t peer)
804 {
805   connection_t remote_peer;
806   xbt_dict_cursor_t cursor = NULL;
807   char* key;
808   xbt_dict_foreach (peer->peers, cursor, key, remote_peer) {
809     msg_task_t task = task_message_new(MESSAGE_HANDSHAKE, peer->hostname, peer->mailbox, peer->id,
810                                        task_message_size(MESSAGE_HANDSHAKE));
811     MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
812     XBT_DEBUG("Sending a HANDSHAKE to %s", remote_peer->mailbox);
813   }
814 }
815
816 /** @brief Send a "handshake" message to an user
817  *  @param peer peer data
818  *  @param mailbox mailbox where to we send the message
819  */
820 void send_handshake(peer_t peer, const char* mailbox)
821 {
822   XBT_DEBUG("Sending a HANDSHAKE to %s", mailbox);
823   msg_task_t task = task_message_new(MESSAGE_HANDSHAKE, peer->hostname, peer->mailbox, peer->id,
824                                      task_message_size(MESSAGE_HANDSHAKE));
825   MSG_task_dsend(task, mailbox, task_message_free);
826 }
827
828 /** Send a "choked" message to a peer. */
829 void send_choked(peer_t peer, const char* mailbox)
830 {
831   XBT_DEBUG("Sending a CHOKE to %s", mailbox);
832   msg_task_t task =
833       task_message_new(MESSAGE_CHOKE, peer->hostname, peer->mailbox, peer->id, task_message_size(MESSAGE_CHOKE));
834   MSG_task_dsend(task, mailbox, task_message_free);
835 }
836
837 /** Send a "unchoked" message to a peer */
838 void send_unchoked(peer_t peer, const char* mailbox)
839 {
840   XBT_DEBUG("Sending a UNCHOKE to %s", mailbox);
841   msg_task_t task =
842       task_message_new(MESSAGE_UNCHOKE, peer->hostname, peer->mailbox, peer->id, task_message_size(MESSAGE_UNCHOKE));
843   MSG_task_dsend(task, mailbox, task_message_free);
844 }
845
846 /** Send a "HAVE" message to all peers we are connected to */
847 void send_have(peer_t peer, int piece)
848 {
849   XBT_DEBUG("Sending HAVE message to all my peers");
850   connection_t remote_peer;
851   xbt_dict_cursor_t cursor = NULL;
852   char* key;
853   xbt_dict_foreach (peer->peers, cursor, key, remote_peer) {
854     msg_task_t task = task_message_index_new(MESSAGE_HAVE, peer->hostname, peer->mailbox, peer->id, piece,
855                                              task_message_size(MESSAGE_HAVE));
856     MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
857   }
858 }
859
860 /** @brief Send a bitfield message to all the peers the peer has.
861  *  @param peer peer data
862  */
863 void send_bitfield(peer_t peer, const char* mailbox)
864 {
865   XBT_DEBUG("Sending a BITFIELD to %s", mailbox);
866   msg_task_t task = task_message_bitfield_new(peer->hostname, peer->mailbox, peer->id, peer->bitfield, FILE_PIECES);
867   MSG_task_dsend(task, mailbox, task_message_free);
868 }
869
870 /** Send a "request" message to a pair, containing a request for a piece */
871 void send_request(peer_t peer, const char* mailbox, int piece, int block_index, int block_length)
872 {
873   XBT_DEBUG("Sending a REQUEST to %s for piece %d (%d,%d)", mailbox, piece, block_index, block_length);
874   msg_task_t task = task_message_request_new(peer->hostname, peer->mailbox, peer->id, piece, block_index, block_length);
875   MSG_task_dsend(task, mailbox, task_message_free);
876 }
877
878 /** Send a "piece" message to a pair, containing a piece of the file */
879 void send_piece(peer_t peer, const char* mailbox, int piece, int block_index, int block_length)
880 {
881   XBT_DEBUG("Sending the PIECE %d (%d,%d) to %s", piece, block_index, block_length, mailbox);
882   xbt_assert(piece >= 0, "Tried to send a piece that doesn't exist.");
883   xbt_assert(!peer_has_not_piece(peer, piece), "Tried to send a piece that we doesn't have.");
884   msg_task_t task =
885       task_message_piece_new(peer->hostname, peer->mailbox, peer->id, piece, block_index, block_length, BLOCK_SIZE);
886   MSG_task_dsend(task, mailbox, task_message_free);
887 }