| 1 | package Bot::Cobalt::Plugin::Calc::Worker; | ||
| 2 | $Bot::Cobalt::Plugin::Calc::Worker::VERSION = '0.004004'; | ||
| 3 | use strict; | ||
| 4 | use bytes; | ||
| 5 | |||
| 6 | use BSD::Resource qw/ | ||
| 7 | setrlimit | ||
| 8 | |||
| 9 | RLIMIT_DATA | ||
| 10 | RLIMIT_STACK | ||
| 11 | RLIMIT_AS | ||
| 12 | RLIMIT_VMEM | ||
| 13 | RLIMIT_CPU | ||
| 14 | /; | ||
| 15 | |||
| 16 | use Storable 'nfreeze', 'thaw'; | ||
| 17 | |||
| 18 | use Math::Calc::Parser (); | ||
| 19 | |||
| 20 | sub MEMLIMIT_BYTES () { 64 * 1024 * 1024 } | ||
| 21 | |||
| 22 | $SIG{INT} = sub { die "Timed out!\n" }; | ||
| 23 | |||
| 24 | sub worker { | ||
| 25 | binmode *STDOUT; binmode *STDIN; | ||
| 26 | select *STDOUT; | ||
| 27 | $|++; | ||
| 28 | |||
| 29 | # not error-checked, may fail silently on some platforms .. | ||
| 30 | # (OpenBSD lacks RLIMIT_AS f.ex) | ||
| 31 | setrlimit RLIMIT_CPU, 10, 10; | ||
| 32 | for my $const (RLIMIT_DATA RLIMIT_STACK RLIMIT_AS RLIMIT_VMEM) { | ||
| 33 | eval {; setrlimit $const, MEMLIMIT_BYTES, MEMLIMIT_BYTES }; | ||
| 34 | } | ||
| 35 | |||
| 36 | my ($buf, $read_bytes) = ''; | ||
| 37 | while (1) { | ||
| 38 | if (defined $read_bytes) { | ||
| 39 | if (length $buf >= $read_bytes) { | ||
| 40 | my $input = thaw substr $buf, 0, $read_bytes, ''; | ||
| 41 | $read_bytes = undef; | ||
| 42 | |||
| 43 | my ($tag, $expr) = @$input; | ||
| 44 | |||
| 45 | my $result = Math::Calc::Parser->try_evaluate($expr); | ||
| 46 | $result //= "err: ".Math::Calc::Parser->error; | ||
| 47 | |||
| 48 | my $frozen = nfreeze [ $tag, $result ]; | ||
| 49 | my $stream = length($frozen) . chr(0) . $frozen ; | ||
| 50 | die $! unless syswrite(*STDOUT, $stream) == length $stream; | ||
| 51 | exit 0 | ||
| 52 | } | ||
| 53 | } elsif ($buf =~ s/^(\d+)\0//) { | ||
| 54 | $read_bytes = $1; | ||
| 55 | next | ||
| 56 | } | ||
| 57 | |||
| 58 | my $readb = sysread *STDIN, $buf, 4096, length $buf; | ||
| 59 | last unless $readb; | ||
| 60 | } | ||
| 61 | |||
| 62 | exit 0 | ||
| 63 | } | ||
| 64 | |||
| 65 | 1; |