]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPClient.php
3011696b8bdfa5291c1116010667e245d4f37bec
[friendica.git] / src / Network / HTTPClient.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\Core\Config\IConfig;
27 use Friendica\Core\System;
28 use Friendica\Util\Network;
29 use Friendica\Util\Profiler;
30 use GuzzleHttp\Client;
31 use GuzzleHttp\Cookie\FileCookieJar;
32 use GuzzleHttp\Exception\RequestException;
33 use GuzzleHttp\Exception\TransferException;
34 use GuzzleHttp\RequestOptions;
35 use Psr\Http\Message\ResponseInterface;
36 use Psr\Log\LoggerInterface;
37
38 /**
39  * Performs HTTP requests to a given URL
40  */
41 class HTTPClient implements IHTTPClient
42 {
43         /** @var LoggerInterface */
44         private $logger;
45         /** @var Profiler */
46         private $profiler;
47         /** @var IConfig */
48         private $config;
49         /** @var string */
50         private $userAgent;
51         /** @var Client */
52         private $client;
53
54         public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, string $userAgent, Client $client)
55         {
56                 $this->logger    = $logger;
57                 $this->profiler  = $profiler;
58                 $this->config    = $config;
59                 $this->userAgent = $userAgent;
60                 $this->client    = $client;
61         }
62
63         /**
64          * @throws HTTPException\InternalServerErrorException
65          */
66         protected function request(string $method, string $url, array $opts = []): IHTTPResult
67         {
68                 $this->profiler->startRecording('network');
69
70                 if (Network::isLocalLink($url)) {
71                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
72                 }
73
74                 if (strlen($url) > 1000) {
75                         $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
76                         $this->profiler->stopRecording();
77                         return CurlResult::createErrorCurl(substr($url, 0, 200));
78                 }
79
80                 $parts2     = [];
81                 $parts      = parse_url($url);
82                 $path_parts = explode('/', $parts['path'] ?? '');
83                 foreach ($path_parts as $part) {
84                         if (strlen($part) <> mb_strlen($part)) {
85                                 $parts2[] = rawurlencode($part);
86                         } else {
87                                 $parts2[] = $part;
88                         }
89                 }
90                 $parts['path'] = implode('/', $parts2);
91                 $url           = Network::unparseURL($parts);
92
93                 if (Network::isUrlBlocked($url)) {
94                         $this->logger->info('Domain is blocked.', ['url' => $url]);
95                         $this->profiler->stopRecording();
96                         return CurlResult::createErrorCurl($url);
97                 }
98
99                 $conf = [];
100
101                 if (!empty($opts['cookiejar'])) {
102                         $jar                           = new FileCookieJar($opts['cookiejar']);
103                         $conf[RequestOptions::COOKIES] = $jar;
104                 }
105
106                 $header = [];
107
108                 if (!empty($opts['accept_content'])) {
109                         array_push($header, 'Accept: ' . $opts['accept_content']);
110                 }
111
112                 if (!empty($opts['header'])) {
113                         $header = array_merge($opts['header'], $header);
114                 }
115
116                 if (!empty($opts['headers'])) {
117                         $this->logger->notice('Wrong option \'headers\' used.');
118                         $header = array_merge($opts['headers'], $header);
119                 }
120
121                 $conf[RequestOptions::HEADERS] = array_merge($this->client->getConfig(RequestOptions::HEADERS), $header);
122
123                 if (!empty($opts['timeout'])) {
124                         $conf[RequestOptions::TIMEOUT] = $opts['timeout'];
125                 }
126
127                 $conf[RequestOptions::ON_HEADERS] = function (ResponseInterface $response) use ($opts) {
128                         if (!empty($opts['content_length']) &&
129                                 $response->getHeaderLine('Content-Length') > $opts['content_length']) {
130                                 throw new TransferException('The file is too big!');
131                         }
132                 };
133
134                 try {
135                         $response = $this->client->$method($url, $conf);
136                         return new GuzzleResponse($response, $url);
137                 } catch (TransferException $exception) {
138                         if ($exception instanceof RequestException &&
139                                 $exception->hasResponse()) {
140                                 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), '');
141                         } else {
142                                 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), '');
143                         }
144                 } finally {
145                         $this->profiler->stopRecording();
146                 }
147         }
148
149         /** {@inheritDoc}
150          *
151          * @throws HTTPException\InternalServerErrorException
152          */
153         public function head(string $url, array $opts = []): IHTTPResult
154         {
155                 return $this->request('head', $url, $opts);
156         }
157
158         /**
159          * {@inheritDoc}
160          */
161         public function get(string $url, array $opts = []): IHTTPResult
162         {
163                 return $this->request('get', $url, $opts);
164         }
165
166         /**
167          * {@inheritDoc}
168          *
169          * @param int $redirects The recursion counter for internal use - default 0
170          *
171          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
172          */
173         public function post(string $url, $params, array $headers = [], int $timeout = 0, &$redirects = 0)
174         {
175                 $this->profiler->startRecording('network');
176
177                 if (Network::isLocalLink($url)) {
178                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
179                 }
180
181                 if (Network::isUrlBlocked($url)) {
182                         $this->logger->info('Domain is blocked.' . ['url' => $url]);
183                         $this->profiler->stopRecording();
184                         return CurlResult::createErrorCurl($url);
185                 }
186
187                 $ch = curl_init($url);
188
189                 if (($redirects > 8) || (!$ch)) {
190                         $this->profiler->stopRecording();
191                         return CurlResult::createErrorCurl($url);
192                 }
193
194                 $this->logger->debug('Post_url: start.', ['url' => $url]);
195
196                 curl_setopt($ch, CURLOPT_HEADER, true);
197                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
198                 curl_setopt($ch, CURLOPT_POST, 1);
199                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
200                 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
201
202                 if ($this->config->get('system', 'ipv4_resolve', false)) {
203                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
204                 }
205
206                 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
207
208                 if (intval($timeout)) {
209                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
210                 } else {
211                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
212                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
213                 }
214
215                 if (!empty($headers)) {
216                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
217                 }
218
219                 $check_cert = $this->config->get('system', 'verifyssl');
220                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
221
222                 if ($check_cert) {
223                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
224                 }
225
226                 $proxy = $this->config->get('system', 'proxy');
227
228                 if (!empty($proxy)) {
229                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
230                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
231                         $proxyuser = $this->config->get('system', 'proxyuser');
232                         if (!empty($proxyuser)) {
233                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
234                         }
235                 }
236
237                 // don't let curl abort the entire application
238                 // if it throws any errors.
239
240                 $s = @curl_exec($ch);
241
242                 $curl_info = curl_getinfo($ch);
243
244                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
245
246                 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
247                         $redirects++;
248                         $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
249                         curl_close($ch);
250                         $this->profiler->stopRecording();
251                         return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
252                 }
253
254                 curl_close($ch);
255
256                 $this->profiler->stopRecording();
257
258                 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
259                 if ($curlResponse->getReturnCode() == 417) {
260                         $redirects++;
261
262                         if (empty($headers)) {
263                                 $headers = ['Expect:'];
264                         } else {
265                                 if (!in_array('Expect:', $headers)) {
266                                         array_push($headers, 'Expect:');
267                                 }
268                         }
269                         $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
270                         return $this->post($url, $params, $headers, $redirects, $timeout);
271                 }
272
273                 $this->logger->debug('Post_url: End.', ['url' => $url]);
274
275                 return $curlResponse;
276         }
277
278         /**
279          * {@inheritDoc}
280          */
281         public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
282         {
283                 if (Network::isLocalLink($url)) {
284                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
285                 }
286
287                 if (Network::isUrlBlocked($url)) {
288                         $this->logger->info('Domain is blocked.', ['url' => $url]);
289                         return $url;
290                 }
291
292                 if (Network::isRedirectBlocked($url)) {
293                         $this->logger->info('Domain should not be redirected.', ['url' => $url]);
294                         return $url;
295                 }
296
297                 $url = Network::stripTrackingQueryParams($url);
298
299                 if ($depth > 10) {
300                         return $url;
301                 }
302
303                 $url = trim($url, "'");
304
305                 $this->profiler->startRecording('network');
306
307                 $ch = curl_init();
308                 curl_setopt($ch, CURLOPT_URL, $url);
309                 curl_setopt($ch, CURLOPT_HEADER, 1);
310                 curl_setopt($ch, CURLOPT_NOBODY, 1);
311                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
312                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
313                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
314                 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
315
316                 curl_exec($ch);
317                 $curl_info = @curl_getinfo($ch);
318                 $http_code = $curl_info['http_code'];
319                 curl_close($ch);
320
321                 $this->profiler->stopRecording();
322
323                 if ($http_code == 0) {
324                         return $url;
325                 }
326
327                 if (in_array($http_code, ['301', '302'])) {
328                         if (!empty($curl_info['redirect_url'])) {
329                                 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
330                         } elseif (!empty($curl_info['location'])) {
331                                 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
332                         }
333                 }
334
335                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
336                 if (!$fetchbody) {
337                         return $this->finalUrl($url, ++$depth, true);
338                 }
339
340                 // if the file is too large then exit
341                 if ($curl_info["download_content_length"] > 1000000) {
342                         return $url;
343                 }
344
345                 // if it isn't a HTML file then exit
346                 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
347                         return $url;
348                 }
349
350                 $this->profiler->startRecording('network');
351
352                 $ch = curl_init();
353                 curl_setopt($ch, CURLOPT_URL, $url);
354                 curl_setopt($ch, CURLOPT_HEADER, 0);
355                 curl_setopt($ch, CURLOPT_NOBODY, 0);
356                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
357                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
358                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
359                 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
360
361                 $body = curl_exec($ch);
362                 curl_close($ch);
363
364                 $this->profiler->stopRecording();
365
366                 if (trim($body) == "") {
367                         return $url;
368                 }
369
370                 // Check for redirect in meta elements
371                 $doc = new DOMDocument();
372                 @$doc->loadHTML($body);
373
374                 $xpath = new DomXPath($doc);
375
376                 $list = $xpath->query("//meta[@content]");
377                 foreach ($list as $node) {
378                         $attr = [];
379                         if ($node->attributes->length) {
380                                 foreach ($node->attributes as $attribute) {
381                                         $attr[$attribute->name] = $attribute->value;
382                                 }
383                         }
384
385                         if (@$attr["http-equiv"] == 'refresh') {
386                                 $path = $attr["content"];
387                                 $pathinfo = explode(";", $path);
388                                 foreach ($pathinfo as $value) {
389                                         if (substr(strtolower($value), 0, 4) == "url=") {
390                                                 return $this->finalUrl(substr($value, 4), ++$depth);
391                                         }
392                                 }
393                         }
394                 }
395
396                 return $url;
397         }
398
399         /**
400          * {@inheritDoc}
401          */
402         public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
403         {
404                 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar);
405
406                 return $ret->getBody();
407         }
408
409         /**
410          * {@inheritDoc}
411          */
412         public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
413         {
414                 return $this->get(
415                         $url,
416                         [
417                                 'timeout'        => $timeout,
418                                 'accept_content' => $accept_content,
419                                 'cookiejar'      => $cookiejar
420                         ]
421                 );
422         }
423 }