blib/lib/LWP/Protocol/Net/Curl.pm

filter: Statementstmt 93.3% 28 / 30 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 10 / 10 Podpod n/a totaltotal 95.0% 38 / 40 CC 1 SCAR 0.3
CC
1
Cov
93%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package LWP::Protocol::Net::Curl;
2 # ABSTRACT: the power of libcurl in the palm of your hands!
3  
4  
5 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 8 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 8 ▶use warnings qw(all);
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 8 ▶use base qw(LWP::Protocol);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 8 ▶use Carp qw(carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 8 ▶use Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 8 ▶use Fcntl;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 8 ▶use HTTP::Date;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 8 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 0 ▶use Net::Curl::Easy qw(:constants);
Subroutine BEGIN: called CC=1 SCAR=2.6
17 use Net::Curl::Multi qw(:constants);
18 use Net::Curl::Share qw(:constants);
19 use Scalar::Util qw(looks_like_number);
20 use URI;
21  
22 our $VERSION = '0.027'; # VERSION
23  
24 my %curlopt;
25 my $share;
26 unless (defined $Config{usethreads}) {
27 $share = Net::Curl::Share->new({ started => time });
28 $share->setopt(CURLSHOPT_SHARE ,=> CURL_LOCK_DATA_COOKIE);
29 $share->setopt(CURLSHOPT_SHARE ,=> CURL_LOCK_DATA_DNS);
30  
31 ## no critic (RequireCheckingReturnValueOfEval)
32 eval { $share->setopt(CURLSHOPT_SHARE ,=> CURL_LOCK_DATA_SSL_SESSION) };
33 }
34  
35 ## no critic (ProhibitPackageVars)
36 my %protocols = map { ($_) x 2 } @{Net::Curl::version_info()->{protocols}};
37 our @implements =
38 sort grep { defined }
39 @protocols
40 {qw{ftp ftps gopher http https sftp scp}};
41 our %implements = map { $_ => 1 } @implements;
42  
43 our $use_select = Net::Curl::Multi->can(q(wait)) ? 0 : 1;
44  
45  
46 # Resolve libcurl constants by string
47 sub _curlopt {
48 my ($key, $no_carp) = @_;
49 return 0 + $key if looks_like_number($key);
50  
51 $key =~ s/^Net::Curl::Easy:://ix;
52 $key =~ y/-/_/;
53 $key =~ s/\W//gx;
54 $key = uc $key;
55 $key = qq(CURLOPT_${key}) if $key !~ /^CURL(?:M|SH)?OPT_/x;
56  
57 my $const = eval {
58 ## no critic (ProhibitNoStrict ProhibitNoWarnings)
59 no strict qw(refs);
60 no warnings qw(once);
61 return *$key->();
62 };
63 carp qq(Invalid libcurl constant: $key)
64 if $@
65 and not defined $no_carp;
66  
67 return $const;
68 }
69  
70 # Sugar for a common setopt() pattern
71 sub _setopt_ifdef {
72 my ($curl, $key, $value, $no_carp) = @_;
73  
74 my $curlopt_key = _curlopt($key, $no_carp);
75 $curl->setopt($curlopt_key => $value)
76 if defined $curlopt_key
77 and defined $value;
78  
79 return;
80 }
81  
82 # Pre-configure the module
83 sub import {
84 my ($class, @args) = @_;
85  
86 my $takeover = 1;
87 if (@args) {
88 my %args = @args;
89 while (my ($key, $value) = each %args) {
90 if ($key eq q(takeover)) {
91 $takeover = $value;
92 } else {
93 my $const = _curlopt($key);
94 $curlopt{$const} = $value
95 if defined $const;
96 }
97 }
98 }
99  
100 if ($takeover) {
101 LWP::Protocol::implementor($_ => $class)
102 for @implements;
103 }
104  
105 return;
106 }
107  
108 # Properly setup libcurl to handle each method in a compatible way
109 sub _handle_method {
110 my ($ua, $easy, $request) = @_;
111  
112 my $method = uc $request->method;
113 my %dispatch = (
114 GET => sub {
115 $easy->setopt(CURLOPT_HTTPGET ,=> 1);
116 }, POST => sub {
117 $easy->setopt(CURLOPT_POST ,=> 1);
118 $easy->setopt(CURLOPT_POSTFIELDS,=> $request->content);
119 $easy->setopt(CURLOPT_POSTFIELDSIZE,=> length $request->content);
120 }, HEAD => sub {
121 $easy->setopt(CURLOPT_NOBODY ,=> 1);
122 }, DELETE => sub {
123 $easy->setopt(CURLOPT_CUSTOMREQUEST ,=> $method);
124 }, PUT => sub {
125 $easy->setopt(CURLOPT_UPLOAD ,=> 1);
126 my $buf = $request->content;
127 my $off = 0;
128 # Do not set CURLOPT_INFILESIZE if Content-Length header exists
129 # and libcurl version is earlier than 7.23.0 (note libcurl will
130 # send two Content-Length headers in versions earlier than 7.23.0
131 # when both the Content-Length header and CURLOPT_INFILESIZE
132 # option is set).
133 $easy->setopt(CURLOPT_INFILESIZE,=> length $buf)
134 if !defined $request->header('Content-Length')
135 || Net::Curl::version_info()->{version_num} >= 0x72300;
136 $easy->setopt(CURLOPT_READFUNCTION ,=> sub {
137 my (undef, $maxlen) = @_;
138 my $chunk = substr $buf, $off, $maxlen;
139 $off += length $chunk;
140 return \$chunk;
141 });
142 },
143 );
144  
145 if (my $protocol = $request->protocol) {
146 my $v;
147 if ($protocol =~ m/^HTTP\/1\.0$/x) {
148 $v = CURL_HTTP_VERSION_1_0;
149 } elsif ($protocol =~ m/^HTTP\/1\.1$/x) {
150 $v = CURL_HTTP_VERSION_1_1;
151 } elsif ($protocol =~ m/^HTTP\/2/x) {
152 $v = eval { Net::Curl::Easy::CURL_HTTP_VERSION_2TLS() };
153 } elsif ($protocol =~ m/^HTTP\/3/x) {
154 $v = eval { Net::Curl::Easy::CURL_HTTP_VERSION_3() };
155 }
156 $easy->setopt(CURLOPT_HTTP_VERSION ,=> $v) if $v;
157 }
158  
159 my $method_ref = $dispatch{$method};
160 if (defined $method_ref) {
161 $method_ref->();
162 } else {
163 ## no critic (RequireCarping RequireUseOfExceptions)
164 die HTTP::Response->new(
165 &HTTP::Status::RC_BAD_REQUEST,
166 qq(Bad method '$method')
167 );
168 }
169  
170 # handle redirects internally (except POST, greatly fsck'd up by IIS servers)
171 if ($method ne q(POST) and grep { $method eq uc } @{$ua->requests_redirectable}) {
172 $easy->setopt(CURLOPT_AUTOREFERER ,=> 1);
173 $easy->setopt(CURLOPT_FOLLOWLOCATION,=> 1);
174 $easy->setopt(CURLOPT_MAXREDIRS ,=> $ua->max_redirect);
175 } else {
176 $easy->setopt(CURLOPT_FOLLOWLOCATION,=> 0);
177 }
178  
179 return $method;
180 }
181  
182 # Compatibilize request headers
183 sub _fix_headers {
184 my ($ua, $easy, $key, $value) = @_;
185  
186 return 0 unless defined $value;
187  
188 # stolen from LWP::Protocol::http
189 $key =~ s/^://x;
190 $value =~ s/\n/ /gx;
191  
192 my $encoding = 0;
193 if ($key =~ /^accept-encoding$/ix) {
194 my @encoding =
195 map { /^(?:x-)?(deflate|gzip|identity)$/ix ? lc $1 : () }
196 split /\s*,\s*/x, $value;
197  
198 if (@encoding) {
199 ++$encoding;
200 $easy->setopt(CURLOPT_ENCODING ,=> join(q(,) => @encoding));
201 }
202 } elsif ($key =~ /^user-agent$/ix) {
203 # While we try our best to look like LWP on the client-side,
204 # it's *definitely* different on the server-site!
205 # I guess it would be nice to introduce ourselves in a polite way.
206 $value =~ s/\b(\Q@{[ $ua->_agent ]}\E)\b/qq($1 ) . Net::Curl::version()/egx;
207 $easy->setopt(CURLOPT_USERAGENT ,=> $value);
208 } elsif ($key =~ /^x[-_](curlopt[-\w]+)$/ix) {
209 _setopt_ifdef($easy, $1 => $value);
210 } else {
211 $easy->pushopt(CURLOPT_HTTPHEADER ,=> [qq[$key: $value]]);
212 }
213  
214 return $encoding;
215 }
216  
217 # Wrap libcurl perform() in a (potentially) non-blocking way
218 sub _perform_loop {
219 my ($multi) = @_;
220  
221 my $running = 0;
222 do {
223 my $timeout = $multi->timeout;
224  
225 if ($running and $timeout > 9) {
226 if ($use_select) {
227 my ($r, $w, $e) = $multi->fdset;
228 select($r, $w, $e, $timeout / 1000);
229 } else {
230 $multi->wait($timeout);
231 }
232 }
233  
234 $running = $multi->perform;
235 while (my (undef, $easy, $result) = $multi->info_read) {
236 $multi->remove_handle($easy);
237 if ($result == CURLE_TOO_MANY_REDIRECTS) {
238 # will return the last request
239 } elsif ($result) {
240 ## no critic (RequireCarping RequireUseOfExceptions)
241 die HTTP::Response->new(
242 &HTTP::Status::RC_BAD_REQUEST,
243 qq($result),
244 );
245 }
246 }
247 } while ($running);
248  
249 return $running;
250 }
251  
252 ## no critic (ProhibitManyArgs)
253 sub request {
254 my ($self, $request, $proxy, $arg, $size, $timeout) = @_;
255  
256 my $ua = $self->{ua};
257 unless (q(Net::Curl::Multi) eq ref $ua->{curl_multi}) {
258 $ua->{curl_multi} = Net::Curl::Multi->new({ def_headers => $ua->{def_headers} });
259  
260 # avoid "callback function is not set" warning
261 _setopt_ifdef(
262 $ua->{curl_multi},
263 q(CURLMOPT_SOCKETFUNCTION) => sub { return 0 },
264 1,
265 );
266 }
267  
268 my $data = '';
269 my $header = '';
270 my $writedata;
271  
272 my $easy = Net::Curl::Easy->new({ request => $request });
273 $ua->{curl_multi}->add_handle($easy);
274  
275 my $previous = undef;
276 my $response = HTTP::Response->new(&HTTP::Status::RC_OK);
277 $response->request($request);
278  
279 $easy->setopt(CURLOPT_HEADERFUNCTION ,=> sub {
280 my ($_easy, $line) = @_;
281 $header .= $line;
282  
283 # I hope only HTTP sends "empty line" as delimiters
284 if ($line =~ /^\s*$/sx) {
285 $response = HTTP::Response->parse($header);
286 my $msg = $response->message;
287 $msg = '' unless defined $msg;
288 $msg =~ s/^\s+|\s+$//gsx;
289 $response->message($msg);
290  
291 $response->request($request->clone);
292 my $effective_url = URI->new('' . $_easy->getinfo(CURLINFO_EFFECTIVE_URL));
293 $response->request->uri($effective_url);
294 $response->previous($previous) if defined $previous;
295 $previous = $response;
296  
297 $header = '';
298 }
299  
300 return length $line;
301 });
302  
303 if (q(CODE) eq ref $arg) {
304 $easy->setopt(CURLOPT_WRITEFUNCTION ,=> sub {
305 my (undef, $chunk) = @_;
306 $arg->($chunk, $response, $self);
307 return length $chunk;
308 });
309 $writedata = undef;
310 } elsif (defined $arg) {
311 # will die() later
312 sysopen $writedata, $arg, O_CREAT | O_NONBLOCK | O_WRONLY;
313 binmode $writedata;
314 } else {
315 $writedata = \$data;
316 }
317  
318 my $encoding = 0;
319 while (my ($key, $value) = each %curlopt) {
320 ++$encoding if $key == CURLOPT_ENCODING;
321 $easy->setopt($key, $value);
322 }
323  
324 # SSL stuff, may not be compiled
325 if ($request->uri->scheme =~ /s$/ix) {
326 _setopt_ifdef($easy, CAINFO => $ua->{ssl_opts}{SSL_ca_file});
327 _setopt_ifdef($easy, CAPATH => $ua->{ssl_opts}{SSL_ca_path});
328 _setopt_ifdef($easy, CURLOPT_SSLCERT=> $ua->{ssl_opts}{SSL_cert_file});
329 _setopt_ifdef($easy, CURLOPT_SSLKEY => $ua->{ssl_opts}{SSL_key_file});
330  
331 # fixes a security flaw denied by libcurl v7.28.1
332 _setopt_ifdef($easy, SSL_VERIFYHOST => (!!$ua->{ssl_opts}{verify_hostname}) << 1);
333 _setopt_ifdef($easy, SSL_VERIFYPEER => 0) unless $ua->{ssl_opts}{verify_hostname};
334 }
335  
336 $easy->setopt(CURLOPT_FILETIME ,=> 1);
337 $easy->setopt(CURLOPT_URL ,=> $request->uri);
338 _setopt_ifdef($easy, CURLOPT_BUFFERSIZE ,=> $size);
339 _setopt_ifdef($easy, CURLOPT_INTERFACE ,=> $ua->{local_address});
340 _setopt_ifdef($easy, CURLOPT_MAXFILESIZE,=> $ua->max_size);
341 _setopt_ifdef($easy, q(CURLOPT_NOPROXY) => join(q(,) => @{$ua->{no_proxy}}), 1);
342 _setopt_ifdef($easy, CURLOPT_PROXY ,=> $proxy);
343 _setopt_ifdef($easy, CURLOPT_SHARE ,=> $share);
344 _setopt_ifdef($easy, CURLOPT_TIMEOUT ,=> $timeout);
345 _setopt_ifdef($easy, CURLOPT_WRITEDATA ,=> $writedata);
346  
347 if ($ua->{show_progress}) {
348 $easy->setopt(CURLOPT_NOPROGRESS ,=> 0);
349 _setopt_ifdef(
350 $easy,
351 q(CURLOPT_PROGRESSFUNCTION) => sub {
352 my (undef, $dltotal, $dlnow) = @_;
353 $ua->progress($dltotal ? $dlnow / $dltotal : q(tick));
354 return 0;
355 },
356 1,
357 );
358 }
359  
360 _handle_method($ua, $easy, $request);
361  
362 $request->headers->scan(sub { $encoding += _fix_headers($ua, $easy, @_) });
363  
364 _perform_loop($ua->{curl_multi});
365  
366 $response->code($easy->getinfo(CURLINFO_RESPONSE_CODE) || 200);
367  
368 my $time = $easy->getinfo(CURLINFO_FILETIME);
369 $response->headers->header(last_modified => time2str($time))
370 if $time > 0;
371  
372 # handle decoded_content() & direct file write
373 if (q(GLOB) eq ref $writedata) {
374 close $writedata;
375 # avoid truncate by collect()
376 $arg = undef;
377 } elsif ($encoding) {
378 $response->headers->header(content_encoding => q(identity));
379 }
380  
381 return $self->collect_once($arg, $response, $data);
382 }
383  
384  
385 1;
386  
387 __END__
↑ Summary