]> Dogcows Code - chaz/p5-File-KDBX/blob - lib/File/KDBX/Loader.pm
Add recursive transactions
[chaz/p5-File-KDBX] / lib / File / KDBX / Loader.pm
1 package File::KDBX::Loader;
2 # ABSTRACT: Load KDBX files
3
4 use warnings;
5 use strict;
6
7 use File::KDBX::Constants qw(:magic :header :version);
8 use File::KDBX::Error;
9 use File::KDBX::Util qw(:io);
10 use File::KDBX;
11 use IO::Handle;
12 use Module::Load ();
13 use Ref::Util qw(is_ref is_scalarref);
14 use Scalar::Util qw(looks_like_number openhandle);
15 use namespace::clean;
16
17 our $VERSION = '999.999'; # VERSION
18
19 =method new
20
21 $loader = File::KDBX::Loader->new(%attributes);
22
23 Construct a new L<File::KDBX::Loader>.
24
25 =cut
26
27 sub new {
28 my $class = shift;
29 my $self = bless {}, $class;
30 $self->init(@_);
31 }
32
33 =method init
34
35 $loader = $loader->init(%attributes);
36
37 Initialize a L<File::KDBX::Loader> with a new set of attributes.
38
39 This is called by L</new>.
40
41 =cut
42
43 sub init {
44 my $self = shift;
45 my %args = @_;
46
47 @$self{keys %args} = values %args;
48
49 return $self;
50 }
51
52 sub _rebless {
53 my $self = shift;
54 my $format = shift // $self->format;
55
56 my $sig2 = $self->kdbx->sig2;
57 my $version = $self->kdbx->version;
58
59 my $subclass;
60
61 if (defined $format) {
62 $subclass = $format;
63 }
64 elsif (defined $sig2 && $sig2 == KDBX_SIG2_1) {
65 $subclass = 'KDB';
66 }
67 elsif (looks_like_number($version)) {
68 my $major = $version & KDBX_VERSION_MAJOR_MASK;
69 my %subclasses = (
70 KDBX_VERSION_2_0() => 'V3',
71 KDBX_VERSION_3_0() => 'V3',
72 KDBX_VERSION_4_0() => 'V4',
73 );
74 $subclass = $subclasses{$major}
75 or throw sprintf('Unsupported KDBX file version: %x', $version), version => $version;
76 }
77 else {
78 throw sprintf('Unknown file version: %s', $version), version => $version;
79 }
80
81 Module::Load::load "File::KDBX::Loader::$subclass";
82 bless $self, "File::KDBX::Loader::$subclass";
83 }
84
85 =method reset
86
87 $loader = $loader->reset;
88
89 Set a L<File::KDBX::Loader> to a blank state, ready to load another KDBX file.
90
91 =cut
92
93 sub reset {
94 my $self = shift;
95 %$self = ();
96 return $self;
97 }
98
99 =method load
100
101 $kdbx = File::KDBX::Loader->load(\$string, $key);
102 $kdbx = File::KDBX::Loader->load(*IO, $key);
103 $kdbx = File::KDBX::Loader->load($filepath, $key);
104 $kdbx = $loader->load(...); # also instance method
105
106 Load a KDBX file.
107
108 The C<$key> is either a L<File::KDBX::Key> or a primitive that can be converted to a Key object.
109
110 =cut
111
112 sub load {
113 my $self = shift;
114 my $src = shift;
115 return $self->load_handle($src, @_) if openhandle($src) || $src eq '-';
116 return $self->load_string($src, @_) if is_scalarref($src);
117 return $self->load_file($src, @_) if !is_ref($src) && defined $src;
118 throw 'Programmer error: Must pass a stringref, filepath or IO handle to read';
119 }
120
121 =method load_string
122
123 $kdbx = File::KDBX::Loader->load_string($string, $key);
124 $kdbx = File::KDBX::Loader->load_string(\$string, $key);
125 $kdbx = $loader->load_string(...); # also instance method
126
127 Load a KDBX file from a string / memory buffer.
128
129 =cut
130
131 sub load_string {
132 my $self = shift;
133 my $str = shift or throw 'Expected string to load';
134 my %args = @_ % 2 == 0 ? @_ : (key => shift, @_);
135
136 my $key = delete $args{key};
137 $args{kdbx} //= $self->kdbx;
138
139 my $ref = is_scalarref($str) ? $str : \$str;
140
141 open(my $fh, '<', $ref) or throw "Failed to open string buffer: $!";
142
143 $self = $self->new if !ref $self;
144 $self->init(%args, fh => $fh)->_read($fh, $key);
145 return $args{kdbx};
146 }
147
148 =method load_file
149
150 $kdbx = File::KDBX::Loader->load_file($filepath, $key);
151 $kdbx = $loader->load_file(...); # also instance method
152
153 Read a KDBX file from a filesystem.
154
155 =cut
156
157 sub load_file {
158 my $self = shift;
159 my $filepath = shift;
160 my %args = @_ % 2 == 0 ? @_ : (key => shift, @_);
161
162 my $key = delete $args{key};
163 $args{kdbx} //= $self->kdbx;
164
165 open(my $fh, '<:raw', $filepath) or throw 'Open file failed', filepath => $filepath;
166
167 $self = $self->new if !ref $self;
168 $self->init(%args, fh => $fh, filepath => $filepath)->_read($fh, $key);
169 return $args{kdbx};
170 }
171
172 =method load_handle
173
174 $kdbx = File::KDBX::Loader->load_handle($fh, $key);
175 $kdbx = File::KDBX::Loader->load_handle(*IO, $key);
176 $kdbx->load_handle(...); # also instance method
177
178 Read a KDBX file from an input stream / file handle.
179
180 =cut
181
182 sub load_handle {
183 my $self = shift;
184 my $fh = shift;
185 my %args = @_ % 2 == 0 ? @_ : (key => shift, @_);
186
187 $fh = *STDIN if $fh eq '-';
188
189 my $key = delete $args{key};
190 $args{kdbx} //= $self->kdbx;
191
192 $self = $self->new if !ref $self;
193 $self->init(%args, fh => $fh)->_read($fh, $key);
194 return $args{kdbx};
195 }
196
197 =attr kdbx
198
199 $kdbx = $loader->kdbx;
200 $loader->kdbx($kdbx);
201
202 Get or set the L<File::KDBX> instance for storing the loaded data into.
203
204 =cut
205
206 sub kdbx {
207 my $self = shift;
208 return File::KDBX->new if !ref $self;
209 $self->{kdbx} = shift if @_;
210 $self->{kdbx} //= File::KDBX->new;
211 }
212
213 =attr format
214
215 Get the file format used for reading the database. Normally the format is auto-detected from the data stream.
216 This auto-detection works well, so there's not really a good reason to explicitly specify the format.
217 Possible formats:
218
219 =for :list
220 * C<V3>
221 * C<V4>
222 * C<KDB>
223 * C<XML>
224 * C<Raw>
225
226 =cut
227
228 sub format { $_[0]->{format} }
229
230 =attr inner_format
231
232 Get the format of the data inside the KDBX envelope. This only applies to C<V3> and C<V4> formats. Possible
233 formats:
234
235 =for :list
236 * C<XML> - Read the database groups and entries as XML (default)
237 * C<Raw> - Read parsing and store the result in L<File::KDBX/raw>
238
239 =cut
240
241 sub inner_format { $_[0]->{inner_format} // 'XML' }
242
243 =attr min_version
244
245 $min_version = File::KDBX::Loader->min_version;
246
247 Get the minimum KDBX file version supported, which is 3.0 or C<0x00030000> as
248 it is encoded.
249
250 To read older KDBX files unsupported by this module, try L<File::KeePass>.
251
252 =cut
253
254 sub min_version { KDBX_VERSION_OLDEST }
255
256 =method read_magic_numbers
257
258 $magic = File::KDBX::Loader->read_magic_numbers($fh);
259 ($sig1, $sig2, $version, $magic) = File::KDBX::Loader->read_magic_numbers($fh);
260
261 $magic = $loader->read_magic_numbers($fh);
262 ($sig1, $sig2, $version, $magic) = $loader->read_magic_numbers($fh);
263
264 Read exactly 12 bytes from an IO handle and parse them into the three magic numbers that begin
265 a KDBX file. This is a quick way to determine if a file is actually a KDBX file.
266
267 C<$sig1> should always be C<KDBX_SIG1> if reading an actual KDB or KDBX file.
268
269 C<$sig2> should be C<KDBX_SIG2_1> for KeePass 1 files and C<KDBX_SIG2_2> for KeePass 2 files.
270
271 C<$version> is the file version (e.g. C<0x00040001>).
272
273 C<$magic> is the raw 12 bytes read from the IO handle.
274
275 If called on an instance, the C<sig1>, C<sig2> and C<version> attributes will be set in the L</kdbx>
276 and the instance will be blessed into the correct loader subclass.
277
278 =cut
279
280 sub read_magic_numbers {
281 my $self = shift;
282 my $fh = shift;
283 my $kdbx = shift // $self->kdbx;
284
285 read_all $fh, my $magic, 12 or throw 'Failed to read file signature';
286
287 my ($sig1, $sig2, $version) = unpack('L<3', $magic);
288
289 if ($kdbx) {
290 $kdbx->sig1($sig1);
291 $kdbx->sig2($sig2);
292 $kdbx->version($version);
293 $self->_rebless if ref $self;
294 }
295
296 return wantarray ? ($sig1, $sig2, $version, $magic) : $magic;
297 }
298
299 sub _fh { $_[0]->{fh} or throw 'IO handle not set' }
300
301 sub _read {
302 my $self = shift;
303 my $fh = shift;
304 my $key = shift;
305
306 my $kdbx = $self->kdbx;
307 $key //= $kdbx->key ? $kdbx->key->reload : undef;
308 $kdbx->reset;
309
310 read_all $fh, my $buf, 1 or throw 'Failed to read the first byte', type => 'parser';
311 my $first = ord($buf);
312 $fh->ungetc($first);
313 if ($first != KDBX_SIG1_FIRST_BYTE) {
314 # not a KDBX file... try skipping the outer layer
315 return $self->_read_inner_body($fh);
316 }
317
318 my $magic = $self->read_magic_numbers($fh, $kdbx);
319 $kdbx->sig1 == KDBX_SIG1 or throw 'Invalid file signature', type => 'parser', sig1 => $kdbx->sig1;
320
321 if (ref($self) =~ /::(?:KDB|V[34])$/) {
322 defined $key or throw 'Must provide a master key', type => 'key.missing';
323 }
324
325 my $headers = $self->_read_headers($fh);
326
327 eval {
328 $self->_read_body($fh, $key, "$magic$headers");
329 };
330 if (my $err = $@) {
331 throw "Failed to load KDBX file: $err",
332 error => $err,
333 compression_error => $IO::Uncompress::Gunzip::GunzipError,
334 crypt_error => $File::KDBX::IO::Crypt::ERROR,
335 hash_error => $File::KDBX::IO::HashBLock::ERROR,
336 hmac_error => $File::KDBX::IO::HmacBLock::ERROR;
337 }
338 }
339
340 sub _read_headers {
341 my $self = shift;
342 my $fh = shift;
343
344 my $headers = $self->kdbx->headers;
345 my $all_raw = '';
346
347 while (my ($type, $val, $raw) = $self->_read_header($fh)) {
348 $all_raw .= $raw;
349 last if $type == HEADER_END;
350 $headers->{$type} = $val;
351 }
352
353 return $all_raw;
354 }
355
356 sub _read_body { die "Not implemented" }
357
358 sub _read_inner_body {
359 my $self = shift;
360
361 my $current_pkg = ref $self;
362 require Scope::Guard;
363 my $guard = Scope::Guard->new(sub { bless $self, $current_pkg });
364
365 $self->_rebless($self->inner_format);
366 $self->_read_inner_body(@_);
367 }
368
369 1;
370 __END__
371
372 =head1 DESCRIPTION
373
374
375 =cut
This page took 0.051067 seconds and 4 git commands to generate.