update workerman to 3.3.4
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
/**
|
||||
* This file is part of workerman.
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the MIT-LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @author walkor<walkor@workerman.net>
|
||||
* @copyright walkor<walkor@workerman.net>
|
||||
* @link http://www.workerman.net/
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Workerman\Protocols;
|
||||
|
||||
use Workerman\Connection\TcpConnection;
|
||||
|
||||
/**
|
||||
* Frame Protocol.
|
||||
*/
|
||||
class Frame
|
||||
{
|
||||
/**
|
||||
* Check the integrity of the package.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @param TcpConnection $connection
|
||||
* @return int
|
||||
*/
|
||||
public static function input($buffer, TcpConnection $connection)
|
||||
{
|
||||
if (strlen($buffer) < 4) {
|
||||
return 0;
|
||||
}
|
||||
$unpack_data = unpack('Ntotal_length', $buffer);
|
||||
return $unpack_data['total_length'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @return string
|
||||
*/
|
||||
public static function decode($buffer)
|
||||
{
|
||||
return substr($buffer, 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @return string
|
||||
*/
|
||||
public static function encode($buffer)
|
||||
{
|
||||
$total_length = 4 + strlen($buffer);
|
||||
return pack('N', $total_length) . $buffer;
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
<?php
|
||||
namespace Workerman\Protocols;
|
||||
/**
|
||||
* Gateway与Worker间通讯的二进制协议
|
||||
*
|
||||
* struct GatewayProtocol
|
||||
* {
|
||||
* unsigned int pack_len,
|
||||
* unsigned char cmd,//命令字
|
||||
* unsigned int local_ip,
|
||||
* unsigned short local_port,
|
||||
* unsigned int client_ip,
|
||||
* unsigned short client_port,
|
||||
* unsigned int client_id,
|
||||
* unsigned char flag,
|
||||
* unsigned int ext_len,
|
||||
* char[ext_len] ext_data,
|
||||
* char[pack_length-HEAD_LEN] body//包体
|
||||
* }
|
||||
*
|
||||
*
|
||||
* @author walkor <walkor@workerman.net>
|
||||
*/
|
||||
|
||||
class GatewayProtocol
|
||||
{
|
||||
// 发给worker,gateway有一个新的连接
|
||||
const CMD_ON_CONNECTION = 1;
|
||||
|
||||
// 发给worker的,客户端有消息
|
||||
const CMD_ON_MESSAGE = 3;
|
||||
|
||||
// 发给worker上的关闭链接事件
|
||||
const CMD_ON_CLOSE = 4;
|
||||
|
||||
// 发给gateway的向单个用户发送数据
|
||||
const CMD_SEND_TO_ONE = 5;
|
||||
|
||||
// 发给gateway的向所有用户发送数据
|
||||
const CMD_SEND_TO_ALL = 6;
|
||||
|
||||
// 发给gateway的踢出用户
|
||||
const CMD_KICK = 7;
|
||||
|
||||
// 发给gateway,通知用户session更改
|
||||
const CMD_UPDATE_SESSION = 9;
|
||||
|
||||
// 获取在线状态
|
||||
const CMD_GET_ONLINE_STATUS = 10;
|
||||
|
||||
// 判断是否在线
|
||||
const CMD_IS_ONLINE = 11;
|
||||
|
||||
// 包体是标量
|
||||
const FLAG_BODY_IS_SCALAR = 0x01;
|
||||
|
||||
/**
|
||||
* 包头长度
|
||||
* @var integer
|
||||
*/
|
||||
const HEAD_LEN = 26;
|
||||
|
||||
public static $empty = array(
|
||||
'cmd' => 0,
|
||||
'local_ip' => '0.0.0.0',
|
||||
'local_port' => 0,
|
||||
'client_ip' => '0.0.0.0',
|
||||
'client_port' => 0,
|
||||
'client_id' => 0,
|
||||
'flag' => 0,
|
||||
'ext_data' => '',
|
||||
'body' => '',
|
||||
);
|
||||
|
||||
/**
|
||||
* 返回包长度
|
||||
* @param string $buffer
|
||||
* @return int return current package length
|
||||
*/
|
||||
public static function input($buffer)
|
||||
{
|
||||
if(strlen($buffer) < self::HEAD_LEN)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
$data = unpack("Npack_len", $buffer);
|
||||
return $data['pack_len'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取整个包的buffer
|
||||
* @param array $data
|
||||
* @return string
|
||||
*/
|
||||
public static function encode($data)
|
||||
{
|
||||
$flag = (int)is_scalar($data['body']);
|
||||
if(!$flag)
|
||||
{
|
||||
$data['body'] = serialize($data['body']);
|
||||
}
|
||||
$ext_len = strlen($data['ext_data']);
|
||||
$package_len = self::HEAD_LEN + $ext_len + strlen($data['body']);
|
||||
return pack("NCNnNnNNC", $package_len,
|
||||
$data['cmd'], ip2long($data['local_ip']),
|
||||
$data['local_port'], ip2long($data['client_ip']),
|
||||
$data['client_port'], $data['client_id'],
|
||||
$ext_len, $flag) . $data['ext_data'] . $data['body'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 从二进制数据转换为数组
|
||||
* @param string $buffer
|
||||
* @return array
|
||||
*/
|
||||
public static function decode($buffer)
|
||||
{
|
||||
$data = unpack("Npack_len/Ccmd/Nlocal_ip/nlocal_port/Nclient_ip/nclient_port/Nclient_id/Next_len/Cflag", $buffer);
|
||||
$data['local_ip'] = long2ip($data['local_ip']);
|
||||
$data['client_ip'] = long2ip($data['client_ip']);
|
||||
if($data['ext_len'] > 0)
|
||||
{
|
||||
$data['ext_data'] = substr($buffer, self::HEAD_LEN, $data['ext_len']);
|
||||
if($data['flag'] & self::FLAG_BODY_IS_SCALAR)
|
||||
{
|
||||
$data['body'] = substr($buffer, self::HEAD_LEN + $data['ext_len']);
|
||||
}
|
||||
else
|
||||
{
|
||||
$data['body'] = unserialize(substr($buffer, self::HEAD_LEN + $data['ext_len']));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$data['ext_data'] = '';
|
||||
if($data['flag'] & self::FLAG_BODY_IS_SCALAR)
|
||||
{
|
||||
$data['body'] = substr($buffer, self::HEAD_LEN);
|
||||
}
|
||||
else
|
||||
{
|
||||
$data['body'] = unserialize(substr($buffer, self::HEAD_LEN));
|
||||
}
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
+281
-324
@@ -1,476 +1,430 @@
|
||||
<?php
|
||||
namespace Workerman\Protocols;
|
||||
<?php
|
||||
/**
|
||||
* This file is part of workerman.
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the MIT-LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @author walkor<walkor@workerman.net>
|
||||
* @copyright walkor<walkor@workerman.net>
|
||||
* @link http://www.workerman.net/
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Workerman\Protocols;
|
||||
|
||||
use Workerman\Connection\TcpConnection;
|
||||
use Workerman\Worker;
|
||||
|
||||
/**
|
||||
* http protocol
|
||||
* @author walkor<walkor@workerman.net>
|
||||
*/
|
||||
class Http
|
||||
{
|
||||
/**
|
||||
* 判断包长
|
||||
* @param string $recv_buffer
|
||||
* Check the integrity of the package.
|
||||
*
|
||||
* @param string $recv_buffer
|
||||
* @param TcpConnection $connection
|
||||
* @return int
|
||||
*/
|
||||
public static function input($recv_buffer, TcpConnection $connection)
|
||||
{
|
||||
if(!strpos($recv_buffer, "\r\n\r\n"))
|
||||
{
|
||||
// 无法获得包长,避免客户端传递超大头部的数据包
|
||||
if(strlen($recv_buffer)>=TcpConnection::$maxPackageSize)
|
||||
{
|
||||
if (!strpos($recv_buffer, "\r\n\r\n")) {
|
||||
// Judge whether the package length exceeds the limit.
|
||||
if (strlen($recv_buffer) >= TcpConnection::$maxPackageSize) {
|
||||
$connection->close();
|
||||
return 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
list($header, $body) = explode("\r\n\r\n", $recv_buffer, 2);
|
||||
if(0 === strpos($recv_buffer, "POST"))
|
||||
{
|
||||
|
||||
list($header,) = explode("\r\n\r\n", $recv_buffer, 2);
|
||||
if (0 === strpos($recv_buffer, "POST")) {
|
||||
// find Content-Length
|
||||
$match = array();
|
||||
if(preg_match("/\r\nContent-Length: ?(\d+)/", $header, $match))
|
||||
{
|
||||
$content_lenght = $match[1];
|
||||
return $content_lenght + strlen($header) + 4;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (preg_match("/\r\nContent-Length: ?(\d+)/i", $header, $match)) {
|
||||
$content_length = $match[1];
|
||||
return $content_length + strlen($header) + 4;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return strlen($header)+4;
|
||||
} elseif (0 === strpos($recv_buffer, "GET")) {
|
||||
return strlen($header) + 4;
|
||||
} else {
|
||||
$connection->send("HTTP/1.1 400 Bad Request\r\n\r\n", true);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 从http数据包中解析$_POST、$_GET、$_COOKIE等
|
||||
* @param string $recv_buffer
|
||||
* Parse $_POST、$_GET、$_COOKIE.
|
||||
*
|
||||
* @param string $recv_buffer
|
||||
* @param TcpConnection $connection
|
||||
* @return void
|
||||
* @return array
|
||||
*/
|
||||
public static function decode($recv_buffer, TcpConnection $connection)
|
||||
{
|
||||
// 初始化
|
||||
$_POST = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES = array();
|
||||
// Init.
|
||||
$_POST = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES = array();
|
||||
$GLOBALS['HTTP_RAW_POST_DATA'] = '';
|
||||
// 清空上次的数据
|
||||
HttpCache::$header = array();
|
||||
// Clear cache.
|
||||
HttpCache::$header = array('Connection' => 'Connection: keep-alive');
|
||||
HttpCache::$instance = new HttpCache();
|
||||
// 需要设置的变量名
|
||||
$_SERVER = array (
|
||||
'QUERY_STRING' => '',
|
||||
'REQUEST_METHOD' => '',
|
||||
'REQUEST_URI' => '',
|
||||
'SERVER_PROTOCOL' => '',
|
||||
'SERVER_SOFTWARE' => 'workerman/3.0',
|
||||
'SERVER_NAME' => '',
|
||||
'HTTP_HOST' => '',
|
||||
'HTTP_USER_AGENT' => '',
|
||||
'HTTP_ACCEPT' => '',
|
||||
'HTTP_ACCEPT_LANGUAGE' => '',
|
||||
'HTTP_ACCEPT_ENCODING' => '',
|
||||
'HTTP_COOKIE' => '',
|
||||
'HTTP_CONNECTION' => '',
|
||||
'REMOTE_ADDR' => '',
|
||||
'REMOTE_PORT' => '0',
|
||||
);
|
||||
|
||||
// 将header分割成数组
|
||||
// $_SERVER
|
||||
$_SERVER = array(
|
||||
'QUERY_STRING' => '',
|
||||
'REQUEST_METHOD' => '',
|
||||
'REQUEST_URI' => '',
|
||||
'SERVER_PROTOCOL' => '',
|
||||
'SERVER_SOFTWARE' => 'workerman/'.Worker::VERSION,
|
||||
'SERVER_NAME' => '',
|
||||
'HTTP_HOST' => '',
|
||||
'HTTP_USER_AGENT' => '',
|
||||
'HTTP_ACCEPT' => '',
|
||||
'HTTP_ACCEPT_LANGUAGE' => '',
|
||||
'HTTP_ACCEPT_ENCODING' => '',
|
||||
'HTTP_COOKIE' => '',
|
||||
'HTTP_CONNECTION' => '',
|
||||
'REMOTE_ADDR' => '',
|
||||
'REMOTE_PORT' => '0',
|
||||
);
|
||||
|
||||
// Parse headers.
|
||||
list($http_header, $http_body) = explode("\r\n\r\n", $recv_buffer, 2);
|
||||
$header_data = explode("\r\n", $http_header);
|
||||
|
||||
list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ', $header_data[0]);
|
||||
|
||||
|
||||
list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ',
|
||||
$header_data[0]);
|
||||
|
||||
$http_post_boundary = '';
|
||||
unset($header_data[0]);
|
||||
foreach($header_data as $content)
|
||||
{
|
||||
foreach ($header_data as $content) {
|
||||
// \r\n\r\n
|
||||
if(empty($content))
|
||||
{
|
||||
if (empty($content)) {
|
||||
continue;
|
||||
}
|
||||
list($key, $value) = explode(':', $content, 2);
|
||||
$key = strtolower($key);
|
||||
$value = trim($value);
|
||||
switch($key)
|
||||
{
|
||||
list($key, $value) = explode(':', $content, 2);
|
||||
$key = str_replace('-', '_', strtoupper($key));
|
||||
$value = trim($value);
|
||||
$_SERVER['HTTP_' . $key] = $value;
|
||||
switch ($key) {
|
||||
// HTTP_HOST
|
||||
case 'host':
|
||||
$_SERVER['HTTP_HOST'] = $value;
|
||||
$tmp = explode(':', $value);
|
||||
case 'HOST':
|
||||
$tmp = explode(':', $value);
|
||||
$_SERVER['SERVER_NAME'] = $tmp[0];
|
||||
if(isset($tmp[1]))
|
||||
{
|
||||
if (isset($tmp[1])) {
|
||||
$_SERVER['SERVER_PORT'] = $tmp[1];
|
||||
}
|
||||
break;
|
||||
// cookie
|
||||
case 'cookie':
|
||||
$_SERVER['HTTP_COOKIE'] = $value;
|
||||
case 'COOKIE':
|
||||
parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
|
||||
break;
|
||||
// user-agent
|
||||
case 'user-agent':
|
||||
$_SERVER['HTTP_USER_AGENT'] = $value;
|
||||
break;
|
||||
// accept
|
||||
case 'accept':
|
||||
$_SERVER['HTTP_ACCEPT'] = $value;
|
||||
break;
|
||||
// accept-language
|
||||
case 'accept-language':
|
||||
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = $value;
|
||||
break;
|
||||
// accept-encoding
|
||||
case 'accept-encoding':
|
||||
$_SERVER['HTTP_ACCEPT_ENCODING'] = $value;
|
||||
break;
|
||||
// connection
|
||||
case 'connection':
|
||||
$_SERVER['HTTP_CONNECTION'] = $value;
|
||||
break;
|
||||
case 'referer':
|
||||
$_SERVER['HTTP_REFERER'] = $value;
|
||||
break;
|
||||
case 'if-modified-since':
|
||||
$_SERVER['HTTP_IF_MODIFIED_SINCE'] = $value;
|
||||
break;
|
||||
case 'if-none-match':
|
||||
$_SERVER['HTTP_IF_NONE_MATCH'] = $value;
|
||||
break;
|
||||
case 'content-type':
|
||||
if(!preg_match('/boundary="?(\S+)"?/', $value, $match))
|
||||
{
|
||||
// content-type
|
||||
case 'CONTENT_TYPE':
|
||||
if (!preg_match('/boundary="?(\S+)"?/', $value, $match)) {
|
||||
$_SERVER['CONTENT_TYPE'] = $value;
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
$_SERVER['CONTENT_TYPE'] = 'multipart/form-data';
|
||||
$http_post_boundary = '--'.$match[1];
|
||||
$http_post_boundary = '--' . $match[1];
|
||||
}
|
||||
break;
|
||||
case 'CONTENT_LENGTH':
|
||||
$_SERVER['CONTENT_LENGTH'] = $value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 需要解析$_POST
|
||||
if($_SERVER['REQUEST_METHOD'] == 'POST')
|
||||
{
|
||||
if(isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] == 'multipart/form-data')
|
||||
{
|
||||
|
||||
// Parse $_POST.
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] === 'multipart/form-data') {
|
||||
self::parseUploadFiles($http_body, $http_post_boundary);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
parse_str($http_body, $_POST);
|
||||
// $GLOBALS['HTTP_RAW_POST_DATA']
|
||||
$GLOBALS['HTTP_RAW_POST_DATA'] = $http_body;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// QUERY_STRING
|
||||
$_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
|
||||
if($_SERVER['QUERY_STRING'])
|
||||
{
|
||||
if ($_SERVER['QUERY_STRING']) {
|
||||
// $GET
|
||||
parse_str($_SERVER['QUERY_STRING'], $_GET);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
$_SERVER['QUERY_STRING'] = '';
|
||||
}
|
||||
|
||||
|
||||
// REQUEST
|
||||
$_REQUEST = array_merge($_GET, $_POST);
|
||||
|
||||
|
||||
// REMOTE_ADDR REMOTE_PORT
|
||||
$_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
|
||||
$_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
|
||||
|
||||
return $recv_buffer;
|
||||
|
||||
return array('get' => $_GET, 'post' => $_POST, 'cookie' => $_COOKIE, 'server' => $_SERVER, 'files' => $_FILES);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 编码,增加HTTP头
|
||||
* @param string $content
|
||||
* Http encode.
|
||||
*
|
||||
* @param string $content
|
||||
* @param TcpConnection $connection
|
||||
* @return string
|
||||
*/
|
||||
public static function encode($content, TcpConnection $connection)
|
||||
{
|
||||
// 没有http-code默认给个
|
||||
if(!isset(HttpCache::$header['Http-Code']))
|
||||
{
|
||||
// Default http-code.
|
||||
if (!isset(HttpCache::$header['Http-Code'])) {
|
||||
$header = "HTTP/1.1 200 OK\r\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
$header = HttpCache::$header['Http-Code']."\r\n";
|
||||
} else {
|
||||
$header = HttpCache::$header['Http-Code'] . "\r\n";
|
||||
unset(HttpCache::$header['Http-Code']);
|
||||
}
|
||||
|
||||
|
||||
// Content-Type
|
||||
if(!isset(HttpCache::$header['Content-Type']))
|
||||
{
|
||||
if (!isset(HttpCache::$header['Content-Type'])) {
|
||||
$header .= "Content-Type: text/html;charset=utf-8\r\n";
|
||||
}
|
||||
|
||||
|
||||
// other headers
|
||||
foreach(HttpCache::$header as $key=>$item)
|
||||
{
|
||||
if('Set-Cookie' == $key && is_array($item))
|
||||
{
|
||||
foreach($item as $it)
|
||||
{
|
||||
$header .= $it."\r\n";
|
||||
foreach (HttpCache::$header as $key => $item) {
|
||||
if ('Set-Cookie' === $key && is_array($item)) {
|
||||
foreach ($item as $it) {
|
||||
$header .= $it . "\r\n";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$header .= $item."\r\n";
|
||||
} else {
|
||||
$header .= $item . "\r\n";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// header
|
||||
$header .= "Server: WorkerMan/3.0\r\nContent-Length: ".strlen($content)."\r\n\r\n";
|
||||
|
||||
$header .= "Server: workerman/" . Worker::VERSION . "\r\nContent-Length: " . strlen($content) . "\r\n\r\n";
|
||||
|
||||
// save session
|
||||
self::sessionWriteClose();
|
||||
|
||||
|
||||
// the whole http package
|
||||
return $header.$content;
|
||||
return $header . $content;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置http头
|
||||
* @return bool
|
||||
*
|
||||
* @return bool|void
|
||||
*/
|
||||
public static function header($content, $replace = true, $http_response_code = 0)
|
||||
{
|
||||
if(PHP_SAPI != 'cli')
|
||||
{
|
||||
if (PHP_SAPI != 'cli') {
|
||||
return $http_response_code ? header($content, $replace, $http_response_code) : header($content, $replace);
|
||||
}
|
||||
if(strpos($content, 'HTTP') === 0)
|
||||
{
|
||||
if (strpos($content, 'HTTP') === 0) {
|
||||
$key = 'Http-Code';
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
$key = strstr($content, ":", true);
|
||||
if(empty($key))
|
||||
{
|
||||
if (empty($key)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if('location' == strtolower($key) && !$http_response_code)
|
||||
{
|
||||
|
||||
if ('location' === strtolower($key) && !$http_response_code) {
|
||||
return self::header($content, true, 302);
|
||||
}
|
||||
|
||||
if(isset(HttpCache::$codes[$http_response_code]))
|
||||
{
|
||||
HttpCache::$header['Http-Code'] = "HTTP/1.1 $http_response_code " . HttpCache::$codes[$http_response_code];
|
||||
if($key == 'Http-Code')
|
||||
{
|
||||
|
||||
if (isset(HttpCache::$codes[$http_response_code])) {
|
||||
HttpCache::$header['Http-Code'] = "HTTP/1.1 $http_response_code " . HttpCache::$codes[$http_response_code];
|
||||
if ($key === 'Http-Code') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if($key == 'Set-Cookie')
|
||||
{
|
||||
|
||||
if ($key === 'Set-Cookie') {
|
||||
HttpCache::$header[$key][] = $content;
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
HttpCache::$header[$key] = $content;
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 删除一个header
|
||||
* Remove header.
|
||||
*
|
||||
* @param string $name
|
||||
* @return void
|
||||
*/
|
||||
public static function headerRemove($name)
|
||||
{
|
||||
if(PHP_SAPI != 'cli')
|
||||
{
|
||||
return header_remove($name);
|
||||
if (PHP_SAPI != 'cli') {
|
||||
header_remove($name);
|
||||
return;
|
||||
}
|
||||
unset( HttpCache::$header[$name]);
|
||||
unset(HttpCache::$header[$name]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置cookie
|
||||
* @param string $name
|
||||
* @param string $value
|
||||
* Set cookie.
|
||||
*
|
||||
* @param string $name
|
||||
* @param string $value
|
||||
* @param integer $maxage
|
||||
* @param string $path
|
||||
* @param string $domain
|
||||
* @param bool $secure
|
||||
* @param bool $HTTPOnly
|
||||
* @param string $path
|
||||
* @param string $domain
|
||||
* @param bool $secure
|
||||
* @param bool $HTTPOnly
|
||||
* @return bool|void
|
||||
*/
|
||||
public static function setcookie($name, $value = '', $maxage = 0, $path = '', $domain = '', $secure = false, $HTTPOnly = false) {
|
||||
if(PHP_SAPI != 'cli')
|
||||
{
|
||||
public static function setcookie(
|
||||
$name,
|
||||
$value = '',
|
||||
$maxage = 0,
|
||||
$path = '',
|
||||
$domain = '',
|
||||
$secure = false,
|
||||
$HTTPOnly = false
|
||||
) {
|
||||
if (PHP_SAPI != 'cli') {
|
||||
return setcookie($name, $value, $maxage, $path, $domain, $secure, $HTTPOnly);
|
||||
}
|
||||
return self::header(
|
||||
'Set-Cookie: ' . $name . '=' . rawurlencode($value)
|
||||
. (empty($domain) ? '' : '; Domain=' . $domain)
|
||||
. (empty($maxage) ? '' : '; Max-Age=' . $maxage)
|
||||
. (empty($path) ? '' : '; Path=' . $path)
|
||||
. (!$secure ? '' : '; Secure')
|
||||
. (!$HTTPOnly ? '' : '; HttpOnly'), false);
|
||||
'Set-Cookie: ' . $name . '=' . rawurlencode($value)
|
||||
. (empty($domain) ? '' : '; Domain=' . $domain)
|
||||
. (empty($maxage) ? '' : '; Max-Age=' . $maxage)
|
||||
. (empty($path) ? '' : '; Path=' . $path)
|
||||
. (!$secure ? '' : '; Secure')
|
||||
. (!$HTTPOnly ? '' : '; HttpOnly'), false);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* sessionStart
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function sessionStart()
|
||||
{
|
||||
if(PHP_SAPI != 'cli')
|
||||
{
|
||||
if (PHP_SAPI != 'cli') {
|
||||
return session_start();
|
||||
}
|
||||
if(HttpCache::$instance->sessionStarted)
|
||||
{
|
||||
if (HttpCache::$instance->sessionStarted) {
|
||||
echo "already sessionStarted\nn";
|
||||
return true;
|
||||
}
|
||||
HttpCache::$instance->sessionStarted = true;
|
||||
// 没有sid,则创建一个session文件,生成一个sid
|
||||
if(!isset($_COOKIE[HttpCache::$sessionName]) || !is_file(HttpCache::$sessionPath . '/sess_' . $_COOKIE[HttpCache::$sessionName]))
|
||||
{
|
||||
$file_name = tempnam(HttpCache::$sessionPath, 'sess_');
|
||||
if(!$file_name)
|
||||
{
|
||||
// Generate a SID.
|
||||
if (!isset($_COOKIE[HttpCache::$sessionName]) || !is_file(HttpCache::$sessionPath . '/ses' . $_COOKIE[HttpCache::$sessionName])) {
|
||||
$file_name = tempnam(HttpCache::$sessionPath, 'ses');
|
||||
if (!$file_name) {
|
||||
return false;
|
||||
}
|
||||
HttpCache::$instance->sessionFile = $file_name;
|
||||
$session_id = substr(basename($file_name), strlen('sess_'));
|
||||
$session_id = substr(basename($file_name), strlen('ses'));
|
||||
return self::setcookie(
|
||||
HttpCache::$sessionName
|
||||
, $session_id
|
||||
, ini_get('session.cookie_lifetime')
|
||||
, ini_get('session.cookie_path')
|
||||
, ini_get('session.cookie_domain')
|
||||
, ini_get('session.cookie_secure')
|
||||
, ini_get('session.cookie_httponly')
|
||||
HttpCache::$sessionName
|
||||
, $session_id
|
||||
, ini_get('session.cookie_lifetime')
|
||||
, ini_get('session.cookie_path')
|
||||
, ini_get('session.cookie_domain')
|
||||
, ini_get('session.cookie_secure')
|
||||
, ini_get('session.cookie_httponly')
|
||||
);
|
||||
}
|
||||
if(!HttpCache::$instance->sessionFile)
|
||||
{
|
||||
HttpCache::$instance->sessionFile = HttpCache::$sessionPath . '/sess_' . $_COOKIE[HttpCache::$sessionName];
|
||||
if (!HttpCache::$instance->sessionFile) {
|
||||
HttpCache::$instance->sessionFile = HttpCache::$sessionPath . '/ses' . $_COOKIE[HttpCache::$sessionName];
|
||||
}
|
||||
// 有sid则打开文件,读取session值
|
||||
if(HttpCache::$instance->sessionFile)
|
||||
{
|
||||
// Read session from session file.
|
||||
if (HttpCache::$instance->sessionFile) {
|
||||
$raw = file_get_contents(HttpCache::$instance->sessionFile);
|
||||
if($raw)
|
||||
{
|
||||
if ($raw) {
|
||||
session_decode($raw);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 保存session
|
||||
* Save session.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function sessionWriteClose()
|
||||
{
|
||||
if(PHP_SAPI != 'cli')
|
||||
{
|
||||
if (PHP_SAPI != 'cli') {
|
||||
return session_write_close();
|
||||
}
|
||||
if(!empty(HttpCache::$instance->sessionStarted) && !empty($_SESSION))
|
||||
{
|
||||
if (!empty(HttpCache::$instance->sessionStarted) && !empty($_SESSION)) {
|
||||
$session_str = session_encode();
|
||||
if($session_str && HttpCache::$instance->sessionFile)
|
||||
{
|
||||
if ($session_str && HttpCache::$instance->sessionFile) {
|
||||
return file_put_contents(HttpCache::$instance->sessionFile, $session_str);
|
||||
}
|
||||
}
|
||||
return empty($_SESSION);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 退出
|
||||
* End, like call exit in php-fpm.
|
||||
*
|
||||
* @param string $msg
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function end($msg = '')
|
||||
{
|
||||
if(PHP_SAPI != 'cli')
|
||||
{
|
||||
if (PHP_SAPI != 'cli') {
|
||||
exit($msg);
|
||||
}
|
||||
if($msg)
|
||||
{
|
||||
if ($msg) {
|
||||
echo $msg;
|
||||
}
|
||||
throw new \Exception('jump_exit');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* get mime types
|
||||
* Get mime types.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function getMimeTypesFile()
|
||||
{
|
||||
return __DIR__.'/Http/mime.types';
|
||||
return __DIR__ . '/Http/mime.types';
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析$_FILES
|
||||
|
||||
/**
|
||||
* Parse $_FILES.
|
||||
*
|
||||
* @param string $http_body
|
||||
* @param string $http_post_boundary
|
||||
* @return void
|
||||
*/
|
||||
protected function parseUploadFiles($http_body, $http_post_boundary)
|
||||
protected static function parseUploadFiles($http_body, $http_post_boundary)
|
||||
{
|
||||
$http_body = substr($http_body, 0, strlen($http_body) - (strlen($http_post_boundary) + 4));
|
||||
$boundary_data_array = explode($http_post_boundary."\r\n", $http_body);
|
||||
if($boundary_data_array[0] === '')
|
||||
{
|
||||
$http_body = substr($http_body, 0, strlen($http_body) - (strlen($http_post_boundary) + 4));
|
||||
$boundary_data_array = explode($http_post_boundary . "\r\n", $http_body);
|
||||
if ($boundary_data_array[0] === '') {
|
||||
unset($boundary_data_array[0]);
|
||||
}
|
||||
foreach($boundary_data_array as $boundary_data_buffer)
|
||||
{
|
||||
foreach ($boundary_data_array as $boundary_data_buffer) {
|
||||
list($boundary_header_buffer, $boundary_value) = explode("\r\n\r\n", $boundary_data_buffer, 2);
|
||||
// 去掉末尾\r\n
|
||||
// Remove \r\n from the end of buffer.
|
||||
$boundary_value = substr($boundary_value, 0, -2);
|
||||
foreach (explode("\r\n", $boundary_header_buffer) as $item)
|
||||
{
|
||||
foreach (explode("\r\n", $boundary_header_buffer) as $item) {
|
||||
list($header_key, $header_value) = explode(": ", $item);
|
||||
$header_key = strtolower($header_key);
|
||||
switch ($header_key)
|
||||
{
|
||||
switch ($header_key) {
|
||||
case "content-disposition":
|
||||
// 是文件
|
||||
if(preg_match('/name=".*?"; filename="(.*?)"$/', $header_value, $match))
|
||||
{
|
||||
// Is file data.
|
||||
if (preg_match('/name=".*?"; filename="(.*?)"$/', $header_value, $match)) {
|
||||
// Parse $_FILES.
|
||||
$_FILES[] = array(
|
||||
'file_name' => $match[1],
|
||||
'file_data' => $boundary_value,
|
||||
'file_size' => strlen($boundary_value),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
// 是post field
|
||||
else
|
||||
{
|
||||
// 收集post
|
||||
if(preg_match('/name="(.*?)"$/', $header_value, $match))
|
||||
{
|
||||
} // Is post field.
|
||||
else {
|
||||
// Parse $_POST.
|
||||
if (preg_match('/name="(.*?)"$/', $header_value, $match)) {
|
||||
$_POST[$match[1]] = $boundary_value;
|
||||
}
|
||||
}
|
||||
@@ -482,57 +436,61 @@ class Http
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析http协议数据包 缓存先关
|
||||
* @author walkor
|
||||
* Http cache for the current http response.
|
||||
*/
|
||||
class HttpCache
|
||||
{
|
||||
public static $codes = array(
|
||||
100 => 'Continue',
|
||||
101 => 'Switching Protocols',
|
||||
200 => 'OK',
|
||||
201 => 'Created',
|
||||
202 => 'Accepted',
|
||||
203 => 'Non-Authoritative Information',
|
||||
204 => 'No Content',
|
||||
205 => 'Reset Content',
|
||||
206 => 'Partial Content',
|
||||
300 => 'Multiple Choices',
|
||||
301 => 'Moved Permanently',
|
||||
302 => 'Found',
|
||||
303 => 'See Other',
|
||||
304 => 'Not Modified',
|
||||
305 => 'Use Proxy',
|
||||
306 => '(Unused)',
|
||||
307 => 'Temporary Redirect',
|
||||
400 => 'Bad Request',
|
||||
401 => 'Unauthorized',
|
||||
402 => 'Payment Required',
|
||||
403 => 'Forbidden',
|
||||
404 => 'Not Found',
|
||||
405 => 'Method Not Allowed',
|
||||
406 => 'Not Acceptable',
|
||||
407 => 'Proxy Authentication Required',
|
||||
408 => 'Request Timeout',
|
||||
409 => 'Conflict',
|
||||
410 => 'Gone',
|
||||
411 => 'Length Required',
|
||||
412 => 'Precondition Failed',
|
||||
413 => 'Request Entity Too Large',
|
||||
414 => 'Request-URI Too Long',
|
||||
415 => 'Unsupported Media Type',
|
||||
416 => 'Requested Range Not Satisfiable',
|
||||
417 => 'Expectation Failed',
|
||||
422 => 'Unprocessable Entity',
|
||||
423 => 'Locked',
|
||||
500 => 'Internal Server Error',
|
||||
501 => 'Not Implemented',
|
||||
502 => 'Bad Gateway',
|
||||
503 => 'Service Unavailable',
|
||||
504 => 'Gateway Timeout',
|
||||
505 => 'HTTP Version Not Supported',
|
||||
);
|
||||
100 => 'Continue',
|
||||
101 => 'Switching Protocols',
|
||||
200 => 'OK',
|
||||
201 => 'Created',
|
||||
202 => 'Accepted',
|
||||
203 => 'Non-Authoritative Information',
|
||||
204 => 'No Content',
|
||||
205 => 'Reset Content',
|
||||
206 => 'Partial Content',
|
||||
300 => 'Multiple Choices',
|
||||
301 => 'Moved Permanently',
|
||||
302 => 'Found',
|
||||
303 => 'See Other',
|
||||
304 => 'Not Modified',
|
||||
305 => 'Use Proxy',
|
||||
306 => '(Unused)',
|
||||
307 => 'Temporary Redirect',
|
||||
400 => 'Bad Request',
|
||||
401 => 'Unauthorized',
|
||||
402 => 'Payment Required',
|
||||
403 => 'Forbidden',
|
||||
404 => 'Not Found',
|
||||
405 => 'Method Not Allowed',
|
||||
406 => 'Not Acceptable',
|
||||
407 => 'Proxy Authentication Required',
|
||||
408 => 'Request Timeout',
|
||||
409 => 'Conflict',
|
||||
410 => 'Gone',
|
||||
411 => 'Length Required',
|
||||
412 => 'Precondition Failed',
|
||||
413 => 'Request Entity Too Large',
|
||||
414 => 'Request-URI Too Long',
|
||||
415 => 'Unsupported Media Type',
|
||||
416 => 'Requested Range Not Satisfiable',
|
||||
417 => 'Expectation Failed',
|
||||
422 => 'Unprocessable Entity',
|
||||
423 => 'Locked',
|
||||
500 => 'Internal Server Error',
|
||||
501 => 'Not Implemented',
|
||||
502 => 'Bad Gateway',
|
||||
503 => 'Service Unavailable',
|
||||
504 => 'Gateway Timeout',
|
||||
505 => 'HTTP Version Not Supported',
|
||||
);
|
||||
|
||||
/**
|
||||
* @var HttpCache
|
||||
*/
|
||||
public static $instance = null;
|
||||
|
||||
public static $header = array();
|
||||
public static $sessionPath = '';
|
||||
public static $sessionName = '';
|
||||
@@ -543,8 +501,7 @@ class HttpCache
|
||||
{
|
||||
self::$sessionName = ini_get('session.name');
|
||||
self::$sessionPath = session_save_path();
|
||||
if(!self::$sessionPath)
|
||||
{
|
||||
if (!self::$sessionPath) {
|
||||
self::$sessionPath = sys_get_temp_dir();
|
||||
}
|
||||
@\session_start();
|
||||
|
||||
@@ -1,43 +1,51 @@
|
||||
<?php
|
||||
/**
|
||||
* This file is part of workerman.
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the MIT-LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @author walkor<walkor@workerman.net>
|
||||
* @copyright walkor<walkor@workerman.net>
|
||||
* @link http://www.workerman.net/
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Workerman\Protocols;
|
||||
|
||||
use \Workerman\Connection\ConnectionInterface;
|
||||
use Workerman\Connection\ConnectionInterface;
|
||||
|
||||
/**
|
||||
* Protocol interface
|
||||
* @author walkor <walkor@workerman.net>
|
||||
*/
|
||||
interface ProtocolInterface
|
||||
{
|
||||
/**
|
||||
* 用于分包,即在接收的buffer中返回当前请求的长度(字节)
|
||||
* 如果可以在$recv_buffer中得到请求包的长度则返回长度
|
||||
* 否则返回0,表示需要更多的数据才能得到当前请求包的长度
|
||||
* 如果返回false或者负数,则代表请求不符合协议,则连接会断开
|
||||
* Check the integrity of the package.
|
||||
* Please return the length of package.
|
||||
* If length is unknow please return 0 that mean wating more data.
|
||||
* If the package has something wrong please return false the connection will be closed.
|
||||
*
|
||||
* @param ConnectionInterface $connection
|
||||
* @param string $recv_buffer
|
||||
* @param string $recv_buffer
|
||||
* @return int|false
|
||||
*/
|
||||
public static function input($recv_buffer, ConnectionInterface $connection);
|
||||
|
||||
|
||||
/**
|
||||
* 用于请求解包
|
||||
* input返回值大于0,并且WorkerMan收到了足够的数据,则自动调用decode
|
||||
* 然后触发onMessage回调,并将decode解码后的数据传递给onMessage回调的第二个参数
|
||||
* 也就是说当收到完整的客户端请求时,会自动调用decode解码,无需业务代码中手动调用
|
||||
* Decode package and emit onMessage($message) callback, $message is the result that decode returned.
|
||||
*
|
||||
* @param ConnectionInterface $connection
|
||||
* @param string $recv_buffer
|
||||
* @param string $recv_buffer
|
||||
* @return mixed
|
||||
*/
|
||||
public static function decode($recv_buffer, ConnectionInterface $connection);
|
||||
|
||||
|
||||
/**
|
||||
* 用于请求打包
|
||||
* 当需要向客户端发送数据即调用$connection->send($data);时
|
||||
* 会自动把$data用encode打包一次,变成符合协议的数据格式,然后再发送给客户端
|
||||
* 也就是说发送给客户端的数据会自动encode打包,无需业务代码中手动调用
|
||||
* Encode package brefore sending to client.
|
||||
*
|
||||
* @param ConnectionInterface $connection
|
||||
* @param mixed $data
|
||||
* @param mixed $data
|
||||
* @return string
|
||||
*/
|
||||
public static function encode($data, ConnectionInterface $connection);
|
||||
|
||||
@@ -1,60 +1,70 @@
|
||||
<?php
|
||||
<?php
|
||||
/**
|
||||
* This file is part of workerman.
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the MIT-LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @author walkor<walkor@workerman.net>
|
||||
* @copyright walkor<walkor@workerman.net>
|
||||
* @link http://www.workerman.net/
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Workerman\Protocols;
|
||||
use \Workerman\Connection\TcpConnection;
|
||||
|
||||
use Workerman\Connection\TcpConnection;
|
||||
|
||||
/**
|
||||
* Text协议
|
||||
* 以换行为请求结束标记
|
||||
* @author walkor <walkor@workerman.net>
|
||||
* Text Protocol.
|
||||
*/
|
||||
|
||||
class Text
|
||||
{
|
||||
/**
|
||||
* 检查包的完整性
|
||||
* 如果能够得到包长,则返回包的长度,否则返回0继续等待数据
|
||||
* @param string $buffer
|
||||
* Check the integrity of the package.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @param TcpConnection $connection
|
||||
* @return int
|
||||
*/
|
||||
public static function input($buffer ,TcpConnection $connection)
|
||||
public static function input($buffer, TcpConnection $connection)
|
||||
{
|
||||
// 由于没有包头,无法预先知道包长,不能无限制的接收数据,
|
||||
// 所以需要判断当前接收的数据是否超过限定值
|
||||
if(strlen($buffer)>=TcpConnection::$maxPackageSize)
|
||||
{
|
||||
// Judge whether the package length exceeds the limit.
|
||||
if (strlen($buffer) >= TcpConnection::$maxPackageSize) {
|
||||
$connection->close();
|
||||
return 0;
|
||||
}
|
||||
// 获得换行字符"\n"位置
|
||||
// Find the position of "\n".
|
||||
$pos = strpos($buffer, "\n");
|
||||
// 没有换行符,无法得知包长,返回0继续等待数据
|
||||
if($pos === false)
|
||||
{
|
||||
// No "\n", packet length is unknown, continue to wait for the data so return 0.
|
||||
if ($pos === false) {
|
||||
return 0;
|
||||
}
|
||||
// 有换行符,返回当前包长,包含换行符
|
||||
return $pos+1;
|
||||
// Return the current package length.
|
||||
return $pos + 1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 打包,当向客户端发送数据的时候会自动调用
|
||||
* Encode.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @return string
|
||||
*/
|
||||
public static function encode($buffer)
|
||||
{
|
||||
// 加上换行
|
||||
return $buffer."\n";
|
||||
// Add "\n"
|
||||
return $buffer . "\n";
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 解包,当接收到的数据字节数等于input返回的值(大于0的值)自动调用
|
||||
* 并传递给onMessage回调函数的$data参数
|
||||
* Decode.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @return string
|
||||
*/
|
||||
public static function decode($buffer)
|
||||
{
|
||||
// 去掉换行
|
||||
// Remove "\n"
|
||||
return trim($buffer);
|
||||
}
|
||||
}
|
||||
|
||||
+276
-229
@@ -1,221 +1,258 @@
|
||||
<?php
|
||||
namespace Workerman\Protocols;
|
||||
<?php
|
||||
/**
|
||||
* WebSocket 协议服务端解包和打包
|
||||
* @author walkor <walkor@workerman.net>
|
||||
* This file is part of workerman.
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the MIT-LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @author walkor<walkor@workerman.net>
|
||||
* @copyright walkor<walkor@workerman.net>
|
||||
* @link http://www.workerman.net/
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Workerman\Protocols;
|
||||
|
||||
use Workerman\Connection\ConnectionInterface;
|
||||
use Workerman\Worker;
|
||||
|
||||
/**
|
||||
* WebSocket protocol.
|
||||
*/
|
||||
class Websocket implements \Workerman\Protocols\ProtocolInterface
|
||||
{
|
||||
/**
|
||||
* websocket头部最小长度
|
||||
* Minimum head length of websocket protocol.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
const MIN_HEAD_LEN = 6;
|
||||
|
||||
const MIN_HEAD_LEN = 2;
|
||||
|
||||
/**
|
||||
* websocket blob类型
|
||||
* @var char
|
||||
* Websocket blob type.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const BINARY_TYPE_BLOB = "\x81";
|
||||
|
||||
/**
|
||||
* websocket arraybuffer类型
|
||||
* @var char
|
||||
* Websocket arraybuffer type.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const BINARY_TYPE_ARRAYBUFFER = "\x82";
|
||||
|
||||
|
||||
/**
|
||||
* 检查包的完整性
|
||||
* @param string $buffer
|
||||
* Check the integrity of the package.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @param ConnectionInterface $connection
|
||||
* @return int
|
||||
*/
|
||||
public static function input($buffer, ConnectionInterface $connection)
|
||||
{
|
||||
// 数据长度
|
||||
// Receive length.
|
||||
$recv_len = strlen($buffer);
|
||||
// 长度不够
|
||||
if($recv_len < self::MIN_HEAD_LEN)
|
||||
{
|
||||
// We need more data.
|
||||
if ($recv_len < self::MIN_HEAD_LEN) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 还没有握手
|
||||
if(empty($connection->websocketHandshake))
|
||||
{
|
||||
|
||||
// Has not yet completed the handshake.
|
||||
if (empty($connection->websocketHandshake)) {
|
||||
return self::dealHandshake($buffer, $connection);
|
||||
}
|
||||
|
||||
// $connection->websocketCurrentFrameLength有值说明当前fin为0,则缓冲websocket帧数据
|
||||
if($connection->websocketCurrentFrameLength)
|
||||
{
|
||||
// 如果当前帧数据未收全,则继续收
|
||||
if($connection->websocketCurrentFrameLength > $recv_len)
|
||||
{
|
||||
// 返回0,因为不清楚完整的数据包长度,需要等待fin=1的帧
|
||||
|
||||
// Buffer websocket frame data.
|
||||
if ($connection->websocketCurrentFrameLength) {
|
||||
// We need more frame data.
|
||||
if ($connection->websocketCurrentFrameLength > $recv_len) {
|
||||
// Return 0, because it is not clear the full packet length, waiting for the frame of fin=1.
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$data_len = ord($buffer[1]) & 127;
|
||||
$firstbyte = ord($buffer[0]);
|
||||
$is_fin_frame = $firstbyte>>7;
|
||||
$opcode = $firstbyte & 0xf;
|
||||
switch($opcode)
|
||||
{
|
||||
// 附加数据帧 @todo 实现附加数据帧
|
||||
} else {
|
||||
$data_len = ord($buffer[1]) & 127;
|
||||
$firstbyte = ord($buffer[0]);
|
||||
$is_fin_frame = $firstbyte >> 7;
|
||||
$opcode = $firstbyte & 0xf;
|
||||
switch ($opcode) {
|
||||
case 0x0:
|
||||
break;
|
||||
// 文本数据帧
|
||||
// Blob type.
|
||||
case 0x1:
|
||||
break;
|
||||
// 二进制数据帧
|
||||
// Arraybuffer type.
|
||||
case 0x2:
|
||||
break;
|
||||
// 关闭的包
|
||||
// Close package.
|
||||
case 0x8:
|
||||
// 如果有设置onWebSocketClose回调,尝试执行
|
||||
if(isset($connection->onWebSocketClose))
|
||||
{
|
||||
call_user_func($connection->onWebSocketClose, $connection);
|
||||
}
|
||||
// 默认行为是关闭连接
|
||||
else
|
||||
{
|
||||
// Try to emit onWebSocketClose callback.
|
||||
if (isset($connection->onWebSocketClose)) {
|
||||
try {
|
||||
call_user_func($connection->onWebSocketClose, $connection);
|
||||
} catch (\Exception $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
} catch (\Error $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
}
|
||||
} // Close connection.
|
||||
else {
|
||||
$connection->close();
|
||||
}
|
||||
return 0;
|
||||
// ping的包
|
||||
// Ping package.
|
||||
case 0x9:
|
||||
// 如果有设置onWebSocketPing回调,尝试执行
|
||||
if(isset($connection->onWebSocketPing))
|
||||
{
|
||||
call_user_func($connection->onWebSocketPing, $connection);
|
||||
}
|
||||
// 默认发送pong
|
||||
else
|
||||
{
|
||||
// Try to emit onWebSocketPing callback.
|
||||
if (isset($connection->onWebSocketPing)) {
|
||||
try {
|
||||
call_user_func($connection->onWebSocketPing, $connection);
|
||||
} catch (\Exception $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
} catch (\Error $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
}
|
||||
} // Send pong package to client.
|
||||
else {
|
||||
$connection->send(pack('H*', '8a00'), true);
|
||||
}
|
||||
// 从接受缓冲区中消费掉该数据包
|
||||
if(!$data_len)
|
||||
{
|
||||
|
||||
// Consume data from receive buffer.
|
||||
if (!$data_len) {
|
||||
$connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
|
||||
if ($recv_len > self::MIN_HEAD_LEN) {
|
||||
return self::input(substr($buffer, self::MIN_HEAD_LEN), $connection);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
// pong的包
|
||||
// Pong package.
|
||||
case 0xa:
|
||||
// 如果有设置onWebSocketPong回调,尝试执行
|
||||
if(isset($connection->onWebSocketPong))
|
||||
{
|
||||
call_user_func($connection->onWebSocketPong, $connection);
|
||||
// Try to emit onWebSocketPong callback.
|
||||
if (isset($connection->onWebSocketPong)) {
|
||||
try {
|
||||
call_user_func($connection->onWebSocketPong, $connection);
|
||||
} catch (\Exception $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
} catch (\Error $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
}
|
||||
}
|
||||
// 从接受缓冲区中消费掉该数据包
|
||||
if(!$data_len)
|
||||
{
|
||||
// Consume data from receive buffer.
|
||||
if (!$data_len) {
|
||||
$connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
|
||||
if ($recv_len > self::MIN_HEAD_LEN) {
|
||||
return self::input(substr($buffer, self::MIN_HEAD_LEN), $connection);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
// 错误的opcode
|
||||
// Wrong opcode.
|
||||
default :
|
||||
echo "error opcode $opcode and close websocket connection\n";
|
||||
echo "error opcode $opcode and close websocket connection. Buffer:" . bin2hex($buffer) . "\n";
|
||||
$connection->close();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// websocket二进制数据
|
||||
$head_len = self::MIN_HEAD_LEN;
|
||||
|
||||
// Calculate packet length.
|
||||
$head_len = 6;
|
||||
if ($data_len === 126) {
|
||||
$head_len = 8;
|
||||
if($head_len > $recv_len)
|
||||
{
|
||||
if ($head_len > $recv_len) {
|
||||
return 0;
|
||||
}
|
||||
$pack = unpack('ntotal_len', substr($buffer, 2, 2));
|
||||
$pack = unpack('nn/ntotal_len', $buffer);
|
||||
$data_len = $pack['total_len'];
|
||||
} else if ($data_len === 127) {
|
||||
$head_len = 14;
|
||||
if($head_len > $recv_len)
|
||||
{
|
||||
return 0;
|
||||
} else {
|
||||
if ($data_len === 127) {
|
||||
$head_len = 14;
|
||||
if ($head_len > $recv_len) {
|
||||
return 0;
|
||||
}
|
||||
$arr = unpack('n/N2c', $buffer);
|
||||
$data_len = $arr['c1']*4294967296 + $arr['c2'];
|
||||
}
|
||||
$arr = unpack('N2', substr($buffer, 2, 8));
|
||||
$data_len = $arr[1]*4294967296 + $arr[2];
|
||||
}
|
||||
$current_frame_length = $head_len + $data_len;
|
||||
if($is_fin_frame)
|
||||
{
|
||||
if ($is_fin_frame) {
|
||||
return $current_frame_length;
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
$connection->websocketCurrentFrameLength = $current_frame_length;
|
||||
}
|
||||
}
|
||||
|
||||
// 收到的数据刚好是一个frame
|
||||
if($connection->websocketCurrentFrameLength == $recv_len)
|
||||
{
|
||||
|
||||
// Received just a frame length data.
|
||||
if ($connection->websocketCurrentFrameLength === $recv_len) {
|
||||
self::decode($buffer, $connection);
|
||||
$connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
|
||||
$connection->websocketCurrentFrameLength = 0;
|
||||
return 0;
|
||||
}
|
||||
// 收到的数据大于一个frame
|
||||
elseif($connection->websocketCurrentFrameLength < $recv_len)
|
||||
{
|
||||
} // The length of the received data is greater than the length of a frame.
|
||||
elseif ($connection->websocketCurrentFrameLength < $recv_len) {
|
||||
self::decode(substr($buffer, 0, $connection->websocketCurrentFrameLength), $connection);
|
||||
$connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
|
||||
$current_frame_length = $connection->websocketCurrentFrameLength;
|
||||
$current_frame_length = $connection->websocketCurrentFrameLength;
|
||||
$connection->websocketCurrentFrameLength = 0;
|
||||
// 继续读取下一个frame
|
||||
// Continue to read next frame.
|
||||
return self::input(substr($buffer, $current_frame_length), $connection);
|
||||
}
|
||||
// 收到的数据不足一个frame
|
||||
else
|
||||
{
|
||||
} // The length of the received data is less than the length of a frame.
|
||||
else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 打包
|
||||
* @param string $buffer
|
||||
* Websocket encode.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @param ConnectionInterface $connection
|
||||
* @return string
|
||||
*/
|
||||
public static function encode($buffer, ConnectionInterface $connection)
|
||||
{
|
||||
if (!is_scalar($buffer)) {
|
||||
throw new \Exception("You can't send(" . gettype($buffer) . ") to client, you need to convert it to a string. ");
|
||||
}
|
||||
$len = strlen($buffer);
|
||||
// 还没握手不能发数据
|
||||
if(empty($connection->websocketHandshake))
|
||||
{
|
||||
$connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Send data before handshake. ", true);
|
||||
$connection->close();
|
||||
return false;
|
||||
if (empty($connection->websocketType)) {
|
||||
$connection->websocketType = self::BINARY_TYPE_BLOB;
|
||||
}
|
||||
|
||||
$first_byte = $connection->websocketType;
|
||||
|
||||
if($len<=125)
|
||||
{
|
||||
return $first_byte.chr($len).$buffer;
|
||||
|
||||
if ($len <= 125) {
|
||||
$encode_buffer = $first_byte . chr($len) . $buffer;
|
||||
} else {
|
||||
if ($len <= 65535) {
|
||||
$encode_buffer = $first_byte . chr(126) . pack("n", $len) . $buffer;
|
||||
} else {
|
||||
$encode_buffer = $first_byte . chr(127) . pack("xxxxN", $len) . $buffer;
|
||||
}
|
||||
}
|
||||
else if($len<=65535)
|
||||
{
|
||||
return $first_byte.chr(126).pack("n", $len).$buffer;
|
||||
}
|
||||
else
|
||||
{
|
||||
return $first_byte.chr(127).pack("xxxxN", $len).$buffer;
|
||||
|
||||
// Handshake not completed so temporary buffer websocket data waiting for send.
|
||||
if (empty($connection->websocketHandshake)) {
|
||||
if (empty($connection->tmpWebsocketData)) {
|
||||
$connection->tmpWebsocketData = '';
|
||||
}
|
||||
$connection->tmpWebsocketData .= $encode_buffer;
|
||||
// Return empty string.
|
||||
return '';
|
||||
}
|
||||
|
||||
return $encode_buffer;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 解包
|
||||
* @param string $buffer
|
||||
* Websocket decode.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @param ConnectionInterface $connection
|
||||
* @return string
|
||||
*/
|
||||
public static function decode($buffer, ConnectionInterface $connection)
|
||||
@@ -224,166 +261,176 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
|
||||
$len = ord($buffer[1]) & 127;
|
||||
if ($len === 126) {
|
||||
$masks = substr($buffer, 4, 4);
|
||||
$data = substr($buffer, 8);
|
||||
} else if ($len === 127) {
|
||||
$masks = substr($buffer, 10, 4);
|
||||
$data = substr($buffer, 14);
|
||||
$data = substr($buffer, 8);
|
||||
} else {
|
||||
$masks = substr($buffer, 2, 4);
|
||||
$data = substr($buffer, 6);
|
||||
if ($len === 127) {
|
||||
$masks = substr($buffer, 10, 4);
|
||||
$data = substr($buffer, 14);
|
||||
} else {
|
||||
$masks = substr($buffer, 2, 4);
|
||||
$data = substr($buffer, 6);
|
||||
}
|
||||
}
|
||||
for ($index = 0; $index < strlen($data); $index++) {
|
||||
$decoded .= $data[$index] ^ $masks[$index % 4];
|
||||
}
|
||||
if($connection->websocketCurrentFrameLength)
|
||||
{
|
||||
if ($connection->websocketCurrentFrameLength) {
|
||||
$connection->websocketDataBuffer .= $decoded;
|
||||
return $connection->websocketDataBuffer;
|
||||
}
|
||||
else
|
||||
{
|
||||
$decoded = $connection->websocketDataBuffer . $decoded;
|
||||
$connection->websocketDataBuffer = '';
|
||||
} else {
|
||||
if ($connection->websocketDataBuffer !== '') {
|
||||
$decoded = $connection->websocketDataBuffer . $decoded;
|
||||
$connection->websocketDataBuffer = '';
|
||||
}
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 处理websocket握手
|
||||
* @param string $buffer
|
||||
* @param TcpConnection $connection
|
||||
* Websocket handshake.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @param \Workerman\Connection\TcpConnection $connection
|
||||
* @return int
|
||||
*/
|
||||
protected static function dealHandshake($buffer, $connection)
|
||||
{
|
||||
// 握手阶段客户端发送HTTP协议
|
||||
if(0 === strpos($buffer, 'GET'))
|
||||
{
|
||||
// 判断\r\n\r\n边界
|
||||
// HTTP protocol.
|
||||
if (0 === strpos($buffer, 'GET')) {
|
||||
// Find \r\n\r\n.
|
||||
$heder_end_pos = strpos($buffer, "\r\n\r\n");
|
||||
if(!$heder_end_pos)
|
||||
{
|
||||
if (!$heder_end_pos) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 解析Sec-WebSocket-Key
|
||||
$header_length = $heder_end_pos + 4;
|
||||
|
||||
// Get Sec-WebSocket-Key.
|
||||
$Sec_WebSocket_Key = '';
|
||||
if(preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/", $buffer, $match))
|
||||
{
|
||||
if (preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) {
|
||||
$Sec_WebSocket_Key = $match[1];
|
||||
}
|
||||
else
|
||||
{
|
||||
$connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Sec-WebSocket-Key not found", true);
|
||||
} else {
|
||||
$connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Sec-WebSocket-Key not found.<br>This is a WebSocket service and can not be accessed via HTTP.<br>See <a href=\"http://wiki.workerman.net/Error1\">http://wiki.workerman.net/Error1</a>",
|
||||
true);
|
||||
$connection->close();
|
||||
return 0;
|
||||
}
|
||||
$new_key = base64_encode(sha1($Sec_WebSocket_Key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
|
||||
// 握手返回的数据
|
||||
$new_message = "HTTP/1.1 101 Switching Protocols\r\n";
|
||||
$new_message .= "Upgrade: websocket\r\n";
|
||||
$new_message .= "Sec-WebSocket-Version: 13\r\n";
|
||||
$new_message .= "Connection: Upgrade\r\n";
|
||||
$new_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
|
||||
// Calculation websocket key.
|
||||
$new_key = base64_encode(sha1($Sec_WebSocket_Key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
|
||||
// Handshake response data.
|
||||
$handshake_message = "HTTP/1.1 101 Switching Protocols\r\n";
|
||||
$handshake_message .= "Upgrade: websocket\r\n";
|
||||
$handshake_message .= "Sec-WebSocket-Version: 13\r\n";
|
||||
$handshake_message .= "Connection: Upgrade\r\n";
|
||||
$handshake_message .= "Server: workerman/".Worker::VERSION."\r\n";
|
||||
$handshake_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
|
||||
// Mark handshake complete..
|
||||
$connection->websocketHandshake = true;
|
||||
// Websocket data buffer.
|
||||
$connection->websocketDataBuffer = '';
|
||||
// Current websocket frame length.
|
||||
$connection->websocketCurrentFrameLength = 0;
|
||||
// Current websocket frame data.
|
||||
$connection->websocketCurrentFrameBuffer = '';
|
||||
$connection->consumeRecvBuffer(strlen($buffer));
|
||||
$connection->send($new_message, true);
|
||||
// blob or arraybuffer
|
||||
$connection->websocketType = self::BINARY_TYPE_BLOB;
|
||||
// 如果有设置onWebSocketConnect回调,尝试执行
|
||||
if(isset($connection->onWebSocketConnect))
|
||||
{
|
||||
self::parseHttpHeader($buffer);
|
||||
try
|
||||
{
|
||||
call_user_func($connection->onWebSocketConnect, $connection, $buffer);
|
||||
}
|
||||
catch(\Exception $e)
|
||||
{
|
||||
echo $e;
|
||||
}
|
||||
$_GET = $_COOKIE = $_SERVER = array();
|
||||
// Consume handshake data.
|
||||
$connection->consumeRecvBuffer($header_length);
|
||||
// Send handshake response.
|
||||
$connection->send($handshake_message, true);
|
||||
|
||||
// There are data waiting to be sent.
|
||||
if (!empty($connection->tmpWebsocketData)) {
|
||||
$connection->send($connection->tmpWebsocketData, true);
|
||||
$connection->tmpWebsocketData = '';
|
||||
}
|
||||
// blob or arraybuffer
|
||||
if (empty($connection->websocketType)) {
|
||||
$connection->websocketType = self::BINARY_TYPE_BLOB;
|
||||
}
|
||||
// Try to emit onWebSocketConnect callback.
|
||||
if (isset($connection->onWebSocketConnect)) {
|
||||
self::parseHttpHeader($buffer);
|
||||
try {
|
||||
call_user_func($connection->onWebSocketConnect, $connection, $buffer);
|
||||
} catch (\Exception $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
} catch (\Error $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
}
|
||||
if (!empty($_SESSION) && class_exists('\GatewayWorker\Lib\Context')) {
|
||||
$connection->session = \GatewayWorker\Lib\Context::sessionEncode($_SESSION);
|
||||
}
|
||||
$_GET = $_SERVER = $_SESSION = $_COOKIE = array();
|
||||
}
|
||||
if (strlen($buffer) > $header_length) {
|
||||
return self::input(substr($buffer, $header_length), $connection);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// 如果是flash的policy-file-request
|
||||
elseif(0 === strpos($buffer,'<polic'))
|
||||
{
|
||||
$policy_xml = '<?xml version="1.0"?><cross-domain-policy><site-control permitted-cross-domain-policies="all"/><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>'."\0";
|
||||
} // Is flash policy-file-request.
|
||||
elseif (0 === strpos($buffer, '<polic')) {
|
||||
$policy_xml = '<?xml version="1.0"?><cross-domain-policy><site-control permitted-cross-domain-policies="all"/><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>' . "\0";
|
||||
$connection->send($policy_xml, true);
|
||||
$connection->consumeRecvBuffer(strlen($buffer));
|
||||
return 0;
|
||||
}
|
||||
// 出错
|
||||
$connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Invalid handshake data for websocket. ", true);
|
||||
// Bad websocket handshake request.
|
||||
$connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Invalid handshake data for websocket. ",
|
||||
true);
|
||||
$connection->close();
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 从header中获取
|
||||
* Parse http header.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @return void
|
||||
*/
|
||||
protected static function parseHttpHeader($buffer)
|
||||
{
|
||||
$header_data = explode("\r\n", $buffer);
|
||||
$_SERVER = array();
|
||||
list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ', $header_data[0]);
|
||||
// Parse headers.
|
||||
list($http_header, ) = explode("\r\n\r\n", $buffer, 2);
|
||||
$header_data = explode("\r\n", $http_header);
|
||||
|
||||
if ($_SERVER) {
|
||||
$_SERVER = array();
|
||||
}
|
||||
|
||||
list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ',
|
||||
$header_data[0]);
|
||||
|
||||
unset($header_data[0]);
|
||||
foreach($header_data as $content)
|
||||
{
|
||||
foreach ($header_data as $content) {
|
||||
// \r\n\r\n
|
||||
if(empty($content))
|
||||
{
|
||||
if (empty($content)) {
|
||||
continue;
|
||||
}
|
||||
list($key, $value) = explode(':', $content, 2);
|
||||
$key = strtolower($key);
|
||||
$value = trim($value);
|
||||
switch($key)
|
||||
{
|
||||
list($key, $value) = explode(':', $content, 2);
|
||||
$key = str_replace('-', '_', strtoupper($key));
|
||||
$value = trim($value);
|
||||
$_SERVER['HTTP_' . $key] = $value;
|
||||
switch ($key) {
|
||||
// HTTP_HOST
|
||||
case 'host':
|
||||
$_SERVER['HTTP_HOST'] = $value;
|
||||
$tmp = explode(':', $value);
|
||||
case 'HOST':
|
||||
$tmp = explode(':', $value);
|
||||
$_SERVER['SERVER_NAME'] = $tmp[0];
|
||||
if(isset($tmp[1]))
|
||||
{
|
||||
if (isset($tmp[1])) {
|
||||
$_SERVER['SERVER_PORT'] = $tmp[1];
|
||||
}
|
||||
break;
|
||||
// HTTP_COOKIE
|
||||
case 'cookie':
|
||||
$_SERVER['HTTP_COOKIE'] = $value;
|
||||
// cookie
|
||||
case 'COOKIE':
|
||||
parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
|
||||
break;
|
||||
// HTTP_USER_AGENT
|
||||
case 'user-agent':
|
||||
$_SERVER['HTTP_USER_AGENT'] = $value;
|
||||
break;
|
||||
// HTTP_REFERER
|
||||
case 'referer':
|
||||
$_SERVER['HTTP_REFERER'] = $value;
|
||||
break;
|
||||
case 'origin':
|
||||
$_SERVER['HTTP_ORIGIN'] = $value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// QUERY_STRING
|
||||
$_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
|
||||
if($_SERVER['QUERY_STRING'])
|
||||
{
|
||||
if ($_SERVER['QUERY_STRING']) {
|
||||
// $GET
|
||||
parse_str($_SERVER['QUERY_STRING'], $_GET);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
$_SERVER['QUERY_STRING'] = '';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,383 @@
|
||||
<?php
|
||||
namespace Workerman\Protocols;
|
||||
|
||||
use Workerman\Worker;
|
||||
use Workerman\Lib\Timer;
|
||||
|
||||
/**
|
||||
* Websocket protocol for client.
|
||||
*/
|
||||
class Ws
|
||||
{
|
||||
/**
|
||||
* Minimum head length of websocket protocol.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
const MIN_HEAD_LEN = 2;
|
||||
|
||||
/**
|
||||
* Websocket blob type.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const BINARY_TYPE_BLOB = "\x81";
|
||||
|
||||
/**
|
||||
* Websocket arraybuffer type.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const BINARY_TYPE_ARRAYBUFFER = "\x82";
|
||||
|
||||
/**
|
||||
* Check the integrity of the package.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @param ConnectionInterface $connection
|
||||
* @return int
|
||||
*/
|
||||
public static function input($buffer, $connection)
|
||||
{
|
||||
if (empty($connection->handshakeStep)) {
|
||||
echo "recv data before handshake. Buffer:" . bin2hex($buffer) . "\n";
|
||||
return false;
|
||||
}
|
||||
// Recv handshake response
|
||||
if ($connection->handshakeStep === 1) {
|
||||
return self::dealHandshake($buffer, $connection);
|
||||
}
|
||||
$recv_len = strlen($buffer);
|
||||
if ($recv_len < self::MIN_HEAD_LEN) {
|
||||
return 0;
|
||||
}
|
||||
// Buffer websocket frame data.
|
||||
if ($connection->websocketCurrentFrameLength) {
|
||||
// We need more frame data.
|
||||
if ($connection->websocketCurrentFrameLength > $recv_len) {
|
||||
// Return 0, because it is not clear the full packet length, waiting for the frame of fin=1.
|
||||
return 0;
|
||||
}
|
||||
} else {
|
||||
$data_len = ord($buffer[1]) & 127;
|
||||
$firstbyte = ord($buffer[0]);
|
||||
$is_fin_frame = $firstbyte >> 7;
|
||||
$opcode = $firstbyte & 0xf;
|
||||
switch ($opcode) {
|
||||
case 0x0:
|
||||
break;
|
||||
// Blob type.
|
||||
case 0x1:
|
||||
break;
|
||||
// Arraybuffer type.
|
||||
case 0x2:
|
||||
break;
|
||||
// Close package.
|
||||
case 0x8:
|
||||
// Try to emit onWebSocketClose callback.
|
||||
if (isset($connection->onWebSocketClose)) {
|
||||
try {
|
||||
call_user_func($connection->onWebSocketClose, $connection);
|
||||
} catch (\Exception $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
} catch (\Error $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
}
|
||||
} // Close connection.
|
||||
else {
|
||||
$connection->close();
|
||||
}
|
||||
return 0;
|
||||
// Ping package.
|
||||
case 0x9:
|
||||
// Try to emit onWebSocketPing callback.
|
||||
if (isset($connection->onWebSocketPing)) {
|
||||
try {
|
||||
call_user_func($connection->onWebSocketPing, $connection);
|
||||
} catch (\Exception $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
} catch (\Error $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
}
|
||||
} // Send pong package to client.
|
||||
else {
|
||||
$connection->send(pack('H*', '8a00'), true);
|
||||
}
|
||||
// Consume data from receive buffer.
|
||||
if (!$data_len) {
|
||||
$connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
|
||||
if ($recv_len > self::MIN_HEAD_LEN) {
|
||||
return self::input(substr($buffer, self::MIN_HEAD_LEN), $connection);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
// Pong package.
|
||||
case 0xa:
|
||||
// Try to emit onWebSocketPong callback.
|
||||
if (isset($connection->onWebSocketPong)) {
|
||||
try {
|
||||
call_user_func($connection->onWebSocketPong, $connection);
|
||||
} catch (\Exception $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
} catch (\Error $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
}
|
||||
}
|
||||
// Consume data from receive buffer.
|
||||
if (!$data_len) {
|
||||
$connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
|
||||
if ($recv_len > self::MIN_HEAD_LEN) {
|
||||
return self::input(substr($buffer, self::MIN_HEAD_LEN), $connection);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
// Wrong opcode.
|
||||
default :
|
||||
echo "error opcode $opcode and close websocket connection. Buffer:" . $buffer . "\n";
|
||||
$connection->close();
|
||||
return 0;
|
||||
}
|
||||
// Calculate packet length.
|
||||
if ($data_len === 126) {
|
||||
if (strlen($buffer) < 6) {
|
||||
return 0;
|
||||
}
|
||||
$pack = unpack('nn/ntotal_len', $buffer);
|
||||
$current_frame_length = $pack['total_len'] + 4;
|
||||
} else if ($data_len === 127) {
|
||||
if (strlen($buffer) < 10) {
|
||||
return 0;
|
||||
}
|
||||
$arr = unpack('n/N2c', $buffer);
|
||||
$current_frame_length = $arr['c1']*4294967296 + $arr['c2'] + 10;
|
||||
} else {
|
||||
$current_frame_length = $data_len + 2;
|
||||
}
|
||||
if ($is_fin_frame) {
|
||||
return $current_frame_length;
|
||||
} else {
|
||||
$connection->websocketCurrentFrameLength = $current_frame_length;
|
||||
}
|
||||
}
|
||||
// Received just a frame length data.
|
||||
if ($connection->websocketCurrentFrameLength === $recv_len) {
|
||||
self::decode($buffer, $connection);
|
||||
$connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
|
||||
$connection->websocketCurrentFrameLength = 0;
|
||||
return 0;
|
||||
} // The length of the received data is greater than the length of a frame.
|
||||
elseif ($connection->websocketCurrentFrameLength < $recv_len) {
|
||||
self::decode(substr($buffer, 0, $connection->websocketCurrentFrameLength), $connection);
|
||||
$connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
|
||||
$current_frame_length = $connection->websocketCurrentFrameLength;
|
||||
$connection->websocketCurrentFrameLength = 0;
|
||||
// Continue to read next frame.
|
||||
return self::input(substr($buffer, $current_frame_length), $connection);
|
||||
} // The length of the received data is less than the length of a frame.
|
||||
else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Websocket encode.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @param ConnectionInterface $connection
|
||||
* @return string
|
||||
*/
|
||||
public static function encode($payload, $connection)
|
||||
{
|
||||
if (empty($connection->websocketType)) {
|
||||
$connection->websocketType = self::BINARY_TYPE_BLOB;
|
||||
}
|
||||
$payload = (string)$payload;
|
||||
if (empty($connection->handshakeStep)) {
|
||||
self::sendHandshake($connection);
|
||||
}
|
||||
$mask = 1;
|
||||
$mask_key = "\x00\x00\x00\x00";
|
||||
|
||||
$pack = '';
|
||||
$length = $length_flag = strlen($payload);
|
||||
if (65535 < $length) {
|
||||
$pack = pack('NN', ($length & 0xFFFFFFFF00000000) >> 32, $length & 0x00000000FFFFFFFF);
|
||||
$length_flag = 127;
|
||||
} else if (125 < $length) {
|
||||
$pack = pack('n*', $length);
|
||||
$length_flag = 126;
|
||||
}
|
||||
|
||||
$head = ($mask << 7) | $length_flag;
|
||||
$head = $connection->websocketType . chr($head) . $pack;
|
||||
|
||||
$frame = $head . $mask_key;
|
||||
// append payload to frame:
|
||||
for ($i = 0; $i < $length; $i++) {
|
||||
$frame .= $payload[$i] ^ $mask_key[$i % 4];
|
||||
}
|
||||
if ($connection->handshakeStep === 1) {
|
||||
$connection->tmpWebsocketData = isset($connection->tmpWebsocketData) ? $connection->tmpWebsocketData . $frame : $frame;
|
||||
return '';
|
||||
}
|
||||
return $frame;
|
||||
}
|
||||
|
||||
/**
|
||||
* Websocket decode.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @param ConnectionInterface $connection
|
||||
* @return string
|
||||
*/
|
||||
public static function decode($bytes, $connection)
|
||||
{
|
||||
$masked = $bytes[1] >> 7;
|
||||
$data_length = $masked ? ord($bytes[1]) & 127 : ord($bytes[1]);
|
||||
$decoded_data = '';
|
||||
if ($masked === true) {
|
||||
if ($data_length === 126) {
|
||||
$mask = substr($bytes, 4, 4);
|
||||
$coded_data = substr($bytes, 8);
|
||||
} else if ($data_length === 127) {
|
||||
$mask = substr($bytes, 10, 4);
|
||||
$coded_data = substr($bytes, 14);
|
||||
} else {
|
||||
$mask = substr($bytes, 2, 4);
|
||||
$coded_data = substr($bytes, 6);
|
||||
}
|
||||
for ($i = 0; $i < strlen($coded_data); $i++) {
|
||||
$decoded_data .= $coded_data[$i] ^ $mask[$i % 4];
|
||||
}
|
||||
} else {
|
||||
if ($data_length === 126) {
|
||||
$decoded_data = substr($bytes, 4);
|
||||
} else if ($data_length === 127) {
|
||||
$decoded_data = substr($bytes, 10);
|
||||
} else {
|
||||
$decoded_data = substr($bytes, 2);
|
||||
}
|
||||
}
|
||||
if ($connection->websocketCurrentFrameLength) {
|
||||
$connection->websocketDataBuffer .= $decoded_data;
|
||||
return $connection->websocketDataBuffer;
|
||||
} else {
|
||||
if ($connection->websocketDataBuffer !== '') {
|
||||
$decoded_data = $connection->websocketDataBuffer . $decoded_data;
|
||||
$connection->websocketDataBuffer = '';
|
||||
}
|
||||
return $decoded_data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send websocket handshake data.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function onConnect($connection)
|
||||
{
|
||||
self::sendHandshake($connection);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean
|
||||
*
|
||||
* @param $connection
|
||||
*/
|
||||
public static function onClose($connection)
|
||||
{
|
||||
$connection->handshakeStep = null;
|
||||
$connection->websocketCurrentFrameLength = 0;
|
||||
$connection->tmpWebsocketData = '';
|
||||
$connection->websocketDataBuffer = '';
|
||||
if (!empty($connection->websocketPingTimer)) {
|
||||
Timer::del($connection->websocketPingTimer);
|
||||
$connection->websocketPingTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send websocket handshake.
|
||||
*
|
||||
* @param \Workerman\Connection\TcpConnection $connection
|
||||
* @return void
|
||||
*/
|
||||
public static function sendHandshake($connection)
|
||||
{
|
||||
if (!empty($connection->handshakeStep)) {
|
||||
return;
|
||||
}
|
||||
// Get Host.
|
||||
$port = $connection->getRemotePort();
|
||||
$host = $port === 80 ? $connection->getRemoteHost() : $connection->getRemoteHost() . ':' . $port;
|
||||
// Handshake header.
|
||||
$header = 'GET ' . $connection->getRemoteURI() . " HTTP/1.1\r\n".
|
||||
"Host: $host\r\n".
|
||||
"Connection: Upgrade\r\n".
|
||||
"Upgrade: websocket\r\n".
|
||||
"Origin: ". (isset($connection->websocketOrigin) ? $connection->websocketOrigin : '*') ."\r\n".
|
||||
"Sec-WebSocket-Version: 13\r\n".
|
||||
"Sec-WebSocket-Key: ".base64_encode(sha1(uniqid(mt_rand(), true), true))."\r\n\r\n";
|
||||
$connection->send($header, true);
|
||||
$connection->handshakeStep = 1;
|
||||
$connection->websocketCurrentFrameLength = 0;
|
||||
$connection->websocketDataBuffer = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Websocket handshake.
|
||||
*
|
||||
* @param string $buffer
|
||||
* @param \Workerman\Connection\TcpConnection $connection
|
||||
* @return int
|
||||
*/
|
||||
public static function dealHandshake($buffer, $connection)
|
||||
{
|
||||
$pos = strpos($buffer, "\r\n\r\n");
|
||||
if ($pos) {
|
||||
// handshake complete
|
||||
$connection->handshakeStep = 2;
|
||||
$handshake_response_length = $pos + 4;
|
||||
// Try to emit onWebSocketConnect callback.
|
||||
if (isset($connection->onWebSocketConnect)) {
|
||||
try {
|
||||
call_user_func($connection->onWebSocketConnect, $connection, substr($buffer, 0, $handshake_response_length));
|
||||
} catch (\Exception $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
} catch (\Error $e) {
|
||||
Worker::log($e);
|
||||
exit(250);
|
||||
}
|
||||
}
|
||||
// Headbeat.
|
||||
if (!empty($connection->websocketPingInterval)) {
|
||||
$connection->websocketPingTimer = Timer::add($connection->websocketPingInterval, function() use ($connection){
|
||||
if (false === $connection->send(pack('H*', '8900'), true)) {
|
||||
Timer::del($connection->websocketPingTimer);
|
||||
$connection->websocketPingTimer = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$connection->consumeRecvBuffer($handshake_response_length);
|
||||
if (!empty($connection->tmpWebsocketData)) {
|
||||
$connection->send($connection->tmpWebsocketData, true);
|
||||
$connection->tmpWebsocketData = '';
|
||||
}
|
||||
if (strlen($buffer) > $handshake_response_length) {
|
||||
return self::input(substr($buffer, $handshake_response_length), $connection);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user