Crop/Server.pm untested

filter: Statementstmt 0.0% 0 / 236 Branchbran 0.0% 0 / 58 Conditioncond 0.0% 0 / 40 MC/DCmcdc 0.0% 0 / 24 Subroutinesub 0.0% 0 / 42 Podpod 0.0% 0 / 22 totaltotal 0.0% 0 / 422 CC 30 SCAR 34.5
CC
30
Cov
0%
_init
132.0
_is_json_correct
42.0
_work
42.0
CRAP 31.6
1 package Crop::Server;
2  
3 =pod
4  
5 =head1 NAME
6  
7 Crop::Server - Server utilities for the Crop framework
8  
9 =head1 SYNOPSIS
10  
11 use Crop::Server;
12 # ...usage...
13  
14 =head1 DESCRIPTION
15  
16 Crop::Server provides server-related utilities for the Crop framework.
17  
18 =head1 AUTHORS
19  
20 Euvgenio (Core Developer)
21  
22 Alex (Contributor)
23  
24 =head1 COPYRIGHT AND LICENSE
25  
26 Apache 2.0
27  
28 =cut
29  
30 use base qw/ Crop::Object Exporter /;
31  
32 =begin nd
33 Class: Crop::Server
34 Protocol-independent a server logic.
35
36 Server process client request in the infinite loop.
37
38 Create the Server exemplar, register handlers, define workqueue in the router, then listen.
39  
40 Router example:
41  
42 (start code)
43 ...
44 $Server->router(sub {
45 my $S = shift;
46 my $I = $S->I;
47 return ['ADD'] if exists $I->{name};
48 'LIST';
49 });
50 (end code)
51 =cut
52  
53 use v5.14;
54 use warnings;
55 no warnings 'experimental';
56  
57 use Encode qw/ decode /;
58 use XML::LibXSLT;
59 use XML::LibXML;
60 use XML::Simple;
61 use JSON;
62 use CGI::Cookie;
63  
64 use FindBin qw/ $RealBin /;
65  
66 use Crop::Debug;
67 use Crop::Error qw/ all_right warn /;
68 use Crop::Server::Constants;
69 use Crop::Server::Handler;
70 use Crop::HTTP::Session;
71 use Crop::DateTime;
72 use Crop::Client;
73 use Crop::Rights;
74  
75 =begin nd
76 Constant: HOMEPAGE
77 Homepage of the web-site is always '/'
78 =cut
79 use constant {
80 HOMEPAGE => '/',
81 };
82  
83 =begin nd
84 Variable: our @EXPORT
85 Export by default:
86
87 OK - handler return status
88 =cut
89 our @EXPORT = qw/ OK PAGELESS /;
90  
91 =begin nd
92 Variable: our %Attributes
93 Attributes:
94  
95 auth - if true an autentication is required; since true by default, you should redefine the <authenticate ( )> method
96 client - client ID
97 content - body of the response
98 cwd - current working directory
99 data - persistent data across all the handlers of an client request
100 json - JSON exemplar
101 handler - hash of registered handlers
102 headers - HTTP headers for response
103 iflow - Input flow of data (see <I ( )>)
104 oflow - Output flow of data (see <O ( )>)
105 special item named {ERROR} contains hashref of all the errors ocquired (see <Crop::Error>)
106 output_t - type of output ('XML', 'XSLT', 'JSON', and so on)
107 page - filename of output template in cwd
108 redirect - URL to redirect
109 request - client request object, <Crop::HTTP::Request> exemplar; will be Saved manually, so stable=>1
110 rights - rights granted to the client, exemplar of <Crop::Rights>
111 router - method establishes a chain of handlers calls; the reuslt of method is array of handler names
112 sendfile - exemplar of <Crop::File::Send> allowes to download file <Crop::File> from inner url (for Nginx)
113 session - exemplar of <Crop::HTTP::Session>
114 tik - start time of request as <Crop::DateTime> object; server sets a corresponding tok at done time
115 user - user object
116 workqueue - array of handlers names establishes executing order
117 xslt - hash of parsed XSLT templates
118
119 The 'stable' attribute means 'do not cleanup after request has done'.
120 =cut
121 our %Attributes = (
122 auth => {default => 1, stable => 1},
123 client => {mode => 'read'},
124 content => undef,
125 cwd => {stable => 1},
126 data => undef,
127 json => {stable => 1},
128 handler => {stable => 1},
129 headers => undef,
130 iflow => undef,
131 oflow => {mode => 'read'},
132 output_t => {default => 'XSLT', stable => 1},
133 page => undef,
134 redirect => undef,
135 request => {mode => 'read', stable => 1},
136 rights => {mode => 'read'},
137 router => {mode => 'write', stable => 1}, # the same all the time, altough result changes
138 sendfile => {mode => 'read/write'},
139 session => {mode => 'read', stable => 1}, # temporary hack!!! needed by $S->session->restore_param in a script
140 tik => {mode => 'read'},
141 user => undef,
142 workqueue => undef,
143 xslt => {stable => 1},
144 );
145  
146 =begin nd
147 Variable: our $Server
148 Singlton.
149
150 <Crop> 'uses' this class, so Server object must be available from outer classes by accessing directly
151 without use of methods of this class.
152
153 Getter is <instance ( )>.
154 =cut
155 our $Server;
156  
157 =begin nd
158 Variable: my $Interrupted
159 Signal to interrupt the Server has received.
160  
161 Variable: my $AtWork
162 Server at work should not be killed.
163 =cut
164 my ($Interrupted, $AtWork);
165  
166 # Try the Server to be terminated correctly as possible
167 $SIG{TERM} = $SIG{INT} = \&interrupt;
168  
169 =begin nd
170 Constructor: new ( )
171 =cut
172 sub new {
173 my $class = shift;
174
175 $Server = $class->SUPER::new(
176 cwd => $RealBin,
177 @_,
178 );
179
180 $Server->{json} = JSON->new->allow_nonref->allow_blessed->convert_blessed if $Server->{output_t} eq 'JSON';
181 # $Server->{json}->pretty->canonical if $Server->{json} and Crop::C->{environmentType} ne 'production';
182  
183 $Server;
184 }
185  
186 =begin nd
187 Method: add_handler ($name, $handler)
188 Add new request handler for the Server main loop.
189
190 Order of calls does not matter.
191
192 Parses XSLT template for future use.
193  
194 (start code)
195 $Server->add_handler(ADD => {
196 page => 'mypage', # mypage.xsl template in use; the 'index.xsl' by default; use the 'PAGELESS' constant unless output exists
197 input => {
198 allow => [qw/ id name description /],
199 },
200 call => sub {
201 my $S = shift;
202 my $I = $S->I;
203 my $O = $S->O;
204  
205 $O->{result} = 25;
206  
207 OK;
208 },
209 });
210 (finish code)
211
212 Parameters:
213 $name - handler name
214 $handler - subref
215 =cut
216 sub add_handler {
217 my ($self, $name, $handler) = @_;
218  
219 return warn "SERVER|CRIT: Redefining of handler $name is prohibited" if exists $self->{handler}{$name};
220  
221 my $Handler = Crop::Server::Handler->new($handler, name => $name) or return warn "HANDLER|CRIT: Can't initiate handler $name";
222  
223 $self->{handler}{$name} = $Handler;
224 my $page = $Handler->page || DEFAULT_TPL;
225  
226 unless ($page eq PAGELESS) {
227 if ($self->{output_t} eq 'XSLT' or $self->{output_t} eq 'XML') {
228 eval {
229 $self->{xslt}{$page} = XML::LibXSLT->new->parse_stylesheet_file("$self->{cwd}/$page" . XSLT_SUFFIX);
230 };
231 warn "SERVER|CRIT: $@$!" if $@;
232 }
233 }
234 }
235  
236 =begin nd
237 Method: _authenticate ( )
238 Perform client autentication.
239
240 By default returns false, meanning 'the autentication failed'. The 'AUTH' error will arised.
241
242 Subclass must redefine this method if any logic is required.
243  
244 Returns:
245 true - autentication is successful
246 flase - if autentication failed
247 =cut
248 sub _authenticate { undef }
249  
250 =begin nd
251 Method: _cleanup ( )
252 Finalyze the current client request.
253
254 Cleans all attributes for security reason, so next request will not see stale values.
255  
256 Kill the server if it has been marked as 'interrupted'.
257 =cut
258 sub _cleanup {
259 my $self = shift;
260  
261 # reset request-specific data to defaults
262 $self->Erase;
263  
264 $self->{session}->Save;
265
266 $self->{request}->tok(Crop::DateTime->new->timestamp);
267 $self->{request}->Save;
268  
269 $Interrupted ? die("SERVER|NOTICE: Server stopped") : undef $AtWork;
270 }
271  
272 =begin nd
273 Method: D ( )
274 Getter for the 'data' attribute.
275  
276 Returns:
277 $self->{data}
278 =cut
279 sub D { shift->{data} }
280  
281 =begin nd
282 Method: fail ($err)
283 Stop a request if the current handler fails.
284
285 Interrupts the working chain and arise the $error.
286  
287 Redirect is produced to referer page unless defined html template.
288  
289 Parameters:
290 $err - error message
291 =cut
292 sub fail {
293 my ($self, $err) = @_;
294  
295 warn $err;
296  
297 # debug 'CROPSERVER_FAIL_PAGE=', $self->{handler}->page;
298 # if ($self->{handler}->page eq 'PAGELESS') {
299 # debug 'CROPSERVER_FAIL_PAGELESS';
300 # $self->redirect('/');
301 # $self->redirect($self->{request}->referer);
302 # }
303  
304 FAIL;
305 }
306  
307 =begin nd
308 Method: _flush ( )
309 Flush response to the client.
310
311 Pure virtual method; should be redefined by subclass.
312 =cut
313 sub _flush {
314 warn 'SERVER|CRIT: Crop::Server->_flush() must be redefined by subclass';
315 }
316  
317 =begin nd
318 Method: I ( )
319 The getter of input flow (see the 'iflow' attribute).
320  
321 Returns:
322 hashref of input data
323 =cut
324 sub I { shift->{iflow} }
325  
326 =begin nd
327 Method: _init ( )
328 Initiate request handler loop.
329
330 Each iteration process one certain HTTP request:
331
332 - remember a start time
333 - setup flag 'at work' to prevent destructive cancelation
334 - cleanup error stack
335 - init HTTP request object and session object
336 - cleanup data flows
337 - parse incomming CGI parameters
338 - exec autentication procedure
339 - define workqueue by runing router
340 - setup current output page
341
342 Returns:
343 nothing, but errors will established when process goes wrong
344 =cut
345 sub _init {
346 my $self = shift;
347  
348 # remember start time as soon as posible
349 $self->{tik} = Crop::DateTime->new;
350
351 # it is not a good idea to kill the Server at work
352 $AtWork = 1;
353  
354 # init Error module
355 Crop::Error->erase;
356
357 $self->{rights} = Crop::Rights->new;
358 $self->{rights}->add_role('admin');
359  
360 # set HTTP session and request
361 $self->_init_httprequest;
362  
363 my $session;
364 if (defined $self->{request}->cookie_in) {
365 $session = Crop::HTTP::Session->Get(cookie => $self->{request}->cookie_in);
366 $session //= Crop::HTTP::Session->Get(cookie2 => $self->{request}->cookie_in);
367
368 if ($session) {
369 $session->generate_cookie;
370 $session->mtime($self->{request}->tik);
371 }
372 }
373 unless ($session) {
374 $session = Crop::HTTP::Session->new(
375 ctime => $self->{request}->tik,
376 mtime => $self->{request}->tik,
377 );
378 $session->generate_cookie;
379 $session->Genkey;
380 }
381 $self->{session} = $session;
382
383 unless ($self->{session}->id_client) {
384 my $client = Crop::Client->new->Save;
385
386 $self->{session}->id_client($client->id);
387 }
388
389 $self->{request}->id_session($session->id);
390 $self->{request}->cookie_out($session->cookie);
391  
392 # parse the input flow before the dispatcher starts their work since it operate on input parameters
393 $self->{iflow} = {};
394 $self->{oflow} = {};
395
396 # init data persistent across all the handlers in request
397 $self->{data} = {};
398  
399 # parse input params
400 $self->_parse_input;
401 my $json;
402 if (defined $self->{request}->content_t and $self->{request}->content_t eq 'application/json') {
403 $json = $self->{iflow}{POSTDATA};
404 } elsif (exists $self->{iflow}{json} and keys %{$self->{iflow}} == 1) {
405 $json = $self->{iflow}{json};
406 }
407 $self->_parse_json($json) if $json;
408  
409 # Authentication
410 if ($self->{auth}) {
411 $self->_authenticate or warn 'AUTH: Authentication failed';
412 }
413  
414 # define handlers order
415 $self->{workqueue} = defined $self->{router} ? $self->{router}->($self) : ['DEFAULT'] or warn 'NOHANDLER|CRIT: No any handler match the request';
416 $self->{workqueue} = [$self->{workqueue}] unless ref $self->{workqueue}; # make arrayref, so router may return handler name as a plain string
417  
418 # page could be redefined by handler
419 $self->{page} = DEFAULT_TPL;
420 }
421  
422 =begin nd
423 Function: interrupt ($signal)
424 Handler of TERM or INT signals.
425
426 Interrupt Server gracefully.
427  
428 The Apache web server sends TERM for '$ apachectl graceful' command.
429  
430 This function uses global 'my' variables instead of server attributes for cut dependency of Server constructor.
431
432 Parameters:
433 $signal - signal
434 =cut
435 sub interrupt {
436 my $signal = shift;
437  
438 warn "SERVER|NOTICE: The $signal signal received";
439  
440 $AtWork ? $Interrupted = 1 : die 'SERVER|NOTICE: Server stoped';
441 };
442  
443 =begin nd
444 Method: _init_httprequest ( )
445 Create <Crop::HTTP::Request> object from client data.
446
447 Pure virtual method.
448 =cut
449 sub _init_httprequest { warn 'Crop::Server::_init_httprequest() must be redefined by a subclass' }
450  
451 =begin nd
452 Method: instance ( )
453 Get Singlton.
454  
455 Returns:
456 $Server object as an singlton.
457 =cut
458 sub instance { $Server }
459  
460 =begin nd
461 Method: _is_json_correct ($json)
462 Check incomming JSON for correctness.
463  
464 Input should consists of hashref where items are scalar either hashref.
465  
466 Tree traverse uses a loop+stack.
467  
468 Returns:
469 1 - is correct
470 undef - otherwise
471 =cut
472 sub _is_json_correct {
473 my ($self, $json) = @_;
474  
475 # 'left' contains a names of json objects of current node were not processed
476 # 'node' is the current item of parsing; if left=undef, node were not processed
477 my @stack = {left => undef, node => $json};
478  
479 while (my $frame = pop @stack) {
480 my $node = $frame->{node};
481 next unless ref $node;
482
483 if (ref $node eq 'HASH') {
484 # remember keys of child nodes at the begining of parsing current node
485 $frame->{left} = [keys %$node] unless defined $frame->{left};
486  
487 @{$frame->{left}} or next; # all childs is done
488 my $key = pop @{$frame->{left}};
489  
490 # frame with remaining nodes goes back to the stack for a later parsing
491 push @stack, $frame;
492  
493 # no info about this node, so 'left' is undef
494 push @stack, {left => undef, node => $node->{$key}};
495 } elsif (ref $node eq 'ARRAY') {
496 # debug 'ARRAY_AT_JSON';
497 } elsif (ref $node eq 'JSON::PP::Boolean') {
498 # $$node = 0 or 1; boolean type
499 } else {
500 return warn 'INPUT: JSON parsing error'; # json is incorrect
501 }
502 }
503  
504 1;
505 }
506  
507 =begin nd
508 Method: listen ( )
509 Main loop serves client requests. Pure virtual.
510  
511 Returns:
512 Infinite loop, do not return.
513 =cut
514 sub listen {
515 return warn 'SERVER|CRIT: Crop::Server::listen() must be redefined by a subclass';
516 }
517  
518 =begin nd
519 Method: O ( )
520 The getter of output flow.
521  
522 Returns:
523 hashref
524 =cut
525 sub O { shift->{oflow} }
526  
527 =begin nd
528 Method: _output ( )
529 Build the output and send it to a client.
530 =cut
531 sub _output {
532 my $self = shift;
533  
534 if (defined $self->{sendfile}) {
535 $self->_sendfile;
536 return;
537 }
538
539 Crop::Error::bind $self->{oflow}{ERROR};
540  
541 my $cookie = CGI::Cookie->new(
542 -name => 'session',
543 -value => $self->{request}->cookie_out,
544 # -domain => '.' . $self->Config->{host},
545 -expires => '+365d',
546 );
547 my $cookie_secure = CGI::Cookie->new(
548 -name => 'session',
549 -value => $self->{request}->cookie_out,
550 -expires => '+365d',
551 -secure => 1,
552 -samsite => 'None',
553 );
554 my ($content, $content_t);
555 given ($self->{output_t}) {
556 when ('XSLT') {
557 if (defined $self->{redirect}) {
558 # unless (defined $self->{redirect}) {
559 $self->_redirect;
560 } else {
561 $self->{headers} = [
562 -type => 'text/html; charset=utf-8',
563 -cookie => [$cookie_secure, $cookie],
564 ];
565  
566 my $xml_source = XMLout($self->{oflow}, SuppressEmpty => 1);
567 debug DL_SRV, "xml_source=", $xml_source;
568 my $xml_parser = XML::LibXML->new;
569 my $xml = $xml_parser->load_xml(string => $xml_source);
570  
571 my $page = $self->{page};
572 my $xslt = $self->{xslt}{$page};
573 my $result = $self->{xslt}{$page}->transform($xml);
574 $self->{content} = "<!DOCTYPE html>\n" . $xslt->output_as_bytes($result);
575 }
576 }
577 when ('JSON') {
578 $self->{headers} = [
579 -type => 'application/json',
580 # -type => 'text/html; charset=utf-8',
581 -cookie => [$cookie_secure, $cookie],
582 # -cookie => $cookie,
583 ];
584  
585 $self->{content} = $self->{json}->utf8->encode($self->{oflow});
586 }
587 default: warn 'SERVER|ALERT: Unknown content type';
588 }
589
590 $self->_flush;
591 }
592  
593 =begin nd
594 Method: _parse_input ( )
595 Build an input flow ($self->{iflow}) from incomming parameters.
596
597 Parameters can contain a dot separator
598 >user.name=john&user.email=gmail&
599 so the hash will constructed
600 >{user => {name=>john, email=>gmail}}
601 in the $self->{iflow}
602 =cut
603 sub _parse_input {
604 my $self = shift;
605  
606 my $param = $self->{request}->param;
607 for my $name (keys %$param) {
608 # separate name to nested hashes
609 my @keys = split '\.', $name;
610  
611 # only the last name is a lvalue that suitable for assign to parameter
612 my $last = pop @keys;
613  
614 # step down for all name's parts
615 my $target = $self->{iflow};
616 for (@keys) {
617 # create a new hash for current name
618 exists $target->{$_} and ref $target->{$_} eq 'HASH' or $target->{$_} = {};
619  
620 # do next step down
621 $target = $target->{$_};
622 }
623 $target->{$last} = decode 'utf8', $param->{$name};
624 }
625 }
626  
627 =begin nd
628 Method: _parse_json ($src)
629 Decode incomming JSON.
630
631 Save result to iflow.
632
633 Parameters:
634 $src - raw JSON from either GET, POST, packed to special param, or Content-Type marked
635
636 Returns:
637 iflow - if ok
638 undef - otherwise
639 =cut
640 sub _parse_json {
641 my ($self, $src) = @_;
642
643 my $json = $self->{json}->decode($src);
644 $self->_is_json_correct($json) or return warn 'INPUT: Incorrect JSON';
645  
646 $self->{iflow} = $json;
647 }
648  
649 =begin nd
650 Method: redirect ($url)
651 Make a client redirect to $url in a script.
652  
653 > return $Server->redirect('/');
654  
655 Sets redirect attribute to the $url, and returns special constant that means 'make redirect' in the main loop of Server.
656  
657 Parameters:
658 $url - addres to redirect
659  
660 Returns:
661 <Crop::Server::Constants::REDIRECT>
662 =cut
663 sub redirect {
664 my ($self, $url) = @_;
665  
666 $self->{redirect} = $url // HOMEPAGE;
667  
668 REDIRECT;
669 }
670  
671 =begin nd
672 Method: _redirect ( )
673 Send redirect to a client.
674  
675 Pure virtual method must be redefined by subclass.
676 =cut
677 sub _redirect {
678 warn 'SERVER|ALERT: ' . __PACKAGE__ . '::_redirect() method must be redefined by a subclass';
679 }
680  
681 =begin nd
682 Method: _sendfile ( )
683 Send X-Accel-Redirect to a client to allow download.
684
685 Pure virtual method must be redefined by a subclass.
686 =cut
687 sub _sendfile {
688 warn 'SERVER|ALERT: ' . __PACKAGE__ . '::_sendfile() method must be redefined by subclass';
689 }
690  
691 =begin nd
692 Method: _work ( )
693 Handle current request.
694
695 Altough Gateway Interfaces are different, general logic is the same for every client request.
696 =cut
697 sub _work {
698 my $self = shift;
699
700 $self->_init;
701 if (all_right) {
702 HANDLER:
703 while (my $name = shift @{$self->{workqueue}}) {
704 # debug 'HANDLER_NAME=', $name;
705
706 unless (exists $self->{handler}{$name}) {
707 warn "SERVER|CRIT: No such Handler: $name";
708 last HANDLER;
709 }
710 my $handler = $self->{handler}{$name};
711  
712 # check client input for allowed parameters
713 unless ($handler->checkin($self->{iflow})) {
714 warn 'INPUT|ERR: Input flow does not satisfy to rules of handler ', $handler->name;
715 last HANDLER;
716 }
717
718 my $rc = $handler->call->($self);
719 given ($rc) {
720 when (OK) {
721 # debug DL_SRV, "RC of handler $name is ", OK;
722 $self->{page} = $handler->page || DEFAULT_TPL;
723 }
724 when (FAIL) {
725 # debug DL_SRV, "RC of handler $name is ", FAIL;
726 if ($handler->page eq PAGELESS) {
727 $self->{redirect} = $self->{request}->referer; # TODO: check the original domain
728 # $self->_redirect;
729  
730 $self->{session}->pass_thru;
731 } else {
732 $self->{page} = $handler->page || DEFAULT_TPL;
733 }
734 last HANDLER;
735 }
736 when (REDIRECT) {
737 # debug DL_SRV, "RC of handler $name is ", REDIRECT;
738 # $self->_redirect;
739 last HANDLER;
740 }
741 when (WORKFLOW) {
742 # debug DL_SRV, "RC of handler $name is ", WORKFLOW;
743 }
744 default {
745 warn "SERVER|CRIT: Unknown return code: '$rc' in Handler $name";
746 last HANDLER;
747 }
748 }
749 }
750 }
751 warn "SERVER|CRIT: Error at main loop" unless all_right;
752  
753 $self->_output;
754 $self->_cleanup;
755 }
756  
757 1;