summaryrefslogtreecommitdiffstats
path: root/Spline/Socketmap.pm
blob: f78ed3fc17cffd42f83d379fc7eafff9ec05fc58 (plain)
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
package Spline::Socketmap;

use strict;
use warnings;
use base qw(Net::Server::PreFork);

use Spline::Srs qw( srs_forward srs_reverse );

use base 'Exporter';
our @EXPORT = qw( );
our @EXPORT_OK = qw( );

our $timeout = 10;
our $handler = undef; 

sub call_handler(@) {
    return unless ref($handler) eq 'CODE';
    return \&$handler(@_);
}

sub handle_request($) {
    my $data = shift;

    my ($map, $key) = split(/ /, $data, 2);
    my $result = call_handler($map, $key);
    if (defined $result) {
        reply($result);
    }
    else {
        reply('TEMP Protocol error');
    }
}

sub netstring_read_length($) {
    my $fd = shift;
    my $length;

    local $/ = ':';
    $length = <$fd>;
    die "Cannot read netstring length" unless defined($length);
    chomp $length;

    return $length;
}

sub netstring_read($) {
    my $fd = shift;
    my ($length, $data);

    $length = netstring_read_length($fd);
    if (read($fd, $data, $length) == $length) {
        (getc() eq ',') or die "Closing , missing";
    }
    else {
        die 'Received only ' . length($data) . " of $length bytes";
    }

    return $data;
}

sub netstring_write($$) {
    my ($fd, $data) = @_;

    print $fd length($data).':'.$data.',';
}

sub process_request {
    my $self = shift;

    eval {
        local $SIG{'ALRM'} = sub { die "Timed Out!\n" };
        alarm($timeout);

        handle_request(netstring_read(*STDIN));
        alarm(0);
    };
    my $err = $@;
    alarm(0);


    if ($err) {
        if ($err =~ /timed out/i) {
            reply('TEMP Timeout');
        }
        else {
            reply('TEMP Unknown error');
        }
    }
}

sub reply($) {
    netstring_write(*STDOUT, @_);
}

1;

# vim: set et ts=4: