| 1 |
#! perl # mandatory depends=tcp |
| 2 |
|
| 3 |
# websocket protocol server (RFC6455), actually only the handshake part |
| 4 |
# the framing is implemented in socket/lowlevel.C |
| 5 |
# this implementations doesn't even try to completely implement th RFC, |
| 6 |
# it tries only to be good enough. |
| 7 |
|
| 8 |
use Digest::SHA1 (); |
| 9 |
|
| 10 |
# websocket requests can be very long, and we want the tcp code to buffer for us |
| 11 |
our $detector = ext::tcp::register websocket => 4096, sub { |
| 12 |
m{^(?i:GET) \ (?i:http://[^/]+)? /ws \ (?:(?i)HTTP/[0-9\.]+).*\015\012\015\012}xs |
| 13 |
}, sub { |
| 14 |
my ($id, $fh, $buf) = @_; |
| 15 |
|
| 16 |
$buf =~ /^Sec-WebSocket-Version\s*:\s*([0-9]+)/mi |
| 17 |
or return; |
| 18 |
my $version = $1; # 8=ff10, 13=rfc |
| 19 |
|
| 20 |
$buf =~ /^Sec-WebSocket-Key\s*:\s*(\S+)/mi |
| 21 |
or return; |
| 22 |
my $key = $1; |
| 23 |
|
| 24 |
if ($version != 8 && $version != 13) { |
| 25 |
syswrite $fh, "HTTP/1.1 400 version mismatch\015\012" |
| 26 |
. "connection: close\015\012" |
| 27 |
. "sec-websocket-version: 13, 8\015\012\015\012"; |
| 28 |
return; |
| 29 |
} |
| 30 |
|
| 31 |
my $res = "HTTP/1.1 101 upgrading\015\012" |
| 32 |
. "connection: upgrade\015\012" |
| 33 |
. "upgrade: websocket\015\012" |
| 34 |
. "sec-websocket-accept: " . (Digest::SHA1::sha1_base64 $key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") . "=\015\012" |
| 35 |
. "\015\012"; |
| 36 |
|
| 37 |
syswrite $fh, $res; |
| 38 |
|
| 39 |
my $ns = cf::client::create fileno $_[1], $_[0]; |
| 40 |
$ns->ws_version ($version); |
| 41 |
$ns->run; |
| 42 |
}; |
| 43 |
|