BioTorrents.de’s version of Gazelle
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

torrent.class.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. <?php
  2. # todo: Rplace with https://github.com/OPSnet/bencode-torrent
  3. /*******************************************************************************
  4. |~~~~ Gazelle bencode parser ~~~~|
  5. --------------------------------------------------------------------------------
  6. Welcome to the Gazelle bencode parser. bencoding is the way of encoding data
  7. that bittorrent uses in torrent files. When we read the torrent files, we get
  8. one long string that must be parsed into a format we can easily edit - that's
  9. where this file comes into play.
  10. There are 4 data types in bencode:
  11. * String
  12. * Int
  13. * List - array without keys
  14. - like array('value', 'value 2', 'value 3', 'etc')
  15. * Dictionary - array with string keys
  16. - like array['key 1'] = 'value 1'; array['key 2'] = 'value 2';
  17. Before you go any further, we recommend reading the sections on bencoding and
  18. metainfo file structure here: http://wiki.theory.org/BitTorrentSpecification
  19. //----- How we store the data -----//
  20. * Strings
  21. - Stored as php strings. Not difficult to remember.
  22. * Integers
  23. - Stored as php ints
  24. - must be casted with (int)
  25. * Lists
  26. - Stored as a BENCODE_LIST object.
  27. - The actual list is in BENCODE_LIST::$Val, as an array with incrementing integer indices
  28. - The list in BENCODE_LIST::$Val is populated by the BENCODE_LIST::dec() function
  29. * Dictionaries
  30. - Stored as a BENCODE_DICT object.
  31. - The actual list is in BENCODE_DICT::$Val, as an array with string indices
  32. - The list in BENCODE_DICT::$Val is populated by the BENCODE_DICT::dec() function
  33. //----- BENCODE_* Objects -----//
  34. Lists and dictionaries are stored as objects. They each have the following
  35. functions:
  36. * decode(Type, $Key)
  37. - Decodes ANY bencoded element, given the type and the key
  38. - Gets the position and string from $this
  39. * encode($Val)
  40. - Encodes ANY non-bencoded element, given the value
  41. * dec()
  42. - Decodes either a dictionary or a list, depending on where it's called from
  43. - Uses the decode() function quite a bit
  44. * enc()
  45. - Encodes either a dictionary or a list, depending on where it's called from
  46. - Relies mostly on the encode() function
  47. Finally, as all torrents are just large dictionaries, the TORRENT class extends
  48. the BENCODE_DICT class.
  49. *******************************************************************************/
  50. class BENCODE2
  51. {
  52. public $Val; // Decoded array
  53. public $Pos = 1; // Pointer that indicates our position in the string
  54. public $Str = ''; // Torrent string
  55. public function __construct($Val, $IsParsed = false)
  56. {
  57. if (!$IsParsed) {
  58. $this->Str = $Val;
  59. $this->dec();
  60. } else {
  61. $this->Val = $Val;
  62. }
  63. }
  64. // Decode an element based on the type. The type is really just an indicator.
  65. public function decode($Type, $Key)
  66. {
  67. if (is_number($Type)) { // Element is a string
  68. // Get length of string
  69. $StrLen = $Type;
  70. while ($this->Str[$this->Pos + 1] !== ':') {
  71. $this->Pos++;
  72. $StrLen.=$this->Str[$this->Pos];
  73. }
  74. $this->Val[$Key] = substr($this->Str, $this->Pos + 2, $StrLen);
  75. $this->Pos += $StrLen;
  76. $this->Pos += 2;
  77. } elseif ($Type === 'i') { // Element is an int
  78. $this->Pos++;
  79. // Find end of integer (first occurance of 'e' after position)
  80. $End = strpos($this->Str, 'e', $this->Pos);
  81. // Get the integer, and - IMPORTANT - cast it as an int, so we know later that it's an int and not a string
  82. $this->Val[$Key] = (int)substr($this->Str, $this->Pos, $End-$this->Pos);
  83. $this->Pos = $End + 1;
  84. } elseif ($Type === 'l') { // Element is a list
  85. $this->Val[$Key] = new BENCODE_LIST(substr($this->Str, $this->Pos));
  86. $this->Pos += $this->Val[$Key]->Pos;
  87. } elseif ($Type === 'd') { // Element is a dictionary
  88. $this->Val[$Key] = new BENCODE_DICT(substr($this->Str, $this->Pos));
  89. $this->Pos += $this->Val[$Key]->Pos;
  90. // Sort by key to respect spec
  91. if (!empty($this->Val[$Key]->Val)) {
  92. ksort($this->Val[$Key]->Val);
  93. }
  94. } else {
  95. die('Invalid torrent file');
  96. }
  97. }
  98. public function encode($Val)
  99. {
  100. if (is_int($Val)) { // Integer
  101. return 'i'.$Val.'e';
  102. } elseif (is_string($Val)) {
  103. return strlen($Val).':'.$Val;
  104. } elseif (is_object($Val)) {
  105. return $Val->enc();
  106. } else {
  107. return 'fail';
  108. }
  109. }
  110. }
  111. class BENCODE_LIST extends BENCODE2
  112. {
  113. public function enc()
  114. {
  115. if (empty($this->Val)) {
  116. return 'le';
  117. }
  118. $Str = 'l';
  119. reset($this->Val);
  120. foreach ($this->Val as $Value) {
  121. $Str.=$this->encode($Value);
  122. }
  123. return $Str.'e';
  124. }
  125. // Decode a list
  126. public function dec()
  127. {
  128. $Key = 0; // Array index
  129. $Length = strlen($this->Str);
  130. while ($this->Pos < $Length) {
  131. $Type = $this->Str[$this->Pos];
  132. // $Type now indicates what type of element we're dealing with
  133. // It's either an integer (string), 'i' (an integer), 'l' (a list), 'd' (a dictionary), or 'e' (end of dictionary/list)
  134. if ($Type === 'e') { // End of list
  135. $this->Pos += 1;
  136. unset($this->Str); // Since we're finished parsing the string, we don't need to store it anymore. Benchmarked - this makes the parser run way faster
  137. return;
  138. }
  139. // Decode the bencoded element
  140. // This function changes $this->Pos and $this->Val, so you don't have to
  141. $this->decode($Type, $Key);
  142. ++$Key;
  143. }
  144. return true;
  145. }
  146. }
  147. class BENCODE_DICT extends BENCODE2
  148. {
  149. public function enc()
  150. {
  151. if (empty($this->Val)) {
  152. return 'de';
  153. }
  154. $Str = 'd';
  155. reset($this->Val);
  156. foreach ($this->Val as $Key => $Value) {
  157. $Str.=strlen($Key).':'.$Key.$this->encode($Value);
  158. }
  159. return $Str.'e';
  160. }
  161. // Decode a dictionary
  162. public function dec()
  163. {
  164. $Length = strlen($this->Str);
  165. while ($this->Pos<$Length) {
  166. if ($this->Str[$this->Pos] === 'e') { // End of dictionary
  167. $this->Pos += 1;
  168. unset($this->Str); // Since we're finished parsing the string, we don't need to store it anymore. Benchmarked - this makes the parser run way faster
  169. return;
  170. }
  171. // Get the dictionary key
  172. // Length of the key, in bytes
  173. $KeyLen = $this->Str[$this->Pos];
  174. // Allow for multi-digit lengths
  175. while ($this->Str[$this->Pos + 1] !== ':' && $this->Pos + 1 < $Length) {
  176. $this->Pos++;
  177. $KeyLen.=$this->Str[$this->Pos];
  178. }
  179. // $this->Pos is now on the last letter of the key length
  180. // Adding 2 brings it past that character and the ':' to the beginning of the string
  181. $this->Pos += 2;
  182. // Get the name of the key
  183. $Key = substr($this->Str, $this->Pos, $KeyLen);
  184. // Move the position past the key to the beginning of the element
  185. $this->Pos += $KeyLen;
  186. $Type = $this->Str[$this->Pos];
  187. // $Type now indicates what type of element we're dealing with
  188. // It's either an integer (string), 'i' (an integer), 'l' (a list), 'd' (a dictionary), or 'e' (end of dictionary/list)
  189. // Decode the bencoded element
  190. // This function changes $this->Pos and $this->Val, so you don't have to
  191. $this->decode($Type, $Key);
  192. }
  193. return true;
  194. }
  195. }
  196. class TORRENT extends BENCODE_DICT
  197. {
  198. public function dump()
  199. {
  200. // Convenience function used for testing and figuring out how we store the data
  201. print_r($this->Val);
  202. }
  203. public function dump_data()
  204. {
  205. // Function which serializes $this->Val for storage
  206. return base64_encode(serialize($this->Val));
  207. }
  208. public function set_announce_list($UrlsList)
  209. {
  210. $AnnounceList = new BENCODE_LIST([], true);
  211. foreach ($UrlsList as $Urls) {
  212. $SubList = new BENCODE_LIST($Urls, true);
  213. unset($SubList->Str);
  214. $AnnounceList->Val[] = $SubList;
  215. }
  216. $this->Val['announce-list'] = $AnnounceList;
  217. }
  218. public function set_announce_url($Announce)
  219. {
  220. $this->Val['announce'] = $Announce;
  221. ksort($this->Val);
  222. }
  223. // Returns an array of:
  224. // * the files in the torrent
  225. // * the total size of files described therein
  226. public function file_list()
  227. {
  228. $FileList = [];
  229. if (!isset($this->Val['info']->Val['files'])) { // Single file mode
  230. $TotalSize = $this->Val['info']->Val['length'];
  231. $FileList[] = array($TotalSize, $this->get_name());
  232. } else { // Multiple file mode
  233. $FileNames = [];
  234. $FileSizes = [];
  235. $TotalSize = 0;
  236. $Files = $this->Val['info']->Val['files']->Val;
  237. if (isset($Files[0]->Val['path.utf-8'])) {
  238. $PathKey = 'path.utf-8';
  239. } else {
  240. $PathKey = 'path';
  241. }
  242. foreach ($Files as $File) {
  243. $FileSize = $File->Val['length'];
  244. $TotalSize += $FileSize;
  245. $FileName = ltrim(implode('/', $File->Val[$PathKey]->Val), '/');
  246. $FileSizes[] = $FileSize;
  247. $FileNames[] = $FileName;
  248. }
  249. natcasesort($FileNames);
  250. foreach ($FileNames as $Index => $FileName) {
  251. $FileList[] = array($FileSizes[$Index], $FileName);
  252. }
  253. }
  254. return array($TotalSize, $FileList);
  255. }
  256. public function get_name()
  257. {
  258. if (isset($this->Val['info']->Val['name.utf-8'])) {
  259. return $this->Val['info']->Val['name.utf-8'];
  260. } else {
  261. return $this->Val['info']->Val['name'];
  262. }
  263. }
  264. public function make_private()
  265. {
  266. //----- The following properties do not affect the infohash:
  267. // anounce-list is an unofficial extension to the protocol
  268. // that allows for multiple trackers per torrent
  269. unset($this->Val['announce-list']);
  270. // Bitcomet & Azureus cache peers in here
  271. unset($this->Val['nodes']);
  272. // Azureus stores the dht_backup_enable flag here
  273. unset($this->Val['azureus_properties']);
  274. // Remove web-seeds
  275. unset($this->Val['url-list']);
  276. // Remove libtorrent resume info
  277. unset($this->Val['libtorrent_resume']);
  278. //----- End properties that do not affect the infohash
  279. if ($this->Val['info']->Val['private']) {
  280. return true; // Torrent is private
  281. } else {
  282. // Torrent is not private!
  283. // Add private tracker flag and sort info dictionary
  284. $this->Val['info']->Val['private'] = 1;
  285. ksort($this->Val['info']->Val);
  286. return false;
  287. }
  288. }
  289. }