bencode2.cc 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2010 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 "bencode2.h"
  36. #include <sstream>
  37. #include "fmt.h"
  38. #include "DlAbortEx.h"
  39. #include "error_code.h"
  40. #include "BufferedFile.h"
  41. #include "util.h"
  42. namespace aria2 {
  43. namespace bencode2 {
  44. namespace {
  45. template<typename InputIterator>
  46. std::pair<SharedHandle<ValueBase>, InputIterator>
  47. decodeiter
  48. (InputIterator first,
  49. InputIterator last,
  50. size_t depth);
  51. } // namespace
  52. namespace {
  53. template<typename InputIterator>
  54. std::pair<std::pair<InputIterator, InputIterator>, InputIterator>
  55. decoderawstring(InputIterator first, InputIterator last)
  56. {
  57. InputIterator i = first;
  58. int32_t len;
  59. for(; i != last && *i != ':'; ++i);
  60. if(i == last || i == first || !util::parseIntNoThrow(len, first, i) ||
  61. len < 0) {
  62. throw DL_ABORT_EX2("Bencode decoding failed:"
  63. " A positive integer expected but none found.",
  64. error_code::BENCODE_PARSE_ERROR);
  65. }
  66. ++i;
  67. if(last-i < len) {
  68. throw DL_ABORT_EX2
  69. (fmt("Bencode decoding failed:"
  70. " Expected %d bytes of data, but only %d read.",
  71. len, static_cast<int>(last-i)),
  72. error_code::BENCODE_PARSE_ERROR);
  73. }
  74. return std::make_pair(std::make_pair(i, i+len), i+len);
  75. }
  76. } // namespace
  77. namespace {
  78. template<typename InputIterator>
  79. std::pair<SharedHandle<ValueBase>, InputIterator>
  80. decodestring(InputIterator first, InputIterator last)
  81. {
  82. std::pair<std::pair<InputIterator, InputIterator>, InputIterator> r =
  83. decoderawstring(first, last);
  84. return std::make_pair(String::g(r.first.first, r.first.second), r.second);
  85. }
  86. } // namespace
  87. namespace {
  88. template<typename InputIterator>
  89. std::pair<SharedHandle<ValueBase>, InputIterator>
  90. decodeinteger(InputIterator first, InputIterator last)
  91. {
  92. InputIterator i = first;
  93. for(; i != last && *i != 'e'; ++i);
  94. Integer::ValueType iv;
  95. if(i == last || !util::parseLLIntNoThrow(iv, first, i)) {
  96. throw DL_ABORT_EX2("Bencode decoding failed:"
  97. " Integer expected but none found",
  98. error_code::BENCODE_PARSE_ERROR);
  99. }
  100. return std::make_pair(Integer::g(iv), ++i);
  101. }
  102. } // namespace
  103. namespace {
  104. template<typename InputIterator>
  105. std::pair<SharedHandle<ValueBase>, InputIterator>
  106. decodedict
  107. (InputIterator first,
  108. InputIterator last,
  109. size_t depth)
  110. {
  111. SharedHandle<Dict> dict = Dict::g();
  112. while(first != last) {
  113. if(*first == 'e') {
  114. return std::make_pair(dict, ++first);
  115. } else {
  116. std::pair<std::pair<InputIterator, InputIterator>, InputIterator> keyp =
  117. decoderawstring(first, last);
  118. std::pair<SharedHandle<ValueBase>, InputIterator> r =
  119. decodeiter(keyp.second, last, depth);
  120. dict->put(std::string(keyp.first.first, keyp.first.second), r.first);
  121. first = r.second;
  122. }
  123. }
  124. throw DL_ABORT_EX2("Bencode decoding failed:"
  125. " Unexpected EOF in dict context. 'e' expected.",
  126. error_code::BENCODE_PARSE_ERROR);
  127. }
  128. } // namespace
  129. namespace {
  130. template<typename InputIterator>
  131. std::pair<SharedHandle<ValueBase>, InputIterator>
  132. decodelist
  133. (InputIterator first,
  134. InputIterator last,
  135. size_t depth)
  136. {
  137. SharedHandle<List> list = List::g();
  138. while(first != last) {
  139. if(*first == 'e') {
  140. return std::make_pair(list, ++first);
  141. } else {
  142. std::pair<SharedHandle<ValueBase>, InputIterator> r =
  143. decodeiter(first, last, depth);
  144. list->append(r.first);
  145. first = r.second;
  146. }
  147. }
  148. throw DL_ABORT_EX2("Bencode decoding failed:"
  149. " Unexpected EOF in list context. 'e' expected.",
  150. error_code::BENCODE_PARSE_ERROR);
  151. }
  152. } // namespace
  153. namespace {
  154. void checkDepth(size_t depth)
  155. {
  156. if(depth >= MAX_STRUCTURE_DEPTH) {
  157. throw DL_ABORT_EX2("Bencode decoding failed: Structure is too deep.",
  158. error_code::BENCODE_PARSE_ERROR);
  159. }
  160. }
  161. } // namespace
  162. namespace {
  163. template<typename InputIterator>
  164. std::pair<SharedHandle<ValueBase>, InputIterator>
  165. decodeiter
  166. (InputIterator first,
  167. InputIterator last,
  168. size_t depth)
  169. {
  170. checkDepth(depth);
  171. if(first == last) {
  172. throw DL_ABORT_EX2("Bencode decoding failed:"
  173. " Unexpected EOF in term context."
  174. " 'd', 'l', 'i' or digit is expected.",
  175. error_code::BENCODE_PARSE_ERROR);
  176. }
  177. if(*first == 'd') {
  178. return decodedict(++first, last, depth+1);
  179. } else if(*first == 'l') {
  180. return decodelist(++first, last, depth+1);
  181. } else if(*first == 'i') {
  182. return decodeinteger(++first, last);
  183. } else {
  184. return decodestring(first, last);
  185. }
  186. }
  187. } // namespace
  188. namespace {
  189. template<typename InputIterator>
  190. SharedHandle<ValueBase> decodegen
  191. (InputIterator first,
  192. InputIterator last,
  193. size_t& end)
  194. {
  195. if(first == last) {
  196. return SharedHandle<ValueBase>();
  197. }
  198. std::pair<SharedHandle<ValueBase>, InputIterator> p =
  199. decodeiter(first, last, 0);
  200. end = p.second-first;
  201. return p.first;
  202. }
  203. } // namespace
  204. SharedHandle<ValueBase> decode
  205. (std::string::const_iterator first,
  206. std::string::const_iterator last)
  207. {
  208. size_t end;
  209. return decodegen(first, last, end);
  210. }
  211. SharedHandle<ValueBase> decode
  212. (std::string::const_iterator first,
  213. std::string::const_iterator last,
  214. size_t& end)
  215. {
  216. return decodegen(first, last, end);
  217. }
  218. SharedHandle<ValueBase> decode
  219. (const unsigned char* first,
  220. const unsigned char* last)
  221. {
  222. size_t end;
  223. return decodegen(first, last, end);
  224. }
  225. SharedHandle<ValueBase> decode
  226. (const unsigned char* first,
  227. const unsigned char* last,
  228. size_t& end)
  229. {
  230. return decodegen(first, last, end);
  231. }
  232. SharedHandle<ValueBase> decodeFromFile(const std::string& filename)
  233. {
  234. BufferedFile fp(filename, BufferedFile::READ);
  235. if(fp) {
  236. std::stringstream ss;
  237. fp.transfer(ss);
  238. fp.close();
  239. const std::string s = ss.str();
  240. size_t end;
  241. return decodegen(s.begin(), s.end(), end);
  242. } else {
  243. throw DL_ABORT_EX2
  244. (fmt("Bencode decoding failed: Cannot open file '%s'.",
  245. filename.c_str()),
  246. error_code::BENCODE_PARSE_ERROR);
  247. }
  248. }
  249. std::string encode(const ValueBase* vlb)
  250. {
  251. class BencodeValueBaseVisitor:public ValueBaseVisitor {
  252. private:
  253. std::ostringstream out_;
  254. public:
  255. virtual void visit(const String& string)
  256. {
  257. const std::string& s = string.s();
  258. out_ << s.size() << ":";
  259. out_.write(s.data(), s.size());
  260. }
  261. virtual void visit(const Integer& integer)
  262. {
  263. out_ << "i" << integer.i() << "e";
  264. }
  265. virtual void visit(const Bool& v) {}
  266. virtual void visit(const Null& v) {}
  267. virtual void visit(const List& list)
  268. {
  269. out_ << "l";
  270. for(List::ValueType::const_iterator i = list.begin(), eoi = list.end();
  271. i != eoi; ++i){
  272. (*i)->accept(*this);
  273. }
  274. out_ << "e";
  275. }
  276. virtual void visit(const Dict& dict)
  277. {
  278. out_ << "d";
  279. for(Dict::ValueType::const_iterator i = dict.begin(), eoi = dict.end();
  280. i != eoi; ++i){
  281. const std::string& key = (*i).first;
  282. out_ << key.size() << ":";
  283. out_.write(key.data(), key.size());
  284. (*i).second->accept(*this);
  285. }
  286. out_ << "e";
  287. }
  288. std::string getResult() const
  289. {
  290. return out_.str();
  291. }
  292. };
  293. BencodeValueBaseVisitor visitor;
  294. vlb->accept(visitor);
  295. return visitor.getResult();
  296. }
  297. std::string encode(const SharedHandle<ValueBase>& vlb)
  298. {
  299. return encode(vlb.get());
  300. }
  301. } // namespace bencode2
  302. } // namespace aria2