This repository has been archived by the owner on Jun 5, 2018. It is now read-only.
/
swec
executable file
·2614 lines (2334 loc) · 65.9 KB
/
swec
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
# swec - Simple Web Error Checker
# Copyright (C) Eskild Hustvedt 2008, 2009, 2010
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.
use strict;
use warnings;
# Used to fetch data
use LWP::UserAgent;
# Used for cookie support
use HTTP::Cookies;
# Used for printing the error listing to the user
use Data::Dumper;
# Used for commandline parsing
use Getopt::Long;
# Used for session support
use Storable;
# OS detection
use POSIX qw(uname);
# Need these to locate the default.sdf
use Cwd qw(realpath);
use File::Basename qw(dirname);
# Makes code easier to read
use constant {
true => 1,
false => 0,
};
# Signal handling
$SIG{INT} = \&ErrorReport;
$SIG{TERM} = \&ErrorReport;
# The version number
my $VERSION = '0.5';
# The base URI
my $baseURI;
# The same in regex
my $baseURIRegex;
# True if we have run the error report. We don't set this to false until
# after we've started processing pages, no need to display an empty
# report.
my $hasRunErrorRep = true;
# The base user agent string
my $BaseUA = 'SWEC/'.$VERSION.' (%OS%; Simple Web Error Checker/LWP; spider/crawler) giveme ';
# Appended to the user agent, can be changed with commandline options
my $GiveMeUA = 'Mozilla/5.0 Firefox Gecko';
# The logfile
my $logfile;
# Debug logging level
my $debugLog = 0;
# The regex of filenames to ignore
my $ignoreregex = '\.(png|exe|run|gif|pdf|phps|deb|rpm|bin|jpe?g|css|bz2|gz|tar|tgz|zip|rar|odt|odp|doc|psp|swf|js|patch|vim)';
# The session hashref, if we have a session
my $session;
# The session filename, if we have a session
my $session_file;
# -- Global arrays --
# This is an array that we use in order to not have to sort the %Checks hash
# each and every time it is run. This should never be put into a session,
# but be resorted on each load.
# It's simply an array of names.
my @DefaultSortedChecks;
# The same, but for URL tests
my @URLSortedChecks;
# List of loaded SDF files
my @LoadedSDF;
# List of page seeds
my @PageSeeds;
# List of page seeds to POST to
my @PageSeedsPost;
# Logged messages, pushed to by toLog()
my @loggedMessages;
# -- Core settings, and their defaults --
my %settings = (
SDFFile => undef, # String, path to an SDF file (XXX: not in use)
HardErrorMax => 5, # Int, the hard number of max errors that can occur on a page type before we
# assume all pages of that type has errors.
skipHEAD => false, # Boolean, true if we should skip the HEAD requests
Debug => false, # Boolean, debugging is off by default
OnlyNewErrors => false, # Boolean, true if we should only print information about new errors
keepGoing => false, # Boolean, true if we should just keep on parsing links from pages with errors
htmlInfo => false, # Boolean, true if we don't have HTML::LinkExtractor but have HTML::Entities
uriEncode => false, # Boolean, true if we have URI::Encode
checkSubDomains => false,# Boolean, true if we should allow subdomains in the URIRegex
noIgnores => false, # Boolean, true if default --matchmax ignores should not be added
disabledLibs => {}, # Hashref of libs that SWEC should not use
);
# -- Global hashes --
# Filter checks, loaded from an SDF file.
# See the manpage for a definition of the SDF file format.
# The syntax of this hash is:
# NAME => {
# sdf_setting => sdf_value,
# }
# Checks will be present in this hash, even if they are suppose to be ignored
# (ie. it exists in the %IgnoreChecks hash), but will be skipped at runtime.
my %Checks;
my (
%MatchMax, # Hash of expression => setting pairs. See addMatchMax()
%HasRun, # Hash of url => true pairs of URLs that have been processed
%HasPrinted, # Hash of url path => true pairs of URLs that have been printed
%CurrLinks, # Hash of url => true pairs of URLs that are known not to have been processed
%ErrorPages, # Hash of url => error pairs
%ErrorCount, # Hash of url => number of errors
%PageCount, # Hash of url => number of pages fetched
%IgnoreChecks, # Hash of SWEC/SDF checks to ignore
%wasPageSeed, # Hash of url => true pairs of URLs that were seeds
);
my %MatchedMax = (
seen => {}, # If we have seen a URL previously, its status is saved here
checkCount => {}, # Contains how many times an expression has matched
);
# -- Global objects --
# The LWP::UserAgent object
my($UA);
# HTML::LinkExtractor object
my $EX;
# == Begin main app ==
# Display the help screen if no args were supplied.
help() if not @ARGV;
# Commandline parsing
GetOptions
(
'ie' => sub {
$GiveMeUA = 'Mozilla/5.0 MSIE Trident';
},
'opera' => sub {
$GiveMeUA = 'Opera Presto';
},
'chrome' => sub
{
$GiveMeUA = 'Mozilla/5.0 AppleWebKit (KHTML, like Gecko) Chrome Safari';
},
'android' => sub
{
$GiveMeUA = 'Mozilla/5.0 Android AppleWebKit (KHTML, like Gecko) Mobile Safari';
},
'ua=s' => sub {
shift;
$BaseUA = shift;
$GiveMeUA = ' (SWEC - Simple Web Error Checker-perl/LWP; spider/crawler)';
},
'session=s' => \$session_file,
'i|sessnam=s' => sub {
shift;
my $nam = shift;
$session_file = $nam.'.ses';
$logfile = $nam.'.log';
},
's|urlseed=s' => sub {
shift;
my $u = shift;
push(@PageSeeds,$u);
},
'postseed=s{2}' => \@PageSeedsPost,
'm|matchmax=s' => sub {
shift;
my $match = shift;
my $no = $match;
my $reversed = 0;
if(not $match =~ s/=\d+$//)
{
swecDie(10,"Failed to parse commandline: --matchmax $match\n");
}
if(not $no =~ s/^.*=(\d+)$/$1/)
{
swecDie(10,"Failed to parse commandline: --matchmax $no\n");
}
if ($match =~ s/^!//)
{
$reversed = 1;
}
$_ = '';
eval
{
/$match/
};
if ($@)
{
swecDie(10,"Regular expression error in --matchmax: $@");
}
addMatchMax($match,$no,$reversed);
},
'b|baseurl|baseuri=s' => \$baseURI,
'l|log=s' => \$logfile,
'debuglog+' => \$debugLog,
'e|harderrorlimit=i' => \$settings{HardErrorMax},
'parsedump=s' => sub {
shift;
my $file = shift;
LoadSDFv2($file,\%Checks);
$Data::Dumper::Sortkeys = true;
$Data::Dumper::Varname = 'SDF_PARSE_DUMP';
$Data::Dumper::Terse = true;
$Data::Dumper::Indent = 1;
print Dumper(\%Checks);
exit(0);
},
'validate=s' => sub {
shift;
my $file = shift;
local $| = true;
LoadSDFv2($file,\%Checks);
print "$file syntax OK\n";
exit(0);
},
'debuginfo' => sub {
debugInfo();
},
'x|exclude=s' => sub {
shift;
my $t = shift;
$IgnoreChecks{$t} = true;
},
'checksub|checksubdomains' => \$settings{checkSubDomains},
'keepgoing' => \$settings{keepGoing},
'nohead' => \$settings{skipHEAD},
'noignores' => \$settings{noIgnores},
'lwphead' => \&LWP_CommandlineEmu,
'lwpget' => \&LWP_CommandlineEmu,
'onlynew' => sub {
$settings{OnlyNewErrors} = true,
},
'disable-lib|disablelib=s' => sub {
shift;
my $lib = shift;
$settings{disabledLibs}->{$lib} = true;
},
'h|help' => sub { help(); },
'help-all' => sub { help(1) },
'version' => sub { print "SWEC version $VERSION\n"; exit 0; },
) or exit(10);
main();
# Purpose: Main program
# Usage: main();
sub main
{
# Initialize session
if(defined $session_file and not -e $session_file)
{
print "$session_file: does not exist. Assuming new session.\n";
$session = {};
}
else
{
loadSession();
}
# Prepare the baseURI
prepareBaseURI();
setTermTitle('swec ['.$baseURI.']');
# Prepare URL seeds
prepareSeeds();
# Load the SDF data
AutoLoadSDF();
# Initialize LWP
InitLWP();
# Initialize our optional libs
initOptionalLibs();
if(not $settings{noIgnores})
{
foreach my $def (qw(logout delete))
{
if(not defined $MatchMax{$def})
{
addMatchMax($def,0,false);
}
}
}
# Purge STDOUT at once
$| = true;
# We've begun processing, so now errors should be shown
$hasRunErrorRep = false;
# First fetch the post seeds
if (@PageSeedsPost)
{
initPageSeedsPost();
FetchLinks(\@PageSeedsPost,true)
}
# Then fetch the normal seeds
FetchLinks(\@PageSeeds);
# Load data from the session if we have one
if ($session)
{
my %ErrorLinks;
# Import errors from session into ErrorLinks and run through those pages.
# (links found inside those pages will be appended to CurrLinks).
SessionImportLinks(\%ErrorLinks,true);
if(keys %ErrorLinks)
{
FetchLinks(\%ErrorLinks);
}
# Now import all other links saved in the session into CurrLinks
SessionImportLinks(\%CurrLinks,false);
}
# Finally, loop until there are no links left
while(keys %CurrLinks)
{
FetchLinks(\%CurrLinks);
}
# And output the error report
ErrorReport();
}
# Purpose: Initialize our seeds
# Usage: prepareSeeds();
sub prepareSeeds
{
my @newSeeds;
foreach my $u (@PageSeeds)
{
my $seed = getFullSeedURL($u);
if(not $seed)
{
swecDie(10,"--urlseed '$u' does not contain http:// and no --baseurl was found..\n");
}
push(@newSeeds,$seed);
}
@PageSeeds = @newSeeds;
}
# Purpose: Initialize a single seed
# Usage: $u = getFullSeedURL();
sub getFullSeedURL
{
my $url = shift;
if(not $url =~ /^http/)
{
if ($baseURI)
{
$url = $baseURI.'/'.$url;
$url =~ s#/+#/#g;
$url =~ s#^(https?):/#$1://#g;
}
else
{
$url = undef;
}
}
return $url;
}
# Purpose: Initialize PageSeedsPost
# Usage: initPageSeedsPost();
sub initPageSeedsPost
{
my @result;
for(my $i = 0; $i < @PageSeedsPost; $i++)
{
my $u = $PageSeedsPost[$i];
my $url = getFullSeedURL($u);
if(not $url)
{
swecDie(10,"--urlseed '$u' does not contain http:// and no --baseurl was found..\n");
}
$i++;
my $data = $PageSeedsPost[$i];
my $resultingData = {};
foreach my $l (split(/\&/,$data))
{
my $key = $l;
my $value = $l;
$key =~ s/^([^=]+)=.*/$1/;
$value =~ s/^[^=]+=(.*)/$1/;
if ($key eq $l or $value eq $l)
{
swecDie(10,"Failed to parse data pair for --postseed $url: \"$l\"");
}
$resultingData->{$key} = $value;
}
push(@result,$url,$resultingData);
}
@PageSeedsPost = @result;
}
# Purpose: Initialize the base URI
# Usage: prepareBaseURI();
sub prepareBaseURI
{
# If we make an assumption about something, this should be set to true
# and we will output a message about it at the end of this block.
my $madeAssumption = false;
my $useURLSeed;
# If we don't have a $baseURI then we need to find one
if(not $baseURI)
{
# Fetch from session if present
if ($session and $session->{baseuri})
{
$baseURI = $session->{baseuri};
}
else
{
# Try to fetch from parameters
if (@ARGV)
{
$baseURI = shift(@ARGV);
$madeAssumption = true;
}
# Give up
if (not $baseURI)
{
swecDie(10,"You must supply a --baseurl\n");
}
if(not @PageSeeds)
{
$useURLSeed = $baseURI;
$baseURI =~ s{^((\w+\:+/+)?[^/]+).*}{$1};
# If our baseURI is the same as the URL seed here, then
# we don't have additional URI bits, so don't set useURLSeed.
if($baseURI eq $useURLSeed)
{
$useURLSeed = undef;
}
}
}
}
# Make sure that it starts with something://, if not, assume http://
if(not $baseURI =~ m#^\w+://#)
{
$baseURI = 'http://'.$baseURI;
$madeAssumption = true;
}
prepareBaseURIRegex();
# Output a message that says we assumed something
# Ensure we have at least one page seed and load from the session if needed
if(not @PageSeeds)
{
if ($session and keys(%{$session->{pageSeeds}}))
{
@PageSeeds = @{$session->{pageSeeds}};
}
else
{
if ($madeAssumption)
{
print "Assuming --baseurl $baseURI\n";
}
if ($useURLSeed)
{
$useURLSeed =~ s{^\w+://[^/]+}{};
$useURLSeed =~ s{/+}{/};
if(not $useURLSeed =~ m{^/})
{
$useURLSeed = '/'.$useURLSeed;
}
print "Assuming --urlseed $useURLSeed\n";
push(@PageSeeds,$useURLSeed);
}
else
{
print "Assuming --urlseed /\n";
push(@PageSeeds,'/');
}
}
}
if($session and not keys %MatchMax and $session->{MatchMax})
{
%MatchMax = %{$session->{MatchMax}};
}
}
# Purpose: Initialize the base URI regex
# Usage: prepareBaseURIRegex();
sub prepareBaseURIRegex
{
my $scheme = $baseURI;
my $domain = $baseURI;
$domain =~ s{^\w+://}{};
$scheme =~ s{^(\w+://).*}{$1};
if (not $scheme)
{
$scheme = 'http://';
}
if ($settings{checkSubDomains})
{
$baseURIRegex = qr{($scheme)?([^/]+\.)?$domain};
}
else
{
if ($domain =~ /^www/)
{
$baseURIRegex = qr/($scheme)?$domain/;
}
else
{
$baseURIRegex = qr/($scheme)?(www\.)?$domain/;
}
}
}
# Purpose: Set the title of the xterm/screen
# Usage: setTermTitle(TITLE);
sub setTermTitle
{
return if not defined $ENV{TERM};
my $title = shift;
if ($ENV{TERM} =~ /screen/)
{
print "\033k$title\033\\";
}
else
{
print "\033]0;$title\007";
}
}
# Purpose: Output information useful for debugging
# Usage: debuginfo();
sub debugInfo
{
eval('use Digest::MD5;');
print "SWEC version $VERSION\n";
my $md5 = Digest::MD5->new();
my $loc = realpath($0);
open(my $f,'<',$loc);
$md5->addfile($f);
my $digest = $md5->hexdigest;
close($f);
my $fmt = '%-20s: %s'."\n";
printf($fmt,'MD5',$digest);
setupUAString();
printf($fmt,'User agent',$BaseUA.$GiveMeUA);
printf($fmt,'Ignore regex',$ignoreregex);
if(keys %{$settings{disabledLibs}})
{
printf($fmt,'Libs disabled by user',join(' ',keys %{$settings{disabledLibs}}));
}
my $parser;
my $uriEncode;
if(tryUse('HTML::LinkExtractor'))
{
$parser = 'HTML::LinkExtractor';
printf($fmt,'HTML::LinkExtractor','available ('.$HTML::LinkExtractor::VERSION.')');
}
else
{
printf($fmt,'HTML::LinkExtractor','not available');
if(tryUse('HTML::Entities'))
{
$parser = 'builtin with HTML::Entities';
printf($fmt,'HTML::Entities','available ('.$HTML::Entities::VERSION.')');
}
else
{
$parser = 'builtin without HTML::Entities';
printf($fmt,'HTML::Entities','not available');
}
}
printf($fmt,'Parser',$parser);
if(tryUse('URI::Encode'))
{
printf($fmt,'URI::Encode','available ('.$URI::Encode::VERSION.')');
$uriEncode = 'URI::Encode';
}
else
{
printf($fmt,'URI::Encode','not available');
$uriEncode = '(none)';
}
printf($fmt,'URI encoder',$uriEncode);
exit(0);
}
# Purpose: Output the help screen and exit
# Usage: help();
sub help
{
my $all = shift;
print "swec - Simple Web Error Checker version $VERSION\n\n";
print "USAGE: swec [OPTIONS]\n";
print " OR : swec ([OPTIONS]) [HOST]\n\n";
if ($all)
{
PrintHelp('','--help','Print the normal help screen');
PrintHelp('','--help-all','Print this help screen');
PrintHelp('','--version','Print version information and exit');
}
else
{
PrintHelp('','--help','Print this help screen');
PrintHelp('','--help-all','Print an extended help screen with advanced options');
}
PrintHelp('','--ie','Pretend to be IE (default: Firefox)');
PrintHelp('','--opera','Pretend to be Opera (default: Firefox)');
PrintHelp('','--chrome','Pretend to be Google Chrome (default: Firefox)');
PrintHelp('','--android','Pretend to be an Android phone (default: Firefox)');
PrintHelp('','--ua','Manually specify user agent string');
PrintHelp('-b','--baseurl','The base URL. Will only check URLs matching it and will use it as the domain/url for pages that have relative paths');
PrintHelp('-s','--urlseed','The URL seed, the first URL to check. Can be supplied multiple times, order does not matter. Supply -b before -s in order to be able to supply relative paths');
PrintHelp('-l','--log','Write a log to this file');
PrintHelp('','--session','Save and load session from the file supplied. See the manpage for more information on sessions.');
PrintHelp('-i','--sessnam','Takes a FILE argument. Short for --session FILE.ses --log FILE.log');
PrintHelp('-x','--exclude','Exclude the test ID supplied');
PrintHelp('','--nohead','SWEC sends a HEAD request before each GET request to detect binary files. This makes SWEC skip the HEAD request and rely on file name filtering to detect binary files.');
PrintHelp('','--lwpget, --lwphead','SWEC equivalents of the lwp-request GET and HEAD commands. See the manpage for more information');
PrintHelp('','--keepgoing','Parse a page for links even if it contained errors');
if ($all)
{
PrintHelp('','--postseed','Works like --urlseed but takes a second parameter; a string of key-value pairs that will be POSTed. See the manpage for more information.');
PrintHelp('','--checksub','Allow SWEC to follow and check links to subdomains of the --baseurl');
PrintHelp('-e','--harderrorlimit','Change the hard error page limit, the max amount of pages of any link type to request before deciding that all pages of that type will return errors (and thus not request any more) (default: 5)');
PrintHelp('-m','--matchmax','Takes a parameter in the form: [REGEXP]=COUNT. [REGEXP] will be matched against all URLs, and SWEC will never test more than COUNT URLs that matches [REGEXP]');
PrintHelp('','--validate','Takes a FILE argument. Validate the syntax of the SDF file supplied');
PrintHelp('','--parsedump','Takes a FILE argument. Load the SDF file supplied and dump the parsed data structure to STDOUT. Useful for debugging problems with regular expressions, or simply to see how SWEC sees your SDF file');
PrintHelp('','--disable-lib','Takes a single argument, the library to skip using. See the manpage for details.');
if(InPath('perldoc'))
{
print "\nFor more complete documentation, run: perldoc $0\n";
}
elsif(InPath('man'))
{
print "\nFor more complete documentation, run: man swec\n";
}
}
exit(0);
}
# Purpose: Get the real URL for the URL pair supplied
# Usage: my $URL = GetRealUrl(PARENT, CHILD);
sub GetRealUrl
{
my $URL = shift;
my $parent = shift;
my $return;
if( $URL =~ m#^(https?)# )
{
return $URL;
}
elsif(not $URL =~ m{^/})
{
my $parentPath = getBaseURL($parent);
$parentPath =~ s/^https?:\/\/[^\/]+//;
if ($parentPath =~ /\/$/)
{
$return = $parentPath.$URL;
}
elsif($URL =~ /^\?/)
{
$parentPath =~ s/\?.*//;
}
elsif ($parentPath =~ /\w+\.\w+$/)
{
$parentPath =~ s/\/+\w+\.\w+$//;
}
$return = $parentPath.$URL;
}
else
{
$return = $URL;
}
if ($parent =~ m{^http})
{
$parent =~ s{^(https?://[^/]+).*}{$1};
$return = $parent.'/'.$return;
}
else
{
$return = $baseURI.'/'.$return;
}
return $return;
}
# Purpose: Emulate the commandline GET and HEAD lwp commands
# Usage: \&LWP_CommandlineEmu in a parameter
sub LWP_CommandlineEmu
{
# We need to set hasRunErrorRep to true, so if the user presses ctrl+c
# we won't run a useless error report.
$hasRunErrorRep = 1;
my $arg = shift;
InitLWP();
my $type = 'head';
if ($arg =~ /get/)
{
$type = 'get';
}
foreach my $url (@ARGV)
{
next if $url =~ /^\-\-\w+$/;
$url = ($url =~ m{^\w\w+://}) ? $url : 'http://'.$url;
print "\n--\n$url:\n--\n";
my $r = LWP_Request($type,$url);
print $r->headers_as_string;
if ($type eq 'get')
{
print "\n";
print $r->content;
if(not $r->content =~ /\n$/)
{
print "\n";
}
}
}
exit(0);
}
# Purpose: Prepare the UA string
# Usage: setupUAString();
sub setupUAString
{
# Set the UA string
my @UNAME = uname();
my $name = $UNAME[0] eq 'Linux' ? 'GNU/Linux' : $UNAME[0];
$BaseUA =~ s/%OS%/$name/g;
}
# Purpose: Check for a file in path
# Usage: InPath(FILE)
sub InPath
{
foreach (split /:/, $ENV{PATH}) { if (-x "$_/@_" and not -d "$_/@_" ) { return 1; } } return 0;
}
# Purpose: Initialize LWP
# Usage: InitLWP();
sub InitLWP
{
setupUAString();
# Create our LWP::UserAgent object, used for HTTP requests
$UA = LWP::UserAgent->new(
'agent' => $BaseUA.$GiveMeUA
);
# We need to support cookies
$UA->cookie_jar(HTTP::Cookies->new());
}
# Purpose: Persistant wrapper around LWP. Will re-request a URL three times with
# three second intervals if needed
# Usage: LWP_Request('type',URL);
# type is either head or get
sub LWP_Request
{
my($type,$URL,$postData) = @_;
my $r;
my $success = 0;
for(my $l = 0; $l < 3; $l++)
{
if ($l != 0)
{
if ($l == 1)
{
print "connection error - ";
}
print "retrying... ";
sleep(3);
}
if ($type eq 'head')
{
$r = $UA->head($URL);
}
elsif($type eq 'get')
{
$r = $UA->get($URL);
}
elsif($type eq 'post')
{
printd(2,'Posting '.Dumper($postData).' to '.$URL) if $debugLog;
$r = $UA->post($URL,$postData);
}
else
{
swecDie(9,"LWP_Request(): unknown type: $type");
}
if (not (($r->is_error) && ($r->status_line =~ /(reset by peer|Connection refused|Can't connect)/i)))
{
$success = 1;
last;
}
}
if ($success)
{
return $r;
}
else
{
return;
}
}
# Purpose: Dump an arrayref or hashref to STDOUT with a pretty format
# Usage: print swecDumper(someRef);
sub swecDumper
{
my $ref = shift;
my $l = "\n";
if (ref($ref) eq 'HASH')
{
foreach my $h (keys %{$ref})
{
$l .= sprintf('%-30s => %s'."\n",$h,$ref->{$h});
}
}
elsif(ref($ref) eq 'ARRAY')
{
foreach my $line (@{$ref})
{
$l .= $line;
}
}
return $l;
}
# Purpose: Output the final error report and logfile, also call session writing functions
# Usage: ErrorReport();
sub ErrorReport
{
my %Errors = %ErrorPages;
my $rep;
exit(0) if $hasRunErrorRep;
my $returnVal = 0;
$hasRunErrorRep = true;
print "\n---\n\n";
$rep .= $baseURI.":\n";
$rep .= 'Out of '.scalar(keys(%HasRun)).' pages fetched, '.scalar(keys(%ErrorPages)).' had errors'."\n";
# Only include 'base page' info if it differs from the above
if(scalar(keys(%PageCount)) != scalar(keys(%HasRun)))
{
$rep .= 'Out of '.scalar(keys(%PageCount)).' base pages checked '.scalar(keys(%ErrorCount)).' had errors'."\n";
}
if ($settings{OnlyNewErrors} && $session)
{
SesRemoveOldErrors(\%Errors);
}
if(keys %Errors)
{
appendToSession('ErrorPages',\%Errors);
$rep .= swecDumper(\%Errors);
$returnVal = 1;
}
else
{
$rep .= "\nNo errors to report.\n";
}
print $rep;
if ($session)
{
if(keys %ErrorPages)
{
appendToSession('LastRawErrorPages',\%ErrorPages,true);
}
appendToSession('lasthumanlog',$rep);
appendToSession('baseuri',$baseURI);
appendToSession('logfile',$logfile);
appendToSession('pageSeeds',\@PageSeeds);
appendToSession('HasRun',\%HasRun);
appendToSession('HardErrorMax',$settings{HardErrorMax});
appendToSession('BaseUA',$BaseUA);
appendToSession('GiveMeUA',$GiveMeUA);
appendToSession('LoadedSDF',\@LoadedSDF);
appendToSession('MatchMax',\%MatchMax);
if ($settings{Debug})
{
appendToSession('Debug_SDF',\%Checks,true);
}
writeSession();
}
if ($logfile)
{
open (my $rf,'>',$logfile) or swecDie(10,'Failed to open '.$logfile.' for writing: '.$!);
print {$rf} $rep;
if (@loggedMessages)
{
print {$rf} "Log messages:\n";
print {$rf} join("\n",@loggedMessages);
}
print {$rf} "\n\nDumps:\n";
print {$rf} 'Used UA: '. $BaseUA.$GiveMeUA ."\n";
print {$rf} "HasRun:\n".swecDumper(\%HasRun);
print {$rf} "\nErrorCount:\n".swecDumper(\%ErrorCount);
print {$rf} "\nPageCount:\n".swecDumper(\%PageCount);
print {$rf} "\nSeeds:\n".swecDumper(\@PageSeeds);
close($rf);
print "Log written to $logfile\n";
}
exit($returnVal);
}
# Purpose: Parse HTML entities, regardless of which parser is available
# Usage: my $parsed = htmlParseEntities($str);
sub htmlParseEntities
{
my $str = shift;
if ($settings{htmlInfo})
{
return decode_entities($str);
}
$str =~ s/&/&/gi;
return $str;
}
# Purpose: Get links from a string, regardless of which link extractor is in use
# Usage: my $links = getLinksFrom($string);
# Returns an array of hashrefs in the form { href => link };
sub getLinksFrom
{
my $data = shift;
if ($EX)
{
$EX->parse(\$data);
return $EX->links;
}
else
{
my @links;
$data =~ s/(\n|\r)/ /g;
my @all = split(/(<|>)/,$data);
foreach my $l (@all)
{
next if not $l =~ /^a\s/i;
if($l =~ s/.*href="([^"]+)".*/$1/i || $l =~ s/.*href='([^']+)'.*/$1/i)
{
push(@links,{ href => htmlParseEntities($l) });
}
}
return \@links;
}
}
# Purpose: Try using the lib supplied, returning 1 on success 0 on failure
# Usage: tryUse('Some::lib qw(something)');
sub tryUse
{
my $lib = shift;
my $check = $lib;
$check =~ s/\s+.+//;
if (!$settings{disabledLibs}->{$lib} && eval('use '.$lib.';1;'))
{
return 1;
}
return 0;
}
# Purpose: Initialize the link extractor and URI encoder
# Usage: initOptionalLibs();
sub initOptionalLibs
{
if(tryUse('HTML::LinkExtractor'))
{
$EX = HTML::LinkExtractor->new();
}
else
{
if ($settings{disabledLibs}->{'HTML::LinkExtractor'})
{
warn("Note: Use of HTML::LinkExtractor disabled\n");
}
if(tryUse('HTML::Entities qw(decode_entities)'))
{
$settings{htmlInfo} = true;
}
else
{
if ($settings{disabledLibs}->{'HTML::LinkExtractor'})
{
warn("Warning: Use of HTML::Entities disabled, will use (less reliable) alternate entity parsing\n");
}
else
{
warn("Warning: HTML::Entities missing, falling back to (less reliable) alternate entitiy parsing\n");
}
}
}