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