PeerConnection.cc 7.5 KB

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