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