PHPIN.NET

 找回密码
 立即注册
查看: 7055|回复: 0

[PHP类\函数] lightbenc.php:PHP解析torrent内容类

[复制链接]

469

主题

31

回帖

5497

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
5497
发表于 2015-9-26 10:03:35 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
lightbenc.php:PHP解析torrent内容类

lightbenc.php:
  1. <?php
  2. /* lightbenc.php


  3.         Dear Bram Cohen,
  4.                 You are an arse
  5.         WHAT were you smoking ?



  6. This implementation should use one order of magnitude less memory then the TBdev version.
  7. The bdecoding speed is similar to TBdev, bencoding is faster, and much faster then bdecoding.

  8. Call the bdecode() function with the bencoded string:

  9. $str="d7:oneListl8:a stringe10:oneIntegeri34ee";
  10. var_dump(bdecode($str));

  11. array(3) {
  12.   ["oneList"]=>
  13.   array(1) {
  14.     [0]=>
  15.     string(8) "a string"
  16.   }
  17.   ["oneInteger"]=>
  18.   int(34)
  19.   ["isDct"]=>
  20.   bool(true)
  21. }

  22. The returned value is a nested data type with the following type of elements:
  23. - ints    (test type with is_integer($x))
  24. - strings (test type with is_string($x))
  25. - lists   (test type with is_array($x) && !isset($x[isDct])
  26. - dicts   (test type with is_array($x) && isset($x[isDct])

  27. All elements have the native PHP type, except for the dictionary which is an array with an "isDct" key.
  28. This is necessary since PHP makes no distinction between flat and associative arrays. Note that the isDct
  29. key is allways set as a bool, so that even if the dictionary contains an actual "isDct" value, the
  30. functions behave transparently, i.e. they don't strip out or overwrite actual "isDct" keys.

  31. As such, this implementation is not a drop-in replacement of the TBDev code, hence the new function names
  32. For all practical purposes, it's just as flexible, and very easy to use. For example:

  33. // decode the torrent file
  34. $dict= bdecode_file($torrentfilename);
  35. // change announce url
  36. $dict['announce']='http://inferno.demonoid.com';
  37. // add private tracker flag
  38. $dict['info']['private']=1;
  39. // compute infohash
  40. $infohash = pack("H*", sha1(bencode($dict["info"])));
  41. // recreate the torrent file
  42. $torrentfile=bencode($dict);

  43. After calling bencode(), the passed nested array will have all it's dictionaries sorted by key.
  44. The bencoded data generated by bencode() will have sorted dictionaries, but bdecode() does not require
  45. this in the input stream, and will keep the order unchanged.

  46. This implementation is hereby released under the GFYPL, version 1.00.


  47.         The Go Fuck Yourself Public License, version 1.00

  48.         Article 1
  49.         You can go fuck yourself.

  50.         END OF ALL TERMS AND CONDITIONS

  51. */
  52. class Lightbenc{
  53.     public static function bdecode($s, &$pos=0) {
  54.         if($pos>=strlen($s)) {
  55.             return null;
  56.         }
  57.         switch($s[$pos]){
  58.         case 'd':
  59.             $pos++;
  60.             $retval=array();
  61.             while ($s[$pos]!='e'){
  62.                 $key=Lightbenc::bdecode($s, $pos);
  63.                 $val=Lightbenc::bdecode($s, $pos);
  64.                 if ($key===null || $val===null)
  65.                     break;
  66.                 $retval[$key]=$val;
  67.             }
  68.             $retval["isDct"]=true;
  69.             $pos++;
  70.             return $retval;

  71.         case 'l':
  72.             $pos++;
  73.             $retval=array();
  74.             while ($s[$pos]!='e'){
  75.                 $val=Lightbenc::bdecode($s, $pos);
  76.                 if ($val===null)
  77.                     break;
  78.                 $retval[]=$val;
  79.             }
  80.             $pos++;
  81.             return $retval;

  82.         case 'i':
  83.             $pos++;
  84.             $digits=strpos($s, 'e', $pos)-$pos;
  85.             $val=(int)substr($s, $pos, $digits);
  86.             $pos+=$digits+1;
  87.             return $val;

  88.     //        case "0": case "1": case "2": case "3": case "4":
  89.     //        case "5": case "6": case "7": case "8": case "9":
  90.         default:
  91.             $digits=strpos($s, ':', $pos)-$pos;
  92.             if ($digits<0 || $digits >20)
  93.                 return null;
  94.             $len=(int)substr($s, $pos, $digits);
  95.             $pos+=$digits+1;
  96.             $str=substr($s, $pos, $len);
  97.             $pos+=$len;
  98.             //echo "pos: $pos str: [$str] len: $len digits: $digits\n";
  99.             return (string)$str;
  100.         }
  101.         return null;
  102.     }

  103.     public static function bencode(&$d){
  104.         if(is_array($d)){
  105.             $ret="l";
  106.             if(isset($d["isDct"])&&$d["isDct"]){
  107.                 $isDict=1;
  108.                 $ret="d";
  109.                 // this is required by the specs, and BitTornado actualy chokes on unsorted dictionaries
  110.                 ksort($d, SORT_STRING);
  111.             }
  112.             foreach($d as $key=>$value) {
  113.                 if(isset($isDict)&&$isDict){
  114.                     // skip the isDct element, only if it's set by us
  115.                     if($key=="isDct" and is_bool($value)) continue;
  116.                     $ret.=strlen($key).":".$key;
  117.                 }
  118.                 if (is_string($value)) {
  119.                     $ret.=strlen($value).":".$value;
  120.                 } elseif (is_int($value)){
  121.                     $ret.="i${value}e";
  122.                 } else {
  123.                     $ret.=Lightbenc::bencode ($value);
  124.                 }
  125.             }
  126.             return $ret."e";
  127.         } elseif (is_string($d)) // fallback if we're given a single bencoded string or int
  128.             return strlen($d).":".$d;
  129.         elseif (is_int($d))
  130.             return "i${d}e";
  131.         else
  132.             return null;
  133.     }

  134.     public static function bdecode_file($filename){
  135.         $f=file_get_contents($filename, FILE_BINARY);
  136.         return Lightbenc::bdecode($f);
  137.     }

  138.     public static function bdecode_getinfo($filename){
  139.         $t = Lightbenc::bdecode(file_get_contents($filename, FILE_BINARY));
  140.         $t['info_hash'] = sha1(Lightbenc::bencode($t['info']));

  141.         if(is_array($t['info']['files'])){ //multifile
  142.             $t['info']['size'] = 0;
  143.             $t['info']['filecount'] = 0;

  144.             foreach($t['info']['files'] as $file){
  145.                 $t['info']['filecount']++;
  146.                 $t['info']['size']+=$file['length'];
  147.             }
  148.         }else{
  149.             $t['info']['size'] = $t['info']['length'];
  150.             $t['info']["filecount"] = 1;
  151.             $t['info']['files'][0]['path'] = $t['info']['name'];
  152.             $t['info']['files'][0]['length'] = $t['info']['length'];
  153.         }
  154.         return $t;
  155.     }
  156. }


  157. ?>
复制代码

使用方法:
引入lightbenc.php文件
  1. include "lightbenc.php";
复制代码

构建实例
  1. $Lightbenc = new Lightbenc();
复制代码

解析bt文件
  1. $file_info = $Lightbenc->bdecode_getinfo(‘ed01289e3f9d660fa1f60b79c13fb4eec8901498.torrent’);
复制代码

$file_info 就是我们获取到的bt文件的信息,里面包含了bt文件的服务器地址,文件个数和文件大小等信息,其中:

文件名称:$bt[‘info’][‘files’][/*这边要是个偶数*/][‘path.utf-8′][0];
文件大小:$bt[‘info’][‘files’][/*这边要是个偶数*/][‘path.utf-8′][0];
如果要输出GBK的编码就把上面代码里面的’path.utf-8’换成’path’就可以了

杂记
  1. include "lightbenc.php";
  2. $file="1.torrent";//BT文件名
  3. $btinfo = Lightbenc::BDecode($file);//解析BT文件信息,放入$btinfo数组
  4. $infohash = Lightbenc::bdecode_getinfo($file);//解析BT文件hash值,并放入$infohash数组
  5. //可以用以下函数获取以上所有数组信息
  6. echo var_dump(Lightbenc::bdecode($file));
  7. echo var_dump(Lightbenc::bdecode_getinfo($file));
  8. //下面是我总结的一些
  9. echo $btinfo['info']['name'];//获取种子文件名
  10. echo $btinfo['announce'][/*从0开始,一个数对应一个服务器*/];//读取Tracker服务器列表
  11. echo $btinfo['info']['files'][/*从0开始,一个数对应一个文件*/]['path']['0'];//读取BT文件名称,多个文件的替换中间的数字
  12. echo $btinfo['info']['files'][/*从0开始,一个数对应一个文件*/]['length'];//读取BT文件单个文件大小
  13. echo $infohash['info_hash'];//获取BT文件hash值
复制代码

相关帖子

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|PHPIN.NET ( 冀ICP备12000898号-14 )|网站地图

GMT+8, 2024-3-29 02:48

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表