]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
Fixing SQL error when receiving DFRN posts (#5527)
[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\DBA;
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 (!DBA::isResult($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' ) ", DBA::escape($dfrn_id), DBA::escape($dfrn_id));
78                         break;
79                 case 0:
80                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
81                         break;
82                 case 1:
83                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($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                 DBA::escape($a->argv[1])
108         );
109
110         if (!DBA::isResult($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::fetchFirst("SELECT *, `name` as `senderName`,
216                                         0 AS `importer_uid`,
217                                         '' AS `uprvkey`,
218                                         'UTC' AS `timezone`,
219                                         '' AS `nickname`,
220                                         '' AS `sprvkey`,
221                                         '' AS `spubkey`,
222                                         0 AS `page-flags`,
223                                         0 AS `account-type`,
224                                         0 AS `prvnets`
225                                         FROM `contact`
226                                         WHERE NOT `blocked` AND `id` = ? LIMIT 1",
227                                         $contact['id']);
228
229         // This should never fail
230         if (!DBA::isResult($importer)) {
231                 logger('Contact not found for address ' . $msg['author']);
232                 System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
233         }
234
235         logger('Importing post from ' . $msg['author'] . ' with the public envelope.', LOGGER_DEBUG);
236
237         // Now we should be able to import it
238         $ret = DFRN::import($msg['message'], $importer);
239         System::xmlExit($ret, 'Done');
240 }
241
242 function dfrn_dispatch_private($user, $postdata)
243 {
244         $msg = Diaspora::decodeRaw($user, $postdata);
245         if (!$msg) {
246                 System::xmlExit(4, 'Unable to parse message');
247         }
248
249         // Check if the user has got this contact
250         $cid = Contact::getIdForURL($msg['author'], $user['uid']);
251         if (!$cid) {
252                 // Otherwise there should be a public contact
253                 $cid = Contact::getIdForURL($msg['author']);
254                 if (!$cid) {
255                         logger('Contact not found for address ' . $msg['author']);
256                         System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
257                 }
258         }
259
260         // We now have some contact, so we fetch it
261         $importer = DBA::fetchFirst("SELECT *, `name` as `senderName`
262                                         FROM `contact`
263                                         WHERE NOT `blocked` AND `id` = ? LIMIT 1",
264                                         $cid);
265
266         // This should never fail
267         if (!DBA::isResult($importer)) {
268                 logger('Contact not found for address ' . $msg['author']);
269                 System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
270         }
271
272         // Set the user id. This is important if this is a public contact
273         $importer['importer_uid']  = $user['uid'];
274
275         $importer = array_merge($importer, $user);
276
277         logger('Importing post from ' . $msg['author'] . ' to ' . $user['nickname'] . ' with the private envelope.', LOGGER_DEBUG);
278
279         // Now we should be able to import it
280         $ret = DFRN::import($msg['message'], $importer);
281         System::xmlExit($ret, 'Done');
282 }
283
284 function dfrn_notify_content(App $a) {
285
286         if (x($_GET,'dfrn_id')) {
287
288                 /*
289                  * initial communication from external contact, $direction is their direction.
290                  * If this is a duplex communication, ours will be the opposite.
291                  */
292
293                 $dfrn_id = notags(trim($_GET['dfrn_id']));
294                 $dfrn_version = (float) $_GET['dfrn_version'];
295                 $rino_remote = ((x($_GET,'rino')) ? intval($_GET['rino']) : 0);
296                 $type = "";
297                 $last_update = "";
298
299                 logger('new notification dfrn_id=' . $dfrn_id);
300
301                 $direction = (-1);
302                 if (strpos($dfrn_id,':') == 1) {
303                         $direction = intval(substr($dfrn_id,0,1));
304                         $dfrn_id = substr($dfrn_id,2);
305                 }
306
307                 $hash = random_string();
308
309                 $status = 0;
310
311                 DBA::delete('challenge', ["`expire` < ?", time()]);
312
313                 $fields = ['challenge' => $hash, 'dfrn-id' => $dfrn_id, 'expire' => time() + 90,
314                         'type' => $type, 'last_update' => $last_update];
315                 DBA::insert('challenge', $fields);
316
317                 logger('challenge=' . $hash, LOGGER_DATA);
318
319                 $sql_extra = '';
320                 switch($direction) {
321                         case (-1):
322                                 $sql_extra = sprintf(" AND (`issued-id` = '%s' OR `dfrn-id` = '%s') ", DBA::escape($dfrn_id), DBA::escape($dfrn_id));
323                                 $my_id = $dfrn_id;
324                                 break;
325                         case 0:
326                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
327                                 $my_id = '1:' . $dfrn_id;
328                                 break;
329                         case 1:
330                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
331                                 $my_id = '0:' . $dfrn_id;
332                                 break;
333                         default:
334                                 $status = 1;
335                                 break; // NOTREACHED
336                 }
337
338                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`page-flags` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
339                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s'
340                                 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
341                                 DBA::escape($a->argv[1])
342                 );
343
344                 if (!DBA::isResult($r)) {
345                         logger('No user data found for ' . $a->argv[1] . ' - SQL: ' . $sql_extra);
346                         killme();
347                 }
348
349                 logger("Remote rino version: ".$rino_remote." for ".$r[0]["url"], LOGGER_DATA);
350
351                 $challenge    = '';
352                 $encrypted_id = '';
353                 $id_str       = $my_id . '.' . mt_rand(1000,9999);
354
355                 $prv_key = trim($r[0]['prvkey']);
356                 $pub_key = trim($r[0]['pubkey']);
357                 $dplx    = intval($r[0]['duplex']);
358
359                 if (($dplx && strlen($prv_key)) || (strlen($prv_key) && !strlen($pub_key))) {
360                         openssl_private_encrypt($hash, $challenge, $prv_key);
361                         openssl_private_encrypt($id_str, $encrypted_id, $prv_key);
362                 } elseif (strlen($pub_key)) {
363                         openssl_public_encrypt($hash, $challenge, $pub_key);
364                         openssl_public_encrypt($id_str, $encrypted_id, $pub_key);
365                 } else {
366                         /// @TODO these kind of else-blocks are making the code harder to understand
367                         $status = 1;
368                 }
369
370                 $challenge    = bin2hex($challenge);
371                 $encrypted_id = bin2hex($encrypted_id);
372
373
374                 $rino = Config::get('system', 'rino_encrypt');
375                 $rino = intval($rino);
376
377                 logger("Local rino version: ". $rino, LOGGER_DATA);
378
379                 // if requested rino is lower than enabled local rino, lower local rino version
380                 // if requested rino is higher than enabled local rino, reply with local rino
381                 if ($rino_remote < $rino) {
382                         $rino = $rino_remote;
383                 }
384
385                 if (($r[0]['rel'] && ($r[0]['rel'] != Contact::SHARING)) || ($r[0]['page-flags'] == Contact::PAGE_COMMUNITY)) {
386                         $perm = 'rw';
387                 } else {
388                         $perm = 'r';
389                 }
390
391                 header("Content-type: text/xml");
392
393                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
394                         . '<dfrn_notify>' . "\r\n"
395                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
396                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
397                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
398                         . "\t" . '<perm>' . $perm . '</perm>' . "\r\n"
399                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
400                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
401                         . '</dfrn_notify>' . "\r\n" ;
402
403                 killme();
404         }
405 }