| 1 | package EV::WebKit::Control; | ||
| 2 | use v5.10; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Carp (); | ||
| 7 | use Errno (); | ||
| 8 | use EV; | ||
| 9 | use IO::Socket::UNIX (); # () like every other import here: its Socket re-exports would otherwise land in this package as callable methods | ||
| 10 | use MIME::Base64 (); | ||
| 11 | use Scalar::Util qw(weaken); | ||
| 12 | |||
| 13 | # How much unwritten output one client may accumulate before it is dropped. A | ||
| 14 | # page can generate console lines faster than a stalled client reads them, and | ||
| 15 | # the browser must not grow to hold them. Generous enough that no responsive | ||
| 16 | # client ever approaches it: a full-page screenshot is a few megabytes. | ||
| 17 | use constant MAX_CLIENT_BACKLOG => 64 * 1024 * 1024; | ||
| 18 | use EV::WebKit::Protocol; | ||
| 19 | |||
| 20 | our $VERSION = '0.05'; | ||
| 21 | |||
| 22 | # A control server for a RUNNING EV::WebKit instance: another process can drive | ||
| 23 | # the browser this one opened. | ||
| 24 | # | ||
| 25 | # This server is a PURE CONSUMER of EV::WebKit's public API. It calls the same | ||
| 26 | # go()/find()/script() any caller would, and adds no code path inside the | ||
| 27 | # browser. That is load-bearing rather than tidy: the core's invariants hold | ||
| 28 | # because they are CLOSED, and a socket server reaching into internals would | ||
| 29 | # reopen every one of them. If you find yourself writing $b->{...} here, stop. | ||
| 30 | |||
| 31 | # Methods that answer immediately. | ||
| 32 | my %SYNC = map { $_ => 1 } qw( | ||
| 33 | uri title is_loading user_agent can_go_back can_go_forward status | ||
| 34 | stop settings set_user_agent set_proxy show_devtools zoom | ||
| 35 | ); | ||
| 36 | |||
| 37 | # Methods that take a trailing callback and answer later. | ||
| 38 | # | ||
| 39 | # NOT here, because they need their own handling: | ||
| 40 | # find, find_all, find_js, find_all_js, wait_for -- all resolve with an ELEMENT, which cannot | ||
| 41 | # cross a socket; they are marshalled into handles below. (wait_for is the | ||
| 42 | # easy one to miss: it looks like a plain "wait until" call, but on success | ||
| 43 | # it hands back the element it was waiting for.) | ||
| 44 | # screenshot -- its first argument is either a path OR an options hashref, a | ||
| 45 | # distinction the generic option-flattening destroys, and in bytes mode its | ||
| 46 | # result is raw PNG octets that must be base64'd to survive JSON. | ||
| 47 | # scroll -- dispatched separately so it can name its callback (cb => ...). | ||
| 48 | # scroll now accepts a trailing callback too, so the generic path would in | ||
| 49 | # fact work; naming it is kept because scroll's arguments are ALL named, | ||
| 50 | # and a positional tail there is the shape that used to be misread. | ||
| 51 | my %ASYNC = map { $_ => 1 } qw( | ||
| 52 | go load_html back forward reload | ||
| 53 | script script_async html pdf | ||
| 54 | press download wait_for_js frames resize wait_for_navigation | ||
| 55 | set_cookie cookies clear_cookies save_cookies load_cookies | ||
| 56 | ); | ||
| 57 | |||
| 58 | # [min, max] positional arguments each browser method takes BEFORE the | ||
| 59 | # answer-callback the generic dispatch appends. BOTH bounds are load-bearing, | ||
| 60 | # for the same reason they are in %EL_METHOD below: these methods bind the | ||
| 61 | # callback positionally, so a wrong count moves it out of its slot and NOTHING | ||
| 62 | # IS EVER SENT BACK -- a blocking client waits in sysread forever and an ev | ||
| 63 | # one's callback never fires. | ||
| 64 | # | ||
| 65 | # One SHORT slides the callback into a data slot; for go/load_html the | ||
| 66 | # stringified coderef then becomes the uri or the document and the browser | ||
| 67 | # navigates to it. One LONG pushes it past the end, and a trailing JSON null -- | ||
| 68 | # the "no callback" a user naturally writes when porting a local script -- is | ||
| 69 | # not caught by the methods' own `if defined $cb && ref $cb ne 'CODE'` guard, | ||
| 70 | # because undef is not defined. Measured before the max was added: 14 of these | ||
| 71 | # hung on a single trailing null. | ||
| 72 | # | ||
| 73 | # An undef max means the method takes trailing key/value OPTIONS, whose length | ||
| 74 | # the client chooses, so no ceiling is possible (options ride inside `a`, not | ||
| 75 | # `o`). That is press, wait_for_js and pdf. wait_for_navigation takes options | ||
| 76 | # and nothing else, so it is absent entirely rather than carrying a vacuous | ||
| 77 | # [0, undef]. | ||
| 78 | # | ||
| 79 | # Those four, plus save_cookies, POP their callback off the end instead of | ||
| 80 | # binding it positionally, so their slot cannot be displaced and they were never | ||
| 81 | # part of the hang. save_cookies still gets a real [1,2] because it takes no | ||
| 82 | # options -- ($file, $uris?) -- so a bound costs nothing and holds if it is ever | ||
| 83 | # rewritten to bind positionally. | ||
| 84 | # | ||
| 85 | # The find family and wait_for are likewise absent: they are answered by their | ||
| 86 | # own validation in the element-marshalling branch above, long before this | ||
| 87 | # check, so an entry here would be dead weight that read like coverage. | ||
| 88 | my %ARITY = ( | ||
| 89 | go => [1,1], load_html => [1,1], script => [1,1], script_async => [1,2], | ||
| 90 | back => [0,0], forward => [0,0], reload => [0,0], html => [0,0], | ||
| 91 | frames => [0,0], clear_cookies => [0,0], | ||
| 92 | resize => [2,2], download => [2,2], | ||
| 93 | set_cookie => [1,1], cookies => [1,1], load_cookies => [1,1], | ||
| 94 | save_cookies => [1,2], | ||
| 95 | press => [1,undef], wait_for_js => [1,undef], pdf => [1,undef], | ||
| 96 | ); | ||
| 97 | |||
| 98 | # EV::WebKit::Element's methods, reachable as el.<name> with a handle, and the | ||
| 99 | # [min, max] arguments each takes BEFORE its callback. | ||
| 100 | # | ||
| 101 | # Both bounds are load-bearing, but for different reasons. | ||
| 102 | # | ||
| 103 | # SHORT is caught downstream even without the floor: the seven entries with a | ||
| 104 | # minimum all croak in Element's own _need_name/callback guards, which exist for | ||
| 105 | # exactly that slip. The floor is what makes the answer say `expected 1 | ||
| 106 | # argument, got 0` instead of naming an internal helper. | ||
| 107 | # | ||
| 108 | # LONG is the one that goes SILENT. These methods bind positionally rather than | ||
| 109 | # popping the callback off the end, so an extra argument pushes the callback | ||
| 110 | # past its slot, and a trailing JSON `null` is not caught by the | ||
| 111 | # `if defined $cb && ref $cb ne 'CODE'` guard downstream, because undef is not | ||
| 112 | # defined -- so nothing answers and the client hangs until the socket closes. | ||
| 113 | # Measured with the bounds removed: the thirteen [0,0] entries go silent on a | ||
| 114 | # bare `null`, and the five [1,1] ones join them at `['x', null]`, for eighteen | ||
| 115 | # of twenty-one. (A trailing STRING croaks cleanly in most of them; it is | ||
| 116 | # specifically the null.) t/92 pins all twenty-one, both directions. | ||
| 117 | my %EL_METHOD = ( | ||
| 118 | text => [0,0], html => [0,0], value => [0,0], tag => [0,0], is_visible => [0,0], | ||
| 119 | click => [0,0], focus => [0,0], clear => [0,0], submit => [0,0], | ||
| 120 | scroll_into_view => [0,0], hover => [0,0], box => [0,0], uncheck => [0,0], | ||
| 121 | check => [0,1], # the state is optional | ||
| 122 | attr => [1,1], prop => [1,1], type => [1,1], find => [1,1], find_all => [1,1], | ||
| 123 | select_option => [1,1], | ||
| 124 | send_keys => [1,1], # a glob alias for type, and the only alias in the dist | ||
| 125 | ); | ||
| 126 | |||
| 127 | sub listen { | ||
| 128 | my ($class, $browser) = (shift, shift); | ||
| 129 | Carp::croak('listen: a browser is required') unless ref $browser; | ||
| 130 | Carp::croak('listen: options must be name => value pairs') if @_ % 2; | ||
| 131 | my %o = @_; | ||
| 132 | if (my @bad = sort grep { $_ ne 'path' } keys %o) { | ||
| 133 | Carp::croak("listen: unknown option(s): @bad (expected path)"); | ||
| 134 | } | ||
| 135 | my $path = $o{path} or Carp::croak('listen: path is required'); | ||
| 136 | |||
| 137 | # The socket is the authentication boundary: anyone who can connect can run | ||
| 138 | # arbitrary JavaScript in this browser and read every cookie it holds. So | ||
| 139 | # refuse to put it anywhere the world can reach. | ||
| 140 | my ($dir) = $path =~ m{^(.*)/[^/]+$}; | ||
| 141 | $dir = defined $dir ? (length $dir ? $dir : '/') : '.'; | ||
| 142 | my @st = stat $dir or Carp::croak("listen: cannot stat '$dir': $!"); | ||
| 143 | Carp::croak("listen: refusing to listen in a world-writable directory ('$dir')") | ||
| 144 | if ($st[2] & 0002) && !($st[2] & 01000); # world-writable and not sticky | ||
| 145 | |||
| 146 | # A leftover socket file from a crashed process is ordinary; a LIVE one means | ||
| 147 | # somebody else already owns this path. Tell them apart by connecting. | ||
| 148 | if (-e $path || -l $path) { | ||
| 149 | if (IO::Socket::UNIX->new(Peer => $path)) { | ||
| 150 | Carp::croak("listen: '$path' is already served by a live process"); | ||
| 151 | } | ||
| 152 | unlink $path or Carp::croak("listen: cannot remove stale socket '$path': $!"); | ||
| 153 | } | ||
| 154 | |||
| 155 | my $old = umask 0177; # create it 0600 with no chmod race | ||
| 156 | my $srv = IO::Socket::UNIX->new(Local => $path, Listen => 16); | ||
| 157 | umask $old; | ||
| 158 | Carp::croak("listen: cannot listen on '$path': $!") unless $srv; | ||
| 159 | $srv->blocking(0); | ||
| 160 | |||
| 161 | # Writing to a client that has closed raises SIGPIPE, whose default is to | ||
| 162 | # KILL THE PROCESS -- so an ordinary client disconnect, timed badly, would | ||
| 163 | # take the browser down with it. In practice Gtk4::init() happens to set | ||
| 164 | # SIGPIPE to ignore, so this has never fired; relying on a side effect of | ||
| 165 | # somebody else's initialiser is not a plan. Say it ourselves, and let | ||
| 166 | # _flush's EPIPE check do the work. (Process-wide, as signal dispositions | ||
| 167 | # are -- but ignoring SIGPIPE is what any socket server does.) | ||
| 168 | $SIG{PIPE} = 'IGNORE'; | ||
| 169 | |||
| 170 | my $self = bless { | ||
| 171 | browser => $browser, | ||
| 172 | path => $path, | ||
| 173 | srv => $srv, | ||
| 174 | clients => {}, # id => client state | ||
| 175 | next_id => 0, | ||
| 176 | handles => {}, # handle => { el => $element, client => $id } | ||
| 177 | next_handle => 0, | ||
| 178 | }, $class; | ||
| 179 | |||
| 180 | weaken(my $wself = $self); | ||
| 181 | $self->{aw} = EV::io($srv, EV::READ, sub { | ||
| 182 | my $s = $wself or return; | ||
| 183 | while (my $fh = $s->{srv}->accept) { $s->_add_client($fh) } | ||
| 184 | }); | ||
| 185 | |||
| 186 | $self->_wire_events; | ||
| 187 | return $self; | ||
| 188 | } | ||
| 189 | |||
| 190 | # Chain the browser's event handlers so a client hears what it did not ask for -- | ||
| 191 | # above all the human navigating a window the client is also driving. | ||
| 192 | # | ||
| 193 | # CHAINED, never clobbered: eg/browser.pl prints console lines to its terminal | ||
| 194 | # while this server forwards the same lines to its clients, and neither knows | ||
| 195 | # about the other. | ||
| 196 | # | ||
| 197 | # And weakened BOTH ways. The browser holds these closures, so a closure that | ||
| 198 | # captures the browser strongly is a $b -> on_load -> $b cycle plain refcounting | ||
| 199 | # can never break -- this module has shipped that exact bug more than once. The | ||
| 200 | # server is weakened for the same reason from the other side. | ||
| 201 | sub _wire_events { | ||
| 202 | my $self = shift; | ||
| 203 | my $b = $self->{browser}; | ||
| 204 | weaken(my $ws = $self); | ||
| 205 | weaken(my $wb = $b); | ||
| 206 | |||
| 207 | my $prev_nav = $b->on_navigate; | ||
| 208 | $b->on_navigate(sub { | ||
| 209 | if (my $s = $ws) { | ||
| 210 | # Every element handle belongs to the page that just went away: the | ||
| 211 | # registry's epoch changed, so they are all stale by definition. Freeing | ||
| 212 | # them here is what keeps the handle table from growing without bound -- | ||
| 213 | # see _hold. | ||
| 214 | $s->_release_all_handles; | ||
| 215 | $s->_broadcast(navigate => { uri => $_[0] }); | ||
| 216 | } | ||
| 217 | $prev_nav->(@_) if $prev_nav; | ||
| 218 | }); | ||
| 219 | |||
| 220 | my $prev_load = $b->on_load; | ||
| 221 | $b->on_load(sub { | ||
| 222 | my ($s, $br) = ($ws, $wb); | ||
| 223 | if ($s && $br) { | ||
| 224 | $s->_broadcast(load => { | ||
| 225 | uri => scalar eval { $br->uri }, | ||
| 226 | title => scalar eval { $br->title }, | ||
| 227 | }); | ||
| 228 | } | ||
| 229 | $prev_load->(@_) if $prev_load; | ||
| 230 | }); | ||
| 231 | |||
| 232 | my $prev_con = $b->on_console; | ||
| 233 | $b->on_console(sub { | ||
| 234 | if (my $s = $ws) { | ||
| 235 | $s->_broadcast(console => { text => $_[0] }); | ||
| 236 | } | ||
| 237 | $prev_con->(@_) if $prev_con; | ||
| 238 | }); | ||
| 239 | |||
| 240 | my $prev_err = $b->on_error; | ||
| 241 | $b->on_error(sub { | ||
| 242 | if (my $s = $ws) { | ||
| 243 | $s->_broadcast(error => { error => $_[0] }); | ||
| 244 | } | ||
| 245 | $prev_err->(@_) if $prev_err; | ||
| 246 | }); | ||
| 247 | |||
| 248 | # The HUMAN closing the window. (A client's quit over the wire does not come | ||
| 249 | # through here -- see the quit branch of _dispatch, which broadcasts too.) | ||
| 250 | my $prev_close = $b->on_close; | ||
| 251 | $b->on_close(sub { | ||
| 252 | if (my $s = $ws) { | ||
| 253 | $s->_broadcast(close => {}); | ||
| 254 | $s->close; | ||
| 255 | } | ||
| 256 | $prev_close->(@_) if $prev_close; # the caller's EV::break goes LAST | ||
| 257 | }); | ||
| 258 | |||
| 259 | return; | ||
| 260 | } | ||
| 261 | |||
| 262 | sub path { $_[0]{path} } | ||
| 263 | |||
| 264 | sub _add_client { | ||
| 265 | my ($self, $fh) = @_; | ||
| 266 | $fh->blocking(0); | ||
| 267 | my $id = ++$self->{next_id}; | ||
| 268 | my $c = $self->{clients}{$id} = { | ||
| 269 | id => $id, | ||
| 270 | fh => $fh, | ||
| 271 | dec => EV::WebKit::Protocol::decoder(), | ||
| 272 | out => '', | ||
| 273 | }; | ||
| 274 | |||
| 275 | weaken(my $wself = $self); | ||
| 276 | $c->{rw} = EV::io($fh, EV::READ, sub { | ||
| 277 | my $s = $wself or return; | ||
| 278 | my $n = sysread($fh, my $buf, 65536); | ||
| 279 | if (!defined $n) { | ||
| 280 | return if $!{EAGAIN} || $!{EINTR}; | ||
| 281 | return $s->_drop_client($id); | ||
| 282 | } | ||
| 283 | return $s->_drop_client($id) unless $n; # EOF | ||
| 284 | # Stop the instant this client is gone. A `quit` frame tears the server | ||
| 285 | # down mid-loop, and anything pipelined behind it in the same read would | ||
| 286 | # otherwise be dispatched against a client that no longer exists: the | ||
| 287 | # side effects would run and the answer would go nowhere, which is a | ||
| 288 | # silently dropped request -- a hung client. | ||
| 289 | for my $f ($c->{dec}->($buf)) { | ||
| 290 | # Guarded per FRAME: a die inside _dispatch escapes into the read | ||
| 291 | # watcher, losing this frame's answer AND every sibling decoded from | ||
| 292 | # the same sysread. The known cause is fixed at its source, but a | ||
| 293 | # whole batch is too much to lose to any future unguarded path. | ||
| 294 | unless (eval { $s->_dispatch($id, $f); 1 }) { | ||
| 295 | my $e = _clean($@) || 'internal error'; | ||
| 296 | warn "EV::WebKit::Control: dispatch died: $e"; | ||
| 297 | eval { $s->_send($id, { i => $f->{i}, e => $e }) }; | ||
| 298 | } | ||
| 299 | last unless exists $s->{clients}{$id}; | ||
| 300 | } | ||
| 301 | }); | ||
| 302 | |||
| 303 | # Greet, so a client attaching to a long-lived session learns where the | ||
| 304 | # browser already is without having to ask for it. | ||
| 305 | my $b = $self->{browser}; | ||
| 306 | $self->_send($id, { | ||
| 307 | ev => 'hello', | ||
| 308 | proto => EV::WebKit::Protocol::PROTO, | ||
| 309 | uri => scalar eval { $b->uri }, | ||
| 310 | title => scalar eval { $b->title }, | ||
| 311 | }); | ||
| 312 | return; | ||
| 313 | } | ||
| 314 | |||
| 315 | sub _drop_client { | ||
| 316 | my ($self, $id) = @_; | ||
| 317 | my $c = delete $self->{clients}{$id} or return; | ||
| 318 | $self->_release_handles_of($id); | ||
| 319 | delete $c->{rw}; | ||
| 320 | delete $c->{ww}; | ||
| 321 | if ($c->{fh}) { | ||
| 322 | $self->_drain($c); | ||
| 323 | close $c->{fh}; | ||
| 324 | } | ||
| 325 | return; | ||
| 326 | } | ||
| 327 | |||
| 328 | # Get whatever is still queued out of the door before closing the socket. | ||
| 329 | # | ||
| 330 | # Without this, close() throws away {out} -- and {out} is exactly where a | ||
| 331 | # client's own quit-ack and the 'close' event sit when its socket is backed up | ||
| 332 | # (a burst of broadcasts it has not drained yet). The client then sees a bare | ||
| 333 | # EOF and cannot tell an orderly shutdown from the browser crashing, which is | ||
| 334 | # the one thing the close event exists to tell it. | ||
| 335 | # | ||
| 336 | # BOUNDED, because the rule that a stalled client must never block the browser | ||
| 337 | # still holds: half a second, and a peer that has actually gone away fails on the | ||
| 338 | # first write and costs nothing at all. | ||
| 339 | sub _drain { | ||
| 340 | my ($self, $c) = @_; | ||
| 341 | return unless length $c->{out}; | ||
| 342 | my $end = EV::time + 0.5; # EV::time, not time: whole-second granularity made this window anywhere from 10ms to a full second | ||
| 343 | while (length $c->{out} && EV::time < $end) { | ||
| 344 | my $n = syswrite($c->{fh}, $c->{out}); | ||
| 345 | if (defined $n) { substr($c->{out}, 0, $n, ''); next } | ||
| 346 | last unless $!{EAGAIN} || $!{EINTR}; # the peer is gone: nothing to drain to | ||
| 347 | my $w = ''; | ||
| 348 | vec($w, fileno($c->{fh}), 1) = 1; | ||
| 349 | select undef, $w, undef, 0.05; # wait briefly for it to take more | ||
| 350 | } | ||
| 351 | return; | ||
| 352 | } | ||
| 353 | |||
| 354 | # Queue a frame and flush what we can. A slow or stalled client must NEVER block | ||
| 355 | # the browser, so anything the socket will not take right now waits in {out} and | ||
| 356 | # a write watcher drains it. | ||
| 357 | sub _send { | ||
| 358 | my ($self, $id, $frame) = @_; | ||
| 359 | my $c = $self->{clients}{$id} or return; | ||
| 360 | my $line = eval { EV::WebKit::Protocol::encode($frame) }; | ||
| 361 | unless (defined $line) { | ||
| 362 | # A frame the codec cannot encode must NOT become silence. The die would | ||
| 363 | # otherwise happen inside EV::WebKit's _defer timer, where $EV::DIED | ||
| 364 | # merely warns -- and the client would wait forever for a response that | ||
| 365 | # is never coming. A hung client is the one failure mode this protocol | ||
| 366 | # must not have, so an unencodable result is answered AS an error. | ||
| 367 | # | ||
| 368 | # (What triggers this: a method whose result is an object rather than | ||
| 369 | # plain data. find/find_all/wait_for all resolve with an Element, which | ||
| 370 | # is why they are marshalled into handles below. This guard is what keeps | ||
| 371 | # the NEXT such method from being a silent hang instead of an error.) | ||
| 372 | my $why = _clean($@); | ||
| 373 | warn "EV::WebKit::Control: cannot encode a frame: $why"; | ||
| 374 | return unless exists $frame->{i}; # an event: there is nobody to answer | ||
| 375 | $line = EV::WebKit::Protocol::encode({ i => $frame->{i}, e => "cannot encode result: $why" }); | ||
| 376 | } | ||
| 377 | # A client that has stopped reading (SIGSTOP'd, suspended, wedged) still | ||
| 378 | # gets everything queued for it, and the PAGE controls the volume -- console | ||
| 379 | # output is broadcast to every client. Unbounded, that inflates the browser | ||
| 380 | # process until it dies. Drop the client instead: the socket is a | ||
| 381 | # convenience, and losing one backlogged client is not worth the browser. | ||
| 382 | if (length($c->{out}) + length($line) > MAX_CLIENT_BACKLOG) { | ||
| 383 | warn "EV::WebKit::Control: client $id is not reading (backlog over " | ||
| 384 | . MAX_CLIENT_BACKLOG . " bytes) -- dropping it\n"; | ||
| 385 | $self->_drop_client($id); | ||
| 386 | return; | ||
| 387 | } | ||
| 388 | $c->{out} .= $line; | ||
| 389 | $self->_flush($id); | ||
| 390 | return; | ||
| 391 | } | ||
| 392 | |||
| 393 | sub _flush { | ||
| 394 | my ($self, $id) = @_; | ||
| 395 | my $c = $self->{clients}{$id} or return; | ||
| 396 | while (length $c->{out}) { | ||
| 397 | my $n = syswrite($c->{fh}, $c->{out}); | ||
| 398 | if (!defined $n) { | ||
| 399 | last if $!{EAGAIN} || $!{EINTR}; | ||
| 400 | return $self->_drop_client($id); # the peer is gone | ||
| 401 | } | ||
| 402 | substr($c->{out}, 0, $n, ''); | ||
| 403 | } | ||
| 404 | if (length $c->{out}) { | ||
| 405 | weaken(my $wself = $self); | ||
| 406 | $c->{ww} ||= EV::io($c->{fh}, EV::WRITE, sub { | ||
| 407 | my $s = $wself or return; | ||
| 408 | $s->_flush($id); | ||
| 409 | }); | ||
| 410 | } | ||
| 411 | else { | ||
| 412 | delete $c->{ww}; | ||
| 413 | } | ||
| 414 | return; | ||
| 415 | } | ||
| 416 | |||
| 417 | sub _dispatch { | ||
| 418 | my ($self, $id, $f) = @_; | ||
| 419 | if ($f->{_bad}) { | ||
| 420 | $self->_send($id, { i => undef, e => $f->{_bad} }); | ||
| 421 | # An oversized line poisons this connection's decoder for good -- it can | ||
| 422 | # never make sense of the stream again, and every later request would get | ||
| 423 | # the same baffling 'line too long' (even a `title` that takes no | ||
| 424 | # arguments at all). Drop it and let the client reconnect, which is the | ||
| 425 | # only thing that can actually help. | ||
| 426 | $self->_drop_client($id) if $f->{_bad} =~ /too long/; | ||
| 427 | return; | ||
| 428 | } | ||
| 429 | |||
| 430 | my $rid = $f->{i}; | ||
| 431 | my $m = $f->{m} // ''; | ||
| 432 | # SHAPE, not just presence: `// []` guards a MISSING field and does nothing | ||
| 433 | # about a present one of the wrong type, and @{ $hashref } is a fatal "Not an | ||
| 434 | # ARRAY reference" thrown inside the read watcher where nothing catches it. | ||
| 435 | # So {"a":{}} went unanswered and took every frame decoded from the same | ||
| 436 | # sysread with it. | ||
| 437 | for my $bad ([a => 'ARRAY', 'an array'], [o => 'HASH', 'an object']) { | ||
| 438 | my ($k, $want, $shown) = @$bad; | ||
| 439 | next if !defined $f->{$k} || ref $f->{$k} eq $want; | ||
| 440 | return $self->_send($id, { i => $rid, e => "'$k' must be $shown" }); | ||
| 441 | } | ||
| 442 | my @a = @{ $f->{a} // [] }; | ||
| 443 | my %o = %{ $f->{o} // {} }; | ||
| 444 | my $b = $self->{browser}; | ||
| 445 | |||
| 446 | weaken(my $wself = $self); | ||
| 447 | my $answer = sub { # exactly one response per request | ||
| 448 | my ($r, $e) = @_; | ||
| 449 | my $s = $wself or return; | ||
| 450 | $s->_send($id, defined $e ? { i => $rid, e => "$e" } : { i => $rid, r => $r }); | ||
| 451 | }; | ||
| 452 | |||
| 453 | # quit is special: answer FIRST, because the socket is about to close, and | ||
| 454 | # tell every client the browser is going. on_close does not cover this -- | ||
| 455 | # that fires only when a HUMAN closes the window. | ||
| 456 | if ($m eq 'quit') { | ||
| 457 | $answer->(1); | ||
| 458 | $self->_broadcast(close => {}); | ||
| 459 | eval { $b->quit }; | ||
| 460 | $self->close; | ||
| 461 | return; | ||
| 462 | } | ||
| 463 | |||
| 464 | # An Element cannot cross a socket, so find/find_all answer with a HANDLE the | ||
| 465 | # server holds on the client's behalf. | ||
| 466 | my $marshal = sub { | ||
| 467 | my ($r, $e) = @_; | ||
| 468 | my $s = $wself or return; | ||
| 469 | return $answer->(undef, $e) if defined $e; | ||
| 470 | return $answer->(undef) if !defined $r; | ||
| 471 | return $answer->([ map { $s->_hold($id, $_) } @$r ]) if ref $r eq 'ARRAY'; | ||
| 472 | # wait_for(gone => 1) is the one caller here that resolves with a plain | ||
| 473 | # TRUE rather than an element -- deliberately, since a node that is gone | ||
| 474 | # cannot be handed back. Held as if it were one, it became an | ||
| 475 | # EV::WebKit::Client::Element wrapping the scalar 1 on the client (truthy, | ||
| 476 | # so the usual `if ($ok)` hid it) and pinned a server handle per call. | ||
| 477 | return $answer->($r) if !ref $r; | ||
| 478 | return $answer->($s->_hold($id, $r)); | ||
| 479 | }; | ||
| 480 | |||
| 481 | # All three resolve with an Element on success. | ||
| 482 | if ($m eq 'find' || $m eq 'find_all' || $m eq 'wait_for' | ||
| 483 | || $m eq 'find_js' || $m eq 'find_all_js') { | ||
| 484 | my $ok = eval { $b->$m(@a, %o, $marshal); 1 }; | ||
| 485 | return $answer->(undef, _clean($@)) unless $ok; | ||
| 486 | return; | ||
| 487 | } | ||
| 488 | |||
| 489 | # screenshot($path, %opt, $cb) or screenshot(\%opt, $cb) -- the first argument | ||
| 490 | # is a path OR an options hashref, and the generic flattening below cannot | ||
| 491 | # express that: {"o":{"bytes":1}} would become screenshot('bytes', 1, $cb), | ||
| 492 | # which takes 'bytes' for a PATH and writes a PNG to a file of that name in | ||
| 493 | # the server's working directory, then reports success. And in bytes mode the | ||
| 494 | # result is raw PNG octets, which cannot live in a JSON string at all. | ||
| 495 | if ($m eq 'screenshot') { | ||
| 496 | my @args = @a ? (@a, %o) : (\%o); | ||
| 497 | # Whether bytes were asked for has to be worked out the same way | ||
| 498 | # EV::WebKit::screenshot works it out, because a client sends its | ||
| 499 | # arguments positionally, exactly as it received them: the options may be | ||
| 500 | # the leading hashref, or trailing pairs after a path. | ||
| 501 | # The tail must pair up before it becomes a hash, or this warns "Odd | ||
| 502 | # number of elements in hash assignment" from inside the server on a | ||
| 503 | # list the CLIENT chose -- reachable as $c->screenshot(bytes => 1). | ||
| 504 | # screenshot() itself croaks on it a moment later; this only has to | ||
| 505 | # avoid the warning while working out whether bytes were asked for. | ||
| 506 | my %sopt; | ||
| 507 | if (ref $args[0] eq 'HASH') { %sopt = %{ $args[0] } } | ||
| 508 | elsif (@args % 2 == 1) { %sopt = @args[1 .. $#args] } | ||
| 509 | my $want_bytes = $sopt{bytes}; | ||
| 510 | my $ok = eval { | ||
| 511 | $b->screenshot(@args, sub { | ||
| 512 | my ($r, $e) = @_; | ||
| 513 | return $answer->(undef, $e) if defined $e; | ||
| 514 | return $answer->({ b64 => MIME::Base64::encode_base64($r, '') }) | ||
| 515 | if $want_bytes && defined $r; | ||
| 516 | return $answer->($r); # path mode: the result IS the path | ||
| 517 | }); | ||
| 518 | 1; | ||
| 519 | }; | ||
| 520 | return $answer->(undef, _clean($@)) unless $ok; | ||
| 521 | return; | ||
| 522 | } | ||
| 523 | |||
| 524 | if ($m eq 'el.release') { | ||
| 525 | # Ownership checked HERE too: this branch returns before the check below, | ||
| 526 | # whose own comment names el.release as a case it covers -- so it did | ||
| 527 | # not, and handle ids are small sequential integers. Answer as though the | ||
| 528 | # handle is not there, which for this client it is not. | ||
| 529 | my $h = $f->{h} // ''; | ||
| 530 | my $rec = $self->{handles}{$h}; | ||
| 531 | return $answer->(undef, 'stale element') | ||
| 532 | unless $rec && defined $rec->{client} && $rec->{client} == $id; | ||
| 533 | delete $self->{handles}{$h}; | ||
| 534 | return $answer->(1); | ||
| 535 | } | ||
| 536 | |||
| 537 | if (index($m, 'el.') == 0) { | ||
| 538 | my $em = substr($m, 3); | ||
| 539 | return $answer->(undef, "unknown method: $m") unless exists $EL_METHOD{$em}; | ||
| 540 | my ($min, $max) = @{ $EL_METHOD{$em} }; | ||
| 541 | if (@a < $min || @a > $max) { | ||
| 542 | my $want = $min == $max ? $min : "$min to $max"; | ||
| 543 | return $answer->(undef, | ||
| 544 | "$m: expected $want argument" . ($max == 1 && $min == 1 ? '' : 's') . ', got ' . scalar(@a)); | ||
| 545 | } | ||
| 546 | my $rec = $self->{handles}{ $f->{h} // '' }; | ||
| 547 | # A handle belongs to the client that made it. Handle ids are small | ||
| 548 | # sequential integers, so without this a client could reach another's | ||
| 549 | # element -- or el.release it out from under them -- by guessing a | ||
| 550 | # number. It grants no capability a client lacks (they can all find() | ||
| 551 | # whatever they like: the socket is the privilege boundary, and the | ||
| 552 | # design says so), but a handle table keyed per client that does not | ||
| 553 | # CHECK the client is an accident waiting to be relied upon. | ||
| 554 | return $answer->(undef, 'stale element') | ||
| 555 | unless $rec && defined $rec->{client} && $rec->{client} == $id; | ||
| 556 | my $el = $rec->{el}; | ||
| 557 | my $cb = ($em eq 'find' || $em eq 'find_all') ? $marshal : sub { $answer->(@_) }; | ||
| 558 | my $ok = eval { $el->$em(@a, $cb); 1 }; | ||
| 559 | return $answer->(undef, _clean($@)) unless $ok; | ||
| 560 | return; | ||
| 561 | } | ||
| 562 | |||
| 563 | if ($SYNC{$m}) { | ||
| 564 | # Sync methods croak (settings, set_user_agent and set_proxy all do). A | ||
| 565 | # die in one client's request must never kill the browser or drop | ||
| 566 | # anybody else's work -- the same lesson quit()'s flush loops taught. | ||
| 567 | my $r = eval { $b->$m(@a) }; | ||
| 568 | return $answer->(undef, _clean($@)) if $@; | ||
| 569 | $r = 1 if ref $r; # a mutator returns $b; do not try to serialize a browser | ||
| 570 | return $answer->($r); | ||
| 571 | } | ||
| 572 | |||
| 573 | if (my $r = $ARITY{$m}) { | ||
| 574 | my ($min, $max) = @$r; | ||
| 575 | if (@a < $min || (defined $max && @a > $max)) { | ||
| 576 | my ($want, $plural) = | ||
| 577 | !defined $max ? ("at least $min", $min != 1) | ||
| 578 | : $min == $max ? ($min, $min != 1) | ||
| 579 | : ("$min to $max", 1); | ||
| 580 | return $answer->(undef, "$m: expected $want argument" | ||
| 581 | . ($plural ? 's' : '') . ', got ' . scalar(@a)); | ||
| 582 | } | ||
| 583 | } | ||
| 584 | |||
| 585 | # Named, not positional: scroll takes either, and every other argument it | ||
| 586 | # takes is named, so naming this one keeps the list unambiguous. | ||
| 587 | if ($m eq 'scroll') { | ||
| 588 | my $ok = eval { $b->scroll(@a, %o, cb => sub { $answer->(@_) }); 1 }; | ||
| 589 | return $answer->(undef, _clean($@)) unless $ok; | ||
| 590 | return; | ||
| 591 | } | ||
| 592 | |||
| 593 | if ($ASYNC{$m}) { | ||
| 594 | my $ok = eval { $b->$m(@a, %o, sub { $answer->(@_) }); 1 }; | ||
| 595 | return $answer->(undef, _clean($@)) unless $ok; | ||
| 596 | return; | ||
| 597 | } | ||
| 598 | |||
| 599 | return $answer->(undef, "unknown method: $m"); | ||
| 600 | } | ||
| 601 | |||
| 602 | sub _broadcast { | ||
| 603 | my ($self, $ev, $data) = @_; | ||
| 604 | $self->_send($_, { ev => $ev, %{ $data || {} } }) for keys %{ $self->{clients} }; | ||
| 605 | return; | ||
| 606 | } | ||
| 607 | |||
| 608 | # Element handles. | ||
| 609 | # | ||
| 610 | # Every find() mints an EV::WebKit::Element that holds the browser, so a table | ||
| 611 | # that is never pruned rebuilds -- in Perl -- the unbounded registry growth that | ||
| 612 | # was just fixed on the JavaScript side. And a find() poll loop against a | ||
| 613 | # long-lived page is the ordinary case, not an exotic one. | ||
| 614 | # | ||
| 615 | # So handles are freed on three events: the page NAVIGATES (they are all stale by | ||
| 616 | # then -- the page's epoch changed), the CLIENT DISCONNECTS, and an explicit | ||
| 617 | # el.release. That bounds the table by "handles made since the last navigation, | ||
| 618 | # by clients still connected". | ||
| 619 | sub _hold { | ||
| 620 | my ($self, $cid, $el) = @_; | ||
| 621 | # A find still in flight resolves AFTER its client disconnected, and | ||
| 622 | # _release_handles_of has already run by then -- so a handle minted here | ||
| 623 | # would have no owner left to free it, and only the next navigation would. | ||
| 624 | # A session that never navigates accumulated one per lost client. | ||
| 625 | return undef unless exists $self->{clients}{$cid}; | ||
| 626 | my $h = ++$self->{next_handle}; | ||
| 627 | $self->{handles}{$h} = { el => $el, client => $cid }; | ||
| 628 | return { h => $h }; | ||
| 629 | } | ||
| 630 | |||
| 631 | sub _release_handles_of { | ||
| 632 | my ($self, $cid) = @_; | ||
| 633 | for my $h (keys %{ $self->{handles} || {} }) { | ||
| 634 | delete $self->{handles}{$h} | ||
| 635 | if defined $self->{handles}{$h}{client} && $self->{handles}{$h}{client} == $cid; | ||
| 636 | } | ||
| 637 | return; | ||
| 638 | } | ||
| 639 | |||
| 640 | sub _release_all_handles { $_[0]{handles} = {}; return } | ||
| 641 | |||
| 642 | sub _clean { | ||
| 643 | my $e = shift // 'error'; | ||
| 644 | $e =~ s/ at \S+ line \d+\.?\s*\z//; | ||
| 645 | $e =~ s/\s+\z//; | ||
| 646 | return length $e ? $e : 'error'; | ||
| 647 | } | ||
| 648 | |||
| 649 | sub close { | ||
| 650 | my $self = shift; | ||
| 651 | return if $self->{_closed}++; | ||
| 652 | delete $self->{aw}; | ||
| 653 | $self->_drop_client($_) for keys %{ $self->{clients} }; | ||
| 654 | close $self->{srv} if $self->{srv}; | ||
| 655 | delete $self->{srv}; | ||
| 656 | unlink $self->{path} if defined $self->{path} && -S $self->{path}; | ||
| 657 | return; | ||
| 658 | } | ||
| 659 | |||
| 660 | sub DESTROY { local $@; eval { $_[0]->close } } | ||
| 661 | |||
| 662 | 1; | ||
| 663 | |||
| 664 | __END__ |