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