bencode2.cc 6.9 KB

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