This commit is contained in:
walkor
2015-04-04 21:46:31 +08:00
commit 37f4dcf4dc
21 changed files with 4597 additions and 0 deletions
+151
View File
@@ -0,0 +1,151 @@
<?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
{
// 发给workergateway有一个新的连接
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;
}
}
+552
View File
@@ -0,0 +1,552 @@
<?php
namespace Workerman\Protocols;
use Workerman\Connection\TcpConnection;
/**
* http protocol
* @author walkor<walkor@workerman.net>
*/
class Http
{
/**
* 判断包长
* @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)
{
$connection->close();
return 0;
}
return 0;
}
list($header, $body) = 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
{
return 0;
}
}
else
{
return strlen($header)+4;
}
}
/**
* 从http数据包中解析$_POST、$_GET、$_COOKIE等
* @param string $recv_buffer
* @param TcpConnection $connection
* @return void
*/
public static function decode($recv_buffer, TcpConnection $connection)
{
// 初始化
$_POST = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES = array();
$GLOBALS['HTTP_RAW_POST_DATA'] = '';
// 清空上次的数据
HttpCache::$header = array();
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分割成数组
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]);
unset($header_data[0]);
foreach($header_data as $content)
{
// \r\n\r\n
if(empty($content))
{
continue;
}
list($key, $value) = explode(':', $content, 2);
$key = strtolower($key);
$value = trim($value);
switch($key)
{
// HTTP_HOST
case 'host':
$_SERVER['HTTP_HOST'] = $value;
$tmp = explode(':', $value);
$_SERVER['SERVER_NAME'] = $tmp[0];
if(isset($tmp[1]))
{
$_SERVER['SERVER_PORT'] = $tmp[1];
}
break;
// cookie
case 'cookie':
$_SERVER['HTTP_COOKIE'] = $value;
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))
{
$_SERVER['CONTENT_TYPE'] = $value;
}
else
{
$_SERVER['CONTENT_TYPE'] = 'multipart/form-data';
$http_post_boundary = '--'.$match[1];
}
break;
}
}
// 需要解析$_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
{
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'])
{
// $GET
parse_str($_SERVER['QUERY_STRING'], $_GET);
}
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;
}
/**
* 编码,增加HTTP头
* @param string $content
* @param TcpConnection $connection
* @return string
*/
public static function encode($content, TcpConnection $connection)
{
// 没有http-code默认给个
if(!isset(HttpCache::$header['Http-Code']))
{
$header = "HTTP/1.1 200 OK\r\n";
}
else
{
$header = HttpCache::$header['Http-Code']."\r\n";
unset(HttpCache::$header['Http-Code']);
}
// 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";
}
}
else
{
$header .= $item."\r\n";
}
}
// header
$header .= "Server: WorkerMan/3.0\r\nContent-Length: ".strlen($content)."\r\n\r\n";
// save session
self::sessionWriteClose();
// the whole http package
return $header.$content;
}
/**
* 设置http头
* @return bool
*/
public static function header($content, $replace = true, $http_response_code = 0)
{
if(PHP_SAPI != 'cli')
{
return $http_response_code ? header($content, $replace, $http_response_code) : header($content, $replace);
}
if(strpos($content, 'HTTP') === 0)
{
$key = 'Http-Code';
}
else
{
$key = strstr($content, ":", true);
if(empty($key))
{
return false;
}
}
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')
{
return true;
}
}
if($key == 'Set-Cookie')
{
HttpCache::$header[$key][] = $content;
}
else
{
HttpCache::$header[$key] = $content;
}
return true;
}
/**
* 删除一个header
* @param string $name
* @return void
*/
public static function headerRemove($name)
{
if(PHP_SAPI != 'cli')
{
return header_remove($name);
}
unset( HttpCache::$header[$name]);
}
/**
* 设置cookie
* @param string $name
* @param string $value
* @param integer $maxage
* @param string $path
* @param string $domain
* @param bool $secure
* @param bool $HTTPOnly
*/
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);
}
/**
* sessionStart
* @return bool
*/
public static function sessionStart()
{
if(PHP_SAPI != 'cli')
{
return session_start();
}
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)
{
return false;
}
HttpCache::$instance->sessionFile = $file_name;
$session_id = substr(basename($file_name), strlen('sess_'));
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')
);
}
if(!HttpCache::$instance->sessionFile)
{
HttpCache::$instance->sessionFile = HttpCache::$sessionPath . '/sess_' . $_COOKIE[HttpCache::$sessionName];
}
// 有sid则打开文件,读取session值
if(HttpCache::$instance->sessionFile)
{
$raw = file_get_contents(HttpCache::$instance->sessionFile);
if($raw)
{
session_decode($raw);
}
}
}
/**
* 保存session
* @return bool
*/
public static function sessionWriteClose()
{
if(PHP_SAPI != 'cli')
{
return session_write_close();
}
if(!empty(HttpCache::$instance->sessionStarted) && !empty($_SESSION))
{
$session_str = session_encode();
if($session_str && HttpCache::$instance->sessionFile)
{
return file_put_contents(HttpCache::$instance->sessionFile, $session_str);
}
}
return empty($_SESSION);
}
/**
* 退出
* @param string $msg
* @throws \Exception
*/
public static function end($msg = '')
{
if(PHP_SAPI != 'cli')
{
exit($msg);
}
if($msg)
{
echo $msg;
}
throw new \Exception('jump_exit');
}
/**
* get mime types
*/
public static function getMimeTypesFile()
{
return __DIR__.'/Http/mime.types';
}
/**
* 解析$_FILES
*/
protected 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] === '')
{
unset($boundary_data_array[0]);
}
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
$boundary_value = substr($boundary_value, 0, -2);
foreach (explode("\r\n", $boundary_header_buffer) as $item)
{
list($header_key, $header_value) = explode(": ", $item);
$header_key = strtolower($header_key);
switch ($header_key)
{
case "content-disposition":
// 是文件
if(preg_match('/name=".*?"; filename="(.*?)"$/', $header_value, $match))
{
$_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))
{
$_POST[$match[1]] = $boundary_value;
}
}
break;
}
}
}
}
}
/**
* 解析http协议数据包 缓存先关
* @author walkor
*/
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',
);
public static $instance = null;
public static $header = array();
public static $sessionPath = '';
public static $sessionName = '';
public $sessionStarted = false;
public $sessionFile = '';
public static function init()
{
self::$sessionName = ini_get('session.name');
self::$sessionPath = session_save_path();
if(!self::$sessionPath)
{
self::$sessionPath = sys_get_temp_dir();
}
@\session_start();
}
}
+80
View File
@@ -0,0 +1,80 @@
types {
text/html html htm shtml;
text/css css;
text/xml xml;
image/gif gif;
image/jpeg jpeg jpg;
application/x-javascript js;
application/atom+xml atom;
application/rss+xml rss;
text/mathml mml;
text/plain txt;
text/vnd.sun.j2me.app-descriptor jad;
text/vnd.wap.wml wml;
text/x-component htc;
image/png png;
image/tiff tif tiff;
image/vnd.wap.wbmp wbmp;
image/x-icon ico;
image/x-jng jng;
image/x-ms-bmp bmp;
image/svg+xml svg svgz;
image/webp webp;
application/java-archive jar war ear;
application/mac-binhex40 hqx;
application/msword doc;
application/pdf pdf;
application/postscript ps eps ai;
application/rtf rtf;
application/vnd.ms-excel xls;
application/vnd.ms-powerpoint ppt;
application/vnd.wap.wmlc wmlc;
application/vnd.google-earth.kml+xml kml;
application/vnd.google-earth.kmz kmz;
application/x-7z-compressed 7z;
application/x-cocoa cco;
application/x-java-archive-diff jardiff;
application/x-java-jnlp-file jnlp;
application/x-makeself run;
application/x-perl pl pm;
application/x-pilot prc pdb;
application/x-rar-compressed rar;
application/x-redhat-package-manager rpm;
application/x-sea sea;
application/x-shockwave-flash swf;
application/x-stuffit sit;
application/x-tcl tcl tk;
application/x-x509-ca-cert der pem crt;
application/x-xpinstall xpi;
application/xhtml+xml xhtml;
application/zip zip;
application/octet-stream bin exe dll;
application/octet-stream deb;
application/octet-stream dmg;
application/octet-stream eot;
application/octet-stream iso img;
application/octet-stream msi msp msm;
audio/midi mid midi kar;
audio/mpeg mp3;
audio/ogg ogg;
audio/x-m4a m4a;
audio/x-realaudio ra;
video/3gpp 3gpp 3gp;
video/mp4 mp4;
video/mpeg mpeg mpg;
video/quicktime mov;
video/webm webm;
video/x-flv flv;
video/x-m4v m4v;
video/x-mng mng;
video/x-ms-asf asx asf;
video/x-ms-wmv wmv;
video/x-msvideo avi;
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace Workerman\Protocols;
use \Workerman\Connection\ConnectionInterface;
/**
* Protocol interface
* @author walkor <walkor@workerman.net>
*/
interface ProtocolInterface
{
/**
* 用于分包,即在接收的buffer中返回当前请求的长度(字节)
* 如果可以在$recv_buffer中得到请求包的长度则返回长度
* 否则返回0,表示需要更多的数据才能得到当前请求包的长度
* 如果返回false或者负数,则代表请求不符合协议,则连接会断开
* @param ConnectionInterface $connection
* @param string $recv_buffer
* @return int|false
*/
public static function input($recv_buffer, ConnectionInterface $connection);
/**
* 用于请求解包
* input返回值大于0,并且WorkerMan收到了足够的数据,则自动调用decode
* 然后触发onMessage回调,并将decode解码后的数据传递给onMessage回调的第二个参数
* 也就是说当收到完整的客户端请求时,会自动调用decode解码,无需业务代码中手动调用
* @param ConnectionInterface $connection
* @param string $recv_buffer
* @return mixed
*/
public static function decode($recv_buffer, ConnectionInterface $connection);
/**
* 用于请求打包
* 当需要向客户端发送数据即调用$connection->send($data);时
* 会自动把$data用encode打包一次,变成符合协议的数据格式,然后再发送给客户端
* 也就是说发送给客户端的数据会自动encode打包,无需业务代码中手动调用
* @param ConnectionInterface $connection
* @param mixed $data
* @return string
*/
public static function encode($data, ConnectionInterface $connection);
}
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace Workerman\Protocols;
use \Workerman\Connection\TcpConnection;
/**
* Text协议
* 以换行为请求结束标记
* @author walkor <walkor@workerman.net>
*/
class Text
{
/**
* 检查包的完整性
* 如果能够得到包长,则返回包的长度,否则返回0继续等待数据
* @param string $buffer
*/
public static function input($buffer ,TcpConnection $connection)
{
// 由于没有包头,无法预先知道包长,不能无限制的接收数据,
// 所以需要判断当前接收的数据是否超过限定值
if(strlen($buffer)>=TcpConnection::$maxPackageSize)
{
$connection->close();
return 0;
}
// 获得换行字符"\n"位置
$pos = strpos($buffer, "\n");
// 没有换行符,无法得知包长,返回0继续等待数据
if($pos === false)
{
return 0;
}
// 有换行符,返回当前包长,包含换行符
return $pos+1;
}
/**
* 打包,当向客户端发送数据的时候会自动调用
* @param string $buffer
* @return string
*/
public static function encode($buffer)
{
// 加上换行
return $buffer."\n";
}
/**
* 解包,当接收到的数据字节数等于input返回的值(大于0的值)自动调用
* 并传递给onMessage回调函数的$data参数
* @param string $buffer
* @return string
*/
public static function decode($buffer)
{
// 去掉换行
return trim($buffer);
}
}
+390
View File
@@ -0,0 +1,390 @@
<?php
namespace Workerman\Protocols;
/**
* WebSocket 协议服务端解包和打包
* @author walkor <walkor@workerman.net>
*/
use Workerman\Connection\ConnectionInterface;
class Websocket implements \Workerman\Protocols\ProtocolInterface
{
/**
* websocket头部最小长度
* @var int
*/
const MIN_HEAD_LEN = 6;
/**
* websocket blob类型
* @var char
*/
const BINARY_TYPE_BLOB = "\x81";
/**
* websocket arraybuffer类型
* @var char
*/
const BINARY_TYPE_ARRAYBUFFER = "\x82";
/**
* 检查包的完整性
* @param string $buffer
*/
public static function input($buffer, ConnectionInterface $connection)
{
// 数据长度
$recv_len = strlen($buffer);
// 长度不够
if($recv_len < self::MIN_HEAD_LEN)
{
return 0;
}
// 还没有握手
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的帧
return 0;
}
}
else
{
$data_len = ord($buffer[1]) & 127;
$firstbyte = ord($buffer[0]);
$is_fin_frame = $firstbyte>>7;
$opcode = $firstbyte & 0xf;
switch($opcode)
{
// 附加数据帧 @todo 实现附加数据帧
case 0x0:
break;
// 文本数据帧
case 0x1:
break;
// 二进制数据帧
case 0x2:
break;
// 关闭的包
case 0x8:
// 如果有设置onWebSocketClose回调,尝试执行
if(isset($connection->onWebSocketClose))
{
call_user_func($connection->onWebSocketClose, $connection);
}
// 默认行为是关闭连接
else
{
$connection->close();
}
return 0;
// ping的包
case 0x9:
// 如果有设置onWebSocketPing回调,尝试执行
if(isset($connection->onWebSocketPing))
{
call_user_func($connection->onWebSocketPing, $connection);
}
// 默认发送pong
else
{
$connection->send(pack('H*', '8a00'), true);
}
// 从接受缓冲区中消费掉该数据包
if(!$data_len)
{
$connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
return 0;
}
break;
// pong的包
case 0xa:
// 如果有设置onWebSocketPong回调,尝试执行
if(isset($connection->onWebSocketPong))
{
call_user_func($connection->onWebSocketPong, $connection);
}
// 从接受缓冲区中消费掉该数据包
if(!$data_len)
{
$connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
return 0;
}
break;
// 错误的opcode
default :
echo "error opcode $opcode and close websocket connection\n";
$connection->close();
return 0;
}
// websocket二进制数据
$head_len = self::MIN_HEAD_LEN;
if ($data_len === 126) {
$head_len = 8;
if($head_len > $recv_len)
{
return 0;
}
$pack = unpack('ntotal_len', substr($buffer, 2, 2));
$data_len = $pack['total_len'];
} else if ($data_len === 127) {
$head_len = 14;
if($head_len > $recv_len)
{
return 0;
}
$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)
{
return $current_frame_length;
}
else
{
$connection->websocketCurrentFrameLength = $current_frame_length;
}
}
// 收到的数据刚好是一个frame
if($connection->websocketCurrentFrameLength == $recv_len)
{
self::decode($buffer, $connection);
$connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
$connection->websocketCurrentFrameLength = 0;
return 0;
}
// 收到的数据大于一个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;
// 继续读取下一个frame
return self::input(substr($buffer, $current_frame_length), $connection);
}
// 收到的数据不足一个frame
else
{
return 0;
}
}
/**
* 打包
* @param string $buffer
* @return string
*/
public static function encode($buffer, ConnectionInterface $connection)
{
$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;
}
$first_byte = $connection->websocketType;
if($len<=125)
{
return $first_byte.chr($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;
}
}
/**
* 解包
* @param string $buffer
* @return string
*/
public static function decode($buffer, ConnectionInterface $connection)
{
$len = $masks = $data = $decoded = null;
$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);
} 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)
{
$connection->websocketDataBuffer .= $decoded;
return $connection->websocketDataBuffer;
}
else
{
$decoded = $connection->websocketDataBuffer . $decoded;
$connection->websocketDataBuffer = '';
return $decoded;
}
}
/**
* 处理websocket握手
* @param string $buffer
* @param TcpConnection $connection
* @return int
*/
protected static function dealHandshake($buffer, $connection)
{
// 握手阶段客户端发送HTTP协议
if(0 === strpos($buffer, 'GET'))
{
// 判断\r\n\r\n边界
$heder_end_pos = strpos($buffer, "\r\n\r\n");
if(!$heder_end_pos)
{
return 0;
}
// 解析Sec-WebSocket-Key
$Sec_WebSocket_Key = '';
if(preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/", $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);
$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";
$connection->websocketHandshake = true;
$connection->websocketDataBuffer = '';
$connection->websocketCurrentFrameLength = 0;
$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();
}
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";
$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);
$connection->close();
return 0;
}
/**
* 从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]);
unset($header_data[0]);
foreach($header_data as $content)
{
// \r\n\r\n
if(empty($content))
{
continue;
}
list($key, $value) = explode(':', $content, 2);
$key = strtolower($key);
$value = trim($value);
switch($key)
{
// HTTP_HOST
case 'host':
$_SERVER['HTTP_HOST'] = $value;
$tmp = explode(':', $value);
$_SERVER['SERVER_NAME'] = $tmp[0];
if(isset($tmp[1]))
{
$_SERVER['SERVER_PORT'] = $tmp[1];
}
break;
// HTTP_COOKIE
case 'cookie':
$_SERVER['HTTP_COOKIE'] = $value;
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'])
{
// $GET
parse_str($_SERVER['QUERY_STRING'], $_GET);
}
else
{
$_SERVER['QUERY_STRING'] = '';
}
}
}