chiark / gitweb /
http[s] tests: More-or-less functional ftpmaster http server
[dgit.git] / tests / ftpmasterapi-static-server
1 #!/usr/bin/perl -w
2 #
3 # This file is part of the dgit test suite.
4 #
5 # Copyright (C)2004-2015 Best Practical Solutions, LLC
6 # Copyright (C)2019      Ian Jackson
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 #
19 # invocation protocol:
20 #
21 #   ftpmasterapi-static-server >port-file tests/tmp/$thing/aq
22 #
23 # Will write the allocated port number to port-file.
24 # Then we fork and the parent exits 0.
25 # If port-file is unlinked, we exit.
26
27 use strict;
28 use IO::Handle;
29
30 our ($webroot) = @ARGV;
31 our $port = '';
32
33 sub stat_type_check () {
34     die "[$port, $webroot] stdout not ta plain file"
35         unless -f _;
36 }
37
38 stat STDOUT or die $!;
39 stat_type_check();
40
41 sub start_polling_fstat () {
42     $SIG{ALRM} = sub {
43         stat STDOUT or die $!;
44         my $nlink = (stat _)[3];
45         exit 0 unless $nlink;
46         stat_type_check(); # doesn't seem possible to fail but check anyway
47         alarm(1);
48     };
49     alarm(1);
50 }
51
52 package ServerClass;
53
54 use strict;
55 use Socket qw(AF_INET SOCK_STREAM);
56 use Socket qw(AF_INET SOCK_STREAM unpack_sockaddr_in);
57 use IO::Handle;
58
59 use base qw(HTTP::Server::Simple::CGI);
60 use HTTP::Server::Simple::Static;
61
62 sub handle_request {
63     my ($self, $cgi) = @_;
64
65     if (!$self->serve_static($cgi, $::webroot)) {
66         print "HTTP/1.0 404 Not found\r\n";
67         print $cgi->header,
68             $cgi->start_html('Not found'),
69             $cgi->h1('Not found'),
70             $cgi->end_html;
71     }
72 }
73
74 sub port () { return 0; }
75
76 sub after_setup_listener () {
77     my $sn = getsockname HTTP::Server::Simple::HTTPDaemon or die $!;
78     ($main::port,) = unpack_sockaddr_in $sn;
79     print main::STDOUT $port, "\n" or die $!;
80     flush main::STDOUT or die $!;
81     my $c = fork // die $!;
82     exit 0 if $c;
83     ::main::start_polling_fstat();
84 }
85
86 package main;
87
88 our $server = ServerClass->new();
89 $server->run();