]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
Merge pull request #2 from friendica/master
[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
16 require_once 'include/items.php';
17 require_once 'include/event.php';
18
19 function dfrn_notify_post(App $a) {
20         logger(__function__, LOGGER_TRACE);
21
22         if (empty($_POST)) {
23                 require_once 'mod/salmon.php';
24                 salmon_post($a);
25         }
26
27         $dfrn_id      = ((x($_POST,'dfrn_id'))      ? notags(trim($_POST['dfrn_id']))   : '');
28         $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version']    : 2.0);
29         $challenge    = ((x($_POST,'challenge'))    ? notags(trim($_POST['challenge'])) : '');
30         $data         = ((x($_POST,'data'))         ? $_POST['data']                    : '');
31         $key          = ((x($_POST,'key'))          ? $_POST['key']                     : '');
32         $rino_remote  = ((x($_POST,'rino'))         ? intval($_POST['rino'])            :  0);
33         $dissolve     = ((x($_POST,'dissolve'))     ? intval($_POST['dissolve'])        :  0);
34         $perm         = ((x($_POST,'perm'))         ? notags(trim($_POST['perm']))      : 'r');
35         $ssl_policy   = ((x($_POST,'ssl_policy'))   ? notags(trim($_POST['ssl_policy'])): 'none');
36         $page         = ((x($_POST,'page'))         ? intval($_POST['page'])            :  0);
37
38         $forum = (($page == 1) ? 1 : 0);
39         $prv   = (($page == 2) ? 1 : 0);
40
41         $writable = (-1);
42         if ($dfrn_version >= 2.21) {
43                 $writable = (($perm === 'rw') ? 1 : 0);
44         }
45
46         $direction = (-1);
47         if (strpos($dfrn_id, ':') == 1) {
48                 $direction = intval(substr($dfrn_id, 0, 1));
49                 $dfrn_id = substr($dfrn_id, 2);
50         }
51
52         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
53                 dbesc($dfrn_id),
54                 dbesc($challenge)
55         );
56         if (! DBM::is_result($r)) {
57                 logger('dfrn_notify: could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
58                 System::xmlExit(3, 'Could not match challenge');
59         }
60
61         $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s'",
62                 dbesc($dfrn_id),
63                 dbesc($challenge)
64         );
65
66         // find the local user who owns this relationship.
67
68         $sql_extra = '';
69         switch ($direction) {
70                 case (-1):
71                         $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
72                         break;
73                 case 0:
74                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
75                         break;
76                 case 1:
77                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
78                         break;
79                 default:
80                         System::xmlExit(3, 'Invalid direction');
81                         break; // NOTREACHED
82         }
83
84         /*
85          * be careful - $importer will contain both the contact information for the contact
86          * sending us the post, and also the user information for the person receiving it.
87          * since they are mixed together, it is easy to get them confused.
88          */
89
90         $r = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
91                                         `contact`.`pubkey` AS `cpubkey`,
92                                         `contact`.`prvkey` AS `cprvkey`,
93                                         `contact`.`thumb` AS `thumb`,
94                                         `contact`.`url` as `url`,
95                                         `contact`.`name` as `senderName`,
96                                         `user`.*
97                         FROM `contact`
98                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
99                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
100                                 AND `user`.`nickname` = '%s' AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
101                 dbesc($a->argv[1])
102         );
103
104         if (! DBM::is_result($r)) {
105                 logger('dfrn_notify: contact not found for dfrn_id ' . $dfrn_id);
106                 System::xmlExit(3, 'Contact not found');
107                 //NOTREACHED
108         }
109
110         // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
111
112         $importer = $r[0];
113
114         logger("Remote rino version: ".$rino_remote." for ".$importer["url"], LOGGER_DEBUG);
115
116         if ((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
117                 q("UPDATE `contact` SET `writable` = %d, forum = %d, prv = %d WHERE `id` = %d",
118                         intval(($writable == (-1)) ? $importer['writable'] : $writable),
119                         intval($forum),
120                         intval($prv),
121                         intval($importer['id'])
122                 );
123                 if ($writable != (-1)) {
124                         $importer['writable'] = $writable;
125                 }
126                 $importer['forum'] = $page;
127         }
128
129
130         // if contact's ssl policy changed, update our links
131
132         $importer = Contact::updateSslPolicy($importer, $ssl_policy);
133
134         logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
135         logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
136
137         if ($dissolve == 1) {
138                 // Relationship is dissolved permanently
139                 Contact::remove($importer['id']);
140                 logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
141                 System::xmlExit(0, 'relationship dissolved');
142         }
143
144         $rino = Config::get('system', 'rino_encrypt');
145         $rino = intval($rino);
146
147         logger("Local rino version: " .  $rino, LOGGER_DEBUG);
148
149         if (strlen($key)) {
150
151                 // if local rino is lower than remote rino, abort: should not happen!
152                 // but only for $remote_rino > 1, because old code did't send rino version
153                 if ($rino_remote > 1 && $rino < $rino_remote) {
154                         logger("rino version '$rino_remote' is lower than supported '$rino'");
155                         System::xmlExit(0, "rino version '$rino_remote' is lower than supported '$rino'");
156                 }
157
158                 $rawkey = hex2bin(trim($key));
159                 logger('rino: md5 raw key: ' . md5($rawkey));
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         $ret = DFRN::import($data, $importer);
192         System::xmlExit($ret, 'Processed');
193
194         // NOTREACHED
195 }
196
197
198 function dfrn_notify_content(App $a) {
199
200         if(x($_GET,'dfrn_id')) {
201
202                 /*
203                  * initial communication from external contact, $direction is their direction.
204                  * If this is a duplex communication, ours will be the opposite.
205                  */
206
207                 $dfrn_id = notags(trim($_GET['dfrn_id']));
208                 $dfrn_version = (float) $_GET['dfrn_version'];
209                 $rino_remote = ((x($_GET,'rino')) ? intval($_GET['rino']) : 0);
210                 $type = "";
211                 $last_update = "";
212
213                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
214
215                 $direction = (-1);
216                 if(strpos($dfrn_id,':') == 1) {
217                         $direction = intval(substr($dfrn_id,0,1));
218                         $dfrn_id = substr($dfrn_id,2);
219                 }
220
221                 $hash = random_string();
222
223                 $status = 0;
224
225                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
226
227                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
228                         VALUES( '%s', '%s', %d, '%s', '%s' ) ",
229                         dbesc($hash),
230                         dbesc($dfrn_id),
231                         intval(time() + 90 ),
232                         dbesc($type),
233                         dbesc($last_update)
234                 );
235
236                 logger('dfrn_notify: challenge=' . $hash, LOGGER_DEBUG);
237
238                 $sql_extra = '';
239                 switch($direction) {
240                         case (-1):
241                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
242                                 $my_id = $dfrn_id;
243                                 break;
244                         case 0:
245                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
246                                 $my_id = '1:' . $dfrn_id;
247                                 break;
248                         case 1:
249                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
250                                 $my_id = '0:' . $dfrn_id;
251                                 break;
252                         default:
253                                 $status = 1;
254                                 break; // NOTREACHED
255                 }
256
257                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`page-flags` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
258                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s'
259                                 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
260                                 dbesc($a->argv[1])
261                 );
262
263                 if (! DBM::is_result($r)) {
264                         $status = 1;
265                 }
266
267                 logger("Remote rino version: ".$rino_remote." for ".$r[0]["url"], LOGGER_DEBUG);
268
269                 $challenge    = '';
270                 $encrypted_id = '';
271                 $id_str       = $my_id . '.' . mt_rand(1000,9999);
272
273                 $prv_key = trim($r[0]['prvkey']);
274                 $pub_key = trim($r[0]['pubkey']);
275                 $dplx    = intval($r[0]['duplex']);
276
277                 if ((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) {
278                         openssl_private_encrypt($hash, $challenge, $prv_key);
279                         openssl_private_encrypt($id_str, $encrypted_id, $prv_key);
280                 } elseif (strlen($pub_key)) {
281                         openssl_public_encrypt($hash, $challenge, $pub_key);
282                         openssl_public_encrypt($id_str, $encrypted_id, $pub_key);
283                 } else {
284                         /// @TODO these kind of else-blocks are making the code harder to understand
285                         $status = 1;
286                 }
287
288                 $challenge    = bin2hex($challenge);
289                 $encrypted_id = bin2hex($encrypted_id);
290
291
292                 $rino = Config::get('system', 'rino_encrypt');
293                 $rino = intval($rino);
294
295                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
296
297                 // if requested rino is lower than enabled local rino, lower local rino version
298                 // if requested rino is higher than enabled local rino, reply with local rino
299                 if ($rino_remote < $rino) {
300                         $rino = $rino_remote;
301                 }
302
303                 if((($r[0]['rel']) && ($r[0]['rel'] != CONTACT_IS_SHARING)) || ($r[0]['page-flags'] == PAGE_COMMUNITY)) {
304                         $perm = 'rw';
305                 } else {
306                         $perm = 'r';
307                 }
308
309                 header("Content-type: text/xml");
310
311                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
312                         . '<dfrn_notify>' . "\r\n"
313                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
314                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
315                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
316                         . "\t" . '<perm>' . $perm . '</perm>' . "\r\n"
317                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
318                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
319                         . '</dfrn_notify>' . "\r\n" ;
320
321                 killme();
322         }
323
324 }