Logo AND Algorithmique Numérique Distribuée

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