]> git.mxchange.org Git - friendica.git/blob - mod/salmon.php
Move xml_status and http_status_exit
[friendica.git] / mod / salmon.php
1 <?php
2 /**
3  * @file mod/salmon.php
4  */
5 use Friendica\App;
6 use Friendica\Core\PConfig;
7 use Friendica\Database\DBM;
8 use Friendica\Model\Contact;
9 use Friendica\Protocol\OStatus;
10 use Friendica\Protocol\Salmon;
11 use Friendica\Util\Crypto;
12 use Friendica\Util\Network;
13
14 require_once 'include/items.php';
15
16 function salmon_return($val) {
17
18         if($val >= 400)
19                 $err = 'Error';
20         if($val >= 200 && $val < 300)
21                 $err = 'OK';
22
23         logger('mod-salmon returns ' . $val);
24         header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
25         killme();
26
27 }
28
29 function salmon_post(App $a) {
30
31         $xml = file_get_contents('php://input');
32
33         logger('mod-salmon: new salmon ' . $xml, LOGGER_DATA);
34
35         $nick       = (($a->argc > 1) ? notags(trim($a->argv[1])) : '');
36         $mentions   = (($a->argc > 2 && $a->argv[2] === 'mention') ? true : false);
37
38         $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' AND `account_expired` = 0 AND `account_removed` = 0 LIMIT 1",
39                 dbesc($nick)
40         );
41         if (! DBM::is_result($r)) {
42                 Network::httpStatusExit(500);
43         }
44
45         $importer = $r[0];
46
47         // parse the xml
48
49         $dom = simplexml_load_string($xml,'SimpleXMLElement',0,NAMESPACE_SALMON_ME);
50
51         // figure out where in the DOM tree our data is hiding
52
53         if($dom->provenance->data)
54                 $base = $dom->provenance;
55         elseif($dom->env->data)
56                 $base = $dom->env;
57         elseif($dom->data)
58                 $base = $dom;
59
60         if(! $base) {
61                 logger('mod-salmon: unable to locate salmon data in xml ');
62                 Network::httpStatusExit(400);
63         }
64
65         // Stash the signature away for now. We have to find their key or it won't be good for anything.
66
67
68         $signature = base64url_decode($base->sig);
69
70         // unpack the  data
71
72         // strip whitespace so our data element will return to one big base64 blob
73         $data = str_replace([" ","\t","\r","\n"],["","","",""],$base->data);
74
75         // stash away some other stuff for later
76
77         $type = $base->data[0]->attributes()->type[0];
78         $keyhash = $base->sig[0]->attributes()->keyhash[0];
79         $encoding = $base->encoding;
80         $alg = $base->alg;
81
82         // Salmon magic signatures have evolved and there is no way of knowing ahead of time which
83         // flavour we have. We'll try and verify it regardless.
84
85         $stnet_signed_data = $data;
86
87         $signed_data = $data  . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
88
89         $compliant_format = str_replace('=', '', $signed_data);
90
91
92         // decode the data
93         $data = base64url_decode($data);
94
95         $author = OStatus::salmonAuthor($data, $importer);
96         $author_link = $author["author-link"];
97
98         if(! $author_link) {
99                 logger('mod-salmon: Could not retrieve author URI.');
100                 Network::httpStatusExit(400);
101         }
102
103         // Once we have the author URI, go to the web and try to find their public key
104
105         logger('mod-salmon: Fetching key for ' . $author_link);
106
107         $key = Salmon::getKey($author_link, $keyhash);
108
109         if(! $key) {
110                 logger('mod-salmon: Could not retrieve author key.');
111                 Network::httpStatusExit(400);
112         }
113
114         $key_info = explode('.',$key);
115
116         $m = base64url_decode($key_info[1]);
117         $e = base64url_decode($key_info[2]);
118
119         logger('mod-salmon: key details: ' . print_r($key_info,true), LOGGER_DEBUG);
120
121         $pubkey = Crypto::meToPem($m, $e);
122
123         // We should have everything we need now. Let's see if it verifies.
124
125         // Try GNU Social format
126         $verify = Crypto::rsaVerify($signed_data, $signature, $pubkey);
127         $mode = 1;
128
129         if (! $verify) {
130                 logger('mod-salmon: message did not verify using protocol. Trying compliant format.');
131                 $verify = Crypto::rsaVerify($compliant_format, $signature, $pubkey);
132                 $mode = 2;
133         }
134
135         if (! $verify) {
136                 logger('mod-salmon: message did not verify using padding. Trying old statusnet format.');
137                 $verify = Crypto::rsaVerify($stnet_signed_data, $signature, $pubkey);
138                 $mode = 3;
139         }
140
141         if (! $verify) {
142                 logger('mod-salmon: Message did not verify. Discarding.');
143                 Network::httpStatusExit(400);
144         }
145
146         logger('mod-salmon: Message verified with mode '.$mode);
147
148
149         /*
150         *
151         * If we reached this point, the message is good. Now let's figure out if the author is allowed to send us stuff.
152         *
153         */
154
155         $r = q("SELECT * FROM `contact` WHERE `network` IN ('%s', '%s')
156                                                 AND (`nurl` = '%s' OR `alias` = '%s' OR `alias` = '%s')
157                                                 AND `uid` = %d LIMIT 1",
158                 dbesc(NETWORK_OSTATUS),
159                 dbesc(NETWORK_DFRN),
160                 dbesc(normalise_link($author_link)),
161                 dbesc($author_link),
162                 dbesc(normalise_link($author_link)),
163                 intval($importer['uid'])
164         );
165         if (! DBM::is_result($r)) {
166                 logger('mod-salmon: Author unknown to us.');
167                 if(PConfig::get($importer['uid'],'system','ostatus_autofriend')) {
168                         $result = Contact::createFromProbe($importer['uid'], $author_link);
169                         if($result['success']) {
170                                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND ( `url` = '%s' OR `alias` = '%s')
171                                         AND `uid` = %d LIMIT 1",
172                                         dbesc(NETWORK_OSTATUS),
173                                         dbesc($author_link),
174                                         dbesc($author_link),
175                                         intval($importer['uid'])
176                                 );
177                         }
178                 }
179         }
180
181         // Have we ignored the person?
182         // If so we can not accept this post.
183
184         //if((DBM::is_result($r)) && (($r[0]['readonly']) || ($r[0]['rel'] == CONTACT_IS_FOLLOWER) || ($r[0]['blocked']))) {
185         if (DBM::is_result($r) && $r[0]['blocked']) {
186                 logger('mod-salmon: Ignoring this author.');
187                 Network::httpStatusExit(202);
188                 // NOTREACHED
189         }
190
191         // Placeholder for hub discovery.
192         $hub = '';
193
194         $contact_rec = ((DBM::is_result($r)) ? $r[0] : null);
195
196         OStatus::import($data, $importer, $contact_rec, $hub);
197
198         Network::httpStatusExit(200);
199 }