PeerConnection.cc 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 "message.h"
  37. #include "DlAbortEx.h"
  38. #include "LogFactory.h"
  39. #include "Logger.h"
  40. #include "BtHandshakeMessage.h"
  41. #include "Socket.h"
  42. #include "a2netcompat.h"
  43. #include "ARC4Encryptor.h"
  44. #include "ARC4Decryptor.h"
  45. #include "StringFormat.h"
  46. #include <cstring>
  47. #include <cassert>
  48. #include <algorithm>
  49. namespace aria2 {
  50. PeerConnection::PeerConnection(int32_t cuid,
  51. const SocketHandle& socket,
  52. const Option* op)
  53. :cuid(cuid),
  54. socket(socket),
  55. option(op),
  56. logger(LogFactory::getInstance()),
  57. resbufLength(0),
  58. currentPayloadLength(0),
  59. lenbufLength(0),
  60. _socketBuffer(socket),
  61. _encryptionEnabled(false),
  62. _prevPeek(false)
  63. {}
  64. PeerConnection::~PeerConnection() {}
  65. ssize_t PeerConnection::sendMessage(const unsigned char* data,
  66. size_t dataLength)
  67. {
  68. if(socket->isWritable(0)) {
  69. return sendData(data, dataLength, _encryptionEnabled);
  70. } else {
  71. return 0;
  72. }
  73. }
  74. bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) {
  75. if(resbufLength == 0 && 4 > lenbufLength) {
  76. if(!socket->isReadable(0)) {
  77. return false;
  78. }
  79. // read payload size, 32bit unsigned integer
  80. size_t remaining = 4-lenbufLength;
  81. size_t temp = remaining;
  82. readData(lenbuf+lenbufLength, remaining, _encryptionEnabled);
  83. if(remaining == 0) {
  84. // we got EOF
  85. logger->debug("CUID#%d - In PeerConnection::receiveMessage(), remain=%zu",
  86. cuid, temp);
  87. throw DlAbortEx(EX_EOF_FROM_PEER);
  88. }
  89. lenbufLength += remaining;
  90. if(4 > lenbufLength) {
  91. // still 4-lenbufLength bytes to go
  92. return false;
  93. }
  94. uint32_t payloadLength = ntohl(*(reinterpret_cast<uint32_t*>(lenbuf)));
  95. if(payloadLength > MAX_PAYLOAD_LEN) {
  96. throw DlAbortEx(StringFormat(EX_TOO_LONG_PAYLOAD, payloadLength).str());
  97. }
  98. currentPayloadLength = payloadLength;
  99. }
  100. if(!socket->isReadable(0)) {
  101. return false;
  102. }
  103. // we have currentPayloadLen-resbufLen bytes to read
  104. size_t remaining = currentPayloadLength-resbufLength;
  105. size_t temp = remaining;
  106. if(remaining > 0) {
  107. readData(resbuf+resbufLength, remaining, _encryptionEnabled);
  108. if(remaining == 0) {
  109. // we got EOF
  110. logger->debug("CUID#%d - In PeerConnection::receiveMessage(), payloadlen=%zu, remaining=%zu",
  111. cuid, currentPayloadLength, temp);
  112. throw DlAbortEx(EX_EOF_FROM_PEER);
  113. }
  114. resbufLength += remaining;
  115. if(currentPayloadLength > resbufLength) {
  116. return false;
  117. }
  118. }
  119. // we got whole payload.
  120. resbufLength = 0;
  121. lenbufLength = 0;
  122. memcpy(data, resbuf, currentPayloadLength);
  123. dataLength = currentPayloadLength;
  124. return true;
  125. }
  126. bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength,
  127. bool peek) {
  128. assert(BtHandshakeMessage::MESSAGE_LENGTH >= resbufLength);
  129. bool retval = true;
  130. if(_prevPeek && !peek && resbufLength) {
  131. // We have data in previous peek.
  132. // There is a chance that socket is readable because of EOF, for example,
  133. // official bttrack shutdowns socket after sending first 48 bytes of
  134. // handshake in its NAT checking.
  135. // So if there are data in resbuf, return it without checking socket
  136. // status.
  137. _prevPeek = false;
  138. retval = BtHandshakeMessage::MESSAGE_LENGTH <= resbufLength;
  139. } else {
  140. _prevPeek = peek;
  141. size_t remaining = BtHandshakeMessage::MESSAGE_LENGTH-resbufLength;
  142. if(remaining > 0 && !socket->isReadable(0)) {
  143. dataLength = 0;
  144. return false;
  145. }
  146. if(remaining > 0) {
  147. size_t temp = remaining;
  148. readData(resbuf+resbufLength, remaining, _encryptionEnabled);
  149. if(remaining == 0) {
  150. // we got EOF
  151. logger->debug("CUID#%d - In PeerConnection::receiveHandshake(), remain=%zu",
  152. cuid, temp);
  153. throw DlAbortEx(EX_EOF_FROM_PEER);
  154. }
  155. resbufLength += remaining;
  156. if(BtHandshakeMessage::MESSAGE_LENGTH > resbufLength) {
  157. retval = false;
  158. }
  159. }
  160. }
  161. size_t writeLength = std::min(resbufLength, dataLength);
  162. memcpy(data, resbuf, writeLength);
  163. dataLength = writeLength;
  164. if(retval && !peek) {
  165. resbufLength = 0;
  166. }
  167. return retval;
  168. }
  169. void PeerConnection::readData(unsigned char* data, size_t& length, bool encryption)
  170. {
  171. if(encryption) {
  172. unsigned char temp[MAX_PAYLOAD_LEN];
  173. assert(MAX_PAYLOAD_LEN >= length);
  174. socket->readData(temp, length);
  175. _decryptor->decrypt(data, length, temp, length);
  176. } else {
  177. socket->readData(data, length);
  178. }
  179. }
  180. ssize_t PeerConnection::sendData(const unsigned char* data,
  181. size_t length, bool encryption)
  182. {
  183. if(encryption) {
  184. unsigned char temp[4096];
  185. const unsigned char* dptr = data;
  186. size_t r = length;
  187. while(r > 0) {
  188. size_t s = std::min(r, sizeof(temp));
  189. _encryptor->encrypt(temp, s, dptr, s);
  190. _socketBuffer.feedSendBuffer(std::string(&temp[0], &temp[s]));
  191. dptr += s;
  192. r -= s;
  193. }
  194. } else {
  195. _socketBuffer.feedSendBuffer(std::string(&data[0], &data[length]));
  196. }
  197. return _socketBuffer.send();
  198. }
  199. void PeerConnection::enableEncryption(const SharedHandle<ARC4Encryptor>& encryptor,
  200. const SharedHandle<ARC4Decryptor>& decryptor)
  201. {
  202. _encryptor = encryptor;
  203. _decryptor = decryptor;
  204. _encryptionEnabled = true;
  205. }
  206. void PeerConnection::presetBuffer(const unsigned char* data, size_t length)
  207. {
  208. size_t nwrite = std::min((size_t)MAX_PAYLOAD_LEN, length);
  209. memcpy(resbuf, data, nwrite);
  210. resbufLength = length;
  211. }
  212. } // namespace aria2