summaryrefslogtreecommitdiffstats
path: root/tests/SSLServer.pm
blob: 37a8bfa0b6c46c6d88b1ecd0b38b51df64d3cf0f (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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package SSLServer;

# This is only HTTPS server for now.
# But it is named SSLServer to easily distinguish from HTTPServer

use strict;
use warnings;
use lib '.';

use HTTP::Daemon;
use HTTP::Status;
use HTTP::Headers;
use HTTP::Response;

# Skip this test rather than fail it when the module isn't installed
if (!eval {require IO::Socket::SSL;1;}) {
    print STDERR "This test needs the perl module \"IO::Socket::SSL\".\n";
    print STDERR "Install e.g. on Debian with 'apt-get install libio-socket-ssl-perl'\n";
    print STDERR " or if using cpanminus 'cpanm IO::Socket::SSL' could be used to install it.\n";
    exit 77; # skip
}

#use IO::Socket::SSLX; # 'debug4';
use HTTPServer;

our @ISA = qw(IO::Socket::SSL HTTP::Daemon::ClientConn HTTP::Daemon HTTPServer);

my $VERSION = 0.01;

my $CRLF = "\015\012";    # "\r\n" is not portable

# Config options for server
my $log  = undef;
my $DEBUG = undef;

my %ssl_params;

my $sslsock;
my $plaincon;
my %args;

#$HTTP::Daemon::DEBUG=5;
#*DEBUG = \$HTTP::Daemon::DEBUG;

$args{SSL_error_trap} ||= \&ssl_error;

my $class = 'SSLServer';
my $self  = {};
$self = bless $self, $class;

sub init
{
    my $self = shift;
    my %sargs = @_;

    %ssl_params = %sargs;
    unless (exists($ssl_params{'lhostname'}) &&
            exists($ssl_params{'sslport'})   &&
            exists($ssl_params{'ciphers'})   &&
            exists($ssl_params{'cafile'})    &&
            exists($ssl_params{'certfile'})  &&
            exists($ssl_params{'keyfile'})) {
        die "Required parameters for SSL tests are missing";
    }
}

sub ssl_setup_conn
{
    $sslsock = IO::Socket::SSL->new(LocalAddr       => $ssl_params{'lhostname'},
                                    LocalPort       => $ssl_params{'sslport'},
                                    Listen          => 10,
                                    Timeout         => 30,
                                    ReuseAddr       => 1,
                                    SSL_cipher_list => $ssl_params{'ciphers'},
                                    SSL_verify_mode => 0x00,
                                    SSL_ca_file     => $ssl_params{'cafile'},
                                    SSL_cert_file   => $ssl_params{'certfile'},
                                    SSL_key_file    => $ssl_params{'keyfile'});

    $sslsock || warn $IO::Socket::SSL::ERROR;
    return $sslsock;
}

sub fileno
{
    my $self = shift;
    my $fn = ${*$self}{'_SSL_fileno'};
    return defined($fn) ? $fn : $self->SUPER::fileno();
}

sub accept
{
    my $self = shift;
    my $pkg = shift || "SSLServer";
    my ($sock, $peer) = $sslsock->accept($pkg);
    if ($sock) {
        ${*$sock}{'httpd_daemon'} = $self;
        ${*$self}{'httpd_daemon'} = $sock;
        my $fileno = ${*$self}{'_SSL_fileno'} = &fileno($self);
        my $f = $sock->fileno;
        return wantarray ? ($sock, $peer) : $sock;
    }
    else {
        print STDERR "Failed to get socket from SSL\n" if $DEBUG;
        return;
    }

}

sub _default_port { 443; }
sub _default_scheme { "https"; }

sub url
{
    my $self = shift;
    my $url = $self->SUPER::url;
    return $url if ($self->can("HTTP::Daemon::_default_port"));

    # Workaround for old versions of HTTP::Daemon
    $url =~ s!^http:!https:!;
    $url =~ s!/$!:80/! unless ($url =~ m!:(?:\d+)/$!);
    $url =~ s!:443/$!/!;
    return $url;
}

sub _need_more
{
    my $self = shift;
    if ($_[1]) {
        my($timeout, $fdset) = @_[1,2];
        print STDERR "select(,,,$timeout)\n" if $DEBUG;
        my $n = select($fdset,undef,undef,$timeout);
        unless ($n) {
            $self->reason(defined($n) ? "Timeout" : "select: $!");
            return;
        }
    }
    my $total = 0;
    while (1){
        print STDERR sprintf("sysread() already %d\n",$total) if $DEBUG;
        my $n = sysread(${*$self}{'httpd_daemon'}, $_[0], 2048, length($_[0]));
        print STDERR sprintf("sysread() just \$n=%s\n",(defined $n?$n:'undef')) if $DEBUG;
        $total += $n if defined $n;
        last if $! =~ 'Resource temporarily unavailable';
        #SSL_Error because of aggressive reading

        $self->reason(defined($n) ? "Client closed" : "sysread: $!") unless $n;
        last unless $n;
        last unless $n == 2048;
    }
    $total;
}

sub daemon
{
    my $self = shift;
    ${*$self}{'httpd_daemon'};
}

sub conn
{
    my $self = shift;
    ${*$self}{'sslcon'};
}

sub run
{
    my ($self, $urls, $synch_callback) = @_;
    my $initialized = 0;
    my $sslsock;

    while (1)
    {
        if (!$initialized)
        {
            $sslsock = $self->ssl_setup_conn();
            $sslsock || warn "Failed to get ssl sock";

            $initialized = 1;
            open (LOGFILE, '>', "/tmp/wgetserver.log");
            LOGFILE->autoflush(1);
            print LOGFILE "Starting logging";
            $synch_callback->() if $synch_callback;
        }

        my $con = $self->accept();
        ${*$self}{'sslcon'} = $con;

        while (my $req = $self->get_request)
        {
            #my $url_path = $req->url->path;
            my $url_path = $req->url->as_string;
            if ($url_path =~ m{/$})
            {    # append 'index.html'
                $url_path .= 'index.html';
            }

            #if ($url_path =~ m{^/}) { # remove trailing '/'
            #    $url_path = substr ($url_path, 1);
            #}
            if ($log)
            {
                print LOGFILE "Method: ", $req->method, "\n";
                print LOGFILE "Path: ", $url_path, "\n";
                print LOGFILE "Available URLs: ", "\n";
                foreach my $key (keys %$urls)
                {
                    print LOGFILE $key, "\n";
                }
            }
            if (exists($urls->{$url_path}))
            {
                print LOGFILE "Serving requested URL: ", $url_path, "\n" if $log;
                next unless ($req->method eq "HEAD" || $req->method eq "GET");

                my $url_rec = $urls->{$url_path};
                HTTPServer::send_response($self, $req, $url_rec, $con);
                last;
            }
            else
            {
                print LOGFILE "Requested wrong URL: ", $url_path, "\n" if $log;
                $con->send_error($HTTP::Status::RC_FORBIDDEN);
                last;
            }
            last;
        }
        print LOGFILE "Closing connection\n" if $log;
        close(LOGFILE);
        $con->close();
    }
}

1;

# vim: et ts=4 sw=4