PeerConnection.cc 8.0 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 "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. resbufLength(0),
  55. currentPayloadLength(0),
  56. lenbufLength(0),
  57. _socketBuffer(socket),
  58. _encryptionEnabled(false),
  59. _prevPeek(false)
  60. {}
  61. PeerConnection::~PeerConnection() {}
  62. ssize_t PeerConnection::sendMessage(const unsigned char* data,
  63. size_t dataLength)
  64. {
  65. ssize_t writtenLength = sendData(data, dataLength, _encryptionEnabled);
  66. if(logger->debug()) {
  67. logger->debug("sent %d byte(s).", writtenLength);
  68. }
  69. return writtenLength;
  70. }
  71. bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) {
  72. if(resbufLength == 0 && 4 > lenbufLength) {
  73. if(!socket->isReadable(0)) {
  74. return false;
  75. }
  76. // read payload size, 32bit unsigned integer
  77. size_t remaining = 4-lenbufLength;
  78. size_t temp = remaining;
  79. readData(lenbuf+lenbufLength, remaining, _encryptionEnabled);
  80. if(remaining == 0) {
  81. if(socket->wantRead() || socket->wantWrite()) {
  82. return false;
  83. }
  84. // we got EOF
  85. if(logger->debug()) {
  86. logger->debug("CUID#%d - In PeerConnection::receiveMessage(),"
  87. " remain=%lu",
  88. cuid, static_cast<unsigned long>(temp));
  89. }
  90. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  91. }
  92. lenbufLength += remaining;
  93. if(4 > lenbufLength) {
  94. // still 4-lenbufLength bytes to go
  95. return false;
  96. }
  97. uint32_t payloadLength;
  98. memcpy(&payloadLength, lenbuf, sizeof(payloadLength));
  99. payloadLength = ntohl(payloadLength);
  100. if(payloadLength > MAX_PAYLOAD_LEN) {
  101. throw DL_ABORT_EX(StringFormat(EX_TOO_LONG_PAYLOAD, payloadLength).str());
  102. }
  103. currentPayloadLength = payloadLength;
  104. }
  105. if(!socket->isReadable(0)) {
  106. return false;
  107. }
  108. // we have currentPayloadLen-resbufLen bytes to read
  109. size_t remaining = currentPayloadLength-resbufLength;
  110. size_t temp = remaining;
  111. if(remaining > 0) {
  112. readData(resbuf+resbufLength, 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#%d - In PeerConnection::receiveMessage(),"
  120. " payloadlen=%lu, remaining=%lu",
  121. cuid,
  122. static_cast<unsigned long>(currentPayloadLength),
  123. static_cast<unsigned long>(temp));
  124. }
  125. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  126. }
  127. resbufLength += remaining;
  128. if(currentPayloadLength > resbufLength) {
  129. return false;
  130. }
  131. }
  132. // we got whole payload.
  133. resbufLength = 0;
  134. lenbufLength = 0;
  135. memcpy(data, resbuf, currentPayloadLength);
  136. dataLength = currentPayloadLength;
  137. return true;
  138. }
  139. bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength,
  140. bool peek) {
  141. assert(BtHandshakeMessage::MESSAGE_LENGTH >= resbufLength);
  142. bool retval = true;
  143. if(_prevPeek && !peek && resbufLength) {
  144. // We have data in previous peek.
  145. // There is a chance that socket is readable because of EOF, for example,
  146. // official bttrack shutdowns socket after sending first 48 bytes of
  147. // handshake in its NAT checking.
  148. // So if there are data in resbuf, return it without checking socket
  149. // status.
  150. _prevPeek = false;
  151. retval = BtHandshakeMessage::MESSAGE_LENGTH <= resbufLength;
  152. } else {
  153. _prevPeek = peek;
  154. size_t remaining = BtHandshakeMessage::MESSAGE_LENGTH-resbufLength;
  155. if(remaining > 0 && !socket->isReadable(0)) {
  156. dataLength = 0;
  157. return false;
  158. }
  159. if(remaining > 0) {
  160. size_t temp = remaining;
  161. readData(resbuf+resbufLength, remaining, _encryptionEnabled);
  162. if(remaining == 0) {
  163. if(socket->wantRead() || socket->wantWrite()) {
  164. return false;
  165. }
  166. // we got EOF
  167. if(logger->debug()) {
  168. logger->debug
  169. ("CUID#%d - In PeerConnection::receiveHandshake(), remain=%lu",
  170. cuid, static_cast<unsigned long>(temp));
  171. }
  172. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  173. }
  174. resbufLength += remaining;
  175. if(BtHandshakeMessage::MESSAGE_LENGTH > resbufLength) {
  176. retval = false;
  177. }
  178. }
  179. }
  180. size_t writeLength = std::min(resbufLength, dataLength);
  181. memcpy(data, resbuf, writeLength);
  182. dataLength = writeLength;
  183. if(retval && !peek) {
  184. resbufLength = 0;
  185. }
  186. return retval;
  187. }
  188. void PeerConnection::readData(unsigned char* data, size_t& length, bool encryption)
  189. {
  190. if(encryption) {
  191. unsigned char temp[MAX_PAYLOAD_LEN];
  192. assert(MAX_PAYLOAD_LEN >= length);
  193. socket->readData(temp, length);
  194. _decryptor->decrypt(data, length, temp, length);
  195. } else {
  196. socket->readData(data, length);
  197. }
  198. }
  199. ssize_t PeerConnection::sendData(const unsigned char* data,
  200. size_t length, bool encryption)
  201. {
  202. if(encryption) {
  203. unsigned char temp[4096];
  204. const unsigned char* dptr = data;
  205. size_t r = length;
  206. while(r > 0) {
  207. size_t s = std::min(r, sizeof(temp));
  208. _encryptor->encrypt(temp, s, dptr, s);
  209. _socketBuffer.feedSendBuffer(std::string(&temp[0], &temp[s]));
  210. dptr += s;
  211. r -= s;
  212. }
  213. } else {
  214. _socketBuffer.feedSendBuffer(std::string(&data[0], &data[length]));
  215. }
  216. return _socketBuffer.send();
  217. }
  218. void PeerConnection::enableEncryption(const SharedHandle<ARC4Encryptor>& encryptor,
  219. const SharedHandle<ARC4Decryptor>& decryptor)
  220. {
  221. _encryptor = encryptor;
  222. _decryptor = decryptor;
  223. _encryptionEnabled = true;
  224. }
  225. void PeerConnection::presetBuffer(const unsigned char* data, size_t length)
  226. {
  227. size_t nwrite = std::min((size_t)MAX_PAYLOAD_LEN, length);
  228. memcpy(resbuf, data, nwrite);
  229. resbufLength = length;
  230. }
  231. bool PeerConnection::sendBufferIsEmpty() const
  232. {
  233. return _socketBuffer.sendBufferIsEmpty();
  234. }
  235. ssize_t PeerConnection::sendPendingData()
  236. {
  237. ssize_t writtenLength = _socketBuffer.send();
  238. if(logger->debug()) {
  239. logger->debug("sent %d byte(s).", writtenLength);
  240. }
  241. return writtenLength;
  242. }
  243. } // namespace aria2