Blob


1 #!/usr/bin/env perl
2 #
3 # Copyright (c) 2024 Omar Polo <op@openbsd.org>
4 #
5 # Permission to use, copy, modify, and distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8 #
9 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 use v5.36;
18 use IPC::Open2;
19 use Getopt::Long qw(:config bundling);
21 my $auth;
22 my $port = 8000;
24 GetOptions("a:s" => \$auth, "p:i" => \$port)
25 or die("usage: $0 [-a auth] [-p port]\n");
27 my $pid = open2(my $out, my $in, 'nc', '-l', 'localhost', $port);
29 my $clen;
30 while (<$out>) {
31 local $/ = "\r\n";
32 chomp;
34 last if /^$/;
36 if (m/^POST/) {
37 die "bad http request" unless m,^POST / HTTP/1.1$,;
38 next;
39 }
41 if (m/^Host:/) {
42 die "bad Host header" unless /^Host: localhost:$port$/;
43 next;
44 }
46 if (m/^Content-Type/) {
47 die "bad content-type header"
48 unless m,Content-Type: application/json$,;
49 next;
50 }
52 if (m/^Content-Length/) {
53 die "double content-length" if defined $clen;
54 die "bad content-length header"
55 unless m/Content-Length: (\d+)$/;
56 $clen = $1;
57 next;
58 }
60 if (m/Connection/) {
61 die "bad connection header"
62 unless m/Connection: close$/;
63 next;
64 }
66 if (m/Authorization/) {
67 die "bad authorization header"
68 unless m/Authorization: basic (.*)$/;
69 my $t = $1;
70 die "wrong authorization; got $t want $auth"
71 if not defined($auth) or $auth ne $t;
72 next;
73 }
74 }
76 die "no Content-Length header" unless defined $clen;
78 while ($clen != 0) {
79 my $len = $clen;
80 $len = 512 if $clen > 512;
82 my $r = read($out, my $buf, $len);
83 $clen -= $r;
85 print $buf;
86 }
87 say "";
89 print $in "HTTP/1.1 200 OK\r\n";
90 print $in "Content-Length: 0\r\n";
91 print $in "Connection: close\r\n";
92 print $in "\r\n";
94 close $in;
95 close $out;
97 waitpid($pid, 0);
98 exit $? >> 8;