From 7607286f50c4d251460bdecbf3ed3b4198cf1e90 Mon Sep 17 00:00:00 2001 From: Arvid Norberg Date: Fri, 6 Feb 2009 08:51:25 +0000 Subject: [PATCH] fixing bug where the trailing bits in bitfields were not set to 0. Fixes #482 --- include/libtorrent/bitfield.hpp | 13 ++++++++++--- src/bt_peer_connection.cpp | 6 +++++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/include/libtorrent/bitfield.hpp b/include/libtorrent/bitfield.hpp index 9313e6f8a..25c7252db 100644 --- a/include/libtorrent/bitfield.hpp +++ b/include/libtorrent/bitfield.hpp @@ -60,7 +60,7 @@ namespace libtorrent ~bitfield() { dealloc(); } void assign(char const* bytes, int bits) - { resize(bits); std::memcpy(m_bytes, bytes, (bits + 7) / 8); } + { resize(bits); std::memcpy(m_bytes, bytes, (bits + 7) / 8); clear_trailing_bits(); } bool operator[](int index) const { return get_bit(index); } @@ -198,6 +198,7 @@ namespace libtorrent if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b); if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes); + clear_trailing_bits(); } else { @@ -209,6 +210,7 @@ namespace libtorrent void set_all() { std::memset(m_bytes, 0xff, (m_size + 7) / 8); + clear_trailing_bits(); } void clear_all() @@ -240,14 +242,19 @@ namespace libtorrent m_own = true; } m_size = bits; - // clear the tail bits in the last byte - if (m_size && (bits & 7)) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (7 - (bits & 7)); + clear_trailing_bits(); } void free() { dealloc(); m_size = 0; } private: + void clear_trailing_bits() + { + // clear the tail bits in the last byte + if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7)); + } + void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; } unsigned char* m_bytes; int m_size:31; // in bits diff --git a/src/bt_peer_connection.cpp b/src/bt_peer_connection.cpp index d7b04c773..480c1ee58 100644 --- a/src/bt_peer_connection.cpp +++ b/src/bt_peer_connection.cpp @@ -1563,7 +1563,11 @@ namespace libtorrent if (t->is_seed()) { - memset(i.begin, 0xff, packet_size - 5); + memset(i.begin, 0xff, packet_size - 6); + + // Clear trailing bits + unsigned char *p = ((unsigned char *)i.begin) + packet_size - 6; + *p = (0xff << ((8 - (num_pieces & 7)) & 7)) & 0xff; } else {