]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
dfrn functions could now work/Removed unused code
[friendica.git] / mod / dfrn_notify.php
1 <?php
2
3 require_once('include/items.php');
4 require_once('include/event.php');
5
6 require_once('library/defuse/php-encryption-1.2.1/Crypto.php');
7
8 function dfrn_notify_post(&$a) {
9     logger(__function__, LOGGER_TRACE);
10         $dfrn_id      = ((x($_POST,'dfrn_id'))      ? notags(trim($_POST['dfrn_id']))   : '');
11         $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version']    : 2.0);
12         $challenge    = ((x($_POST,'challenge'))    ? notags(trim($_POST['challenge'])) : '');
13         $data         = ((x($_POST,'data'))         ? $_POST['data']                    : '');
14         $key          = ((x($_POST,'key'))          ? $_POST['key']                     : '');
15         $rino_remote  = ((x($_POST,'rino'))         ? intval($_POST['rino'])            :  0);
16         $dissolve     = ((x($_POST,'dissolve'))     ? intval($_POST['dissolve'])        :  0);
17         $perm         = ((x($_POST,'perm'))         ? notags(trim($_POST['perm']))      : 'r');
18         $ssl_policy   = ((x($_POST,'ssl_policy'))   ? notags(trim($_POST['ssl_policy'])): 'none');
19         $page         = ((x($_POST,'page'))         ? intval($_POST['page'])            :  0);
20
21         $forum = (($page == 1) ? 1 : 0);
22         $prv   = (($page == 2) ? 1 : 0);
23
24         $writable = (-1);
25         if($dfrn_version >= 2.21) {
26                 $writable = (($perm === 'rw') ? 1 : 0);
27         }
28
29         $direction = (-1);
30         if(strpos($dfrn_id,':') == 1) {
31                 $direction = intval(substr($dfrn_id,0,1));
32                 $dfrn_id = substr($dfrn_id,2);
33         }
34
35         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
36                 dbesc($dfrn_id),
37                 dbesc($challenge)
38         );
39         if(! count($r)) {
40                 logger('dfrn_notify: could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
41                 xml_status(3);
42         }
43
44         $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s'",
45                 dbesc($dfrn_id),
46                 dbesc($challenge)
47         );
48
49         // find the local user who owns this relationship.
50
51         $sql_extra = '';
52         switch($direction) {
53                 case (-1):
54                         $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
55                         break;
56                 case 0:
57                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
58                         break;
59                 case 1:
60                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
61                         break;
62                 default:
63                         xml_status(3);
64                         break; // NOTREACHED
65         }
66
67         // be careful - $importer will contain both the contact information for the contact
68         // sending us the post, and also the user information for the person receiving it.
69         // since they are mixed together, it is easy to get them confused.
70
71         $r = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
72                                         `contact`.`pubkey` AS `cpubkey`,
73                                         `contact`.`prvkey` AS `cprvkey`,
74                                         `contact`.`thumb` AS `thumb`,
75                                         `contact`.`url` as `url`,
76                                         `contact`.`name` as `senderName`,
77                                         `user`.*
78                         FROM `contact`
79                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
80                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
81                                 AND `user`.`nickname` = '%s' AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
82                 dbesc($a->argv[1])
83         );
84
85         if(! count($r)) {
86                 logger('dfrn_notify: contact not found for dfrn_id ' . $dfrn_id);
87                 xml_status(3);
88                 //NOTREACHED
89         }
90
91         // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
92
93         $importer = $r[0];
94
95         logger("Remote rino version: ".$rino_remote." for ".$importer["url"], LOGGER_DEBUG);
96
97         if((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
98                 q("UPDATE `contact` SET `writable` = %d, forum = %d, prv = %d WHERE `id` = %d",
99                         intval(($writable == (-1)) ? $importer['writable'] : $writable),
100                         intval($forum),
101                         intval($prv),
102                         intval($importer['id'])
103                 );
104                 if($writable != (-1))
105                         $importer['writable'] = $writable;
106                 $importer['forum'] = $page;
107         }
108
109
110         // if contact's ssl policy changed, update our links
111
112         fix_contact_ssl_policy($importer,$ssl_policy);
113
114         logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
115         logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
116
117         if($dissolve == 1) {
118
119                 /**
120                  * Relationship is dissolved permanently
121                  */
122
123                 require_once('include/Contact.php');
124                 contact_remove($importer['id']);
125                 logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
126                 xml_status(0);
127
128         }
129
130
131         // If we are setup as a soapbox we aren't accepting input from this person
132         // This behaviour is deactivated since it really doesn't make sense to even disallow comments
133         // The check if someone is a friend or simply a follower is done in a later place so it needn't to be done here
134         //if($importer['page-flags'] == PAGE_SOAPBOX)
135         //      xml_status(0);
136
137         $rino = get_config('system','rino_encrypt');
138         $rino = intval($rino);
139         // use RINO1 if mcrypt isn't installed and RINO2 was selected
140         if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
141
142         logger("Local rino version: ". $rino, LOGGER_DEBUG);
143
144         if(strlen($key)) {
145
146                 // if local rino is lower than remote rino, abort: should not happen!
147                 // but only for $remote_rino > 1, because old code did't send rino version
148                 if ($rino_remote_version > 1 && $rino < $rino_remote) {
149                         logger("rino version '$rino_remote' is lower than supported '$rino'");
150                         xml_status(0,"rino version '$rino_remote' is lower than supported '$rino'");
151                 }
152
153                 $rawkey = hex2bin(trim($key));
154                 logger('rino: md5 raw key: ' . md5($rawkey));
155                 $final_key = '';
156
157                 if($dfrn_version >= 2.1) {
158                         if((($importer['duplex']) && strlen($importer['cprvkey'])) || (! strlen($importer['cpubkey']))) {
159                                 openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
160                         }
161                         else {
162                                 openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
163                         }
164                 }
165                 else {
166                         if((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
167                                 openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
168                         }
169                         else {
170                                 openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
171                         }
172                 }
173
174                 #logger('rino: received key : ' . $final_key);
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 = aes_decrypt(hex2bin($data),$final_key);
182                                 break;
183                         case 2:
184                                 try {
185                                         $data = Crypto::decrypt(hex2bin($data),$final_key);
186                                 } catch (InvalidCiphertext $ex) { // VERY IMPORTANT
187                                         // Either:
188                                         //   1. The ciphertext was modified by the attacker,
189                                         //   2. The key is wrong, or
190                                         //   3. $ciphertext is not a valid ciphertext or was corrupted.
191                                         // Assume the worst.
192                                         logger('The ciphertext has been tampered with!');
193                                         xml_status(0,'The ciphertext has been tampered with!');
194                                 } catch (Ex\CryptoTestFailed $ex) {
195                                         logger('Cannot safely perform dencryption');
196                                         xml_status(0,'CryptoTestFailed');
197                                 } catch (Ex\CannotPerformOperation $ex) {
198                                         logger('Cannot safely perform decryption');
199                                         xml_status(0,'Cannot safely perform decryption');
200                                 }
201                                 break;
202                         default:
203                                 logger("rino: invalid sent verision '$rino_remote'");
204                                 xml_status(0);
205                 }
206
207
208                 logger('rino: decrypted data: ' . $data, LOGGER_DATA);
209         }
210
211         $ret = local_delivery($importer,$data);
212         xml_status($ret);
213
214         // NOTREACHED
215 }
216
217
218 function dfrn_notify_content(&$a) {
219
220         if(x($_GET,'dfrn_id')) {
221
222                 // initial communication from external contact, $direction is their direction.
223                 // If this is a duplex communication, ours will be the opposite.
224
225                 $dfrn_id = notags(trim($_GET['dfrn_id']));
226                 $dfrn_version = (float) $_GET['dfrn_version'];
227                 $rino_remote = ((x($_GET,'rino')) ? intval($_GET['rino']) : 0);
228                 $type = "";
229                 $last_update = "";
230
231                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
232
233                 $direction = (-1);
234                 if(strpos($dfrn_id,':') == 1) {
235                         $direction = intval(substr($dfrn_id,0,1));
236                         $dfrn_id = substr($dfrn_id,2);
237                 }
238
239                 $hash = random_string();
240
241                 $status = 0;
242
243                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
244
245                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
246                         VALUES( '%s', '%s', %d, '%s', '%s' ) ",
247                         dbesc($hash),
248                         dbesc($dfrn_id),
249                         intval(time() + 90 ),
250                         dbesc($type),
251                         dbesc($last_update)
252                 );
253
254                 logger('dfrn_notify: challenge=' . $hash, LOGGER_DEBUG);
255
256                 $sql_extra = '';
257                 switch($direction) {
258                         case (-1):
259                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
260                                 $my_id = $dfrn_id;
261                                 break;
262                         case 0:
263                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
264                                 $my_id = '1:' . $dfrn_id;
265                                 break;
266                         case 1:
267                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
268                                 $my_id = '0:' . $dfrn_id;
269                                 break;
270                         default:
271                                 $status = 1;
272                                 break; // NOTREACHED
273                 }
274
275                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`page-flags` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
276                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s'
277                                 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
278                                 dbesc($a->argv[1])
279                 );
280
281                 if(! count($r))
282                         $status = 1;
283
284                 logger("Remote rino version: ".$rino_remote." for ".$r[0]["url"], LOGGER_DEBUG);
285
286                 $challenge = '';
287                 $encrypted_id = '';
288                 $id_str = $my_id . '.' . mt_rand(1000,9999);
289
290                 $prv_key = trim($r[0]['prvkey']);
291                 $pub_key = trim($r[0]['pubkey']);
292                 $dplx = intval($r[0]['duplex']);
293
294                 if((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) {
295                         openssl_private_encrypt($hash,$challenge,$prv_key);
296                         openssl_private_encrypt($id_str,$encrypted_id,$prv_key);
297                 }
298                 elseif(strlen($pub_key)) {
299                         openssl_public_encrypt($hash,$challenge,$pub_key);
300                         openssl_public_encrypt($id_str,$encrypted_id,$pub_key);
301                 }
302                 else
303                         $status = 1;
304
305                 $challenge    = bin2hex($challenge);
306                 $encrypted_id = bin2hex($encrypted_id);
307
308
309                 $rino = get_config('system','rino_encrypt');
310                 $rino = intval($rino);
311                 // use RINO1 if mcrypt isn't installed and RINO2 was selected
312                 if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
313
314                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
315
316                 // if requested rino is lower than enabled local rino, lower local rino version
317                 // if requested rino is higher than enabled local rino, reply with local rino
318                 if ($rino_remote < $rino) $rino = $rino_remote;
319
320                 if((($r[0]['rel']) && ($r[0]['rel'] != CONTACT_IS_SHARING)) || ($r[0]['page-flags'] == PAGE_COMMUNITY)) {
321                         $perm = 'rw';
322                 }
323                 else {
324                         $perm = 'r';
325                 }
326
327                 header("Content-type: text/xml");
328
329                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
330                         . '<dfrn_notify>' . "\r\n"
331                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
332                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
333                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
334                         . "\t" . '<perm>' . $perm . '</perm>' . "\r\n"
335                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
336                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
337                         . '</dfrn_notify>' . "\r\n" ;
338
339                 killme();
340         }
341
342 }