PeerConnection.cc 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 "Socket.h"
  45. #include "a2netcompat.h"
  46. #include "ARC4Encryptor.h"
  47. #include "ARC4Decryptor.h"
  48. #include "fmt.h"
  49. #include "util.h"
  50. #include "Peer.h"
  51. namespace aria2 {
  52. PeerConnection::PeerConnection
  53. (cuid_t cuid, const SharedHandle<Peer>& peer, const SocketHandle& socket)
  54. : cuid_(cuid),
  55. peer_(peer),
  56. socket_(socket),
  57. resbuf_(new unsigned char[MAX_PAYLOAD_LEN]),
  58. resbufLength_(0),
  59. currentPayloadLength_(0),
  60. lenbufLength_(0),
  61. socketBuffer_(socket),
  62. encryptionEnabled_(false),
  63. prevPeek_(false)
  64. {}
  65. PeerConnection::~PeerConnection()
  66. {
  67. delete [] resbuf_;
  68. }
  69. void PeerConnection::pushStr(const std::string& data)
  70. {
  71. if(encryptionEnabled_) {
  72. const size_t len = data.size();
  73. unsigned char* chunk = new unsigned char[len];
  74. try {
  75. encryptor_->encrypt
  76. (chunk, len, reinterpret_cast<const unsigned char*>(data.data()), len);
  77. } catch(RecoverableException& e) {
  78. delete [] chunk;
  79. throw;
  80. }
  81. socketBuffer_.pushBytes(chunk, len);
  82. } else {
  83. socketBuffer_.pushStr(data);
  84. }
  85. }
  86. void PeerConnection::pushBytes(unsigned char* data, size_t len)
  87. {
  88. if(encryptionEnabled_) {
  89. unsigned char* chunk = new unsigned char[len];
  90. try {
  91. encryptor_->encrypt(chunk, len, data, len);
  92. } catch(RecoverableException& e) {
  93. delete [] data;
  94. delete [] chunk;
  95. throw;
  96. }
  97. delete [] data;
  98. socketBuffer_.pushBytes(chunk, len);
  99. } else {
  100. socketBuffer_.pushBytes(data, len);
  101. }
  102. }
  103. bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) {
  104. if(resbufLength_ == 0 && 4 > lenbufLength_) {
  105. // read payload size, 32bit unsigned integer
  106. size_t remaining = 4-lenbufLength_;
  107. size_t temp = remaining;
  108. readData(lenbuf_+lenbufLength_, remaining, encryptionEnabled_);
  109. if(remaining == 0) {
  110. if(socket_->wantRead() || socket_->wantWrite()) {
  111. return false;
  112. }
  113. // we got EOF
  114. A2_LOG_DEBUG(fmt("CUID#%lld - In PeerConnection::receiveMessage(),"
  115. " remain=%lu",
  116. cuid_,
  117. static_cast<unsigned long>(temp)));
  118. peer_->setDisconnectedGracefully(true);
  119. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  120. }
  121. lenbufLength_ += remaining;
  122. if(4 > lenbufLength_) {
  123. // still 4-lenbufLength_ bytes to go
  124. return false;
  125. }
  126. uint32_t payloadLength;
  127. memcpy(&payloadLength, lenbuf_, sizeof(payloadLength));
  128. payloadLength = ntohl(payloadLength);
  129. if(payloadLength > MAX_PAYLOAD_LEN) {
  130. throw DL_ABORT_EX(fmt(EX_TOO_LONG_PAYLOAD, payloadLength));
  131. }
  132. currentPayloadLength_ = payloadLength;
  133. }
  134. if(!socket_->isReadable(0)) {
  135. return false;
  136. }
  137. // we have currentPayloadLen-resbufLen bytes to read
  138. size_t remaining = currentPayloadLength_-resbufLength_;
  139. size_t temp = remaining;
  140. if(remaining > 0) {
  141. readData(resbuf_+resbufLength_, remaining, encryptionEnabled_);
  142. if(remaining == 0) {
  143. if(socket_->wantRead() || socket_->wantWrite()) {
  144. return false;
  145. }
  146. // we got EOF
  147. A2_LOG_DEBUG(fmt("CUID#%lld - In PeerConnection::receiveMessage(),"
  148. " payloadlen=%lu, remaining=%lu",
  149. cuid_,
  150. static_cast<unsigned long>(currentPayloadLength_),
  151. static_cast<unsigned long>(temp)));
  152. peer_->setDisconnectedGracefully(true);
  153. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  154. }
  155. resbufLength_ += remaining;
  156. if(currentPayloadLength_ > resbufLength_) {
  157. return false;
  158. }
  159. }
  160. // we got whole payload.
  161. resbufLength_ = 0;
  162. lenbufLength_ = 0;
  163. if(data) {
  164. memcpy(data, resbuf_, currentPayloadLength_);
  165. }
  166. dataLength = currentPayloadLength_;
  167. return true;
  168. }
  169. bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength,
  170. bool peek) {
  171. if(BtHandshakeMessage::MESSAGE_LENGTH < resbufLength_) {
  172. throw DL_ABORT_EX
  173. ("More than BtHandshakeMessage::MESSAGE_LENGTH bytes are buffered.");
  174. }
  175. bool retval = true;
  176. size_t remaining = BtHandshakeMessage::MESSAGE_LENGTH-resbufLength_;
  177. if(remaining > 0) {
  178. size_t temp = remaining;
  179. readData(resbuf_+resbufLength_, remaining, encryptionEnabled_);
  180. if(remaining == 0 && !socket_->wantRead() && !socket_->wantWrite()) {
  181. // we got EOF
  182. A2_LOG_DEBUG
  183. (fmt("CUID#%lld - In PeerConnection::receiveHandshake(), remain=%lu",
  184. cuid_,
  185. static_cast<unsigned long>(temp)));
  186. peer_->setDisconnectedGracefully(true);
  187. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  188. }
  189. resbufLength_ += remaining;
  190. if(BtHandshakeMessage::MESSAGE_LENGTH > resbufLength_) {
  191. retval = false;
  192. }
  193. }
  194. size_t writeLength = std::min(resbufLength_, dataLength);
  195. memcpy(data, resbuf_, writeLength);
  196. dataLength = writeLength;
  197. if(retval && !peek) {
  198. resbufLength_ = 0;
  199. }
  200. return retval;
  201. }
  202. void PeerConnection::readData
  203. (unsigned char* data, size_t& length, bool encryption)
  204. {
  205. if(encryption) {
  206. unsigned char temp[MAX_PAYLOAD_LEN];
  207. assert(MAX_PAYLOAD_LEN >= length);
  208. socket_->readData(temp, length);
  209. decryptor_->decrypt(data, length, temp, length);
  210. } else {
  211. socket_->readData(data, length);
  212. }
  213. }
  214. void PeerConnection::enableEncryption
  215. (const SharedHandle<ARC4Encryptor>& encryptor,
  216. const SharedHandle<ARC4Decryptor>& decryptor)
  217. {
  218. encryptor_ = encryptor;
  219. decryptor_ = decryptor;
  220. encryptionEnabled_ = true;
  221. }
  222. void PeerConnection::presetBuffer(const unsigned char* data, size_t length)
  223. {
  224. size_t nwrite = std::min((size_t)MAX_PAYLOAD_LEN, length);
  225. memcpy(resbuf_, data, nwrite);
  226. resbufLength_ = length;
  227. }
  228. bool PeerConnection::sendBufferIsEmpty() const
  229. {
  230. return socketBuffer_.sendBufferIsEmpty();
  231. }
  232. ssize_t PeerConnection::sendPendingData()
  233. {
  234. ssize_t writtenLength = socketBuffer_.send();
  235. A2_LOG_DEBUG(fmt("sent %ld byte(s).", static_cast<long int>(writtenLength)));
  236. return writtenLength;
  237. }
  238. unsigned char* PeerConnection::detachBuffer()
  239. {
  240. unsigned char* detachbuf = resbuf_;
  241. resbuf_ = new unsigned char[MAX_PAYLOAD_LEN];
  242. return detachbuf;
  243. }
  244. } // namespace aria2