Notifications.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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\ILogger;
  37. use OCP\OCS\IDiscoveryService;
  38. class Notifications {
  39. public const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
  40. /** @var AddressHandler */
  41. private $addressHandler;
  42. /** @var IClientService */
  43. private $httpClientService;
  44. /** @var IDiscoveryService */
  45. private $discoveryService;
  46. /** @var IJobList */
  47. private $jobList;
  48. /** @var ICloudFederationProviderManager */
  49. private $federationProviderManager;
  50. /** @var ICloudFederationFactory */
  51. private $cloudFederationFactory;
  52. /** @var IEventDispatcher */
  53. private $eventDispatcher;
  54. /** @var ILogger */
  55. private $logger;
  56. public function __construct(
  57. AddressHandler $addressHandler,
  58. IClientService $httpClientService,
  59. IDiscoveryService $discoveryService,
  60. ILogger $logger,
  61. IJobList $jobList,
  62. ICloudFederationProviderManager $federationProviderManager,
  63. ICloudFederationFactory $cloudFederationFactory,
  64. IEventDispatcher $eventDispatcher
  65. ) {
  66. $this->addressHandler = $addressHandler;
  67. $this->httpClientService = $httpClientService;
  68. $this->discoveryService = $discoveryService;
  69. $this->jobList = $jobList;
  70. $this->logger = $logger;
  71. $this->federationProviderManager = $federationProviderManager;
  72. $this->cloudFederationFactory = $cloudFederationFactory;
  73. $this->eventDispatcher = $eventDispatcher;
  74. }
  75. /**
  76. * send server-to-server share to remote server
  77. *
  78. * @param string $token
  79. * @param string $shareWith
  80. * @param string $name
  81. * @param string $remoteId
  82. * @param string $owner
  83. * @param string $ownerFederatedId
  84. * @param string $sharedBy
  85. * @param string $sharedByFederatedId
  86. * @param int $shareType (can be a remote user or group share)
  87. * @return bool
  88. * @throws \OCP\HintException
  89. * @throws \OC\ServerNotAvailableException
  90. */
  91. public function sendRemoteShare($token, $shareWith, $name, $remoteId, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) {
  92. [$user, $remote] = $this->addressHandler->splitUserRemote($shareWith);
  93. if ($user && $remote) {
  94. $local = $this->addressHandler->generateRemoteURL();
  95. $fields = [
  96. 'shareWith' => $user,
  97. 'token' => $token,
  98. 'name' => $name,
  99. 'remoteId' => $remoteId,
  100. 'owner' => $owner,
  101. 'ownerFederatedId' => $ownerFederatedId,
  102. 'sharedBy' => $sharedBy,
  103. 'sharedByFederatedId' => $sharedByFederatedId,
  104. 'remote' => $local,
  105. 'shareType' => $shareType
  106. ];
  107. $result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
  108. $status = json_decode($result['result'], true);
  109. $ocsStatus = isset($status['ocs']);
  110. $ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
  111. if ($result['success'] && (!$ocsStatus || $ocsSuccess)) {
  112. $event = new FederatedShareAddedEvent($remote);
  113. $this->eventDispatcher->dispatchTyped($event);
  114. return true;
  115. } else {
  116. $this->logger->info(
  117. "failed sharing $name with $shareWith",
  118. ['app' => 'federatedfilesharing']
  119. );
  120. }
  121. } else {
  122. $this->logger->info(
  123. "could not share $name, invalid contact $shareWith",
  124. ['app' => 'federatedfilesharing']
  125. );
  126. }
  127. return false;
  128. }
  129. /**
  130. * ask owner to re-share the file with the given user
  131. *
  132. * @param string $token
  133. * @param string $id remote Id
  134. * @param string $shareId internal share Id
  135. * @param string $remote remote address of the owner
  136. * @param string $shareWith
  137. * @param int $permission
  138. * @param string $filename
  139. * @return array|false
  140. * @throws \OCP\HintException
  141. * @throws \OC\ServerNotAvailableException
  142. */
  143. public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
  144. $fields = [
  145. 'shareWith' => $shareWith,
  146. 'token' => $token,
  147. 'permission' => $permission,
  148. 'remoteId' => $shareId,
  149. ];
  150. $ocmFields = $fields;
  151. $ocmFields['remoteId'] = (string)$id;
  152. $ocmFields['localId'] = $shareId;
  153. $ocmFields['name'] = $filename;
  154. $ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
  155. if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
  156. return [$ocmResult['token'], $ocmResult['providerId']];
  157. }
  158. $result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
  159. $status = json_decode($result['result'], true);
  160. $httpRequestSuccessful = $result['success'];
  161. $ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
  162. $validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
  163. $validRemoteId = isset($status['ocs']['data']['remoteId']);
  164. if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
  165. return [
  166. $status['ocs']['data']['token'],
  167. $status['ocs']['data']['remoteId']
  168. ];
  169. } elseif (!$validToken) {
  170. $this->logger->info(
  171. "invalid or missing token requesting re-share for $filename to $remote",
  172. ['app' => 'federatedfilesharing']
  173. );
  174. } elseif (!$validRemoteId) {
  175. $this->logger->info(
  176. "missing remote id requesting re-share for $filename to $remote",
  177. ['app' => 'federatedfilesharing']
  178. );
  179. } else {
  180. $this->logger->info(
  181. "failed requesting re-share for $filename to $remote",
  182. ['app' => 'federatedfilesharing']
  183. );
  184. }
  185. return false;
  186. }
  187. /**
  188. * send server-to-server unshare to remote server
  189. *
  190. * @param string $remote url
  191. * @param string $id share id
  192. * @param string $token
  193. * @return bool
  194. */
  195. public function sendRemoteUnShare($remote, $id, $token) {
  196. $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
  197. }
  198. /**
  199. * send server-to-server unshare to remote server
  200. *
  201. * @param string $remote url
  202. * @param string $id share id
  203. * @param string $token
  204. * @return bool
  205. */
  206. public function sendRevokeShare($remote, $id, $token) {
  207. $this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
  208. }
  209. /**
  210. * send notification to remote server if the permissions was changed
  211. *
  212. * @param string $remote
  213. * @param string $remoteId
  214. * @param string $token
  215. * @param int $permissions
  216. * @return bool
  217. */
  218. public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
  219. $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
  220. }
  221. /**
  222. * forward accept reShare to remote server
  223. *
  224. * @param string $remote
  225. * @param string $remoteId
  226. * @param string $token
  227. */
  228. public function sendAcceptShare($remote, $remoteId, $token) {
  229. $this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
  230. }
  231. /**
  232. * forward decline reShare to remote server
  233. *
  234. * @param string $remote
  235. * @param string $remoteId
  236. * @param string $token
  237. */
  238. public function sendDeclineShare($remote, $remoteId, $token) {
  239. $this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
  240. }
  241. /**
  242. * inform remote server whether server-to-server share was accepted/declined
  243. *
  244. * @param string $remote
  245. * @param string $token
  246. * @param string $remoteId Share id on the remote host
  247. * @param string $action possible actions: accept, decline, unshare, revoke, permissions
  248. * @param array $data
  249. * @param int $try
  250. * @return boolean
  251. */
  252. public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
  253. $fields = [
  254. 'token' => $token,
  255. 'remoteId' => $remoteId
  256. ];
  257. foreach ($data as $key => $value) {
  258. $fields[$key] = $value;
  259. }
  260. $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
  261. $status = json_decode($result['result'], true);
  262. if ($result['success'] &&
  263. ($status['ocs']['meta']['statuscode'] === 100 ||
  264. $status['ocs']['meta']['statuscode'] === 200
  265. )
  266. ) {
  267. return true;
  268. } elseif ($try === 0) {
  269. // only add new job on first try
  270. $this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
  271. [
  272. 'remote' => $remote,
  273. 'remoteId' => $remoteId,
  274. 'token' => $token,
  275. 'action' => $action,
  276. 'data' => json_encode($data),
  277. 'try' => $try,
  278. 'lastRun' => $this->getTimestamp()
  279. ]
  280. );
  281. }
  282. return false;
  283. }
  284. /**
  285. * return current timestamp
  286. *
  287. * @return int
  288. */
  289. protected function getTimestamp() {
  290. return time();
  291. }
  292. /**
  293. * try http post with the given protocol, if no protocol is given we pick
  294. * the secure one (https)
  295. *
  296. * @param string $remoteDomain
  297. * @param string $urlSuffix
  298. * @param array $fields post parameters
  299. * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
  300. * @return array
  301. * @throws \Exception
  302. */
  303. protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action = "share") {
  304. if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
  305. $remoteDomain = 'https://' . $remoteDomain;
  306. }
  307. $result = [
  308. 'success' => false,
  309. 'result' => '',
  310. ];
  311. // if possible we use the new OCM API
  312. $ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
  313. if (is_array($ocmResult)) {
  314. $result['success'] = true;
  315. $result['result'] = json_encode([
  316. 'ocs' => ['meta' => ['statuscode' => 200]]]);
  317. return $result;
  318. }
  319. return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
  320. }
  321. /**
  322. * try old federated sharing API if the OCM api doesn't work
  323. *
  324. * @param $remoteDomain
  325. * @param $urlSuffix
  326. * @param array $fields
  327. * @return mixed
  328. * @throws \Exception
  329. */
  330. protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
  331. $result = [
  332. 'success' => false,
  333. 'result' => '',
  334. ];
  335. // Fall back to old API
  336. $client = $this->httpClientService->newClient();
  337. $federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
  338. $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
  339. try {
  340. $response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
  341. 'body' => $fields,
  342. 'timeout' => 10,
  343. 'connect_timeout' => 10,
  344. ]);
  345. $result['result'] = $response->getBody();
  346. $result['success'] = true;
  347. } catch (\Exception $e) {
  348. // if flat re-sharing is not supported by the remote server
  349. // we re-throw the exception and fall back to the old behaviour.
  350. // (flat re-shares has been introduced in Nextcloud 9.1)
  351. if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
  352. throw $e;
  353. }
  354. }
  355. return $result;
  356. }
  357. /**
  358. * send action regarding federated sharing to the remote server using the OCM API
  359. *
  360. * @param $remoteDomain
  361. * @param $fields
  362. * @param $action
  363. *
  364. * @return array|false
  365. */
  366. protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
  367. switch ($action) {
  368. case 'share':
  369. $share = $this->cloudFederationFactory->getCloudFederationShare(
  370. $fields['shareWith'] . '@' . $remoteDomain,
  371. $fields['name'],
  372. '',
  373. $fields['remoteId'],
  374. $fields['ownerFederatedId'],
  375. $fields['owner'],
  376. $fields['sharedByFederatedId'],
  377. $fields['sharedBy'],
  378. $fields['token'],
  379. $fields['shareType'],
  380. 'file'
  381. );
  382. return $this->federationProviderManager->sendShare($share);
  383. case 'reshare':
  384. // ask owner to reshare a file
  385. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  386. $notification->setMessage('REQUEST_RESHARE',
  387. 'file',
  388. $fields['remoteId'],
  389. [
  390. 'sharedSecret' => $fields['token'],
  391. 'shareWith' => $fields['shareWith'],
  392. 'senderId' => $fields['localId'],
  393. 'shareType' => $fields['shareType'],
  394. 'message' => 'Ask owner to reshare the file'
  395. ]
  396. );
  397. return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
  398. case 'unshare':
  399. //owner unshares the file from the recipient again
  400. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  401. $notification->setMessage('SHARE_UNSHARED',
  402. 'file',
  403. $fields['remoteId'],
  404. [
  405. 'sharedSecret' => $fields['token'],
  406. 'messgage' => 'file is no longer shared with you'
  407. ]
  408. );
  409. return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
  410. case 'reshare_undo':
  411. // if a reshare was unshared we send the information to the initiator/owner
  412. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  413. $notification->setMessage('RESHARE_UNDO',
  414. 'file',
  415. $fields['remoteId'],
  416. [
  417. 'sharedSecret' => $fields['token'],
  418. 'message' => 'reshare was revoked'
  419. ]
  420. );
  421. return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
  422. }
  423. return false;
  424. }
  425. }