/**
  * @param Packet $packet
  *
  * @return Packet
  */
 public function dispatch(Packet $packet) : Packet
 {
     $packetType = $packet->getType();
     if (!isset($this->handlers[$packetType])) {
         return $packet;
     }
     $this->doDispatch($this->getHandlers($packetType), $packet);
     return $packet;
 }
 public function decode()
 {
     parent::decode();
     $this->clientID = $this->getLong();
     $this->session = $this->getLong();
     $this->unknown = $this->get(1);
 }
 public function decode()
 {
     parent::decode();
     $this->clientID = $this->getLong();
     $this->sendPing = $this->getLong();
     $this->useSecurity = $this->getByte() > 0;
 }
Exemple #4
0
 public static function broadcast($data, $opcode = Packet::OPCODE_TEXT, $mask = false)
 {
     $data = (string) $data;
     foreach (self::$instances as $client) {
         $message = Packet::frameData($data, $client->version, $opcode, $mask);
         socket_write($client->socket, $message, strlen($message));
     }
 }
 public function send(Packet $packet)
 {
     $conn = $this->connection();
     $bytes = $packet->getBinary();
     fputs($conn, $bytes, strlen($bytes));
     // TODO: Check result checksum!
     $result = fread($conn, 8192);
     if ($result === false) {
         throw new \Exception('CHECK_NRPE: Error receiving data from daemon.');
     } elseif (strlen($result) === 0) {
         throw new \Exception('CHECK_NRPE: Received 0 bytes from daemon.' . ' Check the remote server logs for error messages');
     }
     // TODO: CHECK_NRPE: Receive underflow - only %d bytes received (%d expected)
     $code = unpack('n', substr($result, 8, 2));
     $this->lastReturnCode = $code[1];
     $this->disconnect();
     return rtrim(substr($result, 10, -2));
 }
 public function decode()
 {
     parent::decode();
     $this->getAddress($this->address, $this->port);
     for ($i = 0; $i < 10; ++$i) {
         $this->getAddress($addr, $port, $version);
         $this->systemAddresses[$i] = [$addr, $port, $version];
     }
     $this->sendPing = $this->getLong();
     $this->sendPong = $this->getLong();
 }
 public function decode()
 {
     parent::decode();
     $this->cookie = $this->get(4);
     $this->security = $this->get(1);
     $this->port = $this->getShort();
     $this->dataArray0 = $this->get($this->getByte());
     $this->dataArray = $this->getDataArray(9);
     $this->timestamp = $this->get(2);
     $this->session2 = $this->getLong();
     $this->session = $this->getLong();
 }
 /**
  * Start servers for UDP Discovery and set timer for sending packets
  * @param LoopInterface $loop
  */
 public function start($loop)
 {
     $factory = new \React\Datagram\Factory($loop);
     // IPv4 Server
     $factory->createServer('0.0.0.0:' . $this->discoveryPort)->then(function (\React\Datagram\Socket $client) {
         $client->on('message', function ($message, $serverAddress, $client) {
             //				echo 'received ip4 "' . bin2hex($message) . '" from ' . $serverAddress . PHP_EOL;
             $this->handlePacket(Packet::createFromString($message, $this->stripPort($serverAddress)));
         });
     });
     // IPv6 Server
     $factory->createServer('[::]:' . $this->discoveryPort)->then(function (\React\Datagram\Socket $client) {
         $client->on('message', function ($message, $serverAddress, $client) {
             //				echo 'received ip6 "' . bin2hex($message) . '" from ' . $serverAddress . PHP_EOL;
             $this->handlePacket(Packet::createFromString($message, $this->stripPort($serverAddress)));
         });
     });
     $loop->addPeriodicTimer($this->syncInterval, function () {
         $this->sendAnnouncement();
     });
     $this->sendAnnouncement();
     // TODO remove known hosts after some time
 }
 function parse_null_terminated_string($attribute_name)
 {
     list($result, $length) = Packet::unmarshall_null_terminated_string(substr($this->binary, $this->parse_position));
     $this->attributes[$attribute_name] = substr($this->binary, $this->parse_position, $length - 1);
     $this->parse_position += $length;
 }
 function read_packets()
 {
     while ($this->read_buffer->length() > 4) {
         //      $this->log("reading packets\n");
         //      $this->log("Read Buffer:\n" . hex_pretty_print($this->read_buffer->buffer) . "\n");
         list($length, $number) = Packet::parse_header($this->read_buffer->buffer);
         //      $this->log("got packet {$number} of length {$length} read buffer length: " . $this->read_buffer->length() . "\n");
         if ($length + 4 <= $this->read_buffer->length()) {
             //        $this->log("read packet of length {$length}.\n");
             $binary = $this->read_buffer->pop($length + 4);
             $packet = new Packet($binary);
             //        $this->log("Packet:\n" . hex_pretty_print($binary) . "\n");
             //        $this->log(hex_php_string($binary) . "\n");
             $this->queue_read_packet($packet);
         } else {
             return;
         }
     }
 }
Exemple #11
0
 public function __construct($options = array(), $flags = 0x0)
 {
     $this->setOptions($options);
     parent::__construct(Packet::TYPE_CONNECT, $flags);
 }
 public function __construct()
 {
     parent::__construct(Packet::TYPE_UNSUBACK);
 }
Exemple #13
0
 public final function onFinish($serv, $task_id, $data)
 {
     //fixed the result more than 8k timeout bug
     if (strpos($data, '$$$$$$$$') === 0) {
         $tmp_path = substr($data, 8);
         $data = file_get_contents($tmp_path);
         unlink($tmp_path);
     }
     $data = unserialize($data);
     $fd = $data["fd"];
     if (!isset($this->taskInfo[$fd]) || !$data["result"]) {
         unset($this->taskInfo[$fd]);
         return true;
     }
     $key = $this->taskInfo[$fd]["task"][$task_id];
     $this->taskInfo[$fd]["result"][$key] = $data["result"];
     unset($this->taskInfo[$fd]["task"][$task_id]);
     switch ($data["type"]) {
         case DoraConst::SW_SYNC_SINGLE:
             $Packet = Packet::packFormat("OK", 0, $data["result"]);
             $Packet["guid"] = $this->taskInfo[$fd]["guid"];
             $Packet = Packet::packEncode($Packet);
             //sys_get_temp_dir
             $serv->send($fd, $Packet);
             unset($this->taskInfo[$fd]);
             return true;
             break;
         case DoraConst::SW_SYNC_MULTI:
             if (count($this->taskInfo[$fd]["task"]) == 0) {
                 $Packet = Packet::packFormat("OK", 0, $this->taskInfo[$fd]["result"]);
                 $Packet["guid"] = $this->taskInfo[$fd]["guid"];
                 $Packet = Packet::packEncode($Packet);
                 $serv->send($fd, $Packet);
                 unset($this->taskInfo[$fd]);
                 return true;
             } else {
                 return true;
             }
             break;
         default:
             unset($this->taskInfo[$fd]);
             return true;
             break;
     }
 }
 /** Preparse file
  * @param string $source
  *	Source file
  * @param string $destination
  *	Destination file
  * @param string $path_to_cut
  *	Path to root
  * @param bool $rm_flags
  *	Remove flag comments?
  *
  * @return bool
  */
 public function parseFile($source, $destination, $path_to_cut = "", $rm_flags = false)
 {
     global $Config, $Log;
     // is packet set?
     if (empty($this->Packet)) {
         return false;
     }
     // read
     $Log->doLog(8, "PreParser: Read file '{$source}'");
     $content = ts_FileHandler::readFile($source);
     if ($content === false) {
         $Log->doLog(3, "PreParser: Unable to read file '{$source}'");
         return false;
     }
     // get filetype
     $cache = explode('.', basename($source));
     $filetype = end($cache);
     // filetype to move only?
     if (!in_array($filetype, $this->parse_ext)) {
         if ($source != $destination and !ts_FileHandler::writeFile($destination, $content)) {
             $Log->doLog(3, "PreParser: Unable to move file to '{$destination}'");
             return false;
         }
         return true;
     }
     // split flag comment from rest of content
     if (substr($content, 0, 4) != '<!--') {
         $content = '<!-- | -->' . chr(10) . $content;
     }
     $content_lines = explode(chr(10), $content);
     $flag_comment = trim($content_lines[0]);
     unset($content_lines[0]);
     $content = implode(chr(10), $content_lines);
     // read flags and get path to display
     $flags = $this->getFlags($flag_comment);
     if (isset($flags['p'])) {
         return true;
     }
     $displaypath = substr($destination, strlen($path_to_cut) + 1);
     // add header
     if (!isset($flags['h'])) {
         // remove existing headers
         $content = preg_replace('#(\\/\\*\\* header .* \\*\\/)#Usi', '', $content);
         $content = preg_replace('#(\\<\\?php[\\s]*\\?\\>)#Usi', '', $content);
         $content = preg_replace('#(\\<!--[\\s]*--\\>)#Usi', '', $content);
         // generate new header
         // First two lines have to be separated or the publish
         // script will remove the following header definition!
         $header = '/*' . '* header *********************************************************' . chr(10) . ' * project:   TSunic ' . $Config->get('version') . ' | ' . $this->Packet->getInfo('name') . ' ' . $this->Packet->getInfo('version') . chr(10) . ' * file:      ' . $displaypath . chr(10);
         if ($this->Packet->getInfo('author')) {
             $header .= ' * author:    ' . $this->Packet->getInfo('author') . chr(10);
         }
         if ($this->Packet->getInfo('copyright')) {
             $header .= ' * copyright: ' . $this->Packet->getInfo('copyright') . chr(10);
         }
         if ($this->Packet->getInfo('licence')) {
             $cache = explode(chr(10), $this->Packet->getInfo('licence'));
             $header .= ' * licence:   ' . trim($cache[0]) . chr(10);
             if (count($cache) > 1) {
                 for ($i = 1; $i < count($cache); $i++) {
                     $cache[$i] = trim($cache[$i]);
                     $header .= empty($cache[$i]) ? ' *' . chr(10) : ' *	    ' . $cache[$i] . chr(10);
                 }
             }
         }
         $header .= ' * ************************************************************** */' . chr(10);
         // embed header in required tags
         switch ($filetype) {
             case 'php':
                 $header = '<?php' . chr(10) . $header . '?>';
                 break;
             case 'js':
             case 'css':
                 break;
             default:
                 $header = '<!--' . chr(10) . $header . '-->';
                 break;
         }
         // add header to content
         $content = $header . chr(10) . $content;
         // skip empty lines at the beginning
         $cache = explode(chr(10), $content);
         foreach ($cache as $index => $value) {
             $value = trim($value);
             if (empty($value)) {
                 unset($cache[$index]);
                 continue;
             } elseif ($value == '<?php') {
                 continue;
             }
             break;
         }
         $content = implode(chr(10), $cache);
     }
     // add flag comment again
     if (!$rm_flags) {
         $content = $flag_comment . chr(10) . $content;
     }
     // trim
     $content = str_replace('?>' . chr(10) . '<?php', '', $content);
     // write
     $Log->doLog(8, "PreParser: Write file '{$source}'");
     if (!ts_FileHandler::writeFile($destination, $content, 1)) {
         $Log->doLog(3, "PreParser: Unable to write file ({$destination})");
         return false;
     }
     return true;
 }
Exemple #15
0
 public final function onHttpFinished($serv, $task_id, $data, $response)
 {
     $fd = $data["fd"];
     $guid = $data["guid"];
     //if the guid not exists .it's mean the api no need return result
     if (!isset($this->taskInfo[$fd][$guid])) {
         return true;
     }
     //get the api key
     $key = $this->taskInfo[$fd][$guid]["taskkey"][$task_id];
     //save the result
     $this->taskInfo[$fd][$guid]["result"][$key] = $data["result"];
     //remove the used taskid
     unset($this->taskInfo[$fd][$guid]["taskkey"][$task_id]);
     switch ($data["type"]) {
         case DoraConst::SW_MODE_WAITRESULT_MULTI:
             //all task finished
             if (count($this->taskInfo[$fd][$guid]["taskkey"]) == 0) {
                 $packet = Packet::packFormat("OK", 0, $this->taskInfo[$fd][$guid]["result"]);
                 $packet["guid"] = $guid;
                 $packet = Packet::packEncode($packet, $data["protocol"]);
                 unset($this->taskInfo[$fd][$guid]);
                 $response->end($packet);
                 return true;
             } else {
                 //multi call task
                 //not finished
                 //waiting other result
                 return true;
             }
             break;
         default:
             return true;
             break;
     }
 }
 public function decode()
 {
     parent::decode();
     //TODO, not needed yet
 }
 public function clean()
 {
     $this->packets = [];
     $this->seqNumber = null;
     return parent::clean();
 }
Exemple #18
0
 /**
  * Method to send a packet to the rcon server.
  * @param Packet $packet The packet which will be send to the rcon server.
  * @return bool The state if the packet was successfully send.
  * @since 1.0.0
  */
 public function sendPacket(Packet $packet)
 {
     $this->packet = $packet;
     $request = $this->packet->getRequest();
     return socket_write($this->socket, $request, strlen($request)) === false ? false : true;
 }
 public function __construct()
 {
     parent::__construct(Packet::TYPE_DISCONNECT);
 }
Exemple #20
0
 public static function getPacketFromArray($arr)
 {
     if (isset($arr['from'], $arr['to'], $arr['type'], $arr['content'])) {
         $packet = new Packet();
         $packet->setFrom($arr['from']);
         $packet->setTo($arr['to']);
         $packet->setType($arr['type']);
         $packet->setContent($arr['content']);
         return $packet;
     } else {
         return false;
     }
 }
Exemple #21
0
 public function getAsyncData()
 {
     //wait all the async result
     //when  timeout all the error will return
     //这里有个坑,我不知道具体哪个client需要recive
     while (1) {
         if (count(self::$asynclist) > 0) {
             foreach (self::$asynclist as $k => $client) {
                 if ($client->isConnected()) {
                     $data = $client->recv();
                     if ($data !== false && $data != "") {
                         $data = Packet::packDecode($data);
                         if (isset(self::$asynclist[$data["data"]["guid"]]) && isset($data["data"]["isresult"]) && $data["data"]["isresult"] == 1) {
                             //ok recive an async result
                             //remove the guid on the asynclist
                             unset(self::$asynclist[$data["data"]["guid"]]);
                             //add result to async result
                             self::$asynresult[$data["data"]["guid"]] = $data["data"];
                             self::$asynresult[$data["data"]["guid"]]["fromwait"] = 0;
                             continue;
                         } else {
                             //not in the asynclist drop this packet
                             continue;
                         }
                     } else {
                         //remove the result
                         unset(self::$asynclist[$k]);
                         self::$asynresult[$k] = Packet::packFormat("the recive wrong or timeout", 100009);
                         continue;
                     }
                 } else {
                     //remove the result
                     unset(self::$asynclist[$k]);
                     self::$asynresult[$k] = Packet::packFormat("Get Async Result Fail: Client Closed.", 100012);
                     continue;
                 }
             }
             // foreach the list
         } else {
             break;
         }
     }
     //while
     $result = self::$asynresult;
     self::$asynresult = array();
     return Packet::packFormat("OK", 0, $result);
 }
Exemple #22
0
 /**
  * Send
  *
  * @param Packet $packet The packet
  *
  * @return void
  */
 protected function send($packet)
 {
     $this->log("Sending TACACS+ message... ");
     $data = $packet->toBinary();
     @socket_write($this->socket, $data, Util::binaryLength($data));
     $this->log("DONE (wrote " . Util::binaryLength($data) . " bytes)!");
     $unpackMask = 'H' . TAC_PLUS_HDR_SIZE . 'header/H*body';
     $unpack = unpack($unpackMask, $data);
     $unpackHeader = $unpack['header'];
     $unpackBody = $unpack['body'];
     $this->log("SENT: " . implode($unpack));
     $this->log("SENT (Header): " . $unpackHeader);
     $this->log("SENT (Body): " . $unpackBody);
 }
 public function decode()
 {
     parent::decode();
     $this->pingID = $this->getLong();
 }
Exemple #24
0
 private function doRequest($sendData, $group = "group1", $ip = "", $port = "")
 {
     //get client obj
     try {
         $client = $this->getClientObj($group, $ip, $port);
     } catch (\Exception $e) {
         return Packet::packFormat($e->getMessage(), $e->getCode());
     }
     $ret = $client->send($sendData);
     //ok fail
     if (!$ret) {
         $errorcode = $client->errCode;
         //destroy error client obj to make reconncet
         unset(self::$client[$this->currentClientKey]);
         if ($errorcode == 0) {
             $msg = "connect fail.check host dns.";
             $errorcode = -1;
             $Packet = Packet::packFormat($msg, $errorcode);
         } else {
             $msg = socket_strerror($errorcode);
             $Packet = Packet::packFormat($msg, $errorcode);
         }
         return $Packet;
     }
     //recive the response
     $result = $client->recv();
     //recive error check
     if ($result !== false) {
         return Packet::packDecode($result);
     } else {
         return Packet::packFormat("the recive wrong or timeout", 100009);
     }
 }
Exemple #25
0
 public function __construct()
 {
     parent::__construct(Packet::TYPE_PUBCOMP);
 }
Exemple #26
0
 public function __construct()
 {
     parent::__construct(Packet::TYPE_PINGREQ);
 }
 public function decode()
 {
     parent::decode();
 }
Exemple #28
0
 public function __construct()
 {
     parent::__construct(0);
 }
 public function clean()
 {
     $this->packets = [];
     return parent::clean();
 }
Exemple #30
0
<?php

//入口文件
@(require "pay.php");
$packet = new Packet();
//获取用户信息
$get = $_GET['param'];
$code = $_GET['code'];
$zj = $_GET['zj'];
//判断code是否存在
if ($get == 'access_token' && !empty($code)) {
    $param['param'] = 'access_token';
    $param['code'] = $code;
    if ($zj == 1) {
        //        echo 'zj';die;
        $packet->_route('wxpacket', array('openid' => $code));
        die;
    }
    //获取用户openid信息
    $userinfo = $packet->_route('userinfo', $param);
    if (empty($userinfo['openid'])) {
        exit("NOAUTH");
    }
    //调取支付方法
    $packet->_route('wxpacket', array('openid' => $userinfo['openid']));
} else {
    $packet->_route('userinfo');
}