| 1 | package EV::WebKit::Protocol; | ||
| 2 | use v5.10; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | our $VERSION = '0.05'; | ||
| 7 | |||
| 8 | # The control protocol's wire codec, and nothing else: no EV, no sockets, no | ||
| 9 | # browser. Both the server (EV::WebKit::Control) and the client | ||
| 10 | # (EV::WebKit::Client) use it, so "split on newlines, tolerate a partial read" | ||
| 11 | # exists once instead of drifting in two places -- and it is the one piece of | ||
| 12 | # the protocol that can be tested without a browser at all. | ||
| 13 | # | ||
| 14 | # One JSON object per line, UTF-8 octets. | ||
| 15 | |||
| 16 | use constant PROTO => 1; | ||
| 17 | |||
| 18 | # A client that opens a socket and never sends a newline would otherwise buffer | ||
| 19 | # without bound. 64 MiB is far above any real frame (a base64 full-page | ||
| 20 | # screenshot runs to a few MiB) and far below "eat the machine". | ||
| 21 | use constant MAX_LINE => 64 * 1024 * 1024; | ||
| 22 | |||
| 23 | # utf8(1): unlike EV::WebKit's own JSON object -- which is in CHARACTER mode, | ||
| 24 | # because Glib::Object::Introspection marshals utf8 strings as characters -- | ||
| 25 | # this one writes to a SOCKET, and a socket carries octets. | ||
| 26 | my $JSON = do { | ||
| 27 | my $j = eval { require Cpanel::JSON::XS; Cpanel::JSON::XS->new } | ||
| 28 | || do { require JSON::PP; JSON::PP->new }; | ||
| 29 | $j->canonical(1)->utf8(1); | ||
| 30 | }; | ||
| 31 | |||
| 32 | sub encode { $JSON->encode($_[0]) . "\n" } | ||
| 33 | |||
| 34 | # Returns a stateful decoder. Feed it octets; it returns however many complete | ||
| 35 | # frames those octets completed (possibly none). A line that is not a JSON | ||
| 36 | # object comes back as { _bad => $reason } instead of dying -- one client's | ||
| 37 | # garbage must not take down the browser or anybody else's session. | ||
| 38 | sub decoder { | ||
| 39 | my $buf = ''; | ||
| 40 | my $dead = 0; | ||
| 41 | return sub { | ||
| 42 | my ($octets) = @_; | ||
| 43 | return ({ _bad => 'line too long' }) if $dead; | ||
| 44 | $buf .= $octets if defined $octets && length $octets; | ||
| 45 | if (length($buf) > MAX_LINE) { | ||
| 46 | $dead = 1; | ||
| 47 | $buf = ''; | ||
| 48 | return ({ _bad => 'line too long' }); | ||
| 49 | } | ||
| 50 | my @frames; | ||
| 51 | while ((my $nl = index($buf, "\n")) >= 0) { | ||
| 52 | my $line = substr($buf, 0, $nl, ''); # take the line... | ||
| 53 | substr($buf, 0, 1, ''); # ...and drop the newline | ||
| 54 | next unless length $line; # a blank line is nothing | ||
| 55 | my $f = eval { $JSON->decode($line) }; | ||
| 56 | push @frames, (ref $f eq 'HASH') ? $f : { _bad => 'bad request' }; | ||
| 57 | } | ||
| 58 | return @frames; | ||
| 59 | }; | ||
| 60 | } | ||
| 61 | |||
| 62 | 1; | ||
| 63 | |||
| 64 | __END__ |