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