1
0

Notifications.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. isset($status['ocs']['meta']['statuscode']) &&
  240. ($status['ocs']['meta']['statuscode'] === 100 ||
  241. $status['ocs']['meta']['statuscode'] === 200
  242. )
  243. ) {
  244. return true;
  245. } elseif ($try === 0) {
  246. // only add new job on first try
  247. $this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
  248. [
  249. 'remote' => $remote,
  250. 'remoteId' => $remoteId,
  251. 'token' => $token,
  252. 'action' => $action,
  253. 'data' => json_encode($data),
  254. 'try' => $try,
  255. 'lastRun' => $this->getTimestamp()
  256. ]
  257. );
  258. }
  259. return false;
  260. }
  261. /**
  262. * return current timestamp
  263. *
  264. * @return int
  265. */
  266. protected function getTimestamp() {
  267. return time();
  268. }
  269. /**
  270. * try http post with the given protocol, if no protocol is given we pick
  271. * the secure one (https)
  272. *
  273. * @param string $remoteDomain
  274. * @param string $urlSuffix
  275. * @param array $fields post parameters
  276. * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
  277. * @return array
  278. * @throws \Exception
  279. */
  280. protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action = "share") {
  281. if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
  282. $remoteDomain = 'https://' . $remoteDomain;
  283. }
  284. $result = [
  285. 'success' => false,
  286. 'result' => '',
  287. ];
  288. // if possible we use the new OCM API
  289. $ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
  290. if (is_array($ocmResult)) {
  291. $result['success'] = true;
  292. $result['result'] = json_encode([
  293. 'ocs' => ['meta' => ['statuscode' => 200]]]);
  294. return $result;
  295. }
  296. return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
  297. }
  298. /**
  299. * try old federated sharing API if the OCM api doesn't work
  300. *
  301. * @param $remoteDomain
  302. * @param $urlSuffix
  303. * @param array $fields
  304. * @return mixed
  305. * @throws \Exception
  306. */
  307. protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
  308. $result = [
  309. 'success' => false,
  310. 'result' => '',
  311. ];
  312. // Fall back to old API
  313. $client = $this->httpClientService->newClient();
  314. $federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
  315. $endpoint = $federationEndpoints['share'] ?? '/ocs/v2.php/cloud/shares';
  316. try {
  317. $response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
  318. 'body' => $fields,
  319. 'timeout' => 10,
  320. 'connect_timeout' => 10,
  321. ]);
  322. $result['result'] = $response->getBody();
  323. $result['success'] = true;
  324. } catch (\Exception $e) {
  325. // if flat re-sharing is not supported by the remote server
  326. // we re-throw the exception and fall back to the old behaviour.
  327. // (flat re-shares has been introduced in Nextcloud 9.1)
  328. if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
  329. throw $e;
  330. }
  331. }
  332. return $result;
  333. }
  334. /**
  335. * send action regarding federated sharing to the remote server using the OCM API
  336. *
  337. * @param $remoteDomain
  338. * @param $fields
  339. * @param $action
  340. *
  341. * @return array|false
  342. */
  343. protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
  344. switch ($action) {
  345. case 'share':
  346. $share = $this->cloudFederationFactory->getCloudFederationShare(
  347. $fields['shareWith'] . '@' . $remoteDomain,
  348. $fields['name'],
  349. '',
  350. $fields['remoteId'],
  351. $fields['ownerFederatedId'],
  352. $fields['owner'],
  353. $fields['sharedByFederatedId'],
  354. $fields['sharedBy'],
  355. $fields['token'],
  356. $fields['shareType'],
  357. 'file'
  358. );
  359. return $this->federationProviderManager->sendShare($share);
  360. case 'reshare':
  361. // ask owner to reshare a file
  362. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  363. $notification->setMessage('REQUEST_RESHARE',
  364. 'file',
  365. $fields['remoteId'],
  366. [
  367. 'sharedSecret' => $fields['token'],
  368. 'shareWith' => $fields['shareWith'],
  369. 'senderId' => $fields['localId'],
  370. 'shareType' => $fields['shareType'],
  371. 'message' => 'Ask owner to reshare the file'
  372. ]
  373. );
  374. return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
  375. case 'unshare':
  376. //owner unshares the file from the recipient again
  377. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  378. $notification->setMessage('SHARE_UNSHARED',
  379. 'file',
  380. $fields['remoteId'],
  381. [
  382. 'sharedSecret' => $fields['token'],
  383. 'messgage' => 'file is no longer shared with you'
  384. ]
  385. );
  386. return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
  387. case 'reshare_undo':
  388. // if a reshare was unshared we send the information to the initiator/owner
  389. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  390. $notification->setMessage('RESHARE_UNDO',
  391. 'file',
  392. $fields['remoteId'],
  393. [
  394. 'sharedSecret' => $fields['token'],
  395. 'message' => 'reshare was revoked'
  396. ]
  397. );
  398. return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
  399. }
  400. return false;
  401. }
  402. }