]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Delivery.php
Merge pull request #11780 from annando/untrusted
[friendica.git] / src / Protocol / ActivityPub / Delivery.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol\ActivityPub;
23
24 use Friendica\Core\Logger;
25 use Friendica\Database\DBA;
26 use Friendica\DI;
27 use Friendica\Model\Contact;
28 use Friendica\Model\GServer;
29 use Friendica\Model\Post;
30 use Friendica\Protocol\ActivityPub;
31 use Friendica\Util\HTTPSignature;
32 use Friendica\Worker\Delivery as WorkerDelivery;
33
34 class Delivery
35 {
36         /**
37          * Deliver posts to the given inbox
38          *
39          * @param string $inbox
40          * @return array with the elements "success" and "uri_ids" of the failed posts
41          */
42         public static function deliver(string $inbox): array
43         {
44                 $uri_ids    = [];
45                 $posts      = Post\Delivery::selectForInbox($inbox);
46                 $serverfail = false;
47
48                 foreach ($posts as $post) {
49                         if (!$serverfail) {
50                                 $result = self::deliverToInbox($post['command'], 0, $inbox, $post['uid'], $post['receivers'], $post['uri-id']);
51
52                                 if ($result['serverfailure']) {
53                                         // In a timeout situation we assume that every delivery to that inbox will time out.
54                                         // So we set the flag and try all deliveries at a later time.
55                                         Logger::info('Inbox delivery has a server failure', ['inbox' => $inbox]);
56                                         $serverfail = true;
57                                 }
58                         }
59
60                         if ($serverfail || (!$result['success'] && !$result['drop'])) {
61                                 $uri_ids[] = $post['uri-id'];
62                         }
63                 }
64
65                 Logger::debug('Inbox delivery done', ['inbox' => $inbox, 'posts' => count($posts), 'failed' => count($uri_ids), 'serverfailure' => $serverfail]);
66                 return ['success' => empty($uri_ids), 'uri_ids' => $uri_ids];
67         }
68
69         /**
70          * Deliver the given post to the given inbox
71          *
72          * @param string $cmd
73          * @param integer $item_id
74          * @param string $inbox
75          * @param integer $uid
76          * @param array $receivers
77          * @param integer $uri_id
78          * @return array
79          */
80         public static function deliverToInbox(string $cmd, int $item_id, string $inbox, int $uid, array $receivers, int $uri_id): array
81         {
82                 if (empty($item_id) && !empty($uri_id) && !empty($uid)) {
83                         $item = Post::selectFirst(['id', 'parent', 'origin'], ['uri-id' => $uri_id, 'uid' => [$uid, 0]], ['order' => ['uid' => true]]);
84                         if (empty($item['id'])) {
85                                 Logger::notice('Item not found, removing delivery', ['uri-id' => $uri_id, 'uid' => $uid, 'cmd' => $cmd, 'inbox' => $inbox]);
86                                 Post\Delivery::remove($uri_id, $inbox);
87                                 return true;
88                         } else {
89                                 $item_id = $item['id'];
90                         }
91                 }
92
93                 $success    = true;
94                 $serverfail = false;
95                 $drop       = false;
96
97                 if ($cmd == WorkerDelivery::MAIL) {
98                         $data = ActivityPub\Transmitter::createActivityFromMail($item_id);
99                         if (!empty($data)) {
100                                 $success = HTTPSignature::transmit($data, $inbox, $uid);
101                         }
102                 } elseif ($cmd == WorkerDelivery::SUGGESTION) {
103                         $success = ActivityPub\Transmitter::sendContactSuggestion($uid, $inbox, $item_id);
104                 } elseif ($cmd == WorkerDelivery::RELOCATION) {
105                         // @todo Implementation pending
106                 } elseif ($cmd == WorkerDelivery::POKE) {
107                         // Implementation not planned
108                 } elseif ($cmd == WorkerDelivery::REMOVAL) {
109                         $success = ActivityPub\Transmitter::sendProfileDeletion($uid, $inbox);
110                 } elseif ($cmd == WorkerDelivery::PROFILEUPDATE) {
111                         $success = ActivityPub\Transmitter::sendProfileUpdate($uid, $inbox);
112                 } else {
113                         $data = Post\Activity::getByURIId($uri_id);
114                         if (empty($data)) {
115                                 $data = ActivityPub\Transmitter::createCachedActivityFromItem($item_id);
116                         }
117                         if (!empty($data)) {
118                                 $timestamp  = microtime(true);
119                                 $response   = HTTPSignature::post($data, $inbox, $uid);
120                                 $runtime    = microtime(true) - $timestamp;
121                                 $success    = $response->isSuccess();
122                                 $serverfail = $response->isTimeout();
123                                 if (!$success) {
124                                         // 5xx errors are problems on the server. We don't need to continue delivery then.
125                                         if (!$serverfail && ($response->getReturnCode() >= 500) && ($response->getReturnCode() <= 599)) {
126                                                 $serverfail = true;
127                                         }
128
129                                         // A 404 means that the inbox doesn't exist. We can stop the delivery here.
130                                         if (!$serverfail && ($response->getReturnCode() == 404)) {
131                                                 $serverfail = true;
132                                         }
133
134                                         $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
135                                         if (!$serverfail && $xrd_timeout && ($runtime > $xrd_timeout)) {
136                                                 $serverfail = true;
137                                         }
138
139                                         $curl_timeout = DI::config()->get('system', 'curl_timeout');
140                                         if (!$serverfail && $curl_timeout && ($runtime > $curl_timeout)) {
141                                                 $serverfail = true;
142                                         }
143
144                                         // Resubscribe to relay server upon client error
145                                         if (!$serverfail && ($response->getReturnCode() >= 400) && ($response->getReturnCode() <= 499)) {
146                                                 $actor = self:: fetchActorForRelayInbox($inbox);
147                                                 if (!empty($actor)) {
148                                                         $drop = !ActivityPub\Transmitter::sendRelayFollow($actor);
149                                                         Logger::notice('Resubscribed to relay', ['url' => $actor, 'success' => !$drop]);
150                                                 } elseif ($cmd = WorkerDelivery::DELETION) {
151                                                         // Remote systems not always accept our deletion requests, so we drop them if rejected.
152                                                         // Situation is: In Friendica we allow the thread owner to delete foreign comments to their thread.
153                                                         // Most AP systems don't allow this, so they will reject the deletion request.
154                                                         $drop = true;
155                                                 }
156
157                                         }
158
159                                         Logger::info('Delivery failed', ['retcode' => $response->getReturnCode(), 'serverfailure' => $serverfail, 'drop' => $drop, 'runtime' => round($runtime, 3), 'uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox]);
160                                 }
161                                 if ($uri_id) {
162                                         if ($success) {
163                                                 Post\Delivery::remove($uri_id, $inbox);
164                                         } else {
165                                                 Post\Delivery::incrementFailed($uri_id, $inbox);
166                                         }
167                                 }
168                         }
169                 }
170
171                 self::setSuccess($receivers, $success);
172
173                 Logger::debug('Delivered', ['uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox, 'success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop]);
174
175                 if (($success || $drop) && in_array($cmd, [WorkerDelivery::POST])) {
176                         Post\DeliveryData::incrementQueueDone($uri_id, Post\DeliveryData::ACTIVITYPUB);
177                 }
178
179                 return ['success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop];
180         }
181
182         /**
183          * Fetch the actor of the given inbox of an relay server
184          *
185          * @param string $inbox
186          * @return string
187          */
188         private static function fetchActorForRelayInbox(string $inbox): string
189         {
190                 $apcontact = DBA::selectFirst('apcontact', ['url'], ["`sharedinbox` = ? AND `type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` = ?)",
191                         $inbox, 'Application', 0, Contact::FRIEND]);
192                 return $apcontact['url'] ?? '';
193         }
194
195         /**
196          * mark or unmark the given receivers for archival upon succoess
197          *
198          * @param array $receivers
199          * @param boolean $success
200          * @return void
201          */
202         private static function setSuccess(array $receivers, bool $success)
203         {
204                 $gsid = null;
205
206                 foreach ($receivers as $receiver) {
207                         $contact = Contact::getById($receiver);
208                         if (empty($contact)) {
209                                 continue;
210                         }
211
212                         $gsid = $gsid ?: $contact['gsid'];
213
214                         if ($success) {
215                                 Contact::unmarkForArchival($contact);
216                         } else {
217                                 Contact::markForArchival($contact);
218                         }
219                 }
220
221                 if (!empty($gsid)) {
222                         GServer::setProtocol($gsid, Post\DeliveryData::ACTIVITYPUB);
223                 }
224         }
225 }