PeerConnection.cc 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 "StringFormat.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. logger_(LogFactory::getInstance()),
  58. resbuf_(new unsigned char[MAX_PAYLOAD_LEN]),
  59. resbufLength_(0),
  60. currentPayloadLength_(0),
  61. lenbufLength_(0),
  62. socketBuffer_(socket),
  63. encryptionEnabled_(false),
  64. prevPeek_(false)
  65. {}
  66. PeerConnection::~PeerConnection()
  67. {
  68. delete [] resbuf_;
  69. }
  70. void PeerConnection::pushStr(const std::string& data)
  71. {
  72. if(encryptionEnabled_) {
  73. const size_t len = data.size();
  74. unsigned char* chunk = new unsigned char[len];
  75. try {
  76. encryptor_->encrypt
  77. (chunk, len, reinterpret_cast<const unsigned char*>(data.data()), len);
  78. } catch(RecoverableException& e) {
  79. delete [] chunk;
  80. throw;
  81. }
  82. socketBuffer_.pushBytes(chunk, len);
  83. } else {
  84. socketBuffer_.pushStr(data);
  85. }
  86. }
  87. void PeerConnection::pushBytes(unsigned char* data, size_t len)
  88. {
  89. if(encryptionEnabled_) {
  90. unsigned char* chunk = new unsigned char[len];
  91. try {
  92. encryptor_->encrypt(chunk, len, data, len);
  93. } catch(RecoverableException& e) {
  94. delete [] data;
  95. delete [] chunk;
  96. throw;
  97. }
  98. delete [] data;
  99. socketBuffer_.pushBytes(chunk, len);
  100. } else {
  101. socketBuffer_.pushBytes(data, len);
  102. }
  103. }
  104. bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) {
  105. if(resbufLength_ == 0 && 4 > lenbufLength_) {
  106. if(!socket_->isReadable(0)) {
  107. return false;
  108. }
  109. // read payload size, 32bit unsigned integer
  110. size_t remaining = 4-lenbufLength_;
  111. size_t temp = remaining;
  112. readData(lenbuf_+lenbufLength_, remaining, encryptionEnabled_);
  113. if(remaining == 0) {
  114. if(socket_->wantRead() || socket_->wantWrite()) {
  115. return false;
  116. }
  117. // we got EOF
  118. if(logger_->debug()) {
  119. logger_->debug("CUID#%s - In PeerConnection::receiveMessage(),"
  120. " remain=%lu",
  121. util::itos(cuid_).c_str(),
  122. static_cast<unsigned long>(temp));
  123. }
  124. peer_->setDisconnectedGracefully(true);
  125. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  126. }
  127. lenbufLength_ += remaining;
  128. if(4 > lenbufLength_) {
  129. // still 4-lenbufLength_ bytes to go
  130. return false;
  131. }
  132. uint32_t payloadLength;
  133. memcpy(&payloadLength, lenbuf_, sizeof(payloadLength));
  134. payloadLength = ntohl(payloadLength);
  135. if(payloadLength > MAX_PAYLOAD_LEN) {
  136. throw DL_ABORT_EX(StringFormat(EX_TOO_LONG_PAYLOAD, payloadLength).str());
  137. }
  138. currentPayloadLength_ = payloadLength;
  139. }
  140. if(!socket_->isReadable(0)) {
  141. return false;
  142. }
  143. // we have currentPayloadLen-resbufLen bytes to read
  144. size_t remaining = currentPayloadLength_-resbufLength_;
  145. size_t temp = remaining;
  146. if(remaining > 0) {
  147. readData(resbuf_+resbufLength_, remaining, encryptionEnabled_);
  148. if(remaining == 0) {
  149. if(socket_->wantRead() || socket_->wantWrite()) {
  150. return false;
  151. }
  152. // we got EOF
  153. if(logger_->debug()) {
  154. logger_->debug("CUID#%s - In PeerConnection::receiveMessage(),"
  155. " payloadlen=%lu, remaining=%lu",
  156. util::itos(cuid_).c_str(),
  157. static_cast<unsigned long>(currentPayloadLength_),
  158. static_cast<unsigned long>(temp));
  159. }
  160. peer_->setDisconnectedGracefully(true);
  161. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  162. }
  163. resbufLength_ += remaining;
  164. if(currentPayloadLength_ > resbufLength_) {
  165. return false;
  166. }
  167. }
  168. // we got whole payload.
  169. resbufLength_ = 0;
  170. lenbufLength_ = 0;
  171. if(data) {
  172. memcpy(data, resbuf_, currentPayloadLength_);
  173. }
  174. dataLength = currentPayloadLength_;
  175. return true;
  176. }
  177. bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength,
  178. bool peek) {
  179. assert(BtHandshakeMessage::MESSAGE_LENGTH >= resbufLength_);
  180. bool retval = true;
  181. if(prevPeek_ && !peek && resbufLength_) {
  182. // We have data in previous peek.
  183. // There is a chance that socket is readable because of EOF, for example,
  184. // official bttrack shutdowns socket after sending first 48 bytes of
  185. // handshake in its NAT checking.
  186. // So if there are data in resbuf_, return it without checking socket
  187. // status.
  188. prevPeek_ = false;
  189. retval = BtHandshakeMessage::MESSAGE_LENGTH <= resbufLength_;
  190. } else {
  191. prevPeek_ = peek;
  192. size_t remaining = BtHandshakeMessage::MESSAGE_LENGTH-resbufLength_;
  193. if(remaining > 0 && !socket_->isReadable(0)) {
  194. dataLength = 0;
  195. return false;
  196. }
  197. if(remaining > 0) {
  198. size_t temp = remaining;
  199. readData(resbuf_+resbufLength_, remaining, encryptionEnabled_);
  200. if(remaining == 0) {
  201. if(socket_->wantRead() || socket_->wantWrite()) {
  202. return false;
  203. }
  204. // we got EOF
  205. if(logger_->debug()) {
  206. logger_->debug
  207. ("CUID#%s - In PeerConnection::receiveHandshake(), remain=%lu",
  208. util::itos(cuid_).c_str(), static_cast<unsigned long>(temp));
  209. }
  210. peer_->setDisconnectedGracefully(true);
  211. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  212. }
  213. resbufLength_ += remaining;
  214. if(BtHandshakeMessage::MESSAGE_LENGTH > resbufLength_) {
  215. retval = false;
  216. }
  217. }
  218. }
  219. size_t writeLength = std::min(resbufLength_, dataLength);
  220. memcpy(data, resbuf_, writeLength);
  221. dataLength = writeLength;
  222. if(retval && !peek) {
  223. resbufLength_ = 0;
  224. }
  225. return retval;
  226. }
  227. void PeerConnection::readData
  228. (unsigned char* data, size_t& length, bool encryption)
  229. {
  230. if(encryption) {
  231. unsigned char temp[MAX_PAYLOAD_LEN];
  232. assert(MAX_PAYLOAD_LEN >= length);
  233. socket_->readData(temp, length);
  234. decryptor_->decrypt(data, length, temp, length);
  235. } else {
  236. socket_->readData(data, length);
  237. }
  238. }
  239. void PeerConnection::enableEncryption
  240. (const SharedHandle<ARC4Encryptor>& encryptor,
  241. const SharedHandle<ARC4Decryptor>& decryptor)
  242. {
  243. encryptor_ = encryptor;
  244. decryptor_ = decryptor;
  245. encryptionEnabled_ = true;
  246. }
  247. void PeerConnection::presetBuffer(const unsigned char* data, size_t length)
  248. {
  249. size_t nwrite = std::min((size_t)MAX_PAYLOAD_LEN, length);
  250. memcpy(resbuf_, data, nwrite);
  251. resbufLength_ = length;
  252. }
  253. bool PeerConnection::sendBufferIsEmpty() const
  254. {
  255. return socketBuffer_.sendBufferIsEmpty();
  256. }
  257. ssize_t PeerConnection::sendPendingData()
  258. {
  259. ssize_t writtenLength = socketBuffer_.send();
  260. if(logger_->debug()) {
  261. logger_->debug("sent %ld byte(s).", static_cast<long int>(writtenLength));
  262. }
  263. return writtenLength;
  264. }
  265. } // namespace aria2