| 34 |
rodolico |
1 |
# Simplified BSD License (FreeBSD License)
|
|
|
2 |
#
|
|
|
3 |
# Copyright (c) 2025, Daily Data Inc.
|
|
|
4 |
# All rights reserved.
|
|
|
5 |
#
|
|
|
6 |
# Redistribution and use in source and binary forms, with or without
|
|
|
7 |
# modification, are permitted provided that the following conditions are met:
|
|
|
8 |
#
|
|
|
9 |
# 1. Redistributions of source code must retain the above copyright notice, this
|
|
|
10 |
# list of conditions and the following disclaimer.
|
|
|
11 |
#
|
|
|
12 |
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
|
13 |
# this list of conditions and the following disclaimer in the documentation
|
|
|
14 |
# and/or other materials provided with the distribution.
|
|
|
15 |
#
|
|
|
16 |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
|
17 |
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
|
18 |
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
|
19 |
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
|
20 |
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
|
21 |
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
|
22 |
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
|
23 |
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
|
24 |
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
|
25 |
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
|
26 |
|
| 24 |
rodolico |
27 |
package ZFS_Utils;
|
|
|
28 |
|
|
|
29 |
use strict;
|
|
|
30 |
use warnings;
|
|
|
31 |
use Exporter 'import';
|
|
|
32 |
use Data::Dumper;
|
|
|
33 |
use POSIX qw(strftime);
|
|
|
34 |
use File::Path qw(make_path);
|
|
|
35 |
|
| 34 |
rodolico |
36 |
# library of ZFS related utility functions
|
|
|
37 |
# Copyright 2024 Daily Data Inc. <rodo@dailydata.net>
|
|
|
38 |
|
|
|
39 |
# currently used for sneakernet scripts, but plans to expand to other ZFS related tasks
|
|
|
40 |
# functions include:
|
|
|
41 |
# runCmd: execute a command and return its output
|
|
|
42 |
# shredFile: securely delete a file using gshred
|
|
|
43 |
# logMsg: log messages to a log file and optionally to console
|
|
|
44 |
# mountDriveByLabel: find and mount a drive by its GPT label
|
|
|
45 |
# loadConfig: load a YAML configuration file into a hashref
|
|
|
46 |
# mountGeli: decrypt and mount a GELI encrypted ZFS pool
|
|
|
47 |
# makeGeliKey: create a GELI key by XOR'ing a remote binary keyfile and a local hex key
|
|
|
48 |
# decryptAndMountGeli: decrypt GELI disks and mount the ZFS pool
|
|
|
49 |
# findGeliDisks: find available disks for GELI/ZFS use
|
|
|
50 |
# makeReplicateCommands: create zfs send commands for replication based on snapshot lists
|
|
|
51 |
|
|
|
52 |
|
|
|
53 |
# Exported functions and variables
|
|
|
54 |
|
| 25 |
rodolico |
55 |
our @EXPORT_OK = qw(loadConfig shredFile mountDriveByLabel mountGeli logMsg runCmd makeReplicateCommands $logFileName $displayLogsOnConsole);
|
| 24 |
rodolico |
56 |
|
|
|
57 |
|
| 34 |
rodolico |
58 |
our $VERSION = '0.2';
|
| 24 |
rodolico |
59 |
our $logFileName = '/tmp/zfs_utils.log'; # this can be overridden by the caller, and turned off with empty string
|
| 34 |
rodolico |
60 |
our $displayLogsOnConsole = 1; # if non-zero, log messages are also printed to console
|
| 27 |
rodolico |
61 |
our $merge_stderr = 0; # if set to 1, stderr is captured in runCmd
|
| 24 |
rodolico |
62 |
|
| 25 |
rodolico |
63 |
# Execute a command and return its output.
|
|
|
64 |
# If called in scalar context, returns the full output as a single string.
|
|
|
65 |
# If called in list context, returns the output split into lines.
|
|
|
66 |
# If $merge_stderr is true (default), stderr is merged into stdout (only for scalar commands).
|
| 34 |
rodolico |
67 |
# returns undef on failure and logs failure message.
|
| 25 |
rodolico |
68 |
sub runCmd {
|
| 33 |
rodolico |
69 |
my $cmd = join( ' ', @_ );
|
| 25 |
rodolico |
70 |
$merge_stderr = 1 unless defined $merge_stderr;
|
|
|
71 |
my $output = '';
|
|
|
72 |
|
| 34 |
rodolico |
73 |
logMsg( "Running command [$cmd]" );
|
|
|
74 |
$cmd .= ' 2>&1' if $merge_stderr;
|
|
|
75 |
$output = `$cmd`;
|
|
|
76 |
if ($? == -1) {
|
|
|
77 |
logMsg( "failed to execute: $!");
|
|
|
78 |
return ''
|
|
|
79 |
}
|
|
|
80 |
elsif ($? & 127) { # fatal error, exit program
|
|
|
81 |
logMsg( sprintf( "child died with signal %d, %s coredump\n", ($? & 127), ($? & 128) ? 'with' : 'without' ) );
|
|
|
82 |
die;
|
|
|
83 |
}
|
|
|
84 |
else {
|
|
|
85 |
logMsg( sprintf( "child exited with value %d\n", $? >> 8 ) );
|
|
|
86 |
}
|
| 25 |
rodolico |
87 |
$output //= '';
|
|
|
88 |
|
|
|
89 |
if (wantarray) {
|
|
|
90 |
return $output eq '' ? () : split(/\n/, $output);
|
|
|
91 |
} else {
|
|
|
92 |
return $output;
|
|
|
93 |
}
|
|
|
94 |
}
|
|
|
95 |
|
| 24 |
rodolico |
96 |
# this calls gshred which will overwrite the file 3 times, then
|
|
|
97 |
# remove it.
|
|
|
98 |
# NOTE: this will not work on ZFS, since ZFS is CopyOnWrite (COW)
|
|
|
99 |
# so assuming file is on something without COW (ramdisk, UFS, etc)
|
|
|
100 |
sub shredFile {
|
|
|
101 |
my $filename = shift;
|
|
|
102 |
`/usr/local/bin/gshred -u -f -s 32 $filename` if -e $filename;
|
|
|
103 |
}
|
|
|
104 |
|
|
|
105 |
sub logMsg {
|
|
|
106 |
my $msg = shift;
|
|
|
107 |
my $filename = shift // $logFileName;
|
|
|
108 |
my $timeStampFormat = shift // '%Y-%m-%d %H:%M:%S';
|
|
|
109 |
my $timestamp = strftime($timeStampFormat, localtime());
|
|
|
110 |
if (defined $filename && $filename ne '' ) {
|
|
|
111 |
open my $logfh, '>>', $filename or die "Could not open log file $filename: $!\n";
|
|
|
112 |
print $logfh "$timestamp\t$msg\n";
|
|
|
113 |
close $logfh;
|
|
|
114 |
}
|
|
|
115 |
print "$timestamp\t$msg\n" if ($displayLogsOnConsole);
|
|
|
116 |
}
|
|
|
117 |
|
|
|
118 |
# find a drive by it's label by scanning /dev/gpt/ for $timeout seconds.
|
|
|
119 |
# If the drive is found, mount it on mountPath and return the mountPath.
|
|
|
120 |
# If not found, return empty string.
|
|
|
121 |
sub mountDriveByLabel {
|
| 34 |
rodolico |
122 |
my ($label, $mountPath, $timeout, $checkEvery, $filesystem ) = @_;
|
| 24 |
rodolico |
123 |
unless ($label) {
|
|
|
124 |
logMsg("mountDriveByLabel: No label provided");
|
|
|
125 |
return '';
|
|
|
126 |
}
|
|
|
127 |
unless ( $label =~ /^[a-zA-Z0-9_\-]+$/ ) {
|
|
|
128 |
logMsg("mountDriveByLabel: Invalid label '$label'");
|
|
|
129 |
return '';
|
|
|
130 |
}
|
|
|
131 |
|
|
|
132 |
logMsg("mountDriveByLabel: Looking for drive with label '$label'");
|
|
|
133 |
# default to /mnt/label if not provided
|
|
|
134 |
$mountPath //= "/mnt/$label"; # this is where we'll mount it if we find it
|
| 33 |
rodolico |
135 |
$filesystem //= 'ufs'; # default to mounting ufs
|
| 34 |
rodolico |
136 |
# The location for the label depends on filesystem. Only providing access to ufs and msdos here for safety.
|
|
|
137 |
# gpt labeled drives for ufs are in /dev/gpt/, for msdosfs in /dev/msdosfs/
|
|
|
138 |
$label = $filesystem eq 'msdos' ? "/dev/msdosfs/$label" : "/dev/gpt/$label";
|
| 31 |
rodolico |
139 |
# drive already mounted, just return the path
|
|
|
140 |
return $mountPath if ( runCmd( "mount | grep '$mountPath'" ) );
|
| 24 |
rodolico |
141 |
# default to 10 minutes (600 seconds) if not provided
|
|
|
142 |
$timeout //= 600;
|
|
|
143 |
# default to checking every minute if not provided
|
| 31 |
rodolico |
144 |
$checkEvery //= 15;
|
| 24 |
rodolico |
145 |
# wait up to $timeout seconds for device to appear, checking every 10 seconds
|
|
|
146 |
while ( $timeout > 0 ) {
|
|
|
147 |
if ( -e "$label" ) {
|
|
|
148 |
last;
|
|
|
149 |
} else {
|
|
|
150 |
sleep $checkEvery;
|
|
|
151 |
$timeout -= $checkEvery;
|
| 31 |
rodolico |
152 |
print "Waiting for drive labeled $label\n";
|
| 24 |
rodolico |
153 |
}
|
|
|
154 |
}
|
|
|
155 |
# if we found it, mount and return mount path
|
|
|
156 |
if ( -e "$label" ) {
|
|
|
157 |
# ensure mount point
|
|
|
158 |
unless ( -d $mountPath || make_path($mountPath) ) {
|
|
|
159 |
logMsg("Failed to create $mountPath: $!");
|
|
|
160 |
return '';
|
|
|
161 |
}
|
|
|
162 |
# mount device (let mount detect filesystem)
|
| 33 |
rodolico |
163 |
unless ( runCmd( "mount -t $filesystem $label $mountPath" ) ) {
|
| 24 |
rodolico |
164 |
logMsg("Failed to mount $label on $mountPath: $!");
|
|
|
165 |
return '';
|
|
|
166 |
}
|
|
|
167 |
return $mountPath;
|
|
|
168 |
} else {
|
|
|
169 |
return '';
|
|
|
170 |
}
|
|
|
171 |
}
|
|
|
172 |
|
|
|
173 |
## Load a YAML configuration file into a hashref.
|
|
|
174 |
## If the file does not exist, and a default hashref is provided,
|
|
|
175 |
## create the file by dumping the default to YAML, then return the default.
|
|
|
176 |
sub loadConfig {
|
|
|
177 |
my ($filename, $default) = @_;
|
|
|
178 |
|
|
|
179 |
# If no filename was provided, return default or empty hashref
|
|
|
180 |
die "No filename provided to loadConfig\n" unless defined $filename;
|
|
|
181 |
|
|
|
182 |
# If file doesn't exist but a default hashref was provided, try to
|
|
|
183 |
# create the file by dumping the default to YAML, then return the default.
|
|
|
184 |
unless (-e $filename) {
|
|
|
185 |
logMsg("Config file $filename does not exist. Creating it with default values.");
|
|
|
186 |
if ($default && ref $default eq 'HASH') {
|
|
|
187 |
my $wrote = 0;
|
|
|
188 |
eval {
|
|
|
189 |
require YAML::XS;
|
|
|
190 |
YAML::XS->import();
|
|
|
191 |
YAML::XS::DumpFile($filename, $default);
|
|
|
192 |
$wrote = 1;
|
|
|
193 |
1;
|
|
|
194 |
} or do {
|
|
|
195 |
eval {
|
|
|
196 |
require YAML::Tiny;
|
|
|
197 |
YAML::Tiny->import();
|
|
|
198 |
my $yt = YAML::Tiny->new($default);
|
|
|
199 |
$yt->write($filename);
|
|
|
200 |
$wrote = 1;
|
|
|
201 |
1;
|
|
|
202 |
} or do {
|
|
|
203 |
logMsg("No YAML writer available (YAML::XS or YAML::Tiny). Could not create $filename");
|
|
|
204 |
};
|
|
|
205 |
};
|
|
|
206 |
|
|
|
207 |
die "Failed to write default config to $filename:$!\n" unless $wrote;
|
|
|
208 |
}
|
|
|
209 |
|
|
|
210 |
# No default provided; nothing to create
|
|
|
211 |
return {};
|
|
|
212 |
}
|
|
|
213 |
|
|
|
214 |
my $yaml;
|
|
|
215 |
|
|
|
216 |
# Try YAML::XS first, fall back to YAML::Tiny
|
|
|
217 |
eval {
|
|
|
218 |
require YAML::XS;
|
|
|
219 |
YAML::XS->import();
|
|
|
220 |
$yaml = YAML::XS::LoadFile($filename);
|
|
|
221 |
logMsg("using YAML::XS to load $filename");
|
|
|
222 |
1;
|
|
|
223 |
} or do {
|
|
|
224 |
eval {
|
|
|
225 |
require YAML::Tiny;
|
|
|
226 |
YAML::Tiny->import();
|
|
|
227 |
$yaml = YAML::Tiny->read($filename);
|
|
|
228 |
$yaml = $yaml->[0] if $yaml; # YAML::Tiny returns an arrayref of documents
|
|
|
229 |
logMsg("using YAML::Tiny to load $filename");
|
|
|
230 |
1;
|
|
|
231 |
} or do {
|
|
|
232 |
logMsg("No YAML parser installed (YAML::XS or YAML::Tiny). Skipping config load from $filename");
|
|
|
233 |
return ($default && ref $default eq 'HASH') ? $default : {};
|
|
|
234 |
};
|
|
|
235 |
};
|
|
|
236 |
# Ensure we have a hashref
|
|
|
237 |
die "Config file $filename did not produce a HASH.\n" unless (defined $yaml && ref $yaml eq 'HASH');
|
|
|
238 |
|
|
|
239 |
return $yaml;
|
|
|
240 |
}
|
|
|
241 |
|
|
|
242 |
|
|
|
243 |
|
|
|
244 |
sub mountGeli {
|
|
|
245 |
my $geliConfig = shift;
|
| 30 |
rodolico |
246 |
unless ( $geliConfig->{'localKey'} ) {
|
|
|
247 |
logMsg "Could not find local key in configuration file\n";
|
| 24 |
rodolico |
248 |
return '';
|
|
|
249 |
}
|
|
|
250 |
# find the keyfile disk and mount it
|
|
|
251 |
my $path = mountDriveByLabel( $geliConfig->{'keydiskname'} );
|
|
|
252 |
unless ( $path ne '' and -e "$path/" . $geliConfig->{'keyfile'} ) {
|
|
|
253 |
logMsg "Could not find or mount keyfile disk with label: " . $geliConfig->{'keydiskname'} . "\n";
|
|
|
254 |
return '';
|
|
|
255 |
}
|
|
|
256 |
# create the combined geli keyfile in target location
|
|
|
257 |
unless ( makeGeliKey( "$path/" . $geliConfig->{'keyfile'}, $geliConfig->{'localKey'}, $geliConfig->{'target'} ) ) {
|
|
|
258 |
logMsg "Could not create geli keyfile\n";
|
|
|
259 |
return '';
|
|
|
260 |
}
|
|
|
261 |
# decrypt and mount the geli disks and zfs pool
|
|
|
262 |
my $poolname = decryptAndMountGeli( $geliConfig );
|
|
|
263 |
return $poolname;
|
|
|
264 |
|
|
|
265 |
}
|
|
|
266 |
|
| 30 |
rodolico |
267 |
# find all disks which are candidates for use with geli/zfs
|
|
|
268 |
# Grabs all disks on the system, then removes those with partitions
|
|
|
269 |
# and those already used in zpools.
|
|
|
270 |
sub findGeliDisks {
|
|
|
271 |
logMsg("Finding available disks for GELI/ZFS use");
|
|
|
272 |
# get all disks in system
|
|
|
273 |
my %allDisks = map{ chomp $_ ; $_ => 1 } runCmd( "geom disk list | grep 'Geom name:' | rev | cut -d' ' -f1 | rev" );
|
|
|
274 |
# get the disks with partitions
|
|
|
275 |
my @temp = runCmd( "gpart show -p | grep '^=>'"); # -p prints just the disks without partitions
|
|
|
276 |
# remove them from the list
|
|
|
277 |
foreach my $disk ( @temp ) {
|
|
|
278 |
$allDisks{$1} = 0 if ( $disk =~ m/^=>[\t\s0-9]+([a-z][a-z0-9]+)/ ) ;
|
|
|
279 |
}
|
|
|
280 |
|
|
|
281 |
# get disk which are currently used for zpools
|
|
|
282 |
@temp = runCmd( "zpool status -LP | grep '/dev/'" );
|
|
|
283 |
foreach my $disk ( @temp ) {
|
|
|
284 |
$allDisks{$1} = 0 if $disk =~ m|/dev/([a-z]+\d+)|;
|
|
|
285 |
}
|
|
|
286 |
|
|
|
287 |
# return only the disks which are free (value 1)
|
|
|
288 |
return grep{ $allDisks{$_} == 1 } keys %allDisks;
|
|
|
289 |
}
|
|
|
290 |
|
| 24 |
rodolico |
291 |
## Decrypt each GELI disk from $geliConfig->{'diskList'} using the keyfile,
|
|
|
292 |
## then import and mount the ZFS pool specified in $geliConfig->{'poolname'}.
|
|
|
293 |
##
|
|
|
294 |
## Returns the pool name on success, empty on error.
|
|
|
295 |
sub decryptAndMountGeli {
|
|
|
296 |
my ($geliConfig) = @_;
|
| 30 |
rodolico |
297 |
|
|
|
298 |
# Can't continue at all if no pool name
|
| 24 |
rodolico |
299 |
die "No pool name specified in config\n" unless $geliConfig->{'poolname'};
|
| 30 |
rodolico |
300 |
# if no list of disks provided, try to find them
|
|
|
301 |
$geliConfig->{'diskList'} //= findGeliDisks();
|
|
|
302 |
|
| 24 |
rodolico |
303 |
my $diskList = $geliConfig->{'diskList'};
|
|
|
304 |
my $poolname = $geliConfig->{'poolname'};
|
|
|
305 |
my $keyfile = $geliConfig->{'target'};
|
|
|
306 |
unless ( -e $keyfile ) {
|
|
|
307 |
logMsg "GELI keyfile $keyfile does not exist\n";
|
|
|
308 |
return '';
|
|
|
309 |
}
|
|
|
310 |
|
|
|
311 |
my @decrypted_devices;
|
|
|
312 |
|
|
|
313 |
# Decrypt each disk in the list
|
| 30 |
rodolico |
314 |
foreach my $disk (@{$geliConfig->{'diskList'}}) {
|
| 24 |
rodolico |
315 |
unless ( -e $disk ) {
|
|
|
316 |
logMsg "Disk $disk does not exist\n";
|
|
|
317 |
return '';
|
|
|
318 |
}
|
|
|
319 |
|
|
|
320 |
# Derive the decrypted device name (.eli suffix on FreeBSD)
|
|
|
321 |
my $decrypted = $disk . '.eli';
|
|
|
322 |
|
|
|
323 |
# Decrypt using geli attach with the keyfile
|
|
|
324 |
logMsg("Decrypting $disk with keyfile $keyfile");
|
| 30 |
rodolico |
325 |
if ( my $result = system('geli', 'attach', '-k', $geliConfig->{'target'}, $disk) == 0 ) {
|
| 24 |
rodolico |
326 |
logMsg "Failed to decrypt $disk (exit $result)\n";
|
| 30 |
rodolico |
327 |
next; # ignore failed disks and continue to see if we can import the pool
|
| 24 |
rodolico |
328 |
}
|
|
|
329 |
|
|
|
330 |
unless ( -e $decrypted ) {
|
|
|
331 |
logMsg "Decrypted device $decrypted does not exist after geli attach\n";
|
|
|
332 |
return '';
|
|
|
333 |
}
|
|
|
334 |
push @decrypted_devices, $decrypted;
|
|
|
335 |
}
|
|
|
336 |
|
|
|
337 |
# Import the ZFS pool
|
|
|
338 |
logMsg("Importing ZFS pool $poolname");
|
|
|
339 |
my @import_cmd = ('zpool', 'import');
|
|
|
340 |
# If decrypted devices exist, add their directories to -d list
|
| 30 |
rodolico |
341 |
#foreach my $dev (@decrypted_devices) {
|
|
|
342 |
# my $dir = $dev;
|
|
|
343 |
# $dir =~ s!/[^/]+$!!; # Remove filename to get directory
|
|
|
344 |
# push @import_cmd, '-d', $dir;
|
|
|
345 |
#}
|
|
|
346 |
|
| 24 |
rodolico |
347 |
push @import_cmd, $poolname;
|
|
|
348 |
|
|
|
349 |
my $result = system(@import_cmd);
|
|
|
350 |
unless ( $result == 0 ) {
|
|
|
351 |
logMsg("Failed to import zfs pool $poolname (exit $result)\n");
|
|
|
352 |
return '';
|
|
|
353 |
}
|
|
|
354 |
|
|
|
355 |
# Mount the ZFS pool (zfs mount -a mounts all filesystems in the pool)
|
|
|
356 |
logMsg("Mounting ZFS pool $poolname");
|
|
|
357 |
$result = system('zfs', 'mount', '-a');
|
|
|
358 |
unless ( $result == 0 ) {
|
|
|
359 |
logMsg("Failed to mount zfs pool $poolname (exit $result)\n");
|
|
|
360 |
return '';
|
|
|
361 |
}
|
|
|
362 |
|
|
|
363 |
logMsg("Successfully decrypted and mounted pool $poolname");
|
|
|
364 |
return $poolname;
|
|
|
365 |
}
|
|
|
366 |
|
|
|
367 |
## Create a GELI key by XOR'ing a remote binary keyfile and a local key (hex string).
|
|
|
368 |
##
|
|
|
369 |
## Arguments:
|
|
|
370 |
## $remote_keyfile - path to binary keyfile (32 bytes)
|
|
|
371 |
## $localKeyHexOrPath - hex string (64 hex chars) or path to file containing hex
|
|
|
372 |
## $target - path to write the resulting 32-byte binary key
|
|
|
373 |
##
|
|
|
374 |
## Returns true on success, dies on fatal error.
|
|
|
375 |
sub makeGeliKey {
|
|
|
376 |
my ($remote_keyfile, $localKeyHexOrPath, $target) = @_;
|
|
|
377 |
|
|
|
378 |
die "remote keyfile not provided" unless defined $remote_keyfile;
|
|
|
379 |
die "local key not provided" unless defined $localKeyHexOrPath;
|
|
|
380 |
die "target not provided" unless defined $target;
|
|
|
381 |
|
|
|
382 |
die "Remote keyfile $remote_keyfile does not exist\n" unless -e $remote_keyfile;
|
|
|
383 |
|
|
|
384 |
# Read remote binary key
|
|
|
385 |
open my $rh, '<:raw', $remote_keyfile or die "Unable to open $remote_keyfile: $!\n";
|
|
|
386 |
my $rbuf;
|
|
|
387 |
my $read = read($rh, $rbuf, 32);
|
|
|
388 |
close $rh;
|
|
|
389 |
die "Failed to read 32 bytes from $remote_keyfile (got $read)\n" unless defined $read && $read == 32;
|
|
|
390 |
|
|
|
391 |
# Get local hex string (either direct string or file contents)
|
|
|
392 |
my $hex;
|
|
|
393 |
if (-e $localKeyHexOrPath) {
|
|
|
394 |
open my $lh, '<', $localKeyHexOrPath or die "Unable to open local key file $localKeyHexOrPath: $!\n";
|
|
|
395 |
local $/ = undef;
|
|
|
396 |
$hex = <$lh>;
|
|
|
397 |
close $lh;
|
|
|
398 |
} else {
|
|
|
399 |
$hex = $localKeyHexOrPath;
|
|
|
400 |
}
|
|
|
401 |
# clean hex (remove whitespace/newlines and optional 0x)
|
|
|
402 |
$hex =~ s/0x//g;
|
|
|
403 |
$hex =~ s/[^0-9a-fA-F]//g;
|
|
|
404 |
|
|
|
405 |
die "Local key must be 64 hex characters (256-bit)\n" unless length($hex) == 64;
|
|
|
406 |
|
|
|
407 |
my $lbuf = pack('H*', $hex);
|
|
|
408 |
die "Local key decoded to unexpected length " . length($lbuf) . "\n" unless length($lbuf) == 32;
|
|
|
409 |
|
|
|
410 |
# XOR the two buffers
|
|
|
411 |
my $out = '';
|
|
|
412 |
for my $i (0 .. 31) {
|
|
|
413 |
$out .= chr( ord(substr($rbuf, $i, 1)) ^ ord(substr($lbuf, $i, 1)) );
|
|
|
414 |
}
|
|
|
415 |
|
|
|
416 |
# Ensure target directory exists
|
|
|
417 |
my ($vol, $dirs, $file) = ($target =~ m{^(/?)(.*/)?([^/]+)$});
|
|
|
418 |
if ($dirs) {
|
|
|
419 |
my $dir = $dirs;
|
|
|
420 |
$dir =~ s{/$}{};
|
|
|
421 |
unless (-d $dir) {
|
|
|
422 |
require File::Path;
|
|
|
423 |
File::Path::make_path($dir) or die "Failed to create directory $dir: $!\n";
|
|
|
424 |
}
|
|
|
425 |
}
|
|
|
426 |
|
|
|
427 |
# Write out binary key and protect permissions
|
|
|
428 |
open my $oh, '>:raw', $target or die "Unable to open $target for writing: $!\n";
|
|
|
429 |
print $oh $out or die "Failed to write to $target: $!\n";
|
|
|
430 |
close $oh;
|
|
|
431 |
chmod 0600, $target;
|
|
|
432 |
|
|
|
433 |
return 1;
|
|
|
434 |
}
|
|
|
435 |
|
| 25 |
rodolico |
436 |
sub makeReplicateCommands {
|
|
|
437 |
my ($sourceSnapsRef, $statusRef, $newStatusRef) = @_;
|
|
|
438 |
$sourceSnapsRef ||= [];
|
|
|
439 |
$statusRef ||= [];
|
|
|
440 |
$newStatusRef ||= [];
|
|
|
441 |
|
|
|
442 |
# parse snapshots: each line is expected to have snapshot fullname as first token: pool/fs@snap ...
|
|
|
443 |
my %snaps_by_fs;
|
|
|
444 |
foreach my $line (@$sourceSnapsRef) {
|
|
|
445 |
next unless defined $line && $line =~ /\S/;
|
|
|
446 |
my ($tok) = split /\s+/, $line;
|
|
|
447 |
next unless $tok && $tok =~ /@/;
|
|
|
448 |
my ($fs, $snap) = split /@/, $tok, 2;
|
|
|
449 |
push @{ $snaps_by_fs{$fs} }, $snap;
|
|
|
450 |
}
|
|
|
451 |
|
|
|
452 |
# nothing to do
|
|
|
453 |
return [] unless keys %snaps_by_fs;
|
|
|
454 |
|
|
|
455 |
# figure root filesystem: first snapshot line's fs is the requested root
|
|
|
456 |
my ($first_line) = grep { defined $_ && $_ =~ /\S/ } @$sourceSnapsRef;
|
|
|
457 |
my ($root_fs) = $first_line ? (split(/\s+/, $first_line))[0] =~ /@/ ? (split(/@/, (split(/\s+/, $first_line))[0]))[0] : undef : undef;
|
|
|
458 |
$root_fs ||= (sort keys %snaps_by_fs)[0];
|
|
|
459 |
|
|
|
460 |
# helper: find last status entry for a filesystem (status lines contain full snapshot names pool/fs@snap)
|
|
|
461 |
my %last_status_for;
|
|
|
462 |
for my $s (@$statusRef) {
|
|
|
463 |
next unless $s && $s =~ /@/;
|
|
|
464 |
my ($fs, $snap) = split /@/, $s, 2;
|
|
|
465 |
$last_status_for{$fs} = $snap; # later entries override earlier ones -> last occurrence kept
|
|
|
466 |
}
|
|
|
467 |
|
|
|
468 |
# build per-filesystem "from" and "to"
|
|
|
469 |
my %from_for;
|
|
|
470 |
my %to_for;
|
|
|
471 |
foreach my $fs (keys %snaps_by_fs) {
|
|
|
472 |
my $arr = $snaps_by_fs{$fs};
|
|
|
473 |
next unless @$arr;
|
|
|
474 |
$to_for{$fs} = $arr->[-1];
|
|
|
475 |
$from_for{$fs} = $last_status_for{$fs}; # may be undef -> full send required
|
|
|
476 |
}
|
|
|
477 |
|
|
|
478 |
# decide if we can do a single recursive send:
|
|
|
479 |
# condition: all 'to' snapshot names are identical
|
|
|
480 |
my %to_names = map { $_ => 1 } values %to_for;
|
|
|
481 |
my $single_to_name = (keys %to_names == 1) ? (keys %to_names)[0] : undef;
|
|
|
482 |
|
| 31 |
rodolico |
483 |
my %commands;
|
| 25 |
rodolico |
484 |
|
|
|
485 |
if ($single_to_name) {
|
|
|
486 |
# check whether any from is missing
|
|
|
487 |
my @from_values = map { $from_for{$_} } sort keys %from_for;
|
|
|
488 |
my $any_from_missing = grep { !defined $_ } @from_values;
|
|
|
489 |
my %from_names = map { $_ => 1 } grep { defined $_ } @from_values;
|
|
|
490 |
my $single_from_name = (keys %from_names == 1) ? (keys %from_names)[0] : undef;
|
|
|
491 |
|
|
|
492 |
if ($any_from_missing) {
|
|
|
493 |
# full recursive send from root
|
| 31 |
rodolico |
494 |
$commands{'root_fs'} = sprintf('zfs send -R %s@%s', $root_fs, $single_to_name);
|
| 25 |
rodolico |
495 |
}
|
|
|
496 |
elsif ($single_from_name) {
|
| 31 |
rodolico |
497 |
# incremental recursive send, but don't do it if they are the same
|
|
|
498 |
$commands{$root_fs} = sprintf('zfs send -R -I %s@%s %s@%s',
|
|
|
499 |
$root_fs, $single_from_name, $root_fs, $single_to_name)
|
|
|
500 |
unless $single_from_name eq $single_to_name;
|
| 25 |
rodolico |
501 |
}
|
|
|
502 |
else {
|
|
|
503 |
# from snapshots differ across children -> fall back to per-filesystem sends
|
|
|
504 |
foreach my $fs (sort keys %to_for) {
|
|
|
505 |
my $to = $to_for{$fs};
|
|
|
506 |
my $from = $from_for{$fs};
|
|
|
507 |
if ($from) {
|
| 31 |
rodolico |
508 |
# if from and to are different, add it
|
|
|
509 |
$commands{$fs} = sprintf('zfs send -I %s@%s %s@%s', $fs, $from, $fs, $to)
|
|
|
510 |
unless $from eq $to;
|
| 25 |
rodolico |
511 |
} else {
|
| 31 |
rodolico |
512 |
$commands{$fs} = sprintf('zfs send %s@%s', $fs, $to);
|
| 25 |
rodolico |
513 |
}
|
|
|
514 |
}
|
|
|
515 |
}
|
|
|
516 |
|
|
|
517 |
# update new status: record newest snap for every filesystem
|
|
|
518 |
foreach my $fs (keys %to_for) {
|
|
|
519 |
push @$newStatusRef, sprintf('%s@%s', $fs, $to_for{$fs});
|
|
|
520 |
}
|
|
|
521 |
} else {
|
|
|
522 |
# not all children share same newest snap -> per-filesystem sends
|
|
|
523 |
foreach my $fs (sort keys %to_for) {
|
|
|
524 |
my $to = $to_for{$fs};
|
|
|
525 |
my $from = $from_for{$fs};
|
|
|
526 |
if ($from) {
|
| 31 |
rodolico |
527 |
$commands{$fs} = sprintf('zfs send -I %s@%s %s@%s', $fs, $from, $fs, $to);
|
| 25 |
rodolico |
528 |
} else {
|
| 31 |
rodolico |
529 |
$commands{$fs} = sprintf('zfs send %s@%s', $fs, $to);
|
| 25 |
rodolico |
530 |
}
|
|
|
531 |
push @$newStatusRef, sprintf('%s@%s', $fs, $to);
|
|
|
532 |
}
|
|
|
533 |
}
|
|
|
534 |
|
|
|
535 |
# return arrayref of commands (caller can iterate or join with pipes)
|
| 31 |
rodolico |
536 |
return \%commands;
|
| 25 |
rodolico |
537 |
}
|
|
|
538 |
|
|
|
539 |
|
| 24 |
rodolico |
540 |
1;
|