PeerConnection.cc 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "PeerConnection.h"
  36. #include <cstring>
  37. #include <cassert>
  38. #include <algorithm>
  39. #include "message.h"
  40. #include "DlAbortEx.h"
  41. #include "LogFactory.h"
  42. #include "Logger.h"
  43. #include "BtHandshakeMessage.h"
  44. #include "SocketCore.h"
  45. #include "a2netcompat.h"
  46. #include "ARC4Encryptor.h"
  47. #include "fmt.h"
  48. #include "util.h"
  49. #include "Peer.h"
  50. namespace aria2 {
  51. namespace {
  52. enum {
  53. // Before reading first byte of message length
  54. BT_MSG_PREV_READ_LENGTH,
  55. // Reading 4 bytes message length
  56. BT_MSG_READ_LENGTH,
  57. // Reading message payload following message length
  58. BT_MSG_READ_PAYLOAD
  59. };
  60. } // namespace
  61. PeerConnection::PeerConnection
  62. (cuid_t cuid, const std::shared_ptr<Peer>& peer, const std::shared_ptr<SocketCore>& socket)
  63. : cuid_(cuid),
  64. peer_(peer),
  65. socket_(socket),
  66. msgState_(BT_MSG_PREV_READ_LENGTH),
  67. bufferCapacity_(MAX_BUFFER_CAPACITY),
  68. resbuf_(new unsigned char[bufferCapacity_]),
  69. resbufLength_(0),
  70. currentPayloadLength_(0),
  71. resbufOffset_(0),
  72. msgOffset_(0),
  73. socketBuffer_(socket),
  74. encryptionEnabled_(false),
  75. prevPeek_(false)
  76. {}
  77. PeerConnection::~PeerConnection()
  78. {
  79. delete [] resbuf_;
  80. }
  81. void PeerConnection::pushBytes(unsigned char* data, size_t len,
  82. std::unique_ptr<ProgressUpdate> progressUpdate)
  83. {
  84. if(encryptionEnabled_) {
  85. encryptor_->encrypt(len, data, data);
  86. }
  87. socketBuffer_.pushBytes(data, len, std::move(progressUpdate));
  88. }
  89. bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength)
  90. {
  91. while(1) {
  92. bool done = false;
  93. size_t i;
  94. for(i = resbufOffset_; i < resbufLength_ && !done; ++i) {
  95. unsigned char c = resbuf_[i];
  96. switch(msgState_) {
  97. case(BT_MSG_PREV_READ_LENGTH):
  98. msgOffset_ = i;
  99. currentPayloadLength_ = 0;
  100. msgState_ = BT_MSG_READ_LENGTH;
  101. // Fall through
  102. case(BT_MSG_READ_LENGTH):
  103. currentPayloadLength_ <<= 8;
  104. currentPayloadLength_ += c;
  105. // The message length is uint32_t
  106. if(i - msgOffset_ == 3) {
  107. if(currentPayloadLength_ + 4 > bufferCapacity_) {
  108. throw DL_ABORT_EX(fmt(EX_TOO_LONG_PAYLOAD, currentPayloadLength_));
  109. }
  110. if(currentPayloadLength_ == 0) {
  111. // Length == 0 means keep-alive message.
  112. done = true;
  113. msgState_ = BT_MSG_PREV_READ_LENGTH;
  114. } else {
  115. msgState_ = BT_MSG_READ_PAYLOAD;
  116. }
  117. }
  118. break;
  119. case(BT_MSG_READ_PAYLOAD):
  120. // We chosen the bufferCapacity_ so that whole message,
  121. // including 4 bytes length and payload, in it. So here we
  122. // just make sure that it happens.
  123. if(resbufLength_ - msgOffset_ >= 4 + currentPayloadLength_) {
  124. i = msgOffset_ + 4 + currentPayloadLength_ - 1;
  125. done = true;
  126. msgState_ = BT_MSG_PREV_READ_LENGTH;
  127. } else {
  128. // We need another read.
  129. i = resbufLength_-1;
  130. }
  131. break;
  132. }
  133. }
  134. resbufOffset_ = i;
  135. if(done) {
  136. if(data) {
  137. memcpy(data, resbuf_ + msgOffset_ + 4, currentPayloadLength_);
  138. }
  139. dataLength = currentPayloadLength_;
  140. return true;
  141. } else {
  142. assert(resbufOffset_ == resbufLength_);
  143. if(resbufLength_ != 0) {
  144. if(msgOffset_ == 0 && resbufLength_ == currentPayloadLength_ + 4) {
  145. // All bytes in buffer have been processed, so clear it
  146. // away.
  147. resbufLength_ = 0;
  148. resbufOffset_ = 0;
  149. msgOffset_ = 0;
  150. } else {
  151. // Shift buffer so that resbuf_[msgOffset_] moves to
  152. // rebuf_[0].
  153. memmove(resbuf_, resbuf_ + msgOffset_, resbufLength_ - msgOffset_);
  154. resbufLength_ -= msgOffset_;
  155. resbufOffset_ = resbufLength_;
  156. msgOffset_ = 0;
  157. }
  158. }
  159. size_t nread;
  160. // To reduce the amount of copy involved in buffer shift, large
  161. // payload will be read exactly.
  162. if(currentPayloadLength_ > 4096) {
  163. nread = currentPayloadLength_ + 4 - resbufLength_;
  164. } else {
  165. nread = bufferCapacity_ - resbufLength_;
  166. }
  167. readData(resbuf_+resbufLength_, nread, encryptionEnabled_);
  168. if(nread == 0) {
  169. if(socket_->wantRead() || socket_->wantWrite()) {
  170. break;
  171. } else {
  172. peer_->setDisconnectedGracefully(true);
  173. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  174. }
  175. } else {
  176. resbufLength_ += nread;
  177. }
  178. }
  179. }
  180. return false;
  181. }
  182. bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength,
  183. bool peek) {
  184. if(BtHandshakeMessage::MESSAGE_LENGTH < resbufLength_) {
  185. throw DL_ABORT_EX
  186. ("More than BtHandshakeMessage::MESSAGE_LENGTH bytes are buffered.");
  187. }
  188. bool retval = true;
  189. size_t remaining = BtHandshakeMessage::MESSAGE_LENGTH-resbufLength_;
  190. if(remaining > 0) {
  191. size_t temp = remaining;
  192. readData(resbuf_+resbufLength_, remaining, encryptionEnabled_);
  193. if(remaining == 0 && !socket_->wantRead() && !socket_->wantWrite()) {
  194. // we got EOF
  195. A2_LOG_DEBUG
  196. (fmt("CUID#%" PRId64 " - In PeerConnection::receiveHandshake(), remain=%lu",
  197. cuid_,
  198. static_cast<unsigned long>(temp)));
  199. peer_->setDisconnectedGracefully(true);
  200. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  201. }
  202. resbufLength_ += remaining;
  203. if(BtHandshakeMessage::MESSAGE_LENGTH > resbufLength_) {
  204. retval = false;
  205. }
  206. }
  207. size_t writeLength = std::min(resbufLength_, dataLength);
  208. memcpy(data, resbuf_, writeLength);
  209. dataLength = writeLength;
  210. if(retval && !peek) {
  211. resbufLength_ = 0;
  212. }
  213. return retval;
  214. }
  215. void PeerConnection::readData
  216. (unsigned char* data, size_t& length, bool encryption)
  217. {
  218. socket_->readData(data, length);
  219. if(encryption) {
  220. decryptor_->encrypt(length, data, data);
  221. }
  222. }
  223. void PeerConnection::enableEncryption
  224. (std::unique_ptr<ARC4Encryptor> encryptor,
  225. std::unique_ptr<ARC4Encryptor> decryptor)
  226. {
  227. encryptor_ = std::move(encryptor);
  228. decryptor_ = std::move(decryptor);
  229. encryptionEnabled_ = true;
  230. }
  231. void PeerConnection::presetBuffer(const unsigned char* data, size_t length)
  232. {
  233. size_t nwrite = std::min(bufferCapacity_, length);
  234. memcpy(resbuf_, data, nwrite);
  235. resbufLength_ = length;
  236. }
  237. bool PeerConnection::sendBufferIsEmpty() const
  238. {
  239. return socketBuffer_.sendBufferIsEmpty();
  240. }
  241. size_t PeerConnection::getBufferEntrySize() const
  242. {
  243. return socketBuffer_.getBufferEntrySize();
  244. }
  245. ssize_t PeerConnection::sendPendingData()
  246. {
  247. ssize_t writtenLength = socketBuffer_.send();
  248. A2_LOG_DEBUG(fmt("sent %ld byte(s).", static_cast<long int>(writtenLength)));
  249. return writtenLength;
  250. }
  251. const unsigned char* PeerConnection::getMsgPayloadBuffer() const
  252. {
  253. return resbuf_ + msgOffset_ + 4;
  254. }
  255. void PeerConnection::reserveBuffer(size_t minSize)
  256. {
  257. if(bufferCapacity_ < minSize) {
  258. bufferCapacity_ = minSize;
  259. unsigned char *buf = new unsigned char[bufferCapacity_];
  260. memcpy(buf, resbuf_, resbufLength_);
  261. delete [] resbuf_;
  262. resbuf_ = buf;
  263. }
  264. }
  265. } // namespace aria2