Last active
April 14, 2020 04:27
-
-
Save findstr/0a83d35336e68571b6d456bc267485a9 to your computer and use it in GitHub Desktop.
zproto for php parse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class zproto { | |
private $proto; | |
private $unpack; | |
function __construct($dom) { | |
$this->proto = $dom; | |
} | |
//for compatible less then 7.1.0 | |
private function unpack($fmt, $dat, $off) { | |
$dat = substr($dat, $off); | |
return unpack($fmt, $dat); | |
} | |
public function parse($dat, $name) { | |
$tag = 0; | |
$tagoff = 6; | |
$ret = array(); | |
$proto = $this->proto[$name]; | |
$sz = $this->unpack('L', $dat, 0)[1]; | |
$fn = $this->unpack('S', $dat, 4)[1]; | |
$off = $tagoff + $fn * 2; | |
for ($i = 0; $i < $fn; $i++) { | |
$t = $this->unpack('S', $dat, $tagoff)[1]; $tagoff += 2; | |
$t = $tag + 1; | |
$field = $proto[$t]; | |
switch ($field['type']) { | |
case 'byte': | |
$v = $this->unpack('c', $dat, $off)[1]; $off += 4; | |
break; | |
case 'ubyte': | |
$v = $this->unpack('C', $dat, $off)[1]; $off += 4; | |
break; | |
case 'integer': | |
$v = $this->unpack('l', $dat, $off)[1]; $off += 4; | |
break; | |
case 'uinteger': | |
$v = $this->unpack('V', $dat, $off)[1]; $off += 4; | |
break; | |
case 'long': | |
$v = $this->unpack('q', $dat, $off)[1]; $off += 8; | |
break; | |
case 'ulong': | |
$v = $this->unpack('Q', $dat, $off)[1]; $off += 8; | |
break; | |
case 'string': | |
$len = $this->unpack('L', $dat, $off)[1]; $off += 4; | |
$v = substr($dat, $off, $len); $off += $len; | |
break; | |
default: | |
$len = $this->unpack('L', $dat, $off)[1]; | |
$x = substr($dat, $off); | |
$v = $this->parse($x, $field['type']); | |
$off += $len + 4; | |
break; | |
} | |
$ret[$field['name']] = $v; | |
$tag = $t; | |
} | |
return $ret; | |
} | |
}; | |
$str = "\x04\x00\x00\x00\x02\x00\x00\x00\x00\x00\x04\x00\x00\x00\x02\x00\x00\x00ab"; | |
$proto = [ | |
'foo'=>array( | |
1=>["name"=>"foo", "type" => "uinteger"], | |
2=>["name"=>"foo", "type" => "string"], | |
), | |
]; | |
$obj = new zproto($proto); | |
$arr = $obj->parse($str, "foo"); | |
echo var_dump($arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment