-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLW2.pm
6536 lines (5156 loc) · 194 KB
/
LW2.pm
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
# LW2 version 2.5.1
# LW2 Copyright (c) 2009, Jeff Forristal (wiretrip.net)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Note that this file has been updated as part of the Nikto project,
# and is technically a fork of LibWhisker 2.5.
=head1 NAME
LW2 - Perl HTTP library version 2.5
=head1 SYNOPSIS
use LW2;
require 'LW2.pm';
=head1 DESCRIPTION
Libwhisker is a Perl library useful for HTTP testing scripts. It
contains a pure-Perl reimplementation of functionality found in the C<LWP>,
C<URI>, C<Digest::MD5>, C<Digest::MD4>, C<Data::Dumper>, C<Authen::NTLM>,
C<HTML::Parser>, C<HTML::FormParser>, C<CGI::Upload>, C<MIME::Base64>,
and C<GetOpt::Std> modules.
Libwhisker is designed to be portable (a single perl file), fast (general
benchmarks show libwhisker is faster than LWP), and flexible (great care
was taken to ensure the library does exactly what you want to do, even
if it means breaking the protocol).
=head1 FUNCTIONS
The following are the functions contained in Libwhisker:
=over 4
=cut
package LW2;
$LW2::VERSION="2.5";
$PACKAGE='LW2';
# BEGIN is at the end of the file. Here come the functions.
########################################################################
#
=item B<init_ssl_engine>
Params: $lw_ssl_engine
Return: always returns undef
This function chooses the right SSL Engine and initializes SSL if needed.
This has been done because SSLeay seems to have memory leaks and there
was no other way to quickly change SSL Engine.
lw_ssl_engine can have these values:
auto = autodetection where it uses SSL first
(this is the default upon loading the module)
SSL = Net::SSL
SSLeay = Net::SSLeay
Precondition for the function is that if you choose a specific library
this library must be installed.
=cut
sub init_ssl_engine {
my ($lw_ssl_engine) = @_;
# if user-specified, undef initialization in case user's desired lib is not available
if ($lw_ssl_engine ne 'auto') {
$LW_SSL_LIB = 0;
$_SSL_LIBRARY = undef;
}
if ($lw_ssl_engine eq 'SSLeay'){
# use Net::SSLeay as your SSL Library
eval "use Net::SSLeay";
if ( !$@ ) {
$LW_SSL_LIB = 1;
$_SSL_LIBRARY = 'Net::SSLeay';
Net::SSLeay::load_error_strings();
Net::SSLeay::SSLeay_add_ssl_algorithms();
Net::SSLeay::randomize();
}
else { print "ERROR: $@\n"; exit; }
} elsif ($lw_ssl_engine eq 'SSL'){
# use Net:SSL
eval "use Net::SSL";
if ( !$@ ) {
$LW_SSL_LIB = 2;
$_SSL_LIBRARY = 'Net::SSL';
}
else { print "ERROR: $@\n"; exit; }
}
else {
# assuming autodetection
eval "use Net::SSL";
if ( !$@ ) {
$LW_SSL_LIB = 2;
$_SSL_LIBRARY = 'Net::SSL';
}
else {
eval "use Net::SSLeay";
if ( !$@ ) {
$LW_SSL_LIB = 1;
$_SSL_LIBRARY = 'Net::SSLeay';
Net::SSLeay::load_error_strings();
Net::SSLeay::SSLeay_add_ssl_algorithms();
Net::SSLeay::randomize();
}
}
}
return undef;
} #sub
########################################################################
# Module Initialization starts here
BEGIN {
package LW2;
$PACKAGE='LW2';
## LW module manager stuff ##
$LW_SSL_LIB = 0;
$LW_SSL_KEEPALIVE = 0;
$LW_NONBLOCK_CONNECT = 1;
$_SSL_LIBRARY = undef;
# check for Socket
eval "use Socket";
if ( $@ ) {
die('You have to install the module Socket');
}
# init SSL with autoconfig first. App can later override this
init_ssl_engine('auto');
if ( $^O !~ /Win32/ ) {
eval "use POSIX qw(:errno_h :fcntl_h)";
if ($@) { $LW_NONBLOCK_CONNECT = 0; }
}
else {
# taken from Winsock2.h
*EINPROGRESS = sub { 10036 };
*EWOULDBLOCK = sub { 10035 };
}
} # BEGIN
########################################################################
=item B<auth_brute_force>
Params: $auth_method, \%req, $user, \@passwords [, $domain, $fail_code ]
Return: $first_valid_password, undef if error/none found
Perform a HTTP authentication brute force against a server (host and URI
defined in %req). It will try every password in the password array for
the given user. The first password (in conjunction with the given user)
that doesn't return HTTP 401 is returned (and the brute force is stopped
at that point). You should retry the request with the given password and
double-check that you got a useful HTTP return code that indicates
successful authentication (200, 302), and not something a bit more
abnormal (407, 500, etc). $domain is optional, and is only used for NTLM
auth.
Note: set up any proxy settings and proxy auth in %req before calling
this function.
You can brute-force proxy authentication by setting up the target proxy
as proxy_host and proxy_port in %req, using an arbitrary host and uri
(preferably one that is reachable upon successful proxy authorization),
and setting the $fail_code to 407. The $auth_method passed to this
function should be a proxy-based one ('proxy-basic', 'proxy-ntlm', etc).
if your server returns something other than 401 upon auth failure, then
set $fail_code to whatever is returned (and it needs to be something
*different* than what is received on auth success, or this function
won't be able to tell the difference).
=cut
sub auth_brute_force {
my ( $auth_method, $hrin, $user, $pwordref, $dom, $fail_code ) = @_;
my ( $P, %hout );
$fail_code ||= 401;
return undef if ( !defined $auth_method || length($auth_method) == 0 );
return undef if ( !defined $user || length($user) == 0 );
return undef if ( !( defined $hrin && ref($hrin) ) );
return undef if ( !( defined $pwordref && ref($pwordref) ) );
map {
( $P = $_ ) =~ tr/\r\n//d;
auth_set( $auth_method, $hrin, $user, $P, $dom );
return undef if ( http_do_request( $hrin, \%hout ) );
return $P if ( $hout{whisker}->{code} != $fail_code );
} @$pwordref;
return undef;
}
########################################################################
=item B<auth_unset>
Params: \%req
Return: nothing (modifies %req)
Modifes %req to disable all authentication (regular and proxy).
Note: it only removes the values set by auth_set(). Manually-defined
[Proxy-]Authorization headers will also be deleted (but you shouldn't
be using the auth_* functions if you're manually handling your own auth...)
=cut
sub auth_unset {
my $href = shift;
return if ( !defined $href || !ref($href) );
delete $$href{Authorization};
delete $$href{'Proxy-Authorization'};
delete $$href{whisker}->{auth_callback};
delete $$href{whisker}->{auth_proxy_callback};
delete $$href{whisker}->{auth_data};
delete $$href{whisker}->{auth_proxy_data};
}
########################################################################
=item B<auth_set>
Params: $auth_method, \%req, $user, $password [, $domain]
Return: nothing (modifies %req)
Modifes %req to use the indicated authentication info.
Auth_method can be: 'basic', 'proxy-basic', 'ntlm', 'proxy-ntlm'.
Note: this function may not necessarily set any headers after being called.
Also, proxy-ntlm with SSL is not currently supported.
=cut
sub auth_set {
my ( $method, $href, $user, $pass, $domain ) = ( lc(shift), @_ );
return if ( !( defined $href && ref($href) ) );
return if ( !defined $user || !defined $pass );
if ( $method eq 'basic' ) {
$$href{'Authorization'} =
'Basic ' . encode_base64( $user . ':' . $pass, '' );
}
if ( $method eq 'proxy-basic' ) {
$$href{'Proxy-Authorization'} =
'Basic ' . encode_base64( $user . ':' . $pass, '' );
}
if ( $method eq 'ntlm' ) {
http_close($href);
$$href{whisker}->{auth_data} = ntlm_new( $user, $pass, $domain );
$$href{whisker}->{auth_callback} = \&_ntlm_auth_callback;
}
if ( $method eq 'proxy-ntlm' ) {
utils_croak('',"auth_set: proxy-ntlm auth w/ SSL not currently supported")
if ( $href->{whisker}->{ssl} > 0 );
http_close($href);
$$href{whisker}->{auth_proxy_data} = ntlm_new( $user, $pass, $domain );
$$href{whisker}->{auth_proxy_callback} = \&_ntlm_auth_proxy_callback;
}
}
########################################################################
=item B<cookie_new_jar>
Params: none
Return: $jar
Create a new cookie jar, for use with the other functions. Even though
the jar is technically just a hash, you should still use this function
in order to be future-compatible (should the jar format change).
=cut
sub cookie_new_jar {
return {};
}
########################################################################
=item B<cookie_read>
Params: $jar, \%response [, \%request, $reject ]
Return: $num_of_cookies_read
Read in cookies from an %response hash, and put them in $jar.
Notice: cookie_read uses internal magic done by http_do_request
in order to read cookies regardless of 'Set-Cookie[2]' header
appearance.
If the optional %request hash is supplied, then it will be used to
calculate default host and path values, in case the cookie doesn't
specify them explicitly. If $reject is set to 1, then the %request
hash values are used to calculate and reject cookies which are not
appropriate for the path and domains of the given request.
=cut
sub cookie_read {
my ( $count, $jarref, $hrs, $hrq, $rej ) = ( 0, @_ );
return 0 if ( !( defined $jarref && ref($jarref) ) );
return 0 if ( !( defined $hrs && ref($hrs) ) );
return 0
if (
!(
defined $$hrs{whisker}->{cookies}
&& ref( $$hrs{whisker}->{cookies} )
)
);
my @opt;
if(defined $hrq && ref($hrq)){
push @opt, $hrq->{whisker}->{host};
my $u = $hrq->{whisker}->{uri};
$u=~s#/.*?$##;
$u='/' if($u eq '');
push @opt, $u, $rej;
}
foreach ( @{ $hrs->{whisker}->{cookies} } ) {
cookie_parse( $jarref, $_ , @opt);
$count++;
}
return $count;
}
########################################################################
=item B<cookie_parse>
Params: $jar, $cookie [, $default_domain, $default_path, $reject ]
Return: nothing
Parses the cookie into the various parts and then sets the appropriate
values in the cookie $jar. If the cookie value is blank, it will delete
it from the $jar. See the 'docs/cookies.txt' document for a full
explanation of how Libwhisker parses cookies and what RFC aspects are
supported.
The optional $default_domain value is taken literally. Values with no
leading dot (e.g. 'www.host.com') are considered to be strict hostnames
and will only match the identical hostname. Values with leading dots (e.g.
'.host.com') are treated as sub-domain matches for a single domain level.
If the cookie does not indicate a domain, and a $default_domain is not
provided, then the cookie is considered to match all domains/hosts.
The optional $default_path is used when the cookie does not specify a path.
$default_path must be absolute (start with '/'), or it will be ignored. If
the cookie does not specify a path, and $default_path is not provided, then
the default value '/' will be used.
Set $reject to 1 if you wish to reject cookies based upon the provided
$default_domain and $default_path. Note that $default_domain and
$default_path must be specified for $reject to actually do something
meaningful.
=cut
sub cookie_parse {
my ( $jarref, $header ) = (shift, shift);
my ( $Dd, $Dp, $R ) = (shift, shift, shift||0);
return if ( !( defined $jarref && ref($jarref) ) );
return if ( !( defined $header && length($header) > 0 ) );
my @C = ( undef, undef, undef, undef, 0 );
$header =~ tr/\r\n//d;
my ($f,%seen,$n,$t) = (1);
while( length($header) ){
$header =~ s/^[ \t]+//;
last if(!($header =~ s/^([^ \t=;]+)//));
# LW2.5 change: cookie name is no longer lower-cased
# my $an = lc($1);
my $an = $1;
my $av = undef;
$header =~ s/^[ \t]+//;
if(substr($header,0,1) eq '='){
$header=~s/^=[ \t]*//;
if(substr($header,0,1) eq '"'){
my $p = index($header,'"',1);
last if($p == -1);
$av = substr($header,1,$p-1);
substr($header,0,$p+1)='';
} else {
$av = $1 if($header =~ s/^([^ \t;,]*)//);
}
} else {
my $p = index($header,';');
substr($header,0,$p)='';
}
$header =~ s/^.*?;//;
if($f){
return if(!defined $av);
($f,$n,$C[0])=(0,$an,$av);
} else {
$seen{$an}=$av if(!exists $seen{$an});
}
}
return if(!defined $n || $n eq '');
my $del = 0;
$del++ if($C[0] eq '');
$del++ if(defined $seen{'max-age'} && $seen{'max-age'} eq '0');
if($del){
delete $$jarref{$n} if exists $$jarref{$n};
return;
}
if(defined $seen{domain} && $seen{domain} ne ''){
$t = $seen{domain};
$t='.'.$t if(substr($t,0,1) ne '.' && !_is_ip_address($t));
} else {
$t=$Dd;
}
$t=~s/\.+$// if(defined $t);
$C[1]=$t;
if(defined $seen{path}){
$t = $seen{path};
} else {
$t=$Dp || '/';
}
$t=~s#/+$##;
$t='/' if(substr($t,0,1) ne '/');
$C[2]=$t;
$C[4]=1 if(exists $seen{secure});
return if($R && !_is_valid_cookie_match($C[1], $C[2], $Dd, $Dp));
$$jarref{$n} = \@C;
}
########################################################################
sub _is_ip_address {
my $n = shift;
return 1 if($n=~/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/);
return 0;
}
sub _is_valid_cookie_match {
my ($cd, $cp, $td, $tp) = @_;
return 0 if(index($tp,$cp)!=0);
if(substr($cd,0,1) eq '.'){
if( $td =~ /(.+)$cd$/ ){
return 1 if(index($1,'.') == -1);
}
return 0;
} else {
return 0 if($cd ne $td);
}
return 1;
}
########################################################################
=item B<cookie_write>
Params: $jar, \%request, $override
Return: nothing
Goes through the given $jar and sets the Cookie header in %req pending the
correct domain and path. If $override is true, then the secure, domain and
path restrictions of the cookies are ignored and all cookies are essentially
included.
Notice: cookie expiration is currently not implemented. URL restriction
comparision is also case-insensitive.
=cut
sub cookie_write {
my ( $jarref, $hin, $override ) = @_;
my ( $name, $out ) = ( '', '' );
return if ( !( defined $jarref && ref($jarref) ) );
return if ( !( defined $hin && ref($hin) ) );
$override = $override || 0;
$$hin{'whisker'}->{'ssl'} = $$hin{'whisker'}->{'ssl'} || 0;
foreach $name ( keys %$jarref ) {
next if ( $name eq '' );
if($override){
$out .= "$name=$$jarref{$name}->[0];";
next;
}
next if ( $$hin{'whisker'}->{'ssl'} == 0 && $$jarref{$name}->[4] > 0 );
if ( $$hin{'whisker'}->{'host'} =~ /$$jarref{$name}->[1]$/i
&& $$hin{'whisker'}->{'uri'} =~ /^$$jarref{$name}->[2])/ )
{
$out .= "$name=$$jarref{$name}->[0];";
}
}
if ( $out ne '' ) { $$hin{'Cookie'} = $out; }
}
########################################################################
=item B<cookie_get>
Params: $jar, $name
Return: @elements
Fetch the named cookie from the $jar, and return the components. The
returned items will be an array in the following order:
value, domain, path, expire, secure
value = cookie value, should always be non-empty string
domain = domain root for cookie, can be undefined
path = URL path for cookie, should always be a non-empty string
expire = undefined (depreciated, but exists for backwards-compatibility)
secure = whether or not the cookie is limited to HTTPs; value is 0 or 1
=cut
sub cookie_get {
my ( $jarref, $name ) = @_;
return undef if ( !( defined $jarref && ref($jarref) ) );
if ( defined $$jarref{$name} ) {
return @{ $$jarref{$name} };
}
return undef;
}
########################################################################
=item B<cookie_get_names>
Params: $jar
Return: @names
Fetch all the cookie names from the jar, which then let you cooke_get()
them individually.
=cut
sub cookie_get_names {
my ( $jarref, $name ) = @_;
return undef if ( !( defined $jarref && ref($jarref) ) );
return keys %$jarref;
}
########################################################################
=item B<cookie_get_valid_names>
Params: $jar, $domain, $url, $ssl
Return: @names
Fetch all the cookie names from the jar which are valid for the given
$domain, $url, and $ssl values. $domain should be string scalar of the
target host domain ('www.example.com', etc.). $url should be the absolute
URL for the page ('/index.html', '/cgi-bin/foo.cgi', etc.). $ssl should be
0 for non-secure cookies, or 1 for all (secure and normal) cookies. The
return value is an array of names compatible with cookie_get().
=cut
sub cookie_get_valid_names {
my ( $jarref, $domain, $url, $ssl ) = @_;
return () if ( !( defined $jarref && ref($jarref) ) );
return () if ( !defined $domain || $domain eq '' );
return () if ( !defined $url || $url eq '' );
$ssl ||= 0;
my (@r, $name);
foreach $name ( keys %$jarref ) {
next if ( $name eq '' );
next if ( $$jarref{$name}->[4] > 0 && $ssl == 0 );
if ( $domain =~ /$$jarref{$name}->[1]$/i
&& $url =~ /^$$jarref{$name}->[2])/i ) {
push @r, $name;
}
}
return @r;
}
########################################################################
=item B<cookie_set>
Params: $jar, $name, $value, $domain, $path, $expire, $secure
Return: nothing
Set the named cookie with the provided values into the %jar. $name is
required to be a non-empty string. $value is required, and will delete
the named cookie from the $jar if it is an empty string. $domain and
$path can be strings or undefined. $expire is ignored (but exists
for backwards-compatibility). $secure should be the numeric value of
0 or 1.
=cut
sub cookie_set {
my ( $jarref, $name, $value, $domain, $path, $expire, $secure ) = @_;
my @construct;
return if ( !( defined $jarref && ref($jarref) ) );
return if ( $name eq '' );
if ( !defined $value || $value eq '' ) {
delete $$jarref{$name};
return;
}
$path = $path || '/';
$secure = $secure || 0;
@construct = ( $value, $domain, $path, undef, $secure );
$$jarref{$name} = \@construct;
}
########################################################################
#####################################################
# cluster global variables
%_crawl_config = (
'save_cookies' => 0,
'reuse_cookies' => 1,
'save_offsites' => 0,
'save_non_http' => 0,
'follow_moves' => 1,
'url_limit' => 1000,
'use_params' => 0,
'params_double_record' => 0,
'skip_ext' => {
gif => 1,
jpg => 1,
png => 1,
gz => 1,
swf => 1,
pdf => 1,
zip => 1,
wav => 1,
mp3 => 1,
asf => 1,
tgz => 1
},
'save_skipped' => 0,
'save_referrers' => 0,
'use_referrers' => 1,
'do_head' => 0,
'callback' => 0,
'netloc_bug' => 1,
'normalize_uri' => 1,
'source_callback' => 0
);
%_crawl_linktags = (
'a' => 'href',
'applet' => [qw(codebase archive code)],
'area' => 'href',
'base' => 'href',
'bgsound' => 'src',
'blockquote' => 'cite',
'body' => 'background',
'del' => 'cite',
'embed' => [qw(src pluginspage)],
'form' => 'action',
'frame' => [qw(src longdesc)],
'iframe' => [qw(src longdesc)],
'ilayer' => 'background',
'img' => [qw(src lowsrc longdesc usemap)],
'input' => [qw(src usemap)],
'ins' => 'cite',
'isindex' => 'action',
'head' => 'profile',
'layer' => [qw(background src)],
'link' => 'href',
# 'meta' => 'http-equiv',
'object' => [qw(codebase data archive usemap)],
'q' => 'cite',
'script' => 'src',
'table' => 'background',
'td' => 'background',
'th' => 'background',
'xmp' => 'href',
);
#####################################################
=item B<crawl_new>
Params: $START, $MAX_DEPTH, \%request_hash [, \%tracking_hash ]
Return: $crawl_object
The crawl_new() functions initializes a crawl object (hash) to the default
values, and then returns it for later use by crawl(). $START is the starting
URL (in the form of 'http://www.host.com/url'), and MAX_DEPTH is the maximum
number of levels to crawl (the START URL counts as 1, so a value of 2 will
crawl the START URL and all URLs found on that page). The request_hash
is a standard initialized request hash to be used for requests; you should
set any authentication information or headers in this hash in order for
the crawler to use them. The optional tracking_hash lets you supply a
hash for use in tracking URL results (otherwise crawl_new() will allocate
a new anon hash).
=cut
sub crawl_new {
my ( $start, $depth, $reqref, $trackref ) = @_;
my %X;
return undef if ( !defined $start || !defined $depth );
return undef if ( !defined $reqref || !ref($reqref) );
$trackref = {} if ( !defined $trackref || !ref($trackref) );
$X{track} = $trackref;
$X{request} = $reqref;
$X{depth} = $depth || 2;
$X{start} = $start;
$X{magic} = 7340;
$X{reset} = sub {
$X{errors} = []; # all errors encountered
$X{urls} = []; # temp; used to hold all URLs on page
$X{server_tags} = {}; # all server tags found
$X{referrers} = {}; # who refers to what URLs
$X{offsites} = {}; # all URLs that point offsite
$X{response} = {}; # temp; the response hash
$X{non_http} = {}; # all non_http URLs found
$X{cookies} = {}; # all cookies found
$X{forms} = {}; # all forms found
$X{jar} = {}; # temp; cookie jar
$X{url_queue} = []; # temp; URLs to still fetch
$X{config} = {};
%{ $X{config} } = %_crawl_config;
%{ $X{track} } = ();
$X{parsed_page_count} = 0;
};
$X{crawl} = sub { crawl( \%X, @_ ) };
$X{reset}->();
return \%X;
}
#####################################################
=item B<crawl>
Params: $crawl_object [, $START, $MAX_DEPTH ]
Return: $count [ undef on error ]
The heart of the crawl package. Will perform an HTTP crawl on the
specified HOST, starting at START URI, proceeding up to MAX_DEPTH.
Crawl_object needs to be the variable returned by crawl_new(). You can
also indirectly call crawl() via the crawl_object itself:
$crawl_object->{crawl}->($START,$MAX_DEPTH)
Returns the number of URLs actually crawled (not including those skipped).
=cut
{ # START OF CRAWL CONTAINER
sub crawl {
my ( $C, $START, $MAX_DEPTH ) = @_;
return undef if ( !defined $C || !ref($C) || $C->{magic} != 7340 );
# shortcuts, to reduce dereferences and typing
my $CONFIG = $C->{config};
my $TRACK = $C->{track};
my $URLS = $C->{urls};
my $RESP = $C->{response};
my $REQ = $C->{request};
my $Q = $C->{url_queue};
$START ||= $C->{start};
$C->{depth} = $MAX_DEPTH || $C->{depth};
my ( $COUNT, $T, @ST ) = ( 0, '' );
# ST[] = [ 0.HOST, 1.PORT, 2.URL, 3.DEPTH, 4.CWD, 5.REF ]
my @v = uri_split($START);
my $error = undef;
$error = 'Start protocol not http or https'
if ( $v[1] ne 'http' && $v[1] ne 'https' );
$error = 'Bad start host' if ( !defined $v[2] || $v[2] eq '' );
push( @{ $C->{errors} }, $error ) && return undef if ( defined $error );
@ST = ( $v[2], $v[3], $v[0], 1, '', '' );
$REQ->{whisker}->{ssl} = 1 if ( $v[1] eq 'https' );
$REQ->{whisker}->{host} = $ST[0];
$REQ->{whisker}->{port} = $ST[1];
$REQ->{whisker}->{lowercase_incoming_headers} = 1;
$REQ->{whisker}->{ignore_duplicate_headers} = 0;
delete $REQ->{whisker}->{parameters};
http_fixup_request($REQ);
push @$Q, \@ST;
while (@$Q) {
@ST = @{ shift @$Q };
next if ( defined $TRACK->{ $ST[2] } && $TRACK->{ $ST[2] } ne '?' );
if ( $ST[3] > $C->{depth} ) {
$TRACK->{ $ST[2] } = '?' if ( $CONFIG->{save_skipped} > 0 );
next;
}
$ST[4] = uri_get_dir( $ST[2] );
$REQ->{whisker}->{uri} = $ST[2];
if ( $ST[5] ne '' && $CONFIG->{use_referrers} > 0 ) {
$REQ->{Referrer} = $ST[5];
}
my $result = _crawl_do_request( $REQ, $RESP, $C );
if ( $result == 1 || $result == 2 ) {
push @{ $C->{errors} }, "$ST[2]: $RESP->{whisker}->{error}";
next;
}
$COUNT++;
$TRACK->{ $ST[2] } = $RESP->{whisker}->{code}
if ( $result == 0 || $result == 4 );
$TRACK->{ $ST[2] } = '?'
if ( ( $result == 3 || $result == 5 )
&& $CONFIG->{save_skipped} > 0 );
if ( defined $RESP->{server} && !ref( $RESP->{server} ) ) {
$C->{server_tags}->{ $RESP->{server} }++;
}
if ( defined $RESP->{'set-cookie'} ) {
if ( $CONFIG->{save_cookies} > 0 ) {
if ( ref( $RESP->{'set-cookie'} ) ) {
$C->{cookies}->{$_}++
foreach ( @{ $RESP->{'set-cookie'} } );
}
else {
$C->{cookies}->{ $RESP->{'set-cookie'} }++;
}
}
cookie_read( $C->{jar}, $RESP )
if ( $CONFIG->{reuse_cookies} > 0 );
}
next if ( $result == 4 || $result == 5 );
next if ( scalar @$Q > $CONFIG->{url_limit} );
if ( $result == 0 ) { # page should be parsed
if ( $CONFIG->{source_callback} != 0
&& ref( $CONFIG->{source_callback} ) eq 'CODE' )
{
&{ $CONFIG->{source_callback} }($C);
}
html_find_tags( \$RESP->{whisker}->{data},
\&_crawl_extract_links_test, 0, $C, \%_crawl_linktags );
$C->{parsed_page_count}++;
}
push @$URLS, $RESP->{location} if ( $result == 3 );
foreach $T (@$URLS) {
$T =~ tr/\0\r\n//d;
next if ( length($T) == 0 );
next if ( $T =~ /^#/i ); # fragment
push @{ $C->{referrers}->{$T} }, $ST[2]
if ( $CONFIG->{save_referrers} > 0 );
if ( $T =~ /^([a-zA-Z0-9]*):/
&& lc($1) ne 'http'
&& lc($1) ne 'https' )
{
push @{ $C->{non_http}->{$T} }, $ST[2]
if ( $CONFIG->{save_non_http} > 0 );
next;
}
if ( substr( $T, 0, 2 ) eq '//' && $CONFIG->{netloc_bug} > 0 ) {
if ( $REQ->{whisker}->{ssl} > 0 ) { $T = 'https:' . $T; }
else { $T = 'http:' . $T; }
}
if ( $CONFIG->{callback} != 0 ) {
next if &{ $CONFIG->{callback} }( $T, $C );
}
$T = uri_absolute( $T, $ST[4], $CONFIG->{normalize_uri} );
# (uri,protocol,host,port,params,frag,user,pass)
@v = uri_split($T);
# make sure URL is on same host and port
if ( ( defined $v[2] && $v[2] ne $ST[0] )
|| ( $v[3] > 0 && $v[3] != $ST[1] ) )
{
$C->{offsites}->{ uri_join(@v) }++
if ( $CONFIG->{save_offsites} > 0 );
next;
}
if ( $v[0] =~ /\.([a-z0-9]+)$/i ) {
if ( defined $CONFIG->{skip_ext}->{ lc($1) } ) {
$TRACK->{ $v[0] } = '?'
if ( $CONFIG->{save_skipped} > 0 );
next;
}
}
if ( defined $v[4] && $CONFIG->{use_params} > 0 ) {
$TRACK->{ $v[0] } = '?'
if ( $CONFIG->{params_double_record} > 0
&& !defined $TRACK->{ $v[0] } );
$v[0] = $v[0] . '?' . $v[4];
}
next
if ( defined $TRACK->{ $v[0] } )
; # we've processed this already
# ST[] = [ 0.HOST, 1.PORT, 2.URL, 3.DEPTH, 4.CWD, 5.REF ]
push @$Q, [ $ST[0], $ST[1], $v[0], $ST[3] + 1, '', $ST[2] ];
} # foreach
@$URLS = (); # reset for next round