1 /* Copyright (c) 2012. 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. */
8 #include "connection.h"
11 #include <xbt/RngStream.h>
14 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_peers, "Messages specific for the peers");
16 //TODO: Let users change this
18 * File transfered data
19 * For the test, default values are :
20 * File size: 10 pieces * 5 blocks/piece * 16384 bytes/block = 819200 bytes
23 #define FILE_PIECES 10
24 #define PIECES_BLOCKS 5
25 #define BLOCK_SIZE 16384
28 * Number of blocks asked by each request
30 #define BLOCKS_REQUESTED 2
33 static const int FILE_SIZE = FILE_PIECES * PIECES_BLOCKS * BLOCK_SIZE;
35 void request_new_piece_to_peer(peer_t peer, connection_t remote_peer);
36 void send_request_to_peer(peer_t peer, connection_t remote_peer, int piece);
37 void remove_current_piece(peer_t peer, connection_t remote_peer,
44 int peer(int argc, char *argv[])
48 xbt_assert(argc == 3 || argc == 4, "Wrong number of arguments");
51 peer_init(&peer, atoi(argv[1]), 1);
53 peer_init(&peer, atoi(argv[1]), 0);
56 double deadline = atof(argv[2]);
57 xbt_assert(deadline > 0, "Wrong deadline supplied");
58 XBT_INFO("Hi, I'm joining the network with id %d", peer.id);
59 //Getting peer data from the tracker.
60 if (get_peers_data(&peer)) {
61 XBT_DEBUG("Got %d peers from the tracker", xbt_dict_length(peer.peers));
62 XBT_DEBUG("Here is my current status: %s", peer.bitfield);
63 peer.begin_receive_time = MSG_get_clock();
64 MSG_mailbox_set_async(peer.mailbox);
65 if (has_finished(peer.bitfield)) {
66 peer.pieces = FILE_PIECES;
67 send_handshake_all(&peer);
68 seed_loop(&peer, deadline);
70 leech_loop(&peer, deadline);
71 // XBT_INFO("%d becomes a seeder", peer.id);
72 seed_loop(&peer, deadline);
75 XBT_INFO("Couldn't contact the tracker.");
78 XBT_INFO("Here is my current status: %s", peer.bitfield);
79 if (peer.comm_received) {
80 MSG_comm_destroy(peer.comm_received);
88 * Peer main loop when it is leeching.
89 * @param peer peer data
90 * @param deadline time at which the peer has to leave
92 void leech_loop(peer_t peer, double deadline)
94 double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
95 XBT_DEBUG("Start downloading.");
97 * Send a "handshake" message to all the peers it got
98 * (since it couldn't have gotten more than 50 peers)
100 send_handshake_all(peer);
101 //Wait for at least one "bitfield" message.
102 // wait_for_pieces(peer, deadline);
103 XBT_DEBUG("Starting main leech loop");
105 while (MSG_get_clock() < deadline && peer->pieces < FILE_PIECES) {
106 if (peer->comm_received == NULL) {
107 // XBT_INFO("irecv");
108 peer->task_received = NULL;
109 peer->comm_received =
110 MSG_task_irecv(&peer->task_received, peer->mailbox);
112 if (MSG_comm_test(peer->comm_received)) {
113 // XBT_INFO("comm_test OK");
114 msg_error_t status = MSG_comm_get_status(peer->comm_received);
115 MSG_comm_destroy(peer->comm_received);
116 peer->comm_received = NULL;
117 if (status == MSG_OK) {
118 handle_message(peer, peer->task_received);
121 handle_pending_sends(peer);
122 //We don't execute the choke algorithm if we don't already have a piece
123 if (MSG_get_clock() >= next_choked_update && peer->pieces > 0) {
124 update_choked_peers(peer);
125 next_choked_update += UPDATE_CHOKED_INTERVAL;
127 MSG_process_sleep(1);
134 * Peer main loop when it is seeding
135 * @param peer peer data
136 * @param deadline time when the peer will leave
138 void seed_loop(peer_t peer, double deadline)
140 double next_choked_update = MSG_get_clock() + UPDATE_CHOKED_INTERVAL;
141 XBT_DEBUG("Start seeding.");
142 //start the main seed loop
143 while (MSG_get_clock() < deadline) {
144 if (peer->comm_received == NULL) {
145 peer->task_received = NULL;
146 peer->comm_received =
147 MSG_task_irecv(&peer->task_received, peer->mailbox);
149 if (MSG_comm_test(peer->comm_received)) {
150 msg_error_t status = MSG_comm_get_status(peer->comm_received);
151 MSG_comm_destroy(peer->comm_received);
152 peer->comm_received = NULL;
153 if (status == MSG_OK) {
154 handle_message(peer, peer->task_received);
157 if (MSG_get_clock() >= next_choked_update) {
158 update_choked_peers(peer);
159 //TODO: Change the choked peer algorithm when seeding.
160 next_choked_update += UPDATE_CHOKED_INTERVAL;
162 MSG_process_sleep(1);
169 * Retrieves the peer list from the tracker
170 * @param peer current peer data
172 int get_peers_data(peer_t peer)
174 int success = 0, send_success = 0;
175 double timeout = MSG_get_clock() + GET_PEERS_TIMEOUT;
176 //Build the task to send to the tracker
177 tracker_task_data_t data =
178 tracker_task_data_new(MSG_host_get_name(MSG_host_self()),
179 peer->mailbox_tracker, peer->id, 0, 0, FILE_SIZE);
180 //Build the task to send.
181 msg_task_t task_send = MSG_task_create(NULL, 0, TRACKER_COMM_SIZE, data);
182 msg_task_t task_received = NULL;
183 msg_comm_t comm_received;
184 while (!send_success && MSG_get_clock() < timeout) {
185 XBT_DEBUG("Sending a peer request to the tracker.");
187 MSG_task_send_with_timeout(task_send, TRACKER_MAILBOX,
189 if (status == MSG_OK) {
193 while (!success && MSG_get_clock() < timeout) {
194 comm_received = MSG_task_irecv(&task_received, peer->mailbox_tracker);
195 msg_error_t status = MSG_comm_wait(comm_received, GET_PEERS_TIMEOUT);
196 if (status == MSG_OK) {
197 tracker_task_data_t data = MSG_task_get_data(task_received);
200 //Add the peers the tracker gave us to our peer list.
201 xbt_dynar_foreach(data->peers, i, peer_id) {
202 if (peer_id != peer->id)
203 xbt_dict_set_ext(peer->peers, (char *) &peer_id, sizeof(int),
204 connection_new(peer_id), NULL);
207 //free the communication and the task
208 MSG_comm_destroy(comm_received);
209 tracker_task_data_free(data);
210 MSG_task_destroy(task_received);
211 comm_received = NULL;
219 * Initialize the peer data.
220 * @param peer peer data
221 * @param id id of the peer to take in the network
222 * @param seed indicates if the peer is a seed.
224 void peer_init(peer_t peer, int id, int seed)
227 sprintf(peer->mailbox, "%d", id);
228 sprintf(peer->mailbox_tracker, "tracker_%d", id);
229 peer->peers = xbt_dict_new();
230 peer->active_peers = xbt_dict_new();
231 peer->hostname = MSG_host_get_name(MSG_host_self());
233 peer->bitfield = xbt_new(char, FILE_PIECES + 1);
234 peer->bitfield_blocks = xbt_new(char, (FILE_PIECES) * (PIECES_BLOCKS) + 1);
236 memset(peer->bitfield, '1', sizeof(char) * (FILE_PIECES + 1));
237 memset(peer->bitfield_blocks, '1',
238 sizeof(char) * FILE_PIECES * (PIECES_BLOCKS));
240 memset(peer->bitfield, '0', sizeof(char) * (FILE_PIECES + 1));
241 memset(peer->bitfield_blocks, '0',
242 sizeof(char) * FILE_PIECES * (PIECES_BLOCKS));
245 peer->bitfield[FILE_PIECES] = '\0';
248 peer->pieces_count = xbt_new0(short, FILE_PIECES);
250 peer->current_pieces = xbt_dynar_new(sizeof(int), NULL);
252 peer->stream = RngStream_CreateStream("");
253 peer->comm_received = NULL;
257 peer->pending_sends = xbt_dynar_new(sizeof(msg_comm_t), NULL);
261 * Destroys a poor peer object.
263 void peer_free(peer_t peer)
266 connection_t connection;
267 xbt_dict_cursor_t cursor;
268 xbt_dict_foreach(peer->peers, cursor, key, connection) {
269 connection_free(connection);
271 xbt_dict_free(&peer->peers);
272 xbt_dict_free(&peer->active_peers);
273 xbt_dynar_free(&peer->current_pieces);
274 xbt_dynar_free(&peer->pending_sends);
275 xbt_free(peer->pieces_count);
276 xbt_free(peer->bitfield);
277 xbt_free(peer->bitfield_blocks);
279 RngStream_DeleteStream(&peer->stream);
283 * Returns if a peer has finished downloading the file
284 * @param bitfield peer bitfield
286 int has_finished(char *bitfield)
288 return ((memchr(bitfield, '0', sizeof(char) * FILE_PIECES) ==
292 int nb_interested_peers(peer_t peer)
294 xbt_dict_cursor_t cursor = NULL;
296 connection_t connection;
298 xbt_dict_foreach(peer->peers, cursor, key, connection) {
299 if (connection->interested)
306 * Handle pending sends and remove those which are done
307 * @param peer Peer data
309 void handle_pending_sends(peer_t peer)
313 while ((index = MSG_comm_testany(peer->pending_sends)) != -1) {
314 msg_comm_t comm_send =
315 xbt_dynar_get_as(peer->pending_sends, index, msg_comm_t);
316 int status = MSG_comm_get_status(comm_send);
317 xbt_dynar_remove_at(peer->pending_sends, index, &comm_send);
319 ("Communication %p is finished with status %d, dynar size is now %lu",
320 comm_send, status, xbt_dynar_length(peer->pending_sends));
322 msg_task_t task = MSG_comm_get_task(comm_send);
323 MSG_comm_destroy(comm_send);
325 if (status != MSG_OK) {
326 task_message_free(task);
331 void update_active_peers_set(peer_t peer, connection_t remote_peer)
334 if (remote_peer->interested && !remote_peer->choked_upload) {
335 //add in the active peers set
336 xbt_dict_set_ext(peer->active_peers, (char *) &remote_peer->id,
337 sizeof(int), remote_peer, NULL);
342 xbt_dict_remove_ext(peer->active_peers, (char *) &remote_peer->id,
353 * Handle a received message sent by another peer
354 * @param peer Peer data
355 * @param task task received.
357 void handle_message(peer_t peer, msg_task_t task)
359 message_t message = MSG_task_get_data(task);
360 connection_t remote_peer;
362 xbt_dict_get_or_null_ext(peer->peers, (char *) &message->peer_id,
364 switch (message->type) {
366 case MESSAGE_HANDSHAKE:
367 XBT_DEBUG("Received a HANDSHAKE from %s (%s)", message->mailbox,
368 message->issuer_host_name);
369 //Check if the peer is in our connection list.
371 xbt_dict_set_ext(peer->peers, (char *) &message->peer_id, sizeof(int),
372 connection_new(message->peer_id), NULL);
373 send_handshake(peer, message->mailbox);
375 //Send our bitfield to the peer
376 send_bitfield(peer, message->mailbox);
378 case MESSAGE_BITFIELD:
379 XBT_DEBUG("Recieved a BITFIELD message from %s (%s)", message->mailbox,
380 message->issuer_host_name);
381 //Update the pieces list
382 update_pieces_count_from_bitfield(peer, message->bitfield);
384 remote_peer->bitfield = xbt_strdup(message->bitfield);
385 xbt_assert(!remote_peer->am_interested,
386 "Should not be interested at first");
387 if (is_interested(peer, remote_peer)) {
388 remote_peer->am_interested = 1;
389 send_interested(peer, message->mailbox);
392 case MESSAGE_INTERESTED:
393 XBT_DEBUG("Recieved an INTERESTED message from %s (%s)", message->mailbox,
394 message->issuer_host_name);
395 xbt_assert((remote_peer != NULL),
396 "A non-in-our-list peer has sent us a message. WTH ?");
397 //Update the interested state of the peer.
398 remote_peer->interested = 1;
399 update_active_peers_set(peer, remote_peer);
401 case MESSAGE_NOTINTERESTED:
402 XBT_DEBUG("Received a NOTINTERESTED message from %s (%s)",
403 message->mailbox, message->issuer_host_name);
404 xbt_assert((remote_peer != NULL),
405 "A non-in-our-list peer has sent us a message. WTH ?");
406 remote_peer->interested = 0;
407 update_active_peers_set(peer, remote_peer);
409 case MESSAGE_UNCHOKE:
410 xbt_assert((remote_peer != NULL),
411 "A non-in-our-list peer has sent us a message. WTH ?");
412 XBT_DEBUG("Received a UNCHOKE message from %s (%s)", message->mailbox,
413 message->issuer_host_name);
414 remote_peer->choked_download = 0;
415 //Send requests to the peer, since it has unchoked us
416 if (remote_peer->am_interested)
417 request_new_piece_to_peer(peer, remote_peer);
420 xbt_assert((remote_peer != NULL),
421 "A non-in-our-list peer has sent us a message. WTH ?");
422 XBT_DEBUG("Received a CHOKE message from %s (%s)", message->mailbox,
423 message->issuer_host_name);
424 remote_peer->choked_download = 1;
425 remove_current_piece(peer, remote_peer, remote_peer->current_piece);
428 XBT_DEBUG("Received a HAVE message from %s (%s) of piece %d",
429 message->mailbox, message->issuer_host_name, message->index);
430 xbt_assert(remote_peer->bitfield, "bitfield not received");
431 xbt_assert((message->index >= 0
432 && message->index < FILE_PIECES),
433 "Wrong HAVE message received");
434 remote_peer->bitfield[message->index] = '1';
435 peer->pieces_count[message->index]++;
436 //If the piece is in our pieces, we tell the peer that we are interested.
437 if (!remote_peer->am_interested && peer->bitfield[message->index] == '0') {
438 remote_peer->am_interested = 1;
439 send_interested(peer, message->mailbox);
440 if (!remote_peer->choked_download)
441 request_new_piece_to_peer(peer, remote_peer);
444 case MESSAGE_REQUEST:
445 xbt_assert((message->index >= 0
446 && message->index < FILE_PIECES), "Wrong request received");
447 if (!remote_peer->choked_upload) {
448 XBT_DEBUG("Received a REQUEST from %s (%s) for %d (%d,%d)",
449 message->mailbox, message->issuer_host_name, message->peer_id,
450 message->block_index,
451 message->block_index + message->block_length);
452 if (peer->bitfield[message->index] == '1') {
453 send_piece(peer, message->mailbox, message->index, 0,
454 message->block_index, message->block_length);
457 XBT_DEBUG("Received a REQUEST from %s (%s) for %d but he is choked.",
458 message->mailbox, message->issuer_host_name,
463 xbt_assert((message->index >= 0
464 && message->index < FILE_PIECES), "Wrong piece received");
465 //TODO: Execute à computation.
466 if (message->stalled) {
467 XBT_DEBUG("The received piece %d from %s (%s) is STALLED",
468 message->index, message->mailbox, message->issuer_host_name);
470 XBT_DEBUG("Received piece %d (%d,%d) from %s (%s)", message->index,
471 message->block_index,
472 message->block_index + message->block_length,
473 message->mailbox, message->issuer_host_name);
474 if (peer->bitfield[message->index] == '0') {
475 update_bitfield_blocks(peer, message->index, message->block_index,
476 message->block_length);
477 if (piece_complete(peer, message->index)) {
478 //Removing the piece from our piece list
479 remove_current_piece(peer, remote_peer, message->index);
480 //Setting the fact that we have the piece
481 peer->bitfield[message->index] = '1';
483 XBT_DEBUG("My status is now %s", peer->bitfield);
484 //Sending the information to all the peers we are connected to
485 send_have(peer, message->index);
486 //sending UNINTERSTED to peers that doesn't have what we want.
487 update_interested_after_receive(peer);
488 } else { // piece not completed
489 send_request_to_peer(peer, remote_peer, message->index); // ask for the next block
492 XBT_DEBUG("However, we already have it");
493 request_new_piece_to_peer(peer, remote_peer);
498 XBT_DEBUG("The received CANCEL from %s (%s)",
499 message->mailbox, message->issuer_host_name);
502 //Update the peer speed.
504 connection_add_speed_value(remote_peer,
505 1.0 / (MSG_get_clock() -
506 peer->begin_receive_time));
508 peer->begin_receive_time = MSG_get_clock();
510 task_message_free(task);
513 void request_new_piece_to_peer(peer_t peer, connection_t remote_peer)
515 int piece = select_piece_to_download(peer, remote_peer);
517 xbt_dynar_push_as(peer->current_pieces, int, piece);
518 send_request_to_peer(peer, remote_peer, piece);
522 void remove_current_piece(peer_t peer, connection_t remote_peer,
525 int piece_index = -1, piece, i;
526 xbt_dynar_foreach(peer->current_pieces, i, piece) {
527 if (piece == current_piece) {
532 if (piece_index != -1)
533 xbt_dynar_remove_at(peer->current_pieces, piece_index, NULL);
534 remote_peer->current_piece = -1;
538 * Updates the list of who has a piece from a bitfield
539 * @param peer peer we want to update the list
540 * @param bitfield bitfield
542 void update_pieces_count_from_bitfield(peer_t peer, char *bitfield)
545 for (i = 0; i < FILE_PIECES; i++) {
546 if (bitfield[i] == '1') {
547 peer->pieces_count[i]++;
555 * Return the piece to be downloaded
556 * There are two cases (as described in "Bittorrent Architecture Protocol", Ryan Toole :
557 * If the peer has strictly less than 4 pieces, he chooses a piece at random.
558 * If the peer has more than pieces, he downloads the pieces that are the less
560 * Note: "end game mode" policy is not implemented
561 * @param peer: local peer
562 * @param remote_peer: information about the connection
563 * @return the piece to download if possible. -1 otherwise
565 int select_piece_to_download(peer_t peer, connection_t remote_peer)
567 // TODO : add strict priority policy
569 if (xbt_dynar_length(peer->current_pieces) >= (FILE_PIECES - peer->pieces)) { // end game mode
572 if (peer->pieces < 4 && is_interested_and_free(peer, remote_peer)) { // Random first policy
575 piece = RngStream_RandInt(peer->stream, 0, FILE_PIECES - 1);;
577 (peer->bitfield[piece] == '0'
578 && remote_peer->bitfield[piece] == '1'
579 && !in_current_pieces(peer, piece)));
581 } else { // Rarest first policy
582 int i, min_piece = -1;
583 short min = SHRT_MAX;
584 for (i = 0; i < FILE_PIECES; i++) {
585 if (peer->pieces_count[i] < min && peer->bitfield[i] == '0'
586 && remote_peer->bitfield[i] == '1' && !in_current_pieces(peer, i)) {
587 min = peer->pieces_count[i];
591 // TODO: add randomness when selecting a rarest piece
598 * Update the list of current choked and unchoked peers, using the
600 * @param peer the current peer
602 void update_choked_peers(peer_t peer)
604 if (nb_interested_peers(peer) == 0)
606 // if(xbt_dict_size(peer->active_peers) > 0)
608 XBT_DEBUG("(%d) update_choked peers %d active peers", peer->id,
609 xbt_dict_size(peer->active_peers));
610 //update the current round
611 peer->round = (peer->round + 1) % 3;
612 char *key, *key_choked;
613 connection_t peer_choosed = NULL;
614 connection_t peer_choked = NULL;
615 //remove a peer from the list
616 xbt_dict_cursor_t cursor = NULL;
617 xbt_dict_cursor_first(peer->active_peers, &cursor);
618 if (xbt_dict_length(peer->active_peers) > 0) {
619 key_choked = xbt_dict_cursor_get_key(cursor);
620 peer_choked = xbt_dict_cursor_get_data(cursor);
622 xbt_dict_cursor_free(&cursor);
625 * If we are currently seeding, we unchoke the peer which has
626 * been unchoke the least time.
628 if (peer->pieces == FILE_PIECES) {
629 connection_t connection;
630 double unchoke_time = MSG_get_clock() + 1;
632 xbt_dict_foreach(peer->peers, cursor, key, connection) {
633 if (connection->last_unchoke < unchoke_time && connection->interested
634 && connection->choked_upload) {
635 unchoke_time = connection->last_unchoke;
636 peer_choosed = connection;
640 //Random optimistic unchoking
641 if (peer->round == 0) {
644 //We choose a random peer to unchoke.
645 int id_chosen = RngStream_RandInt(peer->stream, 0,
646 xbt_dict_length(peer->peers) - 1);
648 connection_t connection;
649 xbt_dict_foreach(peer->peers, cursor, key, connection) {
650 if (i == id_chosen) {
651 peer_choosed = connection;
656 xbt_dict_cursor_free(&cursor);
657 if (!peer_choosed->interested || !peer_choosed->choked_upload) {
661 } while (peer_choosed == NULL && j < MAXIMUM_PAIRS);
663 //Use the "fastest download" policy.
664 connection_t connection;
665 double fastest_speed = 0.0;
666 xbt_dict_foreach(peer->peers, cursor, key, connection) {
667 if (connection->peer_speed > fastest_speed
668 && connection->choked_upload && connection->interested) {
669 peer_choosed = connection;
670 fastest_speed = connection->peer_speed;
676 if (peer_choosed != NULL)
678 ("(%d) update_choked peers unchoked (%d) ; int (%d) ; choked (%d) ",
679 peer->id, peer_choosed->id, peer_choosed->interested,
680 peer_choosed->choked_upload);
682 // if (xbt_dict_size(peer->peers) > 0)
683 // xbt_assert((xbt_dict_size(peer->active_peers) != 0),
684 // "No more active peers !");
687 // if (peer_choked != NULL && peer_choked->choked_upload != 0)
688 // peer_choked = NULL;
689 // if (peer_choosed != NULL && peer_choosed->choked_upload == 0)
690 // peer_choosed = NULL;
692 if (peer_choked != peer_choosed) {
693 if (peer_choked != NULL) {
694 xbt_assert((!peer_choked->choked_upload),
695 "Tries to choked a choked peer");
696 peer_choked->choked_upload = 1;
697 xbt_assert((*((int *) key_choked) == peer_choked->id), "WTF !!!");
698 update_active_peers_set(peer, peer_choked);
699 // xbt_dict_remove_ext(peer->active_peers, key_choked, sizeof(int));
700 XBT_DEBUG("(%d) Sending a CHOKE to %d", peer->id, peer_choked->id);
701 send_choked(peer, peer_choked->mailbox);
703 if (peer_choosed != NULL) {
704 xbt_assert((peer_choosed->choked_upload),
705 "Tries to unchoked an unchoked peer");
706 peer_choosed->choked_upload = 0;
707 xbt_dict_set_ext(peer->active_peers, (char *) &peer_choosed->id,
708 sizeof(int), peer_choosed, NULL);
709 peer_choosed->last_unchoke = MSG_get_clock();
710 XBT_DEBUG("(%d) Sending a UNCHOKE to %d", peer->id, peer_choosed->id);
711 update_active_peers_set(peer, peer_choosed);
712 send_unchoked(peer, peer_choosed->mailbox);
718 * Updates our "interested" state about peers: send "not interested" to peers
719 * that don't have any more pieces we want.
720 * @param peer our peer data
722 void update_interested_after_receive(peer_t peer)
725 xbt_dict_cursor_t cursor;
726 connection_t connection;
728 int interested, piece;
729 xbt_dict_foreach(peer->peers, cursor, key, connection) {
731 if (connection->am_interested) {
732 xbt_assert(connection->bitfield, "Bitfield not received");
733 //Check if the peer still has a piece we want.
735 for (i = 0; i < FILE_PIECES; i++) {
736 if (connection->bitfield[i] == '1' && peer->bitfield[i] == '0') {
741 if (!interested) { //no more piece to download from connection
742 connection->am_interested = 0;
743 send_notinterested(peer, connection->mailbox);
749 void update_bitfield_blocks(peer_t peer, int index, int block_index,
753 xbt_assert((index >= 0 && index <= FILE_PIECES), "Wrong piece.");
754 xbt_assert((block_index >= 0
755 && block_index <= PIECES_BLOCKS), "Wrong block : %d.",
757 for (i = block_index; i < (block_index + block_length); i++) {
758 peer->bitfield_blocks[index * PIECES_BLOCKS + i] = '1';
763 * Returns if a peer has completed the download of a piece
765 int piece_complete(peer_t peer, int index)
768 for (i = 0; i < PIECES_BLOCKS; i++) {
769 if (peer->bitfield_blocks[index * PIECES_BLOCKS + i] == '0') {
777 * Returns the first block that a peer doesn't have in a piece.
778 * If the peer has all blocks of the piece, returns -1.
780 int get_first_block(peer_t peer, int piece)
783 for (i = 0; i < PIECES_BLOCKS; i++) {
784 if (peer->bitfield_blocks[piece * PIECES_BLOCKS + i] == '0') {
792 * Returns a piece that is stored by the remote peer but not by the local peer.
795 int is_interested(peer_t peer, connection_t remote_peer)
797 xbt_assert(remote_peer->bitfield, "Bitfield not received");
799 for (i = 0; i < FILE_PIECES; i++) {
800 if (remote_peer->bitfield[i] == '1' && peer->bitfield[i] == '0') {
807 int is_interested_and_free(peer_t peer, connection_t remote_peer)
809 xbt_assert(remote_peer->bitfield, "Bitfield not received");
811 for (i = 0; i < FILE_PIECES; i++) {
812 if (remote_peer->bitfield[i] == '1' && peer->bitfield[i] == '0'
813 && !in_current_pieces(peer, i)) {
822 * Returns a piece that is partially downloaded and stored by the remote peer if any
825 int partially_downloaded_piece(peer_t peer, connection_t remote_peer)
827 xbt_assert(remote_peer->bitfield, "Bitfield not received");
829 for (i = 0; i < FILE_PIECES; i++) {
830 if (remote_peer->bitfield[i] == '1' && peer->bitfield[i] == '0'
831 && !in_current_pieces(peer, i)) {
832 if (get_first_block(peer, i) > 0)
841 * Send request messages to a peer that have unchoked us
843 * @param remote_peer peer data to the peer we want to send the request
845 void send_request_to_peer(peer_t peer, connection_t remote_peer, int piece)
847 remote_peer->current_piece = piece;
849 int block_index, block_length;
850 xbt_assert(remote_peer->bitfield, "bitfield not received");
851 xbt_assert(remote_peer->bitfield[piece] == '1', "WTF !!!");
852 block_index = get_first_block(peer, piece);
853 if (block_index != -1) {
854 block_length = PIECES_BLOCKS - block_index;
855 block_length = min(BLOCKS_REQUESTED, block_length);
856 send_request(peer, remote_peer->mailbox, piece, block_index,
863 * Indicates if a piece is currently being downloaded by the peer.
865 int in_current_pieces(peer_t peer, int piece)
869 xbt_dynar_foreach(peer->current_pieces, i, peer_piece) {
870 if (peer_piece == piece) {
880 /***********************************************************
882 * Low level message functions
884 ***********************************************************/
889 * Send a "interested" message to a peer
890 * @param peer peer data
891 * @param mailbox destination mailbox
893 void send_interested(peer_t peer, const char *mailbox)
896 task_message_new(MESSAGE_INTERESTED, peer->hostname, peer->mailbox,
897 peer->id, task_message_size(MESSAGE_INTERESTED));
898 MSG_task_dsend(task, mailbox, task_message_free);
899 XBT_DEBUG("Sending INTERESTED to %s", mailbox);
904 * Send a "not interested" message to a peer
905 * @param peer peer data
906 * @param mailbox destination mailbox
908 void send_notinterested(peer_t peer, const char *mailbox)
911 task_message_new(MESSAGE_NOTINTERESTED, peer->hostname, peer->mailbox,
912 peer->id, task_message_size(MESSAGE_NOTINTERESTED));
913 MSG_task_dsend(task, mailbox, task_message_free);
914 XBT_DEBUG("Sending NOTINTERESTED to %s", mailbox);
919 * Send a handshake message to all the peers the peer has.
920 * @param peer peer data
922 void send_handshake_all(peer_t peer)
924 connection_t remote_peer;
925 xbt_dict_cursor_t cursor = NULL;
927 xbt_dict_foreach(peer->peers, cursor, key, remote_peer) {
929 task_message_new(MESSAGE_HANDSHAKE, peer->hostname, peer->mailbox,
930 peer->id, task_message_size(MESSAGE_HANDSHAKE));
931 MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
932 XBT_DEBUG("Sending a HANDSHAKE to %s", remote_peer->mailbox);
937 * Send a "handshake" message to an user
938 * @param peer peer data
939 * @param mailbox mailbox where to we send the message
941 void send_handshake(peer_t peer, const char *mailbox)
944 task_message_new(MESSAGE_HANDSHAKE, peer->hostname, peer->mailbox,
945 peer->id, task_message_size(MESSAGE_HANDSHAKE));
946 MSG_task_dsend(task, mailbox, task_message_free);
947 XBT_DEBUG("Sending a HANDSHAKE to %s", mailbox);
951 * Send a "choked" message to a peer.
953 void send_choked(peer_t peer, const char *mailbox)
955 XBT_DEBUG("Sending a CHOKE to %s", mailbox);
957 task_message_new(MESSAGE_CHOKE, peer->hostname, peer->mailbox,
958 peer->id, task_message_size(MESSAGE_CHOKE));
959 MSG_task_dsend(task, mailbox, task_message_free);
963 * Send a "unchoked" message to a peer
965 void send_unchoked(peer_t peer, const char *mailbox)
967 XBT_DEBUG("Sending a UNCHOKE to %s", mailbox);
969 task_message_new(MESSAGE_UNCHOKE, peer->hostname, peer->mailbox,
970 peer->id, task_message_size(MESSAGE_UNCHOKE));
971 MSG_task_dsend(task, mailbox, task_message_free);
975 * Send a "HAVE" message to all peers we are connected to
977 void send_have(peer_t peer, int piece)
979 XBT_DEBUG("Sending HAVE message to all my peers");
980 connection_t remote_peer;
981 xbt_dict_cursor_t cursor = NULL;
983 xbt_dict_foreach(peer->peers, cursor, key, remote_peer) {
985 task_message_index_new(MESSAGE_HAVE, peer->hostname, peer->mailbox,
987 task_message_size(MESSAGE_HAVE));
988 MSG_task_dsend(task, remote_peer->mailbox, task_message_free);
993 * Send a bitfield message to all the peers the peer has.
994 * @param peer peer data
996 void send_bitfield(peer_t peer, const char *mailbox)
998 XBT_DEBUG("Sending a BITFIELD to %s", mailbox);
1000 task_message_bitfield_new(peer->hostname, peer->mailbox, peer->id,
1001 peer->bitfield, FILE_PIECES);
1002 //Async send and append to pending sends
1003 msg_comm_t comm = MSG_task_isend(task, mailbox);
1004 xbt_dynar_push(peer->pending_sends, &comm);
1008 * Send a "request" message to a pair, containing a request for a piece
1010 void send_request(peer_t peer, const char *mailbox, int piece,
1011 int block_index, int block_length)
1013 XBT_DEBUG("Sending a REQUEST to %s for piece %d (%d,%d)", mailbox, piece,
1014 block_index, block_length);
1016 task_message_request_new(peer->hostname, peer->mailbox, peer->id, piece,
1017 block_index, block_length);
1018 MSG_task_dsend(task, mailbox, task_message_free);
1022 * Send a "piece" message to a pair, containing a piece of the file
1024 void send_piece(peer_t peer, const char *mailbox, int piece, int stalled,
1025 int block_index, int block_length)
1027 XBT_DEBUG("Sending the PIECE %d (%d,%d) to %s", piece, block_index,
1028 block_length, mailbox);
1029 xbt_assert(piece >= 0, "Tried to send a piece that doesn't exist.");
1030 xbt_assert((peer->bitfield[piece] == '1'),
1031 "Tried to send a piece that we doesn't have.");
1033 task_message_piece_new(peer->hostname, peer->mailbox, peer->id, piece,
1034 stalled, block_index, block_length, BLOCK_SIZE);
1035 MSG_task_dsend(task, mailbox, task_message_free);