]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPRequest.php
Merge pull request #1 from friendica/develop
[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 Psr\Log\LoggerInterface;
32
33 /**
34  * Performs HTTP requests to a given URL
35  */
36 class HTTPRequest implements IHTTPRequest
37 {
38         /** @var LoggerInterface */
39         private $logger;
40         /** @var Profiler */
41         private $profiler;
42         /** @var IConfig */
43         private $config;
44         /** @var string */
45         private $baseUrl;
46
47         public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, App\BaseURL $baseUrl)
48         {
49                 $this->logger   = $logger;
50                 $this->profiler = $profiler;
51                 $this->config   = $config;
52                 $this->baseUrl  = $baseUrl->get();
53         }
54
55         /**
56          * {@inheritDoc}
57          *
58          * @param int $redirects The recursion counter for internal use - default 0
59          *
60          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
61          */
62         public function get(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
63         {
64                 $stamp1 = microtime(true);
65
66                 if (strlen($url) > 1000) {
67                         $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
68                         return CurlResult::createErrorCurl(substr($url, 0, 200));
69                 }
70
71                 $parts2     = [];
72                 $parts      = parse_url($url);
73                 $path_parts = explode('/', $parts['path'] ?? '');
74                 foreach ($path_parts as $part) {
75                         if (strlen($part) <> mb_strlen($part)) {
76                                 $parts2[] = rawurlencode($part);
77                         } else {
78                                 $parts2[] = $part;
79                         }
80                 }
81                 $parts['path'] = implode('/', $parts2);
82                 $url           = Network::unparseURL($parts);
83
84                 if (Network::isUrlBlocked($url)) {
85                         $this->logger->info('Domain is blocked.', ['url' => $url]);
86                         return CurlResult::createErrorCurl($url);
87                 }
88
89                 $ch = @curl_init($url);
90
91                 if (($redirects > 8) || (!$ch)) {
92                         return CurlResult::createErrorCurl($url);
93                 }
94
95                 @curl_setopt($ch, CURLOPT_HEADER, true);
96
97                 if (!empty($opts['cookiejar'])) {
98                         curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
99                         curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
100                 }
101
102                 // These settings aren't needed. We're following the location already.
103                 //      @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
104                 //      @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
105
106                 if (!empty($opts['accept_content'])) {
107                         curl_setopt(
108                                 $ch,
109                                 CURLOPT_HTTPHEADER,
110                                 ['Accept: ' . $opts['accept_content']]
111                         );
112                 }
113
114                 if (!empty($opts['header'])) {
115                         curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
116                 }
117
118                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
119                 @curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
120
121                 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
122
123                 if ($range > 0) {
124                         @curl_setopt($ch, 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                 curl_setopt($ch, CURLOPT_ENCODING, '');
131
132                 if (!empty($opts['headers'])) {
133                         @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
134                 }
135
136                 if (!empty($opts['nobody'])) {
137                         @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
138                 }
139
140                 if (!empty($opts['timeout'])) {
141                         @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
142                 } else {
143                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
144                         @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
145                 }
146
147                 // by default we will allow self-signed certs
148                 // but you can override this
149
150                 $check_cert = $this->config->get('system', 'verifyssl');
151                 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
152
153                 if ($check_cert) {
154                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
155                 }
156
157                 $proxy = $this->config->get('system', 'proxy');
158
159                 if (!empty($proxy)) {
160                         @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
161                         @curl_setopt($ch, CURLOPT_PROXY, $proxy);
162                         $proxyuser = $this->config->get('system', 'proxyuser');
163
164                         if (!empty($proxyuser)) {
165                                 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
166                         }
167                 }
168
169                 if ($this->config->get('system', 'ipv4_resolve', false)) {
170                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
171                 }
172
173                 if ($binary) {
174                         @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
175                 }
176
177                 // don't let curl abort the entire application
178                 // if it throws any errors.
179
180                 $s         = @curl_exec($ch);
181                 $curl_info = @curl_getinfo($ch);
182
183                 // Special treatment for HTTP Code 416
184                 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
185                 if (($curl_info['http_code'] == 416) && ($range > 0)) {
186                         @curl_setopt($ch, CURLOPT_RANGE, '');
187                         $s         = @curl_exec($ch);
188                         $curl_info = @curl_getinfo($ch);
189                 }
190
191                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
192
193                 if ($curlResponse->isRedirectUrl()) {
194                         $redirects++;
195                         $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
196                         @curl_close($ch);
197                         return $this->get($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
198                 }
199
200                 @curl_close($ch);
201
202                 $this->profiler->saveTimestamp($stamp1, 'network');
203
204                 return $curlResponse;
205         }
206
207         /**
208          * {@inheritDoc}
209          *
210          * @param int $redirects The recursion counter for internal use - default 0
211          *
212          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
213          */
214         public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
215         {
216                 $stamp1 = microtime(true);
217
218                 if (Network::isUrlBlocked($url)) {
219                         $this->logger->info('Domain is blocked.' . ['url' => $url]);
220                         return CurlResult::createErrorCurl($url);
221                 }
222
223                 $ch = curl_init($url);
224
225                 if (($redirects > 8) || (!$ch)) {
226                         return CurlResult::createErrorCurl($url);
227                 }
228
229                 $this->logger->debug('Post_url: start.', ['url' => $url]);
230
231                 curl_setopt($ch, CURLOPT_HEADER, true);
232                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
233                 curl_setopt($ch, CURLOPT_POST, 1);
234                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
235                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
236
237                 if ($this->config->get('system', 'ipv4_resolve', false)) {
238                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
239                 }
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 ($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                 $url = Network::stripTrackingQueryParams($url);
321
322                 if ($depth > 10) {
323                         return $url;
324                 }
325
326                 $url = trim($url, "'");
327
328                 $stamp1 = microtime(true);
329
330                 $ch = curl_init();
331                 curl_setopt($ch, CURLOPT_URL, $url);
332                 curl_setopt($ch, CURLOPT_HEADER, 1);
333                 curl_setopt($ch, CURLOPT_NOBODY, 1);
334                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
335                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
336                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
337
338                 curl_exec($ch);
339                 $curl_info = @curl_getinfo($ch);
340                 $http_code = $curl_info['http_code'];
341                 curl_close($ch);
342
343                 $this->profiler->saveTimestamp($stamp1, "network");
344
345                 if ($http_code == 0) {
346                         return $url;
347                 }
348
349                 if (in_array($http_code, ['301', '302'])) {
350                         if (!empty($curl_info['redirect_url'])) {
351                                 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
352                         } elseif (!empty($curl_info['location'])) {
353                                 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
354                         }
355                 }
356
357                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
358                 if (!$fetchbody) {
359                         return $this->finalUrl($url, ++$depth, true);
360                 }
361
362                 // if the file is too large then exit
363                 if ($curl_info["download_content_length"] > 1000000) {
364                         return $url;
365                 }
366
367                 // if it isn't a HTML file then exit
368                 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
369                         return $url;
370                 }
371
372                 $stamp1 = microtime(true);
373
374                 $ch = curl_init();
375                 curl_setopt($ch, CURLOPT_URL, $url);
376                 curl_setopt($ch, CURLOPT_HEADER, 0);
377                 curl_setopt($ch, CURLOPT_NOBODY, 0);
378                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
379                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
380                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
381
382                 $body = curl_exec($ch);
383                 curl_close($ch);
384
385                 $this->profiler->saveTimestamp($stamp1, "network");
386
387                 if (trim($body) == "") {
388                         return $url;
389                 }
390
391                 // Check for redirect in meta elements
392                 $doc = new DOMDocument();
393                 @$doc->loadHTML($body);
394
395                 $xpath = new DomXPath($doc);
396
397                 $list = $xpath->query("//meta[@content]");
398                 foreach ($list as $node) {
399                         $attr = [];
400                         if ($node->attributes->length) {
401                                 foreach ($node->attributes as $attribute) {
402                                         $attr[$attribute->name] = $attribute->value;
403                                 }
404                         }
405
406                         if (@$attr["http-equiv"] == 'refresh') {
407                                 $path = $attr["content"];
408                                 $pathinfo = explode(";", $path);
409                                 foreach ($pathinfo as $value) {
410                                         if (substr(strtolower($value), 0, 4) == "url=") {
411                                                 return $this->finalUrl(substr($value, 4), ++$depth);
412                                         }
413                                 }
414                         }
415                 }
416
417                 return $url;
418         }
419
420         /**
421          * {@inheritDoc}
422          *
423          * @param int $redirects The recursion counter for internal use - default 0
424          *
425          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
426          */
427         public function fetch(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
428         {
429                 $ret = $this->fetchFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
430
431                 return $ret->getBody();
432         }
433
434         /**
435          * {@inheritDoc}
436          *
437          * @param int $redirects The recursion counter for internal use - default 0
438          *
439          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
440          */
441         public function fetchFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
442         {
443                 return $this->get(
444                         $url,
445                         $binary,
446                         [
447                                 'timeout'        => $timeout,
448                                 'accept_content' => $accept_content,
449                                 'cookiejar'      => $cookiejar
450                         ],
451                         $redirects
452                 );
453         }
454
455         /**
456          * {@inheritDoc}
457          */
458         public function getUserAgent()
459         {
460                 return
461                         FRIENDICA_PLATFORM . " '" .
462                         FRIENDICA_CODENAME . "' " .
463                         FRIENDICA_VERSION . '-' .
464                         DB_UPDATE_VERSION . '; ' .
465                         $this->baseUrl;
466         }
467 }