MToken/Server.pm untested

filter: Statementstmt 0.0% 0 / 342 Branchbran 0.0% 0 / 122 Conditioncond 0.0% 0 / 79 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 38 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 594 SCAR 82.7
CC
62
Cov
0%
handler
650.0
index_post
182.0
_ieq
56.0
CRAP 3906.0
1 package MToken::Server; # $Id: Server.pm 70 2019-06-09 18:25:29Z minus $
2 use strict;
3 use warnings FATAL => 'all';
4 use utf8;
5  
6 =encoding utf-8
7  
8 =head1 NAME
9  
10 MToken::Server - mod_perl2 server for storing backups of MToken devices
11  
12 =head1 VERSION
13  
14 Version 1.01
15  
16 =head1 SYNOPSIS
17  
18 # Apache2 config section
19 <Location /mtoken>
20 SetHandler modperl
21 PerlResponseHandler MToken::Server
22 #PerlSetVar Debug 1
23 PerlSetVar MTokenDir /var/www/mtoken
24 </Location>
25  
26 =head1 DESCRIPTION
27  
28 To use the functionality of this module, you must edit the virtual-host section of
29 the Apache2 WEB server configuration file by specifying the directory for storing
30 backup files and authorization data. For example please run
31 command: "make serverconfig"
32  
33 =head2 FUNCTIONS
34  
35 =over 8
36  
37 =item B<handler>
38  
39 Handler for Apache2 WEB server
40  
41 =item B<index_get>
42  
43 This function returns a list of files on directory in the JSON format
44  
45 {
46 "response_object" : "index_get",
47 "data" : {
48 "uri" : "/mtoken",
49 "finished" : 1501500207,
50 "is_index" : 1,
51 "qs" : "",
52 "started" : 1501500206,
53 "method" : "GET",
54 "finishedfmt" : "07/31/17 14:23:27 MSK",
55 "location" : "/mtoken",
56 "startedfmt" : "07/31/17 14:23:26 MSK",
57 "debug" : 0,
58 "filename" : "",
59 "mtokendir" : "/var/www/mtoken/mtoken",
60 "files" : [
61 {
62 "sha1" : "9a7cf5e50477dceab768fdc449eee233e3a9d670",
63 "date_fmt" : "2017/07/26",
64 "file" : "/var/www/mtoken/mtoken/myfooproject.20170726",
65 "size" : 19830,
66 "filename" : "myfooproject.20170726",
67 "md5" : "4b435617553a7a226210b142ccb2cbcc",
68 "date_sfx" : "20170726"
69 }
70 ]
71 },
72 "request_object" : null,
73 "error" : [],
74 "status" : 1
75 }
76  
77 =item B<index_post>
78  
79 This function add new backup file to directory
80  
81 =item B<file_get>
82  
83 This function provides downloading the backup file from directory
84  
85 =item B<file_put>
86  
87 Update the backup file in the directory
88  
89 =item B<file_delete>
90  
91 This function provides removing the backup file from directory
92  
93 =back
94  
95 =head1 HISTORY
96  
97 See C<Changes> file
98  
99 =head1 DEPENDENCIES
100  
101 L<LWP>, C<mod_perl2>, L<CTK>
102  
103 =head1 TO DO
104  
105 See C<TODO> file
106  
107 =head1 BUGS
108  
109 * none noted
110  
111 =head1 SEE ALSO
112  
113 L<CTK>, L<mod_perl2>
114  
115 =head1 AUTHOR
116  
117 Serż Minus (Sergey Lepenkov) L<http://www.serzik.com> E<lt>abalama@cpan.orgE<gt>
118  
119 =head1 COPYRIGHT
120  
121 Copyright (C) 1998-2019 D&D Corporation. All Rights Reserved
122  
123 =head1 LICENSE
124  
125 This program is free software; you can redistribute it and/or
126 modify it under the same terms as Perl itself.
127  
128 See C<LICENSE> file and L<https://dev.perl.org/licenses/>
129  
130 =cut
131  
132 use vars qw/ $VERSION /;
133 $VERSION = "1.01";
134  
135 use Encode;
136 use Encode::Locale;
137  
138 use mod_perl2;
139 use Apache2::RequestIO ();
140 use Apache2::RequestRec ();
141 use Apache2::RequestUtil ();
142 use Apache2::ServerRec ();
143 use Apache2::ServerUtil ();
144 use Apache2::Connection ();
145 use Apache2::Const -compile => qw/ :common :http /;
146 use Apache2::Log;
147 use Apache2::Util ();
148 use APR::Const -compile => qw/ :common /;
149 use APR::Table ();
150  
151 use CGI -compile => qw/ :all /;
152 use CTK::Serializer;
153 use File::Spec;
154 use File::Find;
155 use File::Basename;
156  
157 use MToken::Util qw/filesize md5sum sha1sum/;
158  
159 use constant {
160 PREFIX => "MToken",
161 LOCATION => "/mtoken",
162 DATE_FORMAT => "%D %H:%M:%S %Z",
163 CONTENT_TYPE => "application/json; charset=utf-8",
164 SERIALIZE_FORMAT => 'json',
165 SR_ATTRS => {
166 json => [
167 { # For serialize
168 utf8 => 0,
169 pretty => 1,
170 allow_nonref => 1,
171 allow_blessed => 1,
172 },
173 { # For deserialize
174 utf8 => 0,
175 allow_nonref => 1,
176 allow_blessed => 1,
177 },
178 ],
179 },
180 OBJECTS_REQUIRED => [qw/
181 index_post
182 /],
183 ERRORS => {
184 0 => "Internal error",
185 1 => "Can't create directory %s: %s",
186 2 => "Incorrect permissions for directory %s. Required permissions: RWX for owner",
187 3 => "Incorrect uploaded file name",
188 4 => "Can't open file for saving %s: %s",
189 5 => "Can't upload file %s",
190 6 => "File size mismatch: Expected: %s; Got: %s",
191 7 => "File md5sum mismatch: Expected: %s; Got: %s",
192 8 => "File sha1sum mismatch: Expected: %s; Got: %s",
193 9 => "Object mismatch: Expected: %s; Got: %s",
194 10 => "File already exists: %s",
195 11 => "Can't rewrite file, please use PUT command for updating it: %s",
196 12 => "Can't delete file %s: %s",
197 13 => "File not exists: %s",
198 Apache2::Const::HTTP_NO_CONTENT => "No content",
199 Apache2::Const::HTTP_BAD_REQUEST => "Bad request: %s",
200 Apache2::Const::HTTP_METHOD_NOT_ALLOWED => "This method not allowed: %s",
201 },
202 };
203 my $DEBUG;
204  
205 sub handler {
206 my $r = shift;
207 Apache2::RequestUtil->request($r);
208 $r->handler('modperl');
209 my $q = new CGI if $r->method ne 'PUT';
210 $r->content_type(CONTENT_TYPE);
211 my $uri = $r->uri || ""; $uri =~ s/\/+$//;
212 my $location = $r->location || LOCATION; $location =~ s/\/+$//;
213 my $blank = {
214 status => 1,
215 error => [],
216 request_object => scalar($q ? $q->param("object") : ''),
217 data => {
218 started => $r->request_time,
219 startedfmt => decode(locale => Apache2::Util::ht_time(
220 $r->pool, $r->request_time, DATE_FORMAT, 0
221 )),
222 method => $r->method,
223 location => $location,
224 uri => $uri,
225 qs => $r->args || "",
226 },
227 };
228 my %json = %$blank;
229  
230 # Debug Mode
231 $DEBUG = $r->dir_config("debug") || 0;
232 $json{data}{debug} = $DEBUG ? 1 : 0;
233  
234 # Directory
235 my $docroot = $r->document_root();
236 my $mtokendir = $r->dir_config("mtokendir") // $docroot;
237 unless (File::Spec->file_name_is_absolute($mtokendir)) {
238 $mtokendir = File::Spec->catdir($docroot, $mtokendir);
239 }
240 unless (-e $mtokendir) {
241 mkdir($mtokendir) or _set_error(\%json, 1, $mtokendir, $!) && return _output($r => \%json);
242 }
243 unless (-r $mtokendir and -w _ and -x _) {
244 _set_error(\%json, 2, $mtokendir);
245 return _output($r => \%json);
246 }
247 $json{data}{mtokendir} = $mtokendir;
248  
249 # Index & File
250 my $is_index = 1;
251 my $file = "";
252 if ($uri =~ /\.[0-9]{8}$/) { # Is File by mask
253 if (index($uri,$location,0) == 0) { # Catched!
254 $file = substr($uri,length($location)+1);
255 if ($file && $file !~ /\//) {
256 $is_index = 0;
257 }
258 } else {
259 $is_index = 1;
260 }
261 }
262 $json{data}{is_index} = $is_index;
263 $json{data}{filename} = $file;
264  
265 # Dispatching
266 my $status = 0;
267 my $meth = uc($r->method || "GET");
268 if ($is_index) { # GET and POST for index
269 if ($meth eq "GET" or $meth eq "HEAD") {
270 $status = index_get($r, $q, \%json);
271 _debug(sprintf("%s index: %s", $meth, $status ? 'OK' : 'ERROR'));
272 } elsif ($meth eq "POST") {
273 $status = index_post($r, $q, \%json);
274 _debug(sprintf("%s index: %s", $meth, $status ? 'OK' : 'ERROR'));
275 } else {
276 _set_error(\%json, Apache2::Const::HTTP_METHOD_NOT_ALLOWED, $meth);
277 _error("Error method %s", $meth);
278 }
279 } else { # GET, HEAD, PUT and DELETE for file
280 if ($meth eq "GET" or $meth eq "HEAD") {
281 $status = file_get($r, $q, \%json);
282 _debug(sprintf("%s file: %s", $meth, $status == Apache2::Const::OK ? 'OK' : 'ERROR'));
283 return $status;
284 } elsif ($meth eq "PUT") {
285 $status = file_put($r, $q, \%json);
286 _debug(sprintf("%s file: %s", $meth, $status ? 'OK' : 'ERROR'));
287 } elsif ($meth eq "DELETE") {
288 $status = file_delete($r, $q, \%json);
289 _debug(sprintf("%s file: %s", $meth, $status ? 'OK' : 'ERROR'));
290 } else {
291 _set_error(\%json, Apache2::Const::HTTP_METHOD_NOT_ALLOWED, $meth);
292 _error("Error method %s", $meth);
293 }
294 }
295  
296 # Object mismatch
297 my $obj_req = $json{request_object};
298 my $obj_res = $json{response_object};
299 if (grep {$_ eq $obj_res} @{(OBJECTS_REQUIRED())}) {
300 unless ($obj_req) {
301 _set_error(\%json, Apache2::Const::HTTP_BAD_REQUEST, "Object not specified");
302 return _output($r => \%json);
303 }
304 }
305 if ($obj_req && $obj_res) {
306 if ($obj_req ne $obj_res) {
307 _set_error(\%json, 9, $obj_req, $obj_res);
308 }
309 }
310  
311 # OUTPUT
312 return _output($r => \%json);
313 }
314 sub index_get {
315 my ($r, $q, $json) = @_;
316 $json->{response_object} = "index_get";
317 my $filename = $q->param("file") || $q->param("info");
318  
319 my @files = _get_file_list($json->{data}{mtokendir});
320 if ($filename) {
321 $json->{data}{info} = _get_file_info($filename, @files);
322 } else {
323 $json->{data}{files} = [@files];
324 }
325 return 1;
326 }
327 sub index_post {
328 my ($r, $q, $json) = @_;
329 $json->{response_object} = "index_post";
330 my $mtokendir = $json->{data}{mtokendir};
331 my $file_k = "file1";
332 my $fileup = defined($q->param($file_k)) ? $q->param($file_k).'' : '';
333 unless (defined($fileup) && length($fileup)) {
334 _set_error($json, 3);
335 return 0;
336 }
337 my $in_sha1 = $q->param("sha1");
338 my $in_md5 = $q->param("md5");
339 my $in_size = $q->param("size");
340  
341 my $exsts = _get_file_info($fileup, _get_file_list($mtokendir));
342 if ($exsts) { # Catched!
343 if (_ieq($exsts->{size}, $in_size) && _ieq($exsts->{md5}, $in_md5) && _ieq($exsts->{sha1}, $in_sha1)) {
344 _set_error($json, 10, $fileup);
345 } else {
346 _set_error($json, 11, $fileup);
347 }
348 return 0;
349 }
350  
351 $json->{data}{in} = {
352 in_file => $fileup,
353 in_sha1 => $in_sha1,
354 in_md5 => $in_md5,
355 in_size => $in_size,
356 };
357  
358 my $file;
359 if ($fileup && $fileup =~ /^[0-9a-z.\-_]+$/i) {
360 $file = File::Spec->catfile($mtokendir, $fileup);
361 unless (open(UPLOAD,">",$file)) {
362 _set_error($json, 4, $file, $!);
363 return 0;
364 }
365 binmode(UPLOAD);
366 if ( my $fh = $q->upload($file_k) ) {
367 binmode($fh);
368 my $buffer;
369 while ( my $bytesread = read($fh, $buffer,1024) ) {
370 print UPLOAD $buffer;
371 }
372 } else {
373 _set_error($json, 5, $fileup);
374 close UPLOAD;
375 return 0;
376 }
377 close UPLOAD;
378 } else {
379 _set_error($json, 3);
380 return 0;
381 }
382  
383 my $out_size = filesize($file);
384 my $out_sha1 = sha1sum($file);
385 my $out_md5 = md5sum($file);
386  
387 $json->{data}{out} = {
388 out_file => $file,
389 out_sha1 => $out_sha1,
390 out_md5 => $out_md5,
391 out_size => $out_size,
392 };
393  
394 # Mismatch?
395 my $miss = 1;
396 if ($in_size != $out_size) {
397 _set_error($json, 6, $in_size, $out_size);
398 $miss = 0;
399 }
400 if ($in_md5 ne $out_md5) {
401 _set_error($json, 7, $in_md5, $out_md5);
402 $miss = 0;
403 }
404 if ($in_sha1 ne $out_sha1) {
405 _set_error($json, 8, $in_sha1, $out_sha1);
406 $miss = 0;
407 }
408 unless ($miss) {
409 unless (unlink($file) ) {
410 _set_error($json, 12, $file, $!);
411 return 0;
412 }
413 }
414 return $miss;
415 }
416 sub file_get {
417 my ($r, $q, $json) = @_;
418 my $notes = $r->notes;
419  
420 $json->{response_object} = "file_get";
421 my $mtokendir = $json->{data}{mtokendir};
422 my $filename = $json->{data}{filename};
423 my $file = File::Spec->catfile($mtokendir, $filename);
424  
425 return Apache2::Const::NOT_FOUND unless $filename && -e $file;
426 my $len = filesize($file);
427 return Apache2::Const::NOT_FOUND unless $len;
428 $r->set_content_length($len);
429 $r->content_type('application/octet-stream');
430 $r->headers_out->set('Content-Disposition', sprintf("attachment; filename=\"%s\"", $filename));
431 my $rc = $r->sendfile($file,0,$len);
432 unless ($rc == APR::Const::SUCCESS) {
433 my $errmsg = sprintf("Can't send file: %s (%s)", $filename, $file);
434 _error($errmsg);
435 $ENV{REDIRECT_ERROR_NOTES} = $errmsg;
436 $r->subprocess_env(REDIRECT_ERROR_NOTES => $errmsg);
437 $notes->set('error-notes' => $errmsg);
438 return Apache2::Const::SERVER_ERROR;
439 }
440  
441 return Apache2::Const::OK;
442 }
443 sub file_put {
444 my ($r, $q, $json) = @_;
445 $json->{response_object} = "file_put";
446  
447 my $mtokendir = $json->{data}{mtokendir};
448 my $filename = $json->{data}{filename};
449 my $file = File::Spec->catfile($mtokendir, $filename);
450  
451 unless ($filename && -e $file) {
452 _set_error($json, 13, $file);
453 return 0;
454 }
455  
456 unless (open(UPDATE,">",$file)) {
457 _set_error($json, 4, $file, $!);
458 return 0;
459 }
460 binmode(UPDATE);
461 my $buffer;
462 while ( my $bytesread = $r->read($buffer, 1024) ) {
463 print UPDATE $buffer;
464 }
465 close(UPDATE);
466  
467 my $size = filesize($file);
468 unless ($size) {
469 unless (unlink($file) ) {
470 _set_error($json, 12, $file, $!);
471 return 0;
472 }
473 _set_error($json, 5, $file);
474 return 0;
475 }
476  
477 $json->{data}{out} = {
478 out_file => $file,
479 out_sha1 => sha1sum($file),
480 out_md5 => md5sum($file),
481 out_size => $size,
482 };
483 return 1;
484 }
485 sub file_delete {
486 my ($r, $q, $json) = @_;
487 $json->{response_object} = "file_delete";
488  
489 my $mtokendir = $json->{data}{mtokendir};
490 my $filename = $json->{data}{filename};
491 my $file = File::Spec->catfile($mtokendir, $filename);
492  
493 unless ($filename && -e $file) {
494 _set_error($json, 13, $file);
495 return 0;
496 }
497 unless (unlink($file) ) {
498 _set_error($json, 12, $file, $!);
499 return 0;
500 }
501  
502 return 1;
503 }
504  
505 sub _output {
506 my $r = shift;
507 my $json = shift;
508 my $notes = $r->notes;
509 my $tm = time();
510 $json->{data}{finished} = $tm;
511 $json->{data}{finishedfmt} = decode(locale => Apache2::Util::ht_time($r->pool, $tm, DATE_FORMAT, 0));
512  
513 # Serializer
514 my $sr = new CTK::Serializer(SERIALIZE_FORMAT, attrs => SR_ATTRS);
515 unless ($sr->status) {
516 my $errmsg = sprintf("Can't create json serializer: %s", $sr->error);
517 _error($errmsg);
518 $ENV{REDIRECT_ERROR_NOTES} = $errmsg;
519 $r->subprocess_env(REDIRECT_ERROR_NOTES => $errmsg);
520 $notes->set('error-notes' => $errmsg);
521 return Apache2::Const::SERVER_ERROR;
522 }
523  
524 my $output = $sr->serialize($json);
525 unless ($sr->status) {
526 my $errmsg = sprintf("Can't serialize structure: %s", $sr->error);
527 _error($errmsg);
528 $ENV{REDIRECT_ERROR_NOTES} = $errmsg;
529 $r->subprocess_env(REDIRECT_ERROR_NOTES => $errmsg);
530 $notes->set('error-notes' => $errmsg);
531 return Apache2::Const::SERVER_ERROR;
532 }
533  
534 $r->headers_out->set('Accept-Ranges', 'none');
535 $r->set_content_length(length(Encode::encode_utf8($output)) || 0);
536 return Apache2::Const::OK if uc($r->method) eq "HEAD";
537 $r->print($output);
538 $r->rflush();
539 return Apache2::Const::OK;
540 }
541 sub _set_error {
542 my $json = shift;
543 my $code = shift || 0;
544 my @data = @_;
545 my $msg = sprintf(ERRORS->{$code}, @data);
546 push @{$json->{error}}, {code => $code, message => $msg};
547 _debug(sprintf("Error: code=%d; message=\"%s\"", $code, $msg));
548 $json->{status} = 0;
549 return 1;
550 }
551 sub _debug {
552 my $msg = shift;
553 return 1 unless $DEBUG;
554 return 0 unless defined $msg;
555 my $r = Apache2::RequestUtil->request();
556 $r->log->debug(sprintf("%s> %s", PREFIX, $msg)); # ---> Request ok :=)"
557 return 1;
558 }
559 sub _error { # Log error
560 my $msg = shift;
561 return 0 unless defined $msg;
562 my $r = Apache2::RequestUtil->request();
563 $r->log->error(sprintf("%s> %s", PREFIX, $msg));
564 return 1;
565 }
566 sub _get_file_list {
567 my $dir = shift || '.';
568 my @files;
569 find({
570 no_chdir => 1,
571 wanted => sub {
572 my $file = $_;
573 my $filename = basename($_);
574 return unless ((-f $file) && $file =~ /\.[0-9]{8}$/);
575 my ($y,$m,$d) = ($1,$2,$3) if $file =~ /([0-9]{4})([0-9]{2})([0-9]{2})$/;
576 push @files, {
577 file => $file,
578 filename => $filename,
579 size => filesize($file),
580 md5 => md5sum($file),
581 sha1 => sha1sum($file),
582 date_sfx => sprintf("%04d%02d%02d", $y,$m,$d),
583 date_fmt => sprintf("%04d/%02d/%02d", $y,$m,$d),
584 };
585 }}, $dir);
586 return @files;
587 }
588 sub _get_file_info {
589 my $filename = shift;
590 foreach (@_) {
591 return $_ if (ref($_) eq 'HASH') && $_->{filename} eq $filename;
592 }
593 return undef;
594 }
595 sub _ieq {
596 my ($l, $r) = @_;
597 return 0 unless defined $l;
598 return 0 unless defined $r;
599  
600 if ($l =~ /^[0-9a-z]+$/i and $r =~ /^[0-9a-z]+$/i) {
601 return ($l eq $r) ? 1 : 0;
602 } elsif (($l =~ /^[0-9]+$/ and $r =~ /^[0-9]+$/)) {
603 return ($l == $r) ? 1 : 0;
604 }
605 return 0;
606 }
607  
608 1;
609  
610 __END__