]> git.proxmox.com Git - pmg-api.git/blob - test-server.pl
add basic server infrastructure
[pmg-api.git] / test-server.pl
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5 use lib '.';
6
7 use Socket qw(IPPROTO_TCP TCP_NODELAY SOMAXCONN);
8 use IO::Socket::IP;
9 use HTTP::Headers;
10 use HTTP::Response;
11 use Data::Dumper;
12
13 use PVE::Tools qw(run_command);
14 use PVE::INotify;
15 use PVE::APIServer::Formatter::Standard;
16 use PVE::APIServer::Formatter::HTML;
17
18 use PMG::HTTPServer;
19
20 my $nodename = PVE::INotify::nodename();
21 my $port = 9999;
22
23 my $cert_file = "pmg-api.pem";
24
25 if (! -f $cert_file) {
26 print "generating demo server certificate\n";
27 my $cmd = ['openssl', 'req', '-batch', '-x509', '-newkey', 'rsa:4096',
28 '-nodes', '-keyout', $cert_file, '-out', $cert_file,
29 '-subj', "/CN=$nodename/",
30 '-days', '3650'];
31 run_command($cmd);
32 }
33
34 my $socket = IO::Socket::IP->new(
35 LocalAddr => $nodename,
36 LocalPort => $port,
37 Listen => SOMAXCONN,
38 Proto => 'tcp',
39 GetAddrInfoFlags => 0,
40 ReuseAddr => 1) ||
41 die "unable to create socket - $@\n";
42
43 # we often observe delays when using Nagle algorithm,
44 # so we disable that to maximize performance
45 setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1);
46
47 my $accept_lock_fn = "simple-demo.lck";
48 my $lockfh = IO::File->new(">>${accept_lock_fn}") ||
49 die "unable to open lock file '${accept_lock_fn}' - $!\n";
50
51 my $server = PMG::HTTPServer->new(
52 debug => 1,
53 socket => $socket,
54 lockfile => $accept_lock_fn,
55 lockfh => $lockfh,
56 title => 'Proxmox Mail Gateway API',
57 cookie_name => 'PMG',
58 logfh => \*STDOUT,
59 tls_ctx => { verify => 0, cert_file => $cert_file },
60 pages => {
61 '/' => sub { get_index($nodename, @_) },
62 },
63 );
64
65 # NOTE: Requests to non-API pages are not authenticated
66 # so you must be very careful here
67
68 my $root_page = <<__EOD__;
69 <!DOCTYPE html>
70 <html>
71 <head>
72 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
73 <meta http-equiv="X-UA-Compatible" content="IE=edge">
74 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
75 <title>Simple Demo Server</title>
76 </head>
77 <body>
78 <h1>Proxmox Mail Gateway API ($nodename)</h1>
79
80 You can browse the API <a href='/api2/html' >here</a>. Please sign
81 in with usrename <b>demo</b> and passwort <b>demo</b>.
82
83 </body>
84 </html>
85 __EOD__
86
87 sub get_index {
88 my ($nodename, $server, $r, $args) = @_;
89
90 my $headers = HTTP::Headers->new(Content_Type => "text/html; charset=utf-8");
91 my $resp = HTTP::Response->new(200, "OK", $headers, $root_page);
92
93 }
94
95 print "demo server listens at: https://$nodename:$port/\n";
96
97 $server->run();