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