blib/lib/SPRAGL/Cgi_reply.pm untested

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