lib/SPRAGL/Cgi_reply.pm

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