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\System;
29 use Friendica\Util\Network;
30 use Friendica\Util\Profiler;
31 use Psr\Log\LoggerInterface;
34 * Performs HTTP requests to a given URL
38 /** @var LoggerInterface */
47 public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, App\BaseURL $baseUrl)
49 $this->logger = $logger;
50 $this->profiler = $profiler;
51 $this->config = $config;
52 $this->baseUrl = $baseUrl->get();
58 * @param string $url URL to fetch
59 * @param bool $binary default false
60 * TRUE if asked to return binary results (file download)
61 * @param array $opts (optional parameters) assoziative array with:
62 * 'accept_content' => supply Accept: header with 'accept_content' as the value
63 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
64 * 'http_auth' => username:password
65 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
66 * 'nobody' => only return the header
67 * 'cookiejar' => path to cookie jar file
68 * 'header' => header array
69 * @param int $redirects The recursion counter for internal use - default 0
72 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
74 public function get(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
76 $stamp1 = microtime(true);
78 if (strlen($url) > 1000) {
79 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
80 return CurlResult::createErrorCurl(substr($url, 0, 200));
84 $parts = parse_url($url);
85 $path_parts = explode('/', $parts['path'] ?? '');
86 foreach ($path_parts as $part) {
87 if (strlen($part) <> mb_strlen($part)) {
88 $parts2[] = rawurlencode($part);
93 $parts['path'] = implode('/', $parts2);
94 $url = Network::unparseURL($parts);
96 if (Network::isUrlBlocked($url)) {
97 $this->logger->info('Domain is blocked.', ['url' => $url]);
98 return CurlResult::createErrorCurl($url);
101 $ch = @curl_init($url);
103 if (($redirects > 8) || (!$ch)) {
104 return CurlResult::createErrorCurl($url);
107 @curl_setopt($ch, CURLOPT_HEADER, true);
109 if (!empty($opts['cookiejar'])) {
110 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
111 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
114 // These settings aren't needed. We're following the location already.
115 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
116 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
118 if (!empty($opts['accept_content'])) {
122 ['Accept: ' . $opts['accept_content']]
126 if (!empty($opts['header'])) {
127 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
130 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
131 @curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
133 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
136 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
139 // Without this setting it seems as if some webservers send compressed content
140 // This seems to confuse curl so that it shows this uncompressed.
141 /// @todo We could possibly set this value to "gzip" or something similar
142 curl_setopt($ch, CURLOPT_ENCODING, '');
144 if (!empty($opts['headers'])) {
145 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
148 if (!empty($opts['nobody'])) {
149 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
152 if (!empty($opts['timeout'])) {
153 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
155 $curl_time = $this->config->get('system', 'curl_timeout', 60);
156 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
159 // by default we will allow self-signed certs
160 // but you can override this
162 $check_cert = $this->config->get('system', 'verifyssl');
163 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
166 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
169 $proxy = $this->config->get('system', 'proxy');
171 if (!empty($proxy)) {
172 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
173 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
174 $proxyuser = $this->config->get('system', 'proxyuser');
176 if (!empty($proxyuser)) {
177 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
181 if ($this->config->get('system', 'ipv4_resolve', false)) {
182 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
186 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
189 // don't let curl abort the entire application
190 // if it throws any errors.
192 $s = @curl_exec($ch);
193 $curl_info = @curl_getinfo($ch);
195 // Special treatment for HTTP Code 416
196 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
197 if (($curl_info['http_code'] == 416) && ($range > 0)) {
198 @curl_setopt($ch, CURLOPT_RANGE, '');
199 $s = @curl_exec($ch);
200 $curl_info = @curl_getinfo($ch);
203 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
205 if ($curlResponse->isRedirectUrl()) {
207 $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
209 return $this->get($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
214 $this->profiler->saveTimestamp($stamp1, 'network', System::callstack());
216 return $curlResponse;
220 * Send POST request to $url
222 * @param string $url URL to post
223 * @param mixed $params array of POST variables
224 * @param array $headers HTTP headers
225 * @param int $redirects Recursion counter for internal use - default = 0
226 * @param int $timeout The timeout in seconds, default system config value or 60 seconds
228 * @return CurlResult The content
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
233 $stamp1 = microtime(true);
235 if (Network::isUrlBlocked($url)) {
236 $this->logger->info('Domain is blocked.' . ['url' => $url]);
237 return CurlResult::createErrorCurl($url);
240 $ch = curl_init($url);
242 if (($redirects > 8) || (!$ch)) {
243 return CurlResult::createErrorCurl($url);
246 $this->logger->debug('Post_url: start.', ['url' => $url]);
248 curl_setopt($ch, CURLOPT_HEADER, true);
249 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
250 curl_setopt($ch, CURLOPT_POST, 1);
251 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
252 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
254 if ($this->config->get('system', 'ipv4_resolve', false)) {
255 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
258 if (intval($timeout)) {
259 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
261 $curl_time = $this->config->get('system', 'curl_timeout', 60);
262 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
265 if (!empty($headers)) {
266 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
269 $check_cert = $this->config->get('system', 'verifyssl');
270 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
273 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
276 $proxy = $this->config->get('system', 'proxy');
278 if (!empty($proxy)) {
279 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
280 curl_setopt($ch, CURLOPT_PROXY, $proxy);
281 $proxyuser = $this->config->get('system', 'proxyuser');
282 if (!empty($proxyuser)) {
283 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
287 // don't let curl abort the entire application
288 // if it throws any errors.
290 $s = @curl_exec($ch);
292 $curl_info = curl_getinfo($ch);
294 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
296 if ($curlResponse->isRedirectUrl()) {
298 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
300 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
305 $this->profiler->saveTimestamp($stamp1, 'network', System::callstack());
307 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
308 if ($curlResponse->getReturnCode() == 417) {
311 if (empty($headers)) {
312 $headers = ['Expect:'];
314 if (!in_array('Expect:', $headers)) {
315 array_push($headers, 'Expect:');
318 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
319 return $this->post($url, $params, $headers, $redirects, $timeout);
322 $this->logger->debug('Post_url: End.', ['url' => $url]);
324 return $curlResponse;
328 * Returns the original URL of the provided URL
330 * This function strips tracking query params and follows redirections, either
331 * through HTTP code or meta refresh tags. Stops after 10 redirections.
333 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
335 * @see ParseUrl::getSiteinfo
337 * @param string $url A user-submitted URL
338 * @param int $depth The current redirection recursion level (internal)
339 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
340 * @return string A canonical URL
341 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
343 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
345 $url = Network::stripTrackingQueryParams($url);
351 $url = trim($url, "'");
353 $stamp1 = microtime(true);
356 curl_setopt($ch, CURLOPT_URL, $url);
357 curl_setopt($ch, CURLOPT_HEADER, 1);
358 curl_setopt($ch, CURLOPT_NOBODY, 1);
359 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
360 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
361 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
364 $curl_info = @curl_getinfo($ch);
365 $http_code = $curl_info['http_code'];
368 $this->profiler->saveTimestamp($stamp1, "network", System::callstack());
370 if ($http_code == 0) {
374 if (in_array($http_code, ['301', '302'])) {
375 if (!empty($curl_info['redirect_url'])) {
376 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
377 } elseif (!empty($curl_info['location'])) {
378 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
382 // Check for redirects in the meta elements of the body if there are no redirects in the header.
384 return $this->finalUrl($url, ++$depth, true);
387 // if the file is too large then exit
388 if ($curl_info["download_content_length"] > 1000000) {
392 // if it isn't a HTML file then exit
393 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
397 $stamp1 = microtime(true);
400 curl_setopt($ch, CURLOPT_URL, $url);
401 curl_setopt($ch, CURLOPT_HEADER, 0);
402 curl_setopt($ch, CURLOPT_NOBODY, 0);
403 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
404 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
405 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
407 $body = curl_exec($ch);
410 $this->profiler->saveTimestamp($stamp1, "network", System::callstack());
412 if (trim($body) == "") {
416 // Check for redirect in meta elements
417 $doc = new DOMDocument();
418 @$doc->loadHTML($body);
420 $xpath = new DomXPath($doc);
422 $list = $xpath->query("//meta[@content]");
423 foreach ($list as $node) {
425 if ($node->attributes->length) {
426 foreach ($node->attributes as $attribute) {
427 $attr[$attribute->name] = $attribute->value;
431 if (@$attr["http-equiv"] == 'refresh') {
432 $path = $attr["content"];
433 $pathinfo = explode(";", $path);
434 foreach ($pathinfo as $value) {
435 if (substr(strtolower($value), 0, 4) == "url=") {
436 return $this->finalUrl(substr($value, 4), ++$depth);
448 * If binary flag is true, return binary results.
449 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
450 * to preserve cookies from one request to the next.
452 * @param string $url URL to fetch
453 * @param bool $binary default false
454 * TRUE if asked to return binary results (file download)
455 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
456 * @param string $accept_content supply Accept: header with 'accept_content' as the value
457 * @param string $cookiejar Path to cookie jar file
458 * @param int $redirects The recursion counter for internal use - default 0
460 * @return string The fetched content
461 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
463 public function fetchUrl(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
465 $ret = $this->fetchUrlFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
467 return $ret->getBody();
471 * Curl wrapper with array of return values.
473 * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
474 * all the information collected during the fetch.
476 * @param string $url URL to fetch
477 * @param bool $binary default false
478 * TRUE if asked to return binary results (file download)
479 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
480 * @param string $accept_content supply Accept: header with 'accept_content' as the value
481 * @param string $cookiejar Path to cookie jar file
482 * @param int $redirects The recursion counter for internal use - default 0
484 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
485 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
487 public function fetchUrlFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
493 'timeout' => $timeout,
494 'accept_content' => $accept_content,
495 'cookiejar' => $cookiejar
502 * Returns the current UserAgent as a String
504 * @return string the UserAgent as a String
506 public function getUserAgent()
509 FRIENDICA_PLATFORM . " '" .
510 FRIENDICA_CODENAME . "' " .
511 FRIENDICA_VERSION . '-' .
512 DB_UPDATE_VERSION . '; ' .