PeerConnection.cc 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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(cuid_t cuid, const std::shared_ptr<Peer>& peer,
  62. 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_(make_unique<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. }
  78. PeerConnection::~PeerConnection() {}
  79. void PeerConnection::pushBytes(std::vector<unsigned char> data,
  80. std::unique_ptr<ProgressUpdate> progressUpdate)
  81. {
  82. if (encryptionEnabled_) {
  83. encryptor_->encrypt(data.size(), data.data(), data.data());
  84. }
  85. socketBuffer_.pushBytes(std::move(data), std::move(progressUpdate));
  86. }
  87. bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength)
  88. {
  89. while (1) {
  90. bool done = false;
  91. size_t i;
  92. for (i = resbufOffset_; i < resbufLength_ && !done; ++i) {
  93. unsigned char c = resbuf_[i];
  94. switch (msgState_) {
  95. case (BT_MSG_PREV_READ_LENGTH):
  96. msgOffset_ = i;
  97. currentPayloadLength_ = 0;
  98. msgState_ = BT_MSG_READ_LENGTH;
  99. // Fall through
  100. case (BT_MSG_READ_LENGTH):
  101. currentPayloadLength_ <<= 8;
  102. currentPayloadLength_ += c;
  103. // The message length is uint32_t
  104. if (i - msgOffset_ == 3) {
  105. if (currentPayloadLength_ + 4 > bufferCapacity_) {
  106. throw DL_ABORT_EX(fmt(EX_TOO_LONG_PAYLOAD, currentPayloadLength_));
  107. }
  108. if (currentPayloadLength_ == 0) {
  109. // Length == 0 means keep-alive message.
  110. done = true;
  111. msgState_ = BT_MSG_PREV_READ_LENGTH;
  112. }
  113. else {
  114. msgState_ = BT_MSG_READ_PAYLOAD;
  115. }
  116. }
  117. break;
  118. case (BT_MSG_READ_PAYLOAD):
  119. // We chosen the bufferCapacity_ so that whole message,
  120. // including 4 bytes length and payload, in it. So here we
  121. // just make sure that it happens.
  122. if (resbufLength_ - msgOffset_ >= 4 + currentPayloadLength_) {
  123. i = msgOffset_ + 4 + currentPayloadLength_ - 1;
  124. done = true;
  125. msgState_ = BT_MSG_PREV_READ_LENGTH;
  126. }
  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_.get() + msgOffset_ + 4, currentPayloadLength_);
  138. }
  139. dataLength = currentPayloadLength_;
  140. return true;
  141. }
  142. else {
  143. assert(resbufOffset_ == resbufLength_);
  144. if (resbufLength_ != 0) {
  145. if (msgOffset_ == 0 && resbufLength_ == currentPayloadLength_ + 4) {
  146. // All bytes in buffer have been processed, so clear it
  147. // away.
  148. resbufLength_ = 0;
  149. resbufOffset_ = 0;
  150. msgOffset_ = 0;
  151. }
  152. else {
  153. // Shift buffer so that resbuf_[msgOffset_] moves to
  154. // rebuf_[0].
  155. memmove(resbuf_.get(), resbuf_.get() + msgOffset_,
  156. resbufLength_ - msgOffset_);
  157. resbufLength_ -= msgOffset_;
  158. resbufOffset_ = resbufLength_;
  159. msgOffset_ = 0;
  160. }
  161. }
  162. size_t nread;
  163. // To reduce the amount of copy involved in buffer shift, large
  164. // payload will be read exactly.
  165. if (currentPayloadLength_ > 4_k) {
  166. nread = currentPayloadLength_ + 4 - resbufLength_;
  167. }
  168. else {
  169. nread = bufferCapacity_ - resbufLength_;
  170. }
  171. readData(resbuf_.get() + resbufLength_, nread, encryptionEnabled_);
  172. if (nread == 0) {
  173. if (socket_->wantRead() || socket_->wantWrite()) {
  174. break;
  175. }
  176. else {
  177. peer_->setDisconnectedGracefully(true);
  178. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  179. }
  180. }
  181. else {
  182. resbufLength_ += nread;
  183. }
  184. }
  185. }
  186. return false;
  187. }
  188. bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength,
  189. bool peek)
  190. {
  191. if (BtHandshakeMessage::MESSAGE_LENGTH < resbufLength_) {
  192. throw DL_ABORT_EX(
  193. "More than BtHandshakeMessage::MESSAGE_LENGTH bytes are buffered.");
  194. }
  195. bool retval = true;
  196. size_t remaining = BtHandshakeMessage::MESSAGE_LENGTH - resbufLength_;
  197. if (remaining > 0) {
  198. size_t temp = remaining;
  199. readData(resbuf_.get() + resbufLength_, remaining, encryptionEnabled_);
  200. if (remaining == 0 && !socket_->wantRead() && !socket_->wantWrite()) {
  201. // we got EOF
  202. A2_LOG_DEBUG(fmt("CUID#%" PRId64
  203. " - In PeerConnection::receiveHandshake(), remain=%lu",
  204. cuid_, static_cast<unsigned long>(temp)));
  205. peer_->setDisconnectedGracefully(true);
  206. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  207. }
  208. resbufLength_ += remaining;
  209. if (BtHandshakeMessage::MESSAGE_LENGTH > resbufLength_) {
  210. retval = false;
  211. }
  212. }
  213. size_t writeLength = std::min(resbufLength_, dataLength);
  214. memcpy(data, resbuf_.get(), writeLength);
  215. dataLength = writeLength;
  216. if (retval && !peek) {
  217. resbufLength_ = 0;
  218. }
  219. return retval;
  220. }
  221. void PeerConnection::readData(unsigned char* data, size_t& length,
  222. bool encryption)
  223. {
  224. socket_->readData(data, length);
  225. if (encryption) {
  226. decryptor_->encrypt(length, data, data);
  227. }
  228. }
  229. void PeerConnection::enableEncryption(std::unique_ptr<ARC4Encryptor> encryptor,
  230. std::unique_ptr<ARC4Encryptor> decryptor)
  231. {
  232. encryptor_ = std::move(encryptor);
  233. decryptor_ = std::move(decryptor);
  234. encryptionEnabled_ = true;
  235. }
  236. void PeerConnection::presetBuffer(const unsigned char* data, size_t length)
  237. {
  238. size_t nwrite = std::min(bufferCapacity_, length);
  239. memcpy(resbuf_.get(), data, nwrite);
  240. resbufLength_ = length;
  241. }
  242. bool PeerConnection::sendBufferIsEmpty() const
  243. {
  244. return socketBuffer_.sendBufferIsEmpty();
  245. }
  246. size_t PeerConnection::getBufferEntrySize() const
  247. {
  248. return socketBuffer_.getBufferEntrySize();
  249. }
  250. ssize_t PeerConnection::sendPendingData()
  251. {
  252. ssize_t writtenLength = socketBuffer_.send();
  253. A2_LOG_DEBUG(fmt("sent %ld byte(s).", static_cast<long int>(writtenLength)));
  254. return writtenLength;
  255. }
  256. const unsigned char* PeerConnection::getMsgPayloadBuffer() const
  257. {
  258. return resbuf_.get() + msgOffset_ + 4;
  259. }
  260. void PeerConnection::reserveBuffer(size_t minSize)
  261. {
  262. if (bufferCapacity_ < minSize) {
  263. bufferCapacity_ = minSize;
  264. auto buf = make_unique<unsigned char[]>(bufferCapacity_);
  265. memcpy(buf.get(), resbuf_.get(), resbufLength_);
  266. resbuf_ = std::move(buf);
  267. }
  268. }
  269. } // namespace aria2