-
Notifications
You must be signed in to change notification settings - Fork 37
/
scanner.pl
executable file
·1471 lines (1239 loc) · 48.1 KB
/
scanner.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
#!/usr/bin/perl -w
################################################################################
# scanner.pl -- script that crawls through mirror file trees.
#
# Copyright 2006,2007,2008,2009,2010,2011,2012,2013,2014
# Martin Polster, Juergen Weigert, Peter Poeml, Novell Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation;
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
################################################################################
#######################################################################
# rsync protocol implementation
#######################################################################
#
# Copyright (c) 2005 Michael Schroeder ([email protected])
#
# This program is licensed under the BSD license, read LICENSE.BSD
# for further information
#
#######################################################################
use strict;
use DBI;
use Date::Parse;
use LWP::UserAgent;
use Net::FTP;
use Net::Domain;
use Data::Dumper;
use Time::HiRes;
use Socket;
use bytes;
use Config::IniFiles;
use Time::HiRes qw(gettimeofday);
use Encode;
my $version = '2.19.0';
my $verbose = 1;
my $sqlverbose = 0;
#$DB::inhibit_exit = 0;
$SIG{'PIPE'} = 'IGNORE';
$SIG{__DIE__} = sub {
my @a = ((caller 3)[1..3], '=>', (caller 2)[1..3], '=>', (caller 1)[1..3]);
print "__DIE__: (@a)\n";
die @_;
};
$SIG{USR1} = sub { $verbose++; warn "sigusr1 seen. ++verbose = $verbose\n"; };
$SIG{USR2} = sub { $verbose--; warn "sigusr2 seen. --verbose = $verbose\n"; };
$ENV{FTP_PASSIVE} = 1; # used in LWP only, Net::FTP ignores this.
# Create a user agent object
my $ua = LWP::UserAgent->new;
$ua->agent("MirrorBrain Scanner/$version (See http://mirrorbrain.org/scanner_info)");
my $rsync_muxbuf = '';
my $all_servers = 0;
my $start_dir = '/';
my $parallel = 1;
my $list_only = 0;
my $recursion_delay = 0; # seconds delay per *_readdir recuursion
my $force_scan = 0;
my $enable_after_scan = 0;
my $cfgfile = '/etc/mirrorbrain.conf';
my $brain_instance = '';
# FIXME: use DBI functions transaction handling
my $do_transaction = 1;
# save prepared statements
my $sth_update;
my $sth_insert_rel;
my $sth_select_file;
my $sth_insert_file;
my $sth_mirr_addbypath;
my $gig2 = 1<<31; # 2*1024*1024*1024 == 2^1 * 2^10 * 2^10 * 2^10 = 2^31
# these two vars are used in the largefile_check's http request callback to end
# transmission after a maximum amount of data (specified by $http_slice_counter)
my $http_size_hint;
my $http_slice_counter;
# directories to be included from top-level
my @top_include_list;
my @exclude_list;
my @exclude_list_rsync;
# default excludes:
push @exclude_list, '/.~tmp~/';
push @exclude_list_rsync, '*/.~tmp~/';
push @exclude_list_rsync, '/.~tmp~/';
my $ftp_timer_global;
exit usage() unless @ARGV;
while (defined (my $arg = shift)) {
if ($arg !~ m{^-}) { unshift @ARGV, $arg; last; }
elsif ($arg =~ m{^(-h|--help|-\?)}) { exit usage(); }
elsif ($arg =~ m{^(-I|--top-include)}) { push @top_include_list, shift; }
elsif ($arg =~ m{^--exclude$}) { push @exclude_list, shift; }
elsif ($arg =~ m{^--exclude-rsync$}) { push @exclude_list_rsync, shift; }
elsif ($arg =~ m{^-q}) { $verbose--; }
elsif ($arg =~ m{^-v}) { $verbose++; }
elsif ($arg =~ m{^-S}) { $sqlverbose++; }
elsif ($arg =~ m{^-a}) { $all_servers++; }
elsif ($arg =~ m{^-j}) { $parallel = shift; }
elsif ($arg =~ m{^-e}) { $enable_after_scan++; }
elsif ($arg =~ m{^-f}) { $force_scan++; }
elsif ($arg =~ m{^-d}) { $start_dir = shift; }
elsif ($arg =~ m{^--config}) { $cfgfile = shift; }
elsif ($arg =~ m{^-b}) { $brain_instance = shift; }
elsif ($arg =~ m{^-l}) { $list_only++;
$list_only++ if $arg =~ m{ll};
$list_only++ if $arg =~ m{lll}; }
elsif ($arg =~ m{^-}) { exit usage("unknown option '$arg'"); }
}
# read the configuration
my $cfg = new Config::IniFiles( -file => $cfgfile );
$cfg->SectionExists('general') or die 'no [general] section in config file';
# if the instance wasn't specified with -b, we use the first of the defined
# instances
my @brain_instances = split(/, /, $cfg->val('general', 'instances'));
$brain_instance = $brain_instances[0] unless $brain_instance;
$cfg->SectionExists($brain_instance) or die 'no [' . $brain_instance . '] section in config file';
my $db_driver = 'mysql'; # backwards compatible default
$db_driver = $cfg->val($brain_instance, 'dbdriver')
if $cfg->val($brain_instance, 'dbdriver');
my $db_port = 'not set';
if($db_driver eq 'Pg' or $db_driver eq 'postgres' or $db_driver eq 'postgresql') {
$db_port = '5432';
$db_driver = 'Pg';
}
elsif($db_driver eq 'mysql') {
$db_port = '3306';
}
else { die 'unknown dbddriver "' . $db_driver . '" in config file'; }
$db_port = $cfg->val($brain_instance, 'dbport')
if $cfg->val($brain_instance, 'dbport');
my $db_cred = { dbi => 'dbi:' . $db_driver
. ':dbname=' . $cfg->val( $brain_instance, 'dbname')
. ';host=' . $cfg->val( $brain_instance, 'dbhost')
. ';port=' . $db_port,
user => $cfg->val( $brain_instance, 'dbuser'),
pass => $cfg->val( $brain_instance, 'dbpass'),
opt => { PrintError => 0 } };
my %only_server_ids = map { $_ => 1 } @ARGV;
exit usage("Please specify list of server IDs (or -a for all) to scan\n")
unless $all_servers or %only_server_ids or $list_only;
exit usage("-a takes no parameters (or try without -a ).\n") if $all_servers and %only_server_ids;
exit usage("-e is useless without -f\n") if $enable_after_scan and !$force_scan;
exit usage("-j requires a positive number") unless $parallel =~ m{^\d+$} and $parallel > 0;
my $dbh = DBI->connect( $db_cred->{dbi}, $db_cred->{user}, $db_cred->{pass}, $db_cred->{opt}) or die $DBI::errstr;
# we fetch last_scan timestamp as epoch, because below we want to sort by it.
my $sql = qq{SELECT id, identifier, baseurl, baseurl_ftp, baseurl_rsync, enabled, extract(epoch from last_scan) as last_scan FROM server WHERE country != '**' };
print "$sql\n" if $sqlverbose;
my $ary_ref = $dbh->selectall_hashref($sql, 'id')
or die $DBI::errstr;
my @scan_list;
for my $row(sort { int(\$a->{last_scan}) <=> int(\$b->{last_scan}) } values %$ary_ref) {
if(keys %only_server_ids) {
next if !defined $only_server_ids{$row->{id}} and !defined $only_server_ids{$row->{identifier}};
# keep some keys in %only_server_ids!
undef $only_server_ids{$row->{id}};
undef $only_server_ids{$row->{identifier}};
}
if($row->{enabled} == 1 or $force_scan or $list_only > 1) {
push @scan_list, $row;
}
}
#print Dumper \%only_server_ids, \@scan_list;
if(scalar(keys %only_server_ids) > 2 * scalar(@scan_list)) {
# print Dumper \%only_server_ids, \@scan_list;
warn "You specified some disabled mirror_ids, use -f to scan them all.\n";
sleep 2 if scalar @scan_list;
}
my @missing = grep { defined $only_server_ids{$_} } keys %only_server_ids;
die sprintf "serverid not found: %s\n", @missing if @missing;
exit mirror_list(\@scan_list, $list_only-1) if $list_only;
###################
$start_dir =~ s{^/+}{}; # leading slash is implicit; leads to '' per default.
$start_dir =~ s{/+$}{}; # trailing slashes likewise.
##################
# be sure not to parallelize if there is exactly one server to scan.
$parallel = 1 if scalar @scan_list == 1;
if ($parallel > 1) {
my @worker;
my @cmd = ($0);
push @cmd, '-b', $brain_instance;
push @cmd, '-q' unless $verbose;
push @cmd, ('-v') x ($verbose - 1) if $verbose > 1;
push @cmd, ('-q') x (-($verbose - 1)) if $verbose < 0;
foreach my $item(@top_include_list) {
push @cmd, '-I', $item;
}
foreach my $item(@exclude_list) {
push @cmd, '--exclude', $item;
}
foreach my $item(@exclude_list_rsync) {
push @cmd, '--exclude-rsync', $item;
}
push @cmd, '-f' if $force_scan;
push @cmd, '-e' if $enable_after_scan;
push @cmd, '-d', $start_dir if length $start_dir;
# We must not propagate -j here.
# All other options we should propagate.
for my $row (@scan_list) {
# check if one of the workers is idle
my $worker_id = wait_worker(\@worker, $parallel);
$worker[$worker_id] = { identifier => $row->{identifier}, serverid => $row->{id}, pid => fork_child($worker_id, @cmd, $row->{identifier}) };
}
while (wait > -1) {
print "reap\n" if $verbose > 1;
; # reap all children
}
exit 0;
}
if($do_transaction) {
$dbh->{AutoCommit} = 0;
#$dbh->{RaiseError} = 1;
}
for my $row (@scan_list) {
print localtime(time) . " $row->{identifier}: starting\n" if $verbose > 0;
# already in a transaction? why??
#if($do_transaction) {
# $dbh->begin_work or die "$DBI::errstr";
#}
if(length $start_dir) {
$sql = "CREATE TEMPORARY TABLE temp1 AS
SELECT id FROM filearr
WHERE path LIKE '$start_dir/%'
AND $row->{id} = ANY(mirrors)";
} else {
$sql = "CREATE TEMPORARY TABLE temp1 AS
SELECT id FROM filearr
WHERE $row->{id} = ANY(mirrors)";
}
print "$sql\n" if $sqlverbose;
$dbh->do($sql) or die "$sql: ".$DBI::errstr;
$sql = "CREATE INDEX temp1_key ON temp1 (id);
ANALYZE temp1;
SELECT COUNT(*) FROM temp1";
print "$sql\n" if $sqlverbose;
my $ary_ref = $dbh->selectall_arrayref($sql) or die $dbh->errstr();
my $initial_file_count = defined($ary_ref->[0]) ? $ary_ref->[0][0] : 0;
if(length $start_dir) {
print localtime(time) . " $row->{identifier}: files in '$start_dir' before scan: $initial_file_count\n"
if $verbose > 0;
} else {
print localtime(time) . " $row->{identifier}: total files before scan: $initial_file_count\n"
if $verbose > 0;
}
if($do_transaction) {
$dbh->commit or die "$DBI::errstr";
}
#$sql = "SELECT COUNT(*) FROM filearr WHERE $row->{id} = ANY(mirrors)";
#print "$sql\n" if $sqlverbose;
my $start = int(gettimeofday * 1000);
my $file_count = rsync_readdir($row->{identifier}, $row->{id}, $row->{baseurl_rsync}, $start_dir);
if(!$file_count and $row->{baseurl_ftp}) {
print localtime(time) . " $row->{identifier}: no rsync, trying ftp\n" if $verbose > 1;
$file_count = scalar ftp_readdir($row->{identifier}, $row->{id}, $row->{baseurl_ftp}, time, $start_dir);
}
if(!$file_count and $row->{baseurl}) {
print localtime(time) . " $row->{identifier}: no rsync, no ftp, trying http\n" if $verbose > 1;
$file_count = scalar http_readdir($row->{identifier}, $row->{id}, $row->{baseurl}, $start_dir);
}
if($do_transaction) {
$dbh->commit or die "$DBI::errstr";
}
my $duration = (int(gettimeofday * 1000) - $start) / 1000;
if (!$duration) { $duration = 1; }
if (!$file_count) { $file_count = 0; }
my $fpm = int(60*$file_count/$duration);
print localtime(time) . " $row->{identifier}: scanned $file_count files ("
. int($fpm/60) . "/s) in "
. int($duration) . "s\n" if $verbose > 0;
$start = time();
print localtime(time) . " $row->{identifier}: purging old files\n" if $verbose > 1;
#$sql = "SELECT COUNT(*) FROM temp1";
$sql = "SELECT COUNT(mirr_del_byid($row->{id}, id)) FROM temp1";
print "$sql\n" if $sqlverbose;
$ary_ref = $dbh->selectall_arrayref($sql) or die $dbh->errstr();
my $purge_file_count = defined($ary_ref->[0]) ? $ary_ref->[0][0] : 0;
print localtime(time) . " $row->{identifier}: files to be purged: $purge_file_count\n" if $verbose > 0;
$sql = "SELECT COUNT(*) FROM filearr WHERE $row->{id} = ANY(mirrors);";
print "$sql\n" if $sqlverbose;
if(length $start_dir) {
print localtime(time) . " $row->{identifier}: total files in '$start_dir' after scan: $file_count " .
"(delta: " . ($file_count - $initial_file_count) . ")\n" if $verbose > -1;
} else {
$ary_ref = $dbh->selectall_arrayref($sql) or die $dbh->errstr();
$file_count = defined($ary_ref->[0]) ? $ary_ref->[0][0] : 0;
print localtime(time) . " $row->{identifier}: total files after scan: $file_count " .
"(delta: " . ($file_count - $initial_file_count) . ")\n" if $verbose > -1;
}
$duration = time() - $start;
print localtime(time) . " $row->{identifier}: purged old files in " . $duration . "s.\n" if $verbose > 0;
# update the last_scan timestamp; but only if we did a complete scan.
unless ($start_dir) {
$sql = "UPDATE server SET last_scan = NOW(), scan_fpm = $fpm WHERE id = $row->{id};";
print "$sql\n" if $sqlverbose;
my $sth = $dbh->prepare( $sql );
$sth->execute() or die "$row->{identifier}: $DBI::errstr";
}
if($enable_after_scan && $file_count > 1 && !$row->{enabled}) {
$sql = "UPDATE server SET enabled = '1' WHERE id = $row->{id};";
print "$sql\n" if $sqlverbose;
my $sth = $dbh->prepare( $sql );
$sth->execute() or die "$row->{identifier}: $DBI::errstr";
print localtime(time) . " $row->{identifier}: now enabled.\n" if $verbose > 0;
}
$sql = "DROP TABLE temp1";
print "$sql\n" if $sqlverbose;
$dbh->do($sql) or die "$sql: ".$DBI::errstr;
if($do_transaction) {
$dbh->commit or die "$DBI::errstr";
}
print localtime(time) . " $row->{identifier}: done.\n" if $verbose > 0;
}
$dbh->disconnect();
exit 0;
###################################################################################################
sub usage
{
my ($msg) = @_;
print STDERR qq{$0 V$version usage:
scanner [options] [mirror_ids ...]
-b MirrorBrain instance to use
Default: the first which is defined in the config.
-v Be more verbose (Default: $verbose).
-S Show SQL statements.
-q Be quiet.
-l Do not scan. List enabled mirrors only.
-ll As -l, but include disabled mirrors and print urls.
-lll As -ll, but all in one grep-friendly line.
-a Scan all enabled mirrors. Alternative to providing a list of mirror_ids.
-e Enable mirror, after it was scanned. Useful with -f.
-f Force. Scan listed mirror_ids even if they are not enabled.
-d dir Scan only in dir under mirror's baseurl.
Default: start at baseurl.
-j N Run up to N scanner queries in parallel.
--exclude regexp
Define pattern(s) for path names to ignore. Paths matching this pattern
will not be recursed into (thus saving resources) and also, when
matching a file, not added into the database.
This option is effective only for scans via HTTP/FTP. For rsync,
use the --exclude-rsync option (due to different patterns used there).
Here, regular expressions are used.
Path names don't start with a slash; thus, if the regexp starts with a slash
it will not match at the top-level directory.
Option can be repeated.
Default: @exclude_list
--exclude-rsync pattern
Similar like --exclude, but used (only) for rsync scans.
For HTTP/FTP, use the --exclude option (due to different patterns
used there).
The patterns are rsync(1) patterns. Option can be repeated.
Default: @exclude_list_rsync
-T dir Directory to be scanned at the top level; option can be repeated.
Both, names(identifier) and numbers(id) are accepted as mirror_ids.
};
print STDERR "\nERROR: $msg\n" if $msg;
return 0;
}
sub mirror_list
{
my ($list, $longflag) = @_;
print " id name scan_speed last_scan\n";
print "---+-------------------------+-----------+-------------\n";
my $nl = ($longflag > 1) ? "\t" : "\n";
for my $row(@$list) {
printf "%3d %-30s %5d %s$nl", $row->{id}, $row->{identifier}||'--', $row->{scan_fpm}||0, $row->{last_scan}||'';
if($longflag) {
print "\t$row->{baseurl_rsync}$nl" if length($row->{baseurl_rsync}||'') > 0;
print "\t$row->{baseurl_ftp}$nl" if length($row->{baseurl_ftp}||'') > 0;
print "\t$row->{baseurl}$nl" if length($row->{baseurl}||'') > 0;
printf "\tscore=%d country=%s region=%s enabled=%d$nl",
$row->{score}||0, $row->{country}||'', $row->{region}||'', $row->{enabled}||0;
print "\n";
}
}
return 0;
}
sub wait_worker
{
my ($a, $n) = @_;
die if $n < 1;
my %pids;
for(;;) {
for(my $i = 0; $i < $n; $i++) {
return $i unless $a->[$i];
my $p = $a->[$i]{pid};
unless (kill(0, $p)) { # already dead? okay take him home.
print "kill(0, $p) returned 0. reusing $i!\n" if $verbose;
undef $a->[$i];
return $i;
}
$pids{$p} = $i; # not? okay wait.
}
my $p = wait;
my $rc = $?;
if(defined(my $i = $pids{$p})) {
if (($verbose > 1) || ($rc != 0)) {
print "$a->[$i]{identifier}: [#$i, id=$a->[$i]{serverid} pid=$p exit: $?]\n";
}
undef $a->[$i];
return $i; # now, been there, done that.
}
# $p = -1 or other silly things...
warn "wait failed: $!, $?\n";
die "wait failed" if $p < 0;
}
}
sub fork_child
{
my ($idx, @args) = @_;
if (my $p = fork()) {
# parent
print "worker $idx, pid=$p start.\n" if $verbose > 1;
return $p;
}
my $cmd = shift @args;
exec { $cmd } "scanner [#$idx]", @args; # ourselves with a false name and some data.
}
# http://ftp1.opensuse.org/repositories/#@^@repositories/@@
sub http_readdir
{
my ($identifier, $id, $url, $name) = @_;
my $item;
my $urlraw = $url;
my $re = ''; $re = $1 if $url =~ s{#(.*?)$}{};
print "$identifier: http_readdir: url=$url re=$re\n" if $verbose > 2;
$url =~ s{/+$}{}; # we add our own trailing slashes...
$name =~ s{/+$}{};
# are we looking at a top-level directory name?
# (we recognize it by not containing slashes)
my $attop = 0;
$attop = 1 if (length $name) && !($name =~ "/");
if ($attop && scalar(@top_include_list)) {
my $included = 0;
foreach my $item(@top_include_list) {
if ($name =~ $item) {
$included = 1;
}
}
if (!$included) {
print "$identifier: not in top_include_list: $name\n" if $verbose > 1;
return;
}
}
foreach $item(@exclude_list) {
if("$name/" =~ $item) {
print "$identifier: ignore match: $name matches ignored item $item, skipped.\n" if $verbose > 1;
return;
}
}
my @r;
print "$identifier: http dir: $url/$name\n" if $verbose > 2;
print "$identifier: http dir: $name\n" if $verbose == 2;
my ($res, $contents) = cont("$url/$name/?F=1");
if(!$res) {
print "$url/$name/?F=1: error \"$contents\" fetching index, skipped.\n" if $verbose;
return;
}
if($contents =~ s{^.*<(PRE|pre|table)>.*<(a href|A HREF)="\?(N=A|C=.*;O=)[^"]*">}{}s) {
## _ _
## / \ _ __ __ _ ___| |__ ___
## / _ \ | '_ \ / _` |/ __| '_ \ / _ \
## / ___ \| |_) | (_| | (__| | | | __/
## /_/ \_\ .__/ \__,_|\___|_| |_|\___|
## |_|
## good, we know that one. It is a standard apache dir-listing.
##
## bad, apache shows symlinks as a copy of the file or dir they point to.
## no way to avoid duplicate crawls except by defining top_include_dirs,
## scan_exclude or scan_exclude_rsync in /etc/mirrorbrain.conf.
##
$contents =~ s{</(PRE|pre|table)>.*$}{}s;
for my $line (split "\n", $contents) {
$line =~ s/<\/*t[rd].*?>/ /g;
print "$identifier: line: $line\n" if $verbose > 2;
if($line =~ m{^(.*)[Hh][Rr][Ee][Ff]="([^"]+)">([^<]+)</[Aa]>\s+([\w\s:-]+)\s+(-|[\d\.]+[KMG]?)}) {
my ($pre, $name1, $name2, $date, $size) = ($1, $2, $3, $4, $5);
next if $name1 =~ m{^/} or $name1 =~ m{^\.\.};
if($verbose > 2) {
print "$identifier: pre $pre\n";
print "$identifier: name1 $name1\n";
print "$identifier: name2 $name2\n";
print "$identifier: date $date\n";
print "$identifier: size $size\n";
}
$name1 =~ s{%([\da-fA-F]{2})}{pack 'U', hex $1}ge;
$name1 =~ s{^\./}{};
my $dir = 1 if $pre =~ m{"\[DIR\]"};
#print "$identifier: $pre^$name1^$date^$size\n" if $verbose > 1;
my $t = length($name) ? "$name/$name1" : $name1;
if($size eq '-' and ($dir or $name1 =~ m{/$})) {
## we must be really sure it is a directory, when we come here.
## otherwise, we'll retrieve the contents of a file!
sleep($recursion_delay) if $recursion_delay;
push @r, http_readdir($identifier, $id, $urlraw, $t, 0);
}
else {
## it is a file.
my $time = str2time($date);
my $len = byte_size($size);
# str2time returns undef in some rare cases causing KILL! FIXME
# workaround: don't store files with broken times
if(not defined($time)) {
print "$identifier: Error: str2time returns undef on parsing \"$date\". Skipping file $name1\n";
print "$identifier: current line was:\n$line\nat url $url/$name\nname= $name1\n" if $verbose > 1;
}
elsif(largefile_check($identifier, $id, $t, $len)) {
#save timestamp and file in database
if(save_file($t, $identifier, $id, $time, $re)) {
push @r, [ $t , $time ];
}
}
}
}
}
print "$identifier: committing http dir $name\n" if $verbose > 2;
if($do_transaction) {
$dbh->commit or die "$DBI::errstr";
}
} elsif($contents =~ s{^.*<thead>.*>Name<.*<tbody>}{}s) {
## _ _ _ _ _ _
## | (_) __ _| |__ | |_| |_ _ __ __| |
## | | |/ _` | '_ \| __| __| '_ \ / _` |
## | | | (_| | | | | |_| |_| |_) | (_| |
## |_|_|\__, |_| |_|\__|\__| .__/ \__,_|
## |___/ |_|
## Oh look, it's a lighttpd directory index!
$contents =~ s{</tbody>.*$}{}s;
for my $line (split "\n", $contents) {
$line =~ s/<\/*t[rd].*?>/ /g;
print "$identifier: line: $line\n" if $verbose > 2;
if($line =~ m{^(.*)[Hh][Rr][Ee][Ff]="([^"]+)">([^<]+)</[Aa]>.+([\w\s:-]+)\s+(-|[\d\.]+[KMG]?)}) {
my ($pre, $name1, $name2, $date, $size) = ($1, $2, $3, $4, $5);
next if $name1 =~ m{^/} or $name1 =~ m{^\.\.};
if($verbose > 2) {
print "$identifier: pre $pre\n";
print "$identifier: name1 $name1\n";
print "$identifier: name2 $name2\n";
print "$identifier: date $date\n";
print "$identifier: size $size\n";
}
$name1 =~ s{%([\da-fA-F]{2})}{pack 'U', hex $1}ge;
$name1 =~ s{^\./}{};
my $dir = 1 if $pre =~ m{>Directory<};
my $t = length($name) ? "$name/$name1" : $name1;
if($size eq '-' and ($dir or $name1 =~ m{/$})) {
## we must be really sure it is a directory, when we come here.
## otherwise, we'll retrieve the contents of a file!
sleep($recursion_delay) if $recursion_delay;
push @r, http_readdir($identifier, $id, $urlraw, $t, 0);
}
else {
## it is a file.
my $time = $date;
my $len = byte_size($size);
# str2time returns undef in some rare cases causing KILL! FIXME
# workaround: don't store files with broken times
if(not defined($time)) {
print "$identifier: Error: str2time returns undef on parsing \"$date\". Skipping file $name1\n";
print "$identifier: current line was:\n$line\nat url $url/$name\nname= $name1\n" if $verbose > 1;
}
elsif(largefile_check($identifier, $id, $t, $len)) {
#save timestamp and file in database
if(save_file($t, $identifier, $id, $time, $re)) {
push @r, [ $t , $time ];
}
}
}
}
}
print "$identifier: committing http dir $name\n" if $verbose > 2;
if($do_transaction) {
$dbh->commit or die "$DBI::errstr";
}
} elsif($contents =~ s{^<html>.*<head><title>Index of .*<h1>Index of .*</h1><hr><pre><a href="../">../</a>}{}s) {
## _
## _ __ __ _(_)_ __ __ __
## | '_ \ / _` | | '_ \\ \/ /
## | | | | (_| | | | | |> <
## |_| |_|\__, |_|_| |_/_/\_\
## |___/
##
## Oh look, it's a nginx directory index!
$contents =~ s{<pre><a href="../">../</a>.*</pre><hr></body>$}{}s;
for my $line (split "\n", $contents) {
#$line =~ s/<\/*t[rd].*?>/ /g;
print "$identifier: line: $line\n" if $verbose > 2;
# <a href="addons/">addons/</a> 14-May-2010 15:38 -
if($line =~ m{^<a href="([^"]+)">([^<]+)</a>\s*([\w\s:-]+)\s+(-|[\d\.]+)}) {
my ($name1, $name2, $date, $size) = ($1, $2, $3, $4, $5);
next if $name1 =~ m{^/} or $name1 =~ m{^\.\.};
if($verbose > 2) {
print "$identifier: name1 $name1\n";
print "$identifier: name2 $name2\n";
print "$identifier: date $date\n";
print "$identifier: size $size\n";
}
#$name1 =~ s{%([\da-fA-F]{2})}{pack 'c', hex $1}ge;
#$name1 =~ s{^\./}{};
my $t = length($name) ? "$name/$name1" : $name1;
if($size eq '-' and ($name1 =~ m{/$})) {
## we must be really sure it is a directory, when we come here.
## otherwise, we'll retrieve the contents of a file!
sleep($recursion_delay) if $recursion_delay;
push @r, http_readdir($identifier, $id, $urlraw, $t, 0);
}
else {
## it is a file.
my $time = $date;
my $len = byte_size($size);
# str2time returns undef in some rare cases causing KILL! FIXME
# workaround: don't store files with broken times
if(not defined($time)) {
print "$identifier: Error: str2time returns undef on parsing \"$date\". Skipping file $name1\n";
print "$identifier: current line was:\n$line\nat url $url/$name\nname= $name1\n" if $verbose > 1;
}
elsif(largefile_check($identifier, $id, $t, $len)) {
#save timestamp and file in database
if(save_file($t, $identifier, $id, $time, $re)) {
push @r, [ $t , $time ];
}
}
}
}
}
print "$identifier: committing http dir $name\n" if $verbose > 2;
if($do_transaction) {
$dbh->commit or die "$DBI::errstr";
}
}
else {
## we come here, whenever we stumble into an automatic index.html
$contents = substr($contents, 0, 500);
print "$identifier: unparseable HTML index in /$name\n" if $verbose;
warn Dumper $contents, "$identifier: http_readdir: unknown HTML format" if $verbose > 1;
}
return @r;
}
sub byte_size
{
my ($len) = @_;
return $len unless $len =~ m{(.*)([KMG])$};
my ($n, $l) = ($1,$2);
return int($n*1024) if $l eq 'K';
return int($1*1024*1024) if $l eq 'M';
return int($1*1024*1024*1024) if $l eq 'G';
die "byte_size: $len not impl\n";
}
# _____ _____ ____
# | ___|_ _| _ \
# | |_ | | | |_) |
# | _| | | | __/
# |_| |_| |_|
#
# $file_count = scalar ftp_readdir($row->{identifier}, $row->{id}, $row->{baseurl_ftp}, $ftp_timer, $start_dir);
# first call: $ftp undefined
sub ftp_readdir
{
my ($identifier, $id, $url, $ftp_timer, $name, $ftp) = @_;
$ftp_timer_global = $ftp_timer;
my $ftp_age = (time() - $ftp_timer_global);
print "$identifier: last command issued $ftp_age"."s ago\n" if $verbose > 2;
$ftp_timer_global = time();
my $item;
print "$identifier: ftp dir: $name\n" if $verbose > 1;
my $urlraw = $url;
my $re = ''; $re = $1 if $url =~ s{#(.*?)$}{};
$url =~ s{/+$}{}; # we add our own trailing slashes...
my $toplevel = ($ftp) ? 0 : 1;
$ftp = ftp_connect($identifier, "$url/$name") unless defined $ftp;
return unless defined $ftp;
my $text = ftp_cont($ftp, "$url/$name");
if(!ref($text) && $text =~ m/^(\d\d\d)\s/) { # some FTP status code? Not good.
# Bug: Net::FTP wrongly reports timeouts (421) as code 550:
# sunsite.informatik.rwth-aachen.de: ftp dir: ftp://sunsite.informatik.rwth-aachen.de/pub/linux/opensuse/distribution/11.0/repo/debug/suse/i686
# Net::FTP=GLOB(0x112f480)>>> CWD /pub/linux/opensuse/distribution/11.0/repo/debug/suse/i686
# Net::FTP=GLOB(0x112f480)<<< 421 Timeout.
# sunsite.informatik.rwth-aachen.de: ftp status code 550 (550 failed: ftp-cwd(/pub/linux/opensuse/distribution/11.0/repo/debug/suse/i686): ), closing.
#
# Thus, if the connection is older than 60 seconds, we attempt a reconnect.
# Otherwise we quit.
if ($ftp_age > 60) {
warn "$identifier: ftp status code $1. Last command " . $ftp_age . "s ago; attempting reconnect\n";
print "$identifier: $text" if $verbose > 2;
ftp_close($ftp);
$ftp = ftp_connect($identifier, "$url/$name");
return unless defined $ftp;
$text = ftp_cont($ftp, "$url/$name");
} else {
warn "$identifier: ftp status code $1, closing.\n";
print "$identifier: $text" if $verbose > 2;
ftp_close($ftp);
return;
}
}
print "$identifier: ".join("\n", @$text)."\n" if $verbose > 2;
my @r;
for my $i (0..$#$text) {
# -rw-r--r-- 1 804 804 255436 Nov 09 03:13 The Big Picture.tar.gz
if($text->[$i] =~ m/^([dl-])(.........).*\s(\d+)\s(\w\w\w\s+\d\d?\s+\d\d:?\d\d)\s+(\S+.*)$/) {
my ($type, $mode, $size, $timestamp, $fname) = ($1, $2, $3, $4, $5);
next if $fname eq "." or $fname eq "..";
#print "$name / $fname\n";
# are we looking at a top-level directory name?
# (can be recognized by name being an empty string)
if (!length($name) && scalar(@top_include_list)) {
my $included = 0;
foreach my $item(@top_include_list) {
if ($fname =~ $item) {
$included = 1;
}
}
if (!$included) {
print "$identifier: not in top_include_list: $fname\n" if $verbose > 1;
next;
}
}
my $excluded = 0;
my $s = "$name/$fname";
if($type eq "d") {
$s = "$s/";
}
for $item(@exclude_list) {
if ($s =~ $item) {
print "$identifier: $s ignored (matches $item)\n" if $verbose > 0;
$excluded = 1;
}
}
next if ($excluded);
#convert to timestamp
my $time = str2time($timestamp);
my $t = length($name) ? "$name/$fname" : $fname;
if($type eq "d") {
if($mode !~ m{r.[xs]r.[xs]r.[xs]}) {
print "$identifier: bad mode $mode, skipping directory $fname\n" if $verbose;
next;
}
sleep($recursion_delay) if $recursion_delay;
push @r, ftp_readdir($identifier, $id, $urlraw, $ftp_timer_global, $t, $ftp);
}
if($type eq 'l') {
print "$identifier: ignoring symlink ($t)\n" if $verbose > 1;
} else {
if ($mode !~ m{r..r..r..}) {
print "$identifier: bad mode $mode, skipping file $fname\n" if $verbose;
next;
}
#save timestamp and file in database
if(largefile_check($identifier, $id, $t, $size)) {
if(save_file($t, $identifier, $id, $time, $re)) {
push @r, [ $t , $time ];
}
}
}
} else {
if ($text->[$i] !~ /^total/) {
print "$identifier: line could not be parsed: $text->[$i]\n";
}
}
}
print "$identifier: committing ftp dir $name\n" if $verbose > 2;
if($do_transaction) {
$dbh->commit or die "$DBI::errstr";
}
ftp_close($ftp) if $toplevel;
return @r;
}
sub save_file
{
my ($path, $identifier, $serverid, $mod_re, $ign_re) = @_;
#
# optional patch the file names by adding or removing components.
# you never know what strange paths mirror admins choose.
#
return undef if $ign_re and $path =~ m{$ign_re};
if ($mod_re and $mod_re =~ m{@([^@]*)@([^@]*)}) {
print "$identifier: save_file: $path + #$mod_re -> " if $verbose > 2;
my ($m, $r) = ($1, $2);
$path =~ s{$m}{$r};
print "$path\n" if $verbose > 2;
}
$path =~ s{^/+}{}; # be sure we have no leading slashes.
$path =~ s{//+}{/}g; # avoid double slashes.
# explicitely tell Perl that the filename is in UTF-8 encoding
$path = decode_utf8($path);
my $sql = "SELECT mirr_add_bypath(?, ?);";
if (!defined $sth_mirr_addbypath) {
printf "\nPreparing add statement\n\n" if $sqlverbose;
$sth_mirr_addbypath = $dbh->prepare( $sql ) or die "$identifier: $DBI::errstr";
}
printf "$sql <-- $serverid, $path \n" if $sqlverbose;
$sth_mirr_addbypath->execute( $serverid, $path ) or die "$identifier: $DBI::errstr";
my @data = $sth_mirr_addbypath->fetchrow_array();
#if ($sth_mirr_addbypath->rows > 0) {
my $fileid = $data[0];
#print "fileid: $fileid\n";
#}
$sth_mirr_addbypath->finish;
$sql = "DELETE FROM temp1 WHERE id = $fileid";
print "$sql\n" if $sqlverbose;
$dbh->do($sql) or die "$sql: ".$DBI::errstr;
return $path;
}
sub delete_file
{
my ($dbh, $serverid, $path) = @_;
warn "FIXME: delete_file() not impl.\n";
}
sub cont
{
my $url = shift;
# Create a request
my $req = HTTP::Request->new(GET => $url);
$req->header('Accept' => '*/*');
# Pass request to the user agent and get a response back
my $res = $ua->request($req);
# Check the outcome of the response
if ($res->is_success) {
return (1,$res->content);
}
else {
return (0,$res->status_line);
}
}
# getfileid returns the id as inserted in table file.
#
sub getfileid
{
my $path = shift;
my @data;
my $id;
# prepare statements once
my $sql_select_file = "SELECT id FROM file WHERE path = ? LIMIT 1;";
if (!defined $sth_select_file) {