3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU APGL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Network;
27 use Friendica\Core\Config\IConfig;
28 use Friendica\Core\Logger;
29 use Friendica\Core\System;
31 use Friendica\Util\Network;
32 use Friendica\Util\Profiler;
33 use Psr\Log\LoggerInterface;
36 * Performs HTTP requests to a given URL
40 /** @var LoggerInterface */
49 public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, App\BaseURL $baseUrl)
51 $this->logger = $logger;
52 $this->profiler = $profiler;
53 $this->config = $config;
54 $this->baseUrl = $baseUrl->get();
60 * @param string $url URL to fetch
61 * @param bool $binary default false
62 * TRUE if asked to return binary results (file download)
63 * @param array $opts (optional parameters) assoziative array with:
64 * 'accept_content' => supply Accept: header with 'accept_content' as the value
65 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
66 * 'http_auth' => username:password
67 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
68 * 'nobody' => only return the header
69 * 'cookiejar' => path to cookie jar file
70 * 'header' => header array
71 * @param int $redirects The recursion counter for internal use - default 0
74 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
76 public function curl(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
78 $stamp1 = microtime(true);
80 if (strlen($url) > 1000) {
81 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
82 return CurlResult::createErrorCurl(substr($url, 0, 200));
86 $parts = parse_url($url);
87 $path_parts = explode('/', $parts['path'] ?? '');
88 foreach ($path_parts as $part) {
89 if (strlen($part) <> mb_strlen($part)) {
90 $parts2[] = rawurlencode($part);
95 $parts['path'] = implode('/', $parts2);
96 $url = Network::unparseURL($parts);
98 if (Network::isUrlBlocked($url)) {
99 $this->logger->info('Domain is blocked.', ['url' => $url]);
100 return CurlResult::createErrorCurl($url);
103 $ch = @curl_init($url);
105 if (($redirects > 8) || (!$ch)) {
106 return CurlResult::createErrorCurl($url);
109 @curl_setopt($ch, CURLOPT_HEADER, true);
111 if (!empty($opts['cookiejar'])) {
112 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
113 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
116 // These settings aren't needed. We're following the location already.
117 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
118 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
120 if (!empty($opts['accept_content'])) {
124 ['Accept: ' . $opts['accept_content']]
128 if (!empty($opts['header'])) {
129 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
132 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
133 @curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
135 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
138 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
141 // Without this setting it seems as if some webservers send compressed content
142 // This seems to confuse curl so that it shows this uncompressed.
143 /// @todo We could possibly set this value to "gzip" or something similar
144 curl_setopt($ch, CURLOPT_ENCODING, '');
146 if (!empty($opts['headers'])) {
147 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
150 if (!empty($opts['nobody'])) {
151 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
154 if (!empty($opts['timeout'])) {
155 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
157 $curl_time = $this->config->get('system', 'curl_timeout', 60);
158 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
161 // by default we will allow self-signed certs
162 // but you can override this
164 $check_cert = $this->config->get('system', 'verifyssl');
165 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
168 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
171 $proxy = $this->config->get('system', 'proxy');
173 if (!empty($proxy)) {
174 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
175 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
176 $proxyuser = $this->config->get('system', 'proxyuser');
178 if (!empty($proxyuser)) {
179 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
183 if ($this->config->get('system', 'ipv4_resolve', false)) {
184 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
188 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
191 // don't let curl abort the entire application
192 // if it throws any errors.
194 $s = @curl_exec($ch);
195 $curl_info = @curl_getinfo($ch);
197 // Special treatment for HTTP Code 416
198 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
199 if (($curl_info['http_code'] == 416) && ($range > 0)) {
200 @curl_setopt($ch, CURLOPT_RANGE, '');
201 $s = @curl_exec($ch);
202 $curl_info = @curl_getinfo($ch);
205 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
207 if ($curlResponse->isRedirectUrl()) {
209 $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
211 return self::curl($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
216 $this->profiler->saveTimestamp($stamp1, 'network', System::callstack());
218 return $curlResponse;
222 * Send POST request to $url
224 * @param string $url URL to post
225 * @param mixed $params array of POST variables
226 * @param array $headers HTTP headers
227 * @param int $redirects Recursion counter for internal use - default = 0
228 * @param int $timeout The timeout in seconds, default system config value or 60 seconds
230 * @return CurlResult The content
231 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
233 public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
235 $stamp1 = microtime(true);
237 if (Network::isUrlBlocked($url)) {
238 $this->logger->info('Domain is blocked.' . ['url' => $url]);
239 return CurlResult::createErrorCurl($url);
242 $ch = curl_init($url);
244 if (($redirects > 8) || (!$ch)) {
245 return CurlResult::createErrorCurl($url);
248 $this->logger->debug('Post_url: start.', ['url' => $url]);
250 curl_setopt($ch, CURLOPT_HEADER, true);
251 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
252 curl_setopt($ch, CURLOPT_POST, 1);
253 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
254 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
256 if ($this->config->get('system', 'ipv4_resolve', false)) {
257 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
260 if (intval($timeout)) {
261 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
263 $curl_time = $this->config->get('system', 'curl_timeout', 60);
264 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
267 if (!empty($headers)) {
268 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
271 $check_cert = $this->config->get('system', 'verifyssl');
272 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
275 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
278 $proxy = $this->config->get('system', 'proxy');
280 if (!empty($proxy)) {
281 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
282 curl_setopt($ch, CURLOPT_PROXY, $proxy);
283 $proxyuser = $this->config->get('system', 'proxyuser');
284 if (!empty($proxyuser)) {
285 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
289 // don't let curl abort the entire application
290 // if it throws any errors.
292 $s = @curl_exec($ch);
294 $curl_info = curl_getinfo($ch);
296 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
298 if ($curlResponse->isRedirectUrl()) {
300 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
302 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
307 $this->profiler->saveTimestamp($stamp1, 'network', System::callstack());
309 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
310 if ($curlResponse->getReturnCode() == 417) {
313 if (empty($headers)) {
314 $headers = ['Expect:'];
316 if (!in_array('Expect:', $headers)) {
317 array_push($headers, 'Expect:');
320 Logger::info('Server responds with 417, applying workaround', ['url' => $url]);
321 return self::post($url, $params, $headers, $redirects, $timeout);
324 Logger::log('post_url: end ' . $url, Logger::DATA);
326 return $curlResponse;
330 * Returns the original URL of the provided URL
332 * This function strips tracking query params and follows redirections, either
333 * through HTTP code or meta refresh tags. Stops after 10 redirections.
335 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
337 * @see ParseUrl::getSiteinfo
339 * @param string $url A user-submitted URL
340 * @param int $depth The current redirection recursion level (internal)
341 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
342 * @return string A canonical URL
343 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
345 public static function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
347 $url = Network::stripTrackingQueryParams($url);
353 $url = trim($url, "'");
355 $stamp1 = microtime(true);
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_TIMEOUT, 10);
362 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
363 curl_setopt($ch, CURLOPT_USERAGENT, DI::httpRequest()->getUserAgent());
366 $curl_info = @curl_getinfo($ch);
367 $http_code = $curl_info['http_code'];
370 DI::profiler()->saveTimestamp($stamp1, "network", System::callstack());
372 if ($http_code == 0) {
376 if (in_array($http_code, ['301', '302'])) {
377 if (!empty($curl_info['redirect_url'])) {
378 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
379 } elseif (!empty($curl_info['location'])) {
380 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
384 // Check for redirects in the meta elements of the body if there are no redirects in the header.
386 return self::finalUrl($url, ++$depth, true);
389 // if the file is too large then exit
390 if ($curl_info["download_content_length"] > 1000000) {
394 // if it isn't a HTML file then exit
395 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
399 $stamp1 = microtime(true);
402 curl_setopt($ch, CURLOPT_URL, $url);
403 curl_setopt($ch, CURLOPT_HEADER, 0);
404 curl_setopt($ch, CURLOPT_NOBODY, 0);
405 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
406 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
407 curl_setopt($ch, CURLOPT_USERAGENT, DI::httpRequest()->getUserAgent());
409 $body = curl_exec($ch);
412 DI::profiler()->saveTimestamp($stamp1, "network", System::callstack());
414 if (trim($body) == "") {
418 // Check for redirect in meta elements
419 $doc = new DOMDocument();
420 @$doc->loadHTML($body);
422 $xpath = new DomXPath($doc);
424 $list = $xpath->query("//meta[@content]");
425 foreach ($list as $node) {
427 if ($node->attributes->length) {
428 foreach ($node->attributes as $attribute) {
429 $attr[$attribute->name] = $attribute->value;
433 if (@$attr["http-equiv"] == 'refresh') {
434 $path = $attr["content"];
435 $pathinfo = explode(";", $path);
436 foreach ($pathinfo as $value) {
437 if (substr(strtolower($value), 0, 4) == "url=") {
438 return self::finalUrl(substr($value, 4), ++$depth);
450 * If binary flag is true, return binary results.
451 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
452 * to preserve cookies from one request to the next.
454 * @param string $url URL to fetch
455 * @param bool $binary default false
456 * TRUE if asked to return binary results (file download)
457 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
458 * @param string $accept_content supply Accept: header with 'accept_content' as the value
459 * @param string $cookiejar Path to cookie jar file
460 * @param int $redirects The recursion counter for internal use - default 0
462 * @return string The fetched content
463 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
465 public function fetchUrl(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
467 $ret = $this->fetchUrlFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
469 return $ret->getBody();
473 * Curl wrapper with array of return values.
475 * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
476 * all the information collected during the fetch.
478 * @param string $url URL to fetch
479 * @param bool $binary default false
480 * TRUE if asked to return binary results (file download)
481 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
482 * @param string $accept_content supply Accept: header with 'accept_content' as the value
483 * @param string $cookiejar Path to cookie jar file
484 * @param int $redirects The recursion counter for internal use - default 0
486 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
487 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
489 public function fetchUrlFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
495 'timeout' => $timeout,
496 'accept_content' => $accept_content,
497 'cookiejar' => $cookiejar
504 * Returns the current UserAgent as a String
506 * @return string the UserAgent as a String
508 public function getUserAgent()
511 FRIENDICA_PLATFORM . " '" .
512 FRIENDICA_CODENAME . "' " .
513 FRIENDICA_VERSION . '-' .
514 DB_UPDATE_VERSION . '; ' .