]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPRequest.php
Support for stacked profiler analysis
[friendica.git] / src / Network / HTTPRequest.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU APGL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Network;
23
24 use DOMDocument;
25 use DomXPath;
26 use Friendica\App;
27 use Friendica\Core\Config\IConfig;
28 use Friendica\Core\System;
29 use Friendica\Util\Network;
30 use Friendica\Util\Profiler;
31 use Psr\Log\LoggerInterface;
32
33 /**
34  * Performs HTTP requests to a given URL
35  */
36 class HTTPRequest implements IHTTPRequest
37 {
38         /** @var LoggerInterface */
39         private $logger;
40         /** @var Profiler */
41         private $profiler;
42         /** @var IConfig */
43         private $config;
44         /** @var string */
45         private $baseUrl;
46
47         public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, App\BaseURL $baseUrl)
48         {
49                 $this->logger   = $logger;
50                 $this->profiler = $profiler;
51                 $this->config   = $config;
52                 $this->baseUrl  = $baseUrl->get();
53         }
54
55         /** {@inheritDoc}
56          *
57          * @throws HTTPException\InternalServerErrorException
58          */
59         public function head(string $url, array $opts = [])
60         {
61                 $opts['nobody'] = true;
62
63                 return $this->get($url, $opts);
64         }
65
66         /**
67          * {@inheritDoc}
68          *
69          * @param int $redirects The recursion counter for internal use - default 0
70          *
71          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
72          */
73         public function get(string $url, array $opts = [], &$redirects = 0)
74         {
75                 $this->profiler->startRecording('network');
76
77                 if (Network::isLocalLink($url)) {
78                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
79                 }
80
81                 if (strlen($url) > 1000) {
82                         $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
83                         $this->profiler->stopRecording();
84                         return CurlResult::createErrorCurl(substr($url, 0, 200));
85                 }
86
87                 $parts2     = [];
88                 $parts      = parse_url($url);
89                 $path_parts = explode('/', $parts['path'] ?? '');
90                 foreach ($path_parts as $part) {
91                         if (strlen($part) <> mb_strlen($part)) {
92                                 $parts2[] = rawurlencode($part);
93                         } else {
94                                 $parts2[] = $part;
95                         }
96                 }
97                 $parts['path'] = implode('/', $parts2);
98                 $url           = Network::unparseURL($parts);
99
100                 if (Network::isUrlBlocked($url)) {
101                         $this->logger->info('Domain is blocked.', ['url' => $url]);
102                         $this->profiler->stopRecording();
103                         return CurlResult::createErrorCurl($url);
104                 }
105
106                 $ch = @curl_init($url);
107
108                 if (($redirects > 8) || (!$ch)) {
109                         $this->profiler->stopRecording();
110                         return CurlResult::createErrorCurl($url);
111                 }
112
113                 @curl_setopt($ch, CURLOPT_HEADER, true);
114
115                 if (!empty($opts['cookiejar'])) {
116                         curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
117                         curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
118                 }
119
120                 // These settings aren't needed. We're following the location already.
121                 //      @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
122                 //      @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
123
124                 if (!empty($opts['accept_content'])) {
125                         curl_setopt(
126                                 $ch,
127                                 CURLOPT_HTTPHEADER,
128                                 ['Accept: ' . $opts['accept_content']]
129                         );
130                 }
131
132                 if (!empty($opts['header'])) {
133                         curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
134                 }
135
136                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
137                 @curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
138
139                 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
140
141                 if ($range > 0) {
142                         @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
143                 }
144
145                 // Without this setting it seems as if some webservers send compressed content
146                 // This seems to confuse curl so that it shows this uncompressed.
147                 /// @todo  We could possibly set this value to "gzip" or something similar
148                 curl_setopt($ch, CURLOPT_ENCODING, '');
149
150                 if (!empty($opts['headers'])) {
151                         $this->logger->notice('Wrong option \'headers\' used.');
152                         @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
153                 }
154
155                 if (!empty($opts['nobody'])) {
156                         @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
157                 }
158
159                 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
160
161                 if (!empty($opts['timeout'])) {
162                         @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
163                 } else {
164                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
165                         @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
166                 }
167
168                 // by default we will allow self-signed certs
169                 // but you can override this
170
171                 $check_cert = $this->config->get('system', 'verifyssl');
172                 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
173
174                 if ($check_cert) {
175                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
176                 }
177
178                 $proxy = $this->config->get('system', 'proxy');
179
180                 if (!empty($proxy)) {
181                         @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
182                         @curl_setopt($ch, CURLOPT_PROXY, $proxy);
183                         $proxyuser = $this->config->get('system', 'proxyuser');
184
185                         if (!empty($proxyuser)) {
186                                 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
187                         }
188                 }
189
190                 if ($this->config->get('system', 'ipv4_resolve', false)) {
191                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
192                 }
193
194                 $s         = @curl_exec($ch);
195                 $curl_info = @curl_getinfo($ch);
196
197                 // Special treatment for HTTP Code 416
198                 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
199                 if (($curl_info['http_code'] == 416) && ($range > 0)) {
200                         @curl_setopt($ch, CURLOPT_RANGE, '');
201                         $s         = @curl_exec($ch);
202                         $curl_info = @curl_getinfo($ch);
203                 }
204
205                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
206
207                 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
208                         $redirects++;
209                         $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
210                         @curl_close($ch);
211                         $this->profiler->stopRecording();
212                         return $this->get($curlResponse->getRedirectUrl(), $opts, $redirects);
213                 }
214
215                 @curl_close($ch);
216
217                 $this->profiler->stopRecording();
218
219                 return $curlResponse;
220         }
221
222         /**
223          * {@inheritDoc}
224          *
225          * @param int $redirects The recursion counter for internal use - default 0
226          *
227          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
228          */
229         public function post(string $url, $params, array $headers = [], int $timeout = 0, &$redirects = 0)
230         {
231                 $this->profiler->startRecording('network');
232
233                 if (Network::isLocalLink($url)) {
234                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
235                 }
236
237                 if (Network::isUrlBlocked($url)) {
238                         $this->logger->info('Domain is blocked.' . ['url' => $url]);
239                         $this->profiler->stopRecording();
240                         return CurlResult::createErrorCurl($url);
241                 }
242
243                 $ch = curl_init($url);
244
245                 if (($redirects > 8) || (!$ch)) {
246                         $this->profiler->stopRecording();
247                         return CurlResult::createErrorCurl($url);
248                 }
249
250                 $this->logger->debug('Post_url: start.', ['url' => $url]);
251
252                 curl_setopt($ch, CURLOPT_HEADER, true);
253                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
254                 curl_setopt($ch, CURLOPT_POST, 1);
255                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
256                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
257
258                 if ($this->config->get('system', 'ipv4_resolve', false)) {
259                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
260                 }
261
262                 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
263
264                 if (intval($timeout)) {
265                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
266                 } else {
267                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
268                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
269                 }
270
271                 if (!empty($headers)) {
272                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
273                 }
274
275                 $check_cert = $this->config->get('system', 'verifyssl');
276                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
277
278                 if ($check_cert) {
279                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
280                 }
281
282                 $proxy = $this->config->get('system', 'proxy');
283
284                 if (!empty($proxy)) {
285                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
286                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
287                         $proxyuser = $this->config->get('system', 'proxyuser');
288                         if (!empty($proxyuser)) {
289                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
290                         }
291                 }
292
293                 // don't let curl abort the entire application
294                 // if it throws any errors.
295
296                 $s = @curl_exec($ch);
297
298                 $curl_info = curl_getinfo($ch);
299
300                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
301
302                 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
303                         $redirects++;
304                         $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
305                         curl_close($ch);
306                         $this->profiler->stopRecording();
307                         return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
308                 }
309
310                 curl_close($ch);
311
312                 $this->profiler->stopRecording();
313
314                 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
315                 if ($curlResponse->getReturnCode() == 417) {
316                         $redirects++;
317
318                         if (empty($headers)) {
319                                 $headers = ['Expect:'];
320                         } else {
321                                 if (!in_array('Expect:', $headers)) {
322                                         array_push($headers, 'Expect:');
323                                 }
324                         }
325                         $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
326                         return $this->post($url, $params, $headers, $redirects, $timeout);
327                 }
328
329                 $this->logger->debug('Post_url: End.', ['url' => $url]);
330
331                 return $curlResponse;
332         }
333
334         /**
335          * {@inheritDoc}
336          */
337         public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
338         {
339                 if (Network::isLocalLink($url)) {
340                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
341                 }
342
343                 if (Network::isUrlBlocked($url)) {
344                         $this->logger->info('Domain is blocked.', ['url' => $url]);
345                         return $url;
346                 }
347
348                 if (Network::isRedirectBlocked($url)) {
349                         $this->logger->info('Domain should not be redirected.', ['url' => $url]);
350                         return $url;
351                 }
352
353                 $url = Network::stripTrackingQueryParams($url);
354
355                 if ($depth > 10) {
356                         return $url;
357                 }
358
359                 $url = trim($url, "'");
360
361                 $this->profiler->startRecording('network');
362
363                 $ch = curl_init();
364                 curl_setopt($ch, CURLOPT_URL, $url);
365                 curl_setopt($ch, CURLOPT_HEADER, 1);
366                 curl_setopt($ch, CURLOPT_NOBODY, 1);
367                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
368                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
369                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
370                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
371
372                 curl_exec($ch);
373                 $curl_info = @curl_getinfo($ch);
374                 $http_code = $curl_info['http_code'];
375                 curl_close($ch);
376
377                 $this->profiler->stopRecording();
378
379                 if ($http_code == 0) {
380                         return $url;
381                 }
382
383                 if (in_array($http_code, ['301', '302'])) {
384                         if (!empty($curl_info['redirect_url'])) {
385                                 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
386                         } elseif (!empty($curl_info['location'])) {
387                                 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
388                         }
389                 }
390
391                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
392                 if (!$fetchbody) {
393                         return $this->finalUrl($url, ++$depth, true);
394                 }
395
396                 // if the file is too large then exit
397                 if ($curl_info["download_content_length"] > 1000000) {
398                         return $url;
399                 }
400
401                 // if it isn't a HTML file then exit
402                 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
403                         return $url;
404                 }
405
406                 $this->profiler->startRecording('network');
407
408                 $ch = curl_init();
409                 curl_setopt($ch, CURLOPT_URL, $url);
410                 curl_setopt($ch, CURLOPT_HEADER, 0);
411                 curl_setopt($ch, CURLOPT_NOBODY, 0);
412                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
413                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
414                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
415                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
416
417                 $body = curl_exec($ch);
418                 curl_close($ch);
419
420                 $this->profiler->stopRecording();
421
422                 if (trim($body) == "") {
423                         return $url;
424                 }
425
426                 // Check for redirect in meta elements
427                 $doc = new DOMDocument();
428                 @$doc->loadHTML($body);
429
430                 $xpath = new DomXPath($doc);
431
432                 $list = $xpath->query("//meta[@content]");
433                 foreach ($list as $node) {
434                         $attr = [];
435                         if ($node->attributes->length) {
436                                 foreach ($node->attributes as $attribute) {
437                                         $attr[$attribute->name] = $attribute->value;
438                                 }
439                         }
440
441                         if (@$attr["http-equiv"] == 'refresh') {
442                                 $path = $attr["content"];
443                                 $pathinfo = explode(";", $path);
444                                 foreach ($pathinfo as $value) {
445                                         if (substr(strtolower($value), 0, 4) == "url=") {
446                                                 return $this->finalUrl(substr($value, 4), ++$depth);
447                                         }
448                                 }
449                         }
450                 }
451
452                 return $url;
453         }
454
455         /**
456          * {@inheritDoc}
457          *
458          * @param int $redirects The recursion counter for internal use - default 0
459          *
460          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
461          */
462         public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', &$redirects = 0)
463         {
464                 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar, $redirects);
465
466                 return $ret->getBody();
467         }
468
469         /**
470          * {@inheritDoc}
471          *
472          * @param int $redirects The recursion counter for internal use - default 0
473          *
474          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
475          */
476         public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', &$redirects = 0)
477         {
478                 return $this->get(
479                         $url,
480                         [
481                                 'timeout'        => $timeout,
482                                 'accept_content' => $accept_content,
483                                 'cookiejar'      => $cookiejar
484                         ],
485                         $redirects
486                 );
487         }
488
489         /**
490          * {@inheritDoc}
491          */
492         public function getUserAgent()
493         {
494                 return
495                         FRIENDICA_PLATFORM . " '" .
496                         FRIENDICA_CODENAME . "' " .
497                         FRIENDICA_VERSION . '-' .
498                         DB_UPDATE_VERSION . '; ' .
499                         $this->baseUrl;
500         }
501 }