Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1940 lines
53 KiB

<?php
/**
* @file src/Network/Probe.php
*/
namespace Friendica\Network;
/**
* @file src/Network/Probe.php
* @brief Functions for probing URL
*/
use DOMDocument;
use DomXPath;
use Friendica\Core\Cache\Cache;
use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\Protocol;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Model\Contact;
use Friendica\Model\Profile;
use Friendica\Protocol\ActivityNamespace;
use Friendica\Protocol\ActivityPub;
use Friendica\Protocol\Email;
use Friendica\Protocol\Feed;
use Friendica\Util\Crypto;
use Friendica\Util\Network;
use Friendica\Util\Strings;
use Friendica\Util\XML;
/**
* @brief This class contain functions for probing URL
*
*/
class Probe
{
private static $baseurl;
private static $istimeout;
/**
* @brief Rearrange the array so that it always has the same order
*
* @param array $data Unordered data
*
* @return array Ordered data
*/
private static function rearrangeData($data)
{
$fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
"community", "keywords", "location", "about", "gender", "hide",
"batch", "notify", "poll", "request", "confirm", "poco",
"following", "followers", "inbox", "outbox", "sharedinbox",
"priority", "network", "pubkey", "baseurl"];
$newdata = [];
foreach ($fields as $field) {
if (isset($data[$field])) {
$newdata[$field] = $data[$field];
} else {
$newdata[$field] = "";
}
}
// We don't use the "priority" field anymore and replace it with a dummy.
$newdata["priority"] = 0;
return $newdata;
}
/**
* @brief Check if the hostname belongs to the own server
*
* @param string $host The hostname that is to be checked
*
* @return bool Does the testes hostname belongs to the own server?
*/
private static function ownHost($host)
{
$own_host = DI::baseUrl()->getHostname();
$parts = parse_url($host);
if (!isset($parts['scheme'])) {
$parts = parse_url('http://'.$host);
}
if (!isset($parts['host'])) {
return false;
}
return $parts['host'] == $own_host;
}
/**
* @brief Probes for webfinger path via "host-meta"
*
* We have to check if the servers in the future still will offer this.
* It seems as if it was dropped from the standard.
*
* @param string $host The host part of an url
*
* @return array with template and type of the webfinger template for JSON or XML
* @throws HTTPException\InternalServerErrorException
*/
private static function hostMeta($host)
{
// Reset the static variable
self::$baseurl = '';
$ssl_url = "https://".$host."/.well-known/host-meta";
$url = "http://".$host."/.well-known/host-meta";
$xrd_timeout = Config::get('system', 'xrd_timeout', 20);
Logger::log("Probing for ".$host, Logger::DEBUG);
$xrd = null;
$curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
$ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
if ($curlResult->isSuccess()) {
$xml = $curlResult->getBody();
$xrd = XML::parseString($xml, false);
$host_url = 'https://'.$host;
} elseif ($curlResult->isTimeout()) {
Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
self::$istimeout = true;
return false;
}
if (!is_object($xrd)) {
$curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
$connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
if ($curlResult->isTimeout()) {
Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
self::$istimeout = true;
return false;
} elseif ($connection_error && $ssl_connection_error) {
self::$istimeout = true;
return false;
}
$xml = $curlResult->getBody();
$xrd = XML::parseString($xml, false);
$host_url = 'http://'.$host;
}
if (!is_object($xrd)) {
Logger::log("No xrd object found for ".$host, Logger::DEBUG);
return [];
}
$links = XML::elementToArray($xrd);
if (!isset($links["xrd"]["link"])) {
Logger::log("No xrd data found for ".$host, Logger::DEBUG);
return [];
}
$lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
foreach ($links["xrd"]["link"] as $value => $link) {
if (!empty($link["@attributes"])) {
$attributes = $link["@attributes"];
} elseif ($value == "@attributes") {
$attributes = $link;
} else {
continue;
}
if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
$type = (empty($attributes["type"]) ? '' : $attributes["type"]);
$lrdd[$type] = $attributes["template"];
}
}
self::$baseurl = $host_url;
Logger::log("Probing successful for ".$host, Logger::DEBUG);
return $lrdd;
}
/**
* @brief Perform Webfinger lookup and return DFRN data
*
* Given an email style address, perform webfinger lookup and
* return the resulting DFRN profile URL, or if no DFRN profile URL
* is located, returns an OStatus subscription template (prefixed
* with the string 'stat:' to identify it as on OStatus template).
* If this isn't an email style address just return $webbie.
* Return an empty string if email-style addresses but webfinger fails,
* or if the resultant personal XRD doesn't contain a supported
* subscription/friend-request attribute.
*
* amended 7/9/2011 to return an hcard which could save potentially loading
* a lengthy content page to scrape dfrn attributes
*
* @param string $webbie Address that should be probed
* @param string $hcard_url Link to the hcard - is returned by reference
*
* @return string profile link
* @throws HTTPException\InternalServerErrorException
*/
public static function webfingerDfrn($webbie, &$hcard_url)
{
$profile_link = '';
$links = self::lrdd($webbie);
Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
if (!empty($links) && is_array($links)) {
foreach ($links as $link) {
if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
$profile_link = $link['@attributes']['href'];
}
if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
$profile_link = 'stat:'.$link['@attributes']['template'];
}
if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
$hcard_url = $link['@attributes']['href'];
}
}
}
return $profile_link;
}
/**
* @brief Check an URI for LRDD data
*
* this is a replacement for the "lrdd" function.
* It isn't used in this class and has some redundancies in the code.
* When time comes we can check the existing calls for "lrdd" if we can rework them.
*
* @param string $uri Address that should be probed
*
* @return array uri data
* @throws HTTPException\InternalServerErrorException
*/
public static function lrdd($uri)
{
$lrdd = self::hostMeta($uri);
$webfinger = null;
if (is_bool($lrdd)) {
return [];
}
if (!$lrdd) {
$parts = @parse_url($uri);
if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
return [];
}
$host = $parts["host"];
if (!empty($parts["port"])) {
$host .= ':'.$parts["port"];
}
$path_parts = explode("/", trim($parts["path"], "/"));
$nick = array_pop($path_parts);
do {
$lrdd = self::hostMeta($host);
$host .= "/".array_shift($path_parts);
} while (!$lrdd && (sizeof($path_parts) > 0));
}
if (!$lrdd) {
Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
return [];
}
foreach ($lrdd as $type => $template) {
if ($webfinger) {
continue;
}
$path = str_replace('{uri}', urlencode($uri), $template);
$webfinger = self::webfinger($path, $type);
if (!$webfinger && (strstr($uri, "@"))) {
$path = str_replace('{uri}', urlencode("acct:".$uri), $template);
$webfinger = self::webfinger($path, $type);
}
// Special treatment for Mastodon
// Problem is that Mastodon uses an URL format like http://domain.tld/@nick
// But the webfinger for this format fails.
if (!$webfinger && !empty($nick)) {
// Mastodon uses a "@" as prefix for usernames in their url format
$nick = ltrim($nick, '@');
$addr = $nick."@".$host;
$path = str_replace('{uri}', urlencode("acct:".$addr), $template);
$webfinger = self::webfinger($path, $type);
}
}
if (!is_array($webfinger["links"])) {
Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
return false;
}
$data = [];
foreach ($webfinger["links"] as $link) {
$data[] = ["@attributes" => $link];
}
if (is_array($webfinger["aliases"])) {
foreach ($webfinger["aliases"] as $alias) {
$data[] = ["@attributes" =>
["rel" => "alias",
"href" => $alias]];
}
}
return $data;
}
/**
* @brief Fetch information (protocol endpoints and user information) about a given uri
*
* @param string $uri Address that should be probed
* @param string $network Test for this specific network
* @param integer $uid User ID for the probe (only used for mails)
* @param boolean $cache Use cached values?
*
* @return array uri data
* @throws HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
public static function uri($uri, $network = '', $uid = -1, $cache = true)
{
if ($cache) {
$result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
if (!is_null($result)) {
return $result;
}
5 years ago
}
if ($uid == -1) {
$uid = local_user();
}
self::$istimeout = false;
if ($network != Protocol::ACTIVITYPUB) {
$data = self::detect($uri, $network, $uid);
} else {
$data = null;
}
// When the previous detection process had got a time out
// we could falsely detect a Friendica profile as AP profile.
if (!self::$istimeout) {
$ap_profile = ActivityPub::probeProfile($uri);
if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
$data = $ap_profile;
} elseif (!empty($ap_profile)) {
$ap_profile['batch'] = '';
$data = array_merge($ap_profile, $data);
}
3 years ago
} else {
Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
}
if (!isset($data['url'])) {
$data['url'] = $uri;
}
if (!empty($data['photo']) && !empty($data['baseurl'])) {
$data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink($data['baseurl']), Strings::normaliseLink($data['photo']));
} elseif (empty($data['photo'])) {
$data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
}
if (empty($data['name'])) {
if (!empty($data['nick'])) {
$data['name'] = $data['nick'];
}
if (empty($data['name'])) {
$data['name'] = $data['url'];
}
}
if (empty($data['nick'])) {
$data['nick'] = strtolower($data['name']);
if (strpos($data['nick'], ' ')) {
$data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
}
}
if (!empty(self::$baseurl)) {
$data['baseurl'] = self::$baseurl;
}
if (empty($data['network'])) {
$data['network'] = Protocol::PHANTOM;
}
// Ensure that local connections always are DFRN
if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
$data['network'] = Protocol::DFRN;
}
if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
$data['hide'] = self::getHideStatus($data['url']);
}
$data = self::rearrangeData($data);
5 years ago
// Only store into the cache if the value seems to be valid
if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Cache::DAY);
5 years ago
}
return $data;
}
/**
* Fetches the "hide" status from the profile
*
* @param string $url URL of the profile
*
* @return boolean "hide" status
*/
private static function getHideStatus($url)
{
$curlResult = Network::curl($url);
if (!$curlResult->isSuccess()) {
return false;
}
// If the file is too large then exit
if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
return false;
}
// If it isn't a HTML file then exit
if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
return false;
}
$body = $curlResult->getBody();
$doc = new DOMDocument();
@$doc->loadHTML($body);
$xpath = new DOMXPath($doc);
$list = $xpath->query('//meta[@name]');
foreach ($list as $node) {
$meta_tag = [];
if ($node->attributes->length) {
foreach ($node->attributes as $attribute) {
$meta_tag[$attribute->name] = $attribute->value;
}
}
if (empty($meta_tag['content'])) {
continue;
}
$content = strtolower(trim($meta_tag['content']));
switch (strtolower(trim($meta_tag['name']))) {
case 'dfrn-global-visibility':
if ($content == 'false') {
return true;
}
break;
case 'robots':
if (strpos($content, 'noindex') !== false) {
return true;
}
break;
}
}
return false;
}
/**
* @brief Checks if a profile url should be OStatus but only provides partial information
*
* @param array $webfinger Webfinger data
* @param string $lrdd Path template for webfinger request
* @param string $type type
*
* @return array fixed webfinger data
* @throws HTTPException\InternalServerErrorException
*/
private static function fixOStatus($webfinger, $lrdd, $type)
{
if (empty($webfinger['links']) || empty($webfinger['subject'])) {
return $webfinger;
}
$is_ostatus = false;
$has_key = false;
foreach ($webfinger['links'] as $link) {
if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
$is_ostatus = true;
}
if ($link['rel'] == 'magic-public-key') {
$has_key = true;
}
}
if (!$is_ostatus || $has_key) {
return $webfinger;
}
$url = Network::switchScheme($webfinger['subject']);
$path = str_replace('{uri}', urlencode($url), $lrdd);
$webfinger2 = self::webfinger($path, $type);
// Is the new webfinger detectable as OStatus?
if (self::ostatus($webfinger2, true)) {
$webfinger = $webfinger2;
}
return $webfinger;
}
/**
* @brief Fetch information (protocol endpoints and user information) about a given uri
*
* This function is only called by the "uri" function that adds caching and rearranging of data.
*
* @param string $uri Address that should be probed
* @param string $network Test for this specific network
* @param integer $uid User ID for the probe (only used for mails)
*
* @return array uri data
* @throws HTTPException\InternalServerErrorException
*/
private static function detect($uri, $network, $uid)
{
$parts = parse_url($uri);
if (!empty($parts["scheme"]) && !empty($parts["host"])) {
$host = $parts["host"];
if (!empty($parts["port"])) {
$host .= ':'.$parts["port"];
}
if ($host == 'twitter.com') {
return self::twitter($uri);
}
$lrdd = self::hostMeta($host);
if (is_bool($lrdd)) {
return [];
}
$path_parts = explode("/", trim($parts['path'] ?? '', "/"));
while (!$lrdd && (sizeof($path_parts) > 1)) {
$host .= "/".array_shift($path_parts);
$lrdd = self::hostMeta($host);
}
if (!$lrdd) {
Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
return self::feed($uri);
}
$nick = array_pop($path_parts);
// Mastodon uses a "@" as prefix for usernames in their url format
$nick = ltrim($nick, '@');
$addr = $nick."@".$host;
} elseif (strstr($uri, '@')) {
// If the URI starts with "mailto:" then jump directly to the mail detection
if (strpos($uri, 'mailto:') !== false) {
$uri = str_replace('mailto:', '', $uri);
return self::mail($uri, $uid);
}
if ($network == Protocol::MAIL) {
return self::mail($uri, $uid);
}
// Remove "acct:" from the URI
$uri = str_replace('acct:', '', $uri);
$host = substr($uri, strpos($uri, '@') + 1);
$nick = substr($uri, 0, strpos($uri, '@'));
if (strpos($uri, '@twitter.com')) {
return self::twitter($uri);
}
$lrdd = self::hostMeta($host);
if (is_bool($lrdd)) {
return [];
}
if (!$lrdd) {
Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
return self::mail($uri, $uid);
}
$addr = $uri;
} else {
Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
return false;
}
$webfinger = false;
/// @todo Do we need the prefix "acct:" or "acct://"?
foreach ($lrdd as $type => $template) {
if ($webfinger) {
continue;
}
// At first try it with the given uri
$path = str_replace('{uri}', urlencode($uri), $template);
$webfinger = self::webfinger($path, $type);
// Fix possible problems with GNU Social probing to wrong scheme
$webfinger = self::fixOStatus($webfinger, $template, $type);
// We cannot be sure that the detected address was correct, so we don't use the values
if ($webfinger && ($uri != $addr)) {
$nick = "";
$addr = "";
}
// Try webfinger with the address (user@domain.tld)
if (!$webfinger) {
$path = str_replace('{uri}', urlencode($addr), $template);
$webfinger = self::webfinger($path, $type);
}
// Mastodon needs to have it with "acct:"
if (!$webfinger) {
$path = str_replace('{uri}', urlencode("acct:".$addr), $template);
$webfinger = self::webfinger($path, $type);
}
}
if (!$webfinger) {
return self::feed($uri);
}
$result = false;
Logger::log("Probing ".$uri, Logger::DEBUG);
5 years ago
if (in_array($network, ["", Protocol::DFRN])) {
$result = self::dfrn($webfinger);
}
if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
$result = self::diaspora($webfinger);
}
if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
$result = self::ostatus($webfinger);
}
if (in_array($network, ['', Protocol::ZOT])) {
$result = self::zot($webfinger, $result);
}
if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
$result = self::pumpio($webfinger, $addr);
}
if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
$result = self::feed($uri);
} else {
// We overwrite the detected nick with our try if the previois routines hadn't detected it.
// Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
$result["nick"] = $nick;
}
if (empty($result["addr"]) && ($addr != "")) {
$result["addr"] = $addr;
}
}
if (empty($result["network"])) {
$result["network"] = Protocol::PHANTOM;
}
if (empty($result["url"])) {
$result["url"] = $uri;
}
Logger::log($uri." is ".$result["network"], Logger::DEBUG);
5 years ago
if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
$pos = strpos($result["url"], $host);
if ($pos) {
$result["baseurl"] = substr($result["url"], 0, $pos).$host;
}
}
return $result;
}
/**
* Check for Zot contact
*
* @param array $webfinger Webfinger data
* @param array $data previously probed data
*
* @return array Zot data
* @throws HTTPException\InternalServerErrorException
*/
private static function zot($webfinger, $data)
{
if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
foreach ($webfinger["aliases"] as $alias) {
if (substr($alias, 0, 5) == 'acct:') {
$data["addr"] = substr($alias, 5);
}
}
}
if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
$data["addr"] = substr($webfinger["subject"], 5);
}
$zot_url = '';
foreach ($webfinger['links'] as $link) {
if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
$zot_url = $link['href'];
}
}
if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
$condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
if (!DBA::exists('gserver', $condition)) {
return $data;
}
$zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
}
if (empty($zot_url)) {
return $data;
}
$data = self::pollZot($zot_url, $data);
if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
foreach ($webfinger['aliases'] as $alias) {
if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
$data['alias'] = $alias;
}
}
}
return $data;
}
public static function pollZot($url, $data)
{
$curlResult = Network::curl($url);
if ($curlResult->isTimeout()) {
return $data;
}
$content = $curlResult->getBody();
if (!$content) {
return $data;
}
$json = json_decode($content, true);
if (!is_array($json)) {
return $data;
}
2 years ago
if (empty($data['network'])) {