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_32bit.class.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <?php
  2. # todo: Replace this 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 strings with an [*INT*] marker
  24. - Can be stored an an int on 64 bit boxes for uber speed (we do this)
  25. - If stored as an int on 32 bit boxes, it won't allow for any size over 2 gigs
  26. * Lists
  27. - Stored as a BENCODE_LIST object.
  28. - The actual list is in BENCODE_LIST::$Val, as an array with incrementing integer indices
  29. - The list in BENCODE_LIST::$Val is populated by the BENCODE_LIST::dec() function
  30. * Dictionaries
  31. - Stored as a BENCODE_DICT object.
  32. - The actual list is in BENCODE_DICT::$Val, as an array with incrementing integer indices
  33. - The list in BENCODE_DICT::$Val is populated by the BENCODE_DICT::dec() function
  34. //----- BENCODE_* Objects -----//
  35. Lists and dictionaries are stored as objects. They each have the following
  36. functions:
  37. * decode(Type, $Key)
  38. - Decodes ANY bencoded element, given the type and the key
  39. - Gets the position and string from $this
  40. * encode($Val)
  41. - Encodes ANY non-bencoded element, given the value
  42. * dec()
  43. - Decodes either a dictionary or a list, depending on where it's called from
  44. - Uses the decode() function quite a bit
  45. * enc()
  46. - Encodes either a dictionary or a list, depending on where it's called from
  47. - Relies mostly on the encode() function
  48. Finally, as all torrents are just large dictionaries, the TORRENT class extends
  49. the BENCODE_DICT class.
  50. **Note** The version we run doesn't store ints as strings marked with [*INT*]
  51. We store them as php integers. You can do this too for added speed and reduced
  52. hackery, if you're running a 64 bit box, or if you're running a 32 bit box and
  53. don't care about files larger than 2 gigs. The system with the [*INT*]s was
  54. coded up in around 4 minutes for STC when we discovered this problem, then
  55. discovered that floats aren't accurate enough to use. :(
  56. *******************************************************************************/
  57. class BENCODE2
  58. {
  59. public $Val; // Decoded array
  60. public $Pos = 1; // Pointer that indicates our position in the string
  61. public $Str = ''; // Torrent string
  62. public function __construct($Val, $IsParsed = false)
  63. {
  64. if (!$IsParsed) {
  65. $this->Str = $Val;
  66. $this->dec();
  67. } else {
  68. $this->Val = $Val;
  69. }
  70. }
  71. // Decode an element based on the type
  72. public function decode($Type, $Key)
  73. {
  74. if (ctype_digit($Type)) { // Element is a string
  75. // Get length of string
  76. $StrLen = $Type;
  77. while ($this->Str[$this->Pos + 1] != ':') {
  78. $this->Pos++;
  79. $StrLen.=$this->Str[$this->Pos];
  80. }
  81. $this->Val[$Key] = substr($this->Str, $this->Pos + 2, $StrLen);
  82. $this->Pos += $StrLen;
  83. $this->Pos += 2;
  84. } elseif ($Type == 'i') { // Element is an int
  85. $this->Pos++;
  86. // Find end of integer (first occurance of 'e' after position)
  87. $End = strpos($this->Str, 'e', $this->Pos);
  88. // Get the integer, and mark it as an int (on our version 64 bit box, we cast it to an int)
  89. $this->Val[$Key] = '[*INT*]'.substr($this->Str, $this->Pos, $End-$this->Pos);
  90. $this->Pos = $End + 1;
  91. } elseif ($Type == 'l') { // Element is a list
  92. $this->Val[$Key] = new BENCODE_LIST(substr($this->Str, $this->Pos));
  93. $this->Pos += $this->Val[$Key]->Pos;
  94. } elseif ($Type == 'd') { // Element is a dictionary
  95. $this->Val[$Key] = new BENCODE_DICT(substr($this->Str, $this->Pos));
  96. $this->Pos += $this->Val[$Key]->Pos;
  97. // Sort by key to respect spec
  98. ksort($this->Val[$Key]->Val);
  99. } else {
  100. die('Invalid torrent file');
  101. }
  102. }
  103. public function encode($Val)
  104. {
  105. if (is_string($Val)) {
  106. if (substr($Val, 0, 7) == '[*INT*]') {
  107. return 'i'.substr($Val, 7).'e';
  108. } else {
  109. return strlen($Val).':'.$Val;
  110. }
  111. } elseif (is_object($Val)) {
  112. return $Val->enc();
  113. } else {
  114. return 'fail';
  115. }
  116. }
  117. }
  118. class BENCODE_LIST extends BENCODE2
  119. {
  120. public function enc()
  121. {
  122. $Str = 'l';
  123. foreach ($this->Val as $Value) {
  124. $Str.=$this->encode($Value);
  125. }
  126. return $Str.'e';
  127. }
  128. // Decode a list
  129. public function dec()
  130. {
  131. $Key = 0; // Array index
  132. $Length = strlen($this->Str);
  133. while ($this->Pos<$Length) {
  134. $Type = $this->Str[$this->Pos];
  135. // $Type now indicates what type of element we're dealing with
  136. // It's either an integer (string), 'i' (an integer), 'l' (a list), 'd' (a dictionary), or 'e' (end of dictionary/list)
  137. if ($Type == 'e') { // End of list
  138. $this->Pos += 1;
  139. 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.
  140. return;
  141. }
  142. // Decode the bencoded element.
  143. // This function changes $this->Pos and $this->Val, so you don't have to.
  144. $this->decode($Type, $Key);
  145. ++ $Key;
  146. }
  147. return true;
  148. }
  149. }
  150. class BENCODE_DICT extends BENCODE2
  151. {
  152. public function enc()
  153. {
  154. $Str = 'd';
  155. foreach ($this->Val as $Key => $Value) {
  156. $Str.=strlen($Key).':'.$Key.$this->encode($Value);
  157. }
  158. return $Str.'e';
  159. }
  160. // Decode a dictionary
  161. public function dec()
  162. {
  163. $Length = strlen($this->Str);
  164. while ($this->Pos < $Length) {
  165. if ($this->Str[$this->Pos] == 'e') { // End of dictionary
  166. $this->Pos += 1;
  167. 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.
  168. return;
  169. }
  170. // Get the dictionary key
  171. // Length of the key, in bytes
  172. $KeyLen = $this->Str[$this->Pos];
  173. // Allow for multi-digit lengths
  174. while ($this->Str[$this->Pos + 1] != ':' && $this->Pos + 1 < $Length) {
  175. $this->Pos++;
  176. $KeyLen.=$this->Str[$this->Pos];
  177. }
  178. // $this->Pos is now on the last letter of the key length
  179. // Adding 2 brings it past that character and the ':' to the beginning of the string
  180. $this->Pos+=2;
  181. // Get the name of the key
  182. $Key = substr($this->Str, $this->Pos, $KeyLen);
  183. // Move the position past the key to the beginning of the element
  184. $this->Pos += $KeyLen;
  185. $Type = $this->Str[$this->Pos];
  186. // $Type now indicates what type of element we're dealing with
  187. // It's either an integer (string), 'i' (an integer), 'l' (a list), 'd' (a dictionary), or 'e' (end of dictionary/list)
  188. // Decode the bencoded element.
  189. // This function changes $this->Pos and $this->Val, so you don't have to.
  190. $this->decode($Type, $Key);
  191. }
  192. return true;
  193. }
  194. }
  195. class TORRENT extends BENCODE_DICT
  196. {
  197. public function dump()
  198. {
  199. // Convenience function used for testing and figuring out how we store the data
  200. print_r($this->Val);
  201. }
  202. public function dump_data()
  203. {
  204. // Function which serializes $this->Val for storage
  205. return base64_encode(serialize($this->Val));
  206. }
  207. public function set_announce_url($Announce)
  208. {
  209. $this->Val['announce'] = $Announce;
  210. ksort($this->Val);
  211. }
  212. // Returns an array of:
  213. // * the files in the torrent
  214. // * the total size of files described therein
  215. public function file_list()
  216. {
  217. $FileList = [];
  218. if (!isset($this->Val['info']->Val['files'])) { // Single file mode
  219. $TotalSize = substr($this->Val['info']->Val['length'], 7);
  220. $FileList[] = array($TotalSize, $this->get_name());
  221. } else { // Multiple file mode
  222. $FileNames = [];
  223. $FileSizes = [];
  224. $TotalSize = 0;
  225. $Files = $this->Val['info']->Val['files']->Val;
  226. if (isset($Files[0]->Val['path.utf-8'])) {
  227. $PathKey = 'path.utf-8';
  228. } else {
  229. $PathKey = 'path';
  230. }
  231. foreach ($Files as $File) {
  232. $FileSize = substr($File->Val['length'], 7);
  233. $TotalSize += $FileSize;
  234. $FileName = ltrim(implode('/', $File->Val[$PathKey]->Val), '/');
  235. $FileSizes[] = $FileSize;
  236. $FileNames[] = $FileName;
  237. }
  238. natcasesort($FileNames);
  239. foreach ($FileNames as $Index => $FileName) {
  240. $FileList[] = array($FileSizes[$Index], $FileName);
  241. }
  242. }
  243. return array($TotalSize, $FileList);
  244. }
  245. public function get_name()
  246. {
  247. if (isset($this->Val['info']->Val['name.utf-8'])) {
  248. return $this->Val['info']->Val['name.utf-8'];
  249. } else {
  250. return $this->Val['info']->Val['name'];
  251. }
  252. }
  253. public function make_private()
  254. {
  255. //----- The following properties do not affect the infohash:
  256. // anounce-list is an unofficial extension to the protocol
  257. // that allows for multiple trackers per torrent
  258. unset($this->Val['announce-list']);
  259. // Bitcomet & Azureus cache peers in here
  260. unset($this->Val['nodes']);
  261. // Azureus stores the dht_backup_enable flag here
  262. unset($this->Val['azureus_properties']);
  263. // Remove web-seeds
  264. unset($this->Val['url-list']);
  265. // Remove libtorrent resume info
  266. unset($this->Val['libtorrent_resume']);
  267. //----- End properties that do not affect the infohash
  268. if (!empty($this->Val['info']->Val['private']) && $this->Val['info']->Val['private'] == '[*INT*]1') {
  269. return true;
  270. } else {
  271. // Torrent is not private!
  272. // add private tracker flag and sort info dictionary
  273. $this->Val['info']->Val['private'] = '[*INT*]1';
  274. ksort($this->Val['info']->Val);
  275. return false;
  276. }
  277. }
  278. }