You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Notifications.php 13KB

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