forked from virtualmin/virtualmin-gpl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backups-lib.pl
executable file
·6936 lines (6661 loc) · 190 KB
/
backups-lib.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Functions for creating backups and managing schedules
# list_scheduled_backups()
# Returns a list of all scheduled backups
sub list_scheduled_backups
{
local @rv;
# Add old single schedule, from config file
if ($config{'backup_dest'}) {
local %backup = ( 'id' => 1,
'dest' => $config{'backup_dest'},
'fmt' => $config{'backup_fmt'},
'mkdir' => $config{'backup_mkdir'},
'errors' => $config{'backup_errors'},
'increment' => $config{'backup_increment'},
'compression' => $config{'backup_compression'},
'strftime' => $config{'backup_strftime'},
'onebyone' => $config{'backup_onebyone'},
'parent' => $config{'backup_parent'},
'all' => $config{'backup_all'},
'doms' => $config{'backup_doms'},
'plan' => $config{'backup_plan'},
'reseller' => $config{'backup_reseller'},
'feature_all' => $config{'backup_feature_all'},
'email' => $config{'backup_email'},
'email_err' => $config{'backup_email_err'},
'email_doms' => $config{'backup_email_doms'},
'virtualmin' => $config{'backup_virtualmin'},
'purge' => $config{'backup_purge'},
'before' => $config{'backup_before'},
'after' => $config{'backup_after'},
'exclude' => $config{'backup_exclude'},
'key' => $config{'backup_key'},
);
local @bf;
foreach $f (&get_available_backup_features(), &list_backup_plugins()) {
push(@bf, $f) if ($config{'backup_feature_'.$f});
$backup{'opts_'.$f} = $config{'backup_opts_'.$f};
}
for(my $i=1; $config{'backup_dest'.$i}; $i++) {
$backup{'dest'.$i} = $config{'backup_dest'.$i};
$backup{'purge'.$i} = $config{'backup_purge'.$i};
}
$backup{'features'} = join(" ", @bf);
push(@rv, \%backup);
}
# Add others from backups dir
opendir(BACKUPS, $scheduled_backups_dir);
foreach my $b (readdir(BACKUPS)) {
if ($b ne "." && $b ne "..") {
local %backup;
&read_file("$scheduled_backups_dir/$b", \%backup);
$backup{'id'} = $b;
$backup{'file'} = "$scheduled_backups_dir/$b";
delete($backup{'enabled'}); # Worked out below
push(@rv, \%backup);
}
}
closedir(BACKUPS);
# Merge in classic cron jobs to see which are enabled
&foreign_require("cron");
local @jobs = &cron::list_cron_jobs();
foreach my $j (@jobs) {
if ($j->{'user'} eq 'root' &&
$j->{'command'} =~ /^\Q$backup_cron_cmd\E(\s+\-\-id\s+(\d+))?/) {
local $id = $2 || 1;
local ($backup) = grep { $_->{'id'} eq $id } @rv;
if ($backup) {
$backup->{'enabled'} = 1;
©_cron_sched_keys($j, $backup);
}
}
}
# Also merge in webmincron jobs
&foreign_require("webmincron");
local @jobs = &webmincron::list_webmin_crons();
foreach my $j (@jobs) {
if ($j->{'module'} eq $module_name &&
$j->{'func'} eq 'run_cron_script' &&
$j->{'args'}->[0] eq 'backup.pl') {
local $id = $j->{'args'}->[1] =~ /--id\s+(\d+)/ ? $1 : 1;
local ($backup) = grep { $_->{'id'} eq $id } @rv;
if ($backup) {
$backup->{'enabled'} = 2;
©_cron_sched_keys($j, $backup);
}
}
}
@rv = sort { $a->{'id'} <=> $b->{'id'} } @rv;
return @rv;
}
# save_scheduled_backup(&backup)
# Create or update a scheduled backup. Also creates any needed cron job.
sub save_scheduled_backup
{
local ($backup) = @_;
local $wasnew = !$backup->{'id'};
if ($backup->{'id'} == 1) {
# Update schedule in Virtualmin config
$config{'backup_dest'} = $backup->{'dest'};
$config{'backup_fmt'} = $backup->{'fmt'};
$config{'backup_mkdir'} = $backup->{'mkdir'};
$config{'backup_errors'} = $backup->{'errors'};
$config{'backup_increment'} = $backup->{'increment'};
$config{'backup_compression'} = $backup->{'compression'};
$config{'backup_strftime'} = $backup->{'strftime'};
$config{'backup_onebyone'} = $backup->{'onebyone'};
$config{'backup_parent'} = $backup->{'parent'};
$config{'backup_all'} = $backup->{'all'};
$config{'backup_doms'} = $backup->{'doms'};
$config{'backup_plan'} = $backup->{'plan'};
$config{'backup_reseller'} = $backup->{'reseller'};
$config{'backup_feature_all'} = $backup->{'feature_all'};
$config{'backup_email'} = $backup->{'email'};
$config{'backup_email_err'} = $backup->{'email_err'};
$config{'backup_email_doms'} = $backup->{'email_doms'};
$config{'backup_virtualmin'} = $backup->{'virtualmin'};
$config{'backup_purge'} = $backup->{'purge'};
$config{'backup_before'} = $backup->{'before'};
$config{'backup_after'} = $backup->{'after'};
$config{'backup_exclude'} = $backup->{'exclude'};
$config{'backup_key'} = $backup->{'key'};
local @bf = split(/\s+/, $backup->{'features'});
foreach $f (&get_available_backup_features(), &list_backup_plugins()) {
$config{'backup_feature_'.$f} = &indexof($f, @bf) >= 0 ? 1 : 0;
$config{'backup_opts_'.$f} = $backup->{'opts_'.$f};
}
foreach my $k (keys %config) {
if ($k =~ /^backup_(dest|purge)\d+$/) {
delete($config{$k});
}
}
for(my $i=1; $backup->{'dest'.$i}; $i++) {
$config{'backup_dest'.$i} = $backup->{'dest'.$i};
$config{'backup_purge'.$i} = $backup->{'purge'.$i};
}
&lock_file($module_config_file);
&save_module_config();
&unlock_file($module_config_file);
}
else {
# Update or create separate file
&make_dir($scheduled_backups_dir, 0700) if (!-d $scheduled_backups_dir);
$backup->{'id'} ||= &domain_id();
$backup->{'file'} = "$scheduled_backups_dir/$backup->{'id'}";
&lock_file($backup->{'file'});
&write_file($backup->{'file'}, $backup);
&unlock_file($backup->{'file'});
}
# Update or delete cron job
&foreign_require("cron");
local $cmd = $backup_cron_cmd;
$cmd .= " --id $backup->{'id'}" if ($backup->{'id'} != 1);
local $job;
if (!$wasnew) {
local @jobs = &find_cron_script($cmd);
if ($backup->{'id'} == 1) {
# The find_module_cron_job function will match
# backup.pl --id xxx when looking for backup.pl, so we have
# to filter it out
@jobs = grep { $_->{'command'} !~ /\-\-id/ } @jobs;
}
$job = $jobs[0];
}
if ($backup->{'enabled'} && $job) {
# Fix job schedule
©_cron_sched_keys($backup, $job);
if ($job->{'module'}) {
# Webmin cron
&setup_cron_script($job);
}
else {
# Classic cron
&cron::change_cron_job($job);
}
}
elsif ($backup->{'enabled'} && !$job) {
# Create webmincron job
$job = { 'user' => 'root',
'active' => 1,
'command' => $cmd };
©_cron_sched_keys($backup, $job);
&setup_cron_script($job);
}
elsif (!$backup->{'enabled'} && $job) {
# Delete cron job
if ($job->{'module'}) {
# Webmin cron
&delete_cron_script($job);
}
else {
# Classic cron
&cron::delete_cron_job($job);
}
}
&cron::create_wrapper($backup_cron_cmd, $module_name, "backup.pl");
}
# delete_scheduled_backup(&backup)
# Remove one existing backup, and its cron job.
sub delete_scheduled_backup
{
local ($backup) = @_;
$backup->{'id'} || &error("Missing backup ID!");
$backup->{'id'} == 1 && &error("The default backup cannot be deleted!");
&unlink_file($backup->{'file'});
# Delete cron too
local $cmd = $backup_cron_cmd." --id $backup->{'id'}";
local @jobs = &find_cron_script($cmd);
if ($backup->{'id'} == 1) {
@jobs = grep { $_->{'command'} !~ /\-\-id/ } @jobs;
}
if (@jobs) {
&delete_cron_script($jobs[0]);
}
# Also delete logs of this backup
if ($config{'delete_logs'}) {
my @del;
foreach my $log (&list_backup_logs()) {
if ($log->{'sched'} && $log->{'sched'} eq $backup->{'id'}) {
my $id = $log->{'id'};
next if (!$id);
push(@del, $backups_log_dir."/".$id);
push(@del, $backups_log_dir."/".$id.".out");
}
}
if (@del) {
&unlink_file(@del);
}
}
}
# get_backup_as_domain(&domains)
# Returns the domain whose user should be used to run backups
sub get_backup_as_domain
{
my ($doms) = @_;
my ($asd) = grep { !$_->{'parent'} } @$doms;
$asd ||= $doms->[0];
return $asd;
}
# backup_domains(file, &domains, &features, dir-format, skip-errors, &options,
# home-format, &virtualmin-backups, mkdir, onebyone, as-owner,
# &callback-func, differential, on-schedule, &key, kill-running,
# compression-format)
# Perform a backup of one or more domains into a single tar.gz file. Returns
# an OK flag, the size of the backup file, and a list of domains for which
# something went wrong.
sub backup_domains
{
local ($desturls, $doms, $features, $dirfmt, $skip, $opts, $homefmt, $vbs,
$mkdir, $onebyone, $asowner, $cbfunc, $increment, $onsched, $key,
$kill, $compression) = @_;
$opts->{'skip'} = $skip;
$desturls = [ $desturls ] if (!ref($desturls));
local $backupdir;
local $transferred_sz;
# Work out the compression format
if (!$dirfmt && !$homefmt) {
# If backing up to a single file, use the extension to determine the
# compression format
my $c = &suffix_to_compression($desturls->[0]);
if ($c >= 0) {
$compression = $c;
}
}
if (!defined($compression) || $compression eq '') {
# Use global config option for compression format
$compression = $config{'compression'}
}
$opts->{'dir'}->{'compression'} = $compression;
# Make sure differential mode is supported with the compression format
if ($compression == 3 && $increment) {
&$first_print($text{'backup_eincrzip'});
return (0, 0, $doms);
}
# Check if the limit on running backups has been hit
local $err = &check_backup_limits($asowner, $onsched, $desturl);
if ($err) {
&$first_print($err);
return (0, 0, $doms);
}
# Work out who the backup is running as
local $asd = $asowner ? &get_backup_as_domain($doms) : undef;
local $asuser = $asd ? $asd->{'user'} : undef;
# Find the tar command
if (!&get_tar_command()) {
&$first_print($text{'backup_etarcmd'});
return (0, 0, $doms);
}
# Check for clash between encryption and backup format
if ($key && $compression == 3) {
&$first_print($text{'backup_ezipkey'});
return (0, 0, $doms);
}
# Order destinations to put local ones first
@$desturls = sort { ($a =~ /^\// ? 0 : 1) <=> ($b =~ /^\// ? 0 : 1) }
@$desturls;
# See if we can actually connect to the remote server
local $anyremote;
local $anylocal;
local $rsh; # Rackspace cloud files handle
local @okurls;
foreach my $desturl (@$desturls) {
local ($mode, $user, $pass, $server, $path, $port) =
&parse_backup_url($desturl);
if ($mode == 0) {
$desturl = $path; # Canonicalize path
}
if ($mode < 0) {
&$first_print(&text('backup_edesturl', &nice_backup_url($desturl), $user));
return (0, 0, $doms);
}
local $starpass = "*" x length($pass);
if ($mode == 0 && $asd) {
# Always create virtualmin-backup directory
$mkdir = 1;
}
&$first_print(&text('backup_desttest', &nice_backup_url($desturl)));
if ($mode == 1) {
# Try FTP login
local $ftperr;
&ftp_onecommand($server, "PWD", \$ftperr, $user, $pass, $port);
if ($ftperr) {
$ftperr =~ s/\Q$pass\E/$starpass/g;
&$second_print(&text('backup_eftptest', $ftperr));
next;
}
if ($dirfmt) {
# Also create the destination directory and all parents
# (ignoring any error, as it may already exist)
local @makepath = split(/\//, $path);
local $prefix;
if ($makepath[0] eq '') {
# Remove leading /
$prefix = '/';
shift(@makepath);
}
for(my $i=0; $i<@makepath; $i++) {
local $makepath = $prefix.
join("/", @makepath[0..$i]);
local $mkdirerr;
&ftp_onecommand($server, "MKD $makepath",
\$mkdirerr, $user, $pass, $port);
$mkdirerr =~ s/\Q$pass\E/$starpass/g;
}
}
}
elsif ($mode == 2) {
# Extract destination directory and filename
$path =~ /^(.*)\/([^\/]+)\/?$/;
local ($pathdir, $pathfile) = ($1, $2);
# Try a dummy SCP
local $scperr;
local $qserver = &check_ip6address($server) ? "[$server]"
: $server;
local $testuser = $user || "root";
local $testfile = "/tmp/virtualmin-copy-test.$testuser";
local $r = ($user ? "$user\@" : "").$qserver.":".$testfile;
local $temp = &transname();
open(TEMP, ">$temp");
close(TEMP);
&scp_copy($temp, $r, $pass, \$scperr, $port, $asuser);
if ($scperr) {
# Copy to /tmp failed .. try current dir instead
$scperr = undef;
$testfile = "virtualmin-copy-test.$testuser";
$r = ($user ? "$user\@" : "").$qserver.":".$testfile;
&scp_copy($temp, $r, $pass, \$scperr, $port, $asuser);
}
if ($scperr) {
# Copy to ~ failed .. try target dir instead
$scperr = undef;
if ($dirfmt) {
$testfile = "$path/virtualmin-copy-test.$testuser";
}
else {
$testfile = "$pathdir/virtualmin-copy-test.$testuser";
}
$r = ($user ? "$user\@" : "").$qserver.":".$testfile;
&scp_copy($temp, $r, $pass, \$scperr, $port, $asuser);
}
if ($scperr) {
$scperr =~ s/\Q$pass\E/$starpass/g;
&$second_print(&text('backup_escptest', $scperr));
next;
}
# Clean up dummy file if possible
local $sshcmd = "ssh".($port ? " -p $port" : "")." ".
$config{'ssh_args'}." ".
($user ? "$user\@" : "").$server;
local $rmcmd = $sshcmd." rm -f ".quotemeta($testfile);
local $rmerr;
&run_ssh_command($rmcmd, $pass, \$rmerr);
if ($dirfmt && $path ne "/") {
# Also create the destination directory now, by running
# mkdir via ssh or scping an empty dir
# ssh mkdir first
local $mkcmd = $sshcmd." 'mkdir -p $path'";
local $err;
local $lsout = &run_ssh_command($mkcmd, $pass, \$err,
$asuser);
if ($err) {
# Try scping an empty dir
local $empty = &transname($pathfile);
local $mkdirerr;
&make_dir($empty, 0700);
local $r = ($user ? "$user\@" : "").
"$server:$pathdir";
&scp_copy($empty, $r, $pass, \$mkdirerr, $port,
$asuser);
&unlink_file($empty);
}
}
}
elsif ($mode == 3) {
# Connect to S3 service and create bucket
if (!$path && !$dirfmt) {
&$first_print($text{'backup_es3nopath'});
next;
}
local $err = &init_s3_bucket($user, $pass, $server,
$s3_upload_tries,
$config{'s3_location'});
if ($err) {
&$second_print($err);
next;
}
}
elsif ($mode == 6) {
# Connect to Rackspace cloud files and create container
if (!$path && !$dirfmt) {
&$second_print($text{'backup_ersnopath'});
next;
}
$rsh = &rs_connect($config{'rs_endpoint'}, $user, $pass);
if (!ref($rsh)) {
&$second_print($rsh);
next;
}
local $err = &rs_create_container($rsh, $server);
if ($err) {
&$second_print($err);
next;
}
}
elsif ($mode == 7) {
# Connect to Google and create the bucket
local $buckets = &list_gcs_buckets();
if (!ref($buckets)) {
&$second_print($buckets);
next;
}
my ($already) = grep { $_->{'name'} eq $server } @$buckets;
if (!$already) {
local $err = &create_gcs_bucket(
$server, $config{'google_location'});
if ($err) {
&$second_print($err);
next;
}
}
}
elsif ($mode == 8) {
# Connect to Dropbox and create the folder if needed
if ($server) {
my $parent = "/".$server;
$parent =~ s/\/([^\/]+)$//;
$parent =~ s/^\///;
my $files = &list_dropbox_files($parent);
if (!ref($files)) {
&$first_print($files);
next;
}
my ($already) =
grep { $_->{'path_display'} eq "/".$server } @$files;
if (!$already) {
my $err = &create_dropbox_dir("/".$server);
if ($err) {
&$second_print($err);
next;
}
}
}
}
elsif ($mode == 9) {
# Connect to the remote Webmin server
local $w = &dest_to_webmin($desturl);
eval {
local $main::error_must_die = 1;
&remote_foreign_require($w, "webmin");
if ($dirfmt && $path ne "/") {
# Remotely create the destination dir
&remote_foreign_call($w, "webmin", "make_dir",
$path, undef, 1);
}
};
if ($@) {
my $err = $@;
$err =~ s/\s+at\s+\S+\s+line\s+\d+.*//g;
&$second_print($err);
next;
}
}
elsif ($mode == 10) {
# Connect to Backblaze and create the bucket
local $already = &get_bb_bucket($server);
if ($already && !ref($already)) {
&$second_print($already);
next;
}
if (!$already) {
local $err = &create_bb_bucket($server);
if ($err) {
&$second_print($err);
next;
}
}
}
elsif ($mode == 11) {
# Connect to Azure and create the container
local $containers = &list_azure_containers();
if (!ref($containers)) {
&$second_print($containers);
next;
}
my ($already) = grep { $_->{'name'} eq $server } @$containers;
if (!$already) {
local $err = &create_azure_container($server);
if ($err) {
&$second_print($err);
next;
}
}
}
elsif ($mode == 12) {
# Connect to Drive and create the folder
my $folders = &list_drive_folders();
if (!ref($folders)) {
&$second_print($folders);
next;
}
if (!$path && !$homefmt && !$dirfmt) {
&$second_print($text{'backup_edesthomedir'});
next;
}
my $already = &get_drive_folder($server);
if (!ref($already)) {
local $err = &create_drive_folder($server);
if ($err) {
&$second_print($err);
next;
}
}
}
elsif ($mode == 0) {
# Make sure target is / is not a directory
if ($dirfmt && !-d $desturl) {
# Looking for a directory
my $destdir = $desturl;
$destdir =~ s/\/[^\/]+$//;
my $derr;
if ($mkdir) {
# Create the directory as the domain
# user, and check that it worked
$derr = &make_backup_dir(
$desturl, 0700, 1, $asd);
}
elsif ($destdir && -d $destdir &&
$opts->{'dir'}->{'strftime'}) {
# Caller didn't request that the destination
# directory be created, but since the last part
# of the path is date-formatted, create it
# anyway
$derr = &make_backup_dir(
$desturl, 0700, 1, $asd);
}
else {
# Destination directory doesn't exist yet
&$second_print(&text('backup_edirtest',
"<tt>$desturl</tt>"));
next;
}
if ($derr) {
&$second_print(&text('backup_emkdir',
"<tt>$desturl</tt>", $derr));
next;
}
}
elsif (!$dirfmt && -d $desturl) {
# Destination already exists and is a directory, but
# we're expecting to write a file
&$second_print(&text('backup_enotdirtest',
"<tt>$desturl</tt>"));
next;
}
if (!$dirfmt && $mkdir) {
# Create parent directories for a file backup
local $dirdest = $desturl;
$dirdest =~ s/\/[^\/]+$//;
if ($dirdest && !-d $dirdest) {
local $derr = &make_backup_dir(
$dirdest, 0700, 0, $asd);
if ($derr) {
&$second_print(&text('backup_emkdir',
"<tt>$dirdest</tt>", $derr));
next;
}
}
}
}
&$second_print($text{'setup_done'});
# If we made it this far, the URL is valid
push(@okurls, $desturl);
$anyremote = 1 if ($mode > 0);
$anylocal = 1 if ($mode == 0);
}
if (!@okurls) {
# No URLs were valid
return (0, 0, $doms);
}
@$desturls = @okurls;
if (!$anyremote) {
# If all backups are local, there is no point transferring one by one
$onebyone = 0;
}
if ($homefmt && $dirfmt && &indexof("dir", @$features) < 0) {
# A home-format backup was requested, but the home directory was not
# included. Silently switch to dir-format so that it still works.
$homefmt = 0;
}
if (!$homefmt) {
# Create a temp dir for the backup, to be tarred up later
$backupdir = &transname();
if (!-d $backupdir) {
&make_dir($backupdir, 0700);
}
}
if ($homefmt && !$dirfmt) {
# Home format must imply one-per-domain format
&$first_print($text{'backup_ehomeformat'});
return (0, 0, $doms);
}
# Work out where to write the final tar files to
local ($dest, @destfiles, %destfiles_map);
local ($mode0, $user0, $pass0, $server0, $path0, $port0) =
&parse_backup_url($desturls->[0]);
if (!$anylocal) {
# Write archive to temporary file/dir first, for later upload
$path0 =~ /^(.*)\/([^\/]+)\/?$/;
local ($pathdir, $pathfile) = ($1, $2);
$dest = &transname($$."-".$pathfile);
}
else {
# Can write direct to destination (which we might also upload from)
$dest = $path0;
}
if ($dirfmt && !-d $dest) {
# If backing up to a directory that doesn't exist yet, create it
local $derr = &make_backup_dir($dest, 0700, 1, $asd);
if ($derr) {
&$first_print(&text('backup_emkdir', "<tt>$dest</tt>", $derr));
return (0, 0, $doms);
}
}
elsif (!$dirfmt && $anyremote && $asd) {
# Backing up to a temp file as domain owner .. create first
&open_tempfile(DEST, ">$dest");
&close_tempfile(DEST);
&set_ownership_permissions($asd->{'uid'}, $asd->{'gid'}, undef, $dest);
}
# For a home-format backup, the home has to be last
local @backupfeatures = @$features;
local $hfsuffix;
if ($homefmt) {
@backupfeatures = ((grep { $_ ne "dir" } @$features), "dir");
$hfsuffix = &compression_to_suffix($compression);
}
# Take a lock on the backup destination, to avoid concurrent backups to
# the same dest
local @lockfiles;
foreach my $desturl (@$desturls) {
local $lockname = $desturl;
$lockname =~ s/\//_/g;
$lockname =~ s/\s/_/g;
if (!-d $backup_locks_dir) {
&make_dir($backup_locks_dir, 0700);
}
local $lockfile = $backup_locks_dir."/".$lockname;
local $lpid = &test_lock($lockfile);
if ($kill == 2 && $lpid) {
# Destination is locked, wait for it to free up
&$first_print(&text('backup_waitlock', $lpid));
while($lpid = &test_lock($lockfile)) {
sleep(1);
}
&$second_print($text{'backup_donelock'});
}
elsif ($kill != 2 && $lpid) {
# Destination is already locked
if ($kill == 1 && $lpid != $$) {
# Kill the current backup
&kill_logged('TERM', $lpid);
sleep(2);
if (&test_lock($lockfile)) {
&kill_logged('KILL', $lpid);
}
&$second_print(&text('backup_ekilllock', $lpid));
}
else {
# Exit immediately
&$second_print(&text('backup_esamelock', $lpid));
return (0, 0, $doms);
}
}
&lock_file($lockfile);
push(@lockfiles, $lockfile);
}
# Go through all the domains, and for each feature call the backup function
# to add it to the backup directory
local $d;
local $ok = 1;
local @donedoms;
local ($okcount, $errcount) = (0, 0);
local @errdoms;
local %donefeatures; # Map from domain name->features
local @cleanuphomes; # Temporary homes
local %donedoms; # Map from domain name->hash
local $failalldoms;
DOMAIN: foreach $d (sort { $a->{'dom'} cmp $b->{'dom'} } @$doms) {
# Force lock and re-read the domain in case it has changed
&obtain_lock_everything($d);
&lock_domain($d);
my $reread_d = &get_domain($d->{'id'}, undef, 1);
if ($reread_d) {
$d = $reread_d;
}
else {
# Has been deleted!
&$second_print(&text('backup_deleteddom',
&show_domain_name($d)));
$dok = 0;
goto DOMAINFAILED_NOQUOTAS;
}
my $parent = $d->{'parent'} ? &get_domain($d->{'parent'}) : undef;
if ($parent) {
my $reread_parent = &get_domain($parent->{'id'}, undef, 1);
if (!$reread_parent) {
# Parent has been deleted!
&$second_print(&text('backup_deleteddom',
&show_domain_name($parent)));
$dok = 0;
goto DOMAINFAILED_NOQUOTAS;
}
&obtain_lock_everything($parent);
}
# Ensure the backup dest dir is writable by this domain
if (!$homefmt) {
&set_ownership_permissions($d->{'uid'}, $d->{'gid'},
undef, $backupdir);
}
# Make sure there are no databases that don't really exist, as these
# can cause database feature backups to fail.
my @alldbs = &all_databases($d);
&resync_all_databases($d, \@alldbs);
my $dstart = time();
# Begin doing this domain
&$cbfunc($d, 0, $backupdir) if ($cbfunc);
&$first_print(&text('backup_fordomain', &show_domain_name($d) ||
$d->{'id'}));
if (!$d->{'dom'} || !$d->{'home'}) {
# Has no domain name!
&$second_print($text{'backup_emptydomain'});
$dok = 0;
goto DOMAINFAILED_NOQUOTAS;
}
local $f;
local $dok = 1;
local @donefeatures;
if ($homefmt && !-d $d->{'home'}) {
# Create home directory
if (&has_domain_user($d) && $d->{'parent'}) {
# As domain user (sub-server, likely an alias)
&make_dir_as_domain_user($d, $d->{'home'}, 0755, 1);
&set_permissions_as_domain_user($d, 0755, $d->{'home'});
}
else {
# As root (top-level, which should never happen)
&make_dir($d->{'home'}, 0755);
&set_ownership_permissions(
$d->{'uid'}, $d->{'gid'}, undef, $d->{'home'});
}
if (!$d->{'dir'}) {
# Only temporary
$d->{'dir'} = 1;
push(@cleanuphomes, $d);
}
}
elsif ($homefmt && !$d->{'dir'} && -d $d->{'home'}) {
# Home directory actually exists, so enable it on the domain
$d->{'dir'} = 1;
}
# Turn off quotas for the domain so that writes as the domain owner
# don't fail
&disable_quotas($d);
local $lockdir;
if ($homefmt) {
# Backup for most features goes to a sub-dir of the home, which
# is then included in a tar of the home directory
$lockdir = $backupdir = "$d->{'home'}/.backup";
&lock_file($lockdir);
&execute_command("rm -rf ".quotemeta($backupdir));
&disable_quotas($asd) if ($asd);
local $derr = &make_backup_dir($backupdir, 0777, 0, $asd);
&enable_quotas($asd) if ($asd);
if ($derr) {
&$second_print(&text('backup_ebackupdir',
"<tt>$backupdir</tt>", $derr));
$dok = 1;
goto DOMAINFAILED;
}
# If this script exits unexpectedly, cleaup the temporary dir
push(@main::temporary_files, $backupdir);
}
&$indent_print();
my @bplugins = &list_backup_plugins();
foreach $f (@backupfeatures) {
my $bfunc = "backup_$f";
my $fok;
my $ffile = "$backupdir/$d->{'dom'}_$f";
if (&indexof($f, @bplugins) < 0 &&
defined(&$bfunc) &&
($d->{$f} || $f eq "virtualmin" ||
$f eq "mail" && &can_domain_have_users($d))) {
# Call core feature backup function
if ($homefmt && $f eq "dir") {
# For a home format backup, write the home
# itself to the backup destination
$ffile = "$dest/$d->{'dom'}.$hfsuffix";
}
eval {
local $main::error_must_die = 1;
$fok = &$bfunc(
$d, $ffile, $opts->{$f}, $homefmt,
$increment, $asd, $opts, $key);
};
if ($@) {
my $err = $@;
$err =~ s/\s+at\s+\S+\s+line\s+\d+.*//g;
&$second_print(&text('backup_efeatureeval',
$f, $err));
$fok = 0;
}
}
elsif (&indexof($f, @bplugins) >= 0 && $d->{$f}) {
# Call plugin backup function
$fok = &plugin_call($f, "feature_backup",
$d, $ffile, $opts->{$f}, $homefmt,
$increment, $asd, $opts);
}
elsif (&indexof($f, @bplugins) >= 0) {
# Call plugin always backup function
$fok = &plugin_call($f, "feature_always_backup",
$d, $ffile, $opts->{$f}, $homefmt,
$increment, $asd, $opts);
}
if (defined($fok)) {
# See if it worked or not
if (!$fok) {
# Didn't work .. remove failed file, so we
# don't have partial data
if ($ffile && $f ne "dir" &&
$f ne "mysql" && $f ne "postgres") {
foreach my $ff ($ffile,
glob("${ffile}_*")) {
&unlink_file($ff);
}
}
$dok = 0;
}
if (!$fok && (!$skip || $homefmt && $f eq "dir")) {
# If this feature failed and errors aren't being
# skipped, stop the backup. Also stop if this
# was the directory step of a home-format backup
$ok = 0;
$errcount++;
push(@errdoms, $d);
$failalldoms = 1;
goto DOMAINFAILED;
}
push(@donedoms, &clean_domain_passwords($d));
}
if ($fok) {
push(@donefeatures, $f);
}
}
# At this point the .backup directory is in a tar file, so we can
# remove it to save disk space
if ($homefmt && $backupdir &&
&is_under_directory($d->{'home'}, $backupdir)) {
&execute_command("rm -rf ".quotemeta($backupdir));
}
DOMAINFAILED:
&enable_quotas($d);
DOMAINFAILED_NOQUOTAS:
if ($lockdir) {
&unlock_file($lockdir);
}
last if ($failalldoms);
$donefeatures{$d->{'dom'}} = \@donefeatures;
$donedoms{$d->{'dom'}} = $d;
if ($dok) {
$okcount++;
}
else {
$errcount++;
push(@errdoms, $d);
}
if ($onebyone && $homefmt && $dok && $anyremote) {
# Transfer this domain now
local $df = "$d->{'dom'}.$hfsuffix";
&$cbfunc($d, 1, "$dest/$df") if ($cbfunc);
local $tstart = time();
local $binfo = { $d->{'dom'} =>
$donefeatures{$d->{'dom'}} };
local $bdom = { $d->{'dom'} => &clean_domain_passwords($d) };
local $infotemp = &transname();
&uncat_file($infotemp, &serialise_variable($binfo));
local $domtemp = &transname();
&uncat_file($domtemp, &serialise_variable($bdom));
local $done_transferred_sz = 0;
foreach my $desturl (@$desturls) {
local ($mode, $user, $pass, $server, $path, $port) =
&parse_backup_url($desturl);
local $starpass = "*" x length($pass);
local $err;
if ($mode == 0 && $path ne $path0) {
# Copy to another local directory
&$first_print(&text('backup_copy',
"<tt>$path/$df</tt>"));
local $ok;
if ($asd) {
($ok, $err) =
©_source_dest_as_domain_user(
$asd, "$path0/$df", "$path/$df");
($ok, $err) =
©_source_dest_as_domain_user(
$asd, $infotemp, "$path/$df.info")
if (!$err);
($ok, $err) =
©_source_dest_as_domain_user(
$asd, $domtemp, "$path/$df.dom")
if (!$err);
}
else {
($ok, $err) = ©_source_dest(