1 /* Copyright (c) 2012-2014. The SimGrid Team.
2 * All rights reserved. */
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. */
9 #include "connection.h"
12 #include <xbt/RngStream.h>
15 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_peers, "Messages specific for the peers");
17 //TODO: Let users change this
19 * File transfered data
20 * For the test, default values are :
21 * File size: 10 pieces * 5 blocks/piece * 16384 bytes/block = 819200 bytes
24 #define FILE_PIECES 10
25 #define PIECES_BLOCKS 5
26 #define BLOCK_SIZE 16384
27 #define ENABLE_END_GAME_MODE 1
30 * Number of blocks asked by each request
32 #define BLOCKS_REQUESTED 2
35 static const unsigned long int FILE_SIZE = FILE_PIECES * PIECES_BLOCKS * BLOCK_SIZE;
38 #define SLEEP_DURATION 1
43 int peer(int argc, char *argv[])
47 xbt_assert(argc == 3 || argc == 4, "Wrong number of arguments");
50 peer_init(&peer, atoi(argv[1]), 1);
52 peer_init(&peer, atoi(argv[1]), 0);
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);
69 leech_loop(&peer, deadline);
70 seed_loop(&peer, deadline);
73 XBT_INFO("Couldn't contact the tracker.");
76 XBT_INFO("Here is my current status: %s", peer.bitfield);
77 if (peer.comm_received) {
78 MSG_comm_destroy(peer.comm_received);
86 * Peer main loop when it is leeching.
87 * @param peer peer data
88 * @param deadline time at which the peer has to leave
90 void leech_loop(peer_t peer, double deadline)
92 double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
93 XBT_DEBUG("Start downloading.");
95 * Send a "handshake" message to all the peers it got
96 * (since it couldn't have gotten more than 50 peers)
98 send_handshake_all(peer);
99 XBT_DEBUG("Starting main leech loop");
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);
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);
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;
119 MSG_process_sleep(SLEEP_DURATION);
123 if (peer->pieces == FILE_PIECES)
124 XBT_DEBUG("%d becomes a seeder", peer->id);
129 * Peer main loop when it is seeding
130 * @param peer peer data
131 * @param deadline time when the peer will leave
133 void seed_loop(peer_t peer, double deadline)
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);
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);
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;
156 MSG_process_sleep(SLEEP_DURATION);
163 * Retrieves the peer list from the tracker
164 * @param peer current peer data
166 int get_peers_data(peer_t peer)
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,
182 if (status == MSG_OK) {
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);
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);
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;
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.
217 void peer_init(peer_t peer, int id, int seed)
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());
226 peer->bitfield = xbt_new(char, FILE_PIECES + 1);
227 peer->bitfield_blocks = xbt_new(char, (FILE_PIECES) * (PIECES_BLOCKS) + 1);
229 memset(peer->bitfield, '1', sizeof(char) * (FILE_PIECES + 1));
230 memset(peer->bitfield_blocks, '1',
231 sizeof(char) * FILE_PIECES * (PIECES_BLOCKS));
233 memset(peer->bitfield, '0', sizeof(char) * (FILE_PIECES + 1));
234 memset(peer->bitfield_blocks, '0',
235 sizeof(char) * FILE_PIECES * (PIECES_BLOCKS));
238 peer->bitfield[FILE_PIECES] = '\0';
241 peer->pieces_count = xbt_new0(short, FILE_PIECES);
243 peer->current_pieces = xbt_dynar_new(sizeof(int), NULL);
245 peer->stream = RngStream_CreateStream("");
246 peer->comm_received = NULL;
253 * Destroys a poor peer object.
255 void peer_free(peer_t peer)
258 connection_t connection;
259 xbt_dict_cursor_t cursor;
260 xbt_dict_foreach(peer->peers, cursor, key, connection) {
261 connection_free(connection);
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);
270 RngStream_DeleteStream(&peer->stream);
274 * Returns if a peer has finished downloading the file
275 * @param bitfield peer bitfield
277 int has_finished(char *bitfield)
279 return ((memchr(bitfield, '0', sizeof(char) * FILE_PIECES) == NULL) ? 1 : 0);
282 int nb_interested_peers(peer_t peer)
284 xbt_dict_cursor_t cursor = NULL;
286 connection_t connection;
288 xbt_dict_foreach(peer->peers, cursor, key, connection) {
289 if (connection->interested)
296 void update_active_peers_set(peer_t peer, connection_t remote_peer)
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);
307 xbt_dict_remove_ext(peer->active_peers, (char *) &remote_peer->id,
318 * Handle a received message sent by another peer
319 * @param peer Peer data
320 * @param task task received.
322 void handle_message(peer_t peer, msg_task_t task)
324 message_t message = MSG_task_get_data(task);
325 connection_t remote_peer;
327 xbt_dict_get_or_null_ext(peer->peers, (char *) &message->peer_id,
329 switch (message->type) {
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.
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);
340 //Send our bitfield to the peer
341 send_bitfield(peer, message->mailbox);
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);
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);
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);
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);
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);
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);
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);
411 case MESSAGE_REQUEST:
412 xbt_assert(remote_peer->interested, "WTF !!!");
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);
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);
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';
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
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);
465 XBT_DEBUG("The received CANCEL from %s (%s)",
466 message->mailbox, message->issuer_host_name);
469 //Update the peer speed.
471 connection_add_speed_value(remote_peer,
472 1.0 / (MSG_get_clock() -
473 peer->begin_receive_time));
475 peer->begin_receive_time = MSG_get_clock();
477 task_message_free(task);
481 * Selects the appropriate piece to download and requests it to the remote_peer
483 void request_new_piece_to_peer(peer_t peer, connection_t remote_peer)
485 int piece = select_piece_to_download(peer, remote_peer);
487 xbt_dynar_push_as(peer->current_pieces, int, piece);
488 send_request_to_peer(peer, remote_peer, piece);
493 * remove current_piece from the list of currently downloaded pieces.
495 void remove_current_piece(peer_t peer, connection_t remote_peer,
498 int piece_index = -1, piece;
500 xbt_dynar_foreach(peer->current_pieces, i, piece) {
501 if (piece == current_piece) {
506 if (piece_index != -1)
507 xbt_dynar_remove_at(peer->current_pieces, piece_index, NULL);
508 remote_peer->current_piece = -1;
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
516 void update_pieces_count_from_bitfield(peer_t peer, char *bitfield)
519 for (i = 0; i < FILE_PIECES; i++) {
520 if (bitfield[i] == '1') {
521 peer->pieces_count[i]++;
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
540 int select_piece_to_download(peer_t peer, connection_t remote_peer)
544 piece = partially_downloaded_piece(peer, remote_peer);
545 // strict priority policy
550 if (xbt_dynar_length(peer->current_pieces) >= (FILE_PIECES - peer->pieces)
551 && is_interested(peer, remote_peer)) {
552 if(!ENABLE_END_GAME_MODE)
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++;
563 xbt_assert(nb_interesting_pieces != 0, "WTF !!!");
564 // get a random interesting piece
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) {
576 xbt_assert(piece != -1, "WTF !!!");
579 // Random first policy
580 if (peer->pieces < 4 && is_interested_and_free(peer, remote_peer)) {
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++;
591 xbt_assert(nb_interesting_pieces != 0, "WTF !!!");
592 // get a random interesting piece
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) {
605 xbt_assert(piece != -1, "WTF !!!");
607 } else { // Rarest first policy
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];
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))
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) {
640 xbt_assert(piece != -1
641 || !is_interested_and_free(peer, remote_peer), "WTF !!!");
648 * Update the list of current choked and unchoked peers, using the
650 * @param peer the current peer
652 void update_choked_peers(peer_t peer)
654 if (nb_interested_peers(peer) == 0)
656 // if(xbt_dict_size(peer->active_peers) > 0)
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);
672 xbt_dict_cursor_free(&cursor);
675 * If we are currently seeding, we unchoke the peer which has
676 * been unchoke the least time.
678 if (peer->pieces == FILE_PIECES) {
679 connection_t connection;
680 double unchoke_time = MSG_get_clock() + 1;
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;
690 //Random optimistic unchoking
691 if (peer->round == 0) {
694 //We choose a random peer to unchoke.
695 int id_chosen = RngStream_RandInt(peer->stream, 0,
696 xbt_dict_length(peer->peers) - 1);
698 connection_t connection;
699 xbt_dict_foreach(peer->peers, cursor, key, connection) {
700 if (i == id_chosen) {
701 peer_choosed = connection;
706 xbt_dict_cursor_free(&cursor);
707 if (!peer_choosed->interested || !peer_choosed->choked_upload) {
711 } while (peer_choosed == NULL && j < MAXIMUM_PAIRS);
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;
726 if (peer_choosed != NULL)
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);
732 // if (xbt_dict_size(peer->peers) > 0)
733 // xbt_assert((xbt_dict_size(peer->active_peers) != 0),
734 // "No more active peers !");
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;
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);
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);
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
772 void update_interested_after_receive(peer_t peer)
775 xbt_dict_cursor_t cursor;
776 connection_t connection;
778 xbt_dict_foreach(peer->peers, cursor, key, connection) {
780 if (connection->am_interested) {
781 xbt_assert(connection->bitfield, "Bitfield not received");
782 //Check if the peer still has a piece we want.
784 for (i = 0; i < FILE_PIECES; i++) {
785 if (connection->bitfield[i] == '1' && peer->bitfield[i] == '0') {
790 if (!interested) { //no more piece to download from connection
791 connection->am_interested = 0;
792 send_notinterested(peer, connection->mailbox);
798 void update_bitfield_blocks(peer_t peer, int index, int block_index,
802 xbt_assert((index >= 0 && index <= FILE_PIECES), "Wrong piece.");
803 xbt_assert((block_index >= 0
804 && block_index <= PIECES_BLOCKS), "Wrong block : %d.",
806 for (i = block_index; i < (block_index + block_length); i++) {
807 peer->bitfield_blocks[index * PIECES_BLOCKS + i] = '1';
812 * Returns if a peer has completed the download of a piece
814 int piece_complete(peer_t peer, int index)
817 for (i = 0; i < PIECES_BLOCKS; i++) {
818 if (peer->bitfield_blocks[index * PIECES_BLOCKS + i] == '0') {
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.
829 int get_first_block(peer_t peer, int piece)
832 for (i = 0; i < PIECES_BLOCKS; i++) {
833 if (peer->bitfield_blocks[piece * PIECES_BLOCKS + i] == '0') {
841 * Indicates if the remote peer has a piece not stored by the local peer
843 int is_interested(peer_t peer, connection_t remote_peer)
845 xbt_assert(remote_peer->bitfield, "Bitfield not received");
847 for (i = 0; i < FILE_PIECES; i++) {
848 if (remote_peer->bitfield[i] == '1' && peer->bitfield[i] == '0') {
856 * Indicates if the remote peer has a piece not stored by the local peer nor requested by the local peer
858 int is_interested_and_free(peer_t peer, connection_t remote_peer)
860 xbt_assert(remote_peer->bitfield, "Bitfield not received");
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)) {
873 * Returns a piece that is partially downloaded and stored by the remote peer if any
876 int partially_downloaded_piece(peer_t peer, connection_t remote_peer)
878 xbt_assert(remote_peer->bitfield, "Bitfield not received");
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)
892 * Send request messages to a peer that have unchoked us
894 * @param remote_peer peer data to the peer we want to send the request
896 void send_request_to_peer(peer_t peer, connection_t remote_peer, int piece)
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);
912 * Indicates if a piece is currently being downloaded by the peer.
914 int in_current_pieces(peer_t peer, int piece)
918 xbt_dynar_foreach(peer->current_pieces, i, peer_piece) {
919 if (peer_piece == piece) {
929 /***********************************************************
931 * Low level message functions
933 ***********************************************************/
938 * Send a "interested" message to a peer
939 * @param peer peer data
940 * @param mailbox destination mailbox
942 void send_interested(peer_t peer, const char *mailbox)
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);
953 * Send a "not interested" message to a peer
954 * @param peer peer data
955 * @param mailbox destination mailbox
957 void send_notinterested(peer_t peer, const char *mailbox)
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);
968 * Send a handshake message to all the peers the peer has.
969 * @param peer peer data
971 void send_handshake_all(peer_t peer)
973 connection_t remote_peer;
974 xbt_dict_cursor_t cursor = NULL;
976 xbt_dict_foreach(peer->peers, cursor, key, remote_peer) {
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);
986 * Send a "handshake" message to an user
987 * @param peer peer data
988 * @param mailbox mailbox where to we send the message
990 void send_handshake(peer_t peer, const char *mailbox)
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);
1000 * Send a "choked" message to a peer.
1002 void send_choked(peer_t peer, const char *mailbox)
1004 XBT_DEBUG("Sending a CHOKE to %s", mailbox);
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);
1012 * Send a "unchoked" message to a peer
1014 void send_unchoked(peer_t peer, const char *mailbox)
1016 XBT_DEBUG("Sending a UNCHOKE to %s", mailbox);
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);
1024 * Send a "HAVE" message to all peers we are connected to
1026 void send_have(peer_t peer, int piece)
1028 XBT_DEBUG("Sending HAVE message to all my peers");
1029 connection_t remote_peer;
1030 xbt_dict_cursor_t cursor = NULL;
1032 xbt_dict_foreach(peer->peers, cursor, key, remote_peer) {
1034 task_message_index_new(MESSAGE_HAVE, peer->hostname, peer->mailbox,
1036 task_message_size(MESSAGE_HAVE));
1037 MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
1042 * Send a bitfield message to all the peers the peer has.
1043 * @param peer peer data
1045 void send_bitfield(peer_t peer, const char *mailbox)
1047 XBT_DEBUG("Sending a BITFIELD to %s", mailbox);
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);
1055 * Send a "request" message to a pair, containing a request for a piece
1057 void send_request(peer_t peer, const char *mailbox, int piece,
1058 int block_index, int block_length)
1060 XBT_DEBUG("Sending a REQUEST to %s for piece %d (%d,%d)", mailbox, piece,
1061 block_index, block_length);
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);
1069 * Send a "piece" message to a pair, containing a piece of the file
1071 void send_piece(peer_t peer, const char *mailbox, int piece,
1072 int block_index, int block_length)
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.");
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);