1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
|
/* <!-- copyright */
/*
* aria2 - The high speed download utility
*
* Copyright (C) 2006 Tatsuhiro Tsujikawa
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
/* copyright --> */
#include "BtPieceMessage.h"
#include <cstring>
#include <cstdlib>
#include <cassert>
#include "bittorrent_helper.h"
#include "util.h"
#include "message.h"
#include "DlAbortEx.h"
#include "message_digest_helper.h"
#include "DiskAdaptor.h"
#include "Logger.h"
#include "LogFactory.h"
#include "Peer.h"
#include "Piece.h"
#include "PieceStorage.h"
#include "BtMessageDispatcher.h"
#include "BtMessageFactory.h"
#include "BtRequestFactory.h"
#include "PeerConnection.h"
#include "fmt.h"
#include "DownloadContext.h"
#include "PeerStorage.h"
#include "array_fun.h"
#include "WrDiskCache.h"
#include "WrDiskCacheEntry.h"
#include "DownloadFailureException.h"
#include "BtRejectMessage.h"
namespace aria2 {
const char BtPieceMessage::NAME[] = "piece";
BtPieceMessage::BtPieceMessage
(size_t index, int32_t begin, int32_t blockLength)
: AbstractBtMessage(ID, NAME),
index_(index),
begin_(begin),
blockLength_(blockLength),
data_(nullptr),
downloadContext_(nullptr),
peerStorage_(nullptr)
{
setUploading(true);
}
BtPieceMessage::~BtPieceMessage()
{}
void BtPieceMessage::setMsgPayload(const unsigned char* data)
{
data_ = data;
}
std::unique_ptr<BtPieceMessage> BtPieceMessage::create
(const unsigned char* data, size_t dataLength)
{
bittorrent::assertPayloadLengthGreater(9, dataLength, NAME);
bittorrent::assertID(ID, data, NAME);
return make_unique<BtPieceMessage>(bittorrent::getIntParam(data, 1),
bittorrent::getIntParam(data, 5),
dataLength-9);
}
void BtPieceMessage::doReceivedAction()
{
if(isMetadataGetMode()) {
return;
}
auto slot = getBtMessageDispatcher()->getOutstandingRequest
(index_, begin_, blockLength_);
getPeer()->updateDownloadLength(blockLength_);
downloadContext_->updateDownloadLength(blockLength_);
if(slot) {
getPeer()->snubbing(false);
std::shared_ptr<Piece> piece = getPieceStorage()->getPiece(index_);
int64_t offset =
static_cast<int64_t>(index_)*downloadContext_->getPieceLength()+begin_;
A2_LOG_DEBUG(fmt(MSG_PIECE_RECEIVED,
getCuid(),
static_cast<unsigned long>(index_),
begin_,
blockLength_,
static_cast<int64_t>(offset),
static_cast<unsigned long>(slot->getBlockIndex())));
if(piece->hasBlock(slot->getBlockIndex())) {
A2_LOG_DEBUG("Already have this block.");
return;
}
if(piece->getWrDiskCacheEntry()) {
// Write Disk Cache enabled. Unfortunately, it incurs extra data
// copy.
auto dataCopy = new unsigned char[blockLength_];
memcpy(dataCopy, data_+9, blockLength_);
piece->updateWrCache(getPieceStorage()->getWrDiskCache(),
dataCopy, 0, blockLength_, blockLength_, offset);
} else {
getPieceStorage()->getDiskAdaptor()->writeData(data_+9, blockLength_,
offset);
}
piece->completeBlock(slot->getBlockIndex());
A2_LOG_DEBUG(fmt(MSG_PIECE_BITFIELD, getCuid(),
util::toHex(piece->getBitfield(),
piece->getBitfieldLength()).c_str()));
piece->updateHash(begin_, data_+9, blockLength_);
getBtMessageDispatcher()->removeOutstandingRequest(slot);
if(piece->pieceComplete()) {
if(checkPieceHash(piece)) {
onNewPiece(piece);
} else {
onWrongPiece(piece);
peerStorage_->addBadPeer(getPeer()->getIPAddress());
throw DL_ABORT_EX("Bad piece hash.");
}
}
} else {
A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - RequestSlot not found, index=%lu, begin=%d",
getCuid(),
static_cast<unsigned long>(index_),
begin_));
}
}
size_t BtPieceMessage::MESSAGE_HEADER_LENGTH = 13;
void BtPieceMessage::createMessageHeader(unsigned char* msgHeader) const
{
/**
* len --- 9+blockLength, 4bytes
* id --- 7, 1byte
* index --- index, 4bytes
* begin --- begin, 4bytes
* total: 13bytes
*/
bittorrent::createPeerMessageString(msgHeader, MESSAGE_HEADER_LENGTH,
9+blockLength_, ID);
bittorrent::setIntParam(&msgHeader[5], index_);
bittorrent::setIntParam(&msgHeader[9], begin_);
}
size_t BtPieceMessage::getMessageHeaderLength()
{
return MESSAGE_HEADER_LENGTH;
}
namespace {
struct PieceSendUpdate : public ProgressUpdate {
PieceSendUpdate(std::shared_ptr<Peer> peer, size_t headerLength)
: peer(std::move(peer)), headerLength(headerLength) {}
virtual void update(size_t length, bool complete) CXX11_OVERRIDE
{
if(headerLength > 0) {
size_t m = std::min(headerLength, length);
headerLength -= m;
length -= m;
}
peer->updateUploadLength(length);
}
std::shared_ptr<Peer> peer;
size_t headerLength;
};
} // namespace
void BtPieceMessage::send()
{
if(isInvalidate()) {
return;
}
A2_LOG_INFO(fmt(MSG_SEND_PEER_MESSAGE,
getCuid(),
getPeer()->getIPAddress().c_str(),
getPeer()->getPort(),
toString().c_str()));
int64_t pieceDataOffset =
static_cast<int64_t>(index_)*downloadContext_->getPieceLength()+begin_;
pushPieceData(pieceDataOffset, blockLength_);
}
void BtPieceMessage::pushPieceData(int64_t offset, int32_t length) const
{
assert(length <= 16*1024);
auto buf = make_unique<unsigned char[]>(length+MESSAGE_HEADER_LENGTH);
createMessageHeader(buf.get());
ssize_t r;
r = getPieceStorage()->getDiskAdaptor()->readData
(buf.get()+MESSAGE_HEADER_LENGTH, length, offset);
if(r == length) {
getPeerConnection()->pushBytes(buf.release(), length+MESSAGE_HEADER_LENGTH,
make_unique<PieceSendUpdate>
(getPeer(), MESSAGE_HEADER_LENGTH));
// To avoid upload rate overflow, we update the length here at
// once.
downloadContext_->updateUploadLength(length);
} else {
throw DL_ABORT_EX(EX_DATA_READ);
}
}
std::string BtPieceMessage::toString() const
{
return fmt("%s index=%lu, begin=%d, length=%d",
NAME,
static_cast<unsigned long>(index_),
begin_, blockLength_);
}
bool BtPieceMessage::checkPieceHash(const std::shared_ptr<Piece>& piece)
{
if(!getPieceStorage()->isEndGame() && piece->isHashCalculated()) {
A2_LOG_DEBUG(fmt("Hash is available!! index=%lu",
static_cast<unsigned long>(piece->getIndex())));
return
piece->getDigest() == downloadContext_->getPieceHash(piece->getIndex());
} else {
A2_LOG_DEBUG(fmt("Calculating hash index=%lu",
static_cast<unsigned long>(piece->getIndex())));
try {
return piece->getDigestWithWrCache(downloadContext_->getPieceLength(),
getPieceStorage()->getDiskAdaptor())
== downloadContext_->getPieceHash(piece->getIndex());
} catch(RecoverableException& e) {
piece->clearAllBlock(getPieceStorage()->getWrDiskCache());
throw;
}
}
}
void BtPieceMessage::onNewPiece(const std::shared_ptr<Piece>& piece)
{
if(piece->getWrDiskCacheEntry()) {
// We flush cached data whenever an whole piece is retrieved.
piece->flushWrCache(getPieceStorage()->getWrDiskCache());
if(piece->getWrDiskCacheEntry()->getError() !=
WrDiskCacheEntry::CACHE_ERR_SUCCESS) {
piece->clearAllBlock(getPieceStorage()->getWrDiskCache());
throw DOWNLOAD_FAILURE_EXCEPTION2
(fmt("Write disk cache flush failure index=%lu",
static_cast<unsigned long>(piece->getIndex())),
piece->getWrDiskCacheEntry()->getErrorCode());
}
}
A2_LOG_INFO(fmt(MSG_GOT_NEW_PIECE,
getCuid(),
static_cast<unsigned long>(piece->getIndex())));
getPieceStorage()->completePiece(piece);
getPieceStorage()->advertisePiece(getCuid(), piece->getIndex());
}
void BtPieceMessage::onWrongPiece(const std::shared_ptr<Piece>& piece)
{
A2_LOG_INFO(fmt(MSG_GOT_WRONG_PIECE,
getCuid(),
static_cast<unsigned long>(piece->getIndex())));
piece->clearAllBlock(getPieceStorage()->getWrDiskCache());
piece->destroyHashContext();
getBtRequestFactory()->removeTargetPiece(piece);
}
void BtPieceMessage::onChokingEvent(const BtChokingEvent& event)
{
if(!isInvalidate() &&
!getPeer()->isInAmAllowedIndexSet(index_)) {
A2_LOG_DEBUG(fmt(MSG_REJECT_PIECE_CHOKED,
getCuid(),
static_cast<unsigned long>(index_),
begin_,
blockLength_));
if(getPeer()->isFastExtensionEnabled()) {
getBtMessageDispatcher()->addMessageToQueue
(getBtMessageFactory()->createRejectMessage
(index_, begin_, blockLength_));
}
setInvalidate(true);
}
}
void BtPieceMessage::onCancelSendingPieceEvent
(const BtCancelSendingPieceEvent& event)
{
if(!isInvalidate() &&
index_ == event.getIndex() &&
begin_ == event.getBegin() &&
blockLength_ == event.getLength()) {
A2_LOG_DEBUG(fmt(MSG_REJECT_PIECE_CANCEL,
getCuid(),
static_cast<unsigned long>(index_),
begin_,
blockLength_));
if(getPeer()->isFastExtensionEnabled()) {
getBtMessageDispatcher()->addMessageToQueue
(getBtMessageFactory()->createRejectMessage
(index_, begin_, blockLength_));
}
setInvalidate(true);
}
}
void BtPieceMessage::setDownloadContext(DownloadContext* downloadContext)
{
downloadContext_ = downloadContext;
}
void BtPieceMessage::setPeerStorage(PeerStorage* peerStorage)
{
peerStorage_ = peerStorage;
}
} // namespace aria2
|