bencode2.cc 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 <fstream>
  37. #include <sstream>
  38. #include "fmt.h"
  39. #include "DlAbortEx.h"
  40. #include "error_code.h"
  41. namespace aria2 {
  42. namespace bencode2 {
  43. namespace {
  44. SharedHandle<ValueBase> decodeiter(std::istream& ss, size_t depth);
  45. } // namespace
  46. namespace {
  47. void checkdelim(std::istream& ss, const char delim = ':')
  48. {
  49. char d;
  50. if(!(ss.get(d) && d == delim)) {
  51. throw DL_ABORT_EX2
  52. (fmt("Bencode decoding failed: Delimiter '%c' not found.",
  53. delim),
  54. error_code::BENCODE_PARSE_ERROR);
  55. }
  56. }
  57. } // namespace
  58. namespace {
  59. std::string decoderawstring(std::istream& ss)
  60. {
  61. int length;
  62. ss >> length;
  63. if(!ss || length < 0) {
  64. throw DL_ABORT_EX2("Bencode decoding failed:"
  65. " A positive integer expected but none found.",
  66. error_code::BENCODE_PARSE_ERROR);
  67. }
  68. // TODO check length, it must be less than or equal to INT_MAX
  69. checkdelim(ss);
  70. char* buf = new char[length];
  71. ss.read(buf, length);
  72. std::string str(&buf[0], &buf[length]);
  73. delete [] buf;
  74. if(ss.gcount() != static_cast<int>(length)) {
  75. throw DL_ABORT_EX2
  76. (fmt("Bencode decoding failed:"
  77. " Expected %lu bytes of data, but only %ld read.",
  78. static_cast<unsigned long>(length),
  79. static_cast<long int>(ss.gcount())),
  80. error_code::BENCODE_PARSE_ERROR);
  81. }
  82. return str;
  83. }
  84. } // namespace
  85. namespace {
  86. SharedHandle<ValueBase> decodestring(std::istream& ss)
  87. {
  88. return String::g(decoderawstring(ss));
  89. }
  90. } // namespace
  91. namespace {
  92. SharedHandle<ValueBase> decodeinteger(std::istream& ss)
  93. {
  94. Integer::ValueType iv;
  95. ss >> iv;
  96. if(!ss) {
  97. throw DL_ABORT_EX2("Bencode decoding failed:"
  98. " Integer expected but none found",
  99. error_code::BENCODE_PARSE_ERROR);
  100. }
  101. checkdelim(ss, 'e');
  102. return Integer::g(iv);
  103. }
  104. } // namespace
  105. namespace {
  106. SharedHandle<ValueBase> decodedict(std::istream& ss, size_t depth)
  107. {
  108. SharedHandle<Dict> dict = Dict::g();
  109. char c;
  110. while(ss.get(c)) {
  111. if(c == 'e') {
  112. return dict;
  113. } else {
  114. ss.unget();
  115. std::string key = decoderawstring(ss);
  116. dict->put(key, decodeiter(ss, depth));
  117. }
  118. }
  119. throw DL_ABORT_EX2("Bencode decoding failed:"
  120. " Unexpected EOF in dict context. 'e' expected.",
  121. error_code::BENCODE_PARSE_ERROR);
  122. }
  123. } // namespace
  124. namespace {
  125. SharedHandle<ValueBase> decodelist(std::istream& ss, size_t depth)
  126. {
  127. SharedHandle<List> list = List::g();
  128. char c;
  129. while(ss.get(c)) {
  130. if(c == 'e') {
  131. return list;
  132. } else {
  133. ss.unget();
  134. list->append(decodeiter(ss, depth));
  135. }
  136. }
  137. throw DL_ABORT_EX2("Bencode decoding failed:"
  138. " Unexpected EOF in list context. 'e' expected.",
  139. error_code::BENCODE_PARSE_ERROR);
  140. }
  141. } // namespace
  142. namespace {
  143. void checkDepth(size_t depth)
  144. {
  145. if(depth >= MAX_STRUCTURE_DEPTH) {
  146. throw DL_ABORT_EX2("Bencode decoding failed: Structure is too deep.",
  147. error_code::BENCODE_PARSE_ERROR);
  148. }
  149. }
  150. } // namespace
  151. namespace {
  152. SharedHandle<ValueBase> decodeiter(std::istream& ss, size_t depth)
  153. {
  154. checkDepth(depth);
  155. char c;
  156. if(!ss.get(c)) {
  157. throw DL_ABORT_EX2("Bencode decoding failed:"
  158. " Unexpected EOF in term context."
  159. " 'd', 'l', 'i' or digit is expected.",
  160. error_code::BENCODE_PARSE_ERROR);
  161. }
  162. if(c == 'd') {
  163. return decodedict(ss, depth+1);
  164. } else if(c == 'l') {
  165. return decodelist(ss, depth+1);
  166. } else if(c == 'i') {
  167. return decodeinteger(ss);
  168. } else {
  169. ss.unget();
  170. return decodestring(ss);
  171. }
  172. }
  173. } // namespace
  174. SharedHandle<ValueBase> decode(std::istream& in)
  175. {
  176. return decodeiter(in, 0);
  177. }
  178. SharedHandle<ValueBase> decode(const std::string& s)
  179. {
  180. size_t end;
  181. return decode(s, end);
  182. }
  183. SharedHandle<ValueBase> decode(const std::string& s, size_t& end)
  184. {
  185. if(s.empty()) {
  186. return SharedHandle<ValueBase>();
  187. }
  188. std::istringstream ss(s);
  189. SharedHandle<ValueBase> vlb = decodeiter(ss, 0);
  190. end = ss.tellg();
  191. return vlb;
  192. }
  193. SharedHandle<ValueBase> decode(const unsigned char* data, size_t length)
  194. {
  195. return decode(std::string(&data[0], &data[length]));
  196. }
  197. SharedHandle<ValueBase> decode(const unsigned char* data, size_t length, size_t& end)
  198. {
  199. return decode(std::string(&data[0], &data[length]), end);
  200. }
  201. SharedHandle<ValueBase> decodeFromFile(const std::string& filename)
  202. {
  203. std::ifstream f(filename.c_str(), std::ios::binary);
  204. if(f) {
  205. return decode(f);
  206. } else {
  207. throw DL_ABORT_EX2
  208. (fmt("Bencode decoding failed: Cannot open file '%s'.",
  209. filename.c_str()),
  210. error_code::BENCODE_PARSE_ERROR);
  211. }
  212. }
  213. std::string encode(const ValueBase* vlb)
  214. {
  215. class BencodeValueBaseVisitor:public ValueBaseVisitor {
  216. private:
  217. std::ostringstream out_;
  218. public:
  219. virtual void visit(const String& string)
  220. {
  221. const std::string& s = string.s();
  222. out_ << s.size() << ":";
  223. out_.write(s.data(), s.size());
  224. }
  225. virtual void visit(const Integer& integer)
  226. {
  227. out_ << "i" << integer.i() << "e";
  228. }
  229. virtual void visit(const List& list)
  230. {
  231. out_ << "l";
  232. for(List::ValueType::const_iterator i = list.begin(), eoi = list.end();
  233. i != eoi; ++i){
  234. (*i)->accept(*this);
  235. }
  236. out_ << "e";
  237. }
  238. virtual void visit(const Dict& dict)
  239. {
  240. out_ << "d";
  241. for(Dict::ValueType::const_iterator i = dict.begin(), eoi = dict.end();
  242. i != eoi; ++i){
  243. const std::string& key = (*i).first;
  244. out_ << key.size() << ":";
  245. out_.write(key.data(), key.size());
  246. (*i).second->accept(*this);
  247. }
  248. out_ << "e";
  249. }
  250. std::string getResult() const
  251. {
  252. return out_.str();
  253. }
  254. };
  255. BencodeValueBaseVisitor visitor;
  256. vlb->accept(visitor);
  257. return visitor.getResult();
  258. }
  259. std::string encode(const SharedHandle<ValueBase>& vlb)
  260. {
  261. return encode(vlb.get());
  262. }
  263. } // namespace bencode2
  264. } // namespace aria2