Logo AND Algorithmique Numérique Distribuée

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