forked from amenonsen/w3mir
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathw3mir.PL
3340 lines (2588 loc) · 99.5 KB
/
w3mir.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
# -*-perl-*-
use Config;
&read_makefile;
$fullperl = resolve_make_var('FULLPERL') || $Config{'perlpath'};
$islib = resolve_make_var('INSTALLSITELIB');
$name = $0;
$name =~ s~^.*/~~;
$name =~ s~.PL$~~;
open(OUT,"> $name") ||
die "Could open $name for writing: $!\n";
print "writing $name\n";
while (<DATA>) {
if (m~^\#!/.*/perl.*$~o) {
# This substitutes the path perl was installed at on this system
# _and_ removed any (-w) options.
print OUT "#!",$fullperl,$1,"\n";
next;
}
if (/^use lib/o) {
# This substitutes the actuall library install path
print OUT "use lib '$islib';\n";
next;
}
print OUT;
}
close(OUT);
# Make it executable too, and writeable
chmod 0755, $name;
#### The library
sub resolve_make_var ($) {
my($var) = shift @_;
my($val) = $make{$var};
# print "Resolving: ",$var,"=",$val,"\n";
while ($val =~ s~\$\((\S+)\)~$make{$1}~g) {}
# print "Resolved: $var: $make{$var} -> $val\n";
$val;
}
sub read_makefile {
open(MAKEFILE, 'Makefile') ||
die "Could not open Makefile for reading: $!\n";
while (<MAKEFILE>) {
chomp;
next unless m/^([A-Z]+)\s*=\s*(\S+)$/;
$make{$1}=$2;
# print "Makevar: $1 = $2\n";
}
close(MAKEFILE)
}
__END__
#!/usr/bin/perl -w
# Perl 5.002 or later. w3mir is mostly tested with perl 5.004
#
use lib '/hom/janl/lib/perl';
#
# Once upon a long time ago this was Oscar Nierstrasz's
# <[email protected]> htget script.
#
# Retrieves HTML pages, creating local copies in the _current_
# directory. The script will check for the last-modified stamp on the
# document, and will not fetch it if the document isn't changed.
#
# Bug list is in w3mir-README.
#
# Test cases for janl to use:
# w3mir -r -fs http://www.eff.org/ - infinite recursion!
# --- but cursory examination seems to indicate confused server...
# http://java.sun.com/progGuide/index.html check out the img things.
#
# Copyright Holders:
# Nicolai Langfeldt, [email protected]
# Gorm Haug Eriksen, [email protected]
# Chris Szurgot, [email protected]
# Ed Jordan, [email protected]
# Alex Knowles, [email protected] aka ark.
# Copying and modification is governed by the "Artistic License" enclosed in
# the w3mir distribution
#
# History (European format date: dd/mm/yy):
# oscar 25/03/94 -- added -s option to send output to stdout
# oscar 28/03/94 -- made HTTP 1.0 the default
# oscar 30/05/94 -- special handling of directory URLs missing a trailing "/"
# gorm 20/02/95 -- added mirror capacity + fixed a couple of bugs
# janl 28/03/95 -- added a working commandline parser.
# janl 18/09/95 -- Changed to use a net http library. Removed dependency of
# url.pl.
# janl 19/09/95 -- Extensive rewrite. Simplified a lot, works better.
# HTML files are now saved in a new and improved manner,
# which means they can be recognized as such w/o fancy
# filename extention type rules.
# szurgot 27/01/96-- Added "Plaintextmode" wrapper to binmode PAGE.
# binmode page is required under Win32, but broke modified
# checking
# -- Minor change added ; to "# '" strings for Emacs cperl-mode
# szurgot 07/02/96-- When reading in local file for checking of URLs changed
# local ($/) =0; to equal undef;
# janl 08/02/96 -- Added szurgot's changes and changed them :-)
# szurgot 09/02/96-- Added code to strip /#.*$/ from urls when reading from
# local file
# -- Added hasAlarm variable to w3http.pl. Set to 1 if you have
# alarm(). 0 otherwise.
# -- Moved code setting up the valid extensions list into the
# args processing where it belonged
# janl 20/02/96 -- Added szurgot changes again.
# -- Make timeout code work.
# -- and made another win32 test.
# janl 19/03/96 -- Worked through the code for handling not-modified
# documents, it was a bit shabby after htmlop was intro'ed.
# janl 20/03/96 -- -l fix
# janl 23/04/96 -- Added -fs by request (by Rik Faith)
# janl 16/05/96 -- Made -R mandatory, added use and support for
# w3http::SAVEBIN
# szurgot 19/05/96-- Win95 adaptions.
# janl 19/05/96 -- -C did not exactly work as expected. Thanks to Petr
# Novak for bug descriptions.
# janl 19/05/96 -- Changed logic for @didntget, @got and so on to use
# @queue and %urlstat.
# janl 09/09/96 -- Removed -R switch.
# janl 14/09/96 -- Added ir (initial referer) switch
# janl 21/09/96 -- Made retry code saner. There probably needs to be a
# sleep before retry comencing switch. When no tty is
# present it should be fairly long.
# gorm 15/09/96 -- Added cr (check robot) switch. Default to 1 (on)
# janl 22/09/96 -- Modified gorms patch to use WWW::RobotRules. Changed
# robot switch to be consistent with current w3mir
# practice.
# janl 27/09/96 -- Spelling corrections from [email protected]
# -- Folded in manual diffs from ark.
# ark 24/09/96 -- Simple facilities to edit the incomming file(s)
# janl 27/09/96 -- Added switch to enable <!--NOMIRROR--> editing and
# foolproofed ark's patch a bit.
# janl 02/10/96 -- Added -umask switch.
# -- Redirected documents did not have a meaningful referer
# value (it was undefined).
# -- Got w3mir into strict discipline, found some typos...
# janl 20/10/96 -- Mtime is preserved
# janl 21/10/96 -- -lc switch added. Mtime preservation works better.
# janl 06/11/96 -- Treat 301 like 302.
# janl 02/12/96 -- Added config file code, fetch/ignore rules, apply
# janl 04/12/96 -- Better checking of config input.
# janl 06/12/96 -- Putting together the URL selection/editing brains.
# janl 07/12/96 -- Checking out some bugs. Adding multiscope options.
# janl 12/12/96 -- Adding to and defeaturing the multiscope options.
# janl 13/12/96 -- Continuing work in multiscope stuff
# -- Unreferenced file and empty directory removal works.
# janl 19/02/97 -- Can extract urls from adobe acrobat pdf files :-)
# Important: It does _not_ edit urls, so they still
# point at the original site(s).
# janl 21/02/97 -- Fix -lc bug related to case and the apply things.
# -- only use SAVEURL if needed
# janl 11/03/97 -- Finish work on SAVEURL conditional.
# -- Fixed directory removal code.
# -- parse_args did not abort when unknown option/argument
# was specified.
# janl 12/03/97 -- Made test case for -lc. Didn't work. Fixed it. I think.
# Realized we have bug w.r.t. hostname caseing.
# janl 13/03/97 -- All redirected to URLs within scope are now queued.
# That should make the mirror more complete, but it won't
# help browsability when it comes to the redirected doc.
# -- Moved robot retrival to the inside of the mirror loop
# since we now possebly mirror several sites.
# -- Changed 'fetch-options' to 'options'.
# -- Added 'proxy-options'/-pflush to controll proxy server(s).
# janl 09/04/97 -- Started using URI::URL.
# janl 11/04/97 -- Debugging and using URI::URL more correctly various places
# janl 09/05/97 -- Added --agent switch
# janl 12/05/97 -- Simplified scope checks for root URL, changed URL 'apply'
# processing.
# -- Small output formating fix in the robot rules code.
# -- Version is now 0.99
# janl 14/05/97 -- htmpop no-longer puts '<!DOCTYPE...' into doc, so check
# for '<HTML' instead
# janl 11/06/97 -- Made :port optional in server part of auth-domain.
# Always removing :80 from server part to match netloc.
# janl 22/07/97 -- More debugging of rewrite for new features -B, -I.
# janl 01/08/97 -- Fixed bug in RE quoting for Ignore/Fetch
# janl 04/08/97 -- s/writepage/write_page/g
# janl 07/09/97 -- 0.99b1 is released
# janl 19/09/97 -- Kaj Hejer discovers omissions in non-html-url-mining code.
# -- 0.99b2 is released
# janl 24/09/97 -- Matt Chapman found bug in realm-name extraction.
# janl 10/10/97 -- Referer: header supression supressed User: header instead
# -- Added fixup handling, writes .redirs and .referers
# (no dot in win32)
# -- Read .w3mirc (w3mir.ini on win32) if present
# -- Stop file removal code from removing these files
# janl 16/10/97 -- process_tag was mangling url attributes in tags with more
# than one of them. Problem found by Robert L. Binkley
# janl 04/12/97 -- Fixed problem with authentication, misplaced +
# -- default inter-docuent pause is 0. I figure it's better
# to keep one httpd occupied in a steady stream than to
# wait for it to die before we talk to it again.
# janl 13/12/97 -- The arguments to index.html in the form of index.html/foo
# handling code was incomplete. To make it complete would
# have been hard, so it was removed.
# -- If a URL changes from file to directory or vice versa
# this is now handled.
# janl 11/01/98 -- PDF files with no URLs does not cause warnings now.
# -- Close REFERERS and REDIRECTS before calling w3mfix
# janl 22/01/98 -- Proxy authentication as outlined by Christian Geuer
# janl 04/02/98 -- Version 1pre1
# janl 18/02/98 -- Fixed wild_re after tip by Prentiss Riddle.
# -- Version 1pre2
# janl 20/02/98 -- w3http updated to handle complex content-types.
# -- Fix wild_re more, bug noted by James Dumser
# -- 1.0pre3
# janl 18/03/98 -- Version 1.0 is released
# janl 09/04/98 -- Added feature so user can disable newline conversion.
# janl 20/04/98 -- Only convert newlines in HTML files. -> 1.0.2
# janl 09/05/98 -- More carefull clean_disk code.
# -- Check if the redirected URL was a root url, if so
# issue a warning and exit.
# janl 12/05/98 -- use ->unix_path instead of ->as_string to derive local
# filename.
# janl 25/05/98 -- -B didn't work too well.
# janl 09/07/98 -- Redirect to fragment broke us, less broken now -> 1.0.4
# janl 24/09/98 -- Better errormessages on errors -> 1.0.5
# janl 21/11/98 -- Fix errormessages better.
# janl 05/01/99 -- Drop 'Referer: (commandline)'
# janl 13/04/99 -- Add initial referer to root urls in batch mode.
# janl 15/01/00 -- Remove some leftover print statements
# -- Fix also-queue problem as suggested by Sven Koch
# janl 04/02/01 -- Use epath instead of path quite often -> 1.0.10
#
# Variable name discipline:
# - remote, umodified URL. Variables prefixed 'rum_'
# - local, filesystem. Variables prefixed 'lf_'.
# Use these prefixes so we know what we're working with at all times.
# Also, URL objects are postfixed _o
#
# The apply rules and scope rules work this way:
# - First apply the user rules to the remote url.
# - Check if document is within scope after this.
# - Then apply w3mir's rules to the result. This results is the local,
# filesystem, name.
#
# We use features introduced in 5.002.
require 5.002;
# win32 and $nulldevice need to be globals, other modules use them.
use vars qw($win32 $nulldevice);
# To figure out what kind of system this is
BEGIN {
use Config;
$win32 = ( $Config{'osname'} eq 'MSWin32' );
}
# More ways to die:
use Carp;
# Http module:
use w3http;
# html url extraction and manupulation:
use htmlop;
# Extract urls from adobe acrobat pdf files:
use w3pdfuri;
# Date computer:
use HTTP::Date;
# URLs:
use URI::URL;
# For flush method
use FileHandle;
eval '
use URI;
$URI::ABS_ALLOW_RELATIVE_SCHEME=1;
$URI::ABS_REMOTE_LEADING_DOTS=1;
';
# Full discipline:
use strict;
# Set params in the http package, HTTP protocol version:
$w3http::version="1.0";
# The defaults should be for a robotic http agent on good behaviour.
my $debug=0; # Debug level
my $verbose=0; # Verbosity level, -1 = quiet, 0 = normal, 1...
my $pause=0; # Pause between http requests
my $retryPause=600; # Pause between retries. 10 minutes.
my $retry=3; # Max 3 stabs pr. url.
my $r=0; # Recurse? no recursion = absolutify links
my $remove=0; # Remove files that are not there?
my $s=0; # 0: save on disk 1: stdout 2: just forget 'em
my $useauth=0; # Use authorization
my %authdata; # Authorization data
my $check_robottxt = 1; # Check robots.txt
my $do_referer = 1; # Send referers header
my $do_user = 1; # Send user header
my $cache_header = ''; # The cache-control/pragma: no-cache header
my $using_proxy = 0; # Using proxy server or not?
my $batch=0; # Batch get URLs?
my $read_urls=0; # Get urls from STDIN?
my $abs=0; # Absolutify URLs?
my $immediate_redir=0; # Immediately follow a redirect?
my @root_urls; # This is where we start, the root documents
my @root_dirs; # The corresponding directories. for remove
my $chdirto=''; # Place to chdir to after reading config file
my %nodelete=(); # Files that should not be deleted
my $numarg=0; # Number of arguments accepted.
my $list_nomir=0; # List of files not mirrored
# Fixup related things
my $fixrc=''; # Name of w3mfix config file
my $fixup=1; # Do things needed to run fixup
my $runfix=0; # Run w3mfix for user?
my $fixopen=0; # Fixup files open?
my $indexname='index.html';
my $VERSION;
$VERSION='1.0.10';
$w3http::agent = my $w3mir_agent = "w3mir/$VERSION-2001-01-20";
my $iref=''; # Initial referer. Must evaluate to false
# Derived settings
my $mine_urls=0; # Mine URLs from documents?
my $process_urls=0; # Perform (URL) processing of documents?
# Queue of urls to get.
my @rum_queue = ();
my @urls = ();
# URL status map.
my %rum_urlstat = ();
# Status codes:
my $QUEUED = 0; # Queued but not gotten yet.
my $TERROR = 100; # Transient error, retry later
my $HLERR = 101; # Permanent error, give up
my $GOTIT = 200; # Gotten. Note similarity to http result code
my $NOTMOD = 304; # Not modified.
# Negative codes for nonexistent files, easier to check.
my $NEVERMIND= -1; # Don't want it
my $REDIR = -302; # Does not exist, redirected
my $ENOTFND = -404; # Does not exist.
my $OTHERERR = -600; # Some other error happened
my $FROBOTS = -601; # Forbidden by robots.txt rule
# Directory/files survey:
my %lf_file; # What files are present in FS? Disposition? One of:
my $FILEDEL=0; # Delete file
my $FILEHERE=1; # File present in filesystem only
my $FILETHERE=2; # File present on server too.
my %lf_dir; # Number of files/dirs in dir. If 0 dir is
# eligible for deletion.
my %fiddled=(); # If a file becomes a directory or a directory
# becomes a file it is considered fiddled and
# w3mir will not fiddle with it again in this
# run.
# Bitbucket device, very OS dependent.
$nulldevice='/dev/null';
$nulldevice='nul:' if ($win32);
# What to get, and not.
# Text of user supplied fetch/ignore rules
my $rule_text=" # User defined fetch/ignore rules\n";
# Code ref to the rule procedure
my $rule_code;
# Code to prefix and postfix the generated code. Prefix should make
# $_ contain the url to match. Postfix should return 1, the default
# is to get the url/file.
my $rule_prefix='$rule_code = sub { local($_) = shift;'."\n";
my $rule_postfix=" return 1;\n}";
# Scope tests generated by URL/Also directives in cfg. The scope code
# is just like the rule code, but used for program generated
# fetch/ignore rules related to multiscope retrival.
my $scope_fetch=" # Automatic fetch rules for multiscope retrival\n";
my $scope_ignore=" # Automatic ignore rules for multiscope retrival\n";
my $scope_code;
my $scope_prefix='$scope_code = sub { local($_) = shift;'."\n";
my $scope_postfix=" return 0;\n}";
# Function to apply to urls, se rule comments.
my $user_apply_code; # User specified apply code
my $apply_code; # w3mirs apply code
my $apply_prefix='$apply_code = sub { local($_) = @_;'."\n";
my $apply_lc=' $_ = lc $_; ';
my $apply_postfix=' return $_;'."\n}";
my @user_apply; # List of users apply rules.
my @internal_apply; # List of w3mirs apply rules.
my $infoloss=0; # 1 if any URL translations (which cause
# information loss) are in effect. If this is
# true we use the SAVEURL operation.
my $list; # List url on STDOUT?
my $edit; # Edit doc? Remove <!--NOMIRROR>...<!--/NOMIRROR-->
my $header; # Text to insert in header
my $lc=0; # Convert urls/filenames to lowercase?
my $fetch=0; # What to fetch: -1: Some, 0: not modified 1: all
my $convertnl=1; # Convert newlines?
# Non text/html formats we can extract urls from. Function must take one
# argument: the filename.
my %knownformats = ( 'application/pdf', \&w3pdfuri::list,
'application/x-pdf', \&w3pdfuri::list,
);
# Known 'magic numbers' of the known formats. The value is used as
# key in %knownformats. the key part is a exact match for the
# following <string> beginning at the first byte of the file.
# This should probably be made more flexible, but not until we need it.
my %knownmagic = ( '%PDF-', 'application/pdf' );
my $iinline=''; # inline RE code to make RE caseinsensitive
my $ipost=''; # RE postfix to make it caseinsensitive
usage() unless parse_args(@ARGV);
{
my $w3mirc='.w3mirc';
$w3mirc='w3mir.ini' if $win32;
if (-f $w3mirc) {
parse_cfg_file($w3mirc);
$nodelete{$w3mirc}=1;
}
}
# Check arguments and options
if ($#root_urls>=0) {
# OK
} else {
print "URLs: $#rum_queue\n";
usage("No URLs given");
}
# Are we converting newlines today?
$w3http::convert=0 unless $convertnl;
if ($chdirto) {
&mkdir($chdirto.'/this-is-not-created-odd-or-what');
chdir($chdirto) ||
die "w3mir: Can't change working directory to '$chdirto': $!\n";
}
$SIG{'INT'}=sub { print STDERR "\nCaught SIGINT!\n"; exit 1; };
$SIG{'QUIT'}=sub { print STDERR "\nCaught SIGQUIT!\n"; exit 1; };
$SIG{'HUP'}=sub { print STDERR "\nCaught SIGHUP!\n"; exit 1; };
&open_fixup if $fixup;
# Derive how much document processing we should do.
$mine_urls=( $r || $list );
$process_urls=(!$batch && !$edit && !$header);
# $abs can be set explicitly with -abs, and implicitly if not recursing
$abs = 1 unless $r;
print "Absolute references\n" if $abs && $debug;
# Cache_controll specified but proxy not in use?
die "w3mir: If you want to control a cache, use a proxy server!\n"
if ($cache_header && !$using_proxy);
# Compile the second order code
# - The rum scope tests
my $full_rules=$scope_prefix.$scope_fetch.$scope_ignore.$scope_postfix;
# warn "Scope rules:\n-------------\n$full_rules\n---------------\n";
eval $full_rules;
die "$@" if $@;
die "w3mir: Program generated rules did not compile.\nPlease report to w3mir-core\@usit.uio.no. The code is:\n----\n".
$full_rules."\n----\n"
if !defined($scope_code);
$full_rules=$rule_prefix.$rule_text.$rule_postfix;
# warn "Fetch rules:\n-------------\n$full_rules\n---------------\n";
eval $full_rules;
die "$@!" if $@;
# - The user specified rum tests
die "w3mir: Ignore/Fetch rules did not compile.\nPlease report to w3mir-core\@usit.uio.no. The code is:\n----\n".
$full_rules."\n----\n"
if !defined($rule_code);
# - The user specified apply rules
# $SIG{__WARN__} = sub { print "$_[0]\n"; confess ""; };
my $full_apply=$apply_prefix.($lc?$apply_lc:'').
join($ipost.";\n",@user_apply).(($#user_apply>=0)?$ipost:"").";\n".
$apply_postfix;
eval $full_apply;
die "$@!" if $@;
die "w3mir: User apply rules did not compile.\nPlease report to w3mir-core\@usit.uio.no. The code is:
----
".$full_apply."
----\n" if !defined($apply_code);
# print "user apply: $full_apply\n";
$user_apply_code=$apply_code;
# - The w3mir generated apply rules
$full_apply=$apply_prefix.($lc?$apply_lc:'').
join($ipost.";\n",@internal_apply).(($#internal_apply>=0)?$ipost:"").";\n".
$apply_postfix;
eval $full_apply;
die "$@!" if $@;
die "Internal apply rules did not compile. The code is:
----
".$full_apply."
----\n" if !defined($apply_code);
# - Information loss via -lc? There are other sources as well.
$infoloss=1 if $lc;
warn "Infoloss is $infoloss\n" if $debug;
# More setup:
$w3http::debug=$debug;
$w3http::verbose=$verbose;
my %rum_referers=(); # Array of referers, key: rum_url
my $Robot_Blob; # WWW::RobotsRules object, decides if rum_url is
# forbidden to access for us.
my $rum_url_o; # rum url, mostly the current, the one we're getting
my %gotrobots; # Did I get robots.txt from site? key: url->netloc
my($authuser,$authpass);# Username and password for authentication with server
my @rum_newurls; # List of rum_urls in document
if ($check_robottxt) {
# Eval is only way to defer loading of module until we know it's needed?
eval 'use WWW::RobotRules;';
die "Could not load WWW::RobotRules, try -drr switch\n"
unless defined(&WWW::RobotRules::parse);
$Robot_Blob = new WWW::RobotRules $w3mir_agent;
}
# We have several main-modes of operation. Here we select one
if ($r) {
die "w3mir: No URLs? Try 'w3mir -h' for help.\n"
if $#root_urls==-1;
warn "Recursive retrival comencing\n" if $debug;
die "w3mir: Sorry, you cannot combine -r/recurse with -I/read_urls\n"
if $read_urls;
# Recursive
my $url;
foreach $url (@root_urls) {
warn "Root url dequeued: $url\n" if $debug;
if (want_this($url)) {
queue($url);
&add_referer($url,$iref);
} else {
die "w3mir: Inconsistent configuration: Specified $url is not inside retrival scope\n";
}
}
mirror();
} else {
if ($batch) {
warn "Batch retrival commencing\n" if $debug;
# Batch get
if ($read_urls) {
# Get URLs from <STDIN>
while (<STDIN>) {
chomp;
&add_referer($_,$iref);
batch_get($_);
}
} else {
# Get URLs from commandline
my $url;
foreach $url (@root_urls) {
&add_referer($url,$iref);
}
foreach $url (@root_urls) {
batch_get($url);
}
}
} else {
warn "Single url retrival commencing\n" if $debug;
# A single URL, with all processing on
die "w3mir: You specified several URLs and not -B/batch\n"
if $#root_urls>0;
queue($root_urls[0]);
&add_referer($root_urls[0],$iref);
mirror();
}
}
&close_fixup if $fixup;
# This should clean up files:
&clean_disk if $remove;
warn "w3mir: That's all (".$w3http::xfbytes.'+',$w3http::headbytes.
" bytes of it).\n" unless $verbose<0;
if ($runfix) {
eval 'use Config;';
warn "Running w3mfix\n";
if ($win32) {
CORE::system($Config{'perlpath'}." w3mfix $fixrc");
} else {
CORE::system("w3mfix $fixrc");
}
}
exit 0;
sub get_document {
# Get one document by HTTP ($1/rum_url_o). Save in given filename ($2).
# Possebly returning references found in the document. Caller must
# set up referer array, check wantedness and everything else. We
# handle authentication here though.
my($rum_url_o)=shift;
my($lf_url)=shift;
croak("\$rum_url_o is empty") if !defined($rum_url_o) || !$rum_url_o;
croak("$lf_url is empty") if !defined($lf_url) || !$lf_url;
# Make sure it's an object
$rum_url_o = url $rum_url_o
unless ref $rum_url_o;
# Derive a filename from the url, the filename contains no URL-quoting
my($lf_name) = (url "file:$lf_url")->unix_path;
# revert to quick fix:
$lf_name =~ s/^\///;
# Make all intermediate directories
&mkdir($lf_name) if $s==0;
my($rum_as_string) = $rum_url_o->as_string;
print STDERR "GET_DOCUMENT: '",$rum_as_string,"' -> '",$lf_name,"'\n"
if $debug;
my $hostport;
my $www_auth=''; # Value of that http reply header
my $page_ref;
my @rum_newurls; # List of URLs extracted
my $url_extractor;
my $do_query; # Do query or not?
if (defined($rum_urlstat{$rum_as_string}) &&
$rum_urlstat{$rum_as_string}>0) {
warn "w3mir: Internal error, ".$rum_as_string.
" queued several times\n";
next;
}
# Goto here if we want to retry b/c of authentication
try_again:
# Start building the extra http::query arguments again
my @EXTRASTUFF=();
# We'll start by assuming that we're doing the query.
$do_query=1;
# If we're not checking the timestamp, or the file does not exist
# then we get the file unconditionally. Otherwise we only want it
# if it's updated.
if ($fetch==1) {
# Nothing do do?
} else {
if (-f $lf_name) {
if ($fetch==-1) {
print STDERR "w3mir: ".($infoloss?$rum_as_string:$lf_name).
", already have it" if $verbose>=0;
if (!$mine_urls) {
# If -fs and the file exists and we don't need to mine URLs
# we're finished!
warn "Already have it, no mining, returning!\n" if $debug;
print STDERR "\n" if $verbose>=0;
return;
}
$w3http::result=1304; # Pretend it was 'not modified'
$do_query=0;
} else {
push(@EXTRASTUFF,$w3http::IFMODF,$lf_name);
}
}
}
if ($do_query) {
# Does the server want authorization for this file? $www_auth is
# only set if authentication was requested the first time around.
# For testing:
# $www_auth='Basic realm="foo"';
if ($www_auth) {
my($authdata,$method,$realm);
($method,$realm)= $www_auth =~ m/^(\S+)\s+realm=\"([^\"]+)\"/i;
$method=lc $method;
$realm=lc $realm;
die "w3mir: '$method' authentication needed, don't know that.\n"
if ($method ne 'basic');
$hostport = $rum_url_o->netloc;
$authdata=$authdata{$hostport}{$realm} || $authdata{$hostport}{'*'} ||
$authdata{'*'}{$realm} || $authdata{'*'}{'*'};
if ($authdata) {
push(@EXTRASTUFF,$w3http::AUTHORIZ,$authdata);
} else {
print STDERR "w3mir: No authorization data for $hostport/$realm\n";
$rum_urlstat{$rum_as_string}=$NEVERMIND;
next;
}
}
push(@EXTRASTUFF,$w3http::FREEHEAD,$cache_header)
if ($cache_header);
# Insert referer header data if at all
push(@EXTRASTUFF,$w3http::REFERER,$rum_referers{$rum_as_string}[0])
if ($do_referer && exists($rum_referers{$rum_as_string}));
push(@EXTRASTUFF,$w3http::NOUSER)
unless ($do_user);
# YES, $lf_url is right, w3http::query handles this like an url so
# the quoting must all be in place.
my $binfile=$lf_url;
$binfile='-' if $s==1;
$binfile=$nulldevice if $s==2;
if ($pause) {
print STDERR "w3mir: sleeping\n" if $verbose>0;
sleep($pause);
}
print STDERR "w3mir: ".($infoloss?$rum_as_string:$lf_name)
unless $verbose<0;
print STDERR "\nFile: $lf_name\n" if $debug;
&w3http::query($w3http::GETURL,$rum_as_string,
$w3http::SAVEBIN,$binfile,
@EXTRASTUFF);
print STDERR "w3http::result: '",$w3http::result,
"' doc size: ", length($w3http::document),
" doc type: -",$w3http::headval{'CONTENT-TYPE'},
"- plaintexthtml: ",$w3http::plaintexthtml,"\n"
if $debug;
print "Result: ",$w3http::result," Recurse: $r, html: ",
$w3http::plaintexthtml,"\n"
if $debug;
} # if $do_query
if ($w3http::result==200) { # 200 OK
$rum_urlstat{$rum_as_string}=$GOTIT;
if ($mine_urls || $process_urls) {
if ($w3http::plaintexthtml) {
# Only do URL manipulations if this is a html document with no
# special content-encoding. We do not handle encodings, yet.
my $page;
print STDERR ($process_urls)?", processing":", url mining"
if $verbose>0;
print STDERR "\nurl:'$lf_url'\n"
if $debug;
print "\nMining URLs: $mine_urls, Process: $process_urls\n"
if $debug;
($page,@rum_newurls) =
&htmlop::process($w3http::document,
# Only get a new document if wanted
$process_urls?():($htmlop::NODOC),
$htmlop::CANON,
$htmlop::ABS,$rum_url_o,
# Only list urls if wanted
$mine_urls?($htmlop::LIST):(),
# If user wants absolute URLs do not
# relativize them
$abs?
():
(
$htmlop::TAGCALLBACK,\&process_tag,$lf_url,
)
);
# print "URL: ",join("\nURL: ",@rum_newurls),"\n";
if ($process_urls) {
$page_ref=\$page;
$w3http::document='';
} else {
$page_ref=\$w3http::document;
}
} elsif ($s == 0 &&
($url_extractor =
$knownformats{$w3http::headval{'CONTENT-TYPE'}})) {
# The knownformats extractors only work on disk files so write
# doc to disk if not there already (non-html text will not be)
write_page($lf_name,$w3http::document,1);
# Now we try our hand at fetching URIs from non-html files.
print STDERR ", mining URLs" if $verbose>=1;
@rum_newurls = &$url_extractor($lf_name);
# warn "URLs from PDF: ",join(', ',@rum_newurls),"\n";
}
} # if ($mine_urls || $process_urls)
# print "page_ref defined: ",defined($page_ref),"\n";
# print "plaintext: ",$w3http::plaintext,"\n";
$page_ref=\$w3http::document
if !defined($page_ref) && $w3http::plaintexthtml;
if ($w3http::plaintexthtml) {
# ark: this is where I want to do my changes to the page strip
# out the <!--NOMIRROR-->...<!--/NOMIRROR--> Stuff.
$$page_ref=~ s/<(!--)?\s*NO\s*MIRROR\s*(--)?>[^\000]*?<(!--)?\s*\/NO\s*MIRROR\s*(--)?>//g
if $edit;
if ($header) {
# ark: insert a header string at the start of the page
my $mirrorstr=$header;
$mirrorstr =~ s/\$url/$rum_as_string/g;
insert_at_start( $mirrorstr, $page_ref );
}
}
write_page($lf_name,$page_ref,0);
# print "New urls: ",join("\n",@rum_newurls),"\n";
return @rum_newurls;
}
if ($w3http::result==304 || # 304 Not modified
$w3http::result==1304) { # 1304 Have it
{
# last = out of nesting
my $rum_urlstat;
my $rum_newurls;
@rum_newurls=();
print STDERR ", not modified"
if $verbose>=0 && $w3http::result==304;
$rum_urlstat{$rum_as_string}=$NOTMOD;
last unless $mine_urls;
$rum_newurls=get_references($lf_name);
# print "New urls: ",ref($rum_newurls),"\n";
if (!ref($rum_newurls)) {
last;
} elsif (ref($rum_newurls) eq 'SCALAR') {
$page_ref=$rum_newurls;
} elsif (ref($rum_newurls) eq 'ARRAY') {
@rum_newurls=@$rum_newurls;
last;
} else {
die "\nw3mir: internal error: Unknown return type from get_references\n";
}
# Check if it's a html file. I know this tag is in all html
# files, because I put it there as I pull them in.
last unless $$page_ref =~ /<HTML/i;
warn "$lf_name is a html file\n" if $debug;
# It's a html document
print STDERR ", mining URLs" if $verbose>=1;
# This will give us a list of absolute urls
(undef,@rum_newurls) =
&htmlop::process($$page_ref,$htmlop::NODOC,
$htmlop::ABS,$rum_as_string,
$htmlop::USESAVED,'W3MIR',
$htmlop::LIST);
}
print STDERR "\n" if $verbose>=0;
return @rum_newurls;
}
if ($w3http::result==302 || $w3http::result==301) { # Redirect
# Cern and NCSA httpd sends 302 'redirect' if a ending / is
# forgotten on a url. More recent httpds send 301 'permanent
# redirect' in this case. Here we check if the difference in URLs
# is just a / and if so push the url again with the / added. This
# code only works if the http server has the right idea about its
# own name.
#
# 18/3/97: Added code to queue redirected-to-URLs that are within
# the scope of the retrival.
my $new_rum_url;
$rum_urlstat{$rum_as_string}=$REDIR;
# Absolutify the new url, it might be relative to the requested
# document. That's a ugly wart on some servers/admins.
$new_rum_url=url $w3http::headval{'location'};
$new_rum_url=$new_rum_url->abs($rum_url_o);
print REDIRS $rum_as_string,' -> ',$new_rum_url->as_string,"\n"
if $fixup;
if ($immediate_redir) {
print STDERR " =>> ",$new_rum_url->as_string,", getting that instead\n";
return get_document($new_rum_url,$lf_url);
}
# Some redirect to a fragment of another doc...
$new_rum_url->frag(undef);
$new_rum_url=$new_rum_url->as_string;
if ($rum_as_string.'/' eq $new_rum_url) {
if (grep { $rum_as_string eq $_; } @root_urls) {
print STDERR "\nw3mir: missing / in a start URL detected. Please fix commandline/config file.\n";
exit(1);
}
print STDERR ", missing /\n";
queue($new_rum_url);
# Initialize referer to something meaningful
$rum_referers{$new_rum_url}=$rum_referers{$rum_as_string};
} else {
print STDERR " =>> $new_rum_url";
if (want_this($new_rum_url)) {
print STDERR ", getting that\n";
queue($new_rum_url);
$rum_referers{$new_rum_url}=$rum_referers{$rum_as_string};
} else {
print STDERR ", don't want it\n";
}
}
return ();
}
if ($w3http::result==403 || # Forbidden
$w3http::result==404 || # Not found
$w3http::result==406 || # Not Acceptable, hmm, belongs here?
$w3http::result==410) { # Gone - no forwarding address known
$rum_urlstat{$rum_as_string}=$ENOTFND;
&handleerror;
print STDERR "Was refered from: ",
join(',',@{$rum_referers{$rum_as_string}}),
"\n" if @{$rum_referers{$rum_as_string}};
return ();
}
if ($w3http::result==407) {
# Proxy authentication requested
die "Proxy server requests authentication but failed to return the\n".
"REQUIRED Proxy-Authenticate header for this condition\n"