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