I developed a WebSocket server using PHP and it worked fine with ws://, but in production environment it uses https://, then I must use wss://.
Should I use certificate to start the socket or something like that? I can't parse the headers to complete the handshake.
How can I perform handshake behind a https server?
This is a AWS EC2 machine with Amazon Certificate.
I have tried import .pem file to socket initialization, run ws:// behind my https:// environment, and nothing worked :(
Socket initialization:
$socket = stream_socket_server("tcp://0.0.0.0:" . env("APP_WSS_PORTA"), $errno, $errstr);
I have tried also:
use Aws\Acm\AcmClient;$cert = (new AcmClient(include config_path('aws.php')))->GetCertificate(["CertificateArn" => "arn:aws:acm:sa-east-1:EDITED_TO_STACKOVERFLOW"])["CertificateChain"];$cert_path = "cert.pem";file_put_contents(base_path($cert_path), $cert);$context = stream_context_create( ["ssl" => ["local_cert"=> $cert_path]]);$socket = stream_socket_server("tcp://0.0.0.0:" . env("APP_WSS_PORTA"), $errno, $errstr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $context);
My handshake function:
function wsHandshake($data){ echo "> Handshake " . remoteIp() . PHP_EOL; $lines = preg_split("/\r\n/", $data); $headers = array(); foreach ($lines as $line) { $line = chop($line); if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) { $headers[$matches[1]] = $matches[2]; } } var_dump($data); // to debug it :) if (!isset($headers['Sec-WebSocket-Version']) || $headers['Sec-WebSocket-Version'] < 6) { echo '> Versao do WebSocket nao suportada' . PHP_EOL; return false; } $sec_accept = base64_encode(pack('H*', sha1($headers['Sec-WebSocket-Key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))); $response = "HTTP/1.1 101 Switching Protocols\r\n"; $response .= "Upgrade: websocket\r\n"; $response .= "Connection: Upgrade\r\n"; $response .= "Sec-WebSocket-Accept: " . $sec_accept . "\r\n"; $response .= "\r\n"; return $response;}
var_dump with ws://
string(448) "GET / HTTP/1.1Host: 127.0.0.1:3131User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0Accept: */*Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateSec-WebSocket-Version: 13Origin: http://localhostSec-WebSocket-Extensions: permessage-deflateSec-WebSocket-Key: PuIYHJZ4x8IyXajFf4WAsw==Connection: keep-alive, UpgradePragma: no-cacheCache-Control: no-cacheUpgrade: websocket"
var_dump with wss://
string(517) "\000\000��}hh�հ�h����`�ݘ����O��GQ�E� S�8�@��,��=��c���C8�ǯ�G!6{<\000$�+�/̨̩�,�0����\0003\0009\000/\0005\000\000�\000\000\000�\000\000\000\000\000 \000\000\000\000\000\000 \000\000\000#\000\000\000\000\000 hhttp/1.1\000\000\000\000\000\000\0003\000k\000i\000\000 ��"�c��GLGX�Ƶ��:�"ŵ�)բ E��)\000\000Al�d��#Q{��t��q>��eb���u�+�d��M�!2�-��tI����z�y�\ĉ�\000\\000-\000\000\000@\000\0"...