lib/SPRAGL/Cgi_reply.pm

filter: Statementstmt 78.0% 110 / 141 Branchbran 45.6% 21 / 46 Conditioncond 37.5% 3 / 8 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 86.3% 19 / 22 Podpod 100% 8 / 8 totaltotal 70.0% 161 / 230 CC 29 SCAR 19.5
CC
29
Cov
69%
cexit
16.5
signature
15.5
csystem
6.0
CRAP 7.0
« blib/lib/SPRAGL/Cgi_reply.pm ↑ Summary Build »
1 # SPRAGL::Cgi_reply.pm
2 # Simple HTTP replies.
3 # (c) 2022-2023 Bjørn Hee
4 # Licensed under the Apache License, version 2.0
5 # https://www.apache.org/licenses/LICENSE-2.0.txt
6  
7 package SPRAGL::Cgi_reply;
8  
9 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 8 ▶use experimental qw(signatures);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 8 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 8 our $VERSION = 1.21;
14  
15 8 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 8 ▶use File::Basename qw(basename);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 8 ▶use JSON qw(encode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 16 ▶my sub qwac( $s ) {grep{/./} map{split /\s+/} map{s/#.*//r} split/\v+/ , $s;};
Subroutine qwac: called CC=1 SCAR=0.0
20  
21 8 our @EXPORT = qwac '
22 fail # Send reply code and text.
23 redirect # Redirect to URL.
24 reply # Send reply and exit.
25 reply_file # Send file and exit.
26 reply_html # Send HTML reply and exit.
27 reply_json # Send JSON reply and exit.
28 csystem # CGI system command.
29 cexec # CGI exec command.
30 ';
31  
32 8 our @EXPORT_OK = qwac '
33 %status_code # Common status code messages.
34 ';
35  
36 # --------------------------------------------------------------------------- #
37 # Globals and defaults.
38  
39 8 our %status_code = (
40 200 => 'OK' ,
41 201 => 'Created' ,
42 202 => 'Accepted' ,
43 203 => 'Non-Authoritative Information' ,
44 204 => 'No Content' ,
45 205 => 'Reset Content' ,
46 206 => 'Partial Content' ,
47 207 => 'Multi-Status' , # WebDAV
48 208 => 'Already Reported' , # WebDAV
49 226 => 'IM Used' , # HTTP Delta Encoding
50 300 => 'Multiple Choices' ,
51 301 => 'Moved Permanently' ,
52 302 => 'Found' ,
53 303 => 'See Other' ,
54 304 => 'Not Modified' ,
55 305 => 'Use Proxy' ,
56 307 => 'Temporary Redirect' ,
57 308 => 'Permanent Redirect' ,
58 400 => 'Bad Request' ,
59 401 => 'Unauthorized' ,
60 402 => 'Payment Required' ,
61 403 => 'Forbidden' ,
62 404 => 'Not Found' ,
63 405 => 'Method Not Allowed' ,
64 406 => 'Not Acceptable' ,
65 407 => 'Proxy Authentication Required' ,
66 408 => 'Request Timeout' ,
67 409 => 'Conflict' ,
68 410 => 'Gone' ,
69 411 => 'Length Required' ,
70 412 => 'Precondition Failed' ,
71 413 => 'Payload Too Large' ,
72 414 => 'URI Too Long' ,
73 415 => 'Unsupported Media Type' ,
74 416 => 'Range Not Satisfiable' ,
75 417 => 'Expectation Failed' ,
76 418 => 'I\'m a teapot' ,
77 421 => 'Misdirected Request' ,
78 422 => 'Unprocessable Content' , # WebDAV
79 423 => 'Locked' , # WebDAV
80 424 => 'Failed Dependency' , # WebDAV
81 425 => 'Too Early' ,
82 426 => 'Upgrade Required' ,
83 428 => 'Precondition Required' ,
84 429 => 'Too Many Requests' ,
85 431 => 'Request Header Fields Too Large' ,
86 451 => 'Unavailable For Legal Reasons' ,
87 500 => 'Internal Server Error' ,
88 501 => 'Not Implemented' ,
89 502 => 'Bad Gateway' ,
90 503 => 'Service Unavailable' ,
91 504 => 'Gateway Timeout' ,
92 505 => 'HTTP Version Not Supported' ,
93 506 => 'Variant Also Negotiates' ,
94 507 => 'Insufficient Storage' , # WebDAV
95 508 => 'Loop Detected' , # WebDAV
96 510 => 'Not Extended' ,
97 511 => 'Network Authentication Required' ,
98 );
99  
100  
101 # Default headers.
102 8 my %header = (
103 'Content-Type' => 'text/plain; charset=utf-8' ,
104 Pragma => 'no-cache' ,
105 Status => '200 OK' ,
106 );
107  
108 # --------------------------------------------------------------------------- #
109 # Private methods.
110  
111 8 my $cr;
112 my $cx; # For holding a cexec command.
113  
114  
115 ▶my sub hnorm( $h ) {
Subroutine hnorm: called CC=1 SCAR=0.0
116 # Normalize header name. Uppercase the start letters, lowercase all the other.
117 # Remove illegal characters. Change underscores into dashes per convention.
118 1 return $h =~
119 s/[^\!-9\;-\~]//gr =~
120 y/a-z_/A-Z\-/r =~
121 1 s/([A-Z])([A-Z]+)/$1.lc($2)/ger;
122 };
123  
124  
125 8 ▶my sub timestring( $t = time ) { # $t in epoch seconds
Subroutine timestring: called CC=4 SCAR=14.1
126 # Returns for example 1970-01-01 00:00:00
127 8 ▶ return if not defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 0 8 8
128 8 ▶ return if $t !~ m/^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $t =~ /^\d+$/ 0 8 8
129 8 my @utcarray = (gmtime($t))[5,4,3,2,1,0];
130 8 $utcarray[0] += 1900;
131 8 $utcarray[1] += 1;
132 8 return sprintf( '%04u-%02u-%02u %02u:%02u:%02u UTC' , @utcarray );
133 };
134  
135  
136 ▶my sub print_headers() {
Subroutine print_headers: called CC=3 SCAR=11.7
137 8 ▶ $header{Date} //= timestring;
Condition33%1/3
$header{"Date"} //= timestring()
l!l&&r!l&&!r
080
MC/DC0%0/2
$header{"Date"} //= timestring()
$header{"Date"} timestring()
Truth table33%1/3
A //= B
A= $header{"Date"}B= timestring()
ABresult
1X1
011
000
138 8 for my $h (keys %header) {
139 36 print $h.': '.$header{$h}."\r\n";
140 };
141 8 print "\r\n";
142 };
143  
144  
145 ▶my sub cdie( $msg ) {
Subroutine cdie: called CC=1 SCAR=0.0
146 1 warn $msg;
147 1 fail(500);
148 };
149  
150  
151 ▶my sub cexit() {
Subroutine cexit: called CC=5 SCAR=28.1
152  
153 8 ▶ if ($cr != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cr != 1) { } 8 0 8
154 8 $cr = 1;
155 }
156 else {
157 # Hat tip to chrispitude on Stackoverflow
158 # https://stackoverflow.com/questions/3935269/how-can-i-run-a-long-background-process-from-a-perl-cgi-program
159  
160 # fork this process
161 0 my $pid = fork();
162 0 ▶ cdie 'SPRAGL::Cgi_reply::cexec failed: '.$!
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid 0 0 0
163 if not defined $pid;
164  
165 0 ▶ if ($pid == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid == 0) 0 0 0
166 # do this in the child
167 0 open STDIN , '<' , File::Spec->devnull();
168 0 open STDOUT , '>' , File::Spec->devnull();
169 0 open STDERR , '>' , File::Spec->devnull();
170 0 ▶ if ($^O eq 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq 'MSWin32') { } 0 0 0
171 0 qx[start /b ${cx}];
172 }
173 else {
174 0 qx[${cx} &];
175 };
176 0 exit;
177 };
178 };
179  
180 8 open STDERR , '>' , File::Spec->devnull();
181 8 die; # Using die as a catchable version of exit.
182 };
183  
184  
185 ▶my sub rcheck() {
Subroutine rcheck: called CC=4 SCAR=13.9
186 # Check redirection, and handle it if set.
187  
188 9 ▶ if (not exists $header{Location}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $header{"Location"}) 8 1 9
189 8 ▶ return if $header{Status} !~ m/^30[1278]\b/;
Branch: 1 branch
BranchTrueFalseTotal
unless $header{"Status"} =~ /^30[1278]\b/ 7 1 8
190 1 cdie 'Redirection URI missing.';
191 };
192 $header{Status} = '302 '.$status_code{302}
193 1 ▶ if $header{Status} !~ m/^30[1278]\s/;
Branch: 1 branch
BranchTrueFalseTotal
unless $header{"Status"} =~ /^30[1278]\s/ 0 1 1
194  
195 1 $header{'Content-Type'} = 'text/html; charset=utf-8';
196 1 print_headers;
197 print
198 '<html><head></head><body>'.
199 '<a href="'.$header{Location}.'">'.
200 $header{Location}.
201 1 '</a>'.
202 '</body></html>';
203 1 cexit;
204 };
205  
206  
207 ▶my sub signature( $mp , $op , @par ) {
Subroutine signature: called CC=11 SCAR=27.4
208 # Tailor-made signature-like parameter slurping.
209  
210 # Handle object parameter if there is one.
211 9 ▶ if (defined $cr) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cr) 0 9 9
212 0 ▶ cdie 'Multiple calls of cexec.' if $cr == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $cr == 1 0 0 0
213 0 ▶ cdie 'Error in cexec.' if $par[0] ne $cr;
Branch: 1 branch
BranchTrueFalseTotal
if $par[0] ne $cr 0 0 0
214 0 shift @par;
215 0 $cr = 1;
216 };
217  
218 # Take the mandatory parameters to the side.
219 9 ▶ cdie 'Too few arguments for subroutine.'
Branch: 1 branch
BranchTrueFalseTotal
if scalar @par < $mp 0 9 9
220 if scalar @par < $mp;
221 9 my @ret = splice @par , 0 , $mp;
222  
223 # Take the optional parameter, if it is given.
224 9 ▶ if ($op == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op == 1) 4 5 9
225 4 ▶ if ((scalar @par) % 2 == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar(@par) % 2 == 1) { } 0 4 4
226 0 push @ret , shift @par;
227 }
228 else {
229 4 push @ret , undef;
230 };
231 };
232  
233 # Update the header hash with any named parameters left.
234 9 ▶ cdie 'Error in optional named parameters.'
Branch: 1 branch
BranchTrueFalseTotal
if scalar(@par) % 2 == 1 0 9 9
235 if (scalar @par) % 2 == 1;
236 9 ▶ while (@par) {
Branch: 1 branch
BranchTrueFalseTotal
if (@par) 2 9 11
237 2 my $key = shift @par;
238 2 my $val = shift @par;
239 2 $val =~ s/\v+$//;
240 2 ▶ cdie 'Header value contains newline.' if $val =~ m/\n/;
Branch: 1 branch
BranchTrueFalseTotal
if $val =~ /\n/ 0 2 2
241 2 ▶ if ($key =~ m/^redirect$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key =~ /^redirect$/i) { } 1 1 2
242 1 $header{Status} = '302 '.$status_code{302};
243 1 $header{Location} = $val;
244 }
245 else {
246 1 $header{hnorm($key)} = $val;
247 };
248 };
249  
250 9 return @ret;
251  
252 }; # sub signature
253  
254 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
255  
256 8 1;
257  
258 # --------------------------------------------------------------------------- #
259 # Exportable methods.
260  
261 sub fail {
262 # Send status code and text. Also works with "200 OK". Also works with
263 # redirects, for which the second parameter must be the URI redirected to.
264  
265 4 ▶ my ($code,$text) = signature(1,1,@_);
Subroutine fail: called CC=3 SCAR=11.2
Pod documented
266 cdie 'Unknown return code "'.$code.'".'
267 4 ▶ if not exists $status_code{$code};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $SPRAGL::Cgi_reply::status_code{$code} 0 4 4
268 4 $header{Status} = $code.' '.$status_code{$code};
269 4 rcheck;
270 2 print_headers;
271 2 ▶ print $text // $code.' '.$status_code{$code};
Condition50%1/2
$text // $code . ' ' . $SPRAGL::Cgi_reply::status_code{$code}
l!l
02
MC/DC0%0/1
$text // $code . ' ' . $SPRAGL::Cgi_reply::status_code{$code}
$text
Truth table50%1/2
A
A= $text
Aresult
11
00
272 2 cexit;
273 };
274  
275  
276 sub redirect {
277 # Redirect to the given URI.
278 0 ▶ my ($uri) = signature(1,0,@_);
Subroutine redirect: not called CC=1 SCAR=6.9
Pod documented
279 0 $header{Status} = '302 '.$status_code{302};
280 0 $header{Location} = $uri;
281 0 rcheck;
282 };
283  
284  
285 sub reply {
286 2 ▶ my ($text) = signature(1,0,@_);
Subroutine reply: called CC=1 SCAR=0.0
Pod documented
287 2 rcheck;
288 2 print_headers;
289 2 print $text;
290 2 cexit;
291 };
292  
293  
294 sub reply_file {
295 1 ▶ my ($filename) = signature(1,0,@_);
Subroutine reply_file: called CC=3 SCAR=11.1
Pod documented
296 1 ▶ fail 404 if not -f $filename;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $filename 0 1 1
297 1 $header{'Content-Type'} = 'application/octet-stream';
298 1 $header{'Content-Length'} = -s $filename;
299 1 $header{'Content-Disposition'} = 'attachment; filename="'.basename($filename).'"';
300 1 rcheck;
301 1 print_headers;
302 1 ▶ open my $fh , '<' , $filename || fail 500;
Condition33%1/3
$filename || fail(500)
l!l&&r!l&&!r
100
MC/DC0%0/2
$filename || fail(500)
$filename fail(500)
Truth table33%1/3
A || B
A= $filenameB= fail(500)
ABresult
1X1
011
000
303 { # localizing lineseparator change
304 1 local $/ = undef;
305 1 print <$fh>;
306 };
307 1 close $fh;
308 1 cexit;
309 };
310  
311  
312 sub reply_html {
313 1 ▶ my ($doc) = signature(1,0,@_);
Subroutine reply_html: called CC=1 SCAR=0.0
Pod documented
314 1 $header{'Content-Type'} = 'text/html; charset=utf-8';
315 1 rcheck;
316 1 print_headers;
317 1 print $doc;
318 1 cexit;
319 };
320  
321  
322 sub reply_json {
323 1 ▶ my ($hashref) = signature(1,0,@_);
Subroutine reply_json: called CC=1 SCAR=0.0
Pod documented
324 1 $header{'Content-Type'} = 'application/json; charset=utf-8';
325 1 rcheck;
326 1 print_headers;
327 1 print encode_json($hashref);
328 1 cexit;
329 };
330  
331  
332 ▶sub csystem( $c ) {
Subroutine csystem: not called CC=2 SCAR=17.9
Pod documented
333 0 my $out;
334 0 ▶ if ($^O eq 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq 'MSWin32') { } 0 0 0
335 0 $out = qx[start /b ${c}];
336 }
337 else {
338 0 $out = qx[${c} 2>/dev/null];
339 };
340 0 return $out;
341 };
342  
343  
344 ▶sub cexec( $c ) {
Subroutine cexec: not called CC=2 SCAR=17.9
Pod documented
345 0 ▶ cdie 'Undefined command given to cexec.' if not defined $c;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $c 0 0 0
346 0 $cx = $c;
347 0 my $sr;
348 0 $sr->$* = undef;
349 0 $cr = $sr;
350 0 bless $sr , 'SPRAGL::Cgi_reply';
351 0 return $sr;
352 };
353  
354 # --------------------------------------------------------------------------- #
355  
356 =pod
357  
358 =encoding utf8
359  
360 =head1 NAME
361  
362 SPRAGL::Cgi_reply - Simple HTTP replies.
363  
364 =head1 VERSION
365  
366 1.21
367  
368 =head1 SYNOPSIS
369  
370 use SPRAGL::Cgi_reply;
371  
372 my %df = map {(/^(\S+).+\s(\d+)\%/)} grep {/\d\%/} qx[ df ];
373 reply_json \%df;
374  
375 =head1 DESCRIPTION
376  
377 Simple module for sending simple HTTP replies. Geared towards CGI scripts.
378  
379 CGI is simple and quick to code for, even though it is not so performant or fashionable. It nevertheless is handy when making quick and dirty web services that are not going to see a lot of load. HTTP Routing is handled by the file system. Adding or removing functionality is easy and orthogonal, like playing with Lego bricks.
380  
381 The reply methods in SPRAGL::Cgi_reply will exit when they have been called. The exit is based on "die". So it is catchable, END blocks will execute, et cetera.
382  
383 =head1 FUNCTIONS AND VARIABLES
384  
385 Loaded by default:
386 L<fail|/fail( $c )>,
387 L<redirect|/redirect( $u )>,
388 L<reply|/reply( $s )>,
389 L<reply_file|/reply_file( $fn )>,
390 L<reply_html|/reply_html( $d )>,
391 L<reply_json|/reply_json( $hr )>,
392 L<csystem|/csystem( $c )>,
393 L<cexec|/cexec ...>
394  
395 Loaded on demand:
396 L<%status_code|/%status_code>
397  
398 =over
399  
400 =item fail( $c )
401  
402 Replies with the given return code plus the standard return message attached to that, and then exits. Can be given a second parameter, a string, to replace the standard return message with. As in:
403  
404 fail 404 , 'Lost in Space.'; # Instead of just fail 404;
405  
406 =item redirect( $u )
407  
408 Replies with a 302 redirect to the given URI, and then exits.
409  
410 =item reply( $s )
411  
412 Replies with the given string as plain/text, and then exits.
413  
414 =item reply_file( $fn )
415  
416 Replies with the file content pointed to by the given filename, and then exits.
417  
418 =item reply_html( $d )
419  
420 Replies with the given string as HTML, and then exits.
421  
422 =item reply_json( $hr )
423  
424 Replies with the given hashref transformed into JSON, and then exits.
425  
426 =item csystem( $c )
427  
428 CGI system. Runs the given command and returns the output. Your script will wait for it to complete.
429  
430 =item cexec ...
431  
432 CGI exec. Executes a system command, and sends a reply of your choice, in one go. Works like exec ought to in a CGI context. Calling it looks like this:
433  
434 cexec('mysqldump orders > orders_backup.sql')->reply('Database backup started.');
435  
436 Or like this:
437  
438 cexec('sudo postfix stop && postfix start')->redirect('status.html');
439  
440 You must naturally be very careful about what system commands it is possible to run from your webserver.
441  
442 =item %status_code
443  
444 A hash that maps return codes to standard return messages.
445  
446 Only loaded on demand.
447  
448 =back
449  
450 =head2 OPTIONAL NAMED PARAMETERS
451  
452 Optional named parameters can be given in the reply calls. If the name is "redirect" the reply will be like calling the redirect method. If the name is anything else, a header with that name and value will be inserted in the reply. The header will be normalized, by capitalizing words and changing underscores to dashes. The header value will be inserted raw. Be sure to adhere to RFC 8187.
453  
454 Examples:
455  
456 reply $x.' seconds to go!' , refresh => 5; # Inserts a "Refresh: 5" header.
457  
458 fail 503 , 'We are down at the moment, please try again later' , 'Retry-After' => $t;
459  
460 fail 308 , redirect => 'https://perlmaven.com/'; # Redirecting with another code than 302.
461  
462 =head1 DEPENDENCIES
463  
464 File::Basename
465  
466 File::Spec
467  
468 JSON
469  
470 =head1 KNOWN ISSUES
471  
472 No known issues.
473  
474 =head1 TODO
475  
476 =head1 SEE ALSO
477  
478 L<SPRAGL::Cgi_read|https://metacpan.org/pod/SPRAGL::Cgi_read>
479  
480 L<CGI|https://metacpan.org/pod/CGI>
481  
482 =head1 LICENSE & COPYRIGHT
483  
484 (c) 2022-2023 Bjørn Hee
485  
486 Licensed under the Apache License, version 2.0
487  
488 https://www.apache.org/licenses/LICENSE-2.0.txt
489  
490 =cut
491  
492 __END__
« blib/lib/SPRAGL/Cgi_reply.pm ↑ Summary Build »