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