Completed
Pull Request — master (#32303)
by Victor
10:42
created

Notifications::sendOcmRemoteShare()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 6
dl 0
loc 27
rs 9.488
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Björn Schießle <[email protected]>
4
 * @author Joas Schilling <[email protected]>
5
 * @author Lukas Reschke <[email protected]>
6
 * @author Thomas Müller <[email protected]>
7
 * @author Vincent Petry <[email protected]>
8
 *
9
 * @copyright Copyright (c) 2018, ownCloud GmbH
10
 * @license AGPL-3.0
11
 *
12
 * This code is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License, version 3,
14
 * as published by the Free Software Foundation.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19
 * GNU Affero General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Affero General Public License, version 3,
22
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
23
 *
24
 */
25
26
namespace OCA\FederatedFileSharing;
27
28
use OCA\FederatedFileSharing\Ocm\NotificationManager;
29
use OCP\AppFramework\Http;
30
use OCP\BackgroundJob\IJobList;
31
use OCP\Http\Client\IClientService;
32
use OCP\IConfig;
33
34
class Notifications {
35
	const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
36
37
	/** @var AddressHandler */
38
	private $addressHandler;
39
40
	/** @var IClientService */
41
	private $httpClientService;
42
43
	/** @var DiscoveryManager */
44
	private $discoveryManager;
45 1
46
	/** @var IJobList  */
47
	private $jobList;
48
49 1
	/** @var IConfig */
50 1
	private $config;
51 1
52
	/**
53
	 * @param AddressHandler $addressHandler
54
	 * @param IClientService $httpClientService
55
	 * @param DiscoveryManager $discoveryManager
56
	 * @param IJobList $jobList
57
	 * @param IConfig $config
58
	 */
59
	public function __construct(
60
		AddressHandler $addressHandler,
61
		IClientService $httpClientService,
62
		DiscoveryManager $discoveryManager,
63
		IJobList $jobList,
64
		IConfig $config
65
	) {
66
		$this->addressHandler = $addressHandler;
67
		$this->httpClientService = $httpClientService;
68
		$this->discoveryManager = $discoveryManager;
69
		$this->jobList = $jobList;
70
		$this->config = $config;
71
	}
72
73
	/**
74
	 * send server-to-server share to remote server
75
	 *
76
	 * @param Address $shareWithAddress
77
	 * @param Address $ownerAddress
78
	 * @param Address $sharedByAddress
79
	 * @param string $token
80
	 * @param string $shareWith
0 ignored issues
show
Documentation introduced by
There is no parameter named $shareWith. Did you maybe mean $shareWithAddress?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
81
	 * @param string $name
82
	 * @param int $remote_id
83
	 *
84
	 * @return bool
85
	 *
86
	 * @throws \OC\HintException
87
	 * @throws \OC\ServerNotAvailableException
88
	 */
89
	public function sendRemoteShare(Address $shareWithAddress,
90
		Address $ownerAddress,
91
		Address $sharedByAddress,
92
		$token,
93
		$name,
94
		$remote_id
95
	) {
96
		$remoteShareSuccess = false;
97
		if ($shareWithAddress->getUserId() && $shareWithAddress->getCloudId()) {
98
			$remoteShareSuccess = $this->sendOcmRemoteShare(
99
				$shareWithAddress, $ownerAddress, $sharedByAddress, $token, $name, $remote_id
100
			);
101
			if (!$remoteShareSuccess) {
102
				$remoteShareSuccess = $this->sendPreOcmRemoteShare(
103
					$shareWithAddress, $ownerAddress, $sharedByAddress, $token, $name, $remote_id
104
				);
105
			}
106
		}
107
		if ($remoteShareSuccess) {
108
			\OC_Hook::emit(
109
				'OCP\Share',
110
				'federated_share_added',
111
				['server' => $shareWithAddress->getHostName()]
112
			);
113
		}
114
		return $remoteShareSuccess;
115
	}
116
117
	/**
118
	 * ask owner to re-share the file with the given user
119
	 *
120
	 * @param string $token
121
	 * @param int $id remote Id
122
	 * @param int $shareId internal share Id
123
	 * @param string $remote remote address of the owner
124
	 * @param string $shareWith
125
	 * @param int $permission
126
	 * @return bool
127
	 * @throws \Exception
128
	 */
129
	public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission) {
130
		$ocmNotificationManager = new NotificationManager();
131
		$data = [
132
			'shareWith' => $shareWith,
133
			'senderId' => $id
134
		];
135
		$ocmNotification = $ocmNotificationManager->convertToOcmFileNotification($shareId, $token, 'reshare', $data);
136
		$ocmFields = $ocmNotification->toArray();
137
138
		$url = \rtrim(
139
			$this->addressHandler->removeProtocolFromUrl($remote),
140
			'/'
141
		);
142
		$result = $this->tryHttpPostToShareEndpoint($url, '/notifications', $ocmFields, true);
143
		if (isset($result['statusCode']) && $result['statusCode'] === Http::STATUS_CREATED) {
144
			$response = \json_decode($result['result'], true);
145
			if (is_array($response) && isset($response['token']) && isset($response['providerId'])) {
146
				return [
147
					$response['token'],
148
					(int) $response['providerId']
149
				];
150
			}
151
			return true;
152
		}
153
154
		$fields = [
155
			'shareWith' => $shareWith,
156
			'token' => $token,
157
			'permission' => $permission,
158
			'remoteId' => $shareId
159
		];
160
161
		$url = $this->addressHandler->removeProtocolFromUrl($remote);
162
		$result = $this->tryHttpPostToShareEndpoint(\rtrim($url, '/'), '/' . $id . '/reshare', $fields);
163
		$status = \json_decode($result['result'], true);
164
165
		$httpRequestSuccessful = $result['success'];
166
		$validToken = isset($status['ocs']['data']['token']) && \is_string($status['ocs']['data']['token']);
167
		$validRemoteId = isset($status['ocs']['data']['remoteId']);
168
169
		if ($httpRequestSuccessful && $this->isOcsStatusOk($status) && $validToken && $validRemoteId) {
170
			return [
171
				$status['ocs']['data']['token'],
172
				(int)$status['ocs']['data']['remoteId']
173
			];
174
		}
175
176
		return false;
177
	}
178
179
	/**
180
	 * send server-to-server unshare to remote server
181
	 *
182
	 * @param string $remote url
183
	 * @param int $id share id
184
	 * @param string $token
185
	 * @return bool
186
	 */
187
	public function sendRemoteUnShare($remote, $id, $token) {
188
		return $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
189
	}
190
191
	/**
192
	 * send server-to-server unshare to remote server
193
	 *
194
	 * @param string $remote url
195
	 * @param int $id share id
196
	 * @param string $token
197
	 * @return bool
198
	 */
199
	public function sendRevokeShare($remote, $id, $token) {
200
		return $this->sendUpdateToRemote($remote, $id, $token, 'revoke');
201
	}
202
203
	/**
204
	 * send notification to remote server if the permissions was changed
205
	 *
206
	 * @param string $remote
207
	 * @param int $remoteId
208
	 * @param string $token
209
	 * @param int $permissions
210
	 * @return bool
211
	 */
212
	public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
213
		return $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
214
	}
215
216
	/**
217
	 * forward accept reShare to remote server
218
	 *
219
	 * @param string $remote
220
	 * @param int $remoteId
221
	 * @param string $token
222
	 */
223
	public function sendAcceptShare($remote, $remoteId, $token) {
224
		$this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
225
	}
226
227
	/**
228
	 * forward decline reShare to remote server
229
	 *
230
	 * @param string $remote
231
	 * @param int $remoteId
232
	 * @param string $token
233
	 */
234
	public function sendDeclineShare($remote, $remoteId, $token) {
235
		$this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
236
	}
237
238
	/**
239
	 * inform remote server whether server-to-server share was accepted/declined
240
	 *
241
	 * @param string $remote
242
	 * @param int $remoteId Share id on the remote host
243
	 * @param string $token
244
	 * @param string $action possible actions:
245
	 * 	                     accept, decline, unshare, revoke, permissions
246
	 * @param array $data
247
	 * @param int $try
248
	 *
249
	 * @return boolean
250
	 *
251
	 * @throws \Exception
252
	 */
253
	public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
254
		$ocmNotificationManager = new NotificationManager();
255
		$ocmNotification = $ocmNotificationManager->convertToOcmFileNotification($remoteId, $token, $action, $data);
256
		$ocmFields = $ocmNotification->toArray();
257
		$url = \rtrim(
258
			$this->addressHandler->removeProtocolFromUrl($remote),
259
			'/'
260
		);
261
		$result = $this->tryHttpPostToShareEndpoint($url, '/notifications', $ocmFields, true);
262
		if (isset($result['statusCode']) && $result['statusCode'] === Http::STATUS_CREATED) {
263
			return true;
264
		}
265
266
		$fields = ['token' => $token];
267
		foreach ($data as $key => $value) {
268
			$fields[$key] = $value;
269
		}
270
271
		$url = \rtrim(
272
			$this->addressHandler->removeProtocolFromUrl($remote),
273
			'/'
274
		);
275
		$result = $this->tryHttpPostToShareEndpoint($url, '/' . $remoteId . '/' . $action, $fields);
276
		$status = \json_decode($result['result'], true);
277
278
		if ($result['success'] && $this->isOcsStatusOk($status)) {
279
			return true;
280
		} elseif ($try === 0) {
281
			// only add new job on first try
282
			$this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
283
				[
284
					'remote' => $remote,
285
					'remoteId' => $remoteId,
286
					'token' => $token,
287
					'action' => $action,
288
					'data' => \json_encode($data),
289
					'try' => $try,
290
					'lastRun' => $this->getTimestamp()
291
				]
292
			);
293
		}
294
295
		return false;
296
	}
297
298
	/**
299
	 * return current timestamp
300
	 *
301
	 * @return int
302
	 */
303
	protected function getTimestamp() {
304
		return \time();
305
	}
306
307
	/**
308
	 * try http post first with https and then with http as a fallback
309
	 *
310
	 * @param string $remoteDomain
311
	 * @param string $urlSuffix
312
	 * @param array $fields post parameters
313
	 * @return array
314
	 * @throws \Exception
315
	 */
316
	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $useOcm = false) {
317
		$client = $this->httpClientService->newClient();
318
		$protocol = 'https://';
319
		$result = [
320
			'success' => false,
321
			'result' => '',
322
		];
323
		$try = 0;
324
325
		while ($result['success'] === false && $try < 2) {
326
			if ($useOcm) {
327
				$endpoint = $this->discoveryManager->getOcmShareEndpoint($protocol . $remoteDomain);
328
				$endpoint .= $urlSuffix;
329
			} else {
330
				$relativePath = $this->discoveryManager->getShareEndpoint($protocol . $remoteDomain);
331
				$endpoint = $protocol . $remoteDomain . $relativePath . $urlSuffix . '?format=' . self::RESPONSE_FORMAT;
332
			}
333
334
			try {
335
				$response = $client->post($endpoint, [
336
					'body' => $fields,
337
					'timeout' => 10,
338
					'connect_timeout' => 10,
339
				]);
340
				$result['result'] = $response->getBody();
341
				$result['statusCode'] = $response->getStatusCode();
342
				$result['success'] = true;
343
				break;
344
			} catch (\Exception $e) {
345
				// if flat re-sharing is not supported by the remote server
346
				// we re-throw the exception and fall back to the old behaviour.
347
				// (flat re-shares has been introduced in ownCloud 9.1)
348
				if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
349
					throw $e;
350
				}
351
				$allowHttpFallback = $this->config->getSystemValue('sharing.federation.allowHttpFallback', false) === true;
352
				if (!$allowHttpFallback) {
353
					break;
354
				}
355
				$try++;
356
				$protocol = 'http://';
357
			}
358
		}
359
360
		return $result;
361
	}
362
363
	protected function sendOcmRemoteShare(Address $shareWithAddress, Address $ownerAddress, Address $sharedByAddress, $token, $name, $remote_id) {
364
		$fields = [
365
			'shareWith' => $shareWithAddress->getCloudId(),
366
			'name' => $name,
367
			'providerId' => $remote_id,
368
			'owner' => $ownerAddress->getCloudId(),
369
			'ownerDisplayName' => $ownerAddress->getDisplayName(),
370
			'sender' => $sharedByAddress->getCloudId(),
371
			'senderDisplayName' => $sharedByAddress->getDisplayName(),
372
			'shareType' => 'user',
373
			'resourceType' => 'file',
374
			'protocol' => [
375
				'name' => 'webdav',
376
				'options' => [
377
					'sharedSecret' => $token
378
				]
379
			]
380
		];
381
382
		$url = $shareWithAddress->getCleanHostName();
383
		$result = $this->tryHttpPostToShareEndpoint($url, '/shares', $fields, true);
384
385
		if (isset($result['statusCode']) && $result['statusCode'] === Http::STATUS_CREATED) {
386
			return true;
387
		}
388
		return false;
389
	}
390
391
	protected function sendPreOcmRemoteShare(Address $shareWithAddress, Address $ownerAddress, Address $sharedByAddress, $token, $name, $remote_id) {
392
		$fields = [
393
			'shareWith' => $shareWithAddress->getUserId(),
394
			'token' => $token,
395
			'name' => $name,
396
			'remoteId' => $remote_id,
397
			'owner' => $ownerAddress->getUserId(),
398
			'ownerFederatedId' => $ownerAddress->getCloudId(),
399
			'sharedBy' => $sharedByAddress->getUserId(),
400
			'sharedByFederatedId' => $sharedByAddress->getUserId(),
401
			'remote' => $this->addressHandler->generateRemoteURL(),
402
		];
403
		$url = $shareWithAddress->getCleanHostName();
404
		$result = $this->tryHttpPostToShareEndpoint($url, '', $fields);
405
		$status = \json_decode($result['result'], true);
406
407
		if ($result['success'] && $this->isOcsStatusOk($status)) {
408
			return true;
409
		}
410
		return false;
411
	}
412
413
	/**
414
	 * Validate ocs response - 100 or 200 means success
415
	 *
416
	 * @param array $status
417
	 *
418
	 * @return bool
419
	 */
420
	private function isOcsStatusOk($status) {
421
		return \in_array($status['ocs']['meta']['statuscode'], [100, 200]);
422
	}
423
}
424