]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Salmon.php
Merge pull request #8135 from annando/brief
[friendica.git] / src / Protocol / Salmon.php
1 <?php
2 /**
3  * @file src/Protocol/Salmon.php
4  */
5 namespace Friendica\Protocol;
6
7 use Friendica\Core\Logger;
8 use Friendica\Network\Probe;
9 use Friendica\Util\Crypto;
10 use Friendica\Util\Network;
11 use Friendica\Util\Strings;
12 use Friendica\Util\XML;
13
14 /**
15  * Salmon Protocol class
16  *
17  * The Salmon Protocol is a message exchange protocol running over HTTP designed to decentralize commentary
18  * and annotations made against newsfeed articles such as blog posts.
19  */
20 class Salmon
21 {
22         /**
23          * @param string $uri     Uniform Resource Identifier
24          * @param string $keyhash encoded key
25          * @return mixed
26          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
27          */
28         public static function getKey($uri, $keyhash)
29         {
30                 $ret = [];
31
32                 Logger::log('Fetching salmon key for '.$uri);
33
34                 $arr = Probe::lrdd($uri);
35
36                 if (is_array($arr)) {
37                         foreach ($arr as $a) {
38                                 if ($a['@attributes']['rel'] === 'magic-public-key') {
39                                         $ret[] = $a['@attributes']['href'];
40                                 }
41                         }
42                 } else {
43                         return '';
44                 }
45
46                 // We have found at least one key URL
47                 // If it's inline, parse it - otherwise get the key
48
49                 if (count($ret) > 0) {
50                         for ($x = 0; $x < count($ret); $x ++) {
51                                 if (substr($ret[$x], 0, 5) === 'data:') {
52                                         if (strstr($ret[$x], ',')) {
53                                                 $ret[$x] = substr($ret[$x], strpos($ret[$x], ',') + 1);
54                                         } else {
55                                                 $ret[$x] = substr($ret[$x], 5);
56                                         }
57                                 } elseif (Strings::normaliseLink($ret[$x]) == 'http://') {
58                                         $ret[$x] = Network::fetchUrl($ret[$x]);
59                                 }
60                         }
61                 }
62
63
64                 Logger::log('Key located: ' . print_r($ret, true));
65
66                 if (count($ret) == 1) {
67                         // We only found one one key so we don't care if the hash matches.
68                         // If it's the wrong key we'll find out soon enough because
69                         // message verification will fail. This also covers some older
70                         // software which don't supply a keyhash. As long as they only
71                         // have one key we'll be right.
72
73                         return $ret[0];
74                 } else {
75                         foreach ($ret as $a) {
76                                 $hash = Strings::base64UrlEncode(hash('sha256', $a));
77                                 if ($hash == $keyhash) {
78                                         return $a;
79                                 }
80                         }
81                 }
82
83                 return '';
84         }
85
86         /**
87          * @param array  $owner owner
88          * @param string $url   url
89          * @param string $slap  slap
90          * @return integer
91          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
92          */
93         public static function slapper($owner, $url, $slap)
94         {
95                 // does contact have a salmon endpoint?
96
97                 if (! strlen($url)) {
98                         return;
99                 }
100
101                 if (! $owner['sprvkey']) {
102                         Logger::log(sprintf("user '%s' (%d) does not have a salmon private key. Send failed.",
103                         $owner['username'], $owner['uid']));
104                         return;
105                 }
106
107                 Logger::log('slapper called for '.$url.'. Data: ' . $slap);
108
109                 // create a magic envelope
110
111                 $data      = Strings::base64UrlEncode($slap);
112                 $data_type = 'application/atom+xml';
113                 $encoding  = 'base64url';
114                 $algorithm = 'RSA-SHA256';
115                 $keyhash   = Strings::base64UrlEncode(hash('sha256', self::salmonKey($owner['spubkey'])), true);
116
117                 $precomputed = '.' . Strings::base64UrlEncode($data_type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($algorithm);
118
119                 // GNU Social format
120                 $signature   = Strings::base64UrlEncode(Crypto::rsaSign($data . $precomputed, $owner['sprvkey']));
121
122                 // Compliant format
123                 $signature2  = Strings::base64UrlEncode(Crypto::rsaSign(str_replace('=', '', $data . $precomputed), $owner['sprvkey']));
124
125                 // Old Status.net format
126                 $signature3  = Strings::base64UrlEncode(Crypto::rsaSign($data, $owner['sprvkey']));
127
128                 // At first try the non compliant method that works for GNU Social
129                 $xmldata = ["me:env" => ["me:data" => $data,
130                                 "@attributes" => ["type" => $data_type],
131                                 "me:encoding" => $encoding,
132                                 "me:alg" => $algorithm,
133                                 "me:sig" => $signature,
134                                 "@attributes2" => ["key_id" => $keyhash]]];
135
136                 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
137
138                 $salmon = XML::fromArray($xmldata, $xml, false, $namespaces);
139
140                 // slap them
141                 $postResult = Network::post($url, $salmon, [
142                         'Content-type: application/magic-envelope+xml',
143                         'Content-length: ' . strlen($salmon)
144                 ]);
145
146                 $return_code = $postResult->getReturnCode();
147
148                 // check for success, e.g. 2xx
149
150                 if ($return_code > 299) {
151                         Logger::log('GNU Social salmon failed. Falling back to compliant mode');
152
153                         // Now try the compliant mode that normally isn't used for GNU Social
154                         $xmldata = ["me:env" => ["me:data" => $data,
155                                         "@attributes" => ["type" => $data_type],
156                                         "me:encoding" => $encoding,
157                                         "me:alg" => $algorithm,
158                                         "me:sig" => $signature2,
159                                         "@attributes2" => ["key_id" => $keyhash]]];
160
161                         $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
162
163                         $salmon = XML::fromArray($xmldata, $xml, false, $namespaces);
164
165                         // slap them
166                         $postResult = Network::post($url, $salmon, [
167                                 'Content-type: application/magic-envelope+xml',
168                                 'Content-length: ' . strlen($salmon)
169                         ]);
170                         $return_code = $postResult->getReturnCode();
171                 }
172
173                 if ($return_code > 299) {
174                         Logger::log('compliant salmon failed. Falling back to old status.net');
175
176                         // Last try. This will most likely fail as well.
177                         $xmldata = ["me:env" => ["me:data" => $data,
178                                         "@attributes" => ["type" => $data_type],
179                                         "me:encoding" => $encoding,
180                                         "me:alg" => $algorithm,
181                                         "me:sig" => $signature3,
182                                         "@attributes2" => ["key_id" => $keyhash]]];
183
184                         $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
185
186                         $salmon = XML::fromArray($xmldata, $xml, false, $namespaces);
187
188                         // slap them
189                         $postResult = Network::post($url, $salmon, [
190                                 'Content-type: application/magic-envelope+xml',
191                                 'Content-length: ' . strlen($salmon)]);
192                         $return_code = $postResult->getReturnCode();
193                 }
194
195                 Logger::log('slapper for '.$url.' returned ' . $return_code);
196
197                 if (! $return_code) {
198                         return -1;
199                 }
200
201                 if (($return_code == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
202                         return -1;
203                 }
204
205                 return (($return_code >= 200) && ($return_code < 300)) ? 0 : 1;
206         }
207
208         /**
209          * @param string $pubkey public key
210          * @return string
211          * @throws \Exception
212          */
213         public static function salmonKey($pubkey)
214         {
215                 Crypto::pemToMe($pubkey, $m, $e);
216                 return 'RSA' . '.' . Strings::base64UrlEncode($m, true) . '.' . Strings::base64UrlEncode($e, true);
217         }
218 }