Completed
Push — stable13 ( 486dff...83d994 )
by Morris
57:07 queued 32:56
created
lib/private/Files/Storage/Wrapper/Encryption.php 1 patch
Indentation   +979 added lines, -979 removed lines patch added patch discarded remove patch
@@ -48,984 +48,984 @@
 block discarded – undo
48 48
 
49 49
 class Encryption extends Wrapper {
50 50
 
51
-	use LocalTempFileTrait;
52
-
53
-	/** @var string */
54
-	private $mountPoint;
55
-
56
-	/** @var \OC\Encryption\Util */
57
-	private $util;
58
-
59
-	/** @var \OCP\Encryption\IManager */
60
-	private $encryptionManager;
61
-
62
-	/** @var \OCP\ILogger */
63
-	private $logger;
64
-
65
-	/** @var string */
66
-	private $uid;
67
-
68
-	/** @var array */
69
-	protected $unencryptedSize;
70
-
71
-	/** @var \OCP\Encryption\IFile */
72
-	private $fileHelper;
73
-
74
-	/** @var IMountPoint */
75
-	private $mount;
76
-
77
-	/** @var IStorage */
78
-	private $keyStorage;
79
-
80
-	/** @var Update */
81
-	private $update;
82
-
83
-	/** @var Manager */
84
-	private $mountManager;
85
-
86
-	/** @var array remember for which path we execute the repair step to avoid recursions */
87
-	private $fixUnencryptedSizeOf = array();
88
-
89
-	/** @var  ArrayCache */
90
-	private $arrayCache;
91
-
92
-	/**
93
-	 * @param array $parameters
94
-	 * @param IManager $encryptionManager
95
-	 * @param Util $util
96
-	 * @param ILogger $logger
97
-	 * @param IFile $fileHelper
98
-	 * @param string $uid
99
-	 * @param IStorage $keyStorage
100
-	 * @param Update $update
101
-	 * @param Manager $mountManager
102
-	 * @param ArrayCache $arrayCache
103
-	 */
104
-	public function __construct(
105
-			$parameters,
106
-			IManager $encryptionManager = null,
107
-			Util $util = null,
108
-			ILogger $logger = null,
109
-			IFile $fileHelper = null,
110
-			$uid = null,
111
-			IStorage $keyStorage = null,
112
-			Update $update = null,
113
-			Manager $mountManager = null,
114
-			ArrayCache $arrayCache = null
115
-		) {
116
-
117
-		$this->mountPoint = $parameters['mountPoint'];
118
-		$this->mount = $parameters['mount'];
119
-		$this->encryptionManager = $encryptionManager;
120
-		$this->util = $util;
121
-		$this->logger = $logger;
122
-		$this->uid = $uid;
123
-		$this->fileHelper = $fileHelper;
124
-		$this->keyStorage = $keyStorage;
125
-		$this->unencryptedSize = array();
126
-		$this->update = $update;
127
-		$this->mountManager = $mountManager;
128
-		$this->arrayCache = $arrayCache;
129
-		parent::__construct($parameters);
130
-	}
131
-
132
-	/**
133
-	 * see http://php.net/manual/en/function.filesize.php
134
-	 * The result for filesize when called on a folder is required to be 0
135
-	 *
136
-	 * @param string $path
137
-	 * @return int
138
-	 */
139
-	public function filesize($path) {
140
-		$fullPath = $this->getFullPath($path);
141
-
142
-		/** @var CacheEntry $info */
143
-		$info = $this->getCache()->get($path);
144
-		if (isset($this->unencryptedSize[$fullPath])) {
145
-			$size = $this->unencryptedSize[$fullPath];
146
-			// update file cache
147
-			if ($info instanceof ICacheEntry) {
148
-				$info = $info->getData();
149
-				$info['encrypted'] = $info['encryptedVersion'];
150
-			} else {
151
-				if (!is_array($info)) {
152
-					$info = [];
153
-				}
154
-				$info['encrypted'] = true;
155
-			}
156
-
157
-			$info['size'] = $size;
158
-			$this->getCache()->put($path, $info);
159
-
160
-			return $size;
161
-		}
162
-
163
-		if (isset($info['fileid']) && $info['encrypted']) {
164
-			return $this->verifyUnencryptedSize($path, $info['size']);
165
-		}
166
-
167
-		return $this->storage->filesize($path);
168
-	}
169
-
170
-	/**
171
-	 * @param string $path
172
-	 * @return array
173
-	 */
174
-	public function getMetaData($path) {
175
-		$data = $this->storage->getMetaData($path);
176
-		if (is_null($data)) {
177
-			return null;
178
-		}
179
-		$fullPath = $this->getFullPath($path);
180
-		$info = $this->getCache()->get($path);
181
-
182
-		if (isset($this->unencryptedSize[$fullPath])) {
183
-			$data['encrypted'] = true;
184
-			$data['size'] = $this->unencryptedSize[$fullPath];
185
-		} else {
186
-			if (isset($info['fileid']) && $info['encrypted']) {
187
-				$data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
188
-				$data['encrypted'] = true;
189
-			}
190
-		}
191
-
192
-		if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
193
-			$data['encryptedVersion'] = $info['encryptedVersion'];
194
-		}
195
-
196
-		return $data;
197
-	}
198
-
199
-	/**
200
-	 * see http://php.net/manual/en/function.file_get_contents.php
201
-	 *
202
-	 * @param string $path
203
-	 * @return string
204
-	 */
205
-	public function file_get_contents($path) {
206
-
207
-		$encryptionModule = $this->getEncryptionModule($path);
208
-
209
-		if ($encryptionModule) {
210
-			$handle = $this->fopen($path, "r");
211
-			if (!$handle) {
212
-				return false;
213
-			}
214
-			$data = stream_get_contents($handle);
215
-			fclose($handle);
216
-			return $data;
217
-		}
218
-		return $this->storage->file_get_contents($path);
219
-	}
220
-
221
-	/**
222
-	 * see http://php.net/manual/en/function.file_put_contents.php
223
-	 *
224
-	 * @param string $path
225
-	 * @param string $data
226
-	 * @return bool
227
-	 */
228
-	public function file_put_contents($path, $data) {
229
-		// file put content will always be translated to a stream write
230
-		$handle = $this->fopen($path, 'w');
231
-		if (is_resource($handle)) {
232
-			$written = fwrite($handle, $data);
233
-			fclose($handle);
234
-			return $written;
235
-		}
236
-
237
-		return false;
238
-	}
239
-
240
-	/**
241
-	 * see http://php.net/manual/en/function.unlink.php
242
-	 *
243
-	 * @param string $path
244
-	 * @return bool
245
-	 */
246
-	public function unlink($path) {
247
-		$fullPath = $this->getFullPath($path);
248
-		if ($this->util->isExcluded($fullPath)) {
249
-			return $this->storage->unlink($path);
250
-		}
251
-
252
-		$encryptionModule = $this->getEncryptionModule($path);
253
-		if ($encryptionModule) {
254
-			$this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
255
-		}
256
-
257
-		return $this->storage->unlink($path);
258
-	}
259
-
260
-	/**
261
-	 * see http://php.net/manual/en/function.rename.php
262
-	 *
263
-	 * @param string $path1
264
-	 * @param string $path2
265
-	 * @return bool
266
-	 */
267
-	public function rename($path1, $path2) {
268
-
269
-		$result = $this->storage->rename($path1, $path2);
270
-
271
-		if ($result &&
272
-			// versions always use the keys from the original file, so we can skip
273
-			// this step for versions
274
-			$this->isVersion($path2) === false &&
275
-			$this->encryptionManager->isEnabled()) {
276
-			$source = $this->getFullPath($path1);
277
-			if (!$this->util->isExcluded($source)) {
278
-				$target = $this->getFullPath($path2);
279
-				if (isset($this->unencryptedSize[$source])) {
280
-					$this->unencryptedSize[$target] = $this->unencryptedSize[$source];
281
-				}
282
-				$this->keyStorage->renameKeys($source, $target);
283
-				$module = $this->getEncryptionModule($path2);
284
-				if ($module) {
285
-					$module->update($target, $this->uid, []);
286
-				}
287
-			}
288
-		}
289
-
290
-		return $result;
291
-	}
292
-
293
-	/**
294
-	 * see http://php.net/manual/en/function.rmdir.php
295
-	 *
296
-	 * @param string $path
297
-	 * @return bool
298
-	 */
299
-	public function rmdir($path) {
300
-		$result = $this->storage->rmdir($path);
301
-		$fullPath = $this->getFullPath($path);
302
-		if ($result &&
303
-			$this->util->isExcluded($fullPath) === false &&
304
-			$this->encryptionManager->isEnabled()
305
-		) {
306
-			$this->keyStorage->deleteAllFileKeys($fullPath);
307
-		}
308
-
309
-		return $result;
310
-	}
311
-
312
-	/**
313
-	 * check if a file can be read
314
-	 *
315
-	 * @param string $path
316
-	 * @return bool
317
-	 */
318
-	public function isReadable($path) {
319
-
320
-		$isReadable = true;
321
-
322
-		$metaData = $this->getMetaData($path);
323
-		if (
324
-			!$this->is_dir($path) &&
325
-			isset($metaData['encrypted']) &&
326
-			$metaData['encrypted'] === true
327
-		) {
328
-			$fullPath = $this->getFullPath($path);
329
-			$module = $this->getEncryptionModule($path);
330
-			$isReadable = $module->isReadable($fullPath, $this->uid);
331
-		}
332
-
333
-		return $this->storage->isReadable($path) && $isReadable;
334
-	}
335
-
336
-	/**
337
-	 * see http://php.net/manual/en/function.copy.php
338
-	 *
339
-	 * @param string $path1
340
-	 * @param string $path2
341
-	 * @return bool
342
-	 */
343
-	public function copy($path1, $path2) {
344
-
345
-		$source = $this->getFullPath($path1);
346
-
347
-		if ($this->util->isExcluded($source)) {
348
-			return $this->storage->copy($path1, $path2);
349
-		}
350
-
351
-		// need to stream copy file by file in case we copy between a encrypted
352
-		// and a unencrypted storage
353
-		$this->unlink($path2);
354
-		$result = $this->copyFromStorage($this, $path1, $path2);
355
-
356
-		return $result;
357
-	}
358
-
359
-	/**
360
-	 * see http://php.net/manual/en/function.fopen.php
361
-	 *
362
-	 * @param string $path
363
-	 * @param string $mode
364
-	 * @return resource|bool
365
-	 * @throws GenericEncryptionException
366
-	 * @throws ModuleDoesNotExistsException
367
-	 */
368
-	public function fopen($path, $mode) {
369
-
370
-		// check if the file is stored in the array cache, this means that we
371
-		// copy a file over to the versions folder, in this case we don't want to
372
-		// decrypt it
373
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
374
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
375
-			return $this->storage->fopen($path, $mode);
376
-		}
377
-
378
-		$encryptionEnabled = $this->encryptionManager->isEnabled();
379
-		$shouldEncrypt = false;
380
-		$encryptionModule = null;
381
-		$header = $this->getHeader($path);
382
-		$signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
383
-		$fullPath = $this->getFullPath($path);
384
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
385
-
386
-		if ($this->util->isExcluded($fullPath) === false) {
387
-
388
-			$size = $unencryptedSize = 0;
389
-			$realFile = $this->util->stripPartialFileExtension($path);
390
-			$targetExists = $this->file_exists($realFile) || $this->file_exists($path);
391
-			$targetIsEncrypted = false;
392
-			if ($targetExists) {
393
-				// in case the file exists we require the explicit module as
394
-				// specified in the file header - otherwise we need to fail hard to
395
-				// prevent data loss on client side
396
-				if (!empty($encryptionModuleId)) {
397
-					$targetIsEncrypted = true;
398
-					$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
399
-				}
400
-
401
-				if ($this->file_exists($path)) {
402
-					$size = $this->storage->filesize($path);
403
-					$unencryptedSize = $this->filesize($path);
404
-				} else {
405
-					$size = $unencryptedSize = 0;
406
-				}
407
-			}
408
-
409
-			try {
410
-
411
-				if (
412
-					$mode === 'w'
413
-					|| $mode === 'w+'
414
-					|| $mode === 'wb'
415
-					|| $mode === 'wb+'
416
-				) {
417
-					// if we update a encrypted file with a un-encrypted one we change the db flag
418
-					if ($targetIsEncrypted && $encryptionEnabled === false) {
419
-						$cache = $this->storage->getCache();
420
-						if ($cache) {
421
-							$entry = $cache->get($path);
422
-							$cache->update($entry->getId(), ['encrypted' => 0]);
423
-						}
424
-					}
425
-					if ($encryptionEnabled) {
426
-						// if $encryptionModuleId is empty, the default module will be used
427
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
428
-						$shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
429
-						$signed = true;
430
-					}
431
-				} else {
432
-					$info = $this->getCache()->get($path);
433
-					// only get encryption module if we found one in the header
434
-					// or if file should be encrypted according to the file cache
435
-					if (!empty($encryptionModuleId)) {
436
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
437
-						$shouldEncrypt = true;
438
-					} else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
439
-						// we come from a old installation. No header and/or no module defined
440
-						// but the file is encrypted. In this case we need to use the
441
-						// OC_DEFAULT_MODULE to read the file
442
-						$encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
443
-						$shouldEncrypt = true;
444
-						$targetIsEncrypted = true;
445
-					}
446
-				}
447
-			} catch (ModuleDoesNotExistsException $e) {
448
-				$this->logger->warning('Encryption module "' . $encryptionModuleId .
449
-					'" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
450
-			}
451
-
452
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
453
-			if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
454
-				if (!$targetExists || !$targetIsEncrypted) {
455
-					$shouldEncrypt = false;
456
-				}
457
-			}
458
-
459
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
460
-				$headerSize = $this->getHeaderSize($path);
461
-				$source = $this->storage->fopen($path, $mode);
462
-				if (!is_resource($source)) {
463
-					return false;
464
-				}
465
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
466
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
467
-					$size, $unencryptedSize, $headerSize, $signed);
468
-				return $handle;
469
-			}
470
-
471
-		}
472
-
473
-		return $this->storage->fopen($path, $mode);
474
-	}
475
-
476
-
477
-	/**
478
-	 * perform some plausibility checks if the the unencrypted size is correct.
479
-	 * If not, we calculate the correct unencrypted size and return it
480
-	 *
481
-	 * @param string $path internal path relative to the storage root
482
-	 * @param int $unencryptedSize size of the unencrypted file
483
-	 *
484
-	 * @return int unencrypted size
485
-	 */
486
-	protected function verifyUnencryptedSize($path, $unencryptedSize) {
487
-
488
-		$size = $this->storage->filesize($path);
489
-		$result = $unencryptedSize;
490
-
491
-		if ($unencryptedSize < 0 ||
492
-			($size > 0 && $unencryptedSize === $size)
493
-		) {
494
-			// check if we already calculate the unencrypted size for the
495
-			// given path to avoid recursions
496
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
497
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
498
-				try {
499
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
500
-				} catch (\Exception $e) {
501
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
502
-					$this->logger->logException($e);
503
-				}
504
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
505
-			}
506
-		}
507
-
508
-		return $result;
509
-	}
510
-
511
-	/**
512
-	 * calculate the unencrypted size
513
-	 *
514
-	 * @param string $path internal path relative to the storage root
515
-	 * @param int $size size of the physical file
516
-	 * @param int $unencryptedSize size of the unencrypted file
517
-	 *
518
-	 * @return int calculated unencrypted size
519
-	 */
520
-	protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
521
-
522
-		$headerSize = $this->getHeaderSize($path);
523
-		$header = $this->getHeader($path);
524
-		$encryptionModule = $this->getEncryptionModule($path);
525
-
526
-		$stream = $this->storage->fopen($path, 'r');
527
-
528
-		// if we couldn't open the file we return the old unencrypted size
529
-		if (!is_resource($stream)) {
530
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
531
-			return $unencryptedSize;
532
-		}
533
-
534
-		$newUnencryptedSize = 0;
535
-		$size -= $headerSize;
536
-		$blockSize = $this->util->getBlockSize();
537
-
538
-		// if a header exists we skip it
539
-		if ($headerSize > 0) {
540
-			fread($stream, $headerSize);
541
-		}
542
-
543
-		// fast path, else the calculation for $lastChunkNr is bogus
544
-		if ($size === 0) {
545
-			return 0;
546
-		}
547
-
548
-		$signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
549
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
550
-
551
-		// calculate last chunk nr
552
-		// next highest is end of chunks, one subtracted is last one
553
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
554
-
555
-		$lastChunkNr = ceil($size/ $blockSize)-1;
556
-		// calculate last chunk position
557
-		$lastChunkPos = ($lastChunkNr * $blockSize);
558
-		// try to fseek to the last chunk, if it fails we have to read the whole file
559
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
560
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
561
-		}
562
-
563
-		$lastChunkContentEncrypted='';
564
-		$count = $blockSize;
565
-
566
-		while ($count > 0) {
567
-			$data=fread($stream, $blockSize);
568
-			$count=strlen($data);
569
-			$lastChunkContentEncrypted .= $data;
570
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
571
-				$newUnencryptedSize += $unencryptedBlockSize;
572
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
573
-			}
574
-		}
575
-
576
-		fclose($stream);
577
-
578
-		// we have to decrypt the last chunk to get it actual size
579
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
580
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
581
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
582
-
583
-		// calc the real file size with the size of the last chunk
584
-		$newUnencryptedSize += strlen($decryptedLastChunk);
585
-
586
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
587
-
588
-		// write to cache if applicable
589
-		$cache = $this->storage->getCache();
590
-		if ($cache) {
591
-			$entry = $cache->get($path);
592
-			$cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
593
-		}
594
-
595
-		return $newUnencryptedSize;
596
-	}
597
-
598
-	/**
599
-	 * @param Storage\IStorage $sourceStorage
600
-	 * @param string $sourceInternalPath
601
-	 * @param string $targetInternalPath
602
-	 * @param bool $preserveMtime
603
-	 * @return bool
604
-	 */
605
-	public function moveFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
606
-		if ($sourceStorage === $this) {
607
-			return $this->rename($sourceInternalPath, $targetInternalPath);
608
-		}
609
-
610
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
611
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
612
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
613
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
614
-		// - remove $this->copyBetweenStorage
615
-
616
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
617
-			return false;
618
-		}
619
-
620
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
621
-		if ($result) {
622
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
623
-				$result &= $sourceStorage->rmdir($sourceInternalPath);
624
-			} else {
625
-				$result &= $sourceStorage->unlink($sourceInternalPath);
626
-			}
627
-		}
628
-		return $result;
629
-	}
630
-
631
-
632
-	/**
633
-	 * @param Storage\IStorage $sourceStorage
634
-	 * @param string $sourceInternalPath
635
-	 * @param string $targetInternalPath
636
-	 * @param bool $preserveMtime
637
-	 * @param bool $isRename
638
-	 * @return bool
639
-	 */
640
-	public function copyFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
641
-
642
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
643
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
644
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
645
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
646
-		// - remove $this->copyBetweenStorage
647
-
648
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
649
-	}
650
-
651
-	/**
652
-	 * Update the encrypted cache version in the database
653
-	 *
654
-	 * @param Storage\IStorage $sourceStorage
655
-	 * @param string $sourceInternalPath
656
-	 * @param string $targetInternalPath
657
-	 * @param bool $isRename
658
-	 * @param bool $keepEncryptionVersion
659
-	 */
660
-	private function updateEncryptedVersion(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, $keepEncryptionVersion) {
661
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
662
-		$cacheInformation = [
663
-			'encrypted' => $isEncrypted,
664
-		];
665
-		if($isEncrypted) {
666
-			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
667
-
668
-			// In case of a move operation from an unencrypted to an encrypted
669
-			// storage the old encrypted version would stay with "0" while the
670
-			// correct value would be "1". Thus we manually set the value to "1"
671
-			// for those cases.
672
-			// See also https://github.com/owncloud/core/issues/23078
673
-			if($encryptedVersion === 0 || !$keepEncryptionVersion) {
674
-				$encryptedVersion = 1;
675
-			}
676
-
677
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
678
-		}
679
-
680
-		// in case of a rename we need to manipulate the source cache because
681
-		// this information will be kept for the new target
682
-		if ($isRename) {
683
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
684
-		} else {
685
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
686
-		}
687
-	}
688
-
689
-	/**
690
-	 * copy file between two storages
691
-	 *
692
-	 * @param Storage\IStorage $sourceStorage
693
-	 * @param string $sourceInternalPath
694
-	 * @param string $targetInternalPath
695
-	 * @param bool $preserveMtime
696
-	 * @param bool $isRename
697
-	 * @return bool
698
-	 * @throws \Exception
699
-	 */
700
-	private function copyBetweenStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
701
-
702
-		// for versions we have nothing to do, because versions should always use the
703
-		// key from the original file. Just create a 1:1 copy and done
704
-		if ($this->isVersion($targetInternalPath) ||
705
-			$this->isVersion($sourceInternalPath)) {
706
-			// remember that we try to create a version so that we can detect it during
707
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
708
-			// create a 1:1 copy of the file
709
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
710
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
711
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
712
-			if ($result) {
713
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
714
-				// make sure that we update the unencrypted size for the version
715
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
716
-					$this->updateUnencryptedSize(
717
-						$this->getFullPath($targetInternalPath),
718
-						$info['size']
719
-					);
720
-				}
721
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
722
-			}
723
-			return $result;
724
-		}
725
-
726
-		// first copy the keys that we reuse the existing file key on the target location
727
-		// and don't create a new one which would break versions for example.
728
-		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
729
-		if (count($mount) === 1) {
730
-			$mountPoint = $mount[0]->getMountPoint();
731
-			$source = $mountPoint . '/' . $sourceInternalPath;
732
-			$target = $this->getFullPath($targetInternalPath);
733
-			$this->copyKeys($source, $target);
734
-		} else {
735
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
736
-		}
737
-
738
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
739
-			$dh = $sourceStorage->opendir($sourceInternalPath);
740
-			$result = $this->mkdir($targetInternalPath);
741
-			if (is_resource($dh)) {
742
-				while ($result and ($file = readdir($dh)) !== false) {
743
-					if (!Filesystem::isIgnoredDir($file)) {
744
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
745
-					}
746
-				}
747
-			}
748
-		} else {
749
-			try {
750
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
751
-				$target = $this->fopen($targetInternalPath, 'w');
752
-				list(, $result) = \OC_Helper::streamCopy($source, $target);
753
-				fclose($source);
754
-				fclose($target);
755
-			} catch (\Exception $e) {
756
-				fclose($source);
757
-				fclose($target);
758
-				throw $e;
759
-			}
760
-			if($result) {
761
-				if ($preserveMtime) {
762
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
763
-				}
764
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
765
-			} else {
766
-				// delete partially written target file
767
-				$this->unlink($targetInternalPath);
768
-				// delete cache entry that was created by fopen
769
-				$this->getCache()->remove($targetInternalPath);
770
-			}
771
-		}
772
-		return (bool)$result;
773
-
774
-	}
775
-
776
-	/**
777
-	 * get the path to a local version of the file.
778
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
779
-	 *
780
-	 * @param string $path
781
-	 * @return string
782
-	 */
783
-	public function getLocalFile($path) {
784
-		if ($this->encryptionManager->isEnabled()) {
785
-			$cachedFile = $this->getCachedFile($path);
786
-			if (is_string($cachedFile)) {
787
-				return $cachedFile;
788
-			}
789
-		}
790
-		return $this->storage->getLocalFile($path);
791
-	}
792
-
793
-	/**
794
-	 * Returns the wrapped storage's value for isLocal()
795
-	 *
796
-	 * @return bool wrapped storage's isLocal() value
797
-	 */
798
-	public function isLocal() {
799
-		if ($this->encryptionManager->isEnabled()) {
800
-			return false;
801
-		}
802
-		return $this->storage->isLocal();
803
-	}
804
-
805
-	/**
806
-	 * see http://php.net/manual/en/function.stat.php
807
-	 * only the following keys are required in the result: size and mtime
808
-	 *
809
-	 * @param string $path
810
-	 * @return array
811
-	 */
812
-	public function stat($path) {
813
-		$stat = $this->storage->stat($path);
814
-		$fileSize = $this->filesize($path);
815
-		$stat['size'] = $fileSize;
816
-		$stat[7] = $fileSize;
817
-		return $stat;
818
-	}
819
-
820
-	/**
821
-	 * see http://php.net/manual/en/function.hash.php
822
-	 *
823
-	 * @param string $type
824
-	 * @param string $path
825
-	 * @param bool $raw
826
-	 * @return string
827
-	 */
828
-	public function hash($type, $path, $raw = false) {
829
-		$fh = $this->fopen($path, 'rb');
830
-		$ctx = hash_init($type);
831
-		hash_update_stream($ctx, $fh);
832
-		fclose($fh);
833
-		return hash_final($ctx, $raw);
834
-	}
835
-
836
-	/**
837
-	 * return full path, including mount point
838
-	 *
839
-	 * @param string $path relative to mount point
840
-	 * @return string full path including mount point
841
-	 */
842
-	protected function getFullPath($path) {
843
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
844
-	}
845
-
846
-	/**
847
-	 * read first block of encrypted file, typically this will contain the
848
-	 * encryption header
849
-	 *
850
-	 * @param string $path
851
-	 * @return string
852
-	 */
853
-	protected function readFirstBlock($path) {
854
-		$firstBlock = '';
855
-		if ($this->storage->file_exists($path)) {
856
-			$handle = $this->storage->fopen($path, 'r');
857
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
858
-			fclose($handle);
859
-		}
860
-		return $firstBlock;
861
-	}
862
-
863
-	/**
864
-	 * return header size of given file
865
-	 *
866
-	 * @param string $path
867
-	 * @return int
868
-	 */
869
-	protected function getHeaderSize($path) {
870
-		$headerSize = 0;
871
-		$realFile = $this->util->stripPartialFileExtension($path);
872
-		if ($this->storage->file_exists($realFile)) {
873
-			$path = $realFile;
874
-		}
875
-		$firstBlock = $this->readFirstBlock($path);
876
-
877
-		if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
878
-			$headerSize = $this->util->getHeaderSize();
879
-		}
880
-
881
-		return $headerSize;
882
-	}
883
-
884
-	/**
885
-	 * parse raw header to array
886
-	 *
887
-	 * @param string $rawHeader
888
-	 * @return array
889
-	 */
890
-	protected function parseRawHeader($rawHeader) {
891
-		$result = array();
892
-		if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
893
-			$header = $rawHeader;
894
-			$endAt = strpos($header, Util::HEADER_END);
895
-			if ($endAt !== false) {
896
-				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
897
-
898
-				// +1 to not start with an ':' which would result in empty element at the beginning
899
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
900
-
901
-				$element = array_shift($exploded);
902
-				while ($element !== Util::HEADER_END) {
903
-					$result[$element] = array_shift($exploded);
904
-					$element = array_shift($exploded);
905
-				}
906
-			}
907
-		}
908
-
909
-		return $result;
910
-	}
911
-
912
-	/**
913
-	 * read header from file
914
-	 *
915
-	 * @param string $path
916
-	 * @return array
917
-	 */
918
-	protected function getHeader($path) {
919
-		$realFile = $this->util->stripPartialFileExtension($path);
920
-		$exists = $this->storage->file_exists($realFile);
921
-		if ($exists) {
922
-			$path = $realFile;
923
-		}
924
-
925
-		$firstBlock = $this->readFirstBlock($path);
926
-		$result = $this->parseRawHeader($firstBlock);
927
-
928
-		// if the header doesn't contain a encryption module we check if it is a
929
-		// legacy file. If true, we add the default encryption module
930
-		if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
931
-			if (!empty($result)) {
932
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
933
-			} else if ($exists) {
934
-				// if the header was empty we have to check first if it is a encrypted file at all
935
-				// We would do query to filecache only if we know that entry in filecache exists
936
-				$info = $this->getCache()->get($path);
937
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
938
-					$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
939
-				}
940
-			}
941
-		}
942
-
943
-		return $result;
944
-	}
945
-
946
-	/**
947
-	 * read encryption module needed to read/write the file located at $path
948
-	 *
949
-	 * @param string $path
950
-	 * @return null|\OCP\Encryption\IEncryptionModule
951
-	 * @throws ModuleDoesNotExistsException
952
-	 * @throws \Exception
953
-	 */
954
-	protected function getEncryptionModule($path) {
955
-		$encryptionModule = null;
956
-		$header = $this->getHeader($path);
957
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
958
-		if (!empty($encryptionModuleId)) {
959
-			try {
960
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
961
-			} catch (ModuleDoesNotExistsException $e) {
962
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
963
-				throw $e;
964
-			}
965
-		}
966
-
967
-		return $encryptionModule;
968
-	}
969
-
970
-	/**
971
-	 * @param string $path
972
-	 * @param int $unencryptedSize
973
-	 */
974
-	public function updateUnencryptedSize($path, $unencryptedSize) {
975
-		$this->unencryptedSize[$path] = $unencryptedSize;
976
-	}
977
-
978
-	/**
979
-	 * copy keys to new location
980
-	 *
981
-	 * @param string $source path relative to data/
982
-	 * @param string $target path relative to data/
983
-	 * @return bool
984
-	 */
985
-	protected function copyKeys($source, $target) {
986
-		if (!$this->util->isExcluded($source)) {
987
-			return $this->keyStorage->copyKeys($source, $target);
988
-		}
989
-
990
-		return false;
991
-	}
992
-
993
-	/**
994
-	 * check if path points to a files version
995
-	 *
996
-	 * @param $path
997
-	 * @return bool
998
-	 */
999
-	protected function isVersion($path) {
1000
-		$normalized = Filesystem::normalizePath($path);
1001
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
1002
-	}
1003
-
1004
-	/**
1005
-	 * check if the given storage should be encrypted or not
1006
-	 *
1007
-	 * @param $path
1008
-	 * @return bool
1009
-	 */
1010
-	protected function shouldEncrypt($path) {
1011
-		$fullPath = $this->getFullPath($path);
1012
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
1013
-		if ($mountPointConfig === false) {
1014
-			return false;
1015
-		}
1016
-
1017
-		try {
1018
-			$encryptionModule = $this->getEncryptionModule($fullPath);
1019
-		} catch (ModuleDoesNotExistsException $e) {
1020
-			return false;
1021
-		}
1022
-
1023
-		if ($encryptionModule === null) {
1024
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
1025
-		}
1026
-
1027
-		return $encryptionModule->shouldEncrypt($fullPath);
1028
-
1029
-	}
51
+    use LocalTempFileTrait;
52
+
53
+    /** @var string */
54
+    private $mountPoint;
55
+
56
+    /** @var \OC\Encryption\Util */
57
+    private $util;
58
+
59
+    /** @var \OCP\Encryption\IManager */
60
+    private $encryptionManager;
61
+
62
+    /** @var \OCP\ILogger */
63
+    private $logger;
64
+
65
+    /** @var string */
66
+    private $uid;
67
+
68
+    /** @var array */
69
+    protected $unencryptedSize;
70
+
71
+    /** @var \OCP\Encryption\IFile */
72
+    private $fileHelper;
73
+
74
+    /** @var IMountPoint */
75
+    private $mount;
76
+
77
+    /** @var IStorage */
78
+    private $keyStorage;
79
+
80
+    /** @var Update */
81
+    private $update;
82
+
83
+    /** @var Manager */
84
+    private $mountManager;
85
+
86
+    /** @var array remember for which path we execute the repair step to avoid recursions */
87
+    private $fixUnencryptedSizeOf = array();
88
+
89
+    /** @var  ArrayCache */
90
+    private $arrayCache;
91
+
92
+    /**
93
+     * @param array $parameters
94
+     * @param IManager $encryptionManager
95
+     * @param Util $util
96
+     * @param ILogger $logger
97
+     * @param IFile $fileHelper
98
+     * @param string $uid
99
+     * @param IStorage $keyStorage
100
+     * @param Update $update
101
+     * @param Manager $mountManager
102
+     * @param ArrayCache $arrayCache
103
+     */
104
+    public function __construct(
105
+            $parameters,
106
+            IManager $encryptionManager = null,
107
+            Util $util = null,
108
+            ILogger $logger = null,
109
+            IFile $fileHelper = null,
110
+            $uid = null,
111
+            IStorage $keyStorage = null,
112
+            Update $update = null,
113
+            Manager $mountManager = null,
114
+            ArrayCache $arrayCache = null
115
+        ) {
116
+
117
+        $this->mountPoint = $parameters['mountPoint'];
118
+        $this->mount = $parameters['mount'];
119
+        $this->encryptionManager = $encryptionManager;
120
+        $this->util = $util;
121
+        $this->logger = $logger;
122
+        $this->uid = $uid;
123
+        $this->fileHelper = $fileHelper;
124
+        $this->keyStorage = $keyStorage;
125
+        $this->unencryptedSize = array();
126
+        $this->update = $update;
127
+        $this->mountManager = $mountManager;
128
+        $this->arrayCache = $arrayCache;
129
+        parent::__construct($parameters);
130
+    }
131
+
132
+    /**
133
+     * see http://php.net/manual/en/function.filesize.php
134
+     * The result for filesize when called on a folder is required to be 0
135
+     *
136
+     * @param string $path
137
+     * @return int
138
+     */
139
+    public function filesize($path) {
140
+        $fullPath = $this->getFullPath($path);
141
+
142
+        /** @var CacheEntry $info */
143
+        $info = $this->getCache()->get($path);
144
+        if (isset($this->unencryptedSize[$fullPath])) {
145
+            $size = $this->unencryptedSize[$fullPath];
146
+            // update file cache
147
+            if ($info instanceof ICacheEntry) {
148
+                $info = $info->getData();
149
+                $info['encrypted'] = $info['encryptedVersion'];
150
+            } else {
151
+                if (!is_array($info)) {
152
+                    $info = [];
153
+                }
154
+                $info['encrypted'] = true;
155
+            }
156
+
157
+            $info['size'] = $size;
158
+            $this->getCache()->put($path, $info);
159
+
160
+            return $size;
161
+        }
162
+
163
+        if (isset($info['fileid']) && $info['encrypted']) {
164
+            return $this->verifyUnencryptedSize($path, $info['size']);
165
+        }
166
+
167
+        return $this->storage->filesize($path);
168
+    }
169
+
170
+    /**
171
+     * @param string $path
172
+     * @return array
173
+     */
174
+    public function getMetaData($path) {
175
+        $data = $this->storage->getMetaData($path);
176
+        if (is_null($data)) {
177
+            return null;
178
+        }
179
+        $fullPath = $this->getFullPath($path);
180
+        $info = $this->getCache()->get($path);
181
+
182
+        if (isset($this->unencryptedSize[$fullPath])) {
183
+            $data['encrypted'] = true;
184
+            $data['size'] = $this->unencryptedSize[$fullPath];
185
+        } else {
186
+            if (isset($info['fileid']) && $info['encrypted']) {
187
+                $data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
188
+                $data['encrypted'] = true;
189
+            }
190
+        }
191
+
192
+        if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
193
+            $data['encryptedVersion'] = $info['encryptedVersion'];
194
+        }
195
+
196
+        return $data;
197
+    }
198
+
199
+    /**
200
+     * see http://php.net/manual/en/function.file_get_contents.php
201
+     *
202
+     * @param string $path
203
+     * @return string
204
+     */
205
+    public function file_get_contents($path) {
206
+
207
+        $encryptionModule = $this->getEncryptionModule($path);
208
+
209
+        if ($encryptionModule) {
210
+            $handle = $this->fopen($path, "r");
211
+            if (!$handle) {
212
+                return false;
213
+            }
214
+            $data = stream_get_contents($handle);
215
+            fclose($handle);
216
+            return $data;
217
+        }
218
+        return $this->storage->file_get_contents($path);
219
+    }
220
+
221
+    /**
222
+     * see http://php.net/manual/en/function.file_put_contents.php
223
+     *
224
+     * @param string $path
225
+     * @param string $data
226
+     * @return bool
227
+     */
228
+    public function file_put_contents($path, $data) {
229
+        // file put content will always be translated to a stream write
230
+        $handle = $this->fopen($path, 'w');
231
+        if (is_resource($handle)) {
232
+            $written = fwrite($handle, $data);
233
+            fclose($handle);
234
+            return $written;
235
+        }
236
+
237
+        return false;
238
+    }
239
+
240
+    /**
241
+     * see http://php.net/manual/en/function.unlink.php
242
+     *
243
+     * @param string $path
244
+     * @return bool
245
+     */
246
+    public function unlink($path) {
247
+        $fullPath = $this->getFullPath($path);
248
+        if ($this->util->isExcluded($fullPath)) {
249
+            return $this->storage->unlink($path);
250
+        }
251
+
252
+        $encryptionModule = $this->getEncryptionModule($path);
253
+        if ($encryptionModule) {
254
+            $this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
255
+        }
256
+
257
+        return $this->storage->unlink($path);
258
+    }
259
+
260
+    /**
261
+     * see http://php.net/manual/en/function.rename.php
262
+     *
263
+     * @param string $path1
264
+     * @param string $path2
265
+     * @return bool
266
+     */
267
+    public function rename($path1, $path2) {
268
+
269
+        $result = $this->storage->rename($path1, $path2);
270
+
271
+        if ($result &&
272
+            // versions always use the keys from the original file, so we can skip
273
+            // this step for versions
274
+            $this->isVersion($path2) === false &&
275
+            $this->encryptionManager->isEnabled()) {
276
+            $source = $this->getFullPath($path1);
277
+            if (!$this->util->isExcluded($source)) {
278
+                $target = $this->getFullPath($path2);
279
+                if (isset($this->unencryptedSize[$source])) {
280
+                    $this->unencryptedSize[$target] = $this->unencryptedSize[$source];
281
+                }
282
+                $this->keyStorage->renameKeys($source, $target);
283
+                $module = $this->getEncryptionModule($path2);
284
+                if ($module) {
285
+                    $module->update($target, $this->uid, []);
286
+                }
287
+            }
288
+        }
289
+
290
+        return $result;
291
+    }
292
+
293
+    /**
294
+     * see http://php.net/manual/en/function.rmdir.php
295
+     *
296
+     * @param string $path
297
+     * @return bool
298
+     */
299
+    public function rmdir($path) {
300
+        $result = $this->storage->rmdir($path);
301
+        $fullPath = $this->getFullPath($path);
302
+        if ($result &&
303
+            $this->util->isExcluded($fullPath) === false &&
304
+            $this->encryptionManager->isEnabled()
305
+        ) {
306
+            $this->keyStorage->deleteAllFileKeys($fullPath);
307
+        }
308
+
309
+        return $result;
310
+    }
311
+
312
+    /**
313
+     * check if a file can be read
314
+     *
315
+     * @param string $path
316
+     * @return bool
317
+     */
318
+    public function isReadable($path) {
319
+
320
+        $isReadable = true;
321
+
322
+        $metaData = $this->getMetaData($path);
323
+        if (
324
+            !$this->is_dir($path) &&
325
+            isset($metaData['encrypted']) &&
326
+            $metaData['encrypted'] === true
327
+        ) {
328
+            $fullPath = $this->getFullPath($path);
329
+            $module = $this->getEncryptionModule($path);
330
+            $isReadable = $module->isReadable($fullPath, $this->uid);
331
+        }
332
+
333
+        return $this->storage->isReadable($path) && $isReadable;
334
+    }
335
+
336
+    /**
337
+     * see http://php.net/manual/en/function.copy.php
338
+     *
339
+     * @param string $path1
340
+     * @param string $path2
341
+     * @return bool
342
+     */
343
+    public function copy($path1, $path2) {
344
+
345
+        $source = $this->getFullPath($path1);
346
+
347
+        if ($this->util->isExcluded($source)) {
348
+            return $this->storage->copy($path1, $path2);
349
+        }
350
+
351
+        // need to stream copy file by file in case we copy between a encrypted
352
+        // and a unencrypted storage
353
+        $this->unlink($path2);
354
+        $result = $this->copyFromStorage($this, $path1, $path2);
355
+
356
+        return $result;
357
+    }
358
+
359
+    /**
360
+     * see http://php.net/manual/en/function.fopen.php
361
+     *
362
+     * @param string $path
363
+     * @param string $mode
364
+     * @return resource|bool
365
+     * @throws GenericEncryptionException
366
+     * @throws ModuleDoesNotExistsException
367
+     */
368
+    public function fopen($path, $mode) {
369
+
370
+        // check if the file is stored in the array cache, this means that we
371
+        // copy a file over to the versions folder, in this case we don't want to
372
+        // decrypt it
373
+        if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
374
+            $this->arrayCache->remove('encryption_copy_version_' . $path);
375
+            return $this->storage->fopen($path, $mode);
376
+        }
377
+
378
+        $encryptionEnabled = $this->encryptionManager->isEnabled();
379
+        $shouldEncrypt = false;
380
+        $encryptionModule = null;
381
+        $header = $this->getHeader($path);
382
+        $signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
383
+        $fullPath = $this->getFullPath($path);
384
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
385
+
386
+        if ($this->util->isExcluded($fullPath) === false) {
387
+
388
+            $size = $unencryptedSize = 0;
389
+            $realFile = $this->util->stripPartialFileExtension($path);
390
+            $targetExists = $this->file_exists($realFile) || $this->file_exists($path);
391
+            $targetIsEncrypted = false;
392
+            if ($targetExists) {
393
+                // in case the file exists we require the explicit module as
394
+                // specified in the file header - otherwise we need to fail hard to
395
+                // prevent data loss on client side
396
+                if (!empty($encryptionModuleId)) {
397
+                    $targetIsEncrypted = true;
398
+                    $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
399
+                }
400
+
401
+                if ($this->file_exists($path)) {
402
+                    $size = $this->storage->filesize($path);
403
+                    $unencryptedSize = $this->filesize($path);
404
+                } else {
405
+                    $size = $unencryptedSize = 0;
406
+                }
407
+            }
408
+
409
+            try {
410
+
411
+                if (
412
+                    $mode === 'w'
413
+                    || $mode === 'w+'
414
+                    || $mode === 'wb'
415
+                    || $mode === 'wb+'
416
+                ) {
417
+                    // if we update a encrypted file with a un-encrypted one we change the db flag
418
+                    if ($targetIsEncrypted && $encryptionEnabled === false) {
419
+                        $cache = $this->storage->getCache();
420
+                        if ($cache) {
421
+                            $entry = $cache->get($path);
422
+                            $cache->update($entry->getId(), ['encrypted' => 0]);
423
+                        }
424
+                    }
425
+                    if ($encryptionEnabled) {
426
+                        // if $encryptionModuleId is empty, the default module will be used
427
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
428
+                        $shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
429
+                        $signed = true;
430
+                    }
431
+                } else {
432
+                    $info = $this->getCache()->get($path);
433
+                    // only get encryption module if we found one in the header
434
+                    // or if file should be encrypted according to the file cache
435
+                    if (!empty($encryptionModuleId)) {
436
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
437
+                        $shouldEncrypt = true;
438
+                    } else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
439
+                        // we come from a old installation. No header and/or no module defined
440
+                        // but the file is encrypted. In this case we need to use the
441
+                        // OC_DEFAULT_MODULE to read the file
442
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
443
+                        $shouldEncrypt = true;
444
+                        $targetIsEncrypted = true;
445
+                    }
446
+                }
447
+            } catch (ModuleDoesNotExistsException $e) {
448
+                $this->logger->warning('Encryption module "' . $encryptionModuleId .
449
+                    '" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
450
+            }
451
+
452
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
453
+            if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
454
+                if (!$targetExists || !$targetIsEncrypted) {
455
+                    $shouldEncrypt = false;
456
+                }
457
+            }
458
+
459
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
460
+                $headerSize = $this->getHeaderSize($path);
461
+                $source = $this->storage->fopen($path, $mode);
462
+                if (!is_resource($source)) {
463
+                    return false;
464
+                }
465
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
466
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
467
+                    $size, $unencryptedSize, $headerSize, $signed);
468
+                return $handle;
469
+            }
470
+
471
+        }
472
+
473
+        return $this->storage->fopen($path, $mode);
474
+    }
475
+
476
+
477
+    /**
478
+     * perform some plausibility checks if the the unencrypted size is correct.
479
+     * If not, we calculate the correct unencrypted size and return it
480
+     *
481
+     * @param string $path internal path relative to the storage root
482
+     * @param int $unencryptedSize size of the unencrypted file
483
+     *
484
+     * @return int unencrypted size
485
+     */
486
+    protected function verifyUnencryptedSize($path, $unencryptedSize) {
487
+
488
+        $size = $this->storage->filesize($path);
489
+        $result = $unencryptedSize;
490
+
491
+        if ($unencryptedSize < 0 ||
492
+            ($size > 0 && $unencryptedSize === $size)
493
+        ) {
494
+            // check if we already calculate the unencrypted size for the
495
+            // given path to avoid recursions
496
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
497
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
498
+                try {
499
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
500
+                } catch (\Exception $e) {
501
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
502
+                    $this->logger->logException($e);
503
+                }
504
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
505
+            }
506
+        }
507
+
508
+        return $result;
509
+    }
510
+
511
+    /**
512
+     * calculate the unencrypted size
513
+     *
514
+     * @param string $path internal path relative to the storage root
515
+     * @param int $size size of the physical file
516
+     * @param int $unencryptedSize size of the unencrypted file
517
+     *
518
+     * @return int calculated unencrypted size
519
+     */
520
+    protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
521
+
522
+        $headerSize = $this->getHeaderSize($path);
523
+        $header = $this->getHeader($path);
524
+        $encryptionModule = $this->getEncryptionModule($path);
525
+
526
+        $stream = $this->storage->fopen($path, 'r');
527
+
528
+        // if we couldn't open the file we return the old unencrypted size
529
+        if (!is_resource($stream)) {
530
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
531
+            return $unencryptedSize;
532
+        }
533
+
534
+        $newUnencryptedSize = 0;
535
+        $size -= $headerSize;
536
+        $blockSize = $this->util->getBlockSize();
537
+
538
+        // if a header exists we skip it
539
+        if ($headerSize > 0) {
540
+            fread($stream, $headerSize);
541
+        }
542
+
543
+        // fast path, else the calculation for $lastChunkNr is bogus
544
+        if ($size === 0) {
545
+            return 0;
546
+        }
547
+
548
+        $signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
549
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
550
+
551
+        // calculate last chunk nr
552
+        // next highest is end of chunks, one subtracted is last one
553
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
554
+
555
+        $lastChunkNr = ceil($size/ $blockSize)-1;
556
+        // calculate last chunk position
557
+        $lastChunkPos = ($lastChunkNr * $blockSize);
558
+        // try to fseek to the last chunk, if it fails we have to read the whole file
559
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
560
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
561
+        }
562
+
563
+        $lastChunkContentEncrypted='';
564
+        $count = $blockSize;
565
+
566
+        while ($count > 0) {
567
+            $data=fread($stream, $blockSize);
568
+            $count=strlen($data);
569
+            $lastChunkContentEncrypted .= $data;
570
+            if(strlen($lastChunkContentEncrypted) > $blockSize) {
571
+                $newUnencryptedSize += $unencryptedBlockSize;
572
+                $lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
573
+            }
574
+        }
575
+
576
+        fclose($stream);
577
+
578
+        // we have to decrypt the last chunk to get it actual size
579
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
580
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
581
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
582
+
583
+        // calc the real file size with the size of the last chunk
584
+        $newUnencryptedSize += strlen($decryptedLastChunk);
585
+
586
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
587
+
588
+        // write to cache if applicable
589
+        $cache = $this->storage->getCache();
590
+        if ($cache) {
591
+            $entry = $cache->get($path);
592
+            $cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
593
+        }
594
+
595
+        return $newUnencryptedSize;
596
+    }
597
+
598
+    /**
599
+     * @param Storage\IStorage $sourceStorage
600
+     * @param string $sourceInternalPath
601
+     * @param string $targetInternalPath
602
+     * @param bool $preserveMtime
603
+     * @return bool
604
+     */
605
+    public function moveFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
606
+        if ($sourceStorage === $this) {
607
+            return $this->rename($sourceInternalPath, $targetInternalPath);
608
+        }
609
+
610
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
611
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
612
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
613
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
614
+        // - remove $this->copyBetweenStorage
615
+
616
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
617
+            return false;
618
+        }
619
+
620
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
621
+        if ($result) {
622
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
623
+                $result &= $sourceStorage->rmdir($sourceInternalPath);
624
+            } else {
625
+                $result &= $sourceStorage->unlink($sourceInternalPath);
626
+            }
627
+        }
628
+        return $result;
629
+    }
630
+
631
+
632
+    /**
633
+     * @param Storage\IStorage $sourceStorage
634
+     * @param string $sourceInternalPath
635
+     * @param string $targetInternalPath
636
+     * @param bool $preserveMtime
637
+     * @param bool $isRename
638
+     * @return bool
639
+     */
640
+    public function copyFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
641
+
642
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
643
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
644
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
645
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
646
+        // - remove $this->copyBetweenStorage
647
+
648
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
649
+    }
650
+
651
+    /**
652
+     * Update the encrypted cache version in the database
653
+     *
654
+     * @param Storage\IStorage $sourceStorage
655
+     * @param string $sourceInternalPath
656
+     * @param string $targetInternalPath
657
+     * @param bool $isRename
658
+     * @param bool $keepEncryptionVersion
659
+     */
660
+    private function updateEncryptedVersion(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, $keepEncryptionVersion) {
661
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
662
+        $cacheInformation = [
663
+            'encrypted' => $isEncrypted,
664
+        ];
665
+        if($isEncrypted) {
666
+            $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
667
+
668
+            // In case of a move operation from an unencrypted to an encrypted
669
+            // storage the old encrypted version would stay with "0" while the
670
+            // correct value would be "1". Thus we manually set the value to "1"
671
+            // for those cases.
672
+            // See also https://github.com/owncloud/core/issues/23078
673
+            if($encryptedVersion === 0 || !$keepEncryptionVersion) {
674
+                $encryptedVersion = 1;
675
+            }
676
+
677
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
678
+        }
679
+
680
+        // in case of a rename we need to manipulate the source cache because
681
+        // this information will be kept for the new target
682
+        if ($isRename) {
683
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
684
+        } else {
685
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
686
+        }
687
+    }
688
+
689
+    /**
690
+     * copy file between two storages
691
+     *
692
+     * @param Storage\IStorage $sourceStorage
693
+     * @param string $sourceInternalPath
694
+     * @param string $targetInternalPath
695
+     * @param bool $preserveMtime
696
+     * @param bool $isRename
697
+     * @return bool
698
+     * @throws \Exception
699
+     */
700
+    private function copyBetweenStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
701
+
702
+        // for versions we have nothing to do, because versions should always use the
703
+        // key from the original file. Just create a 1:1 copy and done
704
+        if ($this->isVersion($targetInternalPath) ||
705
+            $this->isVersion($sourceInternalPath)) {
706
+            // remember that we try to create a version so that we can detect it during
707
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
708
+            // create a 1:1 copy of the file
709
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
710
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
711
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
712
+            if ($result) {
713
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
714
+                // make sure that we update the unencrypted size for the version
715
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
716
+                    $this->updateUnencryptedSize(
717
+                        $this->getFullPath($targetInternalPath),
718
+                        $info['size']
719
+                    );
720
+                }
721
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
722
+            }
723
+            return $result;
724
+        }
725
+
726
+        // first copy the keys that we reuse the existing file key on the target location
727
+        // and don't create a new one which would break versions for example.
728
+        $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
729
+        if (count($mount) === 1) {
730
+            $mountPoint = $mount[0]->getMountPoint();
731
+            $source = $mountPoint . '/' . $sourceInternalPath;
732
+            $target = $this->getFullPath($targetInternalPath);
733
+            $this->copyKeys($source, $target);
734
+        } else {
735
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
736
+        }
737
+
738
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
739
+            $dh = $sourceStorage->opendir($sourceInternalPath);
740
+            $result = $this->mkdir($targetInternalPath);
741
+            if (is_resource($dh)) {
742
+                while ($result and ($file = readdir($dh)) !== false) {
743
+                    if (!Filesystem::isIgnoredDir($file)) {
744
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
745
+                    }
746
+                }
747
+            }
748
+        } else {
749
+            try {
750
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
751
+                $target = $this->fopen($targetInternalPath, 'w');
752
+                list(, $result) = \OC_Helper::streamCopy($source, $target);
753
+                fclose($source);
754
+                fclose($target);
755
+            } catch (\Exception $e) {
756
+                fclose($source);
757
+                fclose($target);
758
+                throw $e;
759
+            }
760
+            if($result) {
761
+                if ($preserveMtime) {
762
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
763
+                }
764
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
765
+            } else {
766
+                // delete partially written target file
767
+                $this->unlink($targetInternalPath);
768
+                // delete cache entry that was created by fopen
769
+                $this->getCache()->remove($targetInternalPath);
770
+            }
771
+        }
772
+        return (bool)$result;
773
+
774
+    }
775
+
776
+    /**
777
+     * get the path to a local version of the file.
778
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
779
+     *
780
+     * @param string $path
781
+     * @return string
782
+     */
783
+    public function getLocalFile($path) {
784
+        if ($this->encryptionManager->isEnabled()) {
785
+            $cachedFile = $this->getCachedFile($path);
786
+            if (is_string($cachedFile)) {
787
+                return $cachedFile;
788
+            }
789
+        }
790
+        return $this->storage->getLocalFile($path);
791
+    }
792
+
793
+    /**
794
+     * Returns the wrapped storage's value for isLocal()
795
+     *
796
+     * @return bool wrapped storage's isLocal() value
797
+     */
798
+    public function isLocal() {
799
+        if ($this->encryptionManager->isEnabled()) {
800
+            return false;
801
+        }
802
+        return $this->storage->isLocal();
803
+    }
804
+
805
+    /**
806
+     * see http://php.net/manual/en/function.stat.php
807
+     * only the following keys are required in the result: size and mtime
808
+     *
809
+     * @param string $path
810
+     * @return array
811
+     */
812
+    public function stat($path) {
813
+        $stat = $this->storage->stat($path);
814
+        $fileSize = $this->filesize($path);
815
+        $stat['size'] = $fileSize;
816
+        $stat[7] = $fileSize;
817
+        return $stat;
818
+    }
819
+
820
+    /**
821
+     * see http://php.net/manual/en/function.hash.php
822
+     *
823
+     * @param string $type
824
+     * @param string $path
825
+     * @param bool $raw
826
+     * @return string
827
+     */
828
+    public function hash($type, $path, $raw = false) {
829
+        $fh = $this->fopen($path, 'rb');
830
+        $ctx = hash_init($type);
831
+        hash_update_stream($ctx, $fh);
832
+        fclose($fh);
833
+        return hash_final($ctx, $raw);
834
+    }
835
+
836
+    /**
837
+     * return full path, including mount point
838
+     *
839
+     * @param string $path relative to mount point
840
+     * @return string full path including mount point
841
+     */
842
+    protected function getFullPath($path) {
843
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
844
+    }
845
+
846
+    /**
847
+     * read first block of encrypted file, typically this will contain the
848
+     * encryption header
849
+     *
850
+     * @param string $path
851
+     * @return string
852
+     */
853
+    protected function readFirstBlock($path) {
854
+        $firstBlock = '';
855
+        if ($this->storage->file_exists($path)) {
856
+            $handle = $this->storage->fopen($path, 'r');
857
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
858
+            fclose($handle);
859
+        }
860
+        return $firstBlock;
861
+    }
862
+
863
+    /**
864
+     * return header size of given file
865
+     *
866
+     * @param string $path
867
+     * @return int
868
+     */
869
+    protected function getHeaderSize($path) {
870
+        $headerSize = 0;
871
+        $realFile = $this->util->stripPartialFileExtension($path);
872
+        if ($this->storage->file_exists($realFile)) {
873
+            $path = $realFile;
874
+        }
875
+        $firstBlock = $this->readFirstBlock($path);
876
+
877
+        if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
878
+            $headerSize = $this->util->getHeaderSize();
879
+        }
880
+
881
+        return $headerSize;
882
+    }
883
+
884
+    /**
885
+     * parse raw header to array
886
+     *
887
+     * @param string $rawHeader
888
+     * @return array
889
+     */
890
+    protected function parseRawHeader($rawHeader) {
891
+        $result = array();
892
+        if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
893
+            $header = $rawHeader;
894
+            $endAt = strpos($header, Util::HEADER_END);
895
+            if ($endAt !== false) {
896
+                $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
897
+
898
+                // +1 to not start with an ':' which would result in empty element at the beginning
899
+                $exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
900
+
901
+                $element = array_shift($exploded);
902
+                while ($element !== Util::HEADER_END) {
903
+                    $result[$element] = array_shift($exploded);
904
+                    $element = array_shift($exploded);
905
+                }
906
+            }
907
+        }
908
+
909
+        return $result;
910
+    }
911
+
912
+    /**
913
+     * read header from file
914
+     *
915
+     * @param string $path
916
+     * @return array
917
+     */
918
+    protected function getHeader($path) {
919
+        $realFile = $this->util->stripPartialFileExtension($path);
920
+        $exists = $this->storage->file_exists($realFile);
921
+        if ($exists) {
922
+            $path = $realFile;
923
+        }
924
+
925
+        $firstBlock = $this->readFirstBlock($path);
926
+        $result = $this->parseRawHeader($firstBlock);
927
+
928
+        // if the header doesn't contain a encryption module we check if it is a
929
+        // legacy file. If true, we add the default encryption module
930
+        if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
931
+            if (!empty($result)) {
932
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
933
+            } else if ($exists) {
934
+                // if the header was empty we have to check first if it is a encrypted file at all
935
+                // We would do query to filecache only if we know that entry in filecache exists
936
+                $info = $this->getCache()->get($path);
937
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
938
+                    $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
939
+                }
940
+            }
941
+        }
942
+
943
+        return $result;
944
+    }
945
+
946
+    /**
947
+     * read encryption module needed to read/write the file located at $path
948
+     *
949
+     * @param string $path
950
+     * @return null|\OCP\Encryption\IEncryptionModule
951
+     * @throws ModuleDoesNotExistsException
952
+     * @throws \Exception
953
+     */
954
+    protected function getEncryptionModule($path) {
955
+        $encryptionModule = null;
956
+        $header = $this->getHeader($path);
957
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
958
+        if (!empty($encryptionModuleId)) {
959
+            try {
960
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
961
+            } catch (ModuleDoesNotExistsException $e) {
962
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
963
+                throw $e;
964
+            }
965
+        }
966
+
967
+        return $encryptionModule;
968
+    }
969
+
970
+    /**
971
+     * @param string $path
972
+     * @param int $unencryptedSize
973
+     */
974
+    public function updateUnencryptedSize($path, $unencryptedSize) {
975
+        $this->unencryptedSize[$path] = $unencryptedSize;
976
+    }
977
+
978
+    /**
979
+     * copy keys to new location
980
+     *
981
+     * @param string $source path relative to data/
982
+     * @param string $target path relative to data/
983
+     * @return bool
984
+     */
985
+    protected function copyKeys($source, $target) {
986
+        if (!$this->util->isExcluded($source)) {
987
+            return $this->keyStorage->copyKeys($source, $target);
988
+        }
989
+
990
+        return false;
991
+    }
992
+
993
+    /**
994
+     * check if path points to a files version
995
+     *
996
+     * @param $path
997
+     * @return bool
998
+     */
999
+    protected function isVersion($path) {
1000
+        $normalized = Filesystem::normalizePath($path);
1001
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
1002
+    }
1003
+
1004
+    /**
1005
+     * check if the given storage should be encrypted or not
1006
+     *
1007
+     * @param $path
1008
+     * @return bool
1009
+     */
1010
+    protected function shouldEncrypt($path) {
1011
+        $fullPath = $this->getFullPath($path);
1012
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
1013
+        if ($mountPointConfig === false) {
1014
+            return false;
1015
+        }
1016
+
1017
+        try {
1018
+            $encryptionModule = $this->getEncryptionModule($fullPath);
1019
+        } catch (ModuleDoesNotExistsException $e) {
1020
+            return false;
1021
+        }
1022
+
1023
+        if ($encryptionModule === null) {
1024
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
1025
+        }
1026
+
1027
+        return $encryptionModule->shouldEncrypt($fullPath);
1028
+
1029
+    }
1030 1030
 
1031 1031
 }
Please login to merge, or discard this patch.