PeerConnection.cc 9.0 KB

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