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
36 class HTTPRequest implements IHTTPRequest
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 int $redirects The recursion counter for internal use - default 0
60 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
62 public function get(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
64 $stamp1 = microtime(true);
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));
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);
81 $parts['path'] = implode('/', $parts2);
82 $url = Network::unparseURL($parts);
84 if (Network::isUrlBlocked($url)) {
85 $this->logger->info('Domain is blocked.', ['url' => $url]);
86 return CurlResult::createErrorCurl($url);
89 $ch = @curl_init($url);
91 if (($redirects > 8) || (!$ch)) {
92 return CurlResult::createErrorCurl($url);
95 @curl_setopt($ch, CURLOPT_HEADER, true);
97 if (!empty($opts['cookiejar'])) {
98 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
99 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
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);
106 if (!empty($opts['accept_content'])) {
110 ['Accept: ' . $opts['accept_content']]
114 if (!empty($opts['header'])) {
115 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
118 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
119 @curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
121 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
124 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
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, '');
132 if (!empty($opts['headers'])) {
133 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
136 if (!empty($opts['nobody'])) {
137 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
140 if (!empty($opts['timeout'])) {
141 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
143 $curl_time = $this->config->get('system', 'curl_timeout', 60);
144 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
147 // by default we will allow self-signed certs
148 // but you can override this
150 $check_cert = $this->config->get('system', 'verifyssl');
151 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
154 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
157 $proxy = $this->config->get('system', 'proxy');
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');
164 if (!empty($proxyuser)) {
165 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
169 if ($this->config->get('system', 'ipv4_resolve', false)) {
170 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
174 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
177 // don't let curl abort the entire application
178 // if it throws any errors.
180 $s = @curl_exec($ch);
181 $curl_info = @curl_getinfo($ch);
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);
191 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
193 if ($curlResponse->isRedirectUrl()) {
195 $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
197 return $this->get($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
202 $this->profiler->saveTimestamp($stamp1, 'network');
204 return $curlResponse;
210 * @param int $redirects The recursion counter for internal use - default 0
212 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
214 public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
216 $stamp1 = microtime(true);
218 if (Network::isUrlBlocked($url)) {
219 $this->logger->info('Domain is blocked.' . ['url' => $url]);
220 return CurlResult::createErrorCurl($url);
223 $ch = curl_init($url);
225 if (($redirects > 8) || (!$ch)) {
226 return CurlResult::createErrorCurl($url);
229 $this->logger->debug('Post_url: start.', ['url' => $url]);
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());
237 if ($this->config->get('system', 'ipv4_resolve', false)) {
238 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
241 if (intval($timeout)) {
242 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
244 $curl_time = $this->config->get('system', 'curl_timeout', 60);
245 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
248 if (!empty($headers)) {
249 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
252 $check_cert = $this->config->get('system', 'verifyssl');
253 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
256 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
259 $proxy = $this->config->get('system', 'proxy');
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);
270 // don't let curl abort the entire application
271 // if it throws any errors.
273 $s = @curl_exec($ch);
275 $curl_info = curl_getinfo($ch);
277 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
279 if ($curlResponse->isRedirectUrl()) {
281 $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
283 return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
288 $this->profiler->saveTimestamp($stamp1, 'network');
290 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
291 if ($curlResponse->getReturnCode() == 417) {
294 if (empty($headers)) {
295 $headers = ['Expect:'];
297 if (!in_array('Expect:', $headers)) {
298 array_push($headers, 'Expect:');
301 $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
302 return $this->post($url, $params, $headers, $redirects, $timeout);
305 $this->logger->debug('Post_url: End.', ['url' => $url]);
307 return $curlResponse;
313 public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
315 if (Network::isUrlBlocked($url)) {
316 $this->logger->info('Domain is blocked.', ['url' => $url]);
320 $url = Network::stripTrackingQueryParams($url);
326 $url = trim($url, "'");
328 $stamp1 = microtime(true);
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());
339 $curl_info = @curl_getinfo($ch);
340 $http_code = $curl_info['http_code'];
343 $this->profiler->saveTimestamp($stamp1, "network");
345 if ($http_code == 0) {
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);
357 // Check for redirects in the meta elements of the body if there are no redirects in the header.
359 return $this->finalUrl($url, ++$depth, true);
362 // if the file is too large then exit
363 if ($curl_info["download_content_length"] > 1000000) {
367 // if it isn't a HTML file then exit
368 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
372 $stamp1 = microtime(true);
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());
382 $body = curl_exec($ch);
385 $this->profiler->saveTimestamp($stamp1, "network");
387 if (trim($body) == "") {
391 // Check for redirect in meta elements
392 $doc = new DOMDocument();
393 @$doc->loadHTML($body);
395 $xpath = new DomXPath($doc);
397 $list = $xpath->query("//meta[@content]");
398 foreach ($list as $node) {
400 if ($node->attributes->length) {
401 foreach ($node->attributes as $attribute) {
402 $attr[$attribute->name] = $attribute->value;
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);
423 * @param int $redirects The recursion counter for internal use - default 0
425 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
427 public function fetch(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
429 $ret = $this->fetchFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
431 return $ret->getBody();
437 * @param int $redirects The recursion counter for internal use - default 0
439 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
441 public function fetchFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
447 'timeout' => $timeout,
448 'accept_content' => $accept_content,
449 'cookiejar' => $cookiejar
458 public function getUserAgent()
461 FRIENDICA_PLATFORM . " '" .
462 FRIENDICA_CODENAME . "' " .
463 FRIENDICA_VERSION . '-' .
464 DB_UPDATE_VERSION . '; ' .