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