1 package File
::KDBX
::Object
;
2 # ABSTRACT: A KDBX database object
7 use Devel
::GlobalDestruction
;
9 use File
::KDBX
::Util
qw(:uuid);
10 use Hash
::Util
::FieldHash
qw(fieldhashes);
11 use List
::Util
qw(first);
12 use Ref
::Util
qw(is_arrayref is_plain_arrayref is_plain_hashref is_ref);
13 use Scalar
::Util
qw(blessed weaken);
16 our $VERSION = '999.999'; # VERSION
18 fieldhashes \
my (%KDBX, %PARENT, %TXNS, %REFS, %SIGNALS);
22 $object = File
::KDBX
::Object-
>new;
23 $object = File
::KDBX
::Object-
>new(%attributes);
24 $object = File
::KDBX
::Object-
>new(\
%data);
25 $object = File
::KDBX
::Object-
>new(\
%data, $kdbx);
27 Construct a new KDBX object
.
29 There
is a subtlety to
take note of
. There
is a significant difference between
:
31 File
::KDBX
::Entry-
>new(username
=> 'iambatman');
35 File
::KDBX
::Entry-
>new({username
=> 'iambatman'}); # WRONG
37 In the first
, an empty object
is first created
and then initialized with whatever I
<attributes
> are
given. In
38 the second
, a hashref
is blessed
and essentially becomes the object
. The significance
is that the hashref
39 key-value pairs will remain as-is so the structure
is expected to adhere to the shape of a raw B
<Object
>
40 (which varies based on the type of object
), whereas with the first the attributes will set the structure
in
41 the correct way
(just like using the object accessors
/ getters / setters
).
43 The second example isn
't I<generally> wrong -- this type of construction is supported for a reason, to allow
44 for working with KDBX objects at a low level -- but it is wrong in this specific case only because
45 C<< {username => $str} >> isn't a valid raw KDBX entry object
. The L
</username
> attribute
is really a proxy
46 for the C
<UserName
> string
, so the equivalent raw entry object should be
47 C
<< {strings
=> {UserName
=> {value
=> $str}}} >>. These are roughly equivalent
:
49 File
::KDBX
::Entry-
>new(username
=> 'iambatman');
50 File
::KDBX
::Entry-
>new({strings
=> {UserName
=> {value
=> 'iambatman'}}});
52 If this explanation went over your head
, that
's fine. Just stick with the attributes since they are typically
53 easier to use correctly and provide the most convenience. If in the future you think of some kind of KDBX
54 object manipulation you want to do that isn't supported by the accessors
and methods
, just know you I
<can
>
55 access an object
's data directly.
63 return $_[0]->clone if @_ == 1 && blessed $_[0] && $_[0]->isa($class);
66 $data = shift if is_plain_hashref($_[0]);
69 $kdbx = shift if @_ % 2 == 1;
72 $args{kdbx} //= $kdbx if defined $kdbx;
74 my $self = bless $data // {}, $class;
76 $self->_set_nonlazy_attributes if !$data;
80 sub _set_nonlazy_attributes { die 'Not implemented
' }
84 $object = $object->init(%attributes);
86 Called by the constructor to set attributes. You normally should not call this.
94 while (my ($key, $val) = each %args) {
95 if (my $method = $self->can($key)) {
105 $object = File::KDBX::Object->wrap($object);
107 Ensure that a KDBX object is blessed.
114 return $object if blessed $object && $object->isa($class);
115 return $class->new(@_, @$object) if is_arrayref($object);
116 return $class->new($object, @_);
121 $label = $object->label;
122 $object->label($label);
124 Get or set the object's label
, a text string that can act as a non-unique identifier
. For an entry
, the label
125 is its title string
. For a group
, the label
is its name
.
129 sub label
{ die 'Not implemented' }
133 $object_copy = $object->clone;
134 $object_copy = File
::KDBX
::Object-
>new($object);
136 Make a clone of an object
. By
default the clone
is indeed an exact copy that
is associated with the same
137 database but
not actually included
in the object tree
(i
.e
. it
has no parent
). Some options are allowed to
138 get different effects
:
141 * C<new_uuid> - If set, generate a new UUID for the copy (default: false)
142 * C<parent> - If set, add the copy to the same parent group, if any (default: false)
143 * C<relabel> - If set, append " - Copy" to the object's title or name (default: false)
144 * C<entries> - If set, copy child entries, if any (default: true)
145 * C<groups> - If set, copy child groups, if any (default: true)
146 * C<history> - If set, copy entry history, if any (default: true)
147 * C<reference_password> - Toggle whether or not cloned entry's Password string should be set as a field
148 reference to the original entry's Password string (default: false)
149 * C<reference_username> - Toggle whether or not cloned entry's UserName string should be set as a field
150 reference to the original entry's UserName string (default: false)
154 my %CLONE = (entries
=> 1, groups
=> 1, history
=> 1);
159 local $CLONE{new_uuid
} = $args{new_uuid
} // $args{parent
} // 0;
160 local $CLONE{entries
} = $args{entries
} // 1;
161 local $CLONE{groups
} = $args{groups
} // 1;
162 local $CLONE{history
} = $args{history
} // 1;
163 local $CLONE{reference_password
} = $args{reference_password
} // 0;
164 local $CLONE{reference_username
} = $args{reference_username
} // 0;
167 my $copy = Storable
::dclone
($self);
169 if ($args{relabel
} and my $label = $self->label) {
170 $copy->label("$label - Copy");
172 if ($args{parent
} and my $parent = $self->parent) {
173 $parent->add_object($copy);
179 sub STORABLE_freeze
{
184 delete $copy->{entries
} if !$CLONE{entries
};
185 delete $copy->{groups
} if !$CLONE{groups
};
186 delete $copy->{history
} if !$CLONE{history
};
188 return ($cloning ? Hash
::Util
::FieldHash
::id
($self) : ''), $copy;
197 @$self{keys %$copy} = values %$copy;
200 my $kdbx = $KDBX{$addr};
201 $self->kdbx($kdbx) if $kdbx;
204 if (defined $self->{uuid
}) {
205 if (($CLONE{reference_password
} || $CLONE{reference_username
}) && $self->can('strings')) {
206 my $uuid = format_uuid
($self->{uuid
});
208 local $CLONE{new_uuid
} = 0;
209 local $CLONE{entries
} = 1;
210 local $CLONE{groups
} = 1;
211 local $CLONE{history
} = 1;
212 local $CLONE{reference_password
} = 0;
213 local $CLONE{reference_username
} = 0;
214 # Clone only the entry's data and manually bless to avoid infinite recursion.
215 bless Storable
::dclone
({%$copy}), 'File::KDBX::Entry';
217 my $txn = $self->begin_work(snapshot
=> $clone_obj);
218 if ($CLONE{reference_password
}) {
219 $self->password("{REF:P\@I:$uuid}");
221 if ($CLONE{reference_username
}) {
222 $self->username("{REF:U\@I:$uuid}");
226 $self->uuid(generate_uuid
) if $CLONE{new_uuid
};
229 # Dualvars aren't cloned as dualvars, so dualify the icon.
230 $self->icon_id($self->{icon_id
}) if defined $self->{icon_id
};
235 $kdbx = $object->kdbx;
236 $object->kdbx($kdbx);
238 Get
or set the L
<File
::KDBX
> instance associated with this object
.
244 $self = $self->new if !ref $self;
246 if (my $kdbx = shift) {
247 $KDBX{$self} = $kdbx;
254 $KDBX{$self} or throw
'Object is disassociated from a KDBX database', object
=> $self;
259 $string_uuid = $object->id;
260 $string_uuid = $object->id($delimiter);
262 Get the unique identifier
for this object as a B
<formatted
> UUID string
, typically
for display purposes
. You
263 could
use this to compare with other identifiers formatted with the same delimiter
, but it
is more efficient
264 to
use the raw UUID
for that purpose
(see L
</uuid
>).
266 A delimiter can optionally be provided to
break up the UUID string visually
. See
267 L
<File
::KDBX
::Util
/format_uuid
>.
271 sub id
{ format_uuid
(shift-
>uuid, @_) }
277 $group = $object->group;
279 $group = $object->parent;
281 Get the parent group to which an object belongs
or C
<undef> if it belongs to
no group
.
287 my $id = Hash
::Util
::FieldHash
::id
($self);
288 if (my $group = $PARENT{$self}) {
289 my $method = $self->_parent_container;
290 return $group if first
{ $id == Hash
::Util
::FieldHash
::id
($_) } @{$group->$method};
291 delete $PARENT{$self};
293 # always get lineage from root to leaf because the other way requires parent, so it would be recursive
294 my $lineage = $self->kdbx->_trace_lineage($self) or return;
295 my $group = pop @$lineage or return;
296 $PARENT{$self} = $group; weaken
$PARENT{$self};
300 sub parent
{ shift-
>group(@_) }
304 if (my $parent = shift) {
305 $PARENT{$self} = $parent;
306 weaken
$PARENT{$self};
309 delete $PARENT{$self};
314 ### Name of the parent attribute expected to contain the object
315 sub _parent_container
{ die 'Not implemented' }
319 \
@lineage = $object->lineage;
320 \
@lineage = $object->lineage($base_group);
322 Get the direct line of ancestors from C
<$base_group> (default: the root group
) to an object
. The lineage
323 includes the base group but I
<not> the target object
. Returns C
<undef> if the target
is not in the database
324 structure
. Returns an empty arrayref
is the object itself
is a root group
.
332 my $base_addr = $base ? Hash
::Util
::FieldHash
::id
($base) : 0;
337 while ($o = $o->parent) {
339 last if $base_addr == Hash
::Util
::FieldHash
::id
($o);
341 return \
@path if @path && ($base_addr == Hash
::Util
::FieldHash
::id
($path[0]) || $path[0]->is_root);
344 return $self->kdbx->_trace_lineage($self, $base);
349 $object = $object->remove;
351 Remove the object from the database
. If the object
is a group
, all contained objects are removed as well
.
356 # TODO - need a way to not signal database because there are times like in the KDB loader and meta streams
357 # where we do not want to add UUIDs to deleted objects
359 my $parent = $self->parent;
360 $parent->remove_object($self) if $parent;
366 @tags = $entry->tag_list;
368 Get a list of tags
, split from L
</tag
> using delimiters C
<,>, C
<.>, C
<:>, C
<;> and whitespace
.
374 return grep { $_ ne '' } split(/[,\.:;]|\s+/, trim
($self->tags) // '');
379 $image_data = $object->custom_icon;
380 $image_data = $object->custom_icon($image_data, %attributes);
382 Get
or set an icon image
. Returns C
<undef> if there
is no custom icon set
. Setting a custom icon will change
383 the L
</custom_icon_uuid
> attribute
.
385 Custom icon attributes
(supported
in KDBX4
.1
and greater
):
388 * C<name> - Name of the icon (text)
389 * C<last_modification_time> - Just what it says (datetime)
395 my $kdbx = $self->kdbx;
398 my $uuid = defined $img ? $kdbx->add_custom_icon($img, @_) : undef;
399 $self->icon_id(0) if $uuid;
400 $self->custom_icon_uuid($uuid);
403 return $kdbx->custom_icon_data($self->custom_icon_uuid);
408 \
%all_data = $object->custom_data;
409 $object->custom_data(\
%all_data);
411 \
%data = $object->custom_data($key);
412 $object->custom_data($key => \
%data);
413 $object->custom_data(%data);
414 $object->custom_data(key
=> $value, %data);
416 Get
and set custom data
. Custom data
is metadata associated with an object
.
418 Each data item can have a few attributes associated with it
.
421 * C<key> - A unique text string identifier used to look up the data item (required)
422 * C<value> - A text string value (required)
423 * C<last_modification_time> (optional, KDBX4.1+)
429 $self->{custom_data
} = shift if @_ == 1 && is_plain_hashref
($_[0]);
430 return $self->{custom_data
} //= {} if !@_;
432 my %args = @_ == 2 ? (key
=> shift, value
=> shift)
433 : @_ % 2 == 1 ? (key
=> shift, @_) : @_;
435 if (!$args{key
} && !$args{value
}) {
436 my %standard = (key
=> 1, value
=> 1, last_modification_time
=> 1);
437 my @other_keys = grep { !$standard{$_} } keys %args;
438 if (@other_keys == 1) {
439 my $key = $args{key
} = $other_keys[0];
440 $args{value
} = delete $args{$key};
444 my $key = $args{key
} or throw
'Must provide a custom_data key to access';
446 return $self->{custom_data
}{$key} = $args{value
} if is_plain_hashref
($args{value
});
448 while (my ($field, $value) = each %args) {
449 $self->{custom_data
}{$key}{$field} = $value;
451 return $self->{custom_data
}{$key};
454 =method custom_data_value
456 $value = $object->custom_data_value($key);
458 Exactly the same as L
</custom_data
> except returns just the custom data
's value rather than a structure of
459 attributes. This is a shortcut for:
461 my $data = $object->custom_data($key);
462 my $value = defined $data ? $data->{value} : undef;
466 sub custom_data_value {
468 my $data = $self->custom_data(@_) // return undef;
469 return $data->{value};
472 ##############################################################################
476 $txn = $object->begin_work(%options);
477 $object->begin_work(%options);
479 Begin a new transaction. Returns a L<File::KDBX::Transaction> object that can be scoped to ensure a rollback
480 occurs if exceptions are thrown. Alternatively, if called in void context, there will be no
481 B<File::KDBX::Transaction> and it is instead your responsibility to call L</commit> or L</rollback> as
482 appropriate. It is undefined behavior to call these if a B<File::KDBX::Transaction> exists. Recursive
483 transactions are allowed.
485 Signals created during a transaction are delayed until all transactions are resolved. If the outermost
486 transaction is committed, then the signals are de-duplicated and delivered. Otherwise the signals are dropped.
487 This means that the KDBX database will not fix broken references or mark itself dirty until after the
488 transaction is committed.
490 How it works: With the beginning of a transaction, a snapshot of the object is created. In the event of
491 a rollback, the object's data
is replaced with data from the snapshot
.
493 By
default, the snapshot
is shallow
(i
.e
. does not include subroups
, entries
or historical entries
). This
494 means that only modifications to the object itself
(its data
, fields
, strings
, etc
.) are atomic
; modifications
495 to subroups etc
., including adding
or removing items
, are auto-committed instantly
and will persist regardless
496 of the result of the pending transaction
. You can override this
for groups
, entries
and history independently
500 * C<entries> - If set, snapshot entries within a group, deeply (default: false)
501 * C<groups> - If set, snapshot subroups within a group, deeply (default: false)
502 * C<history> - If set, snapshot historical entries within an entry (default: false)
504 For example, if you begin a transaction on a group object using the C<entries> option, like this:
506 $group->begin_work(entries => 1);
508 Then if you modify any of the group's entries OR add new entries OR delete entries, all of that will be undone
509 if the transaction is rolled back. With a default-configured transaction, however, changes to entries are kept
510 even if the transaction is rolled back.
517 if (defined wantarray) {
518 require File
::KDBX
::Transaction
;
519 return File
::KDBX
::Transaction-
>new($self, @_);
523 my $orig = $args{snapshot
} // do {
524 my $c = $self->clone(
525 entries
=> $args{entries
} // 0,
526 groups
=> $args{groups
} // 0,
527 history
=> $args{history
} // 0,
529 $c->{entries
} = $self->{entries
} if !$args{entries
};
530 $c->{groups
} = $self->{groups
} if !$args{groups
};
531 $c->{history
} = $self->{history
} if !$args{history
};
535 my $id = Hash
::Util
::FieldHash
::id
($orig);
536 _save_references
($id, $self, $orig);
538 $self->_signal_begin_work;
540 push @{$self->_txns}, $orig;
547 Commit a transaction
, making updates to C
<$object> permanent
. Returns itself to allow
method chaining
.
553 my $orig = pop @{$self->_txns} or return $self;
554 $self->_commit($orig);
555 my $signals = $self->_signal_commit;
556 $self->_signal_send($signals) if !$self->_in_txn;
564 Roll back the most recent transaction
, throwing away any updates to the L
</object
> made since the transaction
565 began
. Returns itself to allow
method chaining
.
572 my $orig = pop @{$self->_txns} or return $self;
574 my $id = Hash
::Util
::FieldHash
::id
($orig);
575 _restore_references
($id, $orig);
577 $self->_signal_rollback;
582 # Get whether or not there is at least one pending transaction.
583 sub _in_txn
{ scalar @{$_[0]->_txns} }
585 # Get an array ref of pending transactions.
586 sub _txns
{ $TXNS{$_[0]} //= [] }
588 # The _commit hook notifies subclasses that a commit has occurred.
589 sub _commit
{ die 'Not implemented' }
591 # Get a reference to an object that represents an object's committed state. If there is no pending
592 # transaction, this is just $self. If there is a transaction, this is the snapshot take before the transaction
593 # began. This method is private because it provides direct access to the actual snapshot. It is important that
594 # the snapshot not be changed or a rollback would roll back to an altered state.
595 # This is used by File::KDBX::Dumper::XML so as to not dump uncommitted changes.
598 my ($orig) = @{$self->_txns};
599 return $orig // $self;
602 # In addition to cloning an object when beginning work, we also keep track its hashrefs and arrayrefs
603 # internally so that we can restore to the very same structures in the case of a rollback.
604 sub _save_references
{
609 if (is_plain_arrayref
($orig)) {
610 for (my $i = 0; $i < @$orig; ++$i) {
611 _save_references
($id, $self->[$i], $orig->[$i]);
613 $REFS{$id}{Hash
::Util
::FieldHash
::id
($orig)} = $self;
615 elsif (is_plain_hashref
($orig) || (blessed
$orig && $orig->isa(__PACKAGE__
))) {
616 for my $key (keys %$orig) {
617 _save_references
($id, $self->{$key}, $orig->{$key});
619 $REFS{$id}{Hash
::Util
::FieldHash
::id
($orig)} = $self;
623 # During a rollback, copy data from the snapshot back into the original internal structures.
624 sub _restore_references
{
626 my $orig = shift // return;
627 my $self = delete $REFS{$id}{Hash
::Util
::FieldHash
::id
($orig) // ''} // return $orig;
629 if (is_plain_arrayref
($orig)) {
630 @$self = map { _restore_references
($id, $_) } @$orig;
632 elsif (is_plain_hashref
($orig) || (blessed
$orig && $orig->isa(__PACKAGE__
))) {
633 for my $key (keys %$orig) {
634 # next if is_ref($orig->{$key}) &&
635 # (Hash::Util::FieldHash::id($self->{$key}) // 0) == Hash::Util::FieldHash::id($orig->{$key});
636 $self->{$key} = _restore_references
($id, $orig->{$key});
643 ##############################################################################
649 if ($self->_in_txn) {
650 my $stack = $self->_signal_stack;
651 my $queue = $stack->[-1];
652 push @$queue, [$type, @_];
655 $self->_signal_send([[$type, @_]]);
660 sub _signal_stack
{ $SIGNALS{$_[0]} //= [] }
662 sub _signal_begin_work
{
664 push @{$self->_signal_stack}, [];
669 my $signals = pop @{$self->_signal_stack};
670 my $previous = $self->_signal_stack->[-1] // [];
671 push @$previous, @$signals;
675 sub _signal_rollback
{
677 pop @{$self->_signal_stack};
682 my $signals = shift // [];
684 my $kdbx = $KDBX{$self} or return;
686 # de-duplicate, keeping the most recent signal for each type
688 my @signals = grep { !$seen{$_->[0]}++ } reverse @$signals;
690 for my $sig (reverse @signals) {
691 $kdbx->_handle_signal($self, @$sig);
695 ##############################################################################
700 require File
::KDBX
::Group
;
701 return File
::KDBX
::Group-
>wrap($group, $KDBX{$self});
707 require File
::KDBX
::Entry
;
708 return File
::KDBX
::Entry-
>wrap($entry, $KDBX{$self});
711 sub TO_JSON
{ +{%{$_[0]}} }
716 =for Pod::Coverage STORABLE_freeze STORABLE_thaw TO_JSON
720 KDBX is an object database. This abstract class represents an object. You should not use this class directly
721 but instead use its subclasses:
724 * L<File::KDBX::Entry>
725 * L<File::KDBX::Group>
727 There is some functionality shared by both types of objects, and that's what this class provides.
729 Each object can be associated with a L<File::KDBX> database or be disassociated. A disassociated object will
730 not be persisted when dumping a database. It is also possible for an object to be associated with a database
731 but not be part of the object tree (i.e. is not the root group or any subroup or entry). A disassociated
732 object or an object not part of the object tree of a database can be added to a database using one of:
735 * L<File::KDBX/add_entry>
736 * L<File::KDBX/add_group>
737 * L<File::KDBX::Group/add_entry>
738 * L<File::KDBX::Group/add_group>
739 * L<File::KDBX::Entry/add_historical_entry>
741 It is possible to copy or move objects between databases, but B<DO NOT> include the same object in more
742 than one database at once or there could some strange aliasing effects (i.e. changes in one database might
743 effect another in unexpected ways). This could lead to difficult-to-debug problems. It is similarly not safe
744 or valid to add the same object multiple times to the same database. For example:
746 my $entry = File::KDBX::Entry->(title => 'Whatever');
749 $kdbx->add_entry($entry);
750 $another_kdbx->add_entry($entry);
753 $kdbx->add_entry($entry);
754 $kdbx->add_entry($entry); # again
758 # Copy an entry to multiple databases:
759 $kdbx->add_entry($entry);
760 $another_kdbx->add_entry($entry->clone);
762 # OR move an existing entry from one database to another:
763 $kdbx->add_entry($entry->remove);