Logo AND Algorithmique Numérique Distribuée

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