HandshakeExtensionMessage.cc 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2009 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 "HandshakeExtensionMessage.h"
  36. #include "Peer.h"
  37. #include "util.h"
  38. #include "DlAbortEx.h"
  39. #include "LogFactory.h"
  40. #include "Logger.h"
  41. #include "message.h"
  42. #include "fmt.h"
  43. #include "bencode2.h"
  44. #include "DownloadContext.h"
  45. #include "bittorrent_helper.h"
  46. #include "RequestGroup.h"
  47. #include "PieceStorage.h"
  48. #include "FileEntry.h"
  49. namespace aria2 {
  50. const char HandshakeExtensionMessage::EXTENSION_NAME[] = "handshake";
  51. HandshakeExtensionMessage::HandshakeExtensionMessage()
  52. : tcpPort_{0}, metadataSize_{0}, dctx_{nullptr}
  53. {
  54. }
  55. std::string HandshakeExtensionMessage::getPayload()
  56. {
  57. Dict dict;
  58. if (!clientVersion_.empty()) {
  59. dict.put("v", clientVersion_);
  60. }
  61. if (tcpPort_ > 0) {
  62. dict.put("p", Integer::g(tcpPort_));
  63. }
  64. auto extDict = Dict::g();
  65. for (int i = 0; i < ExtensionMessageRegistry::MAX_EXTENSION; ++i) {
  66. int id = extreg_.getExtensionMessageID(i);
  67. if (id) {
  68. extDict->put(strBtExtension(i), Integer::g(id));
  69. }
  70. }
  71. dict.put("m", std::move(extDict));
  72. if (metadataSize_) {
  73. dict.put("metadata_size", Integer::g(metadataSize_));
  74. }
  75. return bencode2::encode(&dict);
  76. }
  77. std::string HandshakeExtensionMessage::toString() const
  78. {
  79. std::string s(fmt("%s client=%s, tcpPort=%u, metadataSize=%lu",
  80. getExtensionName(),
  81. util::percentEncode(clientVersion_).c_str(), tcpPort_,
  82. static_cast<unsigned long>(metadataSize_)));
  83. for (int i = 0; i < ExtensionMessageRegistry::MAX_EXTENSION; ++i) {
  84. int id = extreg_.getExtensionMessageID(i);
  85. if (id) {
  86. s += fmt(", %s=%u", strBtExtension(i), id);
  87. }
  88. }
  89. return s;
  90. }
  91. void HandshakeExtensionMessage::doReceivedAction()
  92. {
  93. if (tcpPort_ > 0) {
  94. peer_->setPort(tcpPort_);
  95. peer_->setIncomingPeer(false);
  96. }
  97. for (int i = 0; i < ExtensionMessageRegistry::MAX_EXTENSION; ++i) {
  98. int id = extreg_.getExtensionMessageID(i);
  99. if (id) {
  100. peer_->setExtension(i, id);
  101. }
  102. }
  103. auto attrs = bittorrent::getTorrentAttrs(dctx_);
  104. if (attrs->metadata.empty()) {
  105. if (!peer_->getExtensionMessageID(ExtensionMessageRegistry::UT_METADATA)) {
  106. // TODO In metadataGetMode, if peer don't support metadata
  107. // transfer, should we drop connection? There is a possibility
  108. // that peer can still tell us peers using PEX.
  109. throw DL_ABORT_EX("Peer doesn't support ut_metadata extension. Goodbye.");
  110. }
  111. if (metadataSize_ > 0) {
  112. if (attrs->metadataSize) {
  113. if (metadataSize_ != attrs->metadataSize) {
  114. throw DL_ABORT_EX("Wrong metadata_size. Which one is correct!?");
  115. }
  116. }
  117. else {
  118. attrs->metadataSize = metadataSize_;
  119. dctx_->getFirstFileEntry()->setLength(metadataSize_);
  120. dctx_->markTotalLengthIsKnown();
  121. dctx_->getOwnerRequestGroup()->initPieceStorage();
  122. // We enter 'end game' mode from the start to get metadata
  123. // quickly.
  124. dctx_->getOwnerRequestGroup()->getPieceStorage()->enterEndGame();
  125. }
  126. peer_->reconfigureSessionResource(dctx_->getPieceLength(),
  127. dctx_->getTotalLength());
  128. peer_->setAllBitfield();
  129. }
  130. else {
  131. throw DL_ABORT_EX("Peer didn't provide metadata_size."
  132. " It seems that it doesn't have whole metadata.");
  133. }
  134. }
  135. }
  136. void HandshakeExtensionMessage::setPeer(const std::shared_ptr<Peer>& peer)
  137. {
  138. peer_ = peer;
  139. }
  140. void HandshakeExtensionMessage::setExtension(int key, uint8_t id)
  141. {
  142. extreg_.setExtensionMessageID(key, id);
  143. }
  144. void HandshakeExtensionMessage::setExtensions(const Extensions& extensions)
  145. {
  146. extreg_.setExtensions(extensions);
  147. }
  148. uint8_t HandshakeExtensionMessage::getExtensionMessageID(int key) const
  149. {
  150. return extreg_.getExtensionMessageID(key);
  151. }
  152. std::unique_ptr<HandshakeExtensionMessage>
  153. HandshakeExtensionMessage::create(const unsigned char* data, size_t length)
  154. {
  155. if (length < 1) {
  156. throw DL_ABORT_EX(fmt(MSG_TOO_SMALL_PAYLOAD_SIZE, EXTENSION_NAME,
  157. static_cast<unsigned long>(length)));
  158. }
  159. A2_LOG_DEBUG(fmt("Creating HandshakeExtensionMessage from %s",
  160. util::percentEncode(data, length).c_str()));
  161. auto decoded = bencode2::decode(data + 1, length - 1);
  162. const Dict* dict = downcast<Dict>(decoded);
  163. if (!dict) {
  164. throw DL_ABORT_EX(
  165. "Unexpected payload format for extended message handshake");
  166. }
  167. auto msg = make_unique<HandshakeExtensionMessage>();
  168. const Integer* port = downcast<Integer>(dict->get("p"));
  169. if (port && 0 < port->i() && port->i() < 65536) {
  170. msg->tcpPort_ = port->i();
  171. }
  172. const String* version = downcast<String>(dict->get("v"));
  173. if (version) {
  174. msg->clientVersion_ = version->s();
  175. }
  176. const Dict* extDict = downcast<Dict>(dict->get("m"));
  177. if (extDict) {
  178. for (auto& elem : *extDict) {
  179. const Integer* extId = downcast<Integer>(elem.second);
  180. if (extId) {
  181. if (extId->i() < 0 || extId->i() > 255) {
  182. A2_LOG_DEBUG(fmt("Extension ID=%" PRId64 " is invalid", extId->i()));
  183. continue;
  184. }
  185. int key = keyBtExtension(elem.first.c_str());
  186. if (key == ExtensionMessageRegistry::MAX_EXTENSION) {
  187. A2_LOG_DEBUG(fmt("Unsupported BitTorrent extension %s=%" PRId64,
  188. elem.first.c_str(), extId->i()));
  189. }
  190. else {
  191. msg->setExtension(key, extId->i());
  192. }
  193. }
  194. }
  195. }
  196. const Integer* metadataSize = downcast<Integer>(dict->get("metadata_size"));
  197. if (metadataSize) {
  198. auto size = metadataSize->i();
  199. if (size < 0) {
  200. throw DL_ABORT_EX(
  201. fmt("Negative metadataSize %" PRId64 " was received", size));
  202. }
  203. // Only accept metadata smaller than 1MiB. Be aware that broken
  204. // client can send negative size!
  205. if (size > 0 && size <= static_cast<int64_t>(1_m)) {
  206. msg->metadataSize_ = size;
  207. }
  208. }
  209. return msg;
  210. }
  211. } // namespace aria2