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