FreeNetwork.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. <?php
  2. declare(strict_types = 1);
  3. // {{{ License
  4. // This file is part of GNU social - https://www.gnu.org/software/social
  5. //
  6. // GNU social is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // GNU social is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  18. // }}}
  19. namespace Component\FreeNetwork;
  20. use App\Core\DB\DB;
  21. use App\Core\Event;
  22. use App\Core\GSFile;
  23. use App\Core\HTTPClient;
  24. use function App\Core\I18n\_m;
  25. use App\Core\Log;
  26. use App\Core\Modules\Component;
  27. use App\Core\Router\RouteLoader;
  28. use App\Core\Router\Router;
  29. use App\Entity\Activity;
  30. use App\Entity\Actor;
  31. use App\Entity\LocalUser;
  32. use App\Entity\Note;
  33. use App\Util\Common;
  34. use App\Util\Exception\ClientException;
  35. use App\Util\Exception\NicknameEmptyException;
  36. use App\Util\Exception\NicknameException;
  37. use App\Util\Exception\NicknameInvalidException;
  38. use App\Util\Exception\NicknameNotAllowedException;
  39. use App\Util\Exception\NicknameTakenException;
  40. use App\Util\Exception\NicknameTooLongException;
  41. use App\Util\Exception\NoSuchActorException;
  42. use App\Util\Exception\ServerException;
  43. use App\Util\Nickname;
  44. use Component\FreeNetwork\Controller\Feeds;
  45. use Component\FreeNetwork\Controller\HostMeta;
  46. use Component\FreeNetwork\Controller\OwnerXrd;
  47. use Component\FreeNetwork\Controller\Webfinger;
  48. use Component\FreeNetwork\Util\Discovery;
  49. use Component\FreeNetwork\Util\WebfingerResource;
  50. use Component\FreeNetwork\Util\WebfingerResource\WebfingerResourceActor;
  51. use Component\FreeNetwork\Util\WebfingerResource\WebfingerResourceNote;
  52. use Exception;
  53. use const PREG_SET_ORDER;
  54. use Symfony\Component\HttpFoundation\JsonResponse;
  55. use Symfony\Component\HttpFoundation\Response;
  56. use XML_XRD;
  57. use XML_XRD_Element_Link;
  58. /**
  59. * Implements WebFinger (RFC7033) for GNU social, as well as Link-based Resource Descriptor Discovery based on RFC6415,
  60. * Web Host Metadata ('.well-known/host-meta') resource.
  61. *
  62. * @package GNUsocial
  63. *
  64. * @author Mikael Nordfeldth <mmn@hethane.se>
  65. * @author Diogo Peralta Cordeiro <mail@diogo.site>
  66. */
  67. class FreeNetwork extends Component
  68. {
  69. public const PLUGIN_VERSION = '0.1.0';
  70. public const OAUTH_ACCESS_TOKEN_REL = 'http://apinamespace.org/oauth/access_token';
  71. public const OAUTH_REQUEST_TOKEN_REL = 'http://apinamespace.org/oauth/request_token';
  72. public const OAUTH_AUTHORIZE_REL = 'http://apinamespace.org/oauth/authorize';
  73. public function onAddRoute(RouteLoader $m): bool
  74. {
  75. // Feeds
  76. $m->connect('feed_network', '/feed/network', [Feeds::class, 'network']);
  77. $m->connect('feed_clique', '/feed/clique', [Feeds::class, 'clique']);
  78. $m->connect('feed_federated', '/feed/federated', [Feeds::class, 'federated']);
  79. $m->connect('freenetwork_hostmeta', '.well-known/host-meta', [HostMeta::class, 'handle']);
  80. $m->connect(
  81. 'freenetwork_hostmeta_format',
  82. '.well-known/host-meta.:format',
  83. [HostMeta::class, 'handle'],
  84. ['format' => '(xml|json)'],
  85. );
  86. // the resource GET parameter can be anywhere, so don't mention it here
  87. $m->connect('freenetwork_webfinger', '.well-known/webfinger', [Webfinger::class, 'handle']);
  88. $m->connect(
  89. 'freenetwork_webfinger_format',
  90. '.well-known/webfinger.:format',
  91. [Webfinger::class, 'handle'],
  92. ['format' => '(xml|json)'],
  93. );
  94. $m->connect('freenetwork_ownerxrd', 'main/ownerxrd', [OwnerXrd::class, 'handle']);
  95. return Event::next;
  96. }
  97. public function onCreateDefaultFeeds(int $actor_id, LocalUser $user, int &$ordering)
  98. {
  99. DB::persist(\App\Entity\Feed::create(['actor_id' => $actor_id, 'url' => Router::url($route = 'feed_network'), 'route' => $route, 'title' => _m('Meteorites'), 'ordering' => $ordering++]));
  100. DB::persist(\App\Entity\Feed::create(['actor_id' => $actor_id, 'url' => Router::url($route = 'feed_clique'), 'route' => $route, 'title' => _m('Planetary System'), 'ordering' => $ordering++]));
  101. DB::persist(\App\Entity\Feed::create(['actor_id' => $actor_id, 'url' => Router::url($route = 'feed_federated'), 'route' => $route, 'title' => _m('Galaxy'), 'ordering' => $ordering++]));
  102. return Event::next;
  103. }
  104. public function onStartGetProfileAcctUri(Actor $profile, &$acct): bool
  105. {
  106. $wfr = new WebFingerResourceActor($profile);
  107. try {
  108. $acct = $wfr->reconstructAcct();
  109. } catch (Exception) {
  110. return Event::next;
  111. }
  112. return Event::stop;
  113. }
  114. /**
  115. * Last attempts getting a WebFingerResource object
  116. *
  117. * @param string $resource String that contains the requested URI
  118. * @param null|WebfingerResource $target WebFingerResource extended object goes here
  119. * @param array $args Array which may contains arguments such as 'rel' filtering values
  120. *
  121. * @throws NicknameEmptyException
  122. * @throws NicknameException
  123. * @throws NicknameInvalidException
  124. * @throws NicknameNotAllowedException
  125. * @throws NicknameTakenException
  126. * @throws NicknameTooLongException
  127. * @throws NoSuchActorException
  128. * @throws ServerException
  129. */
  130. public function onEndGetWebFingerResource(string $resource, ?WebfingerResource &$target = null, array $args = []): bool
  131. {
  132. // * Either we didn't find the profile, then we want to make
  133. // the $profile variable null for clarity.
  134. // * Or we did find it but for a possibly malicious remote
  135. // user who might've set their profile URL to a Note URL
  136. // which would've caused a sort of DoS unless we continue
  137. // our search here by discarding the remote profile.
  138. $profile = null;
  139. if (Discovery::isAcct($resource)) {
  140. $parts = explode('@', mb_substr(urldecode($resource), 5)); // 5 is strlen of 'acct:'
  141. if (\count($parts) === 2) {
  142. [$nick, $domain] = $parts;
  143. if ($domain !== $_ENV['SOCIAL_DOMAIN']) {
  144. throw new ServerException(_m('Remote profiles not supported via WebFinger yet.'));
  145. }
  146. $nick = Nickname::normalize(nickname: $nick, check_already_used: false, check_is_allowed: false);
  147. $freenetwork_actor = LocalUser::getByPK(['nickname' => $nick]);
  148. if (!($freenetwork_actor instanceof LocalUser)) {
  149. throw new NoSuchActorException($nick);
  150. }
  151. $profile = $freenetwork_actor->getActor();
  152. }
  153. } else {
  154. try {
  155. if (Common::isValidHttpUrl($resource)) {
  156. // This means $resource is a valid url
  157. $resource_parts = parse_url($resource);
  158. // TODO: Use URLMatcher
  159. if ($resource_parts['host'] === $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) {
  160. $str = $resource_parts['path'];
  161. // actor_view_nickname
  162. $renick = '/\/@(' . Nickname::DISPLAY_FMT . ')\/?/m';
  163. // actor_view_id
  164. $reuri = '/\/actor\/(\d+)\/?/m';
  165. if (preg_match_all($renick, $str, $matches, PREG_SET_ORDER, 0) === 1) {
  166. $profile = LocalUser::getByPK(['nickname' => $matches[0][1]])->getActor();
  167. } elseif (preg_match_all($reuri, $str, $matches, PREG_SET_ORDER, 0) === 1) {
  168. $profile = Actor::getById((int) $matches[0][1]);
  169. }
  170. }
  171. }
  172. } catch (NoSuchActorException $e) {
  173. // not a User, maybe a Note? we'll try that further down...
  174. // try {
  175. // Log::debug(__METHOD__ . ': Finding User_group URI for WebFinger lookup on resource==' . $resource);
  176. // $group = new User_group();
  177. // $group->whereAddIn('uri', array_keys($alt_urls), $group->columnType('uri'));
  178. // $group->limit(1);
  179. // if ($group->find(true)) {
  180. // $profile = $group->getProfile();
  181. // }
  182. // unset($group);
  183. // } catch (Exception $e) {
  184. // Log::error(get_class($e) . ': ' . $e->getMessage());
  185. // throw $e;
  186. // }
  187. }
  188. }
  189. if ($profile instanceof Actor) {
  190. Log::debug(__METHOD__ . ': Found Profile with ID==' . $profile->getID() . ' for resource==' . $resource);
  191. $target = new WebfingerResourceActor($profile);
  192. return Event::stop; // We got our target, stop handler execution
  193. }
  194. if (!\is_null($note = DB::findOneBy(Note::class, ['url' => $resource], return_null: true))) {
  195. $target = new WebfingerResourceNote($note);
  196. return Event::stop; // We got our target, stop handler execution
  197. }
  198. return Event::next;
  199. }
  200. public function onStartHostMetaLinks(array &$links): bool
  201. {
  202. foreach (Discovery::supportedMimeTypes() as $type) {
  203. $links[] = new XML_XRD_Element_Link(
  204. Discovery::LRDD_REL,
  205. Router::url(id: 'freenetwork_webfinger', args: [], type: Router::ABSOLUTE_URL) . '?resource={uri}',
  206. $type,
  207. isTemplate: true,
  208. );
  209. }
  210. // TODO OAuth connections
  211. //$links[] = new XML_XRD_Element_link(self::OAUTH_ACCESS_TOKEN_REL, common_local_url('ApiOAuthAccessToken'));
  212. //$links[] = new XML_XRD_Element_link(self::OAUTH_REQUEST_TOKEN_REL, common_local_url('ApiOAuthRequestToken'));
  213. //$links[] = new XML_XRD_Element_link(self::OAUTH_AUTHORIZE_REL, common_local_url('ApiOAuthAuthorize'));
  214. return Event::next;
  215. }
  216. /**
  217. * Add a link header for LRDD Discovery
  218. */
  219. public function onStartShowHTML($action): bool
  220. {
  221. if ($action instanceof ShowstreamAction) {
  222. $resource = $action->getTarget()->getUri();
  223. $url = common_local_url('webfinger') . '?resource=' . urlencode($resource);
  224. foreach ([Discovery::JRD_MIMETYPE, Discovery::XRD_MIMETYPE] as $type) {
  225. header('Link: <' . $url . '>; rel="' . Discovery::LRDD_REL . '"; type="' . $type . '"', false);
  226. }
  227. }
  228. return Event::next;
  229. }
  230. public function onStartDiscoveryMethodRegistration(Discovery $disco): bool
  231. {
  232. $disco->registerMethod('\Component\FreeNetwork\Util\LrddMethod\LrddMethodWebfinger');
  233. return Event::next;
  234. }
  235. public function onEndDiscoveryMethodRegistration(Discovery $disco): bool
  236. {
  237. $disco->registerMethod('\Component\FreeNetwork\Util\LrddMethod\LrddMethodHostMeta');
  238. $disco->registerMethod('\Component\FreeNetwork\Util\LrddMethod\LrddMethodLinkHeader');
  239. $disco->registerMethod('\Component\FreeNetwork\Util\LrddMethod\LrddMethodLinkHtml');
  240. return Event::next;
  241. }
  242. /**
  243. * @throws ClientException
  244. * @throws ServerException
  245. */
  246. public function onControllerResponseInFormat(string $route, array $accept_header, array $vars, ?Response &$response = null): bool
  247. {
  248. if (!\in_array($route, ['freenetwork_hostmeta', 'freenetwork_hostmeta_format', 'freenetwork_webfinger', 'freenetwork_webfinger_format', 'freenetwork_ownerxrd'])) {
  249. return Event::next;
  250. }
  251. $mimeType = array_intersect(array_values(Discovery::supportedMimeTypes()), $accept_header);
  252. /*
  253. * "A WebFinger resource MUST return a JRD as the representation
  254. * for the resource if the client requests no other supported
  255. * format explicitly via the HTTP "Accept" header. [...]
  256. * The WebFinger resource MUST silently ignore any requested
  257. * representations that it does not understand and support."
  258. * -- RFC 7033 (WebFinger)
  259. * http://tools.ietf.org/html/rfc7033
  260. */
  261. $mimeType = \count($mimeType) !== 0 ? array_pop($mimeType) : $vars['default_mimetype'];
  262. $headers = [];
  263. if (Common::config('discovery', 'cors')) {
  264. $headers['Access-Control-Allow-Origin'] = '*';
  265. }
  266. $headers['Content-Type'] = $mimeType;
  267. $response = match ($mimeType) {
  268. Discovery::XRD_MIMETYPE => new Response(content: $vars['xrd']->to('xml'), headers: $headers),
  269. Discovery::JRD_MIMETYPE, Discovery::JRD_MIMETYPE_OLD => new JsonResponse(data: $vars['xrd']->to('json'), headers: $headers, json: true),
  270. };
  271. $response->headers->set('cache-control', 'no-store, no-cache, must-revalidate');
  272. return Event::stop;
  273. }
  274. /**
  275. * Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz
  276. *
  277. * @param string $text The text from which to extract webfinger IDs
  278. * @param string $preMention Character(s) that signals a mention ('@', '!'...)
  279. *
  280. * @return array the matching IDs (without $preMention) and each respective position in the given string
  281. */
  282. public static function extractWebfingerIds(string $text, string $preMention = '@'): array
  283. {
  284. $wmatches = [];
  285. $result = preg_match_all(
  286. '/' . Nickname::BEFORE_MENTIONS . preg_quote($preMention, '/') . '(' . Nickname::WEBFINGER_FMT . ')/',
  287. $text,
  288. $wmatches,
  289. \PREG_OFFSET_CAPTURE,
  290. );
  291. if ($result === false) {
  292. Log::error(__METHOD__ . ': Error parsing webfinger IDs from text (preg_last_error==' . preg_last_error() . ').');
  293. return [];
  294. } elseif (($n_matches = \count($wmatches)) != 0) {
  295. Log::debug((sprintf('Found %d matches for WebFinger IDs: %s', $n_matches, print_r($wmatches, true))));
  296. }
  297. return $wmatches[1];
  298. }
  299. /**
  300. * Profile URL matches: @param string $text The text from which to extract URL mentions
  301. *
  302. * @param string $preMention Character(s) that signals a mention ('@', '!'...)
  303. *
  304. * @return array the matching URLs (without @ or acct:) and each respective position in the given string
  305. * @example.com/mublog/user
  306. */
  307. public static function extractUrlMentions(string $text, string $preMention = '@'): array
  308. {
  309. $wmatches = [];
  310. // In the regexp below we need to match / _before_ URL_REGEX_VALID_PATH_CHARS because it otherwise gets merged
  311. // with the TLD before (but / is in URL_REGEX_VALID_PATH_CHARS anyway, it's just its positioning that is important)
  312. $result = preg_match_all(
  313. '/' . Nickname::BEFORE_MENTIONS . preg_quote($preMention, '/') . '(' . URL_REGEX_DOMAIN_NAME . '(?:\/[' . URL_REGEX_VALID_PATH_CHARS . ']*)*)/',
  314. $text,
  315. $wmatches,
  316. \PREG_OFFSET_CAPTURE,
  317. );
  318. if ($result === false) {
  319. Log::error(__METHOD__ . ': Error parsing profile URL mentions from text (preg_last_error==' . preg_last_error() . ').');
  320. return [];
  321. } elseif (\count($wmatches)) {
  322. Log::debug((sprintf('Found %d matches for profile URL mentions: %s', \count($wmatches), print_r($wmatches, true))));
  323. }
  324. return $wmatches[1];
  325. }
  326. /**
  327. * Find any explicit remote mentions. Accepted forms:
  328. * Webfinger: @user@example.com
  329. * Profile link: @param Actor $sender
  330. *
  331. * @param string $text input markup text
  332. * @param $mentions
  333. *
  334. * @return bool hook return value
  335. * @example.com/mublog/user
  336. */
  337. public function onEndFindMentions(Actor $sender, string $text, array &$mentions): bool
  338. {
  339. $matches = [];
  340. foreach (self::extractWebfingerIds($text, $preMention = '@') as $wmatch) {
  341. [$target, $pos] = $wmatch;
  342. Log::info("Checking webfinger person '{$target}'");
  343. $actor = null;
  344. $resource_parts = explode($preMention, $target);
  345. if ($resource_parts[1] === $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) {
  346. $actor = LocalUser::getByPK(['nickname' => $resource_parts[0]])->getActor();
  347. } else {
  348. Event::handle('FreeNetworkFindMentions', [$target, &$actor]);
  349. if (\is_null($actor)) {
  350. continue;
  351. }
  352. }
  353. \assert($actor instanceof Actor);
  354. $displayName = !empty($actor->getFullname()) ? $actor->getFullname() : $actor->getNickname() ?? $target; // TODO: we could do getBestName() or getFullname() here
  355. $matches[$pos] = [
  356. 'mentioned' => [$actor],
  357. 'type' => 'mention',
  358. 'text' => $displayName,
  359. 'position' => $pos,
  360. 'length' => mb_strlen($target),
  361. 'url' => $actor->getUri(),
  362. ];
  363. }
  364. foreach (self::extractUrlMentions($text) as $wmatch) {
  365. [$target, $pos] = $wmatch;
  366. $url = "https://{$target}";
  367. if (Common::isValidHttpUrl($url)) {
  368. // This means $resource is a valid url
  369. $resource_parts = parse_url($url);
  370. // TODO: Use URLMatcher
  371. if ($resource_parts['host'] === $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) {
  372. $str = $resource_parts['path'];
  373. // actor_view_nickname
  374. $renick = '/\/@(' . Nickname::DISPLAY_FMT . ')\/?/m';
  375. // actor_view_id
  376. $reuri = '/\/actor\/(\d+)\/?/m';
  377. if (preg_match_all($renick, $str, $matches, PREG_SET_ORDER, 0) === 1) {
  378. $actor = LocalUser::getByPK(['nickname' => $matches[0][1]])->getActor();
  379. } elseif (preg_match_all($reuri, $str, $matches, PREG_SET_ORDER, 0) === 1) {
  380. $actor = Actor::getById((int) $matches[0][1]);
  381. } else {
  382. Log::error('Unexpected behaviour onEndFindMentions at FreeNetwork');
  383. throw new ServerException('Unexpected behaviour onEndFindMentions at FreeNetwork');
  384. }
  385. } else {
  386. Log::info("Checking actor address '{$url}'");
  387. $link = new XML_XRD_Element_Link(
  388. Discovery::LRDD_REL,
  389. 'https://' . parse_url($url, \PHP_URL_HOST) . '/.well-known/webfinger?resource={uri}',
  390. Discovery::JRD_MIMETYPE,
  391. true, // isTemplate
  392. );
  393. $xrd_uri = Discovery::applyTemplate($link->template, $url);
  394. $response = HTTPClient::get($xrd_uri, ['headers' => ['Accept' => $link->type]]);
  395. if ($response->getStatusCode() !== 200) {
  396. continue;
  397. }
  398. $xrd = new XML_XRD();
  399. switch (GSFile::mimetypeBare($response->getHeaders()['content-type'][0])) {
  400. case Discovery::JRD_MIMETYPE_OLD:
  401. case Discovery::JRD_MIMETYPE:
  402. $type = 'json';
  403. break;
  404. case Discovery::XRD_MIMETYPE:
  405. $type = 'xml';
  406. break;
  407. default:
  408. // fall back to letting XML_XRD auto-detect
  409. Log::debug('No recognized content-type header for resource descriptor body on ' . $xrd_uri);
  410. $type = null;
  411. }
  412. $xrd->loadString($response->getContent(), $type);
  413. $actor = null;
  414. Event::handle('FreeNetworkFoundXrd', [$xrd, &$actor]);
  415. if (\is_null($actor)) {
  416. continue;
  417. }
  418. }
  419. $displayName = $actor->getFullname() ?? $actor->getNickname() ?? $target; // TODO: we could do getBestName() or getFullname() here
  420. $matches[$pos] = [
  421. 'mentioned' => [$actor],
  422. 'type' => 'mention',
  423. 'text' => $displayName,
  424. 'position' => $pos,
  425. 'length' => mb_strlen($target),
  426. 'url' => $actor->getUri(),
  427. ];
  428. }
  429. }
  430. foreach ($mentions as $i => $other) {
  431. // If we share a common prefix with a local user, override it!
  432. $pos = $other['position'];
  433. if (isset($matches[$pos])) {
  434. $mentions[$i] = $matches[$pos];
  435. unset($matches[$pos]);
  436. }
  437. }
  438. foreach ($matches as $mention) {
  439. $mentions[] = $mention;
  440. }
  441. return Event::next;
  442. }
  443. public static function notify(Actor $sender, Activity $activity, array $targets, ?string $reason = null): bool
  444. {
  445. $protocols = [];
  446. Event::handle('AddFreeNetworkProtocol', [&$protocols]);
  447. $delivered = [];
  448. foreach ($protocols as $protocol) {
  449. $protocol::freeNetworkDistribute($sender, $activity, $targets, $reason, $delivered);
  450. }
  451. $failed_targets = array_udiff($targets, $delivered, fn (Actor $a, Actor $b): int => $a->getId() <=> $b->getId());
  452. // TODO: Implement failed queues
  453. return false;
  454. }
  455. public static function mentionToName(string $nickname, string $uri): string
  456. {
  457. return '@' . $nickname . '@' . parse_url($uri, \PHP_URL_HOST);
  458. }
  459. public function onPluginVersion(array &$versions): bool
  460. {
  461. $versions[] = [
  462. 'name' => 'WebFinger',
  463. 'version' => self::PLUGIN_VERSION,
  464. 'author' => 'Mikael Nordfeldth',
  465. 'homepage' => GNUSOCIAL_ENGINE_URL,
  466. // TRANS: Plugin description.
  467. 'rawdescription' => _m('WebFinger and LRDD support'),
  468. ];
  469. return true;
  470. }
  471. }