/* */ #include "BtBitfieldMessage.h" #include "PeerMessageUtil.h" #include "Util.h" #include "DlAbortEx.h" #include "message.h" void BtBitfieldMessage::setBitfield(const unsigned char* bitfield, int32_t bitfieldLength) { if(this->bitfield == bitfield) { return; } delete [] this->bitfield; this->bitfieldLength = bitfieldLength; this->bitfield = new unsigned char[this->bitfieldLength]; memcpy(this->bitfield, bitfield, this->bitfieldLength); } BtBitfieldMessageHandle BtBitfieldMessage::create(const unsigned char* data, int32_t dataLength) { if(dataLength <= 1) { throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "bitfield", dataLength, 1); } int8_t id = PeerMessageUtil::getId(data); if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "bitfield", ID); } BtBitfieldMessageHandle message = new BtBitfieldMessage(); message->setBitfield((unsigned char*)data+1, dataLength-1); return message; } void BtBitfieldMessage::doReceivedAction() { peer->setBitfield(bitfield, bitfieldLength); } const unsigned char* BtBitfieldMessage::getMessage() { if(!msg) { /** * len --- 1+bitfieldLength, 4bytes * id --- 5, 1byte * bitfield --- bitfield, len bytes * total: 5+len bytes */ msgLength = 5+bitfieldLength; msg = new unsigned char[msgLength]; PeerMessageUtil::createPeerMessageString(msg, msgLength, 1+bitfieldLength, ID); memcpy(msg+5, bitfield, bitfieldLength); } return msg; } int32_t BtBitfieldMessage::getMessageLength() { getMessage(); return msgLength; } string BtBitfieldMessage::toString() const { return "bitfield "+Util::toHex(bitfield, bitfieldLength); }