1
0

Notifications.php 14 KB

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