]> Dogcows Code - chaz/p5-File-KDBX/blob - lib/File/KDBX/Util.pm
Remove parent Object method
[chaz/p5-File-KDBX] / lib / File / KDBX / Util.pm
1 package File::KDBX::Util;
2 # ABSTRACT: Utility functions for working with KDBX files
3
4 use warnings;
5 use strict;
6
7 use Crypt::PRNG qw(random_bytes random_string);
8 use Encode qw(decode encode);
9 use Exporter qw(import);
10 use File::KDBX::Constants qw(:bool);
11 use File::KDBX::Error;
12 use List::Util 1.33 qw(any all);
13 use Module::Load;
14 use Ref::Util qw(is_arrayref is_coderef is_hashref is_ref is_refref is_scalarref);
15 use Scalar::Util qw(blessed looks_like_number readonly);
16 use Time::Piece;
17 use boolean;
18 use namespace::clean -except => 'import';
19
20 our $VERSION = '999.999'; # VERSION
21
22 our %EXPORT_TAGS = (
23 assert => [qw(DEBUG assert assert_64bit)],
24 class => [qw(extends has list_attributes)],
25 clone => [qw(clone clone_nomagic)],
26 coercion => [qw(to_bool to_number to_string to_time to_tristate to_uuid)],
27 crypt => [qw(pad_pkcs7)],
28 debug => [qw(DEBUG dumper)],
29 fork => [qw(can_fork)],
30 function => [qw(memoize recurse_limit)],
31 empty => [qw(empty nonempty)],
32 erase => [qw(erase erase_scoped)],
33 gzip => [qw(gzip gunzip)],
34 io => [qw(is_readable is_writable read_all)],
35 load => [qw(load_optional load_xs try_load_optional)],
36 search => [qw(query query_any search simple_expression_query)],
37 text => [qw(snakify trim)],
38 uuid => [qw(format_uuid generate_uuid is_uuid uuid UUID_NULL)],
39 uri => [qw(split_url uri_escape_utf8 uri_unescape_utf8)],
40 );
41
42 $EXPORT_TAGS{all} = [map { @$_ } values %EXPORT_TAGS];
43 our @EXPORT_OK = @{$EXPORT_TAGS{all}};
44
45 BEGIN {
46 my $debug = $ENV{DEBUG};
47 $debug = looks_like_number($debug) ? (0 + $debug) : ($debug ? 1 : 0);
48 *DEBUG = $debug == 1 ? sub() { 1 } :
49 $debug == 2 ? sub() { 2 } :
50 $debug == 3 ? sub() { 3 } :
51 $debug == 4 ? sub() { 4 } : sub() { 0 };
52 }
53
54 my %OPS = (
55 'eq' => 2, # binary
56 'ne' => 2,
57 'lt' => 2,
58 'gt' => 2,
59 'le' => 2,
60 'ge' => 2,
61 '==' => 2,
62 '!=' => 2,
63 '<' => 2,
64 '>' => 2,
65 '<=' => 2,
66 '>=' => 2,
67 '=~' => 2,
68 '!~' => 2,
69 '!' => 1, # unary
70 '!!' => 1,
71 '-not' => 1, # special
72 '-false' => 1,
73 '-true' => 1,
74 '-defined' => 1,
75 '-undef' => 1,
76 '-empty' => 1,
77 '-nonempty' => 1,
78 '-or' => -1,
79 '-and' => -1,
80 );
81 my %OP_NEG = (
82 'eq' => 'ne',
83 'ne' => 'eq',
84 'lt' => 'ge',
85 'gt' => 'le',
86 'le' => 'gt',
87 'ge' => 'lt',
88 '==' => '!=',
89 '!=' => '==',
90 '<' => '>=',
91 '>' => '<=',
92 '<=' => '>',
93 '>=' => '<',
94 '=~' => '!~',
95 '!~' => '=~',
96 );
97 my %ATTRIBUTES;
98
99 =func load_xs
100
101 $bool = load_xs();
102 $bool = load_xs($version);
103
104 Attempt to load L<File::KDBX::XS>. Return truthy if C<XS> is loaded. If C<$version> is given, it will check
105 that at least the given version is loaded.
106
107 =cut
108
109 my $XS_LOADED;
110 sub load_xs {
111 my $version = shift;
112
113 goto IS_LOADED if defined $XS_LOADED;
114
115 if ($ENV{PERL_ONLY} || (exists $ENV{PERL_FILE_KDBX_XS} && !$ENV{PERL_FILE_KDBX_XS})) {
116 return $XS_LOADED = FALSE;
117 }
118
119 $XS_LOADED = !!eval { require File::KDBX::XS; 1 };
120
121 IS_LOADED:
122 {
123 local $@;
124 return $XS_LOADED if !$version;
125 return !!eval { File::KDBX::XS->VERSION($version); 1 };
126 }
127 }
128
129 =func assert
130
131 assert { ... };
132
133 Write an executable comment. Only executed if C<DEBUG> is set in the environment.
134
135 =cut
136
137 sub assert(&) { ## no critic (ProhibitSubroutinePrototypes)
138 return if !DEBUG;
139 my $code = shift;
140 return if $code->();
141
142 (undef, my $file, my $line) = caller;
143 $file =~ s!([^/\\]+)$!$1!;
144 my $assertion = '';
145 if (try_load_optional('B::Deparse')) {
146 my $deparse = B::Deparse->new(qw{-P -x9});
147 $assertion = $deparse->coderef2text($code);
148 $assertion =~ s/^\{(?:\s*(?:package[^;]+|use[^;]+);)*\s*(.*?);\s*\}$/$1/s;
149 $assertion =~ s/\s+/ /gs;
150 $assertion = ": $assertion";
151 }
152 die "$0: $file:$line: Assertion failed$assertion\n";
153 }
154
155 =func assert_64bit
156
157 assert_64bit();
158
159 Throw if perl doesn't support 64-bit IVs.
160
161 =cut
162
163 sub assert_64bit() {
164 require Config;
165 $Config::Config{ivsize} < 8
166 and throw "64-bit perl is required to use this feature.\n", ivsize => $Config::Config{ivsize};
167 }
168
169 =func can_fork
170
171 $bool = can_fork;
172
173 Determine if perl can fork, with logic lifted from L<Test2::Util/CAN_FORK>.
174
175 =cut
176
177 sub can_fork {
178 require Config;
179 return 1 if $Config::Config{d_fork};
180 return 0 if $^O ne 'MSWin32' && $^O ne 'NetWare';
181 return 0 if !$Config::Config{useithreads};
182 return 0 if $Config::Config{ccflags} !~ /-DPERL_IMPLICIT_SYS/;
183 return 0 if $] < 5.008001;
184 if ($] == 5.010000 && $Config::Config{ccname} eq 'gcc' && $Config::Config{gccversion}) {
185 return 0 if $Config::Config{gccversion} !~ m/^(\d+)\.(\d+)/;
186 my @parts = split(/[\.\s]+/, $Config::Config{gccversion});
187 return 0 if $parts[0] > 4 || ($parts[0] == 4 && $parts[1] >= 8);
188 }
189 return 0 if $INC{'Devel/Cover.pm'};
190 return 1;
191 }
192
193 =func clone
194
195 $clone = clone($thing);
196
197 Clone deeply. This is an unadorned alias to L<Storable> C<dclone>.
198
199 =cut
200
201 sub clone {
202 require Storable;
203 goto &Storable::dclone;
204 }
205
206 =func clone_nomagic
207
208 $clone = clone_nomagic($thing);
209
210 Clone deeply without keeping [most of] the magic.
211
212 B<WARNING:> At the moment the implementation is naïve and won't respond well to nontrivial data or recursive
213 structures.
214
215 =cut
216
217 sub clone_nomagic {
218 my $thing = shift;
219 if (is_arrayref($thing)) {
220 my @arr = map { clone_nomagic($_) } @$thing;
221 return \@arr;
222 }
223 elsif (is_hashref($thing)) {
224 my %hash;
225 $hash{$_} = clone_nomagic($thing->{$_}) for keys %$thing;
226 return \%hash;
227 }
228 elsif (is_ref($thing)) {
229 return clone($thing);
230 }
231 return $thing;
232 }
233
234 =func dumper
235
236 $str = dumper $thing;
237 dumper $thing; # in void context, prints to STDERR
238
239 Like L<Data::Dumper> but slightly terser in some cases relevent to L<File::KDBX>.
240
241 =cut
242
243 sub dumper {
244 require Data::Dumper;
245 # avoid "once" warnings
246 local $Data::Dumper::Deepcopy = $Data::Dumper::Deepcopy = 1;
247 local $Data::Dumper::Deparse = $Data::Dumper::Deparse = 1;
248 local $Data::Dumper::Indent = 1;
249 local $Data::Dumper::Quotekeys = 0;
250 local $Data::Dumper::Sortkeys = 1;
251 local $Data::Dumper::Terse = 1;
252 local $Data::Dumper::Trailingcomma = 1;
253 local $Data::Dumper::Useqq = 1;
254
255 my @dumps;
256 for my $struct (@_) {
257 my $str = Data::Dumper::Dumper($struct);
258
259 # boolean
260 $str =~ s/bless\( do\{\\\(my \$o = ([01])\)\}, 'boolean' \)/boolean($1)/gs;
261 # Time::Piece
262 $str =~ s/bless\([^\)]+?(\d+)'?,\s+\d+,?\s+\], 'Time::Piece' \),/
263 "scalar gmtime($1), # " . scalar gmtime($1)->datetime/ges;
264
265 print STDERR $str if !defined wantarray;
266 push @dumps, $str;
267 return $str;
268 }
269 return join("\n", @dumps);
270 }
271
272 =func empty
273
274 =func nonempty
275
276 $bool = empty $thing;
277
278 $bool = nonempty $thing;
279
280 Test whether a thing is empty (or nonempty). An empty thing is one of these:
281
282 =for :list
283 * nonexistent
284 * C<undef>
285 * zero-length string
286 * zero-length array
287 * hash with zero keys
288 * reference to an empty thing (recursive)
289
290 Note in particular that zero C<0> is not considered empty because it is an actual value.
291
292 =cut
293
294 sub empty { _empty(@_) }
295 sub nonempty { !_empty(@_) }
296
297 sub _empty {
298 return 1 if @_ == 0;
299 local $_ = shift;
300 return !defined $_
301 || $_ eq ''
302 || (is_arrayref($_) && @$_ == 0)
303 || (is_hashref($_) && keys %$_ == 0)
304 || (is_scalarref($_) && (!defined $$_ || $$_ eq ''))
305 || (is_refref($_) && _empty($$_));
306 }
307
308 =func erase
309
310 erase($string, ...);
311 erase(\$string, ...);
312
313 Overwrite the memory used by one or more string.
314
315 =cut
316
317 BEGIN {
318 if (load_xs) {
319 *_CowREFCNT = \&File::KDBX::XS::CowREFCNT;
320 }
321 elsif (eval { require B::COW; 1 }) {
322 *_CowREFCNT = \&B::COW::cowrefcnt;
323 }
324 else {
325 *_CowREFCNT = sub { undef };
326 }
327 }
328
329 sub erase {
330 # Only bother zeroing out memory if we have the last SvPV COW reference, otherwise we'll end up just
331 # creating a copy and erasing the copy.
332 # TODO - Is this worth doing? Need some benchmarking.
333 for (@_) {
334 if (!is_ref($_)) {
335 next if !defined $_ || readonly $_;
336 my $cowrefcnt = _CowREFCNT($_);
337 goto FREE_NONREF if defined $cowrefcnt && 1 < $cowrefcnt;
338 # if (__PACKAGE__->can('erase_xs')) {
339 # erase_xs($_);
340 # }
341 # else {
342 substr($_, 0, length($_), "\0" x length($_));
343 # }
344 FREE_NONREF: {
345 no warnings 'uninitialized';
346 undef $_;
347 }
348 }
349 elsif (is_scalarref($_)) {
350 next if !defined $$_ || readonly $$_;
351 my $cowrefcnt = _CowREFCNT($$_);
352 goto FREE_REF if defined $cowrefcnt && 1 < $cowrefcnt;
353 # if (__PACKAGE__->can('erase_xs')) {
354 # erase_xs($$_);
355 # }
356 # else {
357 substr($$_, 0, length($$_), "\0" x length($$_));
358 # }
359 FREE_REF: {
360 no warnings 'uninitialized';
361 undef $$_;
362 }
363 }
364 elsif (is_arrayref($_)) {
365 erase(@$_);
366 @$_ = ();
367 }
368 elsif (is_hashref($_)) {
369 erase(values %$_);
370 %$_ = ();
371 }
372 else {
373 throw 'Cannot erase this type of scalar', type => ref $_, what => $_;
374 }
375 }
376 }
377
378 =func erase_scoped
379
380 $scope_guard = erase_scoped($string, ...);
381 $scope_guard = erase_scoped(\$string, ...);
382 undef $scope_guard; # erase happens here
383
384 Get a scope guard that will cause scalars to be erased later (i.e. when the scope ends). This is useful if you
385 want to make sure a string gets erased after you're done with it, even if the scope ends abnormally.
386
387 See L</erase>.
388
389 =cut
390
391 sub erase_scoped {
392 throw 'Programmer error: Cannot call erase_scoped in void context' if !defined wantarray;
393 my @args;
394 for (@_) {
395 !is_ref($_) || is_arrayref($_) || is_hashref($_) || is_scalarref($_)
396 or throw 'Cannot erase this type of scalar', type => ref $_, what => $_;
397 push @args, is_ref($_) ? $_ : \$_;
398 }
399 require Scope::Guard;
400 return Scope::Guard->new(sub { erase(@args) });
401 }
402
403 =func extends
404
405 extends $class;
406
407 Set up the current module to inheret from another module.
408
409 =cut
410
411 sub extends {
412 my $parent = shift;
413 my $caller = caller;
414 load $parent;
415 no strict 'refs'; ## no critic (ProhibitNoStrict)
416 @{"${caller}::ISA"} = $parent;
417 }
418
419 =func has
420
421 has $name => %options;
422
423 Create an attribute getter/setter. Possible options:
424
425 =for :list
426 * C<is> - Either "rw" (default) or "ro"
427 * C<default> - Default value
428 * C<coerce> - Coercive function
429
430 =cut
431
432 sub has {
433 my $name = shift;
434 my %args = @_ % 2 == 1 ? (default => shift, @_) : @_;
435
436 my ($package, $file, $line) = caller;
437
438 my $d = $args{default};
439 my $default = is_arrayref($d) ? sub { [@$d] } : is_hashref($d) ? sub { +{%$d} } : $d;
440 my $coerce = $args{coerce};
441 my $is = $args{is} || 'rw';
442
443 my $store = $args{store};
444 ($store, $name) = split(/\./, $name, 2) if $name =~ /\./;
445
446 my @path = split(/\./, $args{path} || '');
447 my $last = pop @path;
448 my $path = $last ? join('', map { qq{->$_} } @path) . qq{->{'$last'}}
449 : $store ? qq{->$store\->{'$name'}} : qq{->{'$name'}};
450 my $member = qq{\$_[0]$path};
451
452
453 my $default_code = is_coderef $default ? q{scalar $default->($_[0])}
454 : defined $default ? q{$default}
455 : q{undef};
456 my $get = qq{$member //= $default_code;};
457
458 my $set = '';
459 if ($is eq 'rw') {
460 $set = is_coderef $coerce ? qq{$member = scalar \$coerce->(\@_[1..\$#_]) if \$#_;}
461 : defined $coerce ? qq{$member = do { local @_ = (\@_[1..\$#_]); $coerce } if \$#_;}
462 : qq{$member = \$_[1] if \$#_;};
463 }
464
465 push @{$ATTRIBUTES{$package} //= []}, $name;
466 $line -= 4;
467 my $code = <<END;
468 # line $line "$file"
469 sub ${package}::${name} {
470 return $default_code if !Scalar::Util::blessed(\$_[0]);
471 $set
472 $get
473 }
474 END
475 eval $code; ## no critic (ProhibitStringyEval)
476 }
477
478 =func format_uuid
479
480 $string_uuid = format_uuid($raw_uuid);
481 $string_uuid = format_uuid($raw_uuid, $delimiter);
482
483 Format a 128-bit UUID (given as a string of 16 octets) into a hexidecimal string, optionally with a delimiter
484 to break up the UUID visually into five parts. Examples:
485
486 my $uuid = uuid('01234567-89AB-CDEF-0123-456789ABCDEF');
487 say format_uuid($uuid); # -> 0123456789ABCDEF0123456789ABCDEF
488 say format_uuid($uuid, '-'); # -> 01234567-89AB-CDEF-0123-456789ABCDEF
489
490 This is the inverse of L</uuid>.
491
492 =cut
493
494 sub format_uuid {
495 local $_ = shift // "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
496 my $delim = shift // '';
497 length($_) == 16 or throw 'Must provide a 16-bytes UUID', size => length($_), str => $_;
498 return uc(join($delim, unpack('H8 H4 H4 H4 H12', $_)));
499 }
500
501 =func generate_uuid
502
503 $uuid = generate_uuid;
504 $uuid = generate_uuid(\%set);
505 $uuid = generate_uuid(\&test_uuid);
506
507 Generate a new random UUID. It's pretty unlikely that this will generate a repeat, but if you're worried about
508 that you can provide either a set of existing UUIDs (as a hashref where the keys are the elements of a set) or
509 a function to check for existing UUIDs, and this will be sure to not return a UUID already in provided set.
510 Perhaps an example will make it clear:
511
512 my %uuid_set = (
513 uuid('12345678-9ABC-DEFG-1234-56789ABCDEFG') => 'whatever',
514 );
515 $uuid = generate_uuid(\%uuid_set);
516 # OR
517 $uuid = generate_uuid(sub { !$uuid_set{$_} });
518
519 Here, C<$uuid> can't be "12345678-9ABC-DEFG-1234-56789ABCDEFG". This example uses L</uuid> to easily pack
520 a 16-byte UUID from a literal, but it otherwise is not a consequential part of the example.
521
522 =cut
523
524 sub generate_uuid {
525 my $set = @_ % 2 == 1 ? shift : undef;
526 my %args = @_;
527 my $test = $set //= $args{test};
528 $test = sub { !$set->{$_} } if is_hashref($test);
529 $test //= sub { 1 };
530 my $printable = $args{printable} // $args{print};
531 local $_ = '';
532 do {
533 $_ = $printable ? random_string(16) : random_bytes(16);
534 } while (!$test->($_));
535 return $_;
536 }
537
538 =func gunzip
539
540 $unzipped = gunzip($string);
541
542 Decompress an octet stream.
543
544 =cut
545
546 sub gunzip {
547 load_optional('Compress::Raw::Zlib');
548 local $_ = shift;
549 my ($i, $status) = Compress::Raw::Zlib::Inflate->new(-WindowBits => 31);
550 $status == Compress::Raw::Zlib::Z_OK()
551 or throw 'Failed to initialize compression library', status => $status;
552 $status = $i->inflate($_, my $out);
553 $status == Compress::Raw::Zlib::Z_STREAM_END()
554 or throw 'Failed to decompress data', status => $status;
555 return $out;
556 }
557
558 =func gzip
559
560 $zipped = gzip($string);
561
562 Compress an octet stream.
563
564 =cut
565
566 sub gzip {
567 load_optional('Compress::Raw::Zlib');
568 local $_ = shift;
569 my ($d, $status) = Compress::Raw::Zlib::Deflate->new(-WindowBits => 31, -AppendOutput => 1);
570 $status == Compress::Raw::Zlib::Z_OK()
571 or throw 'Failed to initialize compression library', status => $status;
572 $status = $d->deflate($_, my $out);
573 $status == Compress::Raw::Zlib::Z_OK()
574 or throw 'Failed to compress data', status => $status;
575 $status = $d->flush($out);
576 $status == Compress::Raw::Zlib::Z_OK()
577 or throw 'Failed to compress data', status => $status;
578 return $out;
579 }
580
581 =func is_readable
582
583 =func is_writable
584
585 $bool = is_readable($mode);
586 $bool = is_writable($mode);
587
588 Determine of an C<fopen>-style mode is readable, writable or both.
589
590 =cut
591
592 sub is_readable { $_[0] !~ /^[aw]b?$/ }
593 sub is_writable { $_[0] !~ /^rb?$/ }
594
595 =func is_uuid
596
597 $bool = is_uuid($thing);
598
599 Check if a thing is a UUID (i.e. scalar string of length 16).
600
601 =cut
602
603 sub is_uuid { defined $_[0] && !is_ref($_[0]) && length($_[0]) == 16 }
604
605 =func list_attributes
606
607 @attributes = list_attributes($package);
608
609 Get a list of attributes for a class.
610
611 =cut
612
613 sub list_attributes {
614 my $package = shift;
615 return @{$ATTRIBUTES{$package} // []};
616 }
617
618 =func load_optional
619
620 $package = load_optional($package);
621
622 Load a module that isn't required but can provide extra functionality. Throw if the module is not available.
623
624 =cut
625
626 sub load_optional {
627 for my $module (@_) {
628 eval { load $module };
629 if (my $err = $@) {
630 throw "Missing dependency: Please install $module to use this feature.\n",
631 module => $module,
632 error => $err;
633 }
634 }
635 return wantarray ? @_ : $_[0];
636 }
637
638 =func memoize
639
640 \&memoized_code = memoize(\&code, ...);
641
642 Memoize a function. Extra arguments are passed through to C<&code> when it is called.
643
644 =cut
645
646 sub memoize {
647 my $func = shift;
648 my @args = @_;
649 my %cache;
650 return sub { $cache{join("\0", grep { defined } @_)} //= $func->(@args, @_) };
651 }
652
653 =func pad_pkcs7
654
655 $padded_string = pad_pkcs7($string, $block_size),
656
657 Pad a block using the PKCS#7 method.
658
659 =cut
660
661 sub pad_pkcs7 {
662 my $data = shift // throw 'Must provide a string to pad';
663 my $size = shift or throw 'Must provide block size';
664
665 0 <= $size && $size < 256
666 or throw 'Cannot add PKCS7 padding to a large block size', size => $size;
667
668 my $pad_len = $size - length($data) % $size;
669 $data .= chr($pad_len) x $pad_len;
670 }
671
672 =func query
673
674 $query = query(@where);
675 $query->(\%data);
676
677 Generate a function that will run a series of tests on a passed hashref and return true or false depending on
678 if the data record in the hash matched the specified logic.
679
680 The logic can be specified in a manner similar to L<SQL::Abstract/"WHERE CLAUSES"> which was the inspiration
681 for this function, but this code is distinct, supporting an overlapping but not identical feature set and
682 having its own bugs.
683
684 See L<File::KDBX/QUERY> for examples.
685
686 =cut
687
688 sub query { _query(undef, '-or', \@_) }
689
690 =func query_any
691
692 Get either a L</query> or L</simple_expression_query>, depending on the arguments.
693
694 =cut
695
696 sub query_any {
697 my $code = shift;
698
699 if (is_coderef($code) || overload::Method($code, '&{}')) {
700 return $code;
701 }
702 elsif (is_scalarref($code)) {
703 return simple_expression_query($$code, @_);
704 }
705 else {
706 return query($code, @_);
707 }
708 }
709
710 =func read_all
711
712 $size = read_all($fh, my $buffer, $size);
713 $size = read_all($fh, my $buffer, $size, $offset);
714
715 Like L<functions/read> but returns C<undef> if not all C<$size> bytes are read. This is considered an error,
716 distinguishable from other errors by C<$!> not being set.
717
718 =cut
719
720 sub read_all($$$;$) { ## no critic (ProhibitSubroutinePrototypes)
721 my $result = @_ == 3 ? read($_[0], $_[1], $_[2])
722 : read($_[0], $_[1], $_[2], $_[3]);
723 return if !defined $result;
724 return if $result != $_[2];
725 return $result;
726 }
727
728 =func recurse_limit
729
730 \&limited_code = recurse_limit(\&code);
731 \&limited_code = recurse_limit(\&code, $max_depth);
732 \&limited_code = recurse_limit(\&code, $max_depth, \&error_handler);
733
734 Wrap a function with a guard to prevent deep recursion.
735
736 =cut
737
738 sub recurse_limit {
739 my $func = shift;
740 my $max_depth = shift // 200;
741 my $error = shift // sub {};
742 my $depth = 0;
743 return sub { return $error->(@_) if $max_depth < ++$depth; $func->(@_) };
744 };
745
746 =func search
747
748 # Generate a query on-the-fly:
749 \@matches = search(\@records, @where);
750
751 # Use a pre-compiled query:
752 $query = query(@where);
753 \@matches = search(\@records, $query);
754
755 # Use a simple expression:
756 \@matches = search(\@records, \'query terms', @fields);
757 \@matches = search(\@records, \'query terms', $operator, @fields);
758
759 # Use your own subroutine:
760 \@matches = search(\@records, \&query);
761 \@matches = search(\@records, sub { $record = shift; ... });
762
763 Execute a linear search over an array of records using a L</query>. A "record" is usually a hash.
764
765 =cut
766
767 sub search {
768 my $list = shift;
769 my $query = query_any(@_);
770
771 my @match;
772 for my $item (@$list) {
773 push @match, $item if $query->($item);
774 }
775 return \@match;
776 }
777
778 =func simple_expression_query
779
780 $query = simple_expression_query($expression, @fields);
781 $query = simple_expression_query($expression, $operator, @fields);
782
783 Generate a query, like L</query>, to be used with L</search> but built from a "simple expression" as
784 L<described here|https://keepass.info/help/base/search.html#mode_se>.
785
786 An expression is a string with one or more space-separated terms. Terms with spaces can be enclosed in double
787 quotes. Terms are negated if they are prefixed with a minus sign. A record must match every term on at least
788 one of the given fields.
789
790 =cut
791
792 sub simple_expression_query {
793 my $expr = shift;
794 my $op = @_ && ($OPS{$_[0] || ''} || 0) == 2 ? shift : '=~';
795
796 my $neg_op = $OP_NEG{$op};
797 my $is_re = $op eq '=~' || $op eq '!~';
798
799 require Text::ParseWords;
800 my @terms = Text::ParseWords::shellwords($expr);
801
802 my @query = qw(-and);
803
804 for my $term (@terms) {
805 my @subquery = qw(-or);
806
807 my $neg = $term =~ s/^-//;
808 my $condition = [($neg ? $neg_op : $op) => ($is_re ? qr/\Q$term\E/i : $term)];
809
810 for my $field (@_) {
811 push @subquery, $field => $condition;
812 }
813
814 push @query, \@subquery;
815 }
816
817 return query(\@query);
818 }
819
820 =func snakify
821
822 $string = snakify($string);
823
824 Turn a CamelCase string into snake_case.
825
826 =cut
827
828 sub snakify {
829 local $_ = shift;
830 s/UserName/Username/g;
831 s/([a-z])([A-Z0-9])/${1}_${2}/g;
832 s/([A-Z0-9]+)([A-Z0-9])(?![A-Z0-9]|$)/${1}_${2}/g;
833 return lc($_);
834 }
835
836 =func split_url
837
838 ($scheme, $auth, $host, $port, $path, $query, $hash, $usename, $password) = split_url($url);
839
840 Split a URL into its parts.
841
842 For example, C<http://user:pass@localhost:4000/path?query#hash> gets split like:
843
844 =for :list
845 * C<http>
846 * C<user:pass>
847 * C<host>
848 * C<4000>
849 * C</path>
850 * C<?query>
851 * C<#hash>
852 * C<user>
853 * C<pass>
854
855 =cut
856
857 sub split_url {
858 local $_ = shift;
859 my ($scheme, $auth, $host, $port, $path, $query, $hash) =~ m!
860 ^([^:/\?\#]+) ://
861 (?:([^\@]+)\@)
862 ([^:/\?\#]*)
863 (?::(\d+))?
864 ([^\?\#]*)
865 (\?[^\#]*)?
866 (\#(.*))?
867 !x;
868
869 $scheme = lc($scheme);
870
871 $host ||= 'localhost';
872 $host = lc($host);
873
874 $path = "/$path" if $path !~ m!^/!;
875
876 $port ||= $scheme eq 'http' ? 80 : $scheme eq 'https' ? 433 : undef;
877
878 my ($username, $password) = split($auth, ':', 2);
879
880 return ($scheme, $auth, $host, $port, $path, $query, $hash, $username, $password);
881 }
882
883 =func to_bool
884
885 =func to_number
886
887 =func to_string
888
889 =func to_time
890
891 =func to_tristate
892
893 =func to_uuid
894
895 Various typecasting / coercive functions.
896
897 =cut
898
899 sub to_bool { $_[0] // return; boolean($_[0]) }
900 sub to_number { $_[0] // return; 0+$_[0] }
901 sub to_string { $_[0] // return; "$_[0]" }
902 sub to_time {
903 $_[0] // return;
904 return gmtime($_[0]) if looks_like_number($_[0]);
905 return Time::Piece->strptime($_[0], '%Y-%m-%d %H:%M:%S') if !blessed $_[0];
906 return $_[0];
907 }
908 sub to_tristate { $_[0] // return; boolean($_[0]) }
909 sub to_uuid {
910 my $str = to_string(@_) // return;
911 return sprintf('%016s', $str) if length($str) < 16;
912 return substr($str, 0, 16) if 16 < length($str);
913 return $str;
914 }
915
916 =func trim
917
918 $string = trim($string);
919
920 The ubiquitous C<trim> function. Removes all whitespace from both ends of a string.
921
922 =cut
923
924 sub trim($) { ## no critic (ProhibitSubroutinePrototypes)
925 local $_ = shift // return;
926 s/^\s*//;
927 s/\s*$//;
928 return $_;
929 }
930
931 =func try_load_optional
932
933 $package = try_load_optional($package);
934
935 Try to load a module that isn't required but can provide extra functionality, and return true if successful.
936
937 =cut
938
939 sub try_load_optional {
940 for my $module (@_) {
941 eval { load $module };
942 if (my $err = $@) {
943 warn $err if 3 <= DEBUG;
944 return;
945 }
946 }
947 return @_;
948 }
949
950 =func uri_escape_utf8
951
952 $string = uri_escape_utf8($string);
953
954 Percent-encode arbitrary text strings, like for a URI.
955
956 =cut
957
958 my %ESC = map { chr($_) => sprintf('%%%02X', $_) } 0..255;
959 sub uri_escape_utf8 {
960 local $_ = shift // return;
961 $_ = encode('UTF-8', $_);
962 # RFC 3986 section 2.3 unreserved characters
963 s/([^A-Za-z0-9\-\._~])/$ESC{$1}/ge;
964 return $_;
965 }
966
967 =func uri_unescape_utf8
968
969 $string = uri_unescape_utf8($string);
970
971 Inverse of L</uri_escape_utf8>.
972
973 =cut
974
975 sub uri_unescape_utf8 {
976 local $_ = shift // return;
977 s/\%([A-Fa-f0-9]{2})/chr(hex($1))/;
978 return decode('UTF-8', $_);
979 }
980
981 =func uuid
982
983 $raw_uuid = uuid($string_uuid);
984
985 Pack a 128-bit UUID (given as a hexidecimal string with optional C<->'s, like
986 C<12345678-9ABC-DEFG-1234-56789ABCDEFG>) into a string of exactly 16 octets.
987
988 This is the inverse of L</format_uuid>.
989
990 =cut
991
992 sub uuid {
993 local $_ = shift // return "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
994 s/-//g;
995 /^[A-Fa-f0-9]{32}$/ or throw 'Must provide a formatted 128-bit UUID';
996 return pack('H32', $_);
997
998 }
999
1000 =func UUID_NULL
1001
1002 Get the null UUID (i.e. string of 16 null bytes).
1003
1004 =cut
1005
1006 sub UUID_NULL() { "\0" x 16 }
1007
1008 ### --------------------------------------------------------------------------
1009
1010 # Determine if an array looks like keypairs from a hash.
1011 sub _looks_like_keypairs {
1012 my $arr = shift;
1013 return 0 if @$arr % 2 == 1;
1014 for (my $i = 0; $i < @$arr; $i += 2) {
1015 return 0 if is_ref($arr->[$i]);
1016 }
1017 return 1;
1018 }
1019
1020 sub _is_operand_plain {
1021 local $_ = shift;
1022 return !(is_hashref($_) || is_arrayref($_));
1023 }
1024
1025 sub _query {
1026 # dumper \@_;
1027 my $subject = shift;
1028 my $op = shift // throw 'Must specify a query operator';
1029 my $operand = shift;
1030
1031 return _query_simple($op, $subject) if defined $subject && !is_ref($op) && ($OPS{$subject} || 2) < 2;
1032 return _query_simple($subject, $op, $operand) if _is_operand_plain($operand);
1033 return _query_inverse(_query($subject, '-or', $operand)) if $op eq '-not' || $op eq '-false';
1034 return _query($subject, '-and', [%$operand]) if is_hashref($operand);
1035
1036 my @queries;
1037
1038 my @atoms = @$operand;
1039 while (@atoms) {
1040 if (_looks_like_keypairs(\@atoms)) {
1041 my ($atom, $operand) = splice @atoms, 0, 2;
1042 if (my $op_type = $OPS{$atom}) {
1043 if ($op_type == 1 && _is_operand_plain($operand)) { # unary
1044 push @queries, _query_simple($operand, $atom);
1045 }
1046 else {
1047 push @queries, _query($subject, $atom, $operand);
1048 }
1049 }
1050 elsif (!is_ref($atom)) {
1051 push @queries, _query($atom, 'eq', $operand);
1052 }
1053 }
1054 else {
1055 my $atom = shift @atoms;
1056 if ($OPS{$atom}) { # apply new operator over the rest
1057 push @queries, _query($subject, $atom, \@atoms);
1058 last;
1059 }
1060 else { # apply original operator over this one
1061 push @queries, _query($subject, $op, $atom);
1062 }
1063 }
1064 }
1065
1066 if (@queries == 1) {
1067 return $queries[0];
1068 }
1069 elsif ($op eq '-and') {
1070 return _query_all(@queries);
1071 }
1072 elsif ($op eq '-or') {
1073 return _query_any(@queries);
1074 }
1075 throw 'Malformed query';
1076 }
1077
1078 sub _query_simple {
1079 my $subject = shift;
1080 my $op = shift // 'eq';
1081 my $operand = shift;
1082
1083 # these special operators can also act as simple operators
1084 $op = '!!' if $op eq '-true';
1085 $op = '!' if $op eq '-false';
1086 $op = '!' if $op eq '-not';
1087
1088 defined $subject or throw 'Subject is not set in query';
1089 $OPS{$op} >= 0 or throw 'Cannot use a non-simple operator in a simple query';
1090 if (empty($operand)) {
1091 if ($OPS{$op} < 2) {
1092 # no operand needed
1093 }
1094 # Allow field => undef and field => {'ne' => undef} to do the (arguably) right thing.
1095 elsif ($op eq 'eq' || $op eq '==') {
1096 $op = '-empty';
1097 }
1098 elsif ($op eq 'ne' || $op eq '!=') {
1099 $op = '-nonempty';
1100 }
1101 else {
1102 throw 'Operand is required';
1103 }
1104 }
1105
1106 my $field = sub { blessed $_[0] && $_[0]->can($subject) ? $_[0]->$subject : $_[0]->{$subject} };
1107
1108 my %map = (
1109 'eq' => sub { local $_ = $field->(@_); defined && $_ eq $operand },
1110 'ne' => sub { local $_ = $field->(@_); defined && $_ ne $operand },
1111 'lt' => sub { local $_ = $field->(@_); defined && $_ lt $operand },
1112 'gt' => sub { local $_ = $field->(@_); defined && $_ gt $operand },
1113 'le' => sub { local $_ = $field->(@_); defined && $_ le $operand },
1114 'ge' => sub { local $_ = $field->(@_); defined && $_ ge $operand },
1115 '==' => sub { local $_ = $field->(@_); defined && $_ == $operand },
1116 '!=' => sub { local $_ = $field->(@_); defined && $_ != $operand },
1117 '<' => sub { local $_ = $field->(@_); defined && $_ < $operand },
1118 '>' => sub { local $_ = $field->(@_); defined && $_ > $operand },
1119 '<=' => sub { local $_ = $field->(@_); defined && $_ <= $operand },
1120 '>=' => sub { local $_ = $field->(@_); defined && $_ >= $operand },
1121 '=~' => sub { local $_ = $field->(@_); defined && $_ =~ $operand },
1122 '!~' => sub { local $_ = $field->(@_); defined && $_ !~ $operand },
1123 '!' => sub { local $_ = $field->(@_); ! $_ },
1124 '!!' => sub { local $_ = $field->(@_); !!$_ },
1125 '-defined' => sub { local $_ = $field->(@_); defined $_ },
1126 '-undef' => sub { local $_ = $field->(@_); !defined $_ },
1127 '-nonempty' => sub { local $_ = $field->(@_); nonempty $_ },
1128 '-empty' => sub { local $_ = $field->(@_); empty $_ },
1129 );
1130
1131 return $map{$op} // throw "Unexpected operator in query: $op",
1132 subject => $subject,
1133 operator => $op,
1134 operand => $operand;
1135 }
1136
1137 sub _query_inverse {
1138 my $query = shift;
1139 return sub { !$query->(@_) };
1140 }
1141
1142 sub _query_all {
1143 my @queries = @_;
1144 return sub {
1145 my $val = shift;
1146 all { $_->($val) } @queries;
1147 };
1148 }
1149
1150 sub _query_any {
1151 my @queries = @_;
1152 return sub {
1153 my $val = shift;
1154 any { $_->($val) } @queries;
1155 };
1156 }
1157
1158 1;
This page took 0.111556 seconds and 4 git commands to generate.