blib/lib/SPRAGL/Cgi_reply.pm untested

filter: Statementstmt 0.0% 0 / 142 Branchbran 0.0% 0 / 44 Conditioncond 0.0% 0 / 9 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 233 CC 23 SCAR 34.9
CC
23
Cov
0%
signature
110.0
cexit
30.0
rcheck
20.0
CRAP 32.8
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 use strict;
10 use experimental qw(signatures);
11 use Exporter qw(import);
12  
13 our $VERSION = 1.21;
14  
15 use File::Spec ();
16 use File::Basename qw(basename);
17 use JSON qw(encode_json);
18  
19 my sub qwac( $s ) {grep{/./} map{split /\s+/} map{s/#.*//r} split/\v+/ , $s;};
20  
21 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 our @EXPORT_OK = qwac '
33 %status_code # Common status code messages.
34 ';
35  
36 # --------------------------------------------------------------------------- #
37 # Globals and defaults.
38  
39 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 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 my $cr;
112 my $cx; # For holding a cexec command.
113  
114  
115 my sub hnorm( $h ) {
116 # Normalize header name. Uppercase the start letters, lowercase all the other.
117 # Remove illegal characters. Change underscores into dashes per convention.
118 return $h =~
119 s/[^\!-9\;-\~]//gr =~
120 y/a-z_/A-Z\-/r =~
121 s/([A-Z])([A-Z]+)/$1.lc($2)/ger;
122 };
123  
124  
125 my sub timestring( $t = time ) { # $t in epoch seconds
126 # Returns for example 1970-01-01 00:00:00
127 return if not defined $t;
128 return if $t !~ m/^\d+$/;
129 my @utcarray = (gmtime($t))[5,4,3,2,1,0];
130 $utcarray[0] += 1900;
131 $utcarray[1] += 1;
132 return sprintf( '%04u-%02u-%02u %02u:%02u:%02u UTC' , @utcarray );
133 };
134  
135  
136 my sub print_headers() {
137 $header{Date} //= timestring;
138 for my $h (keys %header) {
139 print $h.': '.$header{$h}."\r\n";
140 };
141 print "\r\n";
142 };
143  
144  
145 my sub cdie( $msg ) {
146 warn $msg;
147 fail(500);
148 };
149  
150  
151 my sub cexit() {
152  
153 if ($cr != 1) {
154 $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 my $pid = fork();
162 cdie 'SPRAGL::Cgi_reply::cexec failed: '.$!
163 if not defined $pid;
164  
165 if ($pid == 0) {
166 # do this in the child
167 open STDIN , '<' , File::Spec->devnull();
168 open STDOUT , '>' , File::Spec->devnull();
169 open STDERR , '>' , File::Spec->devnull();
170 if ($^O eq 'MSWin32') {
171 qx[start /b ${cx}];
172 }
173 else {
174 qx[${cx} &];
175 };
176 exit;
177 };
178 };
179  
180 open STDERR , '>' , File::Spec->devnull();
181 die; # Using die as a catchable version of exit.
182 };
183  
184  
185 my sub rcheck() {
186 # Check redirection, and handle it if set.
187  
188 if (not exists $header{Location}) {
189 return if $header{Status} !~ m/^30[1278]\b/;
190 cdie 'Redirection URI missing.';
191 };
192 $header{Status} = '302 '.$status_code{302}
193 if $header{Status} !~ m/^30[1278]\s/;
194  
195 $header{'Content-Type'} = 'text/html; charset=utf-8';
196 print_headers;
197 print
198 '<html><head></head><body>'.
199 '<a href="'.$header{Location}.'">'.
200 $header{Location}.
201 '</a>'.
202 '</body></html>';
203 cexit;
204 };
205  
206  
207 my sub signature( $mp , $op , @par ) {
208 # Tailor-made signature-like parameter slurping.
209  
210 # Handle object parameter if there is one.
211 if (defined $cr) {
212 cdie 'Multiple calls of cexec.' if $cr == 1;
213 cdie 'Error in cexec.' if $par[0] ne $cr;
214 shift @par;
215 $cr = 1;
216 };
217  
218 # Take the mandatory parameters to the side.
219 cdie 'Too few arguments for subroutine.'
220 if scalar @par < $mp;
221 my @ret = splice @par , 0 , $mp;
222  
223 # Take the optional parameter, if it is given.
224 if ($op == 1) {
225 if ((scalar @par) % 2 == 1) {
226 push @ret , shift @par;
227 }
228 else {
229 push @ret , undef;
230 };
231 };
232  
233 # Update the header hash with any named parameters left.
234 cdie 'Error in optional named parameters.'
235 if (scalar @par) % 2 == 1;
236 while (@par) {
237 my $key = shift @par;
238 my $val = shift @par;
239 $val =~ s/\v+$//;
240 cdie 'Header value contains newline.' if $val =~ m/\n/;
241 if ($key =~ m/^redirect$/i) {
242 $header{Status} = '302 '.$status_code{302};
243 $header{Location} = $val;
244 }
245 else {
246 $header{hnorm($key)} = $val;
247 };
248 };
249  
250 return @ret;
251  
252 }; # sub signature
253  
254 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
255  
256 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 my ($code,$text) = signature(1,1,@_);
266 cdie 'Unknown return code "'.$code.'".'
267 if not exists $status_code{$code};
268 $header{Status} = $code.' '.$status_code{$code};
269 rcheck;
270 print_headers;
271 print $text // $code.' '.$status_code{$code};
272 cexit;
273 };
274  
275  
276 sub redirect {
277 # Redirect to the given URI.
278 my ($uri) = signature(1,0,@_);
279 $header{Status} = '302 '.$status_code{302};
280 $header{Location} = $uri;
281 rcheck;
282 };
283  
284  
285 sub reply {
286 my ($text) = signature(1,0,@_);
287 rcheck;
288 print_headers;
289 print $text;
290 cexit;
291 };
292  
293  
294 sub reply_file {
295 my ($filename) = signature(1,0,@_);
296 fail 404 if not -f $filename;
297 $header{'Content-Type'} = 'application/octet-stream';
298 $header{'Content-Length'} = -s $filename;
299 $header{'Content-Disposition'} = 'attachment; filename="'.basename($filename).'"';
300 rcheck;
301 print_headers;
302 open my $fh , '<' , $filename || fail 500;
303 { # localizing lineseparator change
304 local $/ = undef;
305 print <$fh>;
306 };
307 close $fh;
308 cexit;
309 };
310  
311  
312 sub reply_html {
313 my ($doc) = signature(1,0,@_);
314 $header{'Content-Type'} = 'text/html; charset=utf-8';
315 rcheck;
316 print_headers;
317 print $doc;
318 cexit;
319 };
320  
321  
322 sub reply_json {
323 my ($hashref) = signature(1,0,@_);
324 $header{'Content-Type'} = 'application/json; charset=utf-8';
325 rcheck;
326 print_headers;
327 print encode_json($hashref);
328 cexit;
329 };
330  
331  
332 sub csystem( $c ) {
333 my $out;
334 if ($^O eq 'MSWin32') {
335 $out = qx[start /b ${c}];
336 }
337 else {
338 $out = qx[${c} 2>/dev/null];
339 };
340 return $out;
341 };
342  
343  
344 sub cexec( $c ) {
345 cdie 'Undefined command given to cexec.' if not defined $c;
346 $cx = $c;
347 my $sr;
348 $sr->$* = undef;
349 $cr = $sr;
350 bless $sr , 'SPRAGL::Cgi_reply';
351 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__