Notifications.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bjoern Schiessle <bjoern@schiessle.org>
  6. * @author Björn Schießle <bjoern@schiessle.org>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Julius Härtl <jus@bitgrid.net>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Samuel <faust64@gmail.com>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OCA\FederatedFileSharing;
  29. use OCA\FederatedFileSharing\Events\FederatedShareAddedEvent;
  30. use OCP\AppFramework\Http;
  31. use OCP\BackgroundJob\IJobList;
  32. use OCP\EventDispatcher\IEventDispatcher;
  33. use OCP\Federation\ICloudFederationFactory;
  34. use OCP\Federation\ICloudFederationProviderManager;
  35. use OCP\Http\Client\IClientService;
  36. use OCP\OCS\IDiscoveryService;
  37. use Psr\Log\LoggerInterface;
  38. class Notifications {
  39. public const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
  40. public function __construct(
  41. private AddressHandler $addressHandler,
  42. private IClientService $httpClientService,
  43. private IDiscoveryService $discoveryService,
  44. private IJobList $jobList,
  45. private ICloudFederationProviderManager $federationProviderManager,
  46. private ICloudFederationFactory $cloudFederationFactory,
  47. private IEventDispatcher $eventDispatcher,
  48. private LoggerInterface $logger,
  49. ) {
  50. }
  51. /**
  52. * send server-to-server share to remote server
  53. *
  54. * @param string $token
  55. * @param string $shareWith
  56. * @param string $name
  57. * @param string $remoteId
  58. * @param string $owner
  59. * @param string $ownerFederatedId
  60. * @param string $sharedBy
  61. * @param string $sharedByFederatedId
  62. * @param int $shareType (can be a remote user or group share)
  63. * @return bool
  64. * @throws \OCP\HintException
  65. * @throws \OC\ServerNotAvailableException
  66. */
  67. public function sendRemoteShare($token, $shareWith, $name, $remoteId, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) {
  68. [$user, $remote] = $this->addressHandler->splitUserRemote($shareWith);
  69. if ($user && $remote) {
  70. $local = $this->addressHandler->generateRemoteURL();
  71. $fields = [
  72. 'shareWith' => $user,
  73. 'token' => $token,
  74. 'name' => $name,
  75. 'remoteId' => $remoteId,
  76. 'owner' => $owner,
  77. 'ownerFederatedId' => $ownerFederatedId,
  78. 'sharedBy' => $sharedBy,
  79. 'sharedByFederatedId' => $sharedByFederatedId,
  80. 'remote' => $local,
  81. 'shareType' => $shareType
  82. ];
  83. $result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
  84. $status = json_decode($result['result'], true);
  85. $ocsStatus = isset($status['ocs']);
  86. $ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
  87. if ($result['success'] && (!$ocsStatus || $ocsSuccess)) {
  88. $event = new FederatedShareAddedEvent($remote);
  89. $this->eventDispatcher->dispatchTyped($event);
  90. return true;
  91. } else {
  92. $this->logger->info(
  93. "failed sharing $name with $shareWith",
  94. ['app' => 'federatedfilesharing']
  95. );
  96. }
  97. } else {
  98. $this->logger->info(
  99. "could not share $name, invalid contact $shareWith",
  100. ['app' => 'federatedfilesharing']
  101. );
  102. }
  103. return false;
  104. }
  105. /**
  106. * ask owner to re-share the file with the given user
  107. *
  108. * @param string $token
  109. * @param string $id remote Id
  110. * @param string $shareId internal share Id
  111. * @param string $remote remote address of the owner
  112. * @param string $shareWith
  113. * @param int $permission
  114. * @param string $filename
  115. * @return array|false
  116. * @throws \OCP\HintException
  117. * @throws \OC\ServerNotAvailableException
  118. */
  119. public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
  120. $fields = [
  121. 'shareWith' => $shareWith,
  122. 'token' => $token,
  123. 'permission' => $permission,
  124. 'remoteId' => $shareId,
  125. ];
  126. $ocmFields = $fields;
  127. $ocmFields['remoteId'] = (string)$id;
  128. $ocmFields['localId'] = $shareId;
  129. $ocmFields['name'] = $filename;
  130. $ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
  131. if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
  132. return [$ocmResult['token'], $ocmResult['providerId']];
  133. }
  134. $result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
  135. $status = json_decode($result['result'], true);
  136. $httpRequestSuccessful = $result['success'];
  137. $ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
  138. $validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
  139. $validRemoteId = isset($status['ocs']['data']['remoteId']);
  140. if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
  141. return [
  142. $status['ocs']['data']['token'],
  143. $status['ocs']['data']['remoteId']
  144. ];
  145. } elseif (!$validToken) {
  146. $this->logger->info(
  147. "invalid or missing token requesting re-share for $filename to $remote",
  148. ['app' => 'federatedfilesharing']
  149. );
  150. } elseif (!$validRemoteId) {
  151. $this->logger->info(
  152. "missing remote id requesting re-share for $filename to $remote",
  153. ['app' => 'federatedfilesharing']
  154. );
  155. } else {
  156. $this->logger->info(
  157. "failed requesting re-share for $filename to $remote",
  158. ['app' => 'federatedfilesharing']
  159. );
  160. }
  161. return false;
  162. }
  163. /**
  164. * send server-to-server unshare to remote server
  165. *
  166. * @param string $remote url
  167. * @param string $id share id
  168. * @param string $token
  169. * @return bool
  170. */
  171. public function sendRemoteUnShare($remote, $id, $token) {
  172. $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
  173. }
  174. /**
  175. * send server-to-server unshare to remote server
  176. *
  177. * @param string $remote url
  178. * @param string $id share id
  179. * @param string $token
  180. * @return bool
  181. */
  182. public function sendRevokeShare($remote, $id, $token) {
  183. $this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
  184. }
  185. /**
  186. * send notification to remote server if the permissions was changed
  187. *
  188. * @param string $remote
  189. * @param string $remoteId
  190. * @param string $token
  191. * @param int $permissions
  192. * @return bool
  193. */
  194. public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
  195. $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
  196. }
  197. /**
  198. * forward accept reShare to remote server
  199. *
  200. * @param string $remote
  201. * @param string $remoteId
  202. * @param string $token
  203. */
  204. public function sendAcceptShare($remote, $remoteId, $token) {
  205. $this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
  206. }
  207. /**
  208. * forward decline reShare to remote server
  209. *
  210. * @param string $remote
  211. * @param string $remoteId
  212. * @param string $token
  213. */
  214. public function sendDeclineShare($remote, $remoteId, $token) {
  215. $this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
  216. }
  217. /**
  218. * inform remote server whether server-to-server share was accepted/declined
  219. *
  220. * @param string $remote
  221. * @param string $token
  222. * @param string $remoteId Share id on the remote host
  223. * @param string $action possible actions: accept, decline, unshare, revoke, permissions
  224. * @param array $data
  225. * @param int $try
  226. * @return boolean
  227. */
  228. public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
  229. $fields = [
  230. 'token' => $token,
  231. 'remoteId' => $remoteId
  232. ];
  233. foreach ($data as $key => $value) {
  234. $fields[$key] = $value;
  235. }
  236. $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
  237. $status = json_decode($result['result'], true);
  238. if ($result['success'] &&
  239. ($status['ocs']['meta']['statuscode'] === 100 ||
  240. $status['ocs']['meta']['statuscode'] === 200
  241. )
  242. ) {
  243. return true;
  244. } elseif ($try === 0) {
  245. // only add new job on first try
  246. $this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
  247. [
  248. 'remote' => $remote,
  249. 'remoteId' => $remoteId,
  250. 'token' => $token,
  251. 'action' => $action,
  252. 'data' => json_encode($data),
  253. 'try' => $try,
  254. 'lastRun' => $this->getTimestamp()
  255. ]
  256. );
  257. }
  258. return false;
  259. }
  260. /**
  261. * return current timestamp
  262. *
  263. * @return int
  264. */
  265. protected function getTimestamp() {
  266. return time();
  267. }
  268. /**
  269. * try http post with the given protocol, if no protocol is given we pick
  270. * the secure one (https)
  271. *
  272. * @param string $remoteDomain
  273. * @param string $urlSuffix
  274. * @param array $fields post parameters
  275. * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
  276. * @return array
  277. * @throws \Exception
  278. */
  279. protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action = "share") {
  280. if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
  281. $remoteDomain = 'https://' . $remoteDomain;
  282. }
  283. $result = [
  284. 'success' => false,
  285. 'result' => '',
  286. ];
  287. // if possible we use the new OCM API
  288. $ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
  289. if (is_array($ocmResult)) {
  290. $result['success'] = true;
  291. $result['result'] = json_encode([
  292. 'ocs' => ['meta' => ['statuscode' => 200]]]);
  293. return $result;
  294. }
  295. return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
  296. }
  297. /**
  298. * try old federated sharing API if the OCM api doesn't work
  299. *
  300. * @param $remoteDomain
  301. * @param $urlSuffix
  302. * @param array $fields
  303. * @return mixed
  304. * @throws \Exception
  305. */
  306. protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
  307. $result = [
  308. 'success' => false,
  309. 'result' => '',
  310. ];
  311. // Fall back to old API
  312. $client = $this->httpClientService->newClient();
  313. $federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
  314. $endpoint = $federationEndpoints['share'] ?? '/ocs/v2.php/cloud/shares';
  315. try {
  316. $response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
  317. 'body' => $fields,
  318. 'timeout' => 10,
  319. 'connect_timeout' => 10,
  320. ]);
  321. $result['result'] = $response->getBody();
  322. $result['success'] = true;
  323. } catch (\Exception $e) {
  324. // if flat re-sharing is not supported by the remote server
  325. // we re-throw the exception and fall back to the old behaviour.
  326. // (flat re-shares has been introduced in Nextcloud 9.1)
  327. if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
  328. throw $e;
  329. }
  330. }
  331. return $result;
  332. }
  333. /**
  334. * send action regarding federated sharing to the remote server using the OCM API
  335. *
  336. * @param $remoteDomain
  337. * @param $fields
  338. * @param $action
  339. *
  340. * @return array|false
  341. */
  342. protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
  343. switch ($action) {
  344. case 'share':
  345. $share = $this->cloudFederationFactory->getCloudFederationShare(
  346. $fields['shareWith'] . '@' . $remoteDomain,
  347. $fields['name'],
  348. '',
  349. $fields['remoteId'],
  350. $fields['ownerFederatedId'],
  351. $fields['owner'],
  352. $fields['sharedByFederatedId'],
  353. $fields['sharedBy'],
  354. $fields['token'],
  355. $fields['shareType'],
  356. 'file'
  357. );
  358. return $this->federationProviderManager->sendShare($share);
  359. case 'reshare':
  360. // ask owner to reshare a file
  361. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  362. $notification->setMessage('REQUEST_RESHARE',
  363. 'file',
  364. $fields['remoteId'],
  365. [
  366. 'sharedSecret' => $fields['token'],
  367. 'shareWith' => $fields['shareWith'],
  368. 'senderId' => $fields['localId'],
  369. 'shareType' => $fields['shareType'],
  370. 'message' => 'Ask owner to reshare the file'
  371. ]
  372. );
  373. return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
  374. case 'unshare':
  375. //owner unshares the file from the recipient again
  376. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  377. $notification->setMessage('SHARE_UNSHARED',
  378. 'file',
  379. $fields['remoteId'],
  380. [
  381. 'sharedSecret' => $fields['token'],
  382. 'messgage' => 'file is no longer shared with you'
  383. ]
  384. );
  385. return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
  386. case 'reshare_undo':
  387. // if a reshare was unshared we send the information to the initiator/owner
  388. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  389. $notification->setMessage('RESHARE_UNDO',
  390. 'file',
  391. $fields['remoteId'],
  392. [
  393. 'sharedSecret' => $fields['token'],
  394. 'message' => 'reshare was revoked'
  395. ]
  396. );
  397. return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
  398. }
  399. return false;
  400. }
  401. }