-
Notifications
You must be signed in to change notification settings - Fork 42
/
realsync
executable file
·1606 lines (1414 loc) · 47.6 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 = (
"-rltzxvS",
"--delete",
"--partial"
);
my @RSYNC_WRAPPER = ();
my @RSYNC_SSH_WRAPPER = ();
my $REALSYNC_SPEC_FILE = ".realsync";
my @DEFAULT_EXCLUDE = ($REALSYNC_SPEC_FILE, "CVS", ".git", ".svn", ".hg", ".cache", ".idea", "nbproject", "~*", "*.tmp", "*.pyc", "*.swp");
# 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_SPEC_FILE) {
$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);
if ($CONFIG{identity}) {
$FILE_IDENTITY = $CONFIG{identity};
}
# 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);
sleep(1);
}
}
#
# Called at script dead.
#
sub onexit {
my ($iteration_end) = @_;
if ($IN_REPLICATION) {
kill(9, $SSH_PID) if $SSH_PID;
$SSH_PID = undef;
notification("wait");
}
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 ($is_tmp) = @_;
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, $is_tmp);
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_SPEC_FILE/" . $hash;
$DIR_PRIVATE .= ".tmp" if $is_tmp;
$FILE_IDENTITY = "$DIR_PRIVATE/.ssh/identity";
$FILE_CONFIG = "$cwd/$REALSYNC_SPEC_FILE";
}
#
# Legacy pathes for configuration.
#
sub build_pathes_based_on_cwd_legacy {
my ($dir_appdata, $is_tmp) = @_;
$DIR_PRIVATE = $dir_appdata . "/$REALSYNC_SPEC_FILE/" . substr(md5_hex(getcwd()), 0, 10);
$DIR_PRIVATE .= ".tmp" if $is_tmp;
$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)},
);
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);
}
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";
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...");
notification("transfer");
foreach my $change (@changes) {
write_change(\*IN, $change);
}
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_text = sub {
my $s = "(Step $step_num) $_[0]";
$step_num++;
return $s;
};
print "THIS WIZARD APPEARS ONLY ONCE!\nNEXT TIME THE REPLICATION WILL START IMMEDIATELY.\n\n";
my %CONFIG = ();
if (-f $FILE_CONFIG) {
%CONFIG = read_config($FILE_CONFIG);
print "Read options from existing config: $FILE_CONFIG.\n";
} else {
print "Starting an interactive installation.\n";
}
print "\n";
my @config = ();
my $local;
if (!defined $CONFIG{local}) {
$local = ask(
$step_text->("LOCAL directory to replicate FROM:\n "),
getcwd(),
sub { -d $_ ? undef : "No such directory: $_" }
);
$local = "." if $local eq getcwd();
$local =~ s{\\}{/}sg;
$local =~ s{/+$}{}sg;
push @config, {
"name" => "local",
"value" => $local,
"comment" => "Local directory to be realtime-replicated.",
};
} else {
$local = $CONFIG{local};
}
chdir($local) or die "Cannot chdir to $local: $!\n";
build_pathes_based_on_cwd(1); # builds TEMPORARY paths
mkpath($DIR_PRIVATE, 0, 0700); # IMPORTANT: it's a marker to skip the installation wizard next time
my $host = undef;
my $user = undef;
my $step_save = $step_num;
while (1) {
$step_num = $step_save;
if (!defined $CONFIG{host}) {
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.",
};
} else {
$host = $CONFIG{host};
}
if (!defined $CONFIG{user}) {
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.",
};
} else {
$user = $CONFIG{user};
}
# Check if we already have a passwordless access.
print "Checking if we have access to $user\@$host with no password...\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 && chmod 700 .ssh || mkdir .ssh;'
. ' test -e .ssh/authorized_keys && chmod 600 .ssh/authorized_keys; (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;
}
if (!defined $CONFIG{remote}) {
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.",
};
} else {
# Pass.
}
if (!defined $CONFIG{exclude}) {
print "\n";
my $excludes = ask(
$step_text->(
"Exclusions from " . basename($FILE_CONFIG) . " configuration are:\n" .
" " . join(" ", @DEFAULT_EXCLUDE) . "\n" .
"Enter a space-separated list of ADDITIONAL exclusions:",
),
""
);
my $first = 1;
foreach my $mask (@DEFAULT_EXCLUDE, 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;
}
} else {
# Pass.
}
if (!%CONFIG) {
push @config, {
"name" => "#exclude_file",
"value" => ".gitignore",
"comment" => "You may read exclusion list from e.g. a .gitignore file.",
};
}
if (!defined $CONFIG{nosound}) {
push @config, {
"name" => "nosound",
"value" => "0",
"comment" => "To turn off \"synchronization ding\" sound, set the following to 1.",
};
}
if (!%CONFIG) {
unshift @config, {
"name" => "#load",
"value" => "$REALSYNC_SPEC_FILE-local",
"comment" => "You may load some other config files. It's a good practice to put\n"
. "all user-specific options (e.g. \"user\" directive, see below) to\n"
. "$REALSYNC_SPEC_FILE-local plus add this file to .gitignore. After that\n"
. "you commit the current $REALSYNC_SPEC_FILE file to your version control\n"
. "system, so developers may just override options in their own local files."
};
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";
if (@config) {
open(local *F, ">>", $FILE_CONFIG);
if (!%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. The configuration file has been updated.\n";
}
print "Configuration file is:\n $FILE_CONFIG\n";
if (-f $FILE_IDENTITY) {
print "Generated SSH private key is saved to:\n";
print " $FILE_IDENTITY\n";
}
# Flip tmp keys directory into the permanent one at the very end, so if
# one presses Ctrl+C above and relaunches, everything is started from scratch.
my ($tmp_dir_private) = ($DIR_PRIVATE);
build_pathes_based_on_cwd();
rename($tmp_dir_private, $DIR_PRIVATE);
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 "exclude_file") {
push @{$config{exclude}}, read_exclude_file($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}});
}
return %config;
}
#
# Reads a content of .gitignore-like file.
#
sub read_exclude_file {
my ($file) = @_;
my @excludes = ();
open(local *F, $file) or die "Cannot open an exclude file $file: $!\n";
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;
push @excludes, $_ if length($_);
}
return @excludes;
}
#
# 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,