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