Logo AND Algorithmique Numérique Distribuée

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