]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
Merge remote-tracking branch 'upstream/develop' into dfrn-2
[friendica.git] / mod / dfrn_notify.php
1 <?php
2
3 /**
4  * @file mod/dfrn_notify.php
5  * @brief The dfrn notify endpoint
6  * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
7  */
8
9 use Friendica\App;
10 use Friendica\Core\Config;
11 use Friendica\Core\System;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
14 use Friendica\Protocol\DFRN;
15 use Friendica\Protocol\Diaspora;
16
17 require_once 'include/items.php';
18
19 function dfrn_notify_post(App $a) {
20         logger(__function__, LOGGER_TRACE);
21
22         $postdata = file_get_contents('php://input');
23
24         if (empty($_POST) || !empty($postdata)) {
25                 $data = json_decode($postdata);
26                 if (is_object($data)) {
27                         $nick = defaults($a->argv, 1, '');
28                         $user = dba::selectFirst('user', [], ['nickname' => $nick, 'account_expired' => false, 'account_removed' => false]);
29                         if (!DBM::is_result($user)) {
30                                 System::httpExit(500);
31                         }
32                         $msg = Diaspora::decodeRaw($user, $postdata);
33
34                         // Check if the user has got this contact
35                         $cid = getIdForURL($msg['author'], $user['uid']);
36                         if (!$cid) {
37                                 // Otherwise there should be a public contact
38                                 $cid = getIdForURL($msg['author']);
39                                 if (!$cid) {
40                                         logger('Contact not found for address ' . $msg['author']);
41                                         System::xmlExit(3, 'Contact not found');
42                                 }
43                         }
44
45                         // We now have some contact, so we fetch it
46                         $importer = dba::fetch_first("SELECT *, `name` as `senderName`
47                                                         FROM `contact`
48                                                         WHERE NOT `blocked` AND `id` = ? LIMIT 1",
49                                                         $cid);
50
51                         // This should never fail
52                         if (!DBM::is_result($importer)) {
53                                 logger('Contact not found for address ' . $msg['author']);
54                                 System::xmlExit(3, 'Contact not found');
55                         }
56
57                         // Set the user id. This is important if this is a public contact
58                         $importer['uid']  = $user['uid'];
59                         $importer['importer_uid']  = $user['uid'];
60
61                         // Now we should be able to import it
62                         $ret = DFRN::import($msg['message'], $importer);
63                         System::xmlExit($ret, 'Processed');
64                 } else {
65                         require_once 'mod/salmon.php';
66                         salmon_post($a, $postdata);
67                 }
68         }
69
70         $dfrn_id      = ((x($_POST,'dfrn_id'))      ? notags(trim($_POST['dfrn_id']))   : '');
71         $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version']    : 2.0);
72         $challenge    = ((x($_POST,'challenge'))    ? notags(trim($_POST['challenge'])) : '');
73         $data         = ((x($_POST,'data'))         ? $_POST['data']                    : '');
74         $key          = ((x($_POST,'key'))          ? $_POST['key']                     : '');
75         $rino_remote  = ((x($_POST,'rino'))         ? intval($_POST['rino'])            :  0);
76         $dissolve     = ((x($_POST,'dissolve'))     ? intval($_POST['dissolve'])        :  0);
77         $perm         = ((x($_POST,'perm'))         ? notags(trim($_POST['perm']))      : 'r');
78         $ssl_policy   = ((x($_POST,'ssl_policy'))   ? notags(trim($_POST['ssl_policy'])): 'none');
79         $page         = ((x($_POST,'page'))         ? intval($_POST['page'])            :  0);
80
81         $forum = (($page == 1) ? 1 : 0);
82         $prv   = (($page == 2) ? 1 : 0);
83
84         $writable = (-1);
85         if ($dfrn_version >= 2.21) {
86                 $writable = (($perm === 'rw') ? 1 : 0);
87         }
88
89         $direction = (-1);
90         if (strpos($dfrn_id, ':') == 1) {
91                 $direction = intval(substr($dfrn_id, 0, 1));
92                 $dfrn_id = substr($dfrn_id, 2);
93         }
94
95         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
96                 dbesc($dfrn_id),
97                 dbesc($challenge)
98         );
99         if (! DBM::is_result($r)) {
100                 logger('dfrn_notify: could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
101                 System::xmlExit(3, 'Could not match challenge');
102         }
103
104         $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s'",
105                 dbesc($dfrn_id),
106                 dbesc($challenge)
107         );
108
109         // find the local user who owns this relationship.
110
111         $sql_extra = '';
112         switch ($direction) {
113                 case (-1):
114                         $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
115                         break;
116                 case 0:
117                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
118                         break;
119                 case 1:
120                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
121                         break;
122                 default:
123                         System::xmlExit(3, 'Invalid direction');
124                         break; // NOTREACHED
125         }
126
127         /*
128          * be careful - $importer will contain both the contact information for the contact
129          * sending us the post, and also the user information for the person receiving it.
130          * since they are mixed together, it is easy to get them confused.
131          */
132
133         $r = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
134                                         `contact`.`pubkey` AS `cpubkey`,
135                                         `contact`.`prvkey` AS `cprvkey`,
136                                         `contact`.`thumb` AS `thumb`,
137                                         `contact`.`url` as `url`,
138                                         `contact`.`name` as `senderName`,
139                                         `user`.*
140                         FROM `contact`
141                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
142                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
143                                 AND `user`.`nickname` = '%s' AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
144                 dbesc($a->argv[1])
145         );
146
147         if (! DBM::is_result($r)) {
148                 logger('dfrn_notify: contact not found for dfrn_id ' . $dfrn_id);
149                 System::xmlExit(3, 'Contact not found');
150                 //NOTREACHED
151         }
152
153         // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
154
155         $importer = $r[0];
156
157         logger("Remote rino version: ".$rino_remote." for ".$importer["url"], LOGGER_DEBUG);
158
159         if ((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
160                 q("UPDATE `contact` SET `writable` = %d, forum = %d, prv = %d WHERE `id` = %d",
161                         intval(($writable == (-1)) ? $importer['writable'] : $writable),
162                         intval($forum),
163                         intval($prv),
164                         intval($importer['id'])
165                 );
166                 if ($writable != (-1)) {
167                         $importer['writable'] = $writable;
168                 }
169                 $importer['forum'] = $page;
170         }
171
172
173         // if contact's ssl policy changed, update our links
174
175         $importer = Contact::updateSslPolicy($importer, $ssl_policy);
176
177         logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
178         logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
179
180         if ($dissolve == 1) {
181                 // Relationship is dissolved permanently
182                 Contact::remove($importer['id']);
183                 logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
184                 System::xmlExit(0, 'relationship dissolved');
185         }
186
187         $rino = Config::get('system', 'rino_encrypt');
188         $rino = intval($rino);
189
190         logger("Local rino version: " .  $rino, LOGGER_DEBUG);
191
192         if (strlen($key)) {
193
194                 // if local rino is lower than remote rino, abort: should not happen!
195                 // but only for $remote_rino > 1, because old code did't send rino version
196                 if ($rino_remote > 1 && $rino < $rino_remote) {
197                         logger("rino version '$rino_remote' is lower than supported '$rino'");
198                         System::xmlExit(0, "rino version '$rino_remote' is lower than supported '$rino'");
199                 }
200
201                 $rawkey = hex2bin(trim($key));
202                 logger('rino: md5 raw key: ' . md5($rawkey));
203                 $final_key = '';
204
205                 if ($dfrn_version >= 2.1) {
206                         if ((($importer['duplex']) && strlen($importer['cprvkey'])) || (! strlen($importer['cpubkey']))) {
207                                 openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
208                         } else {
209                                 openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
210                         }
211                 } else {
212                         if ((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
213                                 openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
214                         } else {
215                                 openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
216                         }
217                 }
218
219                 switch($rino_remote) {
220                         case 0:
221                         case 1:
222                                 // we got a key. old code send only the key, without RINO version.
223                                 // we assume RINO 1 if key and no RINO version
224                                 $data = DFRN::aesDecrypt(hex2bin($data), $final_key);
225                                 break;
226                         default:
227                                 logger("rino: invalid sent version '$rino_remote'");
228                                 System::xmlExit(0, "Invalid sent version '$rino_remote'");
229                 }
230
231                 logger('rino: decrypted data: ' . $data, LOGGER_DATA);
232         }
233
234         $ret = DFRN::import($data, $importer);
235         System::xmlExit($ret, 'Processed');
236
237         // NOTREACHED
238 }
239
240
241 function dfrn_notify_content(App $a) {
242
243         if(x($_GET,'dfrn_id')) {
244
245                 /*
246                  * initial communication from external contact, $direction is their direction.
247                  * If this is a duplex communication, ours will be the opposite.
248                  */
249
250                 $dfrn_id = notags(trim($_GET['dfrn_id']));
251                 $dfrn_version = (float) $_GET['dfrn_version'];
252                 $rino_remote = ((x($_GET,'rino')) ? intval($_GET['rino']) : 0);
253                 $type = "";
254                 $last_update = "";
255
256                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
257
258                 $direction = (-1);
259                 if(strpos($dfrn_id,':') == 1) {
260                         $direction = intval(substr($dfrn_id,0,1));
261                         $dfrn_id = substr($dfrn_id,2);
262                 }
263
264                 $hash = random_string();
265
266                 $status = 0;
267
268                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
269
270                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
271                         VALUES( '%s', '%s', %d, '%s', '%s' ) ",
272                         dbesc($hash),
273                         dbesc($dfrn_id),
274                         intval(time() + 90 ),
275                         dbesc($type),
276                         dbesc($last_update)
277                 );
278
279                 logger('dfrn_notify: challenge=' . $hash, LOGGER_DEBUG);
280
281                 $sql_extra = '';
282                 switch($direction) {
283                         case (-1):
284                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
285                                 $my_id = $dfrn_id;
286                                 break;
287                         case 0:
288                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
289                                 $my_id = '1:' . $dfrn_id;
290                                 break;
291                         case 1:
292                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
293                                 $my_id = '0:' . $dfrn_id;
294                                 break;
295                         default:
296                                 $status = 1;
297                                 break; // NOTREACHED
298                 }
299
300                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`page-flags` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
301                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s'
302                                 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
303                                 dbesc($a->argv[1])
304                 );
305
306                 if (! DBM::is_result($r)) {
307                         $status = 1;
308                 }
309
310                 logger("Remote rino version: ".$rino_remote." for ".$r[0]["url"], LOGGER_DEBUG);
311
312                 $challenge    = '';
313                 $encrypted_id = '';
314                 $id_str       = $my_id . '.' . mt_rand(1000,9999);
315
316                 $prv_key = trim($r[0]['prvkey']);
317                 $pub_key = trim($r[0]['pubkey']);
318                 $dplx    = intval($r[0]['duplex']);
319
320                 if ((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) {
321                         openssl_private_encrypt($hash, $challenge, $prv_key);
322                         openssl_private_encrypt($id_str, $encrypted_id, $prv_key);
323                 } elseif (strlen($pub_key)) {
324                         openssl_public_encrypt($hash, $challenge, $pub_key);
325                         openssl_public_encrypt($id_str, $encrypted_id, $pub_key);
326                 } else {
327                         /// @TODO these kind of else-blocks are making the code harder to understand
328                         $status = 1;
329                 }
330
331                 $challenge    = bin2hex($challenge);
332                 $encrypted_id = bin2hex($encrypted_id);
333
334
335                 $rino = Config::get('system', 'rino_encrypt');
336                 $rino = intval($rino);
337
338                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
339
340                 // if requested rino is lower than enabled local rino, lower local rino version
341                 // if requested rino is higher than enabled local rino, reply with local rino
342                 if ($rino_remote < $rino) {
343                         $rino = $rino_remote;
344                 }
345
346                 if((($r[0]['rel']) && ($r[0]['rel'] != CONTACT_IS_SHARING)) || ($r[0]['page-flags'] == PAGE_COMMUNITY)) {
347                         $perm = 'rw';
348                 } else {
349                         $perm = 'r';
350                 }
351
352                 header("Content-type: text/xml");
353
354                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
355                         . '<dfrn_notify>' . "\r\n"
356                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
357                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
358                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
359                         . "\t" . '<perm>' . $perm . '</perm>' . "\r\n"
360                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
361                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
362                         . '</dfrn_notify>' . "\r\n" ;
363
364                 killme();
365         }
366
367 }