forked from dimikot/dklab_realsync
-
Notifications
You must be signed in to change notification settings - Fork 1
/
realsync
executable file
·1551 lines (1366 loc) · 45.7 KB
/
realsync
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
#!/usr/bin/perl -w
use Cwd qw(getcwd abs_path);
use strict;
use File::Basename;
use File::Path qw(mkpath rmtree);
use File::Spec;
use Text::ParseWords;
use IPC::Open2;
use IO::Handle;
use Digest::MD5 'md5_hex';
use Fcntl ':mode';
use POSIX ":sys_wait_h";
use threads;
use threads::shared;
# Paths (will be filled later automatically).
my $DIR_PRIVATE = undef; # private area directory (holds e.g. .ssh folder)
my $FILE_CONFIG = undef; # config file
my $FILE_IDENTITY = undef; # identity file within .ssh folder
# Constants.
my $BINDIR = dirname(abs_path(__FILE__));
my $DELAY = 0.2;
my $DEBUG_PATCH_TREE = 0;
my $SSH_VERBOSE = 0;
my $MIN_CHANGES_FOR_RSYNC = 10;
my @SSH_OPTIONS = (
"-o", "Compression=yes",
"-o", "CompressionLevel=9",
"-o", "ConnectTimeout=3",
"-o", "ServerAliveInterval=2",
"-o", "ServerAliveCountMax=4",
"-o", "StrictHostKeyChecking=no",
);
my @RSYNC_OPTIONS = (
"-rltzxv",
"--delete",
);
my @RSYNC_WRAPPER = ();
my @RSYNC_SSH_WRAPPER = ();
# Globals.
my %CONFIG;
my $REM_SCRIPT = get_remote_script();
my $SSH_PID;
my @TREE;
my $IN_REPLICATION = 0;
my $HOOKS =
($ENV{COMSPEC} && 'Realsync::Win32')
|| ($^O =~ /darwin/i && 'Realsync::Darwin')
|| ($^O =~ /linux/i && 'Realsync::Linux')
|| 'Realsync::Generic';
my %PENDING: shared = ();
#
# Does everything,
#
sub main {
eval {
print "dkLab RealSync: replicate developer's files over SSH in realtime.\n\n";
# Make remote script's subs available.
eval("sub { $REM_SCRIPT }"); die $@ if $@;
# If an argument is passed, chdir to that directory. Else use the current one.
my $chdir = $ARGV[0];
if (!defined $chdir && -f '.realsync') {
$chdir = ".";
}
if (!defined $chdir) {
die "Usage:\n realsync SOURCE_DIRECTORY_WHICH_IS_REPLICATED\n";
}
chdir($chdir) or die "Cannot set current directory to $chdir: $!\n";
# Initialize and (possibly) correct environment.
$HOOKS->init_env();
# Correct pathes.
build_pathes_based_on_cwd();
# Run the mainloop.
mainloop();
};
if ($@) {
if (!$IN_REPLICATION) {
print STDERR $@;
} else {
logger($@);
}
print STDERR "\nPress Enter to quit... ";
scalar <STDIN>;
}
}
#
# Main execution loop.
# Called inside eval{} block to catch errors and print them.
#
sub mainloop {
binmode(STDIN); STDIN->autoflush(1);
binmode(STDOUT); STDOUT->autoflush(1);
binmode(STDERR); STDERR->autoflush(1);
$SIG{CHLD} = 'IGNORE'; # later, if you use system(), reset this signal!
$SIG{PIPE} = 'IGNORE'; # do not kill the whole realsync if remote SSH dies
$SIG{INT} = $SIG{TERM} = $SIG{KILL} = sub { onexit(); exit; };
if (!-d $DIR_PRIVATE || !-f $FILE_CONFIG) {
do_install();
}
# If we use a custom identity file, switch home dir to its directory.
if (-f $FILE_IDENTITY) {
$ENV{HOME} = $DIR_PRIVATE;
}
# Read configuration.
%CONFIG = read_config($FILE_CONFIG);
# We MUST avoid chdir: in Cygwin we have problems with non-ASCII names.
-d cfg("local") or die "Bad local directory " . cfg("local") . ": $!\n";
$IN_REPLICATION = 1;
spawn_notify_daemon();
$HOOKS->init_gui();
while (1) {
eval { do_replication() };
logger($@) if $@;
onexit(1);
}
}
#
# Called at script dead.
#
sub onexit {
my ($iteration_end) = @_;
if ($IN_REPLICATION) {
kill(9, $SSH_PID) if $SSH_PID;
$SSH_PID = undef;
$HOOKS->notification("wait") if $HOOKS;
}
if (!$iteration_end) {
$HOOKS->finalize_env() if $HOOKS;
}
}
#
# Called at the end of script.
#
sub END {
onexit();
}
#
# Builds pathes and saves it to global variables.
#
sub build_pathes_based_on_cwd {
my $dir_appdata = ($ENV{APPDATA} || $ENV{HOME}) or die "Environment variable HOME must be set!\n";
# First, try to use legacy scheme.
build_pathes_based_on_cwd_legacy($dir_appdata);
return if -f $FILE_CONFIG;
# Use a new scheme.
my $cwd = getcwd();
my $hash = $cwd;
$hash =~ s{^\w:[/\\]|[/\\]+$}{}sg;
$hash =~ s{\W+}{_}sgi;
$hash = substr($hash, -80) if length($hash) > 80;
$hash = substr(md5_hex($cwd), 0, 10) . "_" . $hash;
# Build pathes.
$DIR_PRIVATE = $dir_appdata . "/.realsync/" . $hash;
$FILE_IDENTITY = "$DIR_PRIVATE/.ssh/identity";
$FILE_CONFIG = "$cwd/.realsync";
}
#
# Legacy pathes for configuration.
#
sub build_pathes_based_on_cwd_legacy {
my ($dir_appdata) = @_;
$DIR_PRIVATE = $dir_appdata . "/.realsync/" . substr(md5_hex(getcwd()), 0, 10);
$FILE_CONFIG = "$DIR_PRIVATE/realsync.ini";
$FILE_IDENTITY = "$DIR_PRIVATE/.ssh/identity";
}
#
# Executes the whole replication algorithm.
#
sub do_replication {
# Run SSH asynchronously to save time.
do_run_ssh("Initiating a background connection with " . cfg("remote") . "...");
# Read initial state BEFORE rsync!
@TREE = ();
my $num_objs = grep { $_->{type} eq "dir" } get_changes();
# Initial rsync.
do_rsync("Fast initial rsync synchronization...") if !$DEBUG_PATCH_TREE;
# Watching.
logger("", 0, 1);
do_watch("Watching for changes in $num_objs folder(s)...");
}
#
# Executes RSYNC command.
#
sub do_rsync {
my ($msg) = @_;
my ($h_host, $h_port) = parse_host_spec(cfg("host"));
my @rsync_cmd = (
@RSYNC_WRAPPER,
"rsync",
"-e", join(" ",
@RSYNC_SSH_WRAPPER,
"ssh",
(-f $FILE_IDENTITY? ("-i", $FILE_IDENTITY) : ()),
split_cmd_args(cfg("ssh_options")),
"-p$h_port"
),
split_cmd_args(cfg("rsync_options")),
$HOOKS->convert_rsync_local_path(cfg("local")) . "/", # the trailing slash is significant!
cfg("user") . '@' . $h_host . ":" . cfg("remote") . "/",
map { ("--exclude", $_) } @{cfg("exclude", 1)},
);
$HOOKS->notification("rsync");
while (1) {
logger($msg);
#logger(join(" ", map { /\s|\*/s? '"' . $_ . '"' : $_ } @rsync_cmd));
local $SIG{CHLD}; # else system() does not work
local $SIG{PIPE}; # to be on a safe side
my $exitcode = system(@rsync_cmd);
if (!defined $exitcode || $exitcode < 0) {
logger("Failed to run rsync: $!\n");
} elsif ($exitcode & 127) {
logger("Rsync died with signal " . ($exitcode & 127));
} elsif (($exitcode >> 8) == 0) {
last;
} else {
logger("Rsync exited with code " . ($exitcode >> 8) . ", retrying...");
}
usleep(0.5);
}
$HOOKS->notification("wait");
}
#
# Executes background SSH process which is used to push changes.
#
sub do_run_ssh {
my ($msg) = @_;
logger($msg);
my $rem_script = $REM_SCRIPT;
$rem_script =~ s/!/@@/sg; # for tcsh
my ($h_host, $h_port) = parse_host_spec(cfg("host"));
my @ssh_cmd = (
"ssh",
($SSH_VERBOSE? ("-v") : ()),
(-f $FILE_IDENTITY? ("-i", $FILE_IDENTITY) : ()),
split_cmd_args(cfg("ssh_options")),
"-p$h_port",
cfg("user") . '@' . $h_host,
# For TCSH we must NEVER insert "!" character into arguments, else it
# breaks the program. So we previously replace "!" to "@@" and then,
# at the remote side, replace it back to "!", but with no "!" specification.
q{exec perl -we '$_=$ARGV[0]; s/@@/\x21/sg; eval($_); die $@ if $@;'} . " '$rem_script'"
);
# use Data::Dumper; print Dumper(\@ssh_cmd); exit;
# Unfortunately on Win32 we cannot read from a handle returned
# from the first open2's argument - Perl hangs even if buffering
# is correctly turned off. So we cannot receive a feedback from
# a remote SSH and are just passively displaying its output.
$SSH_PID = open2(">&STDOUT", \*IN, @ssh_cmd) or die "Cannot run ssh: $!\n";
binmode IN; IN->autoflush(1);
}
#
# Performs endless changes watching.
#
sub do_watch {
my ($msg) = @_;
logger($msg);
# Watching loop.
print IN cfg("remote") . "\n";
$HOOKS->notification("replication");
my $candidates = undef;
while(1) {
my @changes = get_changes($candidates);
if (@changes > $MIN_CHANGES_FOR_RSYNC) {
do_rsync("Detected changes in more than $MIN_CHANGES_FOR_RSYNC objects. Running rsync: it's faster.");
} elsif (@changes) {
logger("Detected " . @changes . " change(s), transmitting...");
$HOOKS->notification("transfer");
foreach my $change (@changes) {
write_change(\*IN, $change);
}
$HOOKS->notification("wait");
}
# Wait with periodical callback checking.
$candidates = wait_notify(sub {
if (!$SSH_PID || !kill(0, $SSH_PID)) {
die "SSH client died, restarting.\n";
}
});
}
}
#
# Performs installation process.
#
sub do_install {
local $SIG{CHLD}; # else system() does not work
local $SIG{PIPE}; # to be on a safe side
my $step_num = 1;
my $step_max = 6;
my $step_text = sub {
my $s = "(Step $step_num/$step_max) $_[0]";
$step_num++;
return $s;
};
print "Starting $step_max-steps interactive installation.\n\n";
print "THIS WIZARD IS APPEARED ONLY ONCE!\n";
print "NEXT TIME THE REPLICATION WILL BE STARTED IMMEDIATELY.\n\n";
my @default_excludes = (".realsync", "CVS", ".git", ".svn", ".hg", ".cache", ".idea", "nbproject", "~*", "*.tmp", "*.pyc", "*.swp");
my @config = ();
push @config, {
"name" => "local",
"value" => (my $local = ask(
$step_text->("LOCAL directory to replicate FROM:\n "),
getcwd(),
sub { -d $_? undef : "No such directory: $_" }
)),
"comment" => "Local directory to be realtime-replicated.",
};
$local =~ s{\\}{/}sg;
$local =~ s{/+$}{}sg;
chdir($local) or die "Cannot chdir to $local: $!\n";
build_pathes_based_on_cwd();
mkpath($DIR_PRIVATE, 0, 0700);
my $host = undef;
my $user = undef;
my $step_save = $step_num;
while (1) {
$step_num = $step_save;
push @config, {
"name" => "host",
"value" => ($host = ask(
$step_text->("REMOTE host to replicate TO (host or host:port):"),
$host,
sub { /^[-\w.]+(?::\d+)?$/s ? undef : "Invalid hostname!" }
)),
"comment" => "Remote host to replicate to over SSH.",
};
push @config, {
"name" => "user",
"value" => ($user = ask(
$step_text->("REMOTE SSH login at $host:"),
$user,
sub { /^\S+$/s ? undef : "Invalid login format!" }
)),
"comment" => "User to connect to the remote host.",
};
# Check if we already have a passwordless access.
print " checking if we have access without a password to this host...\n";
my ($h_host, $h_port) = parse_host_spec($host);
my $cmd_check = "ssh -q -o PasswordAuthentication=no -o BatchMode=yes -o StrictHostKeyChecking=no -p$h_port $user\@$h_host exit";
if (system($cmd_check) == 0) {
print " we already have access to the host, continuing.\n";
last;
} else {
print " no access, generating new SSH keys.\n";
}
# Use a custom SSH key (create a new one if no key exists).
mkpath(dirname($FILE_IDENTITY), 0, 0700);
if (!-f $FILE_IDENTITY) {
my $cmd = "ssh-keygen -N \"\" -q -t rsa -b 2048 -f $FILE_IDENTITY";
if (system($cmd)) {
die "Cannot generate SSH keys. ssh-keygen: $!\n$cmd\n";
}
# Temporarily rename the file to avoid the case when the next
# pubkey copying failed and the user restarts realsync again.
rename($FILE_IDENTITY, "$FILE_IDENTITY.tmp");
}
# For users who ask: "should I enter my password each time?"
ask($step_text->("ONLY ONCE you will be asked for a password. Continue?"), "y");
my $pub_file = "$FILE_IDENTITY.pub";
# system() is better than popen(), because Perl does not flush a child
# process'es STDERR till we read from STDIN (Win32 perl bug?).
print "Copying SSH key to $user\@$host. Executing:\n";
my $cmd = "ssh"
. " -o StrictHostKeyChecking=no -p$h_port $user\@$h_host\n"
. ' "cd; umask 077; test -d .ssh || mkdir .ssh; (echo; cat) >> .ssh/authorized_keys"';
my $show = '$ ' . $cmd;
print "$show\n";
$cmd =~ s/\s*\n\s*/ /sg;
if (system("$cmd < $pub_file")) {
print STDERR "\n";
print STDERR "Failed connecting to $user\@$host. Please enter a correct host, login and password.\n";
print STDERR "\n";
next;
}
print "Public key $pub_file is copied to $user\@$host!\n";
print "\n";
# Successfully copied, so rename the file back.
rename("$FILE_IDENTITY.tmp", $FILE_IDENTITY);
last;
}
push @config, {
"name" => "remote",
"value" => ask(
$step_text->("REMOTE directory at $user\@$host to replicate to:"),
undef,
sub {
print " checking if the directory exists...\n";
my ($h_host, $h_port) = parse_host_spec($host);
my $cmd = "ssh"
. (-f $FILE_IDENTITY? " -i $FILE_IDENTITY" : "")
. " -o StrictHostKeyChecking=no -p$h_port $user\@$h_host \"test -d $_\"";
my $ret = system($cmd) >> 8;
if ($ret != 0) {
return "Directory $_ at $user\@$host does not exist. Try again.";
}
return;
}
),
"comment" => "Directory at the remote host to replicate files to.",
};
print "\n";
my $excludes = ask(
$step_text->(
"Exclusions from " . basename($FILE_CONFIG) . " configuration are:\n" .
" " . join(" ", @default_excludes) . "\n" .
"Enter a space-separated list of ADDITIONAL exclusions:",
),
""
);
my $first = 1;
foreach my $mask (@default_excludes, grep { length } split(m/[\s+,]+/s, $excludes)) {
push @config, {
"name" => "exclude",
"value" => $mask,
"comment" => $first? "Pathname wildcards to be excluded from the replication.\nUse \"*\" for any filename character and \"**\" for any character,\nincluding \"/\" in pathnames." : undef,
};
$first = 0;
}
push @config, {
"name" => "nosound",
"value" => "0",
"comment" => "To turn off \"synchronization ding\" sound, set the following to 1.",
};
push @config, {
"name" => "#load",
"value" => "some_file.ini",
"comment" => "If you need to load some other config file from here, uncomment\nand correct the following directive:",
};
push @config, {
"name" => "#rsync_options",
"value" => join(" ", @RSYNC_OPTIONS),
"comment" => "Options passed to RSYNC.",
};
push @config, {
"name" => "#ssh_options",
"value" => join(" ", @SSH_OPTIONS),
"comment" => "Options passed to SSH.",
};
print "\n";
open(local *F, ">", $FILE_CONFIG);
print F "##\n";
print F "## dkLab RealSync configuration file.\n";
print F "##\n";
foreach my $opt (@config) {
my $comment = $opt->{comment};
if ($comment) {
$comment =~ s/^/# /mg;
print F "\n$comment\n";
}
print F $opt->{name} . " = " . $opt->{value} . "\n";
}
close(F);
print "All done. Configuration is saved to:\n";
print " $FILE_CONFIG\n";
if (-f $FILE_IDENTITY) {
print "Generated SSH private key is saved to:\n";
print " $FILE_IDENTITY\n";
}
print "\n";
print "Press Enter start the replication. ";
scalar <STDIN>;
}
#
# Asks a question interactively.
# Used by installer only.
#
sub ask {
my ($msg, $default, $check) = @_;
while (1) {
print $msg . " ";
print "[" . (length $default? $default : "<none>") . "] " if defined $default;
local $_ = <STDIN>;
s/^\s+|\s+$//sg;
if ($_ eq "") {
return $default if defined $default;
next;
}
if ($check) {
my $err = $check->();
if ($err) {
print "$err\n";
next;
}
}
return $_;
}
}
#
# Reads a config item value.
#
sub cfg {
my ($name, $nodie) = @_;
my $value = $CONFIG{$name};
if ($name eq "ssh_options") {
$value ||= join(" ", @SSH_OPTIONS);
}
if ($name eq "rsync_options") {
$value ||= join(" ", @RSYNC_OPTIONS);
}
if (!$nodie) {
if (!defined $value) {
die("Cannot read \"$name\" configuration option at $FILE_CONFIG!\n");
}
}
if ($name eq "local" || $name eq "remote") {
# Trailing slash is removed, but added at rsync call manually,
# because it is significant for rsync.
$value =~ s{[/\\]+$}{}sg;
}
return $value;
}
#
# Precise sleep function.
#
sub usleep {
my ($delay) = @_;
select(undef, undef, undef, $delay);
}
#
# Pass information about background file changes monitoring.
# This is an abstraction level for multi-thread communication.
#
{
my $NOTIFIES_SUPPORTED: shared = 0;
my @NOTIFIES: shared = ();
sub notifies_set_supported {
my ($flag) = @_;
lock $NOTIFIES_SUPPORTED;
$NOTIFIES_SUPPORTED = !!$flag;
}
sub notifies_is_supported {
lock $NOTIFIES_SUPPORTED;
return $NOTIFIES_SUPPORTED;
}
sub notifies_push {
lock @NOTIFIES;
push @NOTIFIES, @_;
}
sub notifies_pop {
lock @NOTIFIES;
my @changes = @NOTIFIES;
@NOTIFIES = ();
return @changes;
}
}
#
# Calculates filesystem changes between the previous call to
# get_changes() and the current time.
#
sub get_changes {
my ($candidates) = @_;
my @changes = ();
# Build current tree.
my @cur_tree = ();
if (!$candidates || !@$candidates) {
make_tree(\@cur_tree, ".");
} else {
@cur_tree = @TREE;
$candidates = expand_dir_candidates(\@cur_tree, $candidates);
if ($DEBUG_PATCH_TREE) {
foreach (@$candidates) { print "Candidate: $_\n" }
}
patch_tree(\@cur_tree, $candidates);
}
# foreach (@cur_tree) { print $_->{name} . "\n"; } print "\n";
# use Data::Dumper; print Dumper(\@cur_tree); exit;
# Collect deleted entries.
my %cur_tree = map { ($_->{name} => $_) } @cur_tree;
for (my $i = 0; $i < @TREE; $i++) {
my $prev = $TREE[$i];
my $name = $prev->{name};
if (!$cur_tree{$name}) {
push @changes, {
type => "del",
name => $name,
};
# Skip children entries.
for (++$i; $i < @TREE; $i++) {
last if substr($TREE[$i]->{name}, 0, length($name) + 1) ne "$name/";
}
--$i;
}
}
# Collect added entries.
my %TREE = map { ($_->{name} => $_) } @TREE;
foreach my $cur (@cur_tree) {
my $name = $cur->{name};
if (!$TREE{$name} || $TREE{$name}{stamp} != $cur->{stamp} || $TREE{$name}{perm} ne $cur->{perm}) {
push @changes, $cur;
}
}
# use Data::Dumper; open(local *F, ">/realsync.debug"); print F Dumper(\@TREE) . "\n\n"; print F Dumper(\@changes);
@TREE = @cur_tree;
return @changes;
}
#
# Reads filesystem information about $rel.
# Returns undef if no such file/directory exists.
#
sub make_tree_item {
my ($rel) = @_;
my $exclude_re = cfg("exclude_re", 1);
# We use substr($rel, 1) below, because we need to cut leading "."
# (rel pathes are ALWAYS started with ".", so we must cat to avoid its
# matching with ".*" glob wildcard: e.g. "./aa/b" does match ".*"
# glob wildcard, but "/aa/b" - does not.
return if $exclude_re && $rel ne "." && substr($rel, 1) =~ $exclude_re;
my $local = cfg("local");
my $fullpath = "$local/$rel";
my @stat = stat($fullpath);
return if !@stat; # hmm? but it is needed for linux mcedit
my $cur = {
path => $fullpath,
name => $rel,
stamp => $stat[9],
perm => ($HOOKS eq 'Realsync::Win32'? "" : ($stat[2] & 0777)), # Skip perms for Windows
};
if (S_ISREG($stat[2])) {
$cur->{type} = "fil";
} elsif (S_ISDIR($stat[2])) {
$cur->{type} = "dir";
}
return $cur;
}
#
# Makes a tree from the filesystem. You may limit recursion by $max_level: e.g.
# if it is 1, only $rel and its direct children (if any) are returned.
#
sub make_tree {
my ($tree, $rel, $max_level) = @_;
my $cur = make_tree_item($rel) or return;
push @$tree, $cur;
return if defined($max_level) && $max_level == 0;
if ($cur->{type} eq "dir") {
opendir(local *D, $cur->{path}) or die "Cannot opendir $cur->{path}: $!\n";
my @content = sort readdir(D); # sort is VERY important here! we use bsearch!
closedir(D);
foreach my $e (@content) {
next if $e eq "." || $e eq "..";
make_tree($tree, $cur->{name} . "/" . $e, (defined($max_level)? $max_level - 1 : undef));
}
}
}
#
# Updates the current tree in memory checking statuses of enumerated
# candidate elements (each of them may be changed, added or removed).
#
sub patch_tree {
my ($tree, $candidates) = @_;
foreach my $cand (@$candidates) {
my $branch_start_idx = find_branch_start_in_tree($tree, $cand);
if (!defined($tree->[$branch_start_idx]) || $tree->[$branch_start_idx]->{name} ne $cand) {
# Candidate is not within the tree, add it at $branch_start_idx pos.
my @subtree;
make_tree(\@subtree, $cand);
splice(@$tree, $branch_start_idx, 0, @subtree);
} else {
# Candidate is within the old tree.
my $new_item = make_tree_item($cand);
if (!$new_item) {
# Item was deleted. Also remove its children.
my $branch_end_idx = find_branch_end_in_tree($tree, $cand, $branch_start_idx);
splice(@$tree, $branch_start_idx, $branch_end_idx - $branch_start_idx + 1);
} else {
# Item was modified. Just update the previous one.
splice(@$tree, $branch_start_idx, 1, $new_item);
}
}
}
}
#
# For each directory in the candidates list expand it to all direct
# children of this directory (existed now or existed previously).
#
sub expand_dir_candidates {
my ($tree, $candidates) = @_;
my %expanded = ();
foreach my $cand (@$candidates) {
my $item = make_tree_item($cand);
if (!$item || $item->{type} eq 'fil') {
$expanded{$cand} = undef;
} elsif ($item->{type} eq 'dir') {
# First, files/directories which exist directly below $cand NOW (including $cand).
my @existed = ();
make_tree(\@existed, $cand, 1);
@expanded{map { $_->{name} } @existed} = ();
# Next, add sub-files/sub-directories which exist PREVIOUSLY.
my @previous = ();
my $branch_start_idx = find_branch_start_in_tree($tree, $cand);
my $branch_end_idx = find_branch_end_in_tree($tree, $cand, $branch_start_idx);
my $item_is_child_to_cand_re = qr{^\Q$cand\E/[^/]+$}s;
for (my $i = $branch_start_idx + 1; $i <= $branch_end_idx; $i++) {
my $name = $tree->[$i]->{name};
$expanded{$name} = undef if $name =~ $item_is_child_to_cand_re;
}
}
}
return [sort keys %expanded];
}
#
# Searches for $rel position within the tree. If nothing is found,
# returns a position at which $rel should be inserted alphabethically.
#
sub find_branch_start_in_tree {
my ($tree, $rel) = @_;
my $idx = binsearch(
sub {
# Make "/" to be the lowest possible priority. This is needed, because
# the plain "/" is greater than ".", so we have a WRONG ordering:
# - aaa/bbb
# - aaa/bbb.ext
# - aaa/bbb/ccc
# This is wrong, the correct order must be:
# - aaa/bbb
# - aaa/bbb/ccc
# - aaa/bbb.ext
my $a = $_[0]; $a =~ tr{/}{\x00};
my $b = $_[1]->{name}; $b =~ tr{/}{\x00};
return $a cmp $b;
},
$rel,
$tree
);
return $idx;
}
#
# Starting from $branch_start_idx position in the tree, searches for
# the last item which is descendand of $rel (or equals to $rel).
#
sub find_branch_end_in_tree {
my ($tree, $rel, $branch_start_idx) = @_;
my $i;
for ($i = $branch_start_idx + 1; $i < @$tree; $i++) {
last if substr($tree->[$i]->{name}, 0, length($rel) + 1) ne "$rel/";
}
$i--;
return $i;
}
#
# Sorted array binary search.
# Returns the index of the position at which $s must be situated.
#
sub binsearch {
my ($f, $s, $list) = @_;
my $i = 0;
my $j = $#$list;
for (;;) {
my $k = int(($j - $i) / 2) + $i;
my $c = &$f($s, $list->[$k]);
#printf "== %s...%s k=%s %s <=> %s = %s\n", $i, $j, $k, $s, $list->[$k], $c;
if ($c == 0) {
return $k;
} elsif ($c < 0) {
$j = $k - 1;
return $k if ($i > $j);
} else {
$i = $k + 1;
return $i if ($i > $j);
}
}
}
#
# Splits command-line arguments by spaces (with correct quotes processing).
#
sub split_cmd_args {
my ($s) = @_;
return Text::ParseWords::shellwords($s);
}
#
# Reads a configuration file.
#
sub read_config {
my ($file) = @_;
open(local *F, $file) or die "Cannot open $file: $!\n";
my %config;
while (<F>) {
# Comments could be at the beginning of the line only,
# because "#" character is valid e.g. inside a file path.
s/^\s*#.*//sg;
s/^\s+|\s+$//sg;
next if !$_;
my ($k, $v) = ($_ =~ m/^(\w+)(?:\s*=\s*|\s+)(.*)$/s);
next if !$k;
if ($k eq "exclude") {
push @{$config{exclude}}, $v;
} elsif ($k eq "load") {
%config = (%config, read_config(File::Spec->rel2abs($v, dirname($file))));
} else {
$config{$k} = $v;
}
}
if ($config{exclude}) {
$config{exclude_re} = join("|", map { mask_to_re($_) } @{$config{exclude}});
}
if ($config{identity}) {
$FILE_IDENTITY = $config{identity};
}
return %config;
}
#
# Converts filesystem wildcard into regular expression.
#
sub mask_to_re {
my ($mask) = @_;
my $is_basename_mask = $mask !~ m{[/\\]}s && $mask !~ m{\*\*}s;
$mask = "\Q$mask";
$mask =~ s{\\\*\\\*}{.*}sg;
$mask =~ s{\\\*}{[^/\\\\]*}sg;
if ($is_basename_mask) {
$mask = '(?:[/\\\\]|^)' . $mask . '(?:[/\\\\]|$)';
} else {
# Rel path to match with such mask is always started with "./",
# but before matching the first character is cut. So when we
# check rel path like "./aaa/bbb" to be matched by "aaa/b*" mask,
# we are really executing "/aaa/bbb" =~ m{^(?:[/\\\\])?aaa/b.*$}.
$mask = '^(?:[/\\\\])?' . $mask . '$';
}
return $mask;
}
#
# Returns host and port number from a host specification.
#
sub parse_host_spec {
my ($host_port) = @_;
return $host_port =~ /^(.*):(\d+)$/s? ($1, $2) : ($host_port, "22");
}
#
# Reads the script from __DATA__ section of the file.
#
sub get_remote_script {
local $/;
my $script = <DATA>;
$script =~ s/\#[^\n]+//sg;
$script =~ s/"(.*?)"/qq{$1}/sg;
$script =~ s/'(.*?)'/q{$1}/sg;
$script =~ s/[\t\r\n]+/ /sg;
return $script;
}
#
# Runs a notification daemon.
#
sub spawn_notify_daemon {
my $cmd = $HOOKS->get_notify_daemon_cmd() or return;
my $local = main::cfg("local"); $local =~ s{\\}{/}sg;
async {
# Unfortunately we have to use a separate thread an shared-var
# polling to listen to the watcher, because Win32 IO::Select
# does not support waiting on a filehandle.
while (1) {
eval {
logger("Running async notification watcher (to save CPU time).\n");
my $pid = open(NOTIFY_FH, $cmd . "|");
if (!$pid) {
logger("Cannot run notification daemon: $!. Command was:\n $cmd\n");
notifies_set_supported(0);
return;
}
notifies_set_supported(1);
binmode(NOTIFY_FH);
NOTIFY_FH->autoflush(1);
my @buf = ();
while (1) {
my $line = <NOTIFY_FH>; # locks until data is ready
defined $line or die "Notification daemon is terminated unexpectedly, restarting. Command was:\n $cmd\n";
kill(0, $pid) or die "Notification watcher is dead, restarting. Command was:\n $cmd\n";
$line =~ s/^\s+|\s+$//sg;
if ($line eq "-") {
notifies_push(@buf);
@buf = ();
} elsif ($line =~ /^\w+ (.+)/s) {
#print "Received: $line\n" if $DEBUG_PATCH_TREE;
my $path = $1; $path =~ s{\\}{/}sg;
my $rel = File::Spec->file_name_is_absolute($path)? File::Spec->abs2rel($path, $local) : $path;
print "Notify: $rel\n" if $DEBUG_PATCH_TREE;
$rel = "./" . $rel if substr($rel, 0, 2) ne "./" && $rel ne ".";
push @buf, $rel;
} else {
# Unknown response - just wake up.
notifies_push("");
}
}
};
logger($@) if $@;
close(NOTIFY_FH);
sleep(1);
}
}->detach();
# Wait a bit - possibly notification daemon will dead shortly, so we glue
# its mortal message with its launching message.
usleep(0.5);
}