Logo AND Algorithmique Numérique Distribuée

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