/
WebSocket.pm
391 lines (259 loc) · 8.44 KB
/
WebSocket.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# Copyright (C) 2008-2010, Sebastian Riedel.
package Mojo::Transaction::WebSocket;
use strict;
use warnings;
# I'm not calling you a liar but...
# I can't think of a way to finish that sentence.
use base 'Mojo::Transaction';
use Mojo::ByteStream 'b';
use Mojo::Transaction::HTTP;
__PACKAGE__->attr(
receive_message => sub {
sub { }
}
);
__PACKAGE__->attr(handshake => sub { Mojo::Transaction::HTTP->new });
sub client_challenge {
my $self = shift;
# Request
my $req = $self->req;
# Headers
my $headers = $self->req->headers;
# WebSocket challenge
my $solution = $self->_challenge(scalar $headers->sec_websocket_key1,
scalar $headers->sec_websocket_key2, $req->body);
return unless $solution eq $self->res->body;
return 1;
}
sub client_close { shift->server_close(@_) }
sub client_handshake {
my $self = shift;
# Request
my $req = $self->req;
# Headers
my $headers = $req->headers;
# Default headers
$headers->upgrade('WebSocket') unless $headers->upgrade;
$headers->connection('Upgrade') unless $headers->connection;
$headers->sec_websocket_protocol('mojo')
unless $headers->sec_websocket_protocol;
# Generate challenge
$headers->sec_websocket_key1($self->_generate_key)
unless $headers->sec_websocket_key1;
$headers->sec_websocket_key2($self->_generate_key)
unless $headers->sec_websocket_key2;
$req->body(pack 'N*', int(rand 9999999) + 1, int(rand 9999999) + 1);
return $self;
}
sub client_read { shift->server_read(@_) }
sub client_write { shift->server_write(@_) }
sub connection { shift->handshake->connection(@_) }
sub finish {
my $self = shift;
# Send closing handshake
$self->_send_bytes("\xff");
# Finish after writing
return $self->{_finished} = 1;
}
sub is_websocket {1}
sub local_address { shift->handshake->local_address }
sub local_port { shift->handshake->local_port }
sub remote_address { shift->handshake->remote_address }
sub remote_port { shift->handshake->remote_port }
sub req { shift->handshake->req(@_) }
sub res { shift->handshake->res(@_) }
sub send_message {
my ($self, $message) = @_;
# Encode
$message = b($message)->encode('UTF-8')->to_string;
# Send message with framing
$self->_send_bytes("\x00$message\xff");
}
sub server_handshake {
my $self = shift;
# Request
my $req = $self->req;
# Response
my $res = $self->res;
# Handshake
$res->code(101);
$res->headers->upgrade('WebSocket');
$res->headers->connection('Upgrade');
my $scheme = $req->url->to_abs->scheme eq 'https' ? 'wss' : 'ws';
my $location = $req->url->to_abs->scheme($scheme)->to_string;
my $origin = $req->headers->origin;
# Draft 76 WebSocket support
if ($req->headers->sec_websocket_key1) {
$res->headers->sec_websocket_origin($origin);
$res->headers->sec_websocket_location($location);
$res->headers->sec_websocket_protocol(
$req->headers->sec_websocket_protocol);
$res->body(
$self->_challenge(
scalar $req->headers->sec_websocket_key1,
scalar $req->headers->sec_websocket_key2,
$req->body
)
);
}
# DEPRECATED in Snowman!
# Draft 75 WebSocket support
else {
$res->headers->header('WebSocket-Origin', $origin);
$res->headers->header('WebSocket-Location', $location);
}
return $self;
}
# Being eaten by crocodile is just like going to sleep... in a giant blender.
sub server_read {
my ($self, $chunk) = @_;
# Add chunk
my $buffer = $self->{_read} ||= Mojo::ByteStream->new;
$buffer->add_chunk($chunk);
# Full frames
while ((my $i = $buffer->contains("\xff")) >= 0) {
# Closing handshake
return $self->finish if $i == 0;
# Frame
my $message = $buffer->remove($i + 1);
# Remove framing
$message =~ s/^[\x00]//;
$message =~ s/[\xff]$//;
# Callback
$self->receive_message->(
$self, b($message)->decode('UTF-8')->to_string
);
}
return $self;
}
sub server_write {
my $self = shift;
# Not writing anymore
my $write = $self->{_write} ||= Mojo::ByteStream->new;
unless ($write->size) {
$self->{_finished} ? $self->state('done') : $self->state('read');
}
# Empty buffer
return $write->empty;
}
sub _challenge {
my ($self, $key1, $key2, $key3) = @_;
# Shortcut
return unless $key1 && $key2 && $key3;
# Calculate solution for challenge
my $c1 = pack 'N', join('', $key1 =~ /(\d)/g) / ($key1 =~ tr/\ //);
my $c2 = pack 'N', join('', $key2 =~ /(\d)/g) / ($key2 =~ tr/\ //);
return b("$c1$c2$key3")->md5_bytes->to_string;
}
sub _generate_key {
my $self = shift;
# Number of spaces
my $spaces = int(rand 12) + 1;
# Number
my $number = int(rand 99999) + 10;
# Key
my $key = $number * $spaces;
# Insert whitespace
while ($spaces--) {
# Random position
my $pos = int(rand(length($key) - 2)) + 1;
# Insert a space at $pos position
substr($key, $pos, 0) = ' ';
}
return $key;
}
sub _send_bytes {
my ($self, $bytes) = @_;
# Add to buffer
my $write = $self->{_write} ||= Mojo::ByteStream->new;
$write->add_chunk($bytes);
# Writing
$self->state('write');
}
1;
__END__
=head1 NAME
Mojo::Transaction::WebSocket - WebSocket Transaction Container
=head1 SYNOPSIS
use Mojo::Transaction::WebSocket;
=head1 DESCRIPTION
L<Mojo::Transaction::WebSocket> is a container and state machine for
WebSocket transactions as described in C<The Web Socket protocol>.
=head1 ATTRIBUTES
L<Mojo::Transaction::WebSocket> inherits all attributes from
L<Mojo::Transaction> and implements the following new ones.
=head2 C<handshake>
my $handshake = $ws->handshake;
$ws = $ws->handshake(Mojo::Transaction::HTTP->new);
The original handshake transaction.
=head2 C<receive_message>
my $cb = $ws->receive_message;
$ws = $ws->receive_message(sub {...});
The callback that receives decoded messages one by one.
$ws->receive_message(sub {
my ($self, $message) = @_;
});
=head1 METHODS
L<Mojo::Transaction::WebSocket> inherits all methods from
L<Mojo::Transaction> and implements the following new ones.
=head2 C<client_challenge>
my $success = $ws->client_challenge;
Check WebSocket handshake challenge, only used by client.
Note that this method is EXPERIMENTAL and might change without warning!
=head2 C<client_close>
$ws = $ws->client_close;
Connection got closed, only used by clients.
=head2 C<client_handshake>
$ws = $ws->client_handshake;
WebSocket handshake, only used by clients.
Note that this method is EXPERIMENTAL and might change without warning!
=head2 C<client_read>
$ws = $ws->client_read($data);
Read raw WebSocket data, only used by clients.
=head2 C<client_write>
my $chunk = $ws->client_write;
Raw WebSocket data to write, only used by clients.
=head2 C<connection>
my $connection = $ws->connection;
The connection this websocket is using.
=head2 C<finish>
$ws->finish;
Finish the WebSocket connection gracefully.
=head2 C<is_websocket>
my $is_websocket = $ws->is_websocket;
True.
=head2 C<local_address>
my $local_address = $ws->local_address;
The local address of this WebSocket.
=head2 C<local_port>
my $local_port = $ws->local_port;
The local port of this WebSocket.
=head2 C<remote_address>
my $remote_address = $ws->remote_address;
The remote address of this WebSocket.
=head2 C<remote_port>
my $remote_port = $ws->remote_port;
The remote port of this WebSocket.
=head2 C<req>
my $req = $ws->req;
The original handshake request.
=head2 C<res>
my $req = $ws->res;
The original handshake response.
=head2 C<send_message>
$ws->send_message('Hi there!');
Send a message over the WebSocket, encoding and framing will be handled
transparently.
=head2 C<server_handshake>
$ws = $ws->server_handshake;
WebSocket handshake, only used by servers.
Note that this method is EXPERIMENTAL and might change without warning!
=head2 C<server_read>
$ws = $ws->server_read($data);
Read raw WebSocket data, only used by servers.
=head2 C<server_write>
my $chunk = $ws->server_write;
Raw WebSocket data to write, only used by servers.
=head1 SEE ALSO
L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicious.org>.
=cut