File: echo_nonblock.pm

package info (click to toggle)
libapache2-mod-perl2 2.0.9~1624218-2%2Bdeb8u2
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 11,912 kB
  • ctags: 4,588
  • sloc: perl: 95,064; ansic: 14,527; makefile: 49; sh: 18
file content (80 lines) | stat: -rw-r--r-- 2,402 bytes parent folder | download | duplicates (7)
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
# please insert nothing before this line: -*- mode: cperl; cperl-indent-level: 4; cperl-continued-statement-offset: 4; indent-tabs-mode: nil -*-
package TestProtocol::echo_nonblock;

# this test reads from/writes to the socket doing nonblocking IO

use strict;
use warnings FATAL => 'all';

use Apache2::Connection ();
use APR::Socket ();
use APR::Error ();

use Apache::TestTrace;

use Apache2::Const -compile => 'OK';
use APR::Const    -compile => qw(SO_NONBLOCK SUCCESS POLLIN);
use APR::Status ();

use constant BUFF_LEN => 1024;

sub handler {
    my $c = shift;
    my $socket = $c->client_socket;

    $socket->opt_set(APR::Const::SO_NONBLOCK, 1);

    my $counter = 0;
    my $timeout = 0;
    while (1) {

        debug "counter: $counter";
        if ($counter == 1) {
            # this will certainly cause timeout
            $timeout = 0;
        } else {
            # Wait up to ten seconds for data to arrive.
            $timeout = 10_000_000;
        }
        $counter++;

        my $rc = $socket->poll($c->pool, $timeout, APR::Const::POLLIN);
        if ($rc == APR::Const::SUCCESS) {
            my $buf;
            my $len = eval { $socket->recv($buf, BUFF_LEN) };
            if ($@) {
                # rethrow
                die $@ unless ref $@ eq 'APR::Error'
                    && (APR::Status::is_ECONNABORTED($@) ||
                        APR::Status::is_ECONNRESET($@));
                # ECONNABORTED == 103
                # ECONNRESET   == 104
                # ECONNABORTED is not an application error
                # XXX: we don't really test that we always get this
                # condition, since it depends on the timing of the
                # client closing the socket. may be it'd be possible
                # to make sure that APR::Const::ECONNABORTED was received
                # when $counter == 2 if we have slept enough, but how
                # much is enough is unknown
                debug "caught '104: Connection reset by peer' error";
                last;
            }

            last unless $len;

            debug "sending: $buf";
            $socket->send($buf);
        }
        elsif (APR::Status::is_TIMEUP($rc)) {
            debug "timeout";
            $socket->send("TIMEUP\n");
        }
        else {
            die "poll error: $rc: " . APR::Error::strerror($rc);
        }
    }

    Apache2::Const::OK;
}

1;