bencode.cc 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 "bencode.h"
  36. #include <fstream>
  37. #include <sstream>
  38. #include "StringFormat.h"
  39. #include "Util.h"
  40. namespace aria2 {
  41. namespace bencode {
  42. const BDE BDE::none;
  43. BDE::BDE():_type(TYPE_NONE) {}
  44. BDE::BDE(Integer integer):_type(TYPE_INTEGER),
  45. _bobject(new BInteger(integer)) {}
  46. BDE::BDE(const std::string& string):_type(TYPE_STRING),
  47. _bobject(new BString(std::string(string))) {}
  48. BDE::BDE(const char* cstring):_type(TYPE_STRING),
  49. _bobject(new BString(std::string(cstring))) {}
  50. BDE::BDE(const char* data, size_t length):
  51. _type(TYPE_STRING),
  52. _bobject(new BString(std::string(&data[0], &data[length]))) {}
  53. BDE::BDE(const unsigned char* data, size_t length):
  54. _type(TYPE_STRING),
  55. _bobject(new BString(std::string(&data[0], &data[length]))) {}
  56. BDE BDE::dict()
  57. {
  58. BDE bde;
  59. bde._type = TYPE_DICT;
  60. bde._bobject.reset(new BDict());
  61. return bde;
  62. }
  63. BDE BDE::list()
  64. {
  65. BDE bde;
  66. bde._type = TYPE_LIST;
  67. bde._bobject.reset(new BList());
  68. return bde;
  69. }
  70. // Test for Null data
  71. bool BDE::isNone() const
  72. {
  73. return _type == TYPE_NONE;
  74. }
  75. // Integer Interface
  76. bool BDE::isInteger() const
  77. {
  78. return _type == TYPE_INTEGER;
  79. }
  80. BDE::Integer BDE::i() const
  81. {
  82. return _bobject->i();
  83. }
  84. // String Interface
  85. bool BDE::isString() const
  86. {
  87. return _type == TYPE_STRING;
  88. }
  89. const std::string& BDE::s() const
  90. {
  91. return _bobject->s();
  92. }
  93. const unsigned char* BDE::uc() const
  94. {
  95. return _bobject->uc();
  96. }
  97. // Dictionary Interface
  98. bool BDE::isDict() const
  99. {
  100. return _type == TYPE_DICT;
  101. }
  102. BDE& BDE::operator[](const std::string& key)
  103. {
  104. return _bobject->operator[](key);
  105. }
  106. const BDE& BDE::operator[](const std::string& key) const
  107. {
  108. if(_bobject->containsKey(key)) {
  109. return _bobject->operator[](key);
  110. } else {
  111. return none;
  112. }
  113. }
  114. bool BDE::containsKey(const std::string& key) const
  115. {
  116. return _bobject->containsKey(key);
  117. }
  118. void BDE::removeKey(const std::string& key)
  119. {
  120. _bobject->removeKey(key);
  121. }
  122. BDE::Dict::iterator BDE::dictBegin()
  123. {
  124. return _bobject->dictBegin();
  125. }
  126. BDE::Dict::const_iterator BDE::dictBegin() const
  127. {
  128. return _bobject->dictBegin();
  129. }
  130. BDE::Dict::iterator BDE::dictEnd()
  131. {
  132. return _bobject->dictEnd();
  133. }
  134. BDE::Dict::const_iterator BDE::dictEnd() const
  135. {
  136. return _bobject->dictEnd();
  137. }
  138. // List Interface
  139. bool BDE::isList() const
  140. {
  141. return _type == TYPE_LIST;
  142. }
  143. void BDE::append(const BDE& bde)
  144. {
  145. _bobject->append(bde);
  146. }
  147. void BDE::operator<<(const BDE& bde)
  148. {
  149. _bobject->operator<<(bde);
  150. }
  151. BDE& BDE::operator[](size_t index)
  152. {
  153. return _bobject->operator[](index);
  154. }
  155. const BDE& BDE::operator[](size_t index) const
  156. {
  157. return _bobject->operator[](index);
  158. }
  159. BDE::List::iterator BDE::listBegin()
  160. {
  161. return _bobject->listBegin();
  162. }
  163. BDE::List::const_iterator BDE::listBegin() const
  164. {
  165. return _bobject->listBegin();
  166. }
  167. BDE::List::iterator BDE::listEnd()
  168. {
  169. return _bobject->listEnd();
  170. }
  171. BDE::List::const_iterator BDE::listEnd() const
  172. {
  173. return _bobject->listEnd();
  174. }
  175. // Callable from List and Dict
  176. size_t BDE::size() const
  177. {
  178. return _bobject->size();
  179. }
  180. // Callable from List and Dict
  181. bool BDE::empty() const
  182. {
  183. return _bobject->empty();
  184. }
  185. static BDE decodeiter(std::istream& ss);
  186. static void checkdelim(std::istream& ss, const char delim = ':')
  187. {
  188. char d;
  189. if(!(ss.get(d) && d == delim)) {
  190. throw RecoverableException
  191. (StringFormat("Delimiter '%c' not found.", delim).str());
  192. }
  193. }
  194. static std::string decoderawstring(std::istream& ss)
  195. {
  196. size_t length;
  197. ss >> length;
  198. if(!ss) {
  199. throw RecoverableException("A positive integer expected but none found.");
  200. }
  201. // TODO check length, it must be less than or equal to INT_MAX
  202. checkdelim(ss);
  203. char* buf = new char[length];
  204. ss.read(buf, length);
  205. std::string str(&buf[0], &buf[length]);
  206. delete [] buf;
  207. if(ss.gcount() != static_cast<int>(length)) {
  208. throw RecoverableException
  209. (StringFormat("Expected %lu bytes of data, but only %d read.",
  210. static_cast<unsigned long>(length), ss.gcount()).str());
  211. }
  212. return str;
  213. }
  214. static BDE decodestring(std::istream& ss)
  215. {
  216. return BDE(decoderawstring(ss));
  217. }
  218. static BDE decodeinteger(std::istream& ss)
  219. {
  220. BDE::Integer integer;
  221. ss >> integer;
  222. if(!ss) {
  223. throw RecoverableException("Integer expected but none found");
  224. }
  225. checkdelim(ss, 'e');
  226. return BDE(integer);
  227. }
  228. static BDE decodedict(std::istream& ss)
  229. {
  230. BDE dict = BDE::dict();
  231. char c;
  232. while(ss.get(c)) {
  233. if(c == 'e') {
  234. return dict;
  235. } else {
  236. ss.unget();
  237. std::string key = decoderawstring(ss);
  238. dict[key] = decodeiter(ss);
  239. }
  240. }
  241. throw RecoverableException("Unexpected EOF in dict context. 'e' expected.");
  242. }
  243. static BDE decodelist(std::istream& ss)
  244. {
  245. BDE list = BDE::list();
  246. char c;
  247. while(ss.get(c)) {
  248. if(c == 'e') {
  249. return list;
  250. } else {
  251. ss.unget();
  252. list << decodeiter(ss);
  253. }
  254. }
  255. throw RecoverableException("Unexpected EOF in list context. 'e' expected.");
  256. }
  257. static BDE decodeiter(std::istream& ss)
  258. {
  259. char c;
  260. if(!ss.get(c)) {
  261. throw RecoverableException("Unexpected EOF in term context."
  262. " 'd', 'l', 'i' or digit is expected.");
  263. }
  264. if(c == 'd') {
  265. return decodedict(ss);
  266. } else if(c == 'l') {
  267. return decodelist(ss);
  268. } else if(c == 'i') {
  269. return decodeinteger(ss);
  270. } else {
  271. ss.unget();
  272. return decodestring(ss);
  273. }
  274. }
  275. BDE decode(std::istream& in)
  276. {
  277. return decodeiter(in);
  278. }
  279. BDE decode(const std::string& s)
  280. {
  281. if(s.empty()) {
  282. return BDE::none;
  283. }
  284. std::istringstream ss(s);
  285. return decodeiter(ss);
  286. }
  287. BDE decode(const unsigned char* data, size_t length)
  288. {
  289. return decode(std::string(&data[0], &data[length]));
  290. }
  291. BDE decodeFromFile(const std::string& filename)
  292. {
  293. std::ifstream f(filename.c_str(), std::ios::binary);
  294. if(f) {
  295. return decode(f);
  296. } else {
  297. throw RecoverableException
  298. (StringFormat("Cannot open file '%s'.", filename.c_str()).str());
  299. }
  300. }
  301. static void encodeIter(std::ostream& o, const BDE& bde)
  302. {
  303. if(bde.isInteger()) {
  304. o << "i" << bde.i() << "e";
  305. } else if(bde.isString()) {
  306. const std::string& s = bde.s();
  307. o << s.size() << ":";
  308. o.write(s.data(), s.size());
  309. } else if(bde.isDict()) {
  310. o << "d";
  311. for(BDE::Dict::const_iterator i = bde.dictBegin(); i != bde.dictEnd(); ++i){
  312. const std::string& key = (*i).first;
  313. o << key.size() << ":";
  314. o.write(key.data(), key.size());
  315. encodeIter(o, (*i).second);
  316. }
  317. o << "e";
  318. } else if(bde.isList()) {
  319. o << "l";
  320. for(BDE::List::const_iterator i = bde.listBegin(); i != bde.listEnd(); ++i){
  321. encodeIter(o, *i);
  322. }
  323. o << "e";
  324. }
  325. }
  326. std::string encode(const BDE& bde)
  327. {
  328. std::ostringstream ss;
  329. encodeIter(ss, bde);
  330. return ss.str();
  331. }
  332. } // namespace bencode
  333. } // namespace aria2