PeerConnection.cc 7.8 KB

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