-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPcurl.pm
executable file
·4270 lines (3742 loc) · 153 KB
/
Pcurl.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
#!/usr/bin/env perl
# pCurl - a cURL-like implemented in Perl
# with built-in json and xml parsers
# and custom features like STOMP message sending
#
# (c) 2019, 2020, 2022 - Sébastien Kirche
package Pcurl;
use Exporter qw/import/;
@EXPORT_OK = qw/hexdump parse_uri process_http/;
use warnings;
use strict;
use feature 'say';
use feature 'state';
use utf8;
use open ':std', ':encoding(UTF-8)';
use version;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 2;
use Getopt::Long qw(:config no_ignore_case bundling auto_version); # debug
use IO::Select;
use IO::Socket::INET;
use IPC::Open3;
use MIME::Base64 'encode_base64';
use Pod::Usage;
use Socket qw( IPPROTO_TCP TCP_NODELAY );
use Symbol qw( gensym );
use Time::HiRes qw( sleep );
use Time::Local;
# use Carp::Always;
our $VERSION = '0.9.10';
$|++; # auto flush messages
# vars declared before signal handlers because we show a message using them
my %args;
my %processed_request; # Requests done, for not doing again
# -------- Signal handlers -------------------------
BEGIN{ # automagic breakpoint for warnings when script is run by perl -d
$SIG{__WARN__} = sub {
my $msg = shift;
chomp $msg;
say STDERR "Warning: '$msg'";
no warnings 'once'; # avoid « Warning: 'Name "DB::single" used only once: possible typo »
$DB::single = 1; # we stop execution if a warning occurs during run
};
}
sub tell_recursive {
if ($args{recursive}){
say STDERR sprintf("\n%d link%s processed. Enter Ctrl-C twice to stop.", scalar(keys %processed_request), (scalar keys %processed_request > 1 ? 's' : '')) if $args{recursive};
}
}
$SIG{INT} = sub {
state $last_time = 0;
my $now = time;
if ($now - $last_time <= 1){ # Ctrl-C x2 within 1 second
say STDERR "SIGINT / CTRL-C received (Interrupt from keyboard). Leaving.";
exit;
}
tell_recursive();
$last_time = $now;
};
$SIG{QUIT} = sub {
tell_recursive();
say STDERR "SIGQUIT / CTRL-\\ received (Quit from keyboard). Leaving.";
exit };
$SIG{ABRT} = sub { say STDERR "SIGABRT received (Probable abnormal process termination requested by a library). Leaving."; exit };
$SIG{TERM} = sub { say STDERR "SIGTERM received - External termination request. Leaving."; exit };
sub suspend_trap {
say STDERR "SIGTSTP / CTRL-Z received. Suspending...";
$SIG{TSTP} = 'DEFAULT';
kill 'TSTP', -(getpgrp $$);
}
$SIG{TSTP} = \&suspend_trap;
$SIG{CONT} = sub { $SIG{TSTP} = \&suspend_trap; say STDERR "SIGCONT received - continue after suspension." };
# the exit_hook is a hack to not terminate the program on exit() when it is called as package
# because the code has been written initially as a program and can exit with a set of return codes
our $do_not_terminate_on_exit = 0;
BEGIN {
sub exit_hook(;$) {
no warnings qw( exiting );
my $val = $_[0] // 0;
# say "exit($_[0]) called";
my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash) = caller(0);
say "exit($val) called from $filename:$line";
# my $w = (caller(1))[3];
# say "exit($_[0]) called from $w";
last EXIT_OVERRIDE if $do_not_terminate_on_exit;
CORE::exit($_[0] // 0);
};
*CORE::GLOBAL::exit = *exit_hook;
}
# --------------------------------------------------
my $max_redirs = 50; # default value for maximum redirects to follow
my $max_levels = 5; # default max recursion level
my $def_max_wait = 10; # default value for response timeout
my %defports = ( http => 80, # default ports
https => 443,
stomp => 61613,
dict => 2628
);
my $default_page = 'index.html'; # default name for directory index
# when writing output in a file, holder of the initial STDOUT
# my $STDOLD;
my @output_stack = ( *STDOUT );
# my $current_output = $output_stack[0];
# my $is_out_redirected = 0;
my ($http_vers, $tunnel_pid, $auto_ref, $use_cookies, $cookies, $process_action);
my %rel_url_to_local_dir;
my $index_name;
my $acceptrx;
my $rejectrx;
my $prefix = '';
my %broken_url; # URLs that are not valid
my %failed_url; # URLs that resulted in failure
my %discovered_url;
my $asset_counter = 0;
%args = ( 'tcp-nodelay' => 1,
'data' => [],
'data-binary' => [],
'data-raw' => [],
'data-urlencode' => [],
header => [],
'json-pp-indent' => 2,
'user-agent' => "pCurl/$VERSION",
'xml-pp-indent' => 2,
'xml-root-element' => 'root'
);
$http_vers = '1.1'; # default version we want for http
__PACKAGE__->cli( @ARGV ) if !caller() || caller() eq 'PAR'; # handles package called as a script
sub cli {
my @getopt_defs = (
'accept=s',
'action=s',
'action-nullable-values',
'action-res-delimiter=s',
'basic|user=s',
'content=s',
'cookie|b=s',
'cookie-jar|c=s',
'data|data-ascii|d=s@',
'data-binary=s@',
'data-raw=s',
'data-urlencode=s@',
'debug',
'debug-urls',
'debug-json=s',
'debug-json-export',
'fail|f',
'fail-with-body',
'get-curl-command',
'header|H=s@',
'head|I',
'help|h|?',
'include-response|include|i',
'include-request',
'insecure|k',
# 'ipv4|4', # TODO
# 'ipv6|6', # TODO
'json=s',
'json-pp',
'json-pp-indent=i',
'json-stringify-null',
'junk-session-cookies',
'location|follow|L',
'man',
'max-wait=i',
'max-redirs=i',
'noproxy=s',
'output|o=s',
'octet-stream',
'parse-only', # just show how we parse the URL
'port|p=i',
'progression|progress',
'proxy-user|U=s',
'proxy10=s',
'proxy|x=s',
'random-wait',
'remote-header-name|J',
'remote-name|O',
'remote-time|R',
'referer|e=s',
'request|X=s',
'silent|s',
'ssl-ca|cacert=s',
'ssl-cert|cert=s',
'ssl-key|key=s',
'sslv3|3',
# 'stompdest=s',
'stompmsg=s',
'stompread',
'tcp-nodelay!', # negatable: --notcp-nodelay
'tlsv1_0|tlsv1|1',
'tlsv1_1',
'tlsv1_2',
'tlsv1_3',
'upload-file|T=s',
'url=s',
'user-agent|A=s',
'verbose|v',
'version|V', # comment this out to have the built-in version handler that shows program/Getopt/Perl versions
'wait|w=i',
# 'xml-decl=s',
'xml-pp',
'xml-pp-indent=i',
'xml-root-element=s',
# recursive options -------------------------------
'accept-list=s', # a coma-separated list
'accept-regex=s',
'cut-dirs=i',
'directory-prefix|P=s',
'default-page=s',
'level|l=i',
'no-host-directories',
'no-parent|np',
'page-requisites',
'recursive|r',
'recursive-flat|F',
'relative',
'reject-list=s', # a coma-separated list
'reject-regex=s',
'span-hosts',
'summary',
);
if ($Getopt::Long::VERSION >= '2.39') { # Getopt::Long does not support alias with dots before 2.39
push (@getopt_defs,
'http09|http0.9',
'http10|0|http1.0',
'http11|http1.1');
} else {
push (@getopt_defs,
'http09',
'http10',
'http11');
}
GetOptions(\%args, @getopt_defs ) or pod2usage(-exitval => 2, -verbose => 0);
pod2usage(-exitval => 0, -verbose => 1) if $args{help};
pod2usage(-exitval => 0, -verbose => 2) if $args{man};
if ($args{action} && $args{action} eq 'help:'){
parse_process_action($args{action}); # will exit
}
if ($args{version}){
say "pcurl $VERSION";
exit 0;
}
if ($args{'debug-json'}){
say STDERR "Testing JSON parser...";
if ($args{'debug-json'} eq '-'){
my @lines = <STDIN>;
$args{'debug-json'} = join '', @lines;
} elsif (-r $args{'debug-json'}){
open (my $fh, '<', $args{'debug-json'}) or die "Cannot open $args{'debug-json'}: $!";
local $/;
$args{'debug-json'} = <$fh>;
close $fh;
}
say STDERR "Reading done. Parsing...";
my $obj = from_json($args{'debug-json'});
say STDERR "Parsing done. Dumping...";
if ($args{'debug-json-export'}){
say to_json($obj);
} else {
say Data::Dumper->Dump([$obj],[ 'json' ]);
}
exit 0;
}
# Referer provided, or auto-referer?
# auto-referer is: take the url of the previous url as referer when following redirects
if ($args{referer} && $args{referer} =~ /([^;]*)?;auto/){
$auto_ref = 1;
$args{referer} = $1;
}
# Cookies
if ($args{cookie} || $args{'cookie-jar'}){
$use_cookies = 1;
if ($args{cookie}){
# parameter is either a file name or a literal cookie
if (-f $args{cookie}){
$cookies = load_cookie_jar($args{cookie});
say STDERR "Cookies from jar:", Dumper $cookies if $args{debug};
if ($args{'junk-session-cookies'}){
# keep cookies with expiration (if not it's a session cookie)
$cookies = [ grep { $_->{expires} } @$cookies ];
}
} else {
$cookies = load_commandline_cookies($args{cookie});
say STDERR "Cookies from command-line:", Dumper $cookies if $args{debug};
}
}
# keep non-expired cookies
my $now = time;
$cookies = [ grep { !$_->{expires} || ($_->{expires} >= $now) } @$cookies ];
say STDERR "Cookies from jar after purge and expiration:", Dumper $cookies if $args{debug};
}
# shortcut to -H 'Accept: mime'
if ($args{accept}){
push @{$args{header}}, "Accept: $args{accept}";
}
# shortcut for json payloads
if ($args{json}){
push @{$args{header}}, "Content-Type: application/json";
push @{$args{header}}, "Accept: application/json";
push @{$args{data}}, $args{json};
}
# shortcut for Content-Type: octet-stream
if ($args{'octet-stream'}){
$args{content} = 'octet-stream' unless $args{content};
}
my $cli_url = $args{url} || $ARGV[0];
unless ($cli_url){
say STDERR "No url provided...";
pod2usage(-exitval => 1);
}
unless ($cli_url =~ m{^\w+://}){
# mimics curl: no scheme means http
if ($cli_url =~ m{/$}){
$cli_url = "http://$cli_url";
} else {
$cli_url = "http://$cli_url/";
}
}
$acceptrx = $args{'accept-regex'};
$rejectrx = $args{'reject-regex'};
$acceptrx = '(' . join ('|', split(/,/, $args{accept})) . ')$' if $args{accept};
$rejectrx = '(' . join ('|', split(/,/, $args{reject})) . ')$' if $args{reject};
$index_name = $args{'default-page'} || $default_page;
if ($args{'directory-prefix'}){
$prefix = $args{'directory-prefix'};
$prefix .= '/' if $prefix !~ m{/$};
}
if ($args{'parse-only'}){
my $uri = validate_uri($cli_url);
if ($uri){
dump_url($uri);
exit 0;
} else {
exit 1;
}
}
# try to get the vanilla curl command equivalent
if ($args{'get-curl-command'}){
my @cli = ();
# filter out this argument
delete @args{qw( get-curl-command json-pp-indent xml-pp-indent xml-root-element)}; # pcurl specific commands
unshift @cli, 'curl';
if (my $r = delete $args{'request'}){
push @cli, "-X '$r'";
}
# headers lines
push @cli, map { "-H '$_'" } @{$args{header}};
delete $args{header};
if (my $a = delete $args{'user-agent'}){
push @cli, "--user-agent '$a'";
}
if (my $i = delete $args{'include-response'}){
push @cli, "--include";
}
if (my $c = delete $args{content}){
push @cli, "-H 'Content-Type: $c'";
}
my $d; # holder of a command-line argument or set of argiments (eg. dataxx are arrays)
my $v; # one parameter value
if ($d = delete $args{data}){
for $v (@$d){
push @cli, "--data '$v'" if $v;
}
}
if ($d = delete $args{'data-binary'}){
for $v (@$d){
push @cli, "--data-binary '$v'" if $v;
}
}
if ($d = delete $args{'data-raw'}){
for $v (@$d){
push @cli, "--data-raw '$v'" if $v;
}
}
if ($d = delete $args{'data-urlencode'}){
for $v (@$d){
push @cli, "--data-urlencode '$v'" if $v;
}
}
if (my $i = delete $args{'tcp-nodelay'}){
push @cli, "--tcp-nodelay";
}
push @cli, "'$cli_url'";
say join ' ', @cli;
if (%args){ # remaining args?
print "Unexported:";
say Dumper \%args;
}
exit 0;
}
process_loop([$cli_url], $args{level} // $max_levels);
say STDERR sprintf("* %d link%s processed", scalar(keys %processed_request), (scalar keys %processed_request > 1 ? 's' : '')) if $args{recursive} && ($args{summary} || $args{verbose} || $args{debug});
if ($args{summary}){
for my $r (sort keys %processed_request){
if ($processed_request{$r} > 1){
say STDERR sprintf("%s x %d", $r, $processed_request{$r});
} else {
say STDERR $r;
}
}
say STDERR sprintf("* %d Broken URLS:", scalar keys %broken_url) if keys %broken_url;
say STDERR $_ for sort keys %broken_url;
say STDERR sprintf("* %d Failed URLS (can be due to dumb url detection):", scalar keys %failed_url) if keys %failed_url;
say STDERR "$_ -> $failed_url{$_}" for sort keys %failed_url;
}
}
# ------- End of main prog ---------------------------------------------------------------
# TODO this need a refactor to pass arguments to process_http
sub simulate_cli_settings {
my %params = @_;
%args = (%args, %params);
}
sub process_loop {
my ($request_list, $level) = @_;
my @discovered_at_this_level;
say STDERR "List of urls for this round:\n" . join("\n", @$request_list) if $args{recursive} && ($args{verbose} || $args{debug});
REQUEST:
while (@$request_list){
my $req = shift @$request_list;
my $url = validate_uri($req);
unless ($url){
$broken_url{$req}++;
next REQUEST if $args{recursive}; # a broken url is not fatal in recursive mode
exit 1;
}
# complete some default values in case of relative link
$url = complete_url_default_values($url);
my $ustr = sprintf("%s://%s%s%s%s",
$url->{scheme},
auth_string($url),
$url->{host} || '',
defined $url->{port} ? sprintf(':%d', $url->{port}) : '',
canonicalize($url->{path}));
$asset_counter++;
if ($url->{scheme} =~ /^http/){
# HTTP or HTTPS
# version
if ($args{http09}){
$http_vers = '0.9';
} elsif ($args{http10}){
$http_vers = '1.0';
} elsif ($args{http11}){
$http_vers = '1.1';
} else {
$http_vers = '1.1'; # default HTTP version when not specified
}
if ($args{request}){
if ($args{request} =~ /^(GET|HEAD|POST|PUT|TRACE|OPTIONS|DELETE)$/i){
$args{request} = uc $args{request};
if ($args{request} ne 'GET' and HTTP09()){
say STDERR "HTTP/0.9 only supports GET method.\n" ;
exit 2;
}
} else {
# Nothing, one can have a custom HTTP method
}
}
my $method;
if (@{$args{data}} || @{$args{'data-urlencode'}} || @{$args{'data-binary'}} || @{$args{'data-raw'}}){
$method = $args{request} || 'POST';
} elsif ($args{'upload-file'}){
$method = $args{request} || 'PUT';
} else {
$method = $args{head} ? 'HEAD' : $args{request} || 'GET';
}
#$url->{path} = '*' if $method eq 'OPTIONS';
# say STDERR $url->{url} if $args{progression} || $args{verbose} || $args{debug};
unless (exists $processed_request{$req}){
# lazy downloader: do it only once
my $r = process_http(method => $method,
url => $url,
discovered => ($level ||
(defined $args{level} && $args{level} == 0)) ? \@discovered_at_this_level : undef
);
# response might be undef after timeout
$failed_url{$req} = $r->{status}{code} if defined $r->{status} && $r->{status}{code} >= 400 && $r->{status}{code} <= 599;
say STDERR sprintf("%s -> %d / %s",
$url->{url},
$r->{status}{code},
humanize_bytes($r->{body_byte_len})
) if $r->{body_byte_len} && ($args{progression} || $args{verbose} || $args{debug});
}
$processed_request{$req}++;
} elsif ($url->{scheme} =~ /^stomp(?:\+ssl)?$/){
unless ($url->{path} && ($args{stompmsg} || $args{stompread})){
say STDERR "Message sending with --stompmsg <message> or reading with --stompread is supported for now.";
exit 3;
}
process_stomp($url);
} elsif ($url->{scheme} eq 'file'){
unless ( ! defined $url->{host}
|| lc($url->{host}) eq 'localhost'
|| $url->{host} eq '127.0.0.1'){
say STDERR "* Invalid file://hostname/, expected localhost or 127.0.0.1 or none";
exit 4;
}
process_file($url, \@discovered_at_this_level);
} else {
say STDERR "Unknown scheme $url->{scheme}";
exit 14;
}
}
# if we need to process a next level of links in recursive crawler mode
# call us recursively TODO: maybe we could just push in $request_list and return to loop
# instead of recurse using a doouble while
# FIXME: $process_action has been changed by side-effect of process_http()
if (($args{recursive} || $process_action && index($process_action->{what}, 'getlinked')==0)
&& @discovered_at_this_level
&& (
$level > 0
|| (defined $args{level} && $args{level} == 0)
)
){
say STDERR "* processing next level" if $args{verbose} || $args{debug};
my $next_level;
if (defined $args{level} && $args{level} > 0){
$next_level = $level - 1;
} else {
$next_level = 1;
}
process_loop(\@discovered_at_this_level, $next_level);
}
}
sub prefix_print {
my ($fd, $prefix, $text) = @_;
foreach my $line (split /\n/, $text){
print $fd $prefix . $line . "\n";
}
}
sub current_output {
# my $line = [caller(0)]->[2];
# my $sub = [caller(1)]->[3];
# say STDERR "DBG: " . scalar @output_stack . " from $sub at $line";
return $output_stack[$#output_stack];
}
# redirect STDOUT to a file
# unless the out name is '-' to allow binary output to STDOUT
sub redirect_output_to_file {
my $out_name = shift;
# say STDERR "redirect -> $out_name";
if ($out_name && $out_name ne '-'){
# open $STDOLD, '>&', STDOUT;
my $new_fd = gensym();
open $new_fd, '>', $out_name or die "Cannot open '$out_name' for output.";
push @output_stack, $new_fd;
# my $line = [caller(0)]->[2];
# my $sub = [caller(1)]->[3];
# say "DBG: redirect_output_to_file called from $sub at $line";
# say STDERR "DBG: output_stack++ (" . $out_name . ") " . join(' ', @output_stack);
# binmode(STDOUT, ":raw");
# later, to restore STDOUT:
# open (STDOUT, '>&', $STDOLD);
# $is_out_redirected = 1;
# say STDERR "output is " . current_output;
}
}
# close out file and restore STDOUT
sub restore_output {
# my $out_name = $args{output};
# if ($is_out_redirected && (defined fileno($current_output) && fileno($current_output) != fileno(STDOUT))){
if (scalar @output_stack > 1){
close current_output();
# open (STDOUT, '>&', $STDOLD);
# $current_output = *STDOUT;
# $is_out_redirected = 0;
pop @output_stack;
# say STDERR "DBG: output_stack-- " . join(' ', @output_stack);
# say STDERR "restore_output to " . current_output;
}
}
# parse uri and print message if unsuccessful
sub validate_uri {
my $uri = shift;
my $parsed = parse_uri($uri);
unless ($parsed){
say STDERR "It's strange to me that `$uri` does not look like a valid URI...";
}
return $parsed;
}
# perform an HTTP[S] request / response
sub process_http {
my %params = @_;
my $method = $params{method};
my $url_final = $params{url};
my $discovered_links = $params{discovered};
my ($IN, $OUT, $ERR, $host, $port, $resp, $following, $error_code);
$max_redirs = $args{'max-redirs'} if defined $args{'max-redirs'};
my $redirs = $max_redirs; # redirs is a countdown of remaining allowed redirections
# Action is either a specific value to extract from the result (header, json field)
# an can be more sophisticated actions
if ($args{action}){
# FIXME: bad, bad, bad: should not use that global var anymore
$process_action = parse_process_action($args{action});
$process_action->{done} = undef;
}
my $fname;
my $out_file;
my $next_url;
my $no_follow_after_body = 0; # flag if we want to break the follow loop
REDIRECT:
# we can loop in case of 3xx redirect
do {
if ($args{wait}){
my $delay = $args{wait};
if ($args{'random-wait'}){
my $f = sprintf("%.1f", (rand(1) + .5)); # factor is 0.5 .. 1.5
$delay *= $f;
}
sleep($delay);
}
say STDERR "* Processing url $url_final->{url}" if $args{verbose} || $args{debug};
$next_url = '';
# set the filename for output when redirecting or using url name
if ($args{output}){
$fname = $args{output};
} elsif ($args{'remote-name'} && !$args{'remote-header-name'}){
if ($rel_url_to_local_dir{$url_final->{url}}){
# if this is a file from crawler mode
$fname = $rel_url_to_local_dir{$url_final->{url}};
if ($fname =~ m{/$}){
$fname .= "${index_name}";
}
} elsif ($url_final->{path} =~ m{.*/([^/]+)$}){
# get filename from url
if ($args{recursive} && !$args{'recursive-flat'}){
$fname = urldecode($&);
} else {
$fname = urldecode($1);
}
$fname = substr($fname, 1) if $fname =~ m{^/}; # drop initial /
} elsif ($url_final->{path} =~ m{/$}){
$fname = $url_final->{path} . ${index_name};
$fname = substr($fname, 1); # drop initial /
} else {
unless ($following || $process_action && index($process_action->{what}, 'getlinked') == 0){
say STDERR "Cannot get remote file name from url.";
exit 7;
}
}
}
if ($fname && $fname ne '-'){
# process cut-dirs
if ($args{'cut-dirs'}){
# split the path segments
my @path = split(m{/}, $fname);
my $f = pop @path; # keep the file
# remove the required number of elements
if ($args{'recursive-flat'}){
@path = ();
} else {
for (my $i=1; $i <= $args{'cut-dirs'}; $i++){
shift @path;
}
}
if (@path){
$fname = join('/', @path) . "/$f";
} else {
$fname = $f;
}
}
my $h = '';
if ($args{recursive} && !$args{'no-host-directories'}){
$h = $url_final->{host};
if ($url_final->{port} != $defports{$url_final->{scheme}}){
$h .= ':' . $url_final->{port};
}
$h .= '/';
}
$out_file = "${prefix}${h}${fname}";
# make_path($out_file);
# redirect_output_to_file($out_file);
}
my $redirect_pending = 0;
my $discard_output_creation = 0;
my $url_proxy = get_proxy_settings($url_final);
my $pheaders = [];
if ($url_proxy){
if ($url_final->{scheme} eq 'https' && $url_proxy->{auth}){
# try to get the openSSL version
# my $ver = `openssl version` or die "Cannot get openssl version: $!";
# chomp $ver;
# say STDERR "* https tunelling via openSSL is unlikely to work unless openSSL is v3.0-beta1 (found $ver)!";
}
$pheaders = build_http_proxy_headers($url_proxy, $url_final);
$url_final->{proxified} = 1 if $url_final->{scheme} eq 'http'; # direct
$url_final->{tunneled} = 1 if $url_final->{scheme} eq 'https'; # openSSL
}
# connect directly a socket to the server or to a proxy
# or open a tunnel for HTTPS
if ($url_proxy){
($OUT, $IN, $ERR) = connect_direct_socket($url_proxy->{host},
$url_proxy->{port}) if $url_final->{scheme} eq 'http';
($OUT, $IN, $ERR) = connect_ssl_tunnel($url_final, $url_proxy) if $url_final->{scheme} eq 'https';
} else {
($OUT, $IN, $ERR) = connect_direct_socket($url_final->{host},
$url_final->{port}) if $url_final->{scheme} eq 'http';
($OUT, $IN, $ERR) = connect_ssl_tunnel($url_final) if $url_final->{scheme} eq 'https';
}
my $body = prepare_http_body_to_post();
my $headers = build_http_request_headers($method, $url_final, $url_proxy, $body);
if (#$url_final->{proxified} &&
@$pheaders){
# ask proxy to connect
send_http_request($IN, $OUT, $ERR, $pheaders, undef);
my $presp = process_http_response_headers(IN => $IN,
ERR => $ERR,
url => $url_proxy);
say STDERR "* Proxy returned " . $presp->{status}->{code} . " / " . $presp->{status}->{message} if $args{verbose} || $args{debug};
unless ($presp->{status}->{code} == 200){
say STDERR sprintf "Proxy connection unsuccessful: %d / %s", $presp->{status}->{code}, $presp->{status}->{message};
goto BREAK;
}
}
say STDERR "* Sending request to server" if $args{verbose} || $args{debug};
# Write to the server
send_http_request($IN, $OUT, $ERR, $headers, $body);
# Receive the response
if (!HTTP09()){
# there is no header in HTTP/0.9
$resp = process_http_response_headers(IN => $IN,
OUT => current_output(),
ERR => $ERR,
url => $url_final,
url_proxy => $url_proxy,
out_file => $fname,
follow => $following);
print {current_output} ${$resp->{captured_head}} if ($args{head} || $args{'include-response'} || $args{verbose}) && defined ${$resp->{captured_head}};
say STDERR "* received $resp->{head_byte_len} headers bytes" if $args{verbose} || $args{debug};
say STDERR Dumper $resp if $args{debug};
if ($resp->{head_byte_len}){
my $code = $resp->{status}{code};
say STDERR '* ' . $url_final->{url} . ' -> ' . $code if $args{verbose} || $args{debug};
say STDERR Dumper $resp->{headers} if $args{debug};
if ($args{location} && $code && (300 < $code) && ($code <= 399)){
# we want to follow redirects and we have a redirect
unless($redirs){
say STDERR sprintf("* Maximum (%d) redirects followed", $max_redirs);
$no_follow_after_body = 1;
} else {
$redirect_pending = 1;
}
my ($old_scheme, $old_host, $old_port) = ($url_final->{scheme}, $url_final->{host}, $url_final->{port});
my $redirected_url = get_redirected_url($url_final, $resp->{headers}{location});
# check to prevent full site download because of a redirect (eg: a link get a 302 to the root dir)
my $cur = canonicalize($url_final->{url});
my $next = canonicalize($redirected_url->{url});
if (!is_descendant_or_equal($next, $cur) && $args{'no-parent'}){
say STDERR "* ignoring redirected url $redirected_url->{url} from $url_final->{url} because of --no-parent" if $args{verbose} || $args{debug} || $args{'debug-urls'};
goto BREAK;
}
$url_final = $redirected_url;
$next_url = $url_final->{url};
# compare new url with previous and reconnected if needed
if (($url_final->{scheme} ne $old_scheme) || ($url_final->{host} ne $old_host) || ($url_final->{port} != $old_port)){
say STDERR "* Closing connection because of scheme/server redirect" if $args{verbose} || $args{debug};
say STDERR sprintf("* scheme %s -> %s", $old_scheme, $url_final->{scheme}) if $url_final->{scheme} ne $old_scheme && $args{verbose} || $args{debug};
say STDERR sprintf("* host %s -> %s", $old_host, $url_final->{host}) if $url_final->{host} ne $old_host && $args{verbose} || $args{debug};
say STDERR sprintf("* port %s -> %s", $old_port, $url_final->{port}) if $url_final->{port} ne $old_port && $args{verbose} || $args{debug};
close $IN;
close $OUT;
close $ERR if $ERR;
}
say STDERR sprintf("* Redirecting #%d to %s", $max_redirs - $redirs, $url_final->{url}) if $args{verbose} || $args{debug} || $args{'debug-urls'};
$redirs--;
} elsif ($code && $code == 300){
# server do not know what to serve
say STDERR "* 300 'Multiple Choices' on $url_final->{url}" if $args{verbose} || $args{debug};
$discard_output_creation = 1;
} elsif ($code && $code >= 400 && $code <= 599){
# something is wrong
say STDERR "* $code on $url_final->{url}" if $args{verbose} || $args{debug};
if ($args{fail} || $args{'fail-with-body'}){
# we are not in crawling mode
# $error_code = $code; # FIXME: max is 255
$error_code = 11 if $code >= 400 && $code <= 499;
$error_code = 12 if $code >= 500 && $code <= 599;
$no_follow_after_body = 1;
goto BREAK if $args{fail};
}
$discard_output_creation = 1;
# if ($out_file){
# # do not leave empty files
# unlink $out_file;
#}
}
}
}
if (!$redirect_pending
&& !$discard_output_creation
&& ($args{output}
|| $args{'remote-name'}
|| $args{recursive})){
$out_file = urldecode($out_file);
make_path($out_file);
redirect_output_to_file($out_file);
}
# for some actions we need to capture the output into a variable
# also an external caller could want the output saved in the $resp object
my $need_capture;
if ($params{capture}
|| (defined $process_action && !$process_action->{done})
|| ($args{recursive} && $resp->{headers}{'content-type'} && $resp->{headers}{'content-type'} =~ m{(text/html|application/xhtml|text/css|application/javascript)})){
$need_capture = 1;
}
$resp = process_http_response_body(IN => $IN,
OUT => current_output(),
ERR => $ERR,
url => $url_final,
url_proxy => $url_proxy,
response => $resp,
capture => $need_capture,
out_file => $fname,
follow => $following);
say STDERR "* received $resp->{body_byte_len} body bytes" if $args{verbose} || $args{debug};
if ($resp->{head_byte_len} + $resp->{body_byte_len}){
# result other than redirect
if ($process_action){
if (!$process_action->{done}){
perform_action($process_action, $url_final, $resp, $discovered_links, ($params{capture} ? $params{capture} == 1 : 0));
$process_action->{done} = 1;
}
} elsif ($resp->{headers}{'content-type'}
&& $resp->{headers}{'content-type'} =~ '(text/html|application/xhtml|text/css|application/javascript)'
&& !$discard_output_creation
){
if ($discovered_links){
push @$discovered_links, discover_links($resp, $url_final, $acceptrx, $rejectrx, !$args{'recursive-flat'});
}
}
# save eventually the captured data into a file for getlinked or recursive
if ($resp->{captured}
&& (
($process_action && index($process_action->{what}, 'getlinked') == 0)
||
($args{recursive} && $resp->{status}{code} && $resp->{status}{code} != 404)
)){
# need to use select as "print current_output ${$resp->{captured}}" prints "GLOB(0x1f75cd8)" (the current_output) to STDOUT
# my $old_selected = select current_output;
# say STDERR "output is " . current_output;
print {current_output} ${$resp->{captured}} if defined ${$resp->{captured}};
# select $old_selected;
}
# goto BREAK; # weird, 'last' is throwing a warning "Exiting subroutine via last"
}
last REDIRECT if $no_follow_after_body;
} while (($resp->{head_byte_len} + $resp->{body_byte_len}) && $next_url && $redirs >= 0);
BREAK:
restore_output();
if ($args{'remote-time'} # FIXME: add test on redirection
&& $fname #$resp->{redirected}
&& $resp->{headers}{'last-modified'}){
my $timestamp = $resp->{headers}{'last-modified'};
my $epoch = str2epoch($timestamp);
if (-f $out_file && $epoch > -1){
utime($epoch, $epoch, $out_file) or say STDERR "Cannot set modification time of $resp->{redirected}: $!";
}
}
close $IN;
close $OUT;
close $ERR if $ERR;
# save the cookie jar if requested
if ($args{'cookie-jar'}){
save_cookie_jar($args{'cookie-jar'}, $cookies);
}
exit $error_code if $error_code;
return $resp;
}
# when getting a 3xx redirect in HTTP, compute the next URL attributes
# from the Location header
sub get_redirected_url {
my ($url, $location) = @_;
$args{referer} = $url->{url} if $auto_ref; # use previous url as next referer
my ($old_scheme, $old_host, $old_port) = ($url->{scheme}, $url->{host}, $url->{port});
if ($location !~ m{^https?://}){
# fix URLs when scheme is missing
my $user_info = auth_string($url);
my $authority = $url->{host};
$authority = $user_info . $authority if $user_info;
$authority .= sprintf(":%s", $url->{port}) if $url->{port} != $defports{$url->{scheme}};
$location = sprintf("%s://%s%s",
$url->{scheme},
$authority,
canonicalize($location));
}
$url = parse_uri($location);
$url = complete_url_default_values($url); # is this correct??
# FIXME: in case of local schemeless url... <=======
# relative redirect urls may miss some parameters
if (($url->{scheme} ne $old_scheme) || ($url->{host} ne $old_host) || ($url->{port} != $old_port)){
$url->{scheme} = $old_scheme unless $url->{scheme};
$url->{port} = $defports{$url->{scheme}} unless $url->{port};
}
$url->{port} = $old_port unless $url->{port};
$url->{host} = $old_host unless $url->{host};
return $url;
}
# perform a file:// query
sub process_file {
my $url = shift;
my $discovered_links = shift;
my $path = $url->{path};
my $content;