]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPRequest.php
cf9b53a92a402f7b97a3034b00e269dc0d9ab0b3
[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                 $onRedirect = function(
201                         RequestInterface $request,
202                         ResponseInterface $response,
203                         UriInterface $uri
204                 ) {
205                         $this->logger->notice('Curl redirect.', ['url' => $request->getUri(), 'to' => $uri]);
206                 };
207
208                 $onHeaders = function (ResponseInterface $response) use ($opts) {
209                         if (!empty($opts['content_length']) &&
210                                 $response->getHeaderLine('Content-Length') > $opts['content_length']) {
211                                 throw new TransferException('The file is too big!');
212                         }
213                 };
214
215                 $client = new Client([
216                         'allow_redirect' => [
217                                 'max' => 8,
218                                 'on_redirect' => $onRedirect,
219                                 'track_redirect' => true,
220                                 'strict' => true,
221                                 'referer' => true,
222                         ],
223                         'on_headers' => $onHeaders,
224                         'sink' => tempnam(get_temppath(), 'guzzle'),
225                         'curl' => $curlOptions
226                 ]);
227
228                 try {
229                         $response = $client->get($url);
230                         return new GuzzleResponse($response, $url);
231                 } catch (TransferException $exception) {
232                         if ($exception instanceof RequestException &&
233                                 $exception->hasResponse()) {
234                                 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), $exception->getMessage());
235                         } else {
236                                 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), $exception->getMessage());
237                         }
238                 } finally {
239                         $this->profiler->stopRecording();
240                 }
241         }
242
243         /**
244          * {@inheritDoc}
245          *
246          * @param int $redirects The recursion counter for internal use - default 0
247          *
248          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
249          */
250         public function post(string $url, $params, array $headers = [], int $timeout = 0, &$redirects = 0)
251         {
252                 $this->profiler->startRecording('network');
253
254                 if (Network::isLocalLink($url)) {
255                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
256                 }
257
258                 if (Network::isUrlBlocked($url)) {
259                         $this->logger->info('Domain is blocked.' . ['url' => $url]);
260                         $this->profiler->stopRecording();
261                         return CurlResult::createErrorCurl($url);
262                 }
263
264                 $ch = curl_init($url);
265
266                 if (($redirects > 8) || (!$ch)) {
267                         $this->profiler->stopRecording();
268                         return CurlResult::createErrorCurl($url);
269                 }
270
271                 $this->logger->debug('Post_url: start.', ['url' => $url]);
272
273                 curl_setopt($ch, CURLOPT_HEADER, true);
274                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
275                 curl_setopt($ch, CURLOPT_POST, 1);
276                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
277                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
278
279                 if ($this->config->get('system', 'ipv4_resolve', false)) {
280                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
281                 }
282
283                 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
284
285                 if (intval($timeout)) {
286                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
287                 } else {
288                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
289                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
290                 }
291
292                 if (!empty($headers)) {
293                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
294                 }
295
296                 $check_cert = $this->config->get('system', 'verifyssl');
297                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
298
299                 if ($check_cert) {
300                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
301                 }
302
303                 $proxy = $this->config->get('system', 'proxy');
304
305                 if (!empty($proxy)) {
306                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
307                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
308                         $proxyuser = $this->config->get('system', 'proxyuser');
309                         if (!empty($proxyuser)) {
310                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
311                         }
312                 }
313
314                 // don't let curl abort the entire application
315                 // if it throws any errors.
316
317                 $s = @curl_exec($ch);
318
319                 $curl_info = curl_getinfo($ch);
320
321                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
322
323                 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
324                         $redirects++;
325                         $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
326                         curl_close($ch);
327                         $this->profiler->stopRecording();
328                         return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
329                 }
330
331                 curl_close($ch);
332
333                 $this->profiler->stopRecording();
334
335                 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
336                 if ($curlResponse->getReturnCode() == 417) {
337                         $redirects++;
338
339                         if (empty($headers)) {
340                                 $headers = ['Expect:'];
341                         } else {
342                                 if (!in_array('Expect:', $headers)) {
343                                         array_push($headers, 'Expect:');
344                                 }
345                         }
346                         $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
347                         return $this->post($url, $params, $headers, $redirects, $timeout);
348                 }
349
350                 $this->logger->debug('Post_url: End.', ['url' => $url]);
351
352                 return $curlResponse;
353         }
354
355         /**
356          * {@inheritDoc}
357          */
358         public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
359         {
360                 if (Network::isLocalLink($url)) {
361                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
362                 }
363
364                 if (Network::isUrlBlocked($url)) {
365                         $this->logger->info('Domain is blocked.', ['url' => $url]);
366                         return $url;
367                 }
368
369                 if (Network::isRedirectBlocked($url)) {
370                         $this->logger->info('Domain should not be redirected.', ['url' => $url]);
371                         return $url;
372                 }
373
374                 $url = Network::stripTrackingQueryParams($url);
375
376                 if ($depth > 10) {
377                         return $url;
378                 }
379
380                 $url = trim($url, "'");
381
382                 $this->profiler->startRecording('network');
383
384                 $ch = curl_init();
385                 curl_setopt($ch, CURLOPT_URL, $url);
386                 curl_setopt($ch, CURLOPT_HEADER, 1);
387                 curl_setopt($ch, CURLOPT_NOBODY, 1);
388                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
389                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
390                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
391                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
392
393                 curl_exec($ch);
394                 $curl_info = @curl_getinfo($ch);
395                 $http_code = $curl_info['http_code'];
396                 curl_close($ch);
397
398                 $this->profiler->stopRecording();
399
400                 if ($http_code == 0) {
401                         return $url;
402                 }
403
404                 if (in_array($http_code, ['301', '302'])) {
405                         if (!empty($curl_info['redirect_url'])) {
406                                 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
407                         } elseif (!empty($curl_info['location'])) {
408                                 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
409                         }
410                 }
411
412                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
413                 if (!$fetchbody) {
414                         return $this->finalUrl($url, ++$depth, true);
415                 }
416
417                 // if the file is too large then exit
418                 if ($curl_info["download_content_length"] > 1000000) {
419                         return $url;
420                 }
421
422                 // if it isn't a HTML file then exit
423                 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
424                         return $url;
425                 }
426
427                 $this->profiler->startRecording('network');
428
429                 $ch = curl_init();
430                 curl_setopt($ch, CURLOPT_URL, $url);
431                 curl_setopt($ch, CURLOPT_HEADER, 0);
432                 curl_setopt($ch, CURLOPT_NOBODY, 0);
433                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
434                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
435                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
436                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
437
438                 $body = curl_exec($ch);
439                 curl_close($ch);
440
441                 $this->profiler->stopRecording();
442
443                 if (trim($body) == "") {
444                         return $url;
445                 }
446
447                 // Check for redirect in meta elements
448                 $doc = new DOMDocument();
449                 @$doc->loadHTML($body);
450
451                 $xpath = new DomXPath($doc);
452
453                 $list = $xpath->query("//meta[@content]");
454                 foreach ($list as $node) {
455                         $attr = [];
456                         if ($node->attributes->length) {
457                                 foreach ($node->attributes as $attribute) {
458                                         $attr[$attribute->name] = $attribute->value;
459                                 }
460                         }
461
462                         if (@$attr["http-equiv"] == 'refresh') {
463                                 $path = $attr["content"];
464                                 $pathinfo = explode(";", $path);
465                                 foreach ($pathinfo as $value) {
466                                         if (substr(strtolower($value), 0, 4) == "url=") {
467                                                 return $this->finalUrl(substr($value, 4), ++$depth);
468                                         }
469                                 }
470                         }
471                 }
472
473                 return $url;
474         }
475
476         /**
477          * {@inheritDoc}
478          *
479          * @param int $redirects The recursion counter for internal use - default 0
480          *
481          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
482          */
483         public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', &$redirects = 0)
484         {
485                 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar, $redirects);
486
487                 return $ret->getBody();
488         }
489
490         /**
491          * {@inheritDoc}
492          *
493          * @param int $redirects The recursion counter for internal use - default 0
494          *
495          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
496          */
497         public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', &$redirects = 0)
498         {
499                 return $this->get(
500                         $url,
501                         [
502                                 'timeout'        => $timeout,
503                                 'accept_content' => $accept_content,
504                                 'cookiejar'      => $cookiejar
505                         ]
506                 );
507         }
508
509         /**
510          * {@inheritDoc}
511          */
512         public function getUserAgent()
513         {
514                 return
515                         FRIENDICA_PLATFORM . " '" .
516                         FRIENDICA_CODENAME . "' " .
517                         FRIENDICA_VERSION . '-' .
518                         DB_UPDATE_VERSION . '; ' .
519                         $this->baseUrl;
520         }
521 }