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.

salmon.php 5.4 KiB

Cleanups: isResult() more used, readability improved (#5608) * [diaspora]: Maybe SimpleXMLElement is the right type-hint? * Changes proposed + pre-renaming: - pre-renamed $db -> $connection - added TODOs for not allowing bad method invocations (there is a BadMethodCallException in SPL) * If no record is found, below $r[0] will fail with a E_NOTICE and the code doesn't behave as expected. * Ops, one more left ... * Continued: - added documentation for Contact::updateSslPolicy() method - added type-hint for $contact of same method - empty lines added + TODO where the bug origins that $item has no element 'body' * Added empty lines for better readability * Cleaned up: - no more x() (deprecated) usage but empty() instead - fixed mixing of space/tab indending - merged else/if block goether in elseif() (lesser nested code blocks) * Re-fixed DBM -> DBA switch * Fixes/rewrites: - use empty()/isset() instead of deprecated x() - merged 2 nested if() blocks into one - avoided nested if() block inside else block by rewriting it to elseif() - $contact_id is an integer, let's test on > 0 here - added a lot spaces and some empty lines for better readability * Rewrite: - moved all CONTACT_* constants from boot.php to Contact class * CR request: - renamed Contact::CONTACT_IS_* -> Contact::* ;-) * Rewrites: - moved PAGE_* to Friendica\Model\Profile class - fixed mixure with "Contact::* rewrite" * Ops, one still there (return is no function) * Rewrite to Proxy class: - introduced new Friendica\Network\Proxy class for in exchange of proxy_*() functions - moved also all PROXY_* constants there as Proxy::* - removed now no longer needed mod/proxy.php loading as composer's auto-load will do this for us - renamed those proxy_*() functions to better names: + proxy_init() -> Proxy::init() (public) + proxy_url() -> Proxy::proxifyUrl() (public) + proxy_parse_html() -> Proxy::proxifyHtml() (public) + proxy_is_local_image() -> Proxy::isLocalImage() (private) + proxy_parse_query() -> Proxy::parseQuery() (private) + proxy_img_cb() -> Proxy::replaceUrl() (private) * CR request: - moved all PAGE_* constants to Friendica\Model\Contact class - fixed all references of both classes * Ops, need to set $a here ... * CR request: - moved Proxy class to Friendica\Module - extended BaseModule * Ops, no need for own instance of $a when self::getApp() is around. * Proxy-rewrite: - proxy_url() and proxy_parse_html() are both non-module functions (now methods) - so they must be splitted into a seperate class - also the SIZE_* and DEFAULT_TIME constants are both not relevant to module * No instances from utility classes * Fixed error: - proxify*() is now located in `Friendica\Util\ProxyUtils` * Moved back to original place, ops? How did they move here? Well, it was not intended by me. * Removed duplicate (left-over from split) constants and static array. Thank to MrPetovan finding it. * Renamed ProxyUtils -> Proxy and aliased it back to ProxyUtils. * Rewrite: - stopped using deprecated NETWORK_* constants, now Protocol::* should be used - still left them intact for slow/lazy developers ... * Ops, was added accidentally ... * Ops, why these wrong moves? * Ops, one to much (thanks to MrPetovan) * Ops, wrong moving ... * moved back to original place ... * spaces added * empty lines add for better readability. * convertered spaces -> tab for code indenting. * CR request: Add space between if and brace. * CR requests fixed + move reverted - ops, src/Module/*.php has been moved to src/Network/ accidentally - reverted some parts in src/Database/DBA.php as pointed out by Annando - removed internal TODO items - added some spaces for better readability
2 years ago
Cleanups: isResult() more used, readability improved (#5608) * [diaspora]: Maybe SimpleXMLElement is the right type-hint? * Changes proposed + pre-renaming: - pre-renamed $db -> $connection - added TODOs for not allowing bad method invocations (there is a BadMethodCallException in SPL) * If no record is found, below $r[0] will fail with a E_NOTICE and the code doesn't behave as expected. * Ops, one more left ... * Continued: - added documentation for Contact::updateSslPolicy() method - added type-hint for $contact of same method - empty lines added + TODO where the bug origins that $item has no element 'body' * Added empty lines for better readability * Cleaned up: - no more x() (deprecated) usage but empty() instead - fixed mixing of space/tab indending - merged else/if block goether in elseif() (lesser nested code blocks) * Re-fixed DBM -> DBA switch * Fixes/rewrites: - use empty()/isset() instead of deprecated x() - merged 2 nested if() blocks into one - avoided nested if() block inside else block by rewriting it to elseif() - $contact_id is an integer, let's test on > 0 here - added a lot spaces and some empty lines for better readability * Rewrite: - moved all CONTACT_* constants from boot.php to Contact class * CR request: - renamed Contact::CONTACT_IS_* -> Contact::* ;-) * Rewrites: - moved PAGE_* to Friendica\Model\Profile class - fixed mixure with "Contact::* rewrite" * Ops, one still there (return is no function) * Rewrite to Proxy class: - introduced new Friendica\Network\Proxy class for in exchange of proxy_*() functions - moved also all PROXY_* constants there as Proxy::* - removed now no longer needed mod/proxy.php loading as composer's auto-load will do this for us - renamed those proxy_*() functions to better names: + proxy_init() -> Proxy::init() (public) + proxy_url() -> Proxy::proxifyUrl() (public) + proxy_parse_html() -> Proxy::proxifyHtml() (public) + proxy_is_local_image() -> Proxy::isLocalImage() (private) + proxy_parse_query() -> Proxy::parseQuery() (private) + proxy_img_cb() -> Proxy::replaceUrl() (private) * CR request: - moved all PAGE_* constants to Friendica\Model\Contact class - fixed all references of both classes * Ops, need to set $a here ... * CR request: - moved Proxy class to Friendica\Module - extended BaseModule * Ops, no need for own instance of $a when self::getApp() is around. * Proxy-rewrite: - proxy_url() and proxy_parse_html() are both non-module functions (now methods) - so they must be splitted into a seperate class - also the SIZE_* and DEFAULT_TIME constants are both not relevant to module * No instances from utility classes * Fixed error: - proxify*() is now located in `Friendica\Util\ProxyUtils` * Moved back to original place, ops? How did they move here? Well, it was not intended by me. * Removed duplicate (left-over from split) constants and static array. Thank to MrPetovan finding it. * Renamed ProxyUtils -> Proxy and aliased it back to ProxyUtils. * Rewrite: - stopped using deprecated NETWORK_* constants, now Protocol::* should be used - still left them intact for slow/lazy developers ... * Ops, was added accidentally ... * Ops, why these wrong moves? * Ops, one to much (thanks to MrPetovan) * Ops, wrong moving ... * moved back to original place ... * spaces added * empty lines add for better readability. * convertered spaces -> tab for code indenting. * CR request: Add space between if and brace. * CR requests fixed + move reverted - ops, src/Module/*.php has been moved to src/Network/ accidentally - reverted some parts in src/Database/DBA.php as pointed out by Annando - removed internal TODO items - added some spaces for better readability
2 years ago
Cleanups: isResult() more used, readability improved (#5608) * [diaspora]: Maybe SimpleXMLElement is the right type-hint? * Changes proposed + pre-renaming: - pre-renamed $db -> $connection - added TODOs for not allowing bad method invocations (there is a BadMethodCallException in SPL) * If no record is found, below $r[0] will fail with a E_NOTICE and the code doesn't behave as expected. * Ops, one more left ... * Continued: - added documentation for Contact::updateSslPolicy() method - added type-hint for $contact of same method - empty lines added + TODO where the bug origins that $item has no element 'body' * Added empty lines for better readability * Cleaned up: - no more x() (deprecated) usage but empty() instead - fixed mixing of space/tab indending - merged else/if block goether in elseif() (lesser nested code blocks) * Re-fixed DBM -> DBA switch * Fixes/rewrites: - use empty()/isset() instead of deprecated x() - merged 2 nested if() blocks into one - avoided nested if() block inside else block by rewriting it to elseif() - $contact_id is an integer, let's test on > 0 here - added a lot spaces and some empty lines for better readability * Rewrite: - moved all CONTACT_* constants from boot.php to Contact class * CR request: - renamed Contact::CONTACT_IS_* -> Contact::* ;-) * Rewrites: - moved PAGE_* to Friendica\Model\Profile class - fixed mixure with "Contact::* rewrite" * Ops, one still there (return is no function) * Rewrite to Proxy class: - introduced new Friendica\Network\Proxy class for in exchange of proxy_*() functions - moved also all PROXY_* constants there as Proxy::* - removed now no longer needed mod/proxy.php loading as composer's auto-load will do this for us - renamed those proxy_*() functions to better names: + proxy_init() -> Proxy::init() (public) + proxy_url() -> Proxy::proxifyUrl() (public) + proxy_parse_html() -> Proxy::proxifyHtml() (public) + proxy_is_local_image() -> Proxy::isLocalImage() (private) + proxy_parse_query() -> Proxy::parseQuery() (private) + proxy_img_cb() -> Proxy::replaceUrl() (private) * CR request: - moved all PAGE_* constants to Friendica\Model\Contact class - fixed all references of both classes * Ops, need to set $a here ... * CR request: - moved Proxy class to Friendica\Module - extended BaseModule * Ops, no need for own instance of $a when self::getApp() is around. * Proxy-rewrite: - proxy_url() and proxy_parse_html() are both non-module functions (now methods) - so they must be splitted into a seperate class - also the SIZE_* and DEFAULT_TIME constants are both not relevant to module * No instances from utility classes * Fixed error: - proxify*() is now located in `Friendica\Util\ProxyUtils` * Moved back to original place, ops? How did they move here? Well, it was not intended by me. * Removed duplicate (left-over from split) constants and static array. Thank to MrPetovan finding it. * Renamed ProxyUtils -> Proxy and aliased it back to ProxyUtils. * Rewrite: - stopped using deprecated NETWORK_* constants, now Protocol::* should be used - still left them intact for slow/lazy developers ... * Ops, was added accidentally ... * Ops, why these wrong moves? * Ops, one to much (thanks to MrPetovan) * Ops, wrong moving ... * moved back to original place ... * spaces added * empty lines add for better readability. * convertered spaces -> tab for code indenting. * CR request: Add space between if and brace. * CR requests fixed + move reverted - ops, src/Module/*.php has been moved to src/Network/ accidentally - reverted some parts in src/Database/DBA.php as pointed out by Annando - removed internal TODO items - added some spaces for better readability
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. <?php
  2. /**
  3. * @file mod/salmon.php
  4. */
  5. use Friendica\App;
  6. use Friendica\Core\Logger;
  7. use Friendica\Core\Protocol;
  8. use Friendica\Database\DBA;
  9. use Friendica\DI;
  10. use Friendica\Model\Contact;
  11. use Friendica\Protocol\ActivityNamespace;
  12. use Friendica\Protocol\OStatus;
  13. use Friendica\Protocol\Salmon;
  14. use Friendica\Util\Crypto;
  15. use Friendica\Util\Network;
  16. use Friendica\Util\Strings;
  17. function salmon_post(App $a, $xml = '') {
  18. if (empty($xml)) {
  19. $xml = Network::postdata();
  20. }
  21. Logger::log('new salmon ' . $xml, Logger::DATA);
  22. $nick = (($a->argc > 1) ? Strings::escapeTags(trim($a->argv[1])) : '');
  23. $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' AND `account_expired` = 0 AND `account_removed` = 0 LIMIT 1",
  24. DBA::escape($nick)
  25. );
  26. if (! DBA::isResult($r)) {
  27. throw new \Friendica\Network\HTTPException\InternalServerErrorException();
  28. }
  29. $importer = $r[0];
  30. // parse the xml
  31. $dom = simplexml_load_string($xml,'SimpleXMLElement',0, ActivityNamespace::SALMON_ME);
  32. $base = null;
  33. // figure out where in the DOM tree our data is hiding
  34. if (!empty($dom->provenance->data))
  35. $base = $dom->provenance;
  36. elseif (!empty($dom->env->data))
  37. $base = $dom->env;
  38. elseif (!empty($dom->data))
  39. $base = $dom;
  40. if (empty($base)) {
  41. Logger::log('unable to locate salmon data in xml ');
  42. throw new \Friendica\Network\HTTPException\BadRequestException();
  43. }
  44. // Stash the signature away for now. We have to find their key or it won't be good for anything.
  45. $signature = Strings::base64UrlDecode($base->sig);
  46. // unpack the data
  47. // strip whitespace so our data element will return to one big base64 blob
  48. $data = str_replace([" ","\t","\r","\n"],["","","",""],$base->data);
  49. // stash away some other stuff for later
  50. $type = $base->data[0]->attributes()->type[0];
  51. $keyhash = $base->sig[0]->attributes()->keyhash[0];
  52. $encoding = $base->encoding;
  53. $alg = $base->alg;
  54. // Salmon magic signatures have evolved and there is no way of knowing ahead of time which
  55. // flavour we have. We'll try and verify it regardless.
  56. $stnet_signed_data = $data;
  57. $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
  58. $compliant_format = str_replace('=', '', $signed_data);
  59. // decode the data
  60. $data = Strings::base64UrlDecode($data);
  61. $author = OStatus::salmonAuthor($data, $importer);
  62. $author_link = $author["author-link"];
  63. if(! $author_link) {
  64. Logger::log('Could not retrieve author URI.');
  65. throw new \Friendica\Network\HTTPException\BadRequestException();
  66. }
  67. // Once we have the author URI, go to the web and try to find their public key
  68. Logger::log('Fetching key for ' . $author_link);
  69. $key = Salmon::getKey($author_link, $keyhash);
  70. if(! $key) {
  71. Logger::log('Could not retrieve author key.');
  72. throw new \Friendica\Network\HTTPException\BadRequestException();
  73. }
  74. $key_info = explode('.',$key);
  75. $m = Strings::base64UrlDecode($key_info[1]);
  76. $e = Strings::base64UrlDecode($key_info[2]);
  77. Logger::log('key details: ' . print_r($key_info,true), Logger::DEBUG);
  78. $pubkey = Crypto::meToPem($m, $e);
  79. // We should have everything we need now. Let's see if it verifies.
  80. // Try GNU Social format
  81. $verify = Crypto::rsaVerify($signed_data, $signature, $pubkey);
  82. $mode = 1;
  83. if (! $verify) {
  84. Logger::log('message did not verify using protocol. Trying compliant format.');
  85. $verify = Crypto::rsaVerify($compliant_format, $signature, $pubkey);
  86. $mode = 2;
  87. }
  88. if (! $verify) {
  89. Logger::log('message did not verify using padding. Trying old statusnet format.');
  90. $verify = Crypto::rsaVerify($stnet_signed_data, $signature, $pubkey);
  91. $mode = 3;
  92. }
  93. if (! $verify) {
  94. Logger::log('Message did not verify. Discarding.');
  95. throw new \Friendica\Network\HTTPException\BadRequestException();
  96. }
  97. Logger::log('Message verified with mode '.$mode);
  98. /*
  99. *
  100. * If we reached this point, the message is good. Now let's figure out if the author is allowed to send us stuff.
  101. *
  102. */
  103. $r = q("SELECT * FROM `contact` WHERE `network` IN ('%s', '%s')
  104. AND (`nurl` = '%s' OR `alias` = '%s' OR `alias` = '%s')
  105. AND `uid` = %d LIMIT 1",
  106. DBA::escape(Protocol::OSTATUS),
  107. DBA::escape(Protocol::DFRN),
  108. DBA::escape(Strings::normaliseLink($author_link)),
  109. DBA::escape($author_link),
  110. DBA::escape(Strings::normaliseLink($author_link)),
  111. intval($importer['uid'])
  112. );
  113. if (!DBA::isResult($r)) {
  114. Logger::log('Author ' . $author_link . ' unknown to user ' . $importer['uid'] . '.');
  115. if (DI::pConfig()->get($importer['uid'], 'system', 'ostatus_autofriend')) {
  116. $result = Contact::createFromProbe($importer['uid'], $author_link);
  117. if ($result['success']) {
  118. $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND ( `url` = '%s' OR `alias` = '%s')
  119. AND `uid` = %d LIMIT 1",
  120. DBA::escape(Protocol::OSTATUS),
  121. DBA::escape($author_link),
  122. DBA::escape($author_link),
  123. intval($importer['uid'])
  124. );
  125. }
  126. }
  127. }
  128. // Have we ignored the person?
  129. // If so we can not accept this post.
  130. //if((DBA::isResult($r)) && (($r[0]['readonly']) || ($r[0]['rel'] == Contact::FOLLOWER) || ($r[0]['blocked']))) {
  131. if (DBA::isResult($r) && $r[0]['blocked']) {
  132. Logger::log('Ignoring this author.');
  133. throw new \Friendica\Network\HTTPException\AcceptedException();
  134. }
  135. // Placeholder for hub discovery.
  136. $hub = '';
  137. $contact_rec = ((DBA::isResult($r)) ? $r[0] : []);
  138. OStatus::import($data, $importer, $contact_rec, $hub);
  139. throw new \Friendica\Network\HTTPException\OKException();
  140. }