PeerConnection.cc 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. namespace aria2 {
  50. PeerConnection::PeerConnection(int32_t cuid, const SocketHandle& socket)
  51. :cuid(cuid),
  52. socket(socket),
  53. logger(LogFactory::getInstance()),
  54. resbuf(new unsigned char[MAX_PAYLOAD_LEN]),
  55. resbufLength(0),
  56. currentPayloadLength(0),
  57. lenbufLength(0),
  58. _socketBuffer(socket),
  59. _encryptionEnabled(false),
  60. _prevPeek(false)
  61. {}
  62. PeerConnection::~PeerConnection()
  63. {
  64. delete [] resbuf;
  65. }
  66. void PeerConnection::pushStr(const std::string& data)
  67. {
  68. if(_encryptionEnabled) {
  69. const size_t len = data.size();
  70. unsigned char* chunk = new unsigned char[len];
  71. try {
  72. _encryptor->encrypt
  73. (chunk, len, reinterpret_cast<const unsigned char*>(data.data()), len);
  74. } catch(RecoverableException& e) {
  75. delete [] chunk;
  76. throw;
  77. }
  78. _socketBuffer.pushBytes(chunk, len);
  79. } else {
  80. _socketBuffer.pushStr(data);
  81. }
  82. }
  83. void PeerConnection::pushBytes(unsigned char* data, size_t len)
  84. {
  85. if(_encryptionEnabled) {
  86. unsigned char* chunk = new unsigned char[len];
  87. try {
  88. _encryptor->encrypt(chunk, len, data, len);
  89. } catch(RecoverableException& e) {
  90. delete [] data;
  91. delete [] chunk;
  92. throw;
  93. }
  94. delete [] data;
  95. _socketBuffer.pushBytes(chunk, len);
  96. } else {
  97. _socketBuffer.pushBytes(data, len);
  98. }
  99. }
  100. bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) {
  101. if(resbufLength == 0 && 4 > lenbufLength) {
  102. if(!socket->isReadable(0)) {
  103. return false;
  104. }
  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. if(logger->debug()) {
  115. logger->debug("CUID#%d - In PeerConnection::receiveMessage(),"
  116. " remain=%lu",
  117. cuid, static_cast<unsigned long>(temp));
  118. }
  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(StringFormat(EX_TOO_LONG_PAYLOAD, payloadLength).str());
  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. if(logger->debug()) {
  148. logger->debug("CUID#%d - In PeerConnection::receiveMessage(),"
  149. " payloadlen=%lu, remaining=%lu",
  150. cuid,
  151. static_cast<unsigned long>(currentPayloadLength),
  152. static_cast<unsigned long>(temp));
  153. }
  154. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  155. }
  156. resbufLength += remaining;
  157. if(currentPayloadLength > resbufLength) {
  158. return false;
  159. }
  160. }
  161. // we got whole payload.
  162. resbufLength = 0;
  163. lenbufLength = 0;
  164. if(data) {
  165. memcpy(data, resbuf, currentPayloadLength);
  166. }
  167. dataLength = currentPayloadLength;
  168. return true;
  169. }
  170. bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength,
  171. bool peek) {
  172. assert(BtHandshakeMessage::MESSAGE_LENGTH >= resbufLength);
  173. bool retval = true;
  174. if(_prevPeek && !peek && resbufLength) {
  175. // We have data in previous peek.
  176. // There is a chance that socket is readable because of EOF, for example,
  177. // official bttrack shutdowns socket after sending first 48 bytes of
  178. // handshake in its NAT checking.
  179. // So if there are data in resbuf, return it without checking socket
  180. // status.
  181. _prevPeek = false;
  182. retval = BtHandshakeMessage::MESSAGE_LENGTH <= resbufLength;
  183. } else {
  184. _prevPeek = peek;
  185. size_t remaining = BtHandshakeMessage::MESSAGE_LENGTH-resbufLength;
  186. if(remaining > 0 && !socket->isReadable(0)) {
  187. dataLength = 0;
  188. return false;
  189. }
  190. if(remaining > 0) {
  191. size_t temp = remaining;
  192. readData(resbuf+resbufLength, remaining, _encryptionEnabled);
  193. if(remaining == 0) {
  194. if(socket->wantRead() || socket->wantWrite()) {
  195. return false;
  196. }
  197. // we got EOF
  198. if(logger->debug()) {
  199. logger->debug
  200. ("CUID#%d - In PeerConnection::receiveHandshake(), remain=%lu",
  201. cuid, static_cast<unsigned long>(temp));
  202. }
  203. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  204. }
  205. resbufLength += remaining;
  206. if(BtHandshakeMessage::MESSAGE_LENGTH > resbufLength) {
  207. retval = false;
  208. }
  209. }
  210. }
  211. size_t writeLength = std::min(resbufLength, dataLength);
  212. memcpy(data, resbuf, writeLength);
  213. dataLength = writeLength;
  214. if(retval && !peek) {
  215. resbufLength = 0;
  216. }
  217. return retval;
  218. }
  219. void PeerConnection::readData(unsigned char* data, size_t& length, bool encryption)
  220. {
  221. if(encryption) {
  222. unsigned char temp[MAX_PAYLOAD_LEN];
  223. assert(MAX_PAYLOAD_LEN >= length);
  224. socket->readData(temp, length);
  225. _decryptor->decrypt(data, length, temp, length);
  226. } else {
  227. socket->readData(data, length);
  228. }
  229. }
  230. void PeerConnection::enableEncryption(const SharedHandle<ARC4Encryptor>& encryptor,
  231. const SharedHandle<ARC4Decryptor>& decryptor)
  232. {
  233. _encryptor = encryptor;
  234. _decryptor = decryptor;
  235. _encryptionEnabled = true;
  236. }
  237. void PeerConnection::presetBuffer(const unsigned char* data, size_t length)
  238. {
  239. size_t nwrite = std::min((size_t)MAX_PAYLOAD_LEN, length);
  240. memcpy(resbuf, data, nwrite);
  241. resbufLength = length;
  242. }
  243. bool PeerConnection::sendBufferIsEmpty() const
  244. {
  245. return _socketBuffer.sendBufferIsEmpty();
  246. }
  247. ssize_t PeerConnection::sendPendingData()
  248. {
  249. ssize_t writtenLength = _socketBuffer.send();
  250. if(logger->debug()) {
  251. logger->debug("sent %d byte(s).", writtenLength);
  252. }
  253. return writtenLength;
  254. }
  255. } // namespace aria2